Skip to content

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

Address PR comments

Carlos Monastyrski43f4a395dcef
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 1dbdcd611e..840cfed220 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -407,9 +407,9 @@ import {
TPkiScepTransactions,
TPkiScepTransactionsInsert,
TPkiScepTransactionsUpdate,
- TPkiSignerIssuanceJobs,
- TPkiSignerIssuanceJobsInsert,
- TPkiSignerIssuanceJobsUpdate,
+ TPkiSignerCertificateIssuanceJobs,
+ TPkiSignerCertificateIssuanceJobsInsert,
+ TPkiSignerCertificateIssuanceJobsUpdate,
TPkiSigners,
TPkiSignersInsert,
TPkiSignersUpdate,
@@ -1051,10 +1051,10 @@ declare module "knex/types/tables" {
TPkiDiscoveryScanHistoryUpdate
>;
[TableName.PkiSigners]: KnexOriginal.CompositeTableType<TPkiSigners, TPkiSignersInsert, TPkiSignersUpdate>;
- [TableName.PkiSignerIssuanceJobs]: KnexOriginal.CompositeTableType<
- TPkiSignerIssuanceJobs,
- TPkiSignerIssuanceJobsInsert,
- TPkiSignerIssuanceJobsUpdate
+ [TableName.PkiSignerCertificateIssuanceJobs]: KnexOriginal.CompositeTableType<
+ TPkiSignerCertificateIssuanceJobs,
+ TPkiSignerCertificateIssuanceJobsInsert,
+ TPkiSignerCertificateIssuanceJobsUpdate
>;
[TableName.PkiSigningOperations]: KnexOriginal.CompositeTableType<
TPkiSigningOperations,
diff --git a/backend/src/db/migrations/20260528124443_signer-revamp.ts b/backend/src/db/migrations/20260528124443_signer-revamp.ts
index 2cf678d751..800e22e279 100644
--- a/backend/src/db/migrations/20260528124443_signer-revamp.ts
+++ b/backend/src/db/migrations/20260528124443_signer-revamp.ts
@@ -1,295 +1,72 @@
-/* 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;
-};
+const SIGNER_CERTIFICATE_ISSUANCE_JOBS_TABLE = "pki_signer_certificate_issuance_jobs";
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("caId").nullable();
+ t.foreign("caId").references("id").inTable(TableName.CertificateAuthority).onDelete("SET NULL");
+ t.index("caId");
+ t.string("commonName", 256).nullable();
+ t.integer("certificateTtlDays").nullable();
+ t.integer("certificateRenewBeforeDays").nullable();
+ t.text("certificateFailureReason").nullable();
+ t.string("keyAlgorithm", 64).notNullable().defaultTo("RSA_2048");
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");
+ await knex.schema.createTable(SIGNER_CERTIFICATE_ISSUANCE_JOBS_TABLE, (t) => {
+ t.uuid("id").primary().defaultTo(knex.raw("gen_random_uuid()"));
- t.uuid("certificateId");
- t.foreign("certificateId").references("id").inTable(TableName.Certificate).onDelete("SET NULL");
+ t.uuid("signerId").notNullable();
+ t.foreign("signerId").references("id").inTable(TableName.PkiSigners).onDelete("CASCADE");
+ t.index("signerId");
- t.timestamps(true, true, true);
+ t.uuid("caId").notNullable();
+ t.foreign("caId").references("id").inTable(TableName.CertificateAuthority).onDelete("CASCADE");
- t.index(["status", "nextPollAt"], "pki_signer_issuance_jobs_status_nextPollAt_idx");
- });
- }
+ t.string("caType", 64).notNullable();
+ t.string("status", 32).notNullable();
- await knex(TableName.ApprovalRequests)
- .where({ type: "cert-code-signing" })
- .andWhereRaw(`("requestData" -> 'version') IS DISTINCT FROM to_jsonb(1)`)
- .del();
+ t.string("commonName", 256).notNullable();
+ t.integer("certificateTtlDays").notNullable();
+ t.string("keyAlgorithm", 64).notNullable().defaultTo("RSA_2048");
- const signers = (await knex(TableName.PkiSigners).select<SignerRow[]>(
- "id",
- "projectId",
- "name",
- "approvalPolicyId",
- "certificateId",
- "caId",
- "commonName",
- "certificateTtlDays",
- "renewBeforeDays"
- )) as SignerRow[];
+ t.binary("encryptedPrivateKey");
+ t.binary("encryptedCsr");
- 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;
+ t.jsonb("externalOrderRef");
- const EMPTY_JSONB = JSON.stringify({});
+ 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 });
- 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;
+ t.text("failureReason");
- 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
- });
- }
+ t.uuid("certificateId");
+ t.foreign("certificateId").references("id").inTable(TableName.Certificate).onDelete("SET NULL");
- 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;
- }
- }
+ t.timestamps(true, true, true);
- 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();
+ t.index(["status", "nextPollAt"], "pki_signer_certificate_issuance_jobs_status_nextPollAt_idx");
});
}
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.dropTableIfExists(SIGNER_CERTIFICATE_ISSUANCE_JOBS_TABLE);
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");
- }
+ t.dropColumn("keyAlgorithm");
+ t.dropColumn("certificateFailureReason");
+ t.dropColumn("certificateRenewBeforeDays");
+ t.dropColumn("certificateTtlDays");
+ t.dropColumn("commonName");
+ t.dropIndex("caId");
+ t.dropForeign(["caId"]);
+ t.dropColumn("caId");
+ t.uuid("certificateId").notNullable().alter();
});
}
diff --git a/backend/src/db/schemas/approval-request-grants.ts b/backend/src/db/schemas/approval-request-grants.ts
index 6981e797d2..ed8f3b827c 100644
--- a/backend/src/db/schemas/approval-request-grants.ts
+++ b/backend/src/db/schemas/approval-request-grants.ts
@@ -22,8 +22,7 @@ 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(),
- grantedByUserId: z.string().uuid().nullable().optional()
+ bypassReason: z.string().nullable().optional()
});
export type TApprovalRequestGrants = z.infer<typeof ApprovalRequestGrantsSchema>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 417cd32778..9617cc1308 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -164,7 +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-signer-certificate-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.ts
index 3d151407cc..22f9bc6b98 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -293,7 +293,7 @@ export enum TableName {
// Code Signing
PkiSigners = "pki_signers",
- PkiSignerIssuanceJobs = "pki_signer_issuance_jobs",
+ PkiSignerCertificateIssuanceJobs = "pki_signer_certificate_issuance_jobs",
PkiSigningOperations = "pki_signing_operations",
CaSigningConfig = "ca_signing_configs",
@@ -355,7 +355,7 @@ export enum ProjectMembershipRole {
KmsCryptographicOperator = "cryptographic-operator"
}
-export enum ApplicationMembershipRole {
+export enum ResourceMembershipRole {
Admin = "admin",
Operator = "operator",
Auditor = "auditor",
@@ -364,7 +364,7 @@ export enum ApplicationMembershipRole {
export enum ResourceType {
CertificateApplication = "certificate-application",
- Signer = "signer"
+ Signer = "pki-signer"
}
export enum SecretEncryptionAlgo {
diff --git a/backend/src/db/schemas/pki-signer-issuance-jobs.ts b/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts
similarity index 68%
rename from backend/src/db/schemas/pki-signer-issuance-jobs.ts
rename to backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts
index 119731b481..eb42827f0a 100644
--- a/backend/src/db/schemas/pki-signer-issuance-jobs.ts
+++ b/backend/src/db/schemas/pki-signer-certificate-issuance-jobs.ts
@@ -9,7 +9,7 @@ import { zodBuffer } from "@app/lib/zod";
import { TImmutableDBKeys } from "./models";
-export const PkiSignerIssuanceJobsSchema = z.object({
+export const PkiSignerCertificateIssuanceJobsSchema = z.object({
id: z.string().uuid(),
signerId: z.string().uuid(),
caId: z.string().uuid(),
@@ -31,6 +31,11 @@ export const PkiSignerIssuanceJobsSchema = z.object({
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>>;
+export type TPkiSignerCertificateIssuanceJobs = z.infer<typeof PkiSignerCertificateIssuanceJobsSchema>;
+export type TPkiSignerCertificateIssuanceJobsInsert = Omit<
+ z.input<typeof PkiSignerCertificateIssuanceJobsSchema>,
+ TImmutableDBKeys
+>;
+export type TPkiSignerCertificateIssuanceJobsUpdate = Partial<
+ Omit<z.input<typeof PkiSignerCertificateIssuanceJobsSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/pki-signers.ts b/backend/src/db/schemas/pki-signers.ts
index d51e2db3fb..edb3c296b5 100644
--- a/backend/src/db/schemas/pki-signers.ts
+++ b/backend/src/db/schemas/pki-signers.ts
@@ -21,8 +21,8 @@ export const PkiSignersSchema = z.object({
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(),
+ certificateRenewBeforeDays: z.number().nullable().optional(),
+ certificateFailureReason: z.string().nullable().optional(),
keyAlgorithm: z.string().default("RSA_2048")
});
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 83b3cb22cb..f1200e442b 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -952,23 +952,11 @@ const buildApplicationAdminPermissionRules = () => {
ResourcePermissionSub.Member
);
- can(
- [
- ProjectPermissionActions.Read,
- ProjectPermissionActions.Create,
- ProjectPermissionActions.Edit,
- ProjectPermissionActions.Delete
- ],
- ResourcePermissionSub.Role
- );
-
can(
[ProjectPermissionCertificateProfileActions.Read, ProjectPermissionCertificateProfileActions.IssueCert],
ProjectPermissionSub.CertificateProfiles
);
- can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
-
return rules;
};
@@ -1024,13 +1012,11 @@ const buildApplicationOperatorPermissionRules = () => {
can([ProjectPermissionApprovalRequestGrantActions.Read], ResourcePermissionSub.ApprovalRequestGrants);
can([ProjectPermissionMemberActions.Read], ResourcePermissionSub.Member);
- can([ProjectPermissionActions.Read], ResourcePermissionSub.Role);
can(
[ProjectPermissionCertificateProfileActions.Read, ProjectPermissionCertificateProfileActions.IssueCert],
ProjectPermissionSub.CertificateProfiles
);
- can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
return rules;
};
@@ -1051,14 +1037,12 @@ const buildApplicationAuditorPermissionRules = () => {
can([ProjectPermissionApprovalRequestActions.Read], ResourcePermissionSub.ApprovalRequests);
can([ProjectPermissionApprovalRequestGrantActions.Read], ResourcePermissionSub.ApprovalRequestGrants);
can([ProjectPermissionMemberActions.Read], ResourcePermissionSub.Member);
- can([ProjectPermissionActions.Read], ResourcePermissionSub.Role);
can([ProjectPermissionCertificateProfileActions.Read], ProjectPermissionSub.CertificateProfiles);
- can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
return rules;
};
-const buildApplicationProjectAdminFallbackRules = () => {
+const buildProjectAdminApplicationFallbackRules = () => {
const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);
can(
@@ -1078,8 +1062,6 @@ const buildApplicationProjectAdminFallbackRules = () => {
ResourcePermissionSub.Member
);
- can([ProjectPermissionActions.Read], ResourcePermissionSub.Role);
-
can(
[ResourcePermissionCertificateActions.Read, ResourcePermissionCertificateActions.List],
ResourcePermissionSub.Certificates
@@ -1091,7 +1073,7 @@ const buildApplicationProjectAdminFallbackRules = () => {
export const applicationAdminPermissions = buildApplicationAdminPermissionRules();
export const applicationOperatorPermissions = buildApplicationOperatorPermissionRules();
export const applicationAuditorPermissions = buildApplicationAuditorPermissionRules();
-export const applicationProjectAdminFallbackPermissions = buildApplicationProjectAdminFallbackRules();
+export const projectAdminApplicationFallbackPermissions = buildProjectAdminApplicationFallbackRules();
const buildSignerAdminPermissionRules = () => {
const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);
@@ -1101,7 +1083,7 @@ const buildSignerAdminPermissionRules = () => {
ResourcePermissionSignerActions.Read,
ResourcePermissionSignerActions.Edit,
ResourcePermissionSignerActions.Delete,
- ResourcePermissionSignerActions.EnableDisable,
+ ResourcePermissionSignerActions.ManageStatus,
ResourcePermissionSignerActions.ManageMembers,
ResourcePermissionSignerActions.ManagePolicy,
ResourcePermissionSignerActions.Sign,
@@ -1114,18 +1096,6 @@ const buildSignerAdminPermissionRules = () => {
ResourcePermissionSub.Signer
);
- can(
- [
- ProjectPermissionMemberActions.Read,
- ProjectPermissionMemberActions.Create,
- ProjectPermissionMemberActions.Edit,
- ProjectPermissionMemberActions.Delete
- ],
- ResourcePermissionSub.Member
- );
-
- can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
-
return rules;
};
@@ -1142,9 +1112,6 @@ const buildSignerOperatorPermissionRules = () => {
ResourcePermissionSub.Signer
);
- can([ProjectPermissionMemberActions.Read], ResourcePermissionSub.Member);
- can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
-
return rules;
};
@@ -1156,25 +1123,15 @@ const buildSignerAuditorPermissionRules = () => {
ResourcePermissionSub.Signer
);
- can([ProjectPermissionMemberActions.Read], ResourcePermissionSub.Member);
- can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
-
return rules;
};
-const buildSignerProjectAdminFallbackRules = () => {
+const buildProjectAdminSignerFallbackRules = () => {
const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);
- can([ResourcePermissionSignerActions.Read], ResourcePermissionSub.Signer);
-
can(
- [
- ProjectPermissionMemberActions.Read,
- ProjectPermissionMemberActions.Create,
- ProjectPermissionMemberActions.Edit,
- ProjectPermissionMemberActions.Delete
- ],
- ResourcePermissionSub.Member
+ [ResourcePermissionSignerActions.Read, ResourcePermissionSignerActions.ManageMembers],
+ ResourcePermissionSub.Signer
);
return rules;
@@ -1183,4 +1140,4 @@ const buildSignerProjectAdminFallbackRules = () => {
export const signerAdminPermissions = buildSignerAdminPermissionRules();
export const signerOperatorPermissions = buildSignerOperatorPermissionRules();
export const signerAuditorPermissions = buildSignerAuditorPermissionRules();
-export const signerProjectAdminFallbackPermissions = buildSignerProjectAdminFallbackRules();
+export const projectAdminSignerFallbackPermissions = buildProjectAdminSignerFallbackRules();
diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.ts
index 4c35dcd1a4..1648523aff 100644
--- a/backend/src/ee/services/permission/permission-service.ts
+++ b/backend/src/ee/services/permission/permission-service.ts
@@ -6,10 +6,10 @@ import handlebars from "handlebars";
import {
AccessScope,
ActionProjectType,
- ApplicationMembershipRole,
OrganizationActionScope,
OrgMembershipRole,
ProjectMembershipRole,
+ ResourceMembershipRole,
ResourceType,
ServiceTokenScopes,
TProjects
@@ -19,16 +19,16 @@ import {
applicationAdminPermissions,
applicationAuditorPermissions,
applicationOperatorPermissions,
- applicationProjectAdminFallbackPermissions,
cryptographicOperatorPermissions,
+ projectAdminApplicationFallbackPermissions,
projectAdminPermissions,
+ projectAdminSignerFallbackPermissions,
projectMemberPermissions,
projectNoAccessPermissions,
projectViewerPermission,
signerAdminPermissions,
signerAuditorPermissions,
signerOperatorPermissions,
- signerProjectAdminFallbackPermissions,
sshHostBootstrapPermissions
} from "@app/ee/services/permission/default-roles";
import { ResourcePermissionSet } from "@app/ee/services/permission/resource-permission";
@@ -134,13 +134,13 @@ const buildProjectPermissionRules = (projectUserRoles: TBuildProjectPermissionDT
const resolveResourceRoleRules = (resourceType: ResourceType, role: string) => {
if (resourceType === ResourceType.Signer) {
switch (role) {
- case ApplicationMembershipRole.Admin:
+ case ResourceMembershipRole.Admin:
return signerAdminPermissions;
- case ApplicationMembershipRole.Operator:
+ case ResourceMembershipRole.Operator:
return signerOperatorPermissions;
- case ApplicationMembershipRole.Auditor:
+ case ResourceMembershipRole.Auditor:
return signerAuditorPermissions;
- case ApplicationMembershipRole.Custom:
+ case ResourceMembershipRole.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` });
@@ -148,13 +148,13 @@ const resolveResourceRoleRules = (resourceType: ResourceType, role: string) => {
}
switch (role) {
- case ApplicationMembershipRole.Admin:
+ case ResourceMembershipRole.Admin:
return applicationAdminPermissions;
- case ApplicationMembershipRole.Operator:
+ case ResourceMembershipRole.Operator:
return applicationOperatorPermissions;
- case ApplicationMembershipRole.Auditor:
+ case ResourceMembershipRole.Auditor:
return applicationAuditorPermissions;
- case ApplicationMembershipRole.Custom:
+ case ResourceMembershipRole.Custom:
throw new BadRequestError({ message: "Custom resource-level roles are not supported yet" });
default:
throw new NotFoundError({
@@ -174,8 +174,8 @@ const buildResourcePermissionRules = (appUserRoles: TBuildProjectPermissionDTO,
};
const resolveResourceProjectAdminFallback = (resourceType: ResourceType) => {
- if (resourceType === ResourceType.Signer) return signerProjectAdminFallbackPermissions;
- return applicationProjectAdminFallbackPermissions;
+ if (resourceType === ResourceType.Signer) return projectAdminSignerFallbackPermissions;
+ return projectAdminApplicationFallbackPermissions;
};
type MembershipWithRoles = {
@@ -726,7 +726,7 @@ export const permissionServiceFactory = ({
if (resourceMemberships?.length) {
const permissionFromRoles = flattenActiveRolesFromMemberships(
resourceMemberships,
- ApplicationMembershipRole.Custom
+ ResourceMembershipRole.Custom
);
const resourceRules = buildResourcePermissionRules(permissionFromRoles, resourceType);
const mergedRules = isProjectAdmin ? [...resourceRules, ...fallbackRules] : resourceRules;
diff --git a/backend/src/ee/services/permission/resource-permission.ts b/backend/src/ee/services/permission/resource-permission.ts
index bb5b1cc663..b650dd51b4 100644
--- a/backend/src/ee/services/permission/resource-permission.ts
+++ b/backend/src/ee/services/permission/resource-permission.ts
@@ -4,7 +4,6 @@ import {
ProjectPermissionActions,
ProjectPermissionApprovalRequestActions,
ProjectPermissionApprovalRequestGrantActions,
- ProjectPermissionAuditLogsActions,
ProjectPermissionCertificateProfileActions,
ProjectPermissionMemberActions,
ProjectPermissionSub
@@ -21,15 +20,14 @@ export enum ResourcePermissionSub {
ApprovalRequests = "approval-requests",
ApprovalRequestGrants = "approval-request-grants",
Member = "member",
- Role = "role",
- Signer = "signer"
+ Signer = "pki-signer"
}
export enum ResourcePermissionSignerActions {
Read = "read",
Edit = "edit",
Delete = "delete",
- EnableDisable = "enable-disable",
+ ManageStatus = "manage-status",
ManageMembers = "manage-members",
ManagePolicy = "manage-policy",
Sign = "sign",
@@ -94,9 +92,7 @@ export type ResourcePermissionSet =
| [ProjectPermissionApprovalRequestActions, ResourcePermissionSub.ApprovalRequests]
| [ProjectPermissionApprovalRequestGrantActions, ResourcePermissionSub.ApprovalRequestGrants]
| [ProjectPermissionMemberActions, ResourcePermissionSub.Member]
- | [ProjectPermissionActions, ResourcePermissionSub.Role]
| [ResourcePermissionSignerActions, ResourcePermissionSub.Signer]
- | [ProjectPermissionCertificateProfileActions, ProjectPermissionSub.CertificateProfiles]
- | [ProjectPermissionAuditLogsActions, ProjectPermissionSub.AuditLogs];
+ | [ProjectPermissionCertificateProfileActions, ProjectPermissionSub.CertificateProfiles];
export type TResourceAbility = MongoAbility<ResourcePermissionSet>;
diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts
index a64285acbf..3f59ac0c13 100644
--- a/backend/src/server/plugins/error-handler.ts
+++ b/backend/src/server/plugins/error-handler.ts
@@ -256,10 +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,
- ...(error.subproblems && error.subproblems.length > 0 ? { subproblems: error.subproblems } : {})
+ detail: error.message
});
} 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.ts
index de09f8b95d..27f0a6a6b1 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -471,7 +471,12 @@ import { secretValidationRuleDALFactory } from "@app/services/secret-validation-
import { secretValidationRuleServiceFactory } from "@app/services/secret-validation-rule/secret-validation-rule-service";
import { 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 {
+ signerDALFactory,
+ signerRequestDALFactory,
+ 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";
@@ -1352,6 +1357,7 @@ export const registerRoutes = async (
const pkiDiscoveryScanHistoryDAL = pkiDiscoveryScanHistoryDALFactory(db);
const signerDAL = signerDALFactory(db);
+ const signerRequestDAL = signerRequestDALFactory(db);
const signingOperationDAL = signingOperationDALFactory(db);
const signerIssuanceJobDAL = signerIssuanceJobDALFactory(db);
@@ -3109,6 +3115,7 @@ export const registerRoutes = async (
approvalPolicyStepsDAL,
approvalPolicyStepApproversDAL,
approvalRequestDAL,
+ signerRequestDAL,
approvalRequestStepsDAL,
approvalRequestStepEligibleApproversDAL,
approvalRequestGrantsDAL,
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index 2c5107ea33..6a3b24ae29 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -83,8 +83,8 @@ 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 { registerSignerMembershipRoutes } from "./signer-membership-routers";
+import { registerSignerRouter } from "./signer-routers";
import { registerSlackRouter } from "./slack-router";
import { registerSsoRouter } from "./sso-router";
import { registerUserActionRouter } from "./user-action-router";
diff --git a/backend/src/server/routes/v1/signer-membership-router.ts b/backend/src/server/routes/v1/signer-membership-router.ts
deleted file mode 100644
index a070022268..0000000000
--- a/backend/src/server/routes/v1/signer-membership-router.ts
+++ /dev/null
@@ -1,783 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { ApiDocsTags } from "@app/lib/api-docs";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-import { 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-membership-routers/groups-router.ts b/backend/src/server/routes/v1/signer-membership-routers/groups-router.ts
new file mode 100644
index 0000000000..91a02aacc8
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-membership-routers/groups-router.ts
@@ -0,0 +1,172 @@
+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";
+
+import {
+ RemoveSignerMemberResponseSchema,
+ RoleBodySchema,
+ SignerIdParamsSchema,
+ SignerMemberSchema,
+ SignerRoleSchema
+} from "./schemas";
+
+export const registerSignerGroupMembershipRouter = async (server: FastifyZodProvider) => {
+ 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: SignerRoleSchema.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: RemoveSignerMemberResponseSchema }
+ },
+ 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 };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/signer-membership-routers/identities-router.ts b/backend/src/server/routes/v1/signer-membership-routers/identities-router.ts
new file mode 100644
index 0000000000..ea9db078c5
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-membership-routers/identities-router.ts
@@ -0,0 +1,201 @@
+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";
+
+import {
+ EffectiveSignerMemberSchema,
+ RemoveSignerMemberResponseSchema,
+ RoleBodySchema,
+ SignerIdParamsSchema,
+ SignerMemberSchema,
+ SignerRoleSchema
+} from "./schemas";
+
+export const registerSignerIdentityMembershipRouter = async (server: FastifyZodProvider) => {
+ 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: SignerRoleSchema.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: RemoveSignerMemberResponseSchema }
+ },
+ 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/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 };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/signer-membership-routers/index.ts b/backend/src/server/routes/v1/signer-membership-routers/index.ts
new file mode 100644
index 0000000000..99898d39cd
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-membership-routers/index.ts
@@ -0,0 +1,9 @@
+import { registerSignerGroupMembershipRouter } from "./groups-router";
+import { registerSignerIdentityMembershipRouter } from "./identities-router";
+import { registerSignerUserMembershipRouter } from "./users-router";
+
+export const registerSignerMembershipRoutes = async (server: FastifyZodProvider) => {
+ await registerSignerUserMembershipRouter(server);
+ await registerSignerIdentityMembershipRouter(server);
+ await registerSignerGroupMembershipRouter(server);
+};
diff --git a/backend/src/server/routes/v1/signer-membership-routers/schemas.ts b/backend/src/server/routes/v1/signer-membership-routers/schemas.ts
new file mode 100644
index 0000000000..29b8a6ab43
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-membership-routers/schemas.ts
@@ -0,0 +1,50 @@
+import { z } from "zod";
+
+export const SignerIdParamsSchema = z.object({ signerId: z.string().uuid() });
+
+export const SignerRoleSchema = z.enum(["admin", "operator", "auditor"]);
+
+export const RoleBodySchema = z.object({ role: SignerRoleSchema });
+
+export 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()
+});
+
+export 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()
+});
+
+export const RemoveSignerMemberResponseSchema = z.object({
+ membershipId: z.string().uuid(),
+ signerId: z.string().uuid()
+});
diff --git a/backend/src/server/routes/v1/signer-membership-routers/users-router.ts b/backend/src/server/routes/v1/signer-membership-routers/users-router.ts
new file mode 100644
index 0000000000..a045262daa
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-membership-routers/users-router.ts
@@ -0,0 +1,222 @@
+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";
+
+import {
+ EffectiveSignerMemberSchema,
+ RemoveSignerMemberResponseSchema,
+ RoleBodySchema,
+ SignerIdParamsSchema,
+ SignerMemberSchema,
+ SignerRoleSchema
+} from "./schemas";
+
+export const registerSignerUserMembershipRouter = 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: 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: SignerRoleSchema.default("operator")
+ })
+ .refine((val) => val.userIds.length + val.emails.length > 0, {
+ message: "Provide at least one userId or email."
+ }),
+ response: {
+ 200: z.object({
+ memberships: z.array(SignerMemberSchema),
+ skipped: z.array(z.string()),
+ unresolved: z.array(z.string())
+ })
+ }
+ },
+ 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: RemoveSignerMemberResponseSchema }
+ },
+ 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/effective-users",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listSignerEffectiveUserMembers",
+ tags: [ApiDocsTags.PkiSigners],
+ description:
+ "List users that can act on this signer either through a direct membership or through 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: "user"
+ });
+ return { members };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/signer-router.ts b/backend/src/server/routes/v1/signer-router.ts
deleted file mode 100644
index bfb1cbb41d..0000000000
--- a/backend/src/server/routes/v1/signer-router.ts
+++ /dev/null
@@ -1,955 +0,0 @@
-import { z } from "zod";
-
-import { PkiSignersSchema, PkiSigningOperationsSchema } from "@app/db/schemas";
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { ApiDocsTags } from "@app/lib/api-docs";
-import { SigningAlgorithm } from "@app/lib/crypto/sign/types";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-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 { 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",
- url: "/",
- config: { rateLimit: writeLimit },
- schema: {
- hide: false,
- operationId: "createSigner",
- tags: [ApiDocsTags.PkiSigners],
- description: "Create a code signing signer",
- body: z.object({
- projectId: z.string().trim().optional().describe(openApiHidden()),
- name: slugSchema({ min: 1, max: 64, field: "name" }),
- description: z.string().trim().max(256).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
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const signer = await server.services.pkiSigner.create({
- ...req.body,
- projectId: req.body.projectId ?? req.internalCertManagerProjectId,
- 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.CREATE_PKI_SIGNER,
- metadata: {
- signerId: signer.id,
- name: signer.name,
- certificateId: signer.certificateId,
- approvalPolicyId: signer.approvalPolicyId
- }
- }
- });
-
- await server.services.telemetry.sendPostHogEvents({
- event: PostHogEventTypes.SignerCreated,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- orgId: req.permission.orgId
- }
- });
-
- return signer;
- }
- });
-
- server.route({
- method: "GET",
- url: "/",
- config: { rateLimit: readLimit },
- schema: {
- hide: false,
- operationId: "listSigners",
- tags: [ApiDocsTags.PkiSigners],
- description: "List code signing signers for a project",
- querystring: z.object({
- projectId: z.string().trim().optional().describe(openApiHidden()),
- offset: z.coerce.number().int().min(0).default(0),
- limit: z.coerce.number().int().min(1).max(100).default(20),
- search: z.string().trim().optional()
- }),
- response: {
- 200: z.object({
- signers: z.array(
- PkiSignersSchema.extend({
- certificateCommonName: z.string().nullable().optional(),
- certificateSerialNumber: z.string().nullable().optional(),
- certificateNotAfter: z.date().nullable().optional(),
- approvalPolicyName: z.string().nullable().optional()
- })
- ),
- totalCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const projectId = req.query.projectId ?? req.internalCertManagerProjectId;
- const { signers, totalCount } = await server.services.pkiSigner.list({
- ...req.query,
- 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.GET_PKI_SIGNERS,
- metadata: {
- count: signers.length,
- offset: req.query.offset,
- limit: req.query.limit
- }
- }
- });
-
- return { signers, totalCount };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:signerId",
- config: { rateLimit: readLimit },
- schema: {
- hide: false,
- operationId: "getSignerById",
- tags: [ApiDocsTags.PkiSigners],
- description: "Get a code signing signer by ID",
- params: z.object({
- signerId: z.string().uuid()
- }),
- response: {
- 200: PkiSignersSchema.extend({
- certificateCommonName: z.string().nullable().optional(),
- certificateSerialNumber: z.string().nullable().optional(),
- certificateNotAfter: z.date().nullable().optional(),
- certificateNotBefore: z.date().nullable().optional(),
- certificateKeyAlgorithm: z.string().nullable().optional(),
- certificateStatus: z.string().nullable().optional(),
- certificateCaId: z.string().nullable().optional(),
- approvalPolicyName: z.string().nullable().optional()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const signer = await server.services.pkiSigner.getById({
- 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.GET_PKI_SIGNER,
- metadata: {
- signerId: signer.id,
- name: signer.name
- }
- }
- });
-
- return signer;
- }
- });
-
- 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",
- config: { rateLimit: writeLimit },
- schema: {
- hide: false,
- operationId: "updateSigner",
- tags: [ApiDocsTags.PkiSigners],
- description: "Update a code signing signer",
- params: z.object({
- signerId: z.string().uuid()
- }),
- body: z.object({
- name: slugSchema({ min: 1, max: 64, field: "name" }).optional(),
- description: z.string().trim().max(256).nullable().optional(),
- renewBeforeDays: z.number().int().min(1).max(30).nullable().optional()
- }),
- response: {
- 200: PkiSignersSchema
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const signer = await server.services.pkiSigner.update({
- 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.UPDATE_PKI_SIGNER,
- metadata: {
- signerId: signer.id,
- name: signer.name
- }
- }
- });
-
- return signer;
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:signerId",
- config: { rateLimit: writeLimit },
- schema: {
- hide: false,
- operationId: "deleteSigner",
- tags: [ApiDocsTags.PkiSigners],
- description: "Delete a code signing 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.delete({
- 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.DELETE_PKI_SIGNER,
- metadata: {
- signerId: signer.id,
- name: signer.name
- }
- }
- });
-
- await server.services.telemetry.sendPostHogEvents({
- event: PostHogEventTypes.SignerDeleted,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- orgId: req.permission.orgId
- }
- });
-
- return signer;
- }
- });
-
- server.route({
- method: "POST",
- url: "/:signerId/sign",
- config: { rateLimit: writeLimit },
- schema: {
- hide: false,
- operationId: "signData",
- tags: [ApiDocsTags.PkiSigners],
- description: "Sign a pre-hashed digest with a code signing signer",
- params: z.object({
- signerId: z.string().uuid()
- }),
- body: z.object({
- data: z.string().min(1).max(172), // 128 bytes max in base64 = ceil(128/3)*4 = 172 chars
- signingAlgorithm: z.nativeEnum(SigningAlgorithm),
- isDigest: z.boolean().default(false),
- clientMetadata: z
- .object({
- tool: z.string().max(128).optional(),
- hostname: z.string().max(256).optional(),
- reportedIp: z.string().max(64).optional()
- })
- .optional()
- }),
- response: {
- 200: z.object({
- signature: z.string(),
- signingAlgorithm: z.string(),
- signerId: z.string()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- let actorName: string | undefined;
- if (req.auth.authMode === AuthMode.JWT) {
- actorName = `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim() || undefined;
- } else if (req.auth.authMode === AuthMode.IDENTITY_ACCESS_TOKEN) {
- actorName = req.auth.identityName ?? undefined;
- }
-
- const result = await server.services.pkiSigner.sign({
- signerId: req.params.signerId,
- ...req.body,
- actorName,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- projectId: result.projectId,
- event: {
- type: EventType.PKI_SIGNER_SIGN,
- metadata: {
- signerId: req.params.signerId,
- name: result.signerName,
- signingAlgorithm: req.body.signingAlgorithm
- }
- }
- });
-
- await server.services.telemetry.sendPostHogEvents({
- event: PostHogEventTypes.CodeSigningOperation,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- orgId: req.permission.orgId,
- signerId: req.params.signerId
- }
- });
-
- return result;
- }
- });
-
- server.route({
- method: "GET",
- url: "/:signerId/public-key",
- config: { rateLimit: readLimit },
- schema: {
- hide: false,
- operationId: "getSignerPublicKey",
- tags: [ApiDocsTags.PkiSigners],
- description: "Get the public key for a code signing signer",
- params: z.object({
- signerId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- publicKey: z.string(),
- algorithm: z.string()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const result = await server.services.pkiSigner.getPublicKey({
- 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: result.projectId,
- event: {
- type: EventType.GET_PKI_SIGNER_PUBLIC_KEY,
- metadata: {
- signerId: req.params.signerId,
- name: result.signerName
- }
- }
- });
-
- return result;
- }
- });
-
- 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",
- config: { rateLimit: readLimit },
- schema: {
- hide: false,
- operationId: "listSigningOperations",
- tags: [ApiDocsTags.PkiSigners],
- description: "List signing operations for a signer",
- params: z.object({
- signerId: z.string().uuid()
- }),
- querystring: z.object({
- offset: z.coerce.number().int().min(0).default(0),
- limit: z.coerce.number().int().min(1).max(100).default(20),
- status: z.nativeEnum(SigningOperationStatus).optional()
- }),
- response: {
- 200: z.object({
- operations: z.array(
- PkiSigningOperationsSchema.extend({
- actorName: z.string().nullable(),
- actorMembershipId: z.string().uuid().nullable()
- })
- ),
- totalCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const result = await server.services.pkiSigner.listOperations({
- signerId: req.params.signerId,
- ...req.query,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- projectId: result.projectId,
- event: {
- type: EventType.GET_PKI_SIGNING_OPERATIONS,
- metadata: {
- signerId: req.params.signerId,
- count: result.operations.length
- }
- }
- });
-
- return result;
- }
- });
-};
diff --git a/backend/src/server/routes/v1/signer-routers/approval-policy-router.ts b/backend/src/server/routes/v1/signer-routers/approval-policy-router.ts
new file mode 100644
index 0000000000..5e973db699
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-routers/approval-policy-router.ts
@@ -0,0 +1,82 @@
+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 { ApprovalPolicyBodySchema, SignerIdParamsSchema } from "./schemas";
+
+export const registerSignerApprovalPolicyRouter = async (server: FastifyZodProvider) => {
+ 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: SignerIdParamsSchema,
+ 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: "PUT",
+ url: "/:signerId/approval-policy",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "updateSignerApprovalPolicy",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "Replace the signer's approval policy (steps, approvers, limits)",
+ params: SignerIdParamsSchema,
+ body: ApprovalPolicyBodySchema
+ },
+ 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: await server.services.pkiSigner.getProjectIdForSigner(req.params.signerId),
+ event: {
+ type: EventType.UPDATE_PKI_SIGNER_APPROVAL_POLICY,
+ metadata: { signerId: req.params.signerId, stepCount: req.body.steps.length }
+ }
+ });
+
+ return policy;
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/signer-routers/certificate-router.ts b/backend/src/server/routes/v1/signer-routers/certificate-router.ts
new file mode 100644
index 0000000000..476a68235a
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-routers/certificate-router.ts
@@ -0,0 +1,101 @@
+import { z } from "zod";
+
+import { PkiSignersSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } from "@app/lib/api-docs";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+import { SignerIdParamsSchema } from "./schemas";
+
+export const registerSignerCertificateRouter = async (server: FastifyZodProvider) => {
+ 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: SignerIdParamsSchema,
+ 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: SignerIdParamsSchema,
+ 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 };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/signer-routers/index.ts b/backend/src/server/routes/v1/signer-routers/index.ts
new file mode 100644
index 0000000000..9d2c5a132a
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-routers/index.ts
@@ -0,0 +1,15 @@
+import { registerSignerApprovalPolicyRouter } from "./approval-policy-router";
+import { registerSignerCertificateRouter } from "./certificate-router";
+import { registerSignerLifecycleRouter } from "./lifecycle-router";
+import { registerSignerOperationsRouter } from "./operations-router";
+import { registerSignerRequestsRouter } from "./requests-router";
+import { registerSignerSigningRouter } from "./signing-router";
+
+export const registerSignerRouter = async (server: FastifyZodProvider) => {
+ await registerSignerLifecycleRouter(server);
+ await registerSignerSigningRouter(server);
+ await registerSignerCertificateRouter(server);
+ await registerSignerApprovalPolicyRouter(server);
+ await registerSignerRequestsRouter(server);
+ await registerSignerOperationsRouter(server);
+};
diff --git a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts
new file mode 100644
index 0000000000..1e59633fdb
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts
@@ -0,0 +1,373 @@
+import { z } from "zod";
+
+import { PkiSignersSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } from "@app/lib/api-docs";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { 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 { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+import { ApprovalPolicyBodySchema, SignerIdParamsSchema, SignerKeyAlgorithm } from "./schemas";
+
+export const registerSignerLifecycleRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "createSigner",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "Create a code signing signer",
+ body: z.object({
+ projectId: z.string().trim().optional().describe(openApiHidden()),
+ name: slugSchema({ min: 1, max: 64, field: "name" }),
+ description: z.string().trim().max(256).optional(),
+ caId: z.string().uuid().optional(),
+ commonName: z.string().trim().min(1).max(256).optional(),
+ certificateTtlDays: z.number().int().min(1).max(3650).optional(),
+ certificateRenewBeforeDays: z.number().int().min(1).max(30).nullable().optional(),
+ keyAlgorithm: SignerKeyAlgorithm.schema.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: ApprovalPolicyBodySchema.optional()
+ }),
+ response: {
+ 200: PkiSignersSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const signer = await server.services.pkiSigner.create({
+ ...req.body,
+ projectId: req.body.projectId ?? req.internalCertManagerProjectId,
+ 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.CREATE_PKI_SIGNER,
+ metadata: {
+ signerId: signer.id,
+ name: signer.name,
+ certificateId: signer.certificateId,
+ approvalPolicyId: signer.approvalPolicyId
+ }
+ }
+ });
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SignerCreated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ orgId: req.permission.orgId
+ }
+ });
+
+ return signer;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listSigners",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "List code signing signers for a project",
+ querystring: z.object({
+ projectId: z.string().trim().optional().describe(openApiHidden()),
+ offset: z.coerce.number().int().min(0).default(0),
+ limit: z.coerce.number().int().min(1).max(100).default(20),
+ search: z.string().trim().optional()
+ }),
+ response: {
+ 200: z.object({
+ signers: z.array(
+ PkiSignersSchema.extend({
+ certificateCommonName: z.string().nullable().optional(),
+ certificateSerialNumber: z.string().nullable().optional(),
+ certificateNotAfter: z.date().nullable().optional(),
+ approvalPolicyName: z.string().nullable().optional()
+ })
+ ),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.query.projectId ?? req.internalCertManagerProjectId;
+ const { signers, totalCount } = await server.services.pkiSigner.list({
+ ...req.query,
+ 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.GET_PKI_SIGNERS,
+ metadata: {
+ count: signers.length,
+ offset: req.query.offset,
+ limit: req.query.limit
+ }
+ }
+ });
+
+ return { signers, totalCount };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:signerId",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getSignerById",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "Get a code signing signer by ID",
+ params: SignerIdParamsSchema,
+ response: {
+ 200: PkiSignersSchema.extend({
+ certificateCommonName: z.string().nullable().optional(),
+ certificateSerialNumber: z.string().nullable().optional(),
+ certificateNotAfter: z.date().nullable().optional(),
+ certificateNotBefore: z.date().nullable().optional(),
+ certificateKeyAlgorithm: z.string().nullable().optional(),
+ certificateStatus: z.string().nullable().optional(),
+ certificateCaId: z.string().nullable().optional(),
+ approvalPolicyName: z.string().nullable().optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const signer = await server.services.pkiSigner.getById({
+ 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.GET_PKI_SIGNER,
+ metadata: {
+ signerId: signer.id,
+ name: signer.name
+ }
+ }
+ });
+
+ return signer;
+ }
+ });
+
+ 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: SignerIdParamsSchema,
+ response: {
+ 200: z.object({
+ canRead: z.boolean(),
+ canEdit: z.boolean(),
+ canDelete: z.boolean(),
+ canManageStatus: 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",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "updateSigner",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "Update a code signing signer",
+ params: SignerIdParamsSchema,
+ body: z.object({
+ name: slugSchema({ min: 1, max: 64, field: "name" }).optional(),
+ description: z.string().trim().max(256).nullable().optional(),
+ certificateRenewBeforeDays: z.number().int().min(1).max(30).nullable().optional()
+ }),
+ response: {
+ 200: PkiSignersSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const signer = await server.services.pkiSigner.update({
+ 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.UPDATE_PKI_SIGNER,
+ metadata: {
+ signerId: signer.id,
+ name: signer.name
+ }
+ }
+ });
+
+ return signer;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:signerId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "deleteSigner",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "Delete a code signing signer",
+ params: SignerIdParamsSchema,
+ response: {
+ 200: PkiSignersSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const signer = await server.services.pkiSigner.delete({
+ 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.DELETE_PKI_SIGNER,
+ metadata: {
+ signerId: signer.id,
+ name: signer.name
+ }
+ }
+ });
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SignerDeleted,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ orgId: req.permission.orgId
+ }
+ });
+
+ return signer;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:signerId/status",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "updateSignerStatus",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "Enable or disable a signer in a single endpoint",
+ params: SignerIdParamsSchema,
+ body: z.object({ status: z.enum(["active", "disabled"]) }),
+ response: { 200: PkiSignersSchema }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const wantDisabled = req.body.status === "disabled";
+ const signer = wantDisabled
+ ? 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.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: wantDisabled ? EventType.DISABLE_PKI_SIGNER : EventType.ENABLE_PKI_SIGNER,
+ metadata: { signerId: signer.id, name: signer.name }
+ }
+ });
+
+ return signer;
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/signer-routers/operations-router.ts b/backend/src/server/routes/v1/signer-routers/operations-router.ts
new file mode 100644
index 0000000000..69ceef557b
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-routers/operations-router.ts
@@ -0,0 +1,67 @@
+import { z } from "zod";
+
+import { PkiSigningOperationsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } from "@app/lib/api-docs";
+import { readLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { SigningOperationStatus } from "@app/services/signer/signer-enums";
+
+import { SignerIdParamsSchema } from "./schemas";
+
+export const registerSignerOperationsRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:signerId/operations",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listSigningOperations",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "List signing operations for a signer",
+ params: SignerIdParamsSchema,
+ querystring: z.object({
+ offset: z.coerce.number().int().min(0).default(0),
+ limit: z.coerce.number().int().min(1).max(100).default(20),
+ status: z.nativeEnum(SigningOperationStatus).optional()
+ }),
+ response: {
+ 200: z.object({
+ operations: z.array(
+ PkiSigningOperationsSchema.extend({
+ actorName: z.string().nullable(),
+ actorMembershipId: z.string().uuid().nullable()
+ })
+ ),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiSigner.listOperations({
+ signerId: req.params.signerId,
+ ...req.query,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: result.projectId,
+ event: {
+ type: EventType.GET_PKI_SIGNING_OPERATIONS,
+ metadata: {
+ signerId: req.params.signerId,
+ count: result.operations.length
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/signer-routers/requests-router.ts b/backend/src/server/routes/v1/signer-routers/requests-router.ts
new file mode 100644
index 0000000000..fb5223707e
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-routers/requests-router.ts
@@ -0,0 +1,178 @@
+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 { SignerIdParamsSchema } from "./schemas";
+
+export const registerSignerRequestsRouter = async (server: FastifyZodProvider) => {
+ 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: SignerIdParamsSchema,
+ 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: SignerIdParamsSchema,
+ 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: await server.services.pkiSigner.getProjectIdForSigner(req.params.signerId),
+ 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: SignerIdParamsSchema,
+ 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: await server.services.pkiSigner.getProjectIdForSigner(req.params.signerId),
+ 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: await server.services.pkiSigner.getProjectIdForSigner(req.params.signerId),
+ event: {
+ type: EventType.PKI_SIGNER_REVOKE_REQUEST,
+ metadata: { signerId: req.params.signerId, requestId: req.params.requestId }
+ }
+ });
+
+ return result;
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/signer-routers/schemas.ts b/backend/src/server/routes/v1/signer-routers/schemas.ts
new file mode 100644
index 0000000000..8c69d92cda
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-routers/schemas.ts
@@ -0,0 +1,49 @@
+import { z } from "zod";
+
+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
+
+export const SignerIdParamsSchema = z.object({ signerId: z.string().uuid() });
+
+export const SignerKeyAlgorithm = {
+ values: [
+ CertKeyAlgorithm.RSA_2048,
+ CertKeyAlgorithm.RSA_3072,
+ CertKeyAlgorithm.RSA_4096,
+ CertKeyAlgorithm.ECDSA_P256,
+ CertKeyAlgorithm.ECDSA_P384,
+ CertKeyAlgorithm.ECDSA_P521
+ ] as const,
+ get schema() {
+ return z.enum(this.values);
+ }
+} as const;
+
+export const ApprovalPolicyBodySchema = 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()
+ })
+ .refine(
+ (policy) =>
+ policy.steps.length === 0 ||
+ Boolean(policy.constraints?.maxSignings) ||
+ Boolean(policy.constraints?.maxWindowDuration),
+ {
+ message:
+ "Approval policy must define at least one of maxSignings or maxWindowDuration when steps are configured.",
+ path: ["constraints"]
+ }
+ );
diff --git a/backend/src/server/routes/v1/signer-routers/signing-router.ts b/backend/src/server/routes/v1/signer-routers/signing-router.ts
new file mode 100644
index 0000000000..68b5aa8efa
--- /dev/null
+++ b/backend/src/server/routes/v1/signer-routers/signing-router.ts
@@ -0,0 +1,133 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } from "@app/lib/api-docs";
+import { SigningAlgorithm } from "@app/lib/crypto/sign/types";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+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 { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+import { SignerIdParamsSchema } from "./schemas";
+
+export const registerSignerSigningRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/:signerId/sign",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "signData",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "Sign a pre-hashed digest with a code signing signer",
+ params: SignerIdParamsSchema,
+ body: z.object({
+ data: z.string().min(1).max(172), // 128 bytes max in base64 = ceil(128/3)*4 = 172 chars
+ signingAlgorithm: z.nativeEnum(SigningAlgorithm),
+ isDigest: z.boolean().default(false),
+ clientMetadata: z
+ .object({
+ tool: z.string().max(128).optional(),
+ hostname: z.string().max(256).optional(),
+ reportedIp: z.string().max(64).optional()
+ })
+ .optional()
+ }),
+ response: {
+ 200: z.object({
+ signature: z.string(),
+ signingAlgorithm: z.string(),
+ signerId: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ let actorName: string | undefined;
+ if (req.auth.authMode === AuthMode.JWT) {
+ actorName = `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim() || undefined;
+ } else if (req.auth.authMode === AuthMode.IDENTITY_ACCESS_TOKEN) {
+ actorName = req.auth.identityName ?? undefined;
+ }
+
+ const result = await server.services.pkiSigner.sign({
+ signerId: req.params.signerId,
+ ...req.body,
+ actorName,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: result.projectId,
+ event: {
+ type: EventType.PKI_SIGNER_SIGN,
+ metadata: {
+ signerId: req.params.signerId,
+ name: result.signerName,
+ signingAlgorithm: req.body.signingAlgorithm
+ }
+ }
+ });
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.CodeSigningOperation,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ orgId: req.permission.orgId,
+ signerId: req.params.signerId
+ }
+ });
+
+ return result;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:signerId/public-key",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getSignerPublicKey",
+ tags: [ApiDocsTags.PkiSigners],
+ description: "Get the public key for a code signing signer",
+ params: SignerIdParamsSchema,
+ response: {
+ 200: z.object({
+ publicKey: z.string(),
+ algorithm: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiSigner.getPublicKey({
+ 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: result.projectId,
+ event: {
+ type: EventType.GET_PKI_SIGNER_PUBLIC_KEY,
+ metadata: {
+ signerId: req.params.signerId,
+ name: result.signerName
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+};
diff --git a/backend/src/services/approval-policy/approval-policy-enums.ts b/backend/src/services/approval-policy/approval-policy-enums.ts
index 8dc375e1a9..70a2e2e816 100644
--- a/backend/src/services/approval-policy/approval-policy-enums.ts
+++ b/backend/src/services/approval-policy/approval-policy-enums.ts
@@ -7,7 +7,7 @@ export enum ApprovalPolicyType {
export enum ApprovalPolicyScope {
Project = "project",
PkiApplication = "pki-application",
- Signer = "signer"
+ Signer = "pki-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.ts
index 82bafcbdca..19a2023351 100644
--- a/backend/src/services/approval-policy/approval-request-dal.ts
+++ b/backend/src/services/approval-policy/approval-request-dal.ts
@@ -1,12 +1,11 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName, TApprovalRequestApprovals, TApprovalRequests } from "@app/db/schemas";
+import { TableName, TApprovalRequestApprovals } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
import {
- ApprovalPolicyScope,
ApprovalPolicyType,
ApprovalRequestGrantStatus,
ApprovalRequestStatus,
@@ -163,129 +162,15 @@ 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[];
- }) => {
+ const markExpiredRequests = async (): Promise<number> => {
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)
+ const rows = await db(TableName.ApprovalRequests)
.where("status", ApprovalRequestStatus.Pending)
.whereNotNull("expiresAt")
.where("expiresAt", "<", new Date())
- .select("id");
-
- if (expiredRequestIds.length === 0) {
- return [];
- }
-
- const ids = expiredRequestIds.map((r) => r.id);
-
- await db(TableName.ApprovalRequests).whereIn("id", ids).update({ status: ApprovalRequestStatus.Expired });
-
- return ids;
+ .update({ status: ApprovalRequestStatus.Expired })
+ .returning<{ id: string }[]>("id");
+ return rows.length;
} catch (error) {
throw new DatabaseError({ error, name: "Mark expired approval requests" });
}
@@ -296,9 +181,7 @@ export const approvalRequestDALFactory = (db: TDbClient) => {
findStepsByRequestId,
findByProjectId,
findByIdForUpdate,
- markExpiredRequests,
- listSignerRequestsPaginated,
- countSignerRequests
+ markExpiredRequests
};
};
diff --git a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
index e09f612862..1dcf4ba681 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,64 +59,6 @@ import { azureDnsDeleteTxtRecord, azureDnsInsertTxtRecord } from "./dns-provider
import { 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 UNCHANGED_CREDENTIAL_SENTINEL = "__INFISICAL_UNCHANGED__";
const validateDnsResolver = (resolver: string): void => {
@@ -474,19 +416,6 @@ 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.ts
index 452693a05e..50f4769a5c 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 * as x509 from "@peculiar/x509";
+import acme from "acme-client";
import { UnrecoverableError } from "bullmq";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
@@ -411,42 +411,14 @@ export const certificateIssuanceQueueFactory = ({
const skLeafObj = crypto.nativeCrypto.KeyObject.from(leafKeys.privateKey);
skLeaf = skLeafObj.export({ format: "pem", type: "pkcs8" }) as string;
- 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");
+ const [, generatedCsr] = await acme.crypto.createCsr(
+ {
+ altNames: altNames ? altNames.map((san) => san.value) : [],
+ commonName: commonName || ""
+ },
+ skLeaf
+ );
+ certificateCsr = generatedCsr.toString();
}
if (await isCancelled()) {
diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-enums.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-enums.ts
index e872ea5fb0..e2b094f268 100644
--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-enums.ts
+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-enums.ts
@@ -13,3 +13,9 @@ export const DIGICERT_FINAL_ISSUED_STATUSES = [DigiCertOrderStatus.Issued] as co
export enum DigiCertProcessorOutcome {
Skipped = "skipped"
}
+
+export enum DigiCertPollOutcome {
+ Issued = "issued",
+ Pending = "pending",
+ Failed = "failed"
+}
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.ts
index 4771575cc7..4aa8e77ecd 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,7 +39,11 @@ 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 {
+ DIGICERT_FINAL_ISSUED_STATUSES,
+ DigiCertOrderStatus,
+ DigiCertPollOutcome
+} from "./digicert-certificate-authority-enums";
import {
TCreateDigiCertCertificateAuthorityDTO,
TDigiCertCertificateAuthority,
@@ -667,9 +671,9 @@ export const DigiCertCertificateAuthorityFns = ({
caId: string;
orderId: number;
}): Promise<
- | { status: "issued"; certificateId: number }
- | { status: "pending"; orderStatus: string }
- | { status: "failed"; orderStatus: string; reason: string }
+ | { status: DigiCertPollOutcome.Issued; certificateId: number }
+ | { status: DigiCertPollOutcome.Pending; orderStatus: string }
+ | { status: DigiCertPollOutcome.Failed; orderStatus: string; reason: string }
> => {
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
if (!ca.externalCa || ca.externalCa.type !== CaType.DIGICERT) {
@@ -696,7 +700,7 @@ export const DigiCertCertificateAuthorityFns = ({
const isFinalisable = DIGICERT_FINAL_ISSUED_STATUSES.some((status) => status === orderStatus);
if (isFinalisable && certificateId) {
- return { status: "issued", certificateId };
+ return { status: DigiCertPollOutcome.Issued, certificateId };
}
if (
@@ -705,10 +709,10 @@ export const DigiCertCertificateAuthorityFns = ({
orderStatus === DigiCertOrderStatus.Expired ||
orderStatus === DigiCertOrderStatus.Revoked
) {
- return { status: "failed", orderStatus, reason: `DigiCert order ${orderStatus}` };
+ return { status: DigiCertPollOutcome.Failed, orderStatus, reason: `DigiCert order ${orderStatus}` };
}
- return { status: "pending", orderStatus };
+ return { status: DigiCertPollOutcome.Pending, orderStatus };
};
const revokeCertificate = async ({
diff --git a/backend/src/services/certificate-request/certificate-request-dal.ts b/backend/src/services/certificate-request/certificate-request-dal.ts
index ae5501e673..1873b5d1cd 100644
--- a/backend/src/services/certificate-request/certificate-request-dal.ts
+++ b/backend/src/services/certificate-request/certificate-request-dal.ts
@@ -9,6 +9,7 @@ import {
applyProcessedPermissionRulesToQuery,
type ProcessedPermissionRules
} from "@app/lib/knex/permission-filter-utils";
+import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
import { CaStatus } from "@app/services/certificate-authority/certificate-authority-enums";
import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";
@@ -453,15 +454,14 @@ export const certificateRequestDALFactory = (db: TDbClient) => {
}
};
- const markExpiredApprovalRequests = async (expiredApprovalRequestIds: string[]): Promise<number> => {
+ const markExpiredApprovalRequests = async (): Promise<number> => {
try {
- if (expiredApprovalRequestIds.length === 0) {
- return 0;
- }
-
const result = await db(TableName.CertificateRequests)
- .whereIn("approvalRequestId", expiredApprovalRequestIds)
.where("status", CertificateRequestStatus.PENDING_APPROVAL)
+ .whereIn(
+ "approvalRequestId",
+ db.select("id").from(TableName.ApprovalRequests).where("status", ApprovalRequestStatus.Expired)
+ )
.update({ status: CertificateRequestStatus.REJECTED, errorMessage: "Approval request expired" });
return result;
diff --git a/backend/src/services/membership-identity/membership-identity-service.ts b/backend/src/services/membership-identity/membership-identity-service.ts
index 2d20ba3d42..3a092712b0 100644
--- a/backend/src/services/membership-identity/membership-identity-service.ts
+++ b/backend/src/services/membership-identity/membership-identity-service.ts
@@ -1,6 +1,12 @@
import { Knex } from "knex";
-import { AccessScope, ProjectMembershipRole, TemporaryPermissionMode, TMembershipRolesInsert } from "@app/db/schemas";
+import {
+ AccessScope,
+ ProjectMembershipRole,
+ RESOURCE_SCOPE,
+ TemporaryPermissionMode,
+ TMembershipRolesInsert
+} from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
@@ -322,6 +328,21 @@ export const membershipIdentityServiceFactory = ({
);
await membershipRoleDAL.delete({ membershipId: existingMembership.id }, tx);
const doc = await membershipIdentityDAL.deleteById(existingMembership.id, tx);
+
+ if (scopeData.scope === AccessScope.Project) {
+ const projectScopeFields = scopeDatabaseFields as { scopeProjectId?: string };
+ if (projectScopeFields.scopeProjectId) {
+ await membershipIdentityDAL.delete(
+ {
+ scope: RESOURCE_SCOPE,
+ scopeProjectId: projectScopeFields.scopeProjectId,
+ actorIdentityId: dto.selector.identityId
+ },
+ tx
+ );
+ }
+ }
+
return doc;
};
diff --git a/backend/src/services/pki-application/pki-application-membership-service.ts b/backend/src/services/pki-application/pki-application-membership-service.ts
index 919a242a87..456ce29c80 100644
--- a/backend/src/services/pki-application/pki-application-membership-service.ts
+++ b/backend/src/services/pki-application/pki-application-membership-service.ts
@@ -4,9 +4,9 @@ import { Knex } from "knex";
import {
AccessScope,
ActionProjectType,
- ApplicationMembershipRole,
ProjectMembershipRole,
RESOURCE_SCOPE,
+ ResourceMembershipRole,
ResourceType
} from "@app/db/schemas";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
@@ -63,11 +63,11 @@ type TPkiApplicationMembershipServiceFactoryDep = {
export type TPkiApplicationMembershipServiceFactory = ReturnType<typeof pkiApplicationMembershipServiceFactory>;
-const BUILTIN_APPLICATION_ROLES = Object.values(ApplicationMembershipRole).filter(
- (r) => r !== ApplicationMembershipRole.Custom
+const BUILTIN_APPLICATION_ROLES = Object.values(ResourceMembershipRole).filter(
+ (r) => r !== ResourceMembershipRole.Custom
);
-const isBuiltInApplicationRole = (role: string): role is ApplicationMembershipRole =>
+const isBuiltInApplicationRole = (role: string): role is ResourceMembershipRole =>
(BUILTIN_APPLICATION_ROLES as string[]).includes(role);
const unknownApplicationRoleMessage = (role: string) =>
diff --git a/backend/src/services/pki-application/pki-application-service.ts b/backend/src/services/pki-application/pki-application-service.ts
index 6e86d51908..f30242a05d 100644
--- a/backend/src/services/pki-application/pki-application-service.ts
+++ b/backend/src/services/pki-application/pki-application-service.ts
@@ -3,9 +3,9 @@ import { packRules } from "@casl/ability/extra";
import {
ActionProjectType,
- ApplicationMembershipRole,
ProjectMembershipRole,
RESOURCE_SCOPE,
+ ResourceMembershipRole,
ResourceType
} from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
@@ -176,7 +176,7 @@ export const pkiApplicationServiceFactory = ({
},
tx
);
- await membershipRoleDAL.create({ membershipId: newMembership.id, role: ApplicationMembershipRole.Admin }, tx);
+ await membershipRoleDAL.create({ membershipId: newMembership.id, role: ResourceMembershipRole.Admin }, tx);
}
return application;
diff --git a/backend/src/services/project-membership/project-membership-service.ts b/backend/src/services/project-membership/project-membership-service.ts
index 7ac3567918..50676122fa 100644
--- a/backend/src/services/project-membership/project-membership-service.ts
+++ b/backend/src/services/project-membership/project-membership-service.ts
@@ -2,7 +2,14 @@
import { ForbiddenError } from "@casl/ability";
import { Knex } from "knex";
-import { AccessScope, ActionProjectType, ProjectMembershipRole, ProjectVersion, TableName } from "@app/db/schemas";
+import {
+ AccessScope,
+ ActionProjectType,
+ ProjectMembershipRole,
+ ProjectVersion,
+ RESOURCE_SCOPE,
+ TableName
+} from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionMemberActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
@@ -370,6 +377,17 @@ export const projectMembershipServiceFactory = ({
tx
);
+ await membershipUserDAL.delete(
+ {
+ scope: RESOURCE_SCOPE,
+ scopeProjectId: projectId,
+ $in: {
+ actorUserId: projectMembers.map(({ user }) => user.id)
+ }
+ },
+ tx
+ );
+
await secretReminderRecipientsDAL.delete(
{
projectId,
@@ -477,6 +495,16 @@ export const projectMembershipServiceFactory = ({
tx
)
)?.[0];
+
+ await membershipUserDAL.delete(
+ {
+ scope: RESOURCE_SCOPE,
+ scopeProjectId: project.id,
+ actorUserId: actorId
+ },
+ tx
+ );
+
return membership;
});
diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
index cee0829a83..32fcdcbc8a 100644
--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
@@ -100,9 +100,9 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
await userNotificationDAL.pruneNotifications();
await keyValueStoreDAL.pruneExpiredKeys();
await scepTransactionDAL.pruneExpiredTransactions();
- const expiredApprovalRequestIds = await approvalRequestDAL.markExpiredRequests();
- if (expiredApprovalRequestIds.length > 0) {
- await certificateRequestDAL.markExpiredApprovalRequests(expiredApprovalRequestIds);
+ const newlyExpired = await approvalRequestDAL.markExpiredRequests();
+ if (newlyExpired > 0) {
+ await certificateRequestDAL.markExpiredApprovalRequests();
}
await approvalRequestGrantsDAL.markExpiredGrants();
await identityAccessTokenRevocationDAL.removeExpiredRevocations();
@@ -120,9 +120,9 @@ 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);
+ const newlyExpired = await approvalRequestDAL.markExpiredRequests();
+ if (newlyExpired > 0) {
+ await certificateRequestDAL.markExpiredApprovalRequests();
}
await approvalRequestGrantsDAL.markExpiredGrants();
}
diff --git a/backend/src/services/signer-membership/signer-membership-service.ts b/backend/src/services/signer-membership/signer-membership-service.ts
index a4b6a4e8b8..f092c9e5d3 100644
--- a/backend/src/services/signer-membership/signer-membership-service.ts
+++ b/backend/src/services/signer-membership/signer-membership-service.ts
@@ -1,22 +1,16 @@
import { ForbiddenError } from "@casl/ability";
import { Knex } from "knex";
-import {
- AccessScope,
- ActionProjectType,
- ApplicationMembershipRole,
- ProjectMembershipRole,
- RESOURCE_SCOPE,
- ResourceType
-} from "@app/db/schemas";
+import { AccessScope, RESOURCE_SCOPE, ResourceMembershipRole, 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 {
+ ResourcePermissionSignerActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { ActorType } from "@app/services/auth/auth-type";
import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-dal";
@@ -27,6 +21,7 @@ import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TSignerDALFactory } from "../signer/signer-dal";
import { TUserDALFactory } from "../user/user-dal";
import {
+ EffectiveSignerMemberKind,
SignerMemberKind,
TAddSignerMemberDTO,
TAddSignerUserMembersDTO,
@@ -53,7 +48,7 @@ type TSignerMembershipServiceFactoryDep = {
| "findResourceMembershipsForGroup"
>;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "find" | "delete" | "update">;
- permissionService: Pick<TPermissionServiceFactory, "getResourcePermission" | "getProjectPermission">;
+ permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;
userDAL: Pick<TUserDALFactory, "find" | "findByEmailsOrUsernames">;
identityDAL: Pick<TIdentityDALFactory, "find">;
groupDAL: Pick<TGroupDALFactory, "find">;
@@ -64,23 +59,30 @@ type TSignerMembershipServiceFactoryDep = {
export type TSignerMembershipServiceFactory = ReturnType<typeof signerMembershipServiceFactory>;
-export const BUILTIN_SIGNER_ROLES = Object.values(ApplicationMembershipRole).filter(
- (r) => r !== ApplicationMembershipRole.Custom
+export const BUILTIN_SIGNER_ROLES = Object.values(ResourceMembershipRole).filter(
+ (r) => r !== ResourceMembershipRole.Custom
);
-export const isBuiltInSignerRole = (role: string): role is ApplicationMembershipRole =>
+export const isBuiltInSignerRole = (role: string): role is ResourceMembershipRole =>
(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 BUILTIN_ROLE_RANK: Record<string, number> = {
+ [ResourceMembershipRole.Admin]: 3,
+ [ResourceMembershipRole.Operator]: 2,
+ [ResourceMembershipRole.Auditor]: 1
};
-const pickHigherRole = (a: string, b: string) => ((ROLE_RANK[b] ?? 0) > (ROLE_RANK[a] ?? 0) ? b : a);
+const pickGroupRoleForDisplay = (a: string, b: string): string => {
+ const aRank = BUILTIN_ROLE_RANK[a];
+ const bRank = BUILTIN_ROLE_RANK[b];
+ if (aRank !== undefined && bRank !== undefined) return bRank > aRank ? b : a;
+ if (aRank !== undefined) return a;
+ if (bRank !== undefined) return b;
+ return a < b ? a : b;
+};
export const signerMembershipServiceFactory = ({
signerDAL,
@@ -195,7 +197,10 @@ export const signerMembershipServiceFactory = ({
actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Create, ResourcePermissionSub.Member);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionSignerActions.ManageMembers,
+ ResourcePermissionSub.Signer
+ );
if (!isBuiltInSignerRole(role)) {
throw new BadRequestError({ message: unknownSignerRoleMessage(role) });
@@ -203,32 +208,6 @@ export const signerMembershipServiceFactory = ({
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,
@@ -258,22 +237,11 @@ export const signerMembershipServiceFactory = ({
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);
+ // eslint-disable-next-line no-nested-ternary
+ const subjectLabel = userId ? "user" : identityId ? "machine identity" : "group";
+ throw new BadRequestError({
+ message: `This ${subjectLabel} is not a member of this project. Add them to the project first, then assign them to the signer.`
+ });
}
const newMembership = await membershipDAL.create(
@@ -333,7 +301,7 @@ export const signerMembershipServiceFactory = ({
actorAuthMethod,
actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Read, ResourcePermissionSub.Member);
+ ForbiddenError.from(permission).throwUnlessCan(ResourcePermissionSignerActions.Read, ResourcePermissionSub.Signer);
const memberships = await membershipDAL.find({
scope: RESOURCE_SCOPE,
@@ -429,7 +397,7 @@ export const signerMembershipServiceFactory = ({
actorAuthMethod,
actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Read, ResourcePermissionSub.Member);
+ ForbiddenError.from(permission).throwUnlessCan(ResourcePermissionSignerActions.Read, ResourcePermissionSub.Signer);
const allMemberships = await membershipDAL.find({
scope: RESOURCE_SCOPE,
@@ -446,7 +414,7 @@ export const signerMembershipServiceFactory = ({
const idToEntry = new Map<string, EffectiveEntry>();
for (const m of allMemberships) {
- const directActorId = kind === "user" ? m.actorUserId : m.actorIdentityId;
+ const directActorId = kind === EffectiveSignerMemberKind.User ? m.actorUserId : m.actorIdentityId;
const role = directActorId ? (roleByMembership.get(m.id) ?? "") : "";
if (directActorId && role) {
idToEntry.set(directActorId, { role, isDirect: true, viaGroupIds: new Set() });
@@ -457,7 +425,7 @@ export const signerMembershipServiceFactory = ({
const groupIds = groupMemberships.map((m) => m.actorGroupId as string);
if (groupIds.length > 0) {
const expansions =
- kind === "user"
+ kind === EffectiveSignerMemberKind.User
? await userGroupMembershipDAL.find({ $in: { groupId: groupIds } })
: await identityGroupMembershipDAL.find({ $in: { groupId: groupIds } });
@@ -473,11 +441,13 @@ export const signerMembershipServiceFactory = ({
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 {
+ if (!existing) {
idToEntry.set(memberId, { role: groupRole, isDirect: false, viaGroupIds: new Set([groupId]) });
+ } else {
+ existing.viaGroupIds.add(groupId);
+ if (!existing.isDirect) {
+ existing.role = pickGroupRoleForDisplay(existing.role, groupRole);
+ }
}
}
}
@@ -486,7 +456,7 @@ export const signerMembershipServiceFactory = ({
const ids = Array.from(idToEntry.keys());
if (ids.length === 0) return [];
- if (kind === "user") {
+ if (kind === EffectiveSignerMemberKind.User) {
const users = await userDAL.find({ $in: { id: ids } });
return users
.map((u): TEffectiveSignerMember | null => {
@@ -568,7 +538,10 @@ export const signerMembershipServiceFactory = ({
actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Edit, ResourcePermissionSub.Member);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionSignerActions.ManageMembers,
+ ResourcePermissionSub.Signer
+ );
if (!isBuiltInSignerRole(role)) {
throw new BadRequestError({ message: unknownSignerRoleMessage(role) });
@@ -584,7 +557,7 @@ export const signerMembershipServiceFactory = ({
);
const r = updatedRoles[0];
- if (role === ApplicationMembershipRole.Auditor && kind !== SignerMemberKind.Identity) {
+ if (role === ResourceMembershipRole.Auditor && kind !== SignerMemberKind.Identity) {
await approvalPolicyDAL.deleteStepApproversBySubject(
{
projectId,
@@ -641,7 +614,10 @@ export const signerMembershipServiceFactory = ({
actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Delete, ResourcePermissionSub.Member);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionSignerActions.ManageMembers,
+ ResourcePermissionSub.Signer
+ );
const membership = await $findMembershipByMember(signerId, projectId, kind, memberId);
const details = await $buildMemberDetails(membership);
@@ -702,7 +678,10 @@ export const signerMembershipServiceFactory = ({
actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Create, ResourcePermissionSub.Member);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionSignerActions.ManageMembers,
+ ResourcePermissionSub.Signer
+ );
const usersByEmail = emails.length ? await userDAL.find({ $in: { username: emails } }) : [];
const userByEmail = new Map<string, (typeof usersByEmail)[number]>();
@@ -717,22 +696,39 @@ export const signerMembershipServiceFactory = ({
});
const alreadyAttached = new Set<string>(existing.map((m) => m.actorUserId).filter((v): v is string => Boolean(v)));
- const targets: { userId: string; label: string }[] = [];
+ const candidates: { 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 });
+ candidates.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 });
+ candidates.push({ userId: user.id, label: email });
}
});
+ const candidateIds = candidates.map((t) => t.userId);
+ const projectMemberRows = candidateIds.length
+ ? await membershipDAL.find({
+ scope: AccessScope.Project,
+ scopeProjectId: projectId,
+ $in: { actorUserId: candidateIds }
+ })
+ : [];
+ const projectMemberIds = new Set(
+ projectMemberRows.map((m) => m.actorUserId).filter((v): v is string => Boolean(v))
+ );
+ const targets = candidates.filter((t) => {
+ if (projectMemberIds.has(t.userId)) return true;
+ unresolved.push(t.label);
+ return false;
+ });
+
const memberships: TSignerMember[] = [];
const skipped: string[] = [];
for (const t of targets) {
@@ -876,42 +872,6 @@ export const signerMembershipServiceFactory = ({
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,
@@ -920,7 +880,6 @@ export const signerMembershipServiceFactory = ({
updateMemberRole,
removeMember,
listSignersForActor,
- removeActorFromSignerMemberships,
- resolveMembership
+ removeActorFromSignerMemberships
};
};
diff --git a/backend/src/services/signer-membership/signer-membership-types.ts b/backend/src/services/signer-membership/signer-membership-types.ts
index 008cbd3083..2902a3f4cd 100644
--- a/backend/src/services/signer-membership/signer-membership-types.ts
+++ b/backend/src/services/signer-membership/signer-membership-types.ts
@@ -43,7 +43,12 @@ export type TListSignerMembersDTO = {
kind?: TSignerMemberKind;
} & TActorPermission;
-export type TEffectiveSignerMemberKind = "user" | "identity";
+export enum EffectiveSignerMemberKind {
+ User = "user",
+ Identity = "identity"
+}
+
+export type TEffectiveSignerMemberKind = `${EffectiveSignerMemberKind}`;
export type TListEffectiveSignerMembersDTO = {
signerId: string;
diff --git a/backend/src/services/signer/index.ts b/backend/src/services/signer/index.ts
index 10fd58db2c..a4c96d4c98 100644
--- a/backend/src/services/signer/index.ts
+++ b/backend/src/services/signer/index.ts
@@ -1,6 +1,8 @@
export type { TSignerDALFactory } from "./signer-dal";
export { signerDALFactory } from "./signer-dal";
export { SignerStatus, SigningOperationStatus } from "./signer-enums";
+export type { TSignerRequestDALFactory } from "./signer-request-dal";
+export { signerRequestDALFactory } from "./signer-request-dal";
export type { TSignerServiceFactory } from "./signer-service";
export { signerServiceFactory } from "./signer-service";
export type { TSigningOperationDALFactory } from "./signing-operation-dal";
diff --git a/backend/src/services/signer/signer-auto-renewal-queue.ts b/backend/src/services/signer/signer-auto-renewal-queue.ts
index 590a72a95a..8c484b8d7a 100644
--- a/backend/src/services/signer/signer-auto-renewal-queue.ts
+++ b/backend/src/services/signer/signer-auto-renewal-queue.ts
@@ -39,7 +39,7 @@ export const signerAutoRenewalQueueFactory = ({
for (const signer of candidates) {
scanned += 1;
- if (!signer.renewBeforeDays || signer.renewBeforeDays < 1) continue;
+ if (!signer.certificateRenewBeforeDays || signer.certificateRenewBeforeDays < 1) continue;
if (!signer.caId) {
unrenewable += 1;
@@ -64,7 +64,7 @@ export const signerAutoRenewalQueueFactory = ({
const msUntilExpiry = new Date(signer.certificateNotAfter).getTime() - now;
const daysUntilExpiry = msUntilExpiry / MS_PER_DAY;
- const isDue = daysUntilExpiry <= signer.renewBeforeDays;
+ const isDue = daysUntilExpiry <= signer.certificateRenewBeforeDays;
if (!isDue) continue;
needsRenewal += 1;
diff --git a/backend/src/services/signer/signer-issuance-errors.ts b/backend/src/services/signer/signer-issuance-errors.ts
index 74210c9032..53a11e7ea9 100644
--- a/backend/src/services/signer/signer-issuance-errors.ts
+++ b/backend/src/services/signer/signer-issuance-errors.ts
@@ -112,6 +112,54 @@ const collectMessageChain = (err: unknown): string | null => {
return deduped.join(" — ");
};
+export const isTerminalIssuanceError = (err: unknown): boolean => {
+ if (err == null) return false;
+
+ if (err instanceof AcmeError) {
+ const transient = new Set(["AcmeRateLimitedError", "AcmeServerInternalError", "AcmeBadNonceError"]);
+ return !transient.has(err.name);
+ }
+
+ if (
+ err instanceof BadRequestError ||
+ err instanceof NotFoundError ||
+ err instanceof ForbiddenRequestError ||
+ err instanceof CryptographyError
+ ) {
+ return true;
+ }
+
+ if (err instanceof AxiosError) {
+ const status = err.response?.status;
+ if (status && status >= 400 && status < 500 && status !== 408 && status !== 429) {
+ return true;
+ }
+ // No HTTP response
+ return false;
+ }
+
+ if (err instanceof Error && err.message) {
+ const msg = err.message;
+ const TERMINAL_PHRASES = [
+ "exceeds the maximum",
+ "InvalidArgsException",
+ "InvalidArnException",
+ "MalformedCSRException",
+ "LimitExceededException",
+ "ValidationException",
+ "AccessDeniedException",
+ "ResourceNotFoundException",
+ "the requested certificate validity exceeds",
+ "Invalid CSR",
+ "Malformed",
+ "is not supported"
+ ];
+ if (TERMINAL_PHRASES.some((p) => msg.includes(p))) return true;
+ }
+
+ return false;
+};
+
export const formatSignerIssuanceErrorReason = (err: unknown, fallbackContext?: string): string => {
const fallback = fallbackContext
? `${fallbackContext}. Check audit logs for the full error.`
diff --git a/backend/src/services/signer/signer-issuance-fns.ts b/backend/src/services/signer/signer-issuance-fns.ts
index af463cb7f8..e3484e3331 100644
--- a/backend/src/services/signer/signer-issuance-fns.ts
+++ b/backend/src/services/signer/signer-issuance-fns.ts
@@ -95,9 +95,7 @@ export const issueSignerCertificate = async (
}
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."
+ message: "Internal CA record is missing its internal-CA association; cannot issue a signer certificate from it."
});
}
diff --git a/backend/src/services/signer/signer-issuance-job-dal.ts b/backend/src/services/signer/signer-issuance-job-dal.ts
index 7034c698d3..a01dce2ac1 100644
--- a/backend/src/services/signer/signer-issuance-job-dal.ts
+++ b/backend/src/services/signer/signer-issuance-job-dal.ts
@@ -2,7 +2,7 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName, TPkiSignerIssuanceJobs } from "@app/db/schemas";
+import { TableName, TPkiSignerCertificateIssuanceJobs } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex";
@@ -11,15 +11,15 @@ import { SignerIssuanceJobStatus } from "./signer-enums";
export type TSignerIssuanceJobDALFactory = ReturnType<typeof signerIssuanceJobDALFactory>;
export const signerIssuanceJobDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PkiSignerIssuanceJobs);
+ const orm = ormify(db, TableName.PkiSignerCertificateIssuanceJobs);
- const findDuePending = async (now: Date, limit: number, tx?: Knex): Promise<TPkiSignerIssuanceJobs[]> => {
+ const findDuePending = async (now: Date, limit: number, tx?: Knex): Promise<TPkiSignerCertificateIssuanceJobs[]> => {
try {
- return (await (tx || db.replicaNode())(TableName.PkiSignerIssuanceJobs)
+ return (await (tx || db.replicaNode())(TableName.PkiSignerCertificateIssuanceJobs)
.where({ status: SignerIssuanceJobStatus.Pending })
.andWhere("nextPollAt", "<=", now)
.orderBy("nextPollAt", "asc")
- .limit(limit)) as TPkiSignerIssuanceJobs[];
+ .limit(limit)) as TPkiSignerCertificateIssuanceJobs[];
} catch (error) {
throw new DatabaseError({ error, name: "FindDuePendingSignerIssuanceJobs" });
}
@@ -27,7 +27,7 @@ export const signerIssuanceJobDALFactory = (db: TDbClient) => {
const cancelOpenForSigner = async (signerId: string, reason: string, tx?: Knex) => {
try {
- await (tx || db)(TableName.PkiSignerIssuanceJobs)
+ await (tx || db)(TableName.PkiSignerCertificateIssuanceJobs)
.where({ signerId, status: SignerIssuanceJobStatus.Pending })
.update({
status: SignerIssuanceJobStatus.Failed,
@@ -45,9 +45,9 @@ export const signerIssuanceJobDALFactory = (db: TDbClient) => {
nextPollAt: Date,
lastAttemptAt: Date,
tx?: Knex
- ): Promise<TPkiSignerIssuanceJobs | null> => {
+ ): Promise<TPkiSignerCertificateIssuanceJobs | null> => {
try {
- const [row] = await (tx || db)(TableName.PkiSignerIssuanceJobs)
+ const [row] = await (tx || db)(TableName.PkiSignerCertificateIssuanceJobs)
.where({ id: jobId, status: SignerIssuanceJobStatus.Pending, attempts: expectedAttempts })
.update({
attempts: expectedAttempts + 1,
diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.ts
index adbe07f5a7..f71a46d6eb 100644
--- a/backend/src/services/signer/signer-issuance-service.ts
+++ b/backend/src/services/signer/signer-issuance-service.ts
@@ -1,7 +1,7 @@
/* 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 { TPkiSignerCertificateIssuanceJobs } 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";
@@ -14,12 +14,13 @@ import { TCertificateAuthorityDALFactory } from "../certificate-authority/certif
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 { DigiCertPollOutcome } from "../certificate-authority/digicert/digicert-certificate-authority-enums";
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 { formatSignerIssuanceErrorReason, isTerminalIssuanceError } from "./signer-issuance-errors";
import { verifyCodeSigningEku } from "./signer-issuance-fns";
import { TSignerIssuanceJobDALFactory } from "./signer-issuance-job-dal";
@@ -33,7 +34,7 @@ export type TSignerIssuanceServiceFactory = ReturnType<typeof signerIssuanceServ
type TSignerIssuanceServiceDeps = {
signerIssuanceJobDAL: TSignerIssuanceJobDALFactory;
- signerDAL: Pick<TSignerDALFactory, "updateById">;
+ signerDAL: Pick<TSignerDALFactory, "updateById" | "transaction">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create" | "updateById">;
@@ -112,7 +113,7 @@ export const signerIssuanceServiceFactory = ({
return decryptor({ cipherTextBlob: cipher });
};
- const requestIssuance = async (input: TRequestIssuanceInput): Promise<TPkiSignerIssuanceJobs> => {
+ const requestIssuance = async (input: TRequestIssuanceInput): Promise<TPkiSignerCertificateIssuanceJobs> => {
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(input.caId);
if (!ca || ca.projectId !== input.projectId) {
throw new BadRequestError({
@@ -216,16 +217,16 @@ export const signerIssuanceServiceFactory = ({
await stepDigiCert(job);
break;
case CaType.ACME:
- await stepSyncWithCsr(job, "acme");
+ await stepSyncWithCsr(job, CaType.ACME);
break;
case CaType.AZURE_AD_CS:
- await stepSyncWithCsr(job, "azure");
+ await stepSyncWithCsr(job, CaType.AZURE_AD_CS);
break;
case CaType.AWS_PCA:
- await stepSyncWithCsr(job, "aws-pca");
+ await stepSyncWithCsr(job, CaType.AWS_PCA);
break;
case CaType.VENAFI_TPP:
- await stepSyncWithCsr(job, "venafi");
+ await stepSyncWithCsr(job, CaType.VENAFI_TPP);
break;
case CaType.AWS_ACM_PUBLIC_CA:
await markJobFailed(
@@ -241,6 +242,14 @@ export const signerIssuanceServiceFactory = ({
err,
"External Certificate Authority refused to issue the signer certificate"
);
+ if (isTerminalIssuanceError(err)) {
+ await markJobFailed(job, reason);
+ logger.error(
+ err,
+ `signer issuance: terminal failure, not retrying [jobId=${job.id}] [signerId=${job.signerId}]`
+ );
+ return;
+ }
const rows = await signerIssuanceJobDAL.update(
{ id: job.id, status: SignerIssuanceJobStatus.Pending },
{
@@ -251,7 +260,7 @@ export const signerIssuanceServiceFactory = ({
if (rows.length > 0) {
await signerDAL.updateById(job.signerId, {
status: SignerStatus.Pending,
- failureReason: reason
+ certificateFailureReason: reason
});
}
logger.error(
@@ -261,21 +270,21 @@ export const signerIssuanceServiceFactory = ({
}
};
- const markJobFailed = async (job: TPkiSignerIssuanceJobs, reason: string) => {
+ const markJobFailed = async (job: TPkiSignerCertificateIssuanceJobs, 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)
+ certificateFailureReason: 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 markJobFailedIfStillPending = async (job: TPkiSignerCertificateIssuanceJobs, reason: string) => {
const trimmed = reason.slice(0, 1000);
const rows = await signerIssuanceJobDAL.update(
{ id: job.id, status: SignerIssuanceJobStatus.Pending },
@@ -284,7 +293,7 @@ export const signerIssuanceServiceFactory = ({
if (rows.length === 0) return;
await signerDAL.updateById(job.signerId, {
status: SignerStatus.Failed,
- failureReason: trimmed
+ certificateFailureReason: trimmed
});
logger.info(
`signer issuance: job marked Failed [jobId=${job.id}] [signerId=${job.signerId}] [reason=${trimmed.slice(0, 200)}]`
@@ -292,7 +301,7 @@ export const signerIssuanceServiceFactory = ({
};
const attachIssuedCertToSigner = async (
- job: TPkiSignerIssuanceJobs,
+ job: TPkiSignerCertificateIssuanceJobs,
certificateId: string,
projectId: string
): Promise<void> => {
@@ -304,22 +313,32 @@ export const signerIssuanceServiceFactory = ({
return;
}
- await signerDAL.updateById(job.signerId, {
- certificateId,
- status: SignerStatus.Active,
- failureReason: null
- });
- await signerIssuanceJobDAL.updateById(job.id, {
- status: SignerIssuanceJobStatus.Completed,
- certificateId,
- failureReason: null
+ await signerDAL.transaction(async (tx) => {
+ await signerDAL.updateById(
+ job.signerId,
+ {
+ certificateId,
+ status: SignerStatus.Active,
+ certificateFailureReason: null
+ },
+ tx
+ );
+ await signerIssuanceJobDAL.updateById(
+ job.id,
+ {
+ status: SignerIssuanceJobStatus.Completed,
+ certificateId,
+ failureReason: null
+ },
+ tx
+ );
});
logger.info(
`signer issuance: signer attached [jobId=${job.id}] [signerId=${job.signerId}] [certificateId=${certificateId}]`
);
};
- const stepDigiCert = async (job: TPkiSignerIssuanceJobs) => {
+ const stepDigiCert = async (job: TPkiSignerCertificateIssuanceJobs) => {
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(job.caId);
if (!ca) {
await markJobFailed(job, "Certificate authority is no longer available.");
@@ -381,7 +400,7 @@ export const signerIssuanceServiceFactory = ({
const ref = existingRef as { type: CaType.DIGICERT; orderId: number };
const poll = await digicertFns.pollOrderForCertificate({ caId: job.caId, orderId: ref.orderId });
- if (poll.status === "pending") {
+ if (poll.status === DigiCertPollOutcome.Pending) {
await signerIssuanceJobDAL.updateById(job.id, {
nextPollAt: new Date(Date.now() + PENDING_VALIDATION_POLL_INTERVAL_MS)
});
@@ -390,7 +409,7 @@ export const signerIssuanceServiceFactory = ({
);
return;
}
- if (poll.status === "failed") {
+ if (poll.status === DigiCertPollOutcome.Failed) {
await markJobFailed(job, poll.reason);
return;
}
@@ -414,7 +433,10 @@ export const signerIssuanceServiceFactory = ({
await attachIssuedCertToSigner(job, certificateId, projectId);
};
- const stepSyncWithCsr = async (job: TPkiSignerIssuanceJobs, kind: "acme" | "azure" | "aws-pca" | "venafi") => {
+ const stepSyncWithCsr = async (
+ job: TPkiSignerCertificateIssuanceJobs,
+ kind: CaType.ACME | CaType.AZURE_AD_CS | CaType.AWS_PCA | CaType.VENAFI_TPP
+ ) => {
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(job.caId);
if (!ca) {
await markJobFailed(job, "Certificate authority is no longer available.");
@@ -425,7 +447,7 @@ export const signerIssuanceServiceFactory = ({
let certificateId: string;
- if (kind === "acme") {
+ if (kind === CaType.ACME) {
const acmeResult = await acmeFns.orderCertificateFromProfile({
caId: job.caId,
profileId: undefined as unknown as string,
@@ -447,7 +469,7 @@ export const signerIssuanceServiceFactory = ({
throw new BadRequestError({ message: "ACME order returned without a certificate id." });
}
certificateId = acmeResult.id;
- } else if (kind === "azure") {
+ } else if (kind === CaType.AZURE_AD_CS) {
const azureResult = await azureAdCsFns.orderCertificateFromProfile({
caId: job.caId,
profileId: undefined as unknown as string,
@@ -467,7 +489,7 @@ export const signerIssuanceServiceFactory = ({
throw new BadRequestError({ message: "Azure AD CS order returned without a certificate id." });
}
certificateId = azureResult.certificateId;
- } else if (kind === "aws-pca") {
+ } else if (kind === CaType.AWS_PCA) {
const awsResult = await awsPcaFns.orderCertificateFromProfile({
caId: job.caId,
profileId: undefined as unknown as string,
@@ -516,7 +538,7 @@ export const signerIssuanceServiceFactory = ({
const persistCertificatePrivateKey = async (
certificateId: string,
projectId: string,
- job: TPkiSignerIssuanceJobs
+ job: TPkiSignerCertificateIssuanceJobs
) => {
if (!job.encryptedPrivateKey) return;
const existing = await certificateSecretDAL.findOne({ certId: certificateId });
diff --git a/backend/src/services/signer/signer-policy-service.ts b/backend/src/services/signer/signer-policy-service.ts
index dfebaf18d1..0280b0711e 100644
--- a/backend/src/services/signer/signer-policy-service.ts
+++ b/backend/src/services/signer/signer-policy-service.ts
@@ -1,6 +1,6 @@
import { ForbiddenError } from "@casl/ability";
-import { ApplicationMembershipRole, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";
+import { RESOURCE_SCOPE, ResourceMembershipRole, 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";
@@ -35,6 +35,7 @@ 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 { TSignerRequestDALFactory } from "./signer-request-dal";
import {
TGetSignerPolicyDTO,
TListSignerRequestsDTO,
@@ -50,16 +51,8 @@ type TSignerPolicyServiceFactoryDep = {
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"
- >;
+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "create" | "find" | "findById" | "updateById" | "transaction">;
+ signerRequestDAL: TSignerRequestDALFactory;
approvalRequestStepsDAL: Pick<TApprovalRequestStepsDALFactory, "create">;
approvalRequestStepEligibleApproversDAL: Pick<TApprovalRequestStepEligibleApproversDALFactory, "create">;
approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "create" | "find" | "updateById">;
@@ -100,6 +93,7 @@ export const signerPolicyServiceFactory = ({
approvalPolicyStepsDAL,
approvalPolicyStepApproversDAL,
approvalRequestDAL,
+ signerRequestDAL,
approvalRequestStepsDAL,
approvalRequestStepEligibleApproversDAL,
approvalRequestGrantsDAL,
@@ -326,7 +320,7 @@ export const signerPolicyServiceFactory = ({
const roles = await membershipRoleDAL.find({ $in: { membershipId: membershipIds } });
const auditorIds = new Set<string>();
for (const r of roles) {
- if (r.role === ApplicationMembershipRole.Auditor) {
+ if (r.role === ResourceMembershipRole.Auditor) {
const m = memberships.find((mem) => mem.id === r.membershipId);
if (m?.actorUserId) auditorIds.add(m.actorUserId);
}
@@ -361,7 +355,7 @@ export const signerPolicyServiceFactory = ({
const roles = await membershipRoleDAL.find({ $in: { membershipId: membershipIds } });
const auditorGroupIds = new Set<string>();
for (const r of roles) {
- if (r.role === ApplicationMembershipRole.Auditor) {
+ if (r.role === ResourceMembershipRole.Auditor) {
const m = memberships.find((mem) => mem.id === r.membershipId);
if (m?.actorGroupId) auditorGroupIds.add(m.actorGroupId);
}
@@ -385,10 +379,7 @@ export const signerPolicyServiceFactory = ({
ResourcePermissionSignerActions.ManagePolicy
);
- const effectiveConstraints =
- dto.steps.length > 0 && !dto.constraints?.maxSignings && !dto.constraints?.maxWindowDuration
- ? { ...(dto.constraints ?? {}), maxSignings: 1, maxWindowDuration: null }
- : (dto.constraints ?? {});
+ const effectiveConstraints = dto.constraints ?? {};
if (dto.steps.length > 0) {
if (effectiveConstraints.maxWindowDuration) {
@@ -499,7 +490,7 @@ export const signerPolicyServiceFactory = ({
const limit = dto.limit ?? 25;
const [requests, totalCount] = await Promise.all([
- approvalRequestDAL.listSignerRequestsPaginated({
+ signerRequestDAL.listSignerRequestsPaginated({
signerId: signer.id,
projectId: signer.projectId,
type: ApprovalPolicyType.CertCodeSigning,
@@ -507,7 +498,7 @@ export const signerPolicyServiceFactory = ({
offset,
limit
}),
- approvalRequestDAL.countSignerRequests({
+ signerRequestDAL.countSignerRequests({
signerId: signer.id,
projectId: signer.projectId,
type: ApprovalPolicyType.CertCodeSigning,
@@ -644,7 +635,7 @@ export const signerPolicyServiceFactory = ({
if (granteeRoles.length === 0) {
throw new BadRequestError({ message: "Grantee is not a member of this signer." });
}
- const hasGrantableRole = granteeRoles.some((r) => r !== ApplicationMembershipRole.Auditor);
+ const hasGrantableRole = granteeRoles.some((r) => r !== ResourceMembershipRole.Auditor);
if (!hasGrantableRole) {
throw new BadRequestError({ message: "Grantee must be an Administrator or Operator on this signer." });
}
@@ -701,8 +692,7 @@ export const signerPolicyServiceFactory = ({
maxSignings: effectiveSignings,
windowStart: effectiveWindowStart
},
- expiresAt: effectiveWindowEnd ? new Date(effectiveWindowEnd) : null,
- grantedByUserId: dto.actor === ActorType.USER ? dto.actorId : null
+ expiresAt: effectiveWindowEnd ? new Date(effectiveWindowEnd) : null
},
tx
);
diff --git a/backend/src/services/signer/signer-request-dal.ts b/backend/src/services/signer/signer-request-dal.ts
new file mode 100644
index 0000000000..c43e7ed9e5
--- /dev/null
+++ b/backend/src/services/signer/signer-request-dal.ts
@@ -0,0 +1,121 @@
+import { TDbClient } from "@app/db";
+import { TableName, TApprovalRequests } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+
+import {
+ ApprovalPolicyScope,
+ ApprovalPolicyType,
+ ApprovalRequestGrantStatus
+} from "../approval-policy/approval-policy-enums";
+
+export type TSignerRequestDALFactory = ReturnType<typeof signerRequestDALFactory>;
+
+export const signerRequestDALFactory = (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.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;
+ 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
+ }));
+ } 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" });
+ }
+ };
+
+ return {
+ listSignerRequestsPaginated,
+ countSignerRequests
+ };
+};
diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.ts
index 8919ad1296..8eb994b28a 100644
--- a/backend/src/services/signer/signer-service.ts
+++ b/backend/src/services/signer/signer-service.ts
@@ -3,16 +3,16 @@ import * as x509 from "@peculiar/x509";
import { KeyObject } from "crypto";
import {
+ AccessScope,
ActionProjectType,
- ApplicationMembershipRole,
ProjectMembershipRole,
RESOURCE_SCOPE,
+ ResourceMembershipRole,
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 {
@@ -221,11 +221,11 @@ export const signerServiceFactory = ({
});
}
- if (usingCa && dto.renewBeforeDays != null) {
+ if (usingCa && dto.certificateRenewBeforeDays != null) {
const ttl = dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS;
- if (dto.renewBeforeDays >= ttl) {
+ if (dto.certificateRenewBeforeDays >= ttl) {
throw new BadRequestError({
- message: `Renew before (${dto.renewBeforeDays}d) must be less than the certificate validity (${ttl}d).`
+ message: `Renew before (${dto.certificateRenewBeforeDays}d) must be less than the certificate validity (${ttl}d).`
});
}
}
@@ -329,11 +329,11 @@ export const signerServiceFactory = ({
caId: resolvedCaId,
commonName: usingCa ? dto.commonName : null,
certificateTtlDays: usingCa ? (dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS) : null,
- renewBeforeDays: usingCa ? (dto.renewBeforeDays ?? null) : null,
+ certificateRenewBeforeDays: usingCa ? (dto.certificateRenewBeforeDays ?? null) : null,
keyAlgorithm,
status: initialStatus,
approvalPolicyId: policy.id,
- failureReason: null
+ certificateFailureReason: null
},
tx
);
@@ -360,7 +360,7 @@ export const signerServiceFactory = ({
},
tx
);
- await membershipRoleDAL.create({ membershipId: newMembership.id, role: ApplicationMembershipRole.Admin }, tx);
+ await membershipRoleDAL.create({ membershipId: newMembership.id, role: ResourceMembershipRole.Admin }, tx);
}
const pendingMembers = (dto.members ?? []).filter(
@@ -371,6 +371,64 @@ export const signerServiceFactory = ({
message: "Cannot add members during signer creation without an organization context."
});
}
+
+ if (pendingMembers.length > 0) {
+ const pendingUserIds = pendingMembers.filter((m) => m.kind === "user").map((m) => m.id);
+ const pendingIdentityIds = pendingMembers.filter((m) => m.kind === "identity").map((m) => m.id);
+ const pendingGroupIds = pendingMembers.filter((m) => m.kind === "group").map((m) => m.id);
+
+ const [userRows, identityRows, groupRows] = await Promise.all([
+ pendingUserIds.length
+ ? membershipDAL.find(
+ {
+ scope: AccessScope.Project,
+ scopeProjectId: dto.projectId,
+ $in: { actorUserId: pendingUserIds }
+ },
+ { tx }
+ )
+ : Promise.resolve([] as Awaited<ReturnType<typeof membershipDAL.find>>),
+ pendingIdentityIds.length
+ ? membershipDAL.find(
+ {
+ scope: AccessScope.Project,
+ scopeProjectId: dto.projectId,
+ $in: { actorIdentityId: pendingIdentityIds }
+ },
+ { tx }
+ )
+ : Promise.resolve([] as Awaited<ReturnType<typeof membershipDAL.find>>),
+ pendingGroupIds.length
+ ? membershipDAL.find(
+ {
+ scope: AccessScope.Project,
+ scopeProjectId: dto.projectId,
+ $in: { actorGroupId: pendingGroupIds }
+ },
+ { tx }
+ )
+ : Promise.resolve([] as Awaited<ReturnType<typeof membershipDAL.find>>)
+ ]);
+ const validUserIds = new Set(userRows.map((m) => m.actorUserId).filter((v): v is string => Boolean(v)));
+ const validIdentityIds = new Set(
+ identityRows.map((m) => m.actorIdentityId).filter((v): v is string => Boolean(v))
+ );
+ const validGroupIds = new Set(groupRows.map((m) => m.actorGroupId).filter((v): v is string => Boolean(v)));
+ for (const m of pendingMembers) {
+ const ok =
+ (m.kind === "user" && validUserIds.has(m.id)) ||
+ (m.kind === "identity" && validIdentityIds.has(m.id)) ||
+ (m.kind === "group" && validGroupIds.has(m.id));
+ if (!ok) {
+ // eslint-disable-next-line no-nested-ternary
+ const subjectLabel = m.kind === "user" ? "user" : m.kind === "identity" ? "machine identity" : "group";
+ throw new BadRequestError({
+ message: `Cannot add ${subjectLabel} ${m.id} to the signer: they are not a member of this project. Add them to the project first.`
+ });
+ }
+ }
+ }
+
for (const member of pendingMembers) {
if (!isBuiltInSignerRole(member.role)) {
throw new BadRequestError({ message: unknownSignerRoleMessage(member.role) });
@@ -394,16 +452,13 @@ export const signerServiceFactory = ({
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 effectiveConstraints = 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.role !== ResourceMembershipRole.Auditor) {
if (m.kind === "user") allowedApproverIds.add(m.id);
else if (m.kind === "group") allowedGroupApproverIds.add(m.id);
}
@@ -496,7 +551,7 @@ export const signerServiceFactory = ({
);
await signerDAL.updateById(result.id, {
status: SignerStatus.Failed,
- failureReason: formatSignerIssuanceErrorReason(
+ certificateFailureReason: formatSignerIssuanceErrorReason(
queueErr,
"Could not schedule issuance from the external Certificate Authority"
)
@@ -597,16 +652,12 @@ export const signerServiceFactory = ({
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,
+ canManageStatus: allows(ResourcePermissionSignerActions.ManageStatus),
+ canManageMembers: allows(ResourcePermissionSignerActions.ManageMembers),
canManagePolicy: allows(ResourcePermissionSignerActions.ManagePolicy),
canSign: allows(ResourcePermissionSignerActions.Sign),
canRequestSign: allows(ResourcePermissionSignerActions.RequestSign),
@@ -638,19 +689,22 @@ export const signerServiceFactory = ({
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;
+ if (dto.certificateRenewBeforeDays !== undefined) {
+ if (dto.certificateRenewBeforeDays === null) {
+ patch.certificateRenewBeforeDays = null;
} else {
- if (dto.renewBeforeDays < 1 || dto.renewBeforeDays > 30) {
+ if (dto.certificateRenewBeforeDays < 1 || dto.certificateRenewBeforeDays > 30) {
throw new BadRequestError({ message: "Renew before must be between 1 and 30 days." });
}
- if (existingSigner.certificateTtlDays != null && dto.renewBeforeDays >= existingSigner.certificateTtlDays) {
+ if (
+ existingSigner.certificateTtlDays != null &&
+ dto.certificateRenewBeforeDays >= existingSigner.certificateTtlDays
+ ) {
throw new BadRequestError({
- message: `Renew before (${dto.renewBeforeDays}d) must be less than the certificate validity (${existingSigner.certificateTtlDays}d).`
+ message: `Renew before (${dto.certificateRenewBeforeDays}d) must be less than the certificate validity (${existingSigner.certificateTtlDays}d).`
});
}
- patch.renewBeforeDays = dto.renewBeforeDays;
+ patch.certificateRenewBeforeDays = dto.certificateRenewBeforeDays;
}
}
@@ -719,7 +773,7 @@ export const signerServiceFactory = ({
dto.actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(
- ResourcePermissionSignerActions.EnableDisable,
+ ResourcePermissionSignerActions.ManageStatus,
ResourcePermissionSub.Signer
);
@@ -749,7 +803,7 @@ export const signerServiceFactory = ({
dto.actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(
- ResourcePermissionSignerActions.EnableDisable,
+ ResourcePermissionSignerActions.ManageStatus,
ResourcePermissionSub.Signer
);
@@ -804,9 +858,9 @@ export const signerServiceFactory = ({
}
const effectiveTtl = nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS;
- if (signer.renewBeforeDays != null && signer.renewBeforeDays >= effectiveTtl) {
+ if (signer.certificateRenewBeforeDays != null && signer.certificateRenewBeforeDays >= 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.`
+ message: `Certificate validity (${effectiveTtl}d) must be greater than the configured renew before (${signer.certificateRenewBeforeDays}d). Update the renew-before window before reissuing with a shorter validity.`
});
}
@@ -822,7 +876,7 @@ export const signerServiceFactory = ({
if (reissueIsExternal) {
await signerDAL.updateById(dto.signerId, {
status: SignerStatus.Pending,
- failureReason: null
+ certificateFailureReason: null
});
try {
await signerIssuanceService.requestIssuance({
@@ -837,7 +891,7 @@ export const signerServiceFactory = ({
} catch (queueErr) {
await signerDAL.updateById(dto.signerId, {
status: SignerStatus.Failed,
- failureReason: formatSignerIssuanceErrorReason(
+ certificateFailureReason: formatSignerIssuanceErrorReason(
queueErr,
"Could not schedule re-issuance from the external Certificate Authority"
)
@@ -868,7 +922,7 @@ export const signerServiceFactory = ({
return await signerDAL.updateById(dto.signerId, {
certificateId,
status: SignerStatus.Active,
- failureReason: null
+ certificateFailureReason: null
});
} catch (issueErr) {
logger.error(
@@ -877,7 +931,7 @@ export const signerServiceFactory = ({
);
await signerDAL.updateById(dto.signerId, {
status: SignerStatus.Failed,
- failureReason: formatSignerIssuanceErrorReason(issueErr, "Internal CA certificate issuance failed")
+ certificateFailureReason: formatSignerIssuanceErrorReason(issueErr, "Internal CA certificate issuance failed")
});
throw issueErr;
}
@@ -1236,7 +1290,11 @@ export const signerServiceFactory = ({
certificateId: string,
tx?: Parameters<TSignerDALFactory["updateById"]>[2]
) => {
- return signerDAL.updateById(signerId, { certificateId, status: SignerStatus.Active, failureReason: null }, tx);
+ return signerDAL.updateById(
+ signerId,
+ { certificateId, status: SignerStatus.Active, certificateFailureReason: null },
+ tx
+ );
};
const markIssuanceFailed = async (
@@ -1246,7 +1304,7 @@ export const signerServiceFactory = ({
) => {
return signerDAL.updateById(
signerId,
- { status: SignerStatus.Failed, failureReason: reason ? reason.slice(0, 1000) : null },
+ { status: SignerStatus.Failed, certificateFailureReason: reason ? reason.slice(0, 1000) : null },
tx
);
};
@@ -1274,7 +1332,7 @@ export const signerServiceFactory = ({
logger.warn(`signer auto-renewal: ${reason} [signerId=${signer.id}]`);
await signerDAL.updateById(signer.id, {
status: SignerStatus.Failed,
- failureReason: reason.slice(0, 1000)
+ certificateFailureReason: reason.slice(0, 1000)
});
return;
}
@@ -1282,7 +1340,7 @@ export const signerServiceFactory = ({
const reason = `Certificate authority '${ca.name}' is not active.`;
await signerDAL.updateById(signer.id, {
status: SignerStatus.Failed,
- failureReason: reason.slice(0, 1000)
+ certificateFailureReason: reason.slice(0, 1000)
});
return;
}
@@ -1294,7 +1352,7 @@ export const signerServiceFactory = ({
if (isExternal) {
await signerDAL.updateById(signer.id, {
status: SignerStatus.Pending,
- failureReason: null
+ certificateFailureReason: null
});
try {
await signerIssuanceService.requestIssuance({
@@ -1308,7 +1366,7 @@ export const signerServiceFactory = ({
} catch (err) {
await signerDAL.updateById(signer.id, {
status: SignerStatus.Failed,
- failureReason: formatSignerIssuanceErrorReason(
+ certificateFailureReason: formatSignerIssuanceErrorReason(
err,
"Could not schedule auto-renewal from the external Certificate Authority"
)
@@ -1339,7 +1397,7 @@ export const signerServiceFactory = ({
await signerDAL.updateById(signer.id, {
certificateId,
status: SignerStatus.Active,
- failureReason: null
+ certificateFailureReason: null
});
logger.info(
`signer auto-renewal: renewed signer '${signer.name}' [signerId=${signer.id}] [newCertificateId=${certificateId}]`
@@ -1347,17 +1405,24 @@ export const signerServiceFactory = ({
} catch (err) {
await signerDAL.updateById(signer.id, {
status: SignerStatus.Failed,
- failureReason: formatSignerIssuanceErrorReason(err, "Internal CA auto-renewal failed")
+ certificateFailureReason: formatSignerIssuanceErrorReason(err, "Internal CA auto-renewal failed")
});
logger.error(err, `signer auto-renewal: internal CA issuance failed [signerId=${signer.id}]`);
}
};
+ const getProjectIdForSigner = async (signerId: string): Promise<string> => {
+ const signer = await signerDAL.findById(signerId);
+ if (!signer) throw new NotFoundError({ message: `Signer '${signerId}' not found.` });
+ return signer.projectId;
+ };
+
return {
create,
list,
getById,
getMyPermissions,
+ getProjectIdForSigner,
update,
delete: deleteSigner,
enable,
diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.ts
index 0d5aab1257..1415d499b8 100644
--- a/backend/src/services/signer/signer-types.ts
+++ b/backend/src/services/signer/signer-types.ts
@@ -23,7 +23,7 @@ export type TCreateSignerDTO = {
caId?: string;
commonName?: string;
certificateTtlDays?: number;
- renewBeforeDays?: number | null;
+ certificateRenewBeforeDays?: number | null;
keyAlgorithm?: CertKeyAlgorithm;
certificateId?: string;
approvalPolicyId?: string;
@@ -35,7 +35,7 @@ export type TUpdateSignerDTO = {
signerId: string;
name?: string;
description?: string | null;
- renewBeforeDays?: number | null;
+ certificateRenewBeforeDays?: number | null;
} & TActorPermission;
export type TDeleteSignerDTO = {
diff --git a/frontend/src/hooks/api/signers/mutations.tsx b/frontend/src/hooks/api/signers/mutations.tsx
index a409d3afe4..7a34bcd35c 100644
--- a/frontend/src/hooks/api/signers/mutations.tsx
+++ b/frontend/src/hooks/api/signers/mutations.tsx
@@ -84,8 +84,9 @@ export const useEnableSigner = () => {
return useMutation<TSigner, object, TEnableSignerDTO>({
mutationFn: async ({ signerId }) => {
- const { data } = await apiRequest.post<TSigner>(
- `/api/v1/cert-manager/signers/${signerId}/enable`
+ const { data } = await apiRequest.patch<TSigner>(
+ `/api/v1/cert-manager/signers/${signerId}/status`,
+ { status: "active" }
);
return data;
},
@@ -102,8 +103,9 @@ export const useDisableSigner = () => {
return useMutation<TSigner, object, TDisableSignerDTO>({
mutationFn: async ({ signerId }) => {
- const { data } = await apiRequest.post<TSigner>(
- `/api/v1/cert-manager/signers/${signerId}/disable`
+ const { data } = await apiRequest.patch<TSigner>(
+ `/api/v1/cert-manager/signers/${signerId}/status`,
+ { status: "disabled" }
);
return data;
},
@@ -315,7 +317,7 @@ export const useUpdateSignerPolicy = () => {
return useMutation<TSignerPolicy, object, TUpdateSignerPolicyDTO>({
mutationFn: async ({ signerId, ...body }) => {
- const { data } = await apiRequest.patch<TSignerPolicy>(
+ const { data } = await apiRequest.put<TSignerPolicy>(
`/api/v1/cert-manager/signers/${signerId}/approval-policy`,
body
);
diff --git a/frontend/src/hooks/api/signers/queries.tsx b/frontend/src/hooks/api/signers/queries.tsx
index 1d7e2cfa64..d570d00641 100644
--- a/frontend/src/hooks/api/signers/queries.tsx
+++ b/frontend/src/hooks/api/signers/queries.tsx
@@ -51,7 +51,7 @@ export type TSignerMyPermissions = {
canRead: boolean;
canEdit: boolean;
canDelete: boolean;
- canEnableDisable: boolean;
+ canManageStatus: boolean;
canManageMembers: boolean;
canManagePolicy: boolean;
canSign: boolean;
diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.ts
index d9035b1f00..6e91dce3d2 100644
--- a/frontend/src/hooks/api/signers/types.ts
+++ b/frontend/src/hooks/api/signers/types.ts
@@ -72,7 +72,7 @@ export type TSigner = {
caId?: string | null;
commonName?: string | null;
certificateTtlDays?: number | null;
- renewBeforeDays?: number | null;
+ certificateRenewBeforeDays?: number | null;
keyAlgorithm?: SignerKeyAlgorithm | string | null;
lastSignedAt?: string | null;
createdAt: string;
@@ -81,7 +81,7 @@ export type TSigner = {
certificateSerialNumber?: string | null;
certificateNotAfter?: string | null;
approvalPolicyName?: string | null;
- failureReason?: string | null;
+ certificateFailureReason?: string | null;
};
export enum SigningActorType {
@@ -190,7 +190,6 @@ export type TSignerRequest = {
expiresAt?: string | null;
scopeType?: string | null;
scopeId?: string | null;
- grantedByUserId?: string | null;
maxSignings?: number | null;
usedSignings?: number;
grantStatus?: string | null;
@@ -234,7 +233,7 @@ export type TCreateSignerDTO = {
caId?: string;
commonName?: string;
certificateTtlDays?: number;
- renewBeforeDays?: number | null;
+ certificateRenewBeforeDays?: number | null;
keyAlgorithm?: SignerKeyAlgorithm;
certificateId?: string;
approvalPolicyId?: string;
@@ -246,7 +245,7 @@ export type TUpdateSignerDTO = {
signerId: string;
name?: string;
description?: string | null;
- renewBeforeDays?: number | null;
+ certificateRenewBeforeDays?: number | null;
};
export type TDeleteSignerDTO = {
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
index 92a20ca856..696267ccc2 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
@@ -130,7 +130,7 @@ export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateSt
)}
/>
<Controller
- name="renewBeforeDays"
+ name="certificateRenewBeforeDays"
control={form.control}
render={({ field, fieldState: { error } }) => (
<Field>
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
index a52f834393..9c9b27b100 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
@@ -105,7 +105,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
caId: state.caId,
commonName: state.commonName,
certificateTtlDays: state.certificateTtlDays,
- renewBeforeDays: state.renewBeforeDays,
+ certificateRenewBeforeDays: state.certificateRenewBeforeDays,
keyAlgorithm: state.keyAlgorithm
}
});
@@ -118,7 +118,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
caId: "",
commonName: "",
certificateTtlDays: 365,
- renewBeforeDays: null,
+ certificateRenewBeforeDays: null,
keyAlgorithm: SignerKeyAlgorithm.RSA_2048
});
};
@@ -155,7 +155,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
caId: state.caId,
commonName: state.commonName,
certificateTtlDays: state.certificateTtlDays,
- renewBeforeDays: state.renewBeforeDays,
+ certificateRenewBeforeDays: state.certificateRenewBeforeDays,
keyAlgorithm: state.keyAlgorithm,
members: state.pendingMembers.map((m) => ({
kind: m.kind,
@@ -194,7 +194,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
caId: values.caId,
commonName: values.commonName,
certificateTtlDays: values.certificateTtlDays,
- renewBeforeDays: values.renewBeforeDays,
+ certificateRenewBeforeDays: values.certificateRenewBeforeDays,
keyAlgorithm: values.keyAlgorithm
}));
setStep(2);
@@ -227,7 +227,9 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
(s) => s.approverUserIds.length + s.approverGroupIds.length === 0
);
const hasEmptyPolicyStep = firstEmptyPolicyStepIndex >= 0;
- const ctaDisabled = isLast && hasEmptyPolicyStep;
+ const missingConstraints =
+ state.policySteps.length > 0 && !state.maxSignings && !state.maxWindowDuration;
+ const ctaDisabled = isLast && (hasEmptyPolicyStep || missingConstraints);
return (
<Sheet open={isOpen} onOpenChange={handleClose}>
@@ -343,11 +345,14 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
<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
+ {hasEmptyPolicyStep
? `Step ${firstEmptyPolicyStepIndex + 1} needs at least one approver, or remove it.`
- : dirty
- ? "Unsaved changes"
- : ""}
+ : // eslint-disable-next-line no-nested-ternary
+ missingConstraints
+ ? "Set at least one of 'signatures per approval' or 'signing window'."
+ : dirty
+ ? "Unsaved changes"
+ : ""}
</span>
<div className="flex items-center gap-3">
<span className="text-xs text-muted">
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
index 1d4c3cf218..9f5b6b1785 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
@@ -14,7 +14,7 @@ export const certificateSchema = z
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
+ certificateRenewBeforeDays: z
.preprocess(
(v) => {
if (v === "" || v === null || v === undefined) return null;
@@ -34,10 +34,12 @@ export const certificateSchema = z
keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048)
})
.refine(
- (data) => data.renewBeforeDays == null || data.renewBeforeDays < data.certificateTtlDays,
+ (data) =>
+ data.certificateRenewBeforeDays == null ||
+ data.certificateRenewBeforeDays < data.certificateTtlDays,
{
message: "Renew before must be less than the certificate validity (days).",
- path: ["renewBeforeDays"]
+ path: ["certificateRenewBeforeDays"]
}
);
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.ts
index 2b45328a8c..4bf7bf16d5 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
@@ -39,7 +39,7 @@ export type WizardState = {
caId: string;
commonName: string;
certificateTtlDays: number;
- renewBeforeDays: number | null;
+ certificateRenewBeforeDays: number | null;
keyAlgorithm: SignerKeyAlgorithm;
pendingMembers: PendingMember[];
policySteps: PolicyStep[];
@@ -53,11 +53,11 @@ export const INITIAL_WIZARD_STATE: WizardState = {
caId: "",
commonName: "",
certificateTtlDays: 365,
- renewBeforeDays: null,
+ certificateRenewBeforeDays: null,
keyAlgorithm: SignerKeyAlgorithm.RSA_2048,
pendingMembers: [],
policySteps: [],
- maxSignings: 1,
+ maxSignings: null,
maxWindowDuration: null
};
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/SignersTable.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/SignersTable.tsx
index 720e1c83cf..9d92a3bece 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/SignersTable.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/SignersTable.tsx
@@ -1,7 +1,7 @@
import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { format } from "date-fns";
-import { PlusIcon, SearchIcon } from "lucide-react";
+import { AlertTriangleIcon, PlusIcon, SearchIcon } from "lucide-react";
import { ProjectPermissionCan } from "@app/components/permissions";
import {
@@ -30,7 +30,6 @@ import {
TableRow,
Tooltip,
TooltipContent,
- TooltipProvider,
TooltipTrigger
} from "@app/components/v3";
import {
@@ -138,22 +137,37 @@ export const SignersTable = ({ projectId, onCreateSigner }: Props) => {
}
>
<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>
+ <TableCell onClick={(e) => e.stopPropagation()} className="cursor-default">
+ {signer.certificateFailureReason &&
+ (signer.status === SignerStatus.Failed ||
+ signer.status === SignerStatus.Pending) ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex cursor-help items-center gap-1.5">
+ <Badge variant={getSignerStatusBadgeVariant(signer.status)}>
+ {signerStatusLabels[signer.status] ?? signer.status}
+ </Badge>
+ {signer.status === SignerStatus.Pending && (
+ <AlertTriangleIcon
+ className="size-3.5 shrink-0 text-warning"
+ aria-hidden
+ />
+ )}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ align="start"
+ className="max-w-[320px] text-pretty break-words"
+ >
+ {signer.status === SignerStatus.Pending && (
+ <span className="mb-0.5 block text-[10px] tracking-wide text-muted uppercase">
+ Last attempt failed, retrying
</span>
- </TooltipTrigger>
- <TooltipContent className="max-w-[260px] text-pretty break-words">
- {signer.failureReason}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
+ )}
+ {signer.certificateFailureReason}
+ </TooltipContent>
+ </Tooltip>
) : (
<Badge variant={getSignerStatusBadgeVariant(signer.status)}>
{signerStatusLabels[signer.status] ?? signer.status}
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx
index da98ae4b91..2635b69d20 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx
@@ -142,7 +142,7 @@ export const SignerDetailPage = () => {
<span className="inline-flex items-center gap-x-2 align-middle">
{signer.name}
<DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers.overview} />
- {signer.status === SignerStatus.Failed && signer.failureReason ? (
+ {signer.status === SignerStatus.Failed && signer.certificateFailureReason ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
@@ -153,7 +153,7 @@ export const SignerDetailPage = () => {
</span>
</TooltipTrigger>
<TooltipContent className="max-w-[260px] text-pretty break-words">
- {signer.failureReason}
+ {signer.certificateFailureReason}
</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -196,7 +196,7 @@ export const SignerDetailPage = () => {
{signer.status === SignerStatus.Active ? (
<DropdownMenuItem
onClick={() => disableSigner.mutate({ signerId: signer.id })}
- isDisabled={myPerms?.canEnableDisable === false}
+ isDisabled={myPerms?.canManageStatus === false}
>
<BanIcon />
Disable signer
@@ -204,7 +204,7 @@ export const SignerDetailPage = () => {
) : signer.status === SignerStatus.Disabled ? (
<DropdownMenuItem
onClick={() => enableSigner.mutate({ signerId: signer.id })}
- isDisabled={myPerms?.canEnableDisable === false}
+ isDisabled={myPerms?.canManageStatus === false}
>
<CheckCircleIcon />
Enable signer
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx
index 221fb0a669..f02eef8c48 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx
@@ -159,7 +159,7 @@ export const CertificateStep = ({
</Field>
<Controller
- name="renewBeforeDays"
+ name="certificateRenewBeforeDays"
control={form.control}
render={({ field, fieldState: { error } }) => (
<Field>
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx
index 85982bbffe..8192918174 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx
@@ -69,7 +69,7 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
resolver: zodResolver(certificateSchema),
values: {
caId: signer.caId ?? "",
- renewBeforeDays: signer.renewBeforeDays ?? null,
+ certificateRenewBeforeDays: signer.certificateRenewBeforeDays ?? null,
commonName: signer.commonName ?? "",
certificateTtlDays: signer.certificateTtlDays ?? 365
}
@@ -92,7 +92,7 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
basicsForm.reset({ name: signer.name, description: signer.description ?? "" });
certificateForm.reset({
caId: signer.caId ?? "",
- renewBeforeDays: signer.renewBeforeDays ?? null,
+ certificateRenewBeforeDays: signer.certificateRenewBeforeDays ?? null,
commonName: signer.commonName ?? "",
certificateTtlDays: signer.certificateTtlDays ?? 365
});
@@ -108,8 +108,8 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
const nameChanged = basics.name !== signer.name;
const descChanged = (basics.description || "") !== (signer.description ?? "");
- const currentRenew = signer.renewBeforeDays ?? null;
- const nextRenew = cert.renewBeforeDays ?? null;
+ const currentRenew = signer.certificateRenewBeforeDays ?? null;
+ const nextRenew = cert.certificateRenewBeforeDays ?? null;
const renewChanged = nextRenew !== currentRenew;
if (shouldReissue) {
@@ -126,7 +126,7 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
signerId: signer.id,
name: nameChanged ? basics.name : undefined,
description: descChanged ? basics.description || null : undefined,
- renewBeforeDays: renewChanged ? nextRenew : undefined
+ certificateRenewBeforeDays: renewChanged ? nextRenew : undefined
});
}
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts
index 17388ce079..4c5784c5b0 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts
@@ -11,7 +11,7 @@ export type BasicsForm = z.infer<typeof basicsSchema>;
export const certificateSchema = z
.object({
caId: z.string().uuid("Certificate Authority is required"),
- renewBeforeDays: z
+ certificateRenewBeforeDays: z
.preprocess(
(v) => {
if (v === "" || v === null || v === undefined) return null;
@@ -33,12 +33,12 @@ export const certificateSchema = z
})
.refine(
(data) =>
- data.renewBeforeDays == null ||
+ data.certificateRenewBeforeDays == null ||
data.certificateTtlDays == null ||
- data.renewBeforeDays < data.certificateTtlDays,
+ data.certificateRenewBeforeDays < data.certificateTtlDays,
{
message: "Renew before must be less than the certificate validity (days).",
- path: ["renewBeforeDays"]
+ path: ["certificateRenewBeforeDays"]
}
);
export type CertificateForm = z.infer<typeof certificateSchema>;
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/EditSignerPolicyModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/EditSignerPolicyModal.tsx
index d2b5beb4e1..bbc393d029 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/EditSignerPolicyModal.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/EditSignerPolicyModal.tsx
@@ -53,7 +53,7 @@ export const EditSignerPolicyModal = ({
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 [maxWindow, setMaxWindow] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const approverOptions = useMemo<ApproverOption[]>(() => {
@@ -100,10 +100,10 @@ export const EditSignerPolicyModal = ({
}))
);
setMaxSignings(existingPolicy.constraints.maxSignings ?? null);
- setMaxWindow(existingPolicy.constraints.maxWindowDuration ?? "24h");
+ setMaxWindow(existingPolicy.constraints.maxWindowDuration ?? null);
} else {
setSteps([]);
- setMaxSignings(1);
+ setMaxSignings(null);
setMaxWindow(null);
}
}, [isOpen, existingPolicy]);
@@ -139,6 +139,14 @@ export const EditSignerPolicyModal = ({
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 firstOverCommittedStepIndex = steps.findIndex((s) => {
+ if (s.approvers.length === 0) return false;
+ const userCount = s.approvers.filter((a) => a.kind === "user").length;
+ const groupCount = s.approvers.length - userCount;
+ return groupCount === 0 && s.requiredApprovals > userCount;
+ });
+ const hasOverCommittedStep = firstOverCommittedStepIndex >= 0;
+ const stepOneInvalid = hasEmptyStep || hasOverCommittedStep;
const WIZARD_STEPS = steps.length > 0 ? [APPROVERS_STEP, LIMITS_STEP] : [APPROVERS_STEP];
const safeStep = Math.min(step, WIZARD_STEPS.length - 1);
@@ -288,11 +296,15 @@ export const EditSignerPolicyModal = ({
{/* 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"
- }`}
+ : // eslint-disable-next-line no-nested-ternary
+ hasOverCommittedStep
+ ? `Step ${firstOverCommittedStepIndex + 1}: required approvals can't exceed the number of approvers. Add a group to allow more.`
+ : // eslint-disable-next-line no-nested-ternary
+ steps.length === 0
+ ? "Approval is not configured"
+ : `${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">
@@ -307,7 +319,7 @@ export const EditSignerPolicyModal = ({
<Button
variant="project"
onClick={() => setStep((s) => s + 1)}
- isDisabled={hasEmptyStep}
+ isDisabled={stepOneInvalid}
>
Continue
</Button>
@@ -316,7 +328,7 @@ export const EditSignerPolicyModal = ({
variant="project"
onClick={onSave}
isPending={submitting}
- isDisabled={hasEmptyStep}
+ isDisabled={stepOneInvalid}
>
Save policy
</Button>
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningModal.tsx
index 495523737e..b3983f01f8 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningModal.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningModal.tsx
@@ -1,6 +1,7 @@
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
+import ms from "ms";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
@@ -25,6 +26,7 @@ import {
import {
SignerMemberRole,
TEffectiveSignerMember,
+ useGetSignerPolicy,
useListEffectiveSignerMembers,
usePreApproveSigning
} from "@app/hooks/api/signers";
@@ -61,15 +63,29 @@ const schema = z
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);
+const HOURS_24_MS = 24 * 60 * 60 * 1000;
+const isoLocal = (epochMs: number) => new Date(epochMs).toISOString().slice(0, 16);
+
+const parseWindowMs = (s?: string | null): number | null => {
+ if (!s) return null;
+ try {
+ const n = ms(s);
+ return typeof n === "number" && n > 0 ? n : null;
+ } catch {
+ return null;
+ }
+};
export const PreApproveSigningModal = ({ isOpen, onOpenChange, signerId }: Props) => {
const users = useListEffectiveSignerMembers({ signerId, kind: "user" });
const identities = useListEffectiveSignerMembers({ signerId, kind: "identity" });
+ const { data: policy } = useGetSignerPolicy(signerId);
const preApprove = usePreApproveSigning();
const [submitting, setSubmitting] = useState(false);
+ const maxSignings = policy?.constraints?.maxSignings ?? null;
+ const maxWindowDuration = policy?.constraints?.maxWindowDuration ?? null;
+
const memberOptions: MemberOption[] = useMemo(() => {
const opts: MemberOption[] = [];
(users.data?.members ?? []).forEach((m: TEffectiveSignerMember) => {
@@ -93,19 +109,30 @@ export const PreApproveSigningModal = ({ isOpen, onOpenChange, signerId }: Props
return opts;
}, [users.data, identities.data]);
- const { control, handleSubmit, reset } = useForm<FormData>({
- resolver: zodResolver(schema),
- defaultValues: {
+ const buildDefaults = (): FormData => {
+ const now = Date.now();
+ const allowedMs = parseWindowMs(maxWindowDuration);
+ return {
granteeKey: "",
- requestedSignings: 3,
- requestedWindowStart: isoNow(),
- requestedWindowEnd: isoIn24h(),
+ requestedSignings: maxSignings ?? null,
+ requestedWindowStart: isoLocal(now),
+ requestedWindowEnd: isoLocal(now + (allowedMs ?? HOURS_24_MS)),
justification: ""
- }
+ };
+ };
+
+ const { control, handleSubmit, reset } = useForm<FormData>({
+ resolver: zodResolver(schema),
+ defaultValues: buildDefaults()
});
+ useEffect(() => {
+ if (!isOpen) reset(buildDefaults());
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [maxSignings, maxWindowDuration]);
+
const handleClose = (open: boolean) => {
- if (!open) reset();
+ if (!open) reset(buildDefaults());
onOpenChange(open);
};
@@ -181,15 +208,24 @@ export const PreApproveSigningModal = ({ isOpen, onOpenChange, signerId }: Props
<Input
type="number"
min={1}
+ max={maxSignings ?? undefined}
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"
+ placeholder={
+ maxSignings
+ ? `Up to ${maxSignings}`
+ : "Leave empty to rely on the time window"
+ }
isError={Boolean(error)}
/>
- <FieldDescription>Leave empty to rely on the time window.</FieldDescription>
+ <FieldDescription>
+ {maxSignings
+ ? `Policy caps each approval at ${maxSignings} signature${maxSignings === 1 ? "" : "s"}.`
+ : "Leave empty to rely on the time window."}
+ </FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
</Field>
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignModal.tsx
index 5ea5454d89..54c716ad2c 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignModal.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignModal.tsx
@@ -1,6 +1,7 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
+import ms from "ms";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
@@ -21,7 +22,7 @@ import {
Input,
TextArea
} from "@app/components/v3";
-import { useRequestToSign } from "@app/hooks/api/signers";
+import { useGetSignerPolicy, useRequestToSign } from "@app/hooks/api/signers";
type Props = {
isOpen: boolean;
@@ -52,25 +53,50 @@ const schema = z
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);
+const HOURS_24_MS = 24 * 60 * 60 * 1000;
+const isoLocal = (epochMs: number) => new Date(epochMs).toISOString().slice(0, 16);
+
+const parseWindowMs = (s?: string | null): number | null => {
+ if (!s) return null;
+ try {
+ const n = ms(s);
+ return typeof n === "number" && n > 0 ? n : null;
+ } catch {
+ return null;
+ }
+};
export const RequestToSignModal = ({ isOpen, onOpenChange, signerId }: Props) => {
const requestToSign = useRequestToSign();
+ const { data: policy } = useGetSignerPolicy(signerId);
const [submitting, setSubmitting] = useState(false);
+ const maxSignings = policy?.constraints?.maxSignings ?? null;
+ const maxWindowDuration = policy?.constraints?.maxWindowDuration ?? null;
+
+ const buildDefaults = (): FormData => {
+ const now = Date.now();
+ const allowedMs = parseWindowMs(maxWindowDuration);
+ return {
+ requestedSignings: maxSignings ?? null,
+ requestedWindowStart: isoLocal(now),
+ requestedWindowEnd: isoLocal(now + (allowedMs ?? HOURS_24_MS)),
+ justification: ""
+ };
+ };
+
const { control, handleSubmit, reset } = useForm<FormData>({
resolver: zodResolver(schema),
- defaultValues: {
- requestedSignings: 3,
- requestedWindowStart: isoNow(),
- requestedWindowEnd: isoIn24h(),
- justification: ""
- }
+ defaultValues: buildDefaults()
});
+ useEffect(() => {
+ if (!isOpen) reset(buildDefaults());
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [maxSignings, maxWindowDuration]);
+
const handleClose = (open: boolean) => {
- if (!open) reset();
+ if (!open) reset(buildDefaults());
onOpenChange(open);
};
@@ -121,16 +147,23 @@ export const RequestToSignModal = ({ isOpen, onOpenChange, signerId }: Props) =>
<Input
type="number"
min={1}
+ max={maxSignings ?? undefined}
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"
+ placeholder={
+ maxSignings
+ ? `Up to ${maxSignings}`
+ : "Leave empty to rely on the time window"
+ }
isError={Boolean(error)}
/>
<FieldDescription>
- Leave empty to rely on the time window instead.
+ {maxSignings
+ ? `Policy caps each approval at ${maxSignings} signature${maxSignings === 1 ? "" : "s"}.`
+ : "Leave empty to rely on the time window instead."}
</FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx
index 327cbc9d7d..37c3e389dc 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx
@@ -169,7 +169,7 @@ export const SignerApprovalPolicyTab = ({ signerId }: Props) => {
<p className="mt-1 text-sm text-accent">
{hasSteps
? "Control when approval is required before signing."
- : "Approval is off. Members can sign directly."}
+ : "Approval is not configured. Members can sign directly."}
</p>
</div>
<Tooltip>
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerMembersTab.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerMembersTab.tsx
index 7625036c32..db827a9e36 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerMembersTab.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerMembersTab.tsx
@@ -2,6 +2,14 @@ import { useMemo, useState } from "react";
import { MoreHorizontalIcon, Trash2Icon, UserPlusIcon } from "lucide-react";
import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
Badge,
Button,
Card,
@@ -88,6 +96,9 @@ export const SignerMembersTab = ({ signerId }: Props) => {
const updateGroupRole = useUpdateSignerGroupRole();
const removeGroupMember = useRemoveSignerGroupMember();
const [isAddOpen, setIsAddOpen] = useState(false);
+ const [memberToRemove, setMemberToRemove] = useState<TSignerMember | null>(null);
+ const isRemoving =
+ removeUserMember.isPending || removeIdentityMember.isPending || removeGroupMember.isPending;
const all: TSignerMember[] = useMemo(
() => [
@@ -113,14 +124,21 @@ export const SignerMembersTab = ({ signerId }: Props) => {
}
};
- const handleRemove = (m: TSignerMember) => {
+ const confirmRemove = async () => {
+ const m = memberToRemove;
+ if (!m) return;
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 });
+ try {
+ if (kind === "user" && m.actorUserId) {
+ await removeUserMember.mutateAsync({ signerId, userId: m.actorUserId });
+ } else if (kind === "identity" && m.actorIdentityId) {
+ await removeIdentityMember.mutateAsync({ signerId, identityId: m.actorIdentityId });
+ } else if (kind === "group" && m.actorGroupId) {
+ await removeGroupMember.mutateAsync({ signerId, groupId: m.actorGroupId });
+ }
+ setMemberToRemove(null);
+ } catch {
+ // mutation onError surfaces the notification
}
};
@@ -213,7 +231,7 @@ export const SignerMembersTab = ({ signerId }: Props) => {
<DropdownMenuItem
variant="danger"
isDisabled={!canManageMembers}
- onClick={() => handleRemove(m)}
+ onClick={() => setMemberToRemove(m)}
>
<Trash2Icon />
Remove Member
@@ -236,6 +254,30 @@ export const SignerMembersTab = ({ signerId }: Props) => {
signerId={signerId}
existingMembers={all}
/>
+
+ <AlertDialog
+ open={memberToRemove !== null}
+ onOpenChange={(open) => {
+ if (!open && !isRemoving) setMemberToRemove(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Remove this member?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {memberToRemove
+ ? `${labelOf(memberToRemove)} will lose all access to this signer.`
+ : ""}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel isDisabled={isRemoving}>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="danger" isDisabled={isRemoving} onClick={confirmRemove}>
+ Remove member
+ </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.tsx
index 0e5a69b9af..0872e1f889 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/SignerRequestsTab.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/SignerRequestsTab.tsx
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState } from "react";
import { format } from "date-fns";
-import { FilterIcon, XIcon } from "lucide-react";
+import { FilterIcon, MessageSquareTextIcon, XIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
import {
@@ -252,16 +252,28 @@ export const SignerRequestsTab = ({ signerId, canPreApprove, canRequestSign }: P
<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">
+ <div className="mt-0.5 max-w-full text-xs text-muted">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span
+ className="inline-flex max-w-full items-center gap-1 align-middle"
+ aria-label={`Reason: ${req.justification}`}
+ >
+ <MessageSquareTextIcon
+ className="size-3 shrink-0"
+ aria-hidden
+ />
+ <span className="truncate">{req.justification}</span>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md break-words whitespace-pre-wrap">
+ <span className="block text-[10px] tracking-wide text-muted uppercase">
+ Reason
+ </span>
{req.justification}
- </div>
- </TooltipTrigger>
- <TooltipContent className="max-w-md break-words whitespace-pre-wrap">
- {req.justification}
- </TooltipContent>
- </Tooltip>
+ </TooltipContent>
+ </Tooltip>
+ </div>
)}
</div>
</div>