Skip to content

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

Address PR comments

Carlos Monastyrski194e5b548607
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index 8b8eefab35..7a50ee9c06 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -241,7 +241,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
locality: attributes?.locality ?? undefined
};
- const data = await server.services.certificateV3.orderCertificateFromProfile({
+ const data = await server.services.certificateV3.orderCertificate({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -1110,7 +1110,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
keyAlgorithm: req.body.keyAlgorithm
};
- const data = await server.services.certificateV3.orderCertificateFromProfile({
+ const data = await server.services.certificateV3.orderCertificate({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
diff --git a/backend/src/server/routes/v1/hsm-connector-router-schemas.ts b/backend/src/server/routes/v1/hsm-connector-router-schemas.ts
index bf9d445fc1..051731faf6 100644
--- a/backend/src/server/routes/v1/hsm-connector-router-schemas.ts
+++ b/backend/src/server/routes/v1/hsm-connector-router-schemas.ts
@@ -3,7 +3,7 @@ import { z } from "zod";
import { slugSchema } from "@app/server/lib/schemas";
import {
HsmConnectorCredentialsSchema,
- HsmConnectorSanitizedSchema as SharedHsmConnectorSanitizedSchema
+ HsmConnectorSanitizedSchema
} from "@app/services/hsm-connector/hsm-connector-fns";
const HSM_CONNECTOR_NAME_MAX = 32;
@@ -18,8 +18,6 @@ export const gatewayPickRefiner = (data: { gatewayId?: string | null; gatewayPoo
return hasGatewayId !== hasPool;
};
-export const HsmConnectorSanitizedSchema = SharedHsmConnectorSanitizedSchema;
-
export const HsmConnectorTestResultSchema = z.object({
ok: z.boolean(),
members: z
@@ -47,7 +45,6 @@ export const HsmConnectorTestResultSchema = z.object({
export const CreateHsmConnectorBodySchema = z
.object({
- projectId: z.string().uuid(),
name: slugSchema({ min: 1, max: HSM_CONNECTOR_NAME_MAX, field: "name" }),
description: z.string().max(HSM_CONNECTOR_DESCRIPTION_MAX).optional(),
gatewayId: z.string().uuid().optional(),
@@ -56,10 +53,6 @@ export const CreateHsmConnectorBodySchema = z
})
.refine(gatewayPickRefiner, { message: GATEWAY_PICK_MESSAGE, path: ["gatewayId"] });
-export const ListHsmConnectorsQuerySchema = z.object({
- projectId: z.string().uuid()
-});
-
export const UpdateHsmConnectorBodySchema = z
.object({
name: slugSchema({ min: 1, max: HSM_CONNECTOR_NAME_MAX, field: "name" }).optional(),
diff --git a/backend/src/server/routes/v1/hsm-connector-router.ts b/backend/src/server/routes/v1/hsm-connector-router.ts
index 62c7affd17..958e44c048 100644
--- a/backend/src/server/routes/v1/hsm-connector-router.ts
+++ b/backend/src/server/routes/v1/hsm-connector-router.ts
@@ -1,3 +1,4 @@
+import { FastifyRequest } from "fastify";
import { z } from "zod";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
@@ -5,229 +6,237 @@ 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 { HsmConnectorSanitizedSchema } from "@app/services/hsm-connector/hsm-connector-fns";
import {
CreateHsmConnectorBodySchema,
HsmConnectorIdParamSchema,
HsmConnectorLinkedResourcesQuerySchema,
HsmConnectorLinkedResourcesResponseSchema,
- HsmConnectorSanitizedSchema,
HsmConnectorTestResultSchema,
- ListHsmConnectorsQuerySchema,
UpdateHsmConnectorBodySchema
} from "./hsm-connector-router-schemas";
-export const registerHsmConnectorRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "POST",
- url: "/",
- config: { rateLimit: writeLimit },
- schema: {
- hide: false,
- operationId: "createHsmConnector",
- tags: [ApiDocsTags.HsmConnectors],
- body: CreateHsmConnectorBodySchema,
- response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const hsmConnector = await server.services.hsmConnector.createHsmConnector(
- {
- projectId: req.body.projectId,
- name: req.body.name,
- description: req.body.description,
- gatewayId: req.body.gatewayId,
- gatewayPoolId: req.body.gatewayPoolId,
- credentials: req.body.credentials
- },
- req.permission
- );
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- projectId: hsmConnector.projectId,
- event: {
- type: EventType.CREATE_HSM_CONNECTOR,
- metadata: {
- connectorId: hsmConnector.id,
- name: hsmConnector.name,
- gatewayId: hsmConnector.gatewayId,
- gatewayPoolId: hsmConnector.gatewayPoolId
+type HsmConnectorRouterOptions = {
+ resolveProjectId: (req: FastifyRequest) => string;
+};
+
+export const createHsmConnectorRouter =
+ ({ resolveProjectId }: HsmConnectorRouterOptions) =>
+ async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "createHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ body: CreateHsmConnectorBodySchema,
+ response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const hsmConnector = await server.services.hsmConnector.createHsmConnector(
+ {
+ projectId: resolveProjectId(req),
+ name: req.body.name,
+ description: req.body.description,
+ gatewayId: req.body.gatewayId,
+ gatewayPoolId: req.body.gatewayPoolId,
+ credentials: req.body.credentials
+ },
+ req.permission
+ );
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: hsmConnector.projectId,
+ event: {
+ type: EventType.CREATE_HSM_CONNECTOR,
+ metadata: {
+ connectorId: hsmConnector.id,
+ name: hsmConnector.name,
+ gatewayId: hsmConnector.gatewayId,
+ gatewayPoolId: hsmConnector.gatewayPoolId
+ }
}
- }
- });
- return { hsmConnector };
- }
- });
+ });
+ return { hsmConnector };
+ }
+ });
- server.route({
- method: "GET",
- url: "/",
- config: { rateLimit: readLimit },
- schema: {
- hide: false,
- operationId: "listHsmConnectors",
- tags: [ApiDocsTags.HsmConnectors],
- querystring: ListHsmConnectorsQuerySchema,
- response: { 200: z.object({ hsmConnectors: HsmConnectorSanitizedSchema.array() }) }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const hsmConnectors = await server.services.hsmConnector.listHsmConnectors(
- { projectId: req.query.projectId },
- req.permission
- );
- return { hsmConnectors };
- }
- });
+ server.route({
+ method: "GET",
+ url: "/",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listHsmConnectors",
+ tags: [ApiDocsTags.HsmConnectors],
+ response: { 200: z.object({ hsmConnectors: HsmConnectorSanitizedSchema.array() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const hsmConnectors = await server.services.hsmConnector.listHsmConnectors(
+ { projectId: resolveProjectId(req) },
+ req.permission
+ );
+ return { hsmConnectors };
+ }
+ });
- server.route({
- method: "GET",
- url: "/:connectorId",
- config: { rateLimit: readLimit },
- schema: {
- hide: false,
- operationId: "getHsmConnector",
- tags: [ApiDocsTags.HsmConnectors],
- params: HsmConnectorIdParamSchema,
- response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const hsmConnector = await server.services.hsmConnector.getHsmConnectorById(
- { connectorId: req.params.connectorId },
- req.permission
- );
- return { hsmConnector };
- }
- });
+ server.route({
+ method: "GET",
+ url: "/:connectorId",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: HsmConnectorIdParamSchema,
+ response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const hsmConnector = await server.services.hsmConnector.getHsmConnectorById(
+ { connectorId: req.params.connectorId },
+ req.permission
+ );
+ return { hsmConnector };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:connectorId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "updateHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: HsmConnectorIdParamSchema,
+ body: UpdateHsmConnectorBodySchema,
+ response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const hsmConnector = await server.services.hsmConnector.updateHsmConnector(
+ {
+ connectorId: req.params.connectorId,
+ name: req.body.name,
+ description: req.body.description,
+ gatewayId: req.body.gatewayId ?? undefined,
+ gatewayPoolId: req.body.gatewayPoolId ?? undefined,
+ credentials: req.body.credentials
+ },
+ req.permission
+ );
+ const fieldsUpdated = Object.keys(req.body).filter((k) => req.body[k as keyof typeof req.body] !== undefined);
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: hsmConnector.projectId,
+ event: {
+ type: EventType.UPDATE_HSM_CONNECTOR,
+ metadata: {
+ connectorId: hsmConnector.id,
+ name: hsmConnector.name,
+ fieldsUpdated
+ }
+ }
+ });
+ return { hsmConnector };
+ }
+ });
- server.route({
- method: "PATCH",
- url: "/:connectorId",
- config: { rateLimit: writeLimit },
- schema: {
- hide: false,
- operationId: "updateHsmConnector",
- tags: [ApiDocsTags.HsmConnectors],
- params: HsmConnectorIdParamSchema,
- body: UpdateHsmConnectorBodySchema,
- response: { 200: z.object({ hsmConnector: HsmConnectorSanitizedSchema }) }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const hsmConnector = await server.services.hsmConnector.updateHsmConnector(
- {
- connectorId: req.params.connectorId,
- name: req.body.name,
- description: req.body.description,
- gatewayId: req.body.gatewayId ?? undefined,
- gatewayPoolId: req.body.gatewayPoolId ?? undefined,
- credentials: req.body.credentials
- },
- req.permission
- );
- const fieldsUpdated = Object.keys(req.body).filter((k) => req.body[k as keyof typeof req.body] !== undefined);
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- projectId: hsmConnector.projectId,
- event: {
- type: EventType.UPDATE_HSM_CONNECTOR,
- metadata: {
- connectorId: hsmConnector.id,
- name: hsmConnector.name,
- fieldsUpdated
+ server.route({
+ method: "DELETE",
+ url: "/:connectorId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "deleteHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: HsmConnectorIdParamSchema,
+ response: { 200: z.object({ id: z.string().uuid() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const deleted = await server.services.hsmConnector.deleteHsmConnector(
+ { connectorId: req.params.connectorId },
+ req.permission
+ );
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: deleted.projectId,
+ event: {
+ type: EventType.DELETE_HSM_CONNECTOR,
+ metadata: { connectorId: deleted.id, name: deleted.name }
}
- }
- });
- return { hsmConnector };
- }
- });
+ });
+ return { id: deleted.id };
+ }
+ });
- server.route({
- method: "DELETE",
- url: "/:connectorId",
- config: { rateLimit: writeLimit },
- schema: {
- hide: false,
- operationId: "deleteHsmConnector",
- tags: [ApiDocsTags.HsmConnectors],
- params: HsmConnectorIdParamSchema,
- response: { 200: z.object({ id: z.string().uuid() }) }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const deleted = await server.services.hsmConnector.deleteHsmConnector(
- { connectorId: req.params.connectorId },
- req.permission
- );
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- projectId: deleted.projectId,
- event: {
- type: EventType.DELETE_HSM_CONNECTOR,
- metadata: { connectorId: deleted.id, name: deleted.name }
- }
- });
- return { id: deleted.id };
- }
- });
+ server.route({
+ method: "POST",
+ url: "/:connectorId/test",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "testHsmConnector",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: HsmConnectorIdParamSchema,
+ response: { 200: HsmConnectorTestResultSchema }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { projectId, name, result } = await server.services.hsmConnector.testHsmConnector(
+ { connectorId: req.params.connectorId },
+ req.permission
+ );
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId,
+ event: {
+ type: EventType.TEST_HSM_CONNECTOR,
+ metadata: {
+ connectorId: req.params.connectorId,
+ name,
+ ok: result.ok,
+ memberCount: result.members.length
+ }
+ }
+ });
+ return result;
+ }
+ });
- server.route({
- method: "POST",
- url: "/:connectorId/test",
- config: { rateLimit: writeLimit },
- schema: {
- hide: false,
- operationId: "testHsmConnector",
- tags: [ApiDocsTags.HsmConnectors],
- params: HsmConnectorIdParamSchema,
- response: { 200: HsmConnectorTestResultSchema }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { projectId, name, result } = await server.services.hsmConnector.testHsmConnector(
- { connectorId: req.params.connectorId },
- req.permission
- );
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- projectId,
- event: {
- type: EventType.TEST_HSM_CONNECTOR,
- metadata: {
+ server.route({
+ method: "GET",
+ url: "/:connectorId/linked-resources",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listHsmConnectorLinkedResources",
+ tags: [ApiDocsTags.HsmConnectors],
+ params: HsmConnectorIdParamSchema,
+ querystring: HsmConnectorLinkedResourcesQuerySchema,
+ response: { 200: HsmConnectorLinkedResourcesResponseSchema }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.hsmConnector.listLinkedResources(
+ {
connectorId: req.params.connectorId,
- name,
- ok: result.ok,
- memberCount: result.members.length
- }
- }
- });
- return result;
- }
- });
+ offset: req.query.offset,
+ limit: req.query.limit
+ },
+ req.permission
+ );
+ }
+ });
+ };
- server.route({
- method: "GET",
- url: "/:connectorId/linked-resources",
- config: { rateLimit: readLimit },
- schema: {
- hide: false,
- operationId: "listHsmConnectorLinkedResources",
- tags: [ApiDocsTags.HsmConnectors],
- params: HsmConnectorIdParamSchema,
- querystring: HsmConnectorLinkedResourcesQuerySchema,
- response: { 200: HsmConnectorLinkedResourcesResponseSchema }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- return server.services.hsmConnector.listLinkedResources(
- {
- connectorId: req.params.connectorId,
- offset: req.query.offset,
- limit: req.query.limit
- },
- req.permission
- );
- }
- });
-};
+export const registerCertManagerHsmConnectorRouter = createHsmConnectorRouter({
+ resolveProjectId: (req) => req.internalCertManagerProjectId
+});
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index daa09cef58..67b31730e5 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -42,7 +42,7 @@ import { registerExternalGroupOrgRoleMappingRouter } from "./external-group-org-
import { registerGitHubAppRouter } from "./github-app-router";
import { registerGroupOrgMembershipRouter } from "./group-org-membership-router";
import { registerGroupProjectRouter } from "./group-project-router";
-import { registerHsmConnectorRouter } from "./hsm-connector-router";
+import { registerCertManagerHsmConnectorRouter } from "./hsm-connector-router";
import { registerIdentityAccessTokenRouter } from "./identity-access-token-router";
import { registerIdentityAliCloudAuthRouter } from "./identity-alicloud-auth-router";
import { registerIdentityAwsAuthRouter } from "./identity-aws-iam-auth-router";
@@ -187,12 +187,12 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
{ prefix: "/projects/:projectId/memberships" }
);
- await server.register(registerHsmConnectorRouter, { prefix: "/hsm-connectors" });
-
await server.register(
async (pkiRouter) => {
await pkiRouter.register(injectCertManagerProjectId);
+ await pkiRouter.register(registerCertManagerHsmConnectorRouter, { prefix: "/hsm-connectors" });
+
await pkiRouter.register(
async (caRouter) => {
for await (const [caType, router] of Object.entries(CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP)) {
diff --git a/backend/src/server/routes/v1/signer-routers/certificate-router.ts b/backend/src/server/routes/v1/signer-routers/certificate-router.ts
index dcadf33afe..7f6aea752c 100644
--- a/backend/src/server/routes/v1/signer-routers/certificate-router.ts
+++ b/backend/src/server/routes/v1/signer-routers/certificate-router.ts
@@ -6,9 +6,9 @@ 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 { CertKeySource, HsmKeyAlgorithm } from "@app/services/signer/signer-enums";
+import { CertKeySource } from "@app/services/signer/signer-enums";
-import { SignerIdParamsSchema, SignerKeyAlgorithm } from "./schemas";
+import { HSM_SUPPORTED_KEY_ALGORITHMS, SignerIdParamsSchema, SignerKeyAlgorithm } from "./schemas";
export const registerSignerCertificateRouter = async (server: FastifyZodProvider) => {
server.route({
@@ -21,24 +21,36 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProvider
tags: [ApiDocsTags.PkiSigners],
description: "Re-issue the signer's certificate (optionally from a different CA or with a different key source)",
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(),
- keyAlgorithm: SignerKeyAlgorithm.schema.optional(),
- certificate: z
- .object({
- keySource: z.nativeEnum(CertKeySource),
- hsmConnectorId: z.string().uuid().optional(),
- hsmKeyAlgorithm: z.nativeEnum(HsmKeyAlgorithm).optional()
- })
- .refine(
- (data) =>
- data.keySource !== CertKeySource.Hsm || (Boolean(data.hsmConnectorId) && Boolean(data.hsmKeyAlgorithm)),
- { message: `hsmConnectorId and hsmKeyAlgorithm are required when keySource = '${CertKeySource.Hsm}'` }
- )
- .optional()
- }),
+ 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(),
+ keyAlgorithm: SignerKeyAlgorithm.schema.optional(),
+ certificate: z
+ .object({
+ keySource: z.nativeEnum(CertKeySource),
+ hsmConnectorId: z.string().uuid().optional()
+ })
+ .optional()
+ })
+ .superRefine((data, ctx) => {
+ if (data.certificate?.keySource !== CertKeySource.Hsm) return;
+ if (!data.certificate.hsmConnectorId) {
+ ctx.addIssue({
+ code: "custom",
+ message: `hsmConnectorId is required when keySource = '${CertKeySource.Hsm}'`,
+ path: ["certificate", "hsmConnectorId"]
+ });
+ }
+ if (!data.keyAlgorithm || !HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm)) {
+ ctx.addIssue({
+ code: "custom",
+ message: `keyAlgorithm must be one of ${HSM_SUPPORTED_KEY_ALGORITHMS.join(", ")} when keySource = '${CertKeySource.Hsm}'`,
+ path: ["keyAlgorithm"]
+ });
+ }
+ }),
response: { 200: PkiSignersSchema }
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
@@ -64,8 +76,7 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProvider
commonName: req.body.commonName,
keyAlgorithm: req.body.keyAlgorithm,
keySource: req.body.certificate?.keySource,
- hsmConnectorId: req.body.certificate?.hsmConnectorId,
- hsmKeyAlgorithm: req.body.certificate?.hsmKeyAlgorithm
+ hsmConnectorId: req.body.certificate?.hsmConnectorId
}
}
});
diff --git a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts
index d50a76ff6c..d730e156d9 100644
--- a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts
+++ b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts
@@ -8,10 +8,15 @@ 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 { CertKeySource, HsmKeyAlgorithm } from "@app/services/signer/signer-enums";
+import { CertKeySource } from "@app/services/signer/signer-enums";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
-import { ApprovalPolicyBodySchema, SignerIdParamsSchema, SignerKeyAlgorithm } from "./schemas";
+import {
+ ApprovalPolicyBodySchema,
+ HSM_SUPPORTED_KEY_ALGORITHMS,
+ SignerIdParamsSchema,
+ SignerKeyAlgorithm
+} from "./schemas";
export const registerSignerLifecycleRouter = async (server: FastifyZodProvider) => {
server.route({
@@ -23,40 +28,52 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)
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(),
- certificate: z
- .object({
- keySource: z.nativeEnum(CertKeySource).optional().default(CertKeySource.Infisical),
- hsmConnectorId: z.string().uuid().optional(),
- hsmKeyAlgorithm: z.nativeEnum(HsmKeyAlgorithm).optional()
- })
- .refine(
- (data) =>
- data.keySource !== CertKeySource.Hsm || (Boolean(data.hsmConnectorId) && Boolean(data.hsmKeyAlgorithm)),
- { message: `hsmConnectorId and hsmKeyAlgorithm are required when keySource = '${CertKeySource.Hsm}'` }
- )
- .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)
+ 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(),
+ certificate: z
+ .object({
+ keySource: z.nativeEnum(CertKeySource).optional().default(CertKeySource.Infisical),
+ hsmConnectorId: z.string().uuid().optional()
})
- )
- .optional(),
- approvalPolicy: ApprovalPolicyBodySchema.optional()
- }),
+ .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()
+ })
+ .superRefine((data, ctx) => {
+ if (data.certificate?.keySource !== CertKeySource.Hsm) return;
+ if (!data.certificate.hsmConnectorId) {
+ ctx.addIssue({
+ code: "custom",
+ message: `hsmConnectorId is required when keySource = '${CertKeySource.Hsm}'`,
+ path: ["certificate", "hsmConnectorId"]
+ });
+ }
+ if (!data.keyAlgorithm || !HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm)) {
+ ctx.addIssue({
+ code: "custom",
+ message: `keyAlgorithm must be one of ${HSM_SUPPORTED_KEY_ALGORITHMS.join(", ")} when keySource = '${CertKeySource.Hsm}'`,
+ path: ["keyAlgorithm"]
+ });
+ }
+ }),
response: {
200: PkiSignersSchema
}
@@ -176,6 +193,8 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)
certificateNotAfter: z.date().nullable().optional(),
certificateNotBefore: z.date().nullable().optional(),
certificateKeyAlgorithm: z.string().nullable().optional(),
+ certificateKeySource: z.string().nullable().optional(),
+ certificateHsmConnectorId: z.string().nullable().optional(),
certificateStatus: z.string().nullable().optional(),
certificateCaId: z.string().nullable().optional(),
approvalPolicyName: z.string().nullable().optional()
diff --git a/backend/src/server/routes/v1/signer-routers/schemas.ts b/backend/src/server/routes/v1/signer-routers/schemas.ts
index 8c69d92cda..cb26a3deb8 100644
--- a/backend/src/server/routes/v1/signer-routers/schemas.ts
+++ b/backend/src/server/routes/v1/signer-routers/schemas.ts
@@ -18,6 +18,13 @@ export const SignerKeyAlgorithm = {
}
} as const;
+export const HSM_SUPPORTED_KEY_ALGORITHMS: readonly CertKeyAlgorithm[] = [
+ CertKeyAlgorithm.RSA_2048,
+ CertKeyAlgorithm.RSA_4096,
+ CertKeyAlgorithm.ECDSA_P256,
+ CertKeyAlgorithm.ECDSA_P384
+];
+
export const ApprovalPolicyBodySchema = z
.object({
steps: z.array(
diff --git a/backend/src/server/routes/v3/deprecated-certificates-router.ts b/backend/src/server/routes/v3/deprecated-certificates-router.ts
index fdbf963d13..d10966f95a 100644
--- a/backend/src/server/routes/v3/deprecated-certificates-router.ts
+++ b/backend/src/server/routes/v3/deprecated-certificates-router.ts
@@ -387,7 +387,7 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) =>
keyAlgorithm: req.body.keyAlgorithm
};
- const data = await server.services.certificateV3.orderCertificateFromProfile({
+ const data = await server.services.certificateV3.orderCertificate({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
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 4c0d658215..df8a46f60e 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
@@ -286,7 +286,7 @@ const getAcmeChallengeRecord = async (
return { recordName, recordValue };
};
-export const orderCertificate = async (
+export const executeAcmeOrder = async (
{
caId,
profileId,
@@ -332,7 +332,7 @@ export const orderCertificate = async (
try {
await onProgress(message);
} catch (err) {
- logger.warn(err, `ACME orderCertificate onProgress callback failed [caId=${caId}]`);
+ logger.warn(err, `ACME executeAcmeOrder onProgress callback failed [caId=${caId}]`);
}
};
const {
@@ -932,7 +932,7 @@ export const AcmeCertificateAuthorityFns = ({
skLeaf
);
- await orderCertificate(
+ await executeAcmeOrder(
{
caId: subscriber.caId,
subscriberId: subscriber.id,
@@ -957,7 +957,7 @@ export const AcmeCertificateAuthorityFns = ({
await triggerAutoSyncForSubscriber(subscriber.id, { pkiSyncDAL, pkiSyncQueue });
};
- const orderCertificateFromProfile = async ({
+ const orderCertificate = async ({
caId,
profileId,
commonName,
@@ -992,7 +992,7 @@ export const AcmeCertificateAuthorityFns = ({
isCancelled?: () => Promise<boolean>;
abortSignal?: AbortSignal;
}) => {
- return orderCertificate(
+ return executeAcmeOrder(
{
caId,
profileId,
@@ -1031,6 +1031,6 @@ export const AcmeCertificateAuthorityFns = ({
updateCertificateAuthority,
listCertificateAuthorities,
orderSubscriberCertificate,
- orderCertificateFromProfile
+ orderCertificate
};
};
diff --git a/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts b/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts
index eae657fb68..dd041db9a4 100644
--- a/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts
@@ -385,7 +385,7 @@ export const AwsAcmPublicCaCertificateAuthorityFns = ({
* completes, in a single DB transaction. If DNS validation is still pending, this
* function throws AcmPendingError and the queue retries.
*/
- const orderCertificateFromProfile = async ({
+ const orderCertificate = async ({
caId,
profileId,
commonName,
@@ -863,7 +863,7 @@ export const AwsAcmPublicCaCertificateAuthorityFns = ({
createCertificateAuthority,
updateCertificateAuthority,
listCertificateAuthorities,
- orderCertificateFromProfile,
+ orderCertificate,
revokeCertificate
};
};
diff --git a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts
index e0b9ab7239..3e677db112 100644
--- a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts
@@ -514,7 +514,7 @@ export const AwsPcaCertificateAuthorityFns = ({
return cas.map(castDbEntryToAwsPcaCertificateAuthority);
};
- const orderCertificateFromProfile = async ({
+ const orderCertificate = async ({
caId,
profileId,
commonName,
@@ -848,34 +848,11 @@ export const AwsPcaCertificateAuthorityFns = ({
logger.info(revokeResult, "AWS PCA RevokeCertificate result");
};
- const orderCertificateForSigner = (args: {
- caId: string;
- commonName: string;
- altNames?: Array<{ type: CertSubjectAlternativeNameType; value: string }>;
- keyUsages?: CertKeyUsage[];
- extendedKeyUsages?: CertExtendedKeyUsage[];
- validity: { ttl: string };
- notBefore?: Date;
- notAfter?: Date;
- signatureAlgorithm?: string;
- keyAlgorithm?: CertKeyAlgorithm;
- isRenewal?: boolean;
- originalCertificateId?: string;
- csr?: string;
- organization?: string;
- organizationalUnit?: string;
- country?: string;
- state?: string;
- locality?: string;
- isCancelled?: () => Promise<boolean>;
- }) => orderCertificateFromProfile(args);
-
return {
createCertificateAuthority,
updateCertificateAuthority,
listCertificateAuthorities,
- orderCertificateFromProfile,
- orderCertificateForSigner,
+ orderCertificate,
revokeCertificate
};
};
diff --git a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts
index de878f7596..a26c7e15c0 100644
--- a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts
@@ -1094,7 +1094,7 @@ export const AzureAdCsCertificateAuthorityFns = ({
};
};
- const orderCertificateFromProfile = async ({
+ const orderCertificate = async ({
caId,
profileId,
commonName,
@@ -1612,30 +1612,12 @@ export const AzureAdCsCertificateAuthorityFns = ({
}
};
- const orderCertificateForSigner = (args: {
- caId: string;
- commonName: string;
- altNames?: string[];
- keyUsages?: CertKeyUsage[];
- extendedKeyUsages?: CertExtendedKeyUsage[];
- template?: string;
- validity: { ttl: string };
- notBefore?: Date;
- notAfter?: Date;
- signatureAlgorithm?: string;
- keyAlgorithm?: CertKeyAlgorithm;
- isRenewal?: boolean;
- originalCertificateId?: string;
- isCancelled?: () => Promise<boolean>;
- }) => orderCertificateFromProfile(args);
-
return {
createCertificateAuthority,
updateCertificateAuthority,
listCertificateAuthorities,
orderSubscriberCertificate,
- orderCertificateFromProfile,
- orderCertificateForSigner,
+ orderCertificate,
getTemplates
};
};
diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
index 15cd546535..45f984bd79 100644
--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts
@@ -459,7 +459,7 @@ export const certificateIssuanceQueueFactory = ({
acmeResult = await runWithAcmeCancellation(signal, () =>
runWithAcmeOrderTimeout(
(timeoutSignal) =>
- acmeFns.orderCertificateFromProfile({
+ acmeFns.orderCertificate({
caId,
profileId,
commonName: commonName || "",
@@ -573,8 +573,8 @@ export const certificateIssuanceQueueFactory = ({
return;
}
- const azureResult = await azureAdCsFns.orderCertificateFromProfile(
- azureParams as Parameters<typeof azureAdCsFns.orderCertificateFromProfile>[0]
+ const azureResult = await azureAdCsFns.orderCertificate(
+ azureParams as Parameters<typeof azureAdCsFns.orderCertificate>[0]
);
if (await isCancelled()) {
@@ -643,8 +643,8 @@ export const certificateIssuanceQueueFactory = ({
return;
}
- const acmResult = await awsAcmPublicCaFns.orderCertificateFromProfile(
- acmParams as Parameters<typeof awsAcmPublicCaFns.orderCertificateFromProfile>[0]
+ const acmResult = await awsAcmPublicCaFns.orderCertificate(
+ acmParams as Parameters<typeof awsAcmPublicCaFns.orderCertificate>[0]
);
if (await isCancelled()) {
@@ -712,8 +712,8 @@ export const certificateIssuanceQueueFactory = ({
return;
}
- const awsPcaResult = await awsPcaFns.orderCertificateFromProfile(
- awsPcaParams as Parameters<typeof awsPcaFns.orderCertificateFromProfile>[0]
+ const awsPcaResult = await awsPcaFns.orderCertificate(
+ awsPcaParams as Parameters<typeof awsPcaFns.orderCertificate>[0]
);
if (await isCancelled()) {
@@ -780,7 +780,7 @@ export const certificateIssuanceQueueFactory = ({
return;
}
- const digicertResult = await digicertFns.orderCertificateFromProfile({
+ const digicertResult = await digicertFns.orderCertificate({
caId,
commonName: commonName || "",
altNames: altNames?.map((san) => san.value) || [],
@@ -904,7 +904,7 @@ export const certificateIssuanceQueueFactory = ({
return;
}
- const godaddyResult = await godaddyFns.orderCertificateFromProfile({
+ const godaddyResult = await godaddyFns.orderCertificate({
caId,
commonName: commonName || "",
altNames: altNames?.map((san) => san.value) || [],
@@ -988,8 +988,8 @@ export const certificateIssuanceQueueFactory = ({
return;
}
- const venafiTppResult = await venafiTppFns.orderCertificateFromProfile(
- venafiTppParams as Parameters<typeof venafiTppFns.orderCertificateFromProfile>[0]
+ const venafiTppResult = await venafiTppFns.orderCertificate(
+ venafiTppParams as Parameters<typeof venafiTppFns.orderCertificate>[0]
);
if (await isCancelled()) {
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 bdb276f91b..7bb2bacca1 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
@@ -359,7 +359,7 @@ export const DigiCertCertificateAuthorityFns = ({
return cas.map(castDbEntryToDigiCertCertificateAuthority);
};
- const orderCertificateFromProfile = async ({
+ const orderCertificate = async ({
caId,
commonName,
altNames = [],
@@ -725,7 +725,7 @@ export const DigiCertCertificateAuthorityFns = ({
createCertificateAuthority,
updateCertificateAuthority,
listCertificateAuthorities,
- orderCertificateFromProfile,
+ orderCertificate,
fetchAndAttachIssuedCertificate,
pollOrderForCertificate,
revokeCertificate
diff --git a/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-fns.ts b/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-fns.ts
index ff4028577a..599367904b 100644
--- a/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/godaddy/godaddy-certificate-authority-fns.ts
@@ -356,7 +356,7 @@ export const GoDaddyCertificateAuthorityFns = ({
return cas.map(castDbEntryToGoDaddyCertificateAuthority);
};
- const orderCertificateFromProfile = async ({
+ const orderCertificate = async ({
caId,
commonName,
altNames = [],
@@ -652,7 +652,7 @@ export const GoDaddyCertificateAuthorityFns = ({
createCertificateAuthority,
updateCertificateAuthority,
listCertificateAuthorities,
- orderCertificateFromProfile,
+ orderCertificate,
fetchAndAttachIssuedCertificate,
revokeCertificate
};
diff --git a/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts b/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts
index 0674f476e4..e8543439ef 100644
--- a/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts
@@ -539,7 +539,7 @@ export const VenafiTppCertificateAuthorityFns = ({
return cas.map(castDbEntryToVenafiTppCertificateAuthority);
};
- const orderCertificateFromProfile = async ({
+ const orderCertificate = async ({
caId,
profileId,
commonName,
@@ -962,6 +962,6 @@ export const VenafiTppCertificateAuthorityFns = ({
createCertificateAuthority,
updateCertificateAuthority,
listCertificateAuthorities,
- orderCertificateFromProfile
+ orderCertificate
};
};
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
index 8dcdf75126..866880daec 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -955,7 +955,7 @@ describe("CertificateV3Service", () => {
});
});
- describe("orderCertificateFromProfile", () => {
+ describe("orderCertificate", () => {
const mockCertificateOrder = {
altNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "example.com" }],
validity: { ttl: "30d" },
@@ -986,7 +986,7 @@ describe("CertificateV3Service", () => {
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
await expect(
- service.orderCertificateFromProfile({
+ service.orderCertificate({
profileId,
certificateOrder: mockCertificateOrder,
...mockActor
@@ -994,7 +994,7 @@ describe("CertificateV3Service", () => {
).rejects.toThrow(ForbiddenRequestError);
await expect(
- service.orderCertificateFromProfile({
+ service.orderCertificate({
profileId,
certificateOrder: mockCertificateOrder,
...mockActor
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index a9384a7f8a..ef4b65c55f 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -1892,7 +1892,7 @@ export const certificateV3ServiceFactory = ({
};
};
- const orderCertificateFromProfile = async ({
+ const orderCertificate = async ({
profileId,
certificateOrder,
metadata,
@@ -3157,7 +3157,7 @@ export const certificateV3ServiceFactory = ({
return {
issueCertificateFromProfile,
signCertificateFromProfile,
- orderCertificateFromProfile,
+ orderCertificate,
renewCertificate,
updateRenewalConfig,
disableRenewalConfig,
diff --git a/backend/src/services/hsm-connector/hsm-connector-fns.ts b/backend/src/services/hsm-connector/hsm-connector-fns.ts
index f8f7c82343..92aba521af 100644
--- a/backend/src/services/hsm-connector/hsm-connector-fns.ts
+++ b/backend/src/services/hsm-connector/hsm-connector-fns.ts
@@ -3,7 +3,7 @@ import { z } from "zod";
import { KmsDataKey } from "@app/services/kms/kms-types";
import type { THsmConnectorServiceFactoryDep } from "./hsm-connector-service";
-import type { THsmConnectorCredentials, THsmConnectorSanitized } from "./hsm-connector-types";
+import type { THsmConnectorCredentials } from "./hsm-connector-types";
export const HSM_CREDENTIALS_LIMITS = {
slotLabelMax: 128,
@@ -67,29 +67,3 @@ export const HsmConnectorSanitizedSchema = z.object({
createdAt: z.date(),
updatedAt: z.date()
});
-
-export const sanitizeHsmConnector = (args: {
- row: {
- id: string;
- name: string;
- description?: string | null | undefined;
- projectId: string;
- gatewayId?: string | null | undefined;
- gatewayPoolId?: string | null | undefined;
- createdAt: Date;
- updatedAt: Date;
- };
- credentials: THsmConnectorCredentials;
-}): THsmConnectorSanitized =>
- HsmConnectorSanitizedSchema.parse({
- id: args.row.id,
- name: args.row.name,
- description: args.row.description ?? null,
- projectId: args.row.projectId,
- gatewayId: args.row.gatewayId ?? null,
- gatewayPoolId: args.row.gatewayPoolId ?? null,
- slotLabel: args.credentials.slotLabel,
- keyNamePrefix: args.credentials.keyNamePrefix ?? null,
- createdAt: args.row.createdAt,
- updatedAt: args.row.updatedAt
- });
diff --git a/backend/src/services/hsm-connector/hsm-connector-service.ts b/backend/src/services/hsm-connector/hsm-connector-service.ts
index 9f897f5077..da789b6b09 100644
--- a/backend/src/services/hsm-connector/hsm-connector-service.ts
+++ b/backend/src/services/hsm-connector/hsm-connector-service.ts
@@ -21,7 +21,7 @@ import {
decryptHsmConnectorCredentials,
encryptHsmConnectorCredentials,
HsmConnectorCredentialsSchema,
- sanitizeHsmConnector
+ HsmConnectorSanitizedSchema
} from "./hsm-connector-fns";
import { hsmConnectorRoutingFactory } from "./hsm-connector-routing";
import type {
@@ -167,7 +167,11 @@ export const hsmConnectorServiceFactory = ({
throw err;
}
- return sanitizeHsmConnector({ row, credentials: parsedCreds.data });
+ return HsmConnectorSanitizedSchema.parse({
+ ...row,
+ slotLabel: parsedCreds.data.slotLabel,
+ keyNamePrefix: parsedCreds.data.keyNamePrefix ?? null
+ });
};
const listHsmConnectors = async (
@@ -184,7 +188,11 @@ export const hsmConnectorServiceFactory = ({
encryptedCredentials: row.encryptedCredentials,
kmsService
});
- return sanitizeHsmConnector({ row, credentials });
+ return HsmConnectorSanitizedSchema.parse({
+ ...row,
+ slotLabel: credentials.slotLabel,
+ keyNamePrefix: credentials.keyNamePrefix ?? null
+ });
})
);
};
@@ -203,7 +211,11 @@ export const hsmConnectorServiceFactory = ({
encryptedCredentials: row.encryptedCredentials,
kmsService
});
- return sanitizeHsmConnector({ row, credentials });
+ return HsmConnectorSanitizedSchema.parse({
+ ...row,
+ slotLabel: credentials.slotLabel,
+ keyNamePrefix: credentials.keyNamePrefix ?? null
+ });
};
const updateHsmConnector = async (
@@ -285,7 +297,11 @@ export const hsmConnectorServiceFactory = ({
const updated = await hsmConnectorDAL.updateById(row.id, update);
- return sanitizeHsmConnector({ row: updated, credentials: parsedCreds.data });
+ return HsmConnectorSanitizedSchema.parse({
+ ...updated,
+ slotLabel: parsedCreds.data.slotLabel,
+ keyNamePrefix: parsedCreds.data.keyNamePrefix ?? null
+ });
};
const deleteHsmConnector = async (dto: TDeleteHsmConnectorDTO, actor: THsmConnectorServiceActor) => {
diff --git a/backend/src/services/signer/signer-dal.ts b/backend/src/services/signer/signer-dal.ts
index e27f6d87e9..5aed15c5ec 100644
--- a/backend/src/services/signer/signer-dal.ts
+++ b/backend/src/services/signer/signer-dal.ts
@@ -12,6 +12,8 @@ export type TSignerWithCertificate = TPkiSigners & {
certificateNotAfter: Date | null;
certificateNotBefore: Date | null;
certificateKeyAlgorithm: string | null;
+ certificateKeySource: string | null;
+ certificateHsmConnectorId: string | null;
certificateStatus: string | null;
certificateCaId: string | null;
approvalPolicyName: string | null;
@@ -46,6 +48,8 @@ export const signerDALFactory = (db: TDbClient) => {
db.ref("notAfter").withSchema(TableName.Certificate).as("certificateNotAfter"),
db.ref("notBefore").withSchema(TableName.Certificate).as("certificateNotBefore"),
db.ref("keyAlgorithm").withSchema(TableName.Certificate).as("certificateKeyAlgorithm"),
+ db.ref("keySource").withSchema(TableName.Certificate).as("certificateKeySource"),
+ db.ref("hsmConnectorId").withSchema(TableName.Certificate).as("certificateHsmConnectorId"),
db.ref("status").withSchema(TableName.Certificate).as("certificateStatus"),
db.ref("caId").withSchema(TableName.Certificate).as("certificateCaId"),
db.ref("name").withSchema(TableName.ApprovalPolicies).as("approvalPolicyName")
@@ -159,6 +163,8 @@ export const signerDALFactory = (db: TDbClient) => {
db.ref("notAfter").withSchema(TableName.Certificate).as("certificateNotAfter"),
db.ref("notBefore").withSchema(TableName.Certificate).as("certificateNotBefore"),
db.ref("keyAlgorithm").withSchema(TableName.Certificate).as("certificateKeyAlgorithm"),
+ db.ref("keySource").withSchema(TableName.Certificate).as("certificateKeySource"),
+ db.ref("hsmConnectorId").withSchema(TableName.Certificate).as("certificateHsmConnectorId"),
db.ref("status").withSchema(TableName.Certificate).as("certificateStatus"),
db.ref("caId").withSchema(TableName.Certificate).as("certificateCaId"),
db.ref("name").withSchema(TableName.ApprovalPolicies).as("approvalPolicyName")
diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.ts
index 78de428762..d0852d6e77 100644
--- a/backend/src/services/signer/signer-issuance-service.ts
+++ b/backend/src/services/signer/signer-issuance-service.ts
@@ -453,7 +453,7 @@ export const signerIssuanceServiceFactory = ({
"HSM-backed signers are not supported with Azure AD CS yet. Use AWS Private CA, or switch the signer's key source to Infisical."
});
}
- const azureResult = await azureAdCsFns.orderCertificateForSigner({
+ const azureResult = await azureAdCsFns.orderCertificate({
caId: job.caId,
commonName: job.commonName,
altNames: [],
@@ -469,7 +469,7 @@ export const signerIssuanceServiceFactory = ({
}
certificateId = azureResult.certificateId;
} else {
- const awsResult = await awsPcaFns.orderCertificateForSigner({
+ const awsResult = await awsPcaFns.orderCertificate({
caId: job.caId,
commonName: job.commonName,
altNames: [],
diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.ts
index 317677489b..a7c9fcb40f 100644
--- a/backend/src/services/signer/signer-service.ts
+++ b/backend/src/services/signer/signer-service.ts
@@ -59,7 +59,6 @@ import { TSignerDALFactory } from "./signer-dal";
import { CertKeySource, HsmKeyAlgorithm, SignerStatus, SigningOperationStatus } from "./signer-enums";
import { formatSignerIssuanceErrorReason } from "./signer-issuance-errors";
import {
- hsmKeyAlgorithmToCertKeyAlgorithm,
issueHsmBackedSignerCertificate,
issueSignerCertificate,
mapCertKeyAlgorithmToHsmKeyAlgorithm,
@@ -221,17 +220,14 @@ export const resolveReissueTarget = ({
if (targetIsHsm) {
const hsmConnectorId = dto.certificate?.hsmConnectorId ?? currentCert?.hsmConnectorId ?? null;
- const hsmKeyAlgorithm =
- dto.certificate?.hsmKeyAlgorithm ??
- (currentCert?.keyAlgorithm ? mapCertKeyAlgorithmToHsmKeyAlgorithm(currentCert.keyAlgorithm) : undefined);
- if (!hsmConnectorId || !hsmKeyAlgorithm) {
+ const keyAlgorithm =
+ dto.keyAlgorithm ?? (currentCert?.keyAlgorithm as CertKeyAlgorithm | undefined) ?? CertKeyAlgorithm.RSA_2048;
+ const hsmKeyAlgorithm = mapCertKeyAlgorithmToHsmKeyAlgorithm(keyAlgorithm);
+ if (!hsmConnectorId) {
throw new BadRequestError({
- message: "hsmConnectorId and hsmKeyAlgorithm are required to (re)issue with an HSM key source."
+ message: "hsmConnectorId is required to (re)issue with an HSM key source."
});
}
- const keyAlgorithm = dto.certificate?.hsmKeyAlgorithm
- ? hsmKeyAlgorithmToCertKeyAlgorithm(dto.certificate.hsmKeyAlgorithm)
- : ((currentCert?.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048);
return { isHsm: true, switchingKeySource, keyAlgorithm, hsmConnectorId, hsmKeyAlgorithm };
}
@@ -369,9 +365,9 @@ export const signerServiceFactory = ({
if (usingCa && resolvedCaId && !isExternalCa) {
const certificateInput = dto.certificate;
if (certificateInput?.keySource === CertKeySource.Hsm) {
- if (!certificateInput.hsmConnectorId || !certificateInput.hsmKeyAlgorithm) {
+ if (!certificateInput.hsmConnectorId) {
throw new BadRequestError({
- message: "hsmConnectorId and hsmKeyAlgorithm are required when certificate.keySource = 'hsm'."
+ message: "hsmConnectorId is required when certificate.keySource = 'hsm'."
});
}
await hsmConnectorService.assertAttachPermission(
@@ -400,7 +396,7 @@ export const signerServiceFactory = ({
commonName: dto.commonName as string,
certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,
hsmConnectorId: certificateInput.hsmConnectorId,
- hsmKeyAlgorithm: certificateInput.hsmKeyAlgorithm
+ hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(keyAlgorithm)
}
);
issuedCertificateId = certificateId;
@@ -674,12 +670,10 @@ export const signerServiceFactory = ({
certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,
keyAlgorithm,
hsm:
- certificateInput?.keySource === CertKeySource.Hsm &&
- certificateInput.hsmConnectorId &&
- certificateInput.hsmKeyAlgorithm
+ certificateInput?.keySource === CertKeySource.Hsm && certificateInput.hsmConnectorId
? {
hsmConnectorId: certificateInput.hsmConnectorId,
- hsmKeyAlgorithm: certificateInput.hsmKeyAlgorithm,
+ hsmKeyAlgorithm: mapCertKeyAlgorithmToHsmKeyAlgorithm(keyAlgorithm),
actor: {
type: dto.actor,
id: dto.actorId,
diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.ts
index 11443f6ec9..54cda2deea 100644
--- a/backend/src/services/signer/signer-types.ts
+++ b/backend/src/services/signer/signer-types.ts
@@ -2,7 +2,7 @@ import { SigningAlgorithm } from "@app/lib/crypto/sign/types";
import { TProjectPermission } from "@app/lib/types";
import { CertKeyAlgorithm } from "../certificate/certificate-types";
-import { CertKeySource, HsmKeyAlgorithm, SignerStatus, SigningOperationStatus } from "./signer-enums";
+import { CertKeySource, SignerStatus, SigningOperationStatus } from "./signer-enums";
type TActorPermission = Omit<TProjectPermission, "projectId">;
@@ -20,7 +20,6 @@ export type TCreateSignerApprovalPolicyInput = {
export type TSignerCertificateInput = {
keySource?: CertKeySource;
hsmConnectorId?: string;
- hsmKeyAlgorithm?: HsmKeyAlgorithm;
};
export type TCreateSignerDTO = {
diff --git a/docs/documentation/platform/pki/code-signing/signers.mdx b/docs/documentation/platform/pki/code-signing/signers.mdx
index e5216ff731..f30c5295ef 100644
--- a/docs/documentation/platform/pki/code-signing/signers.mdx
+++ b/docs/documentation/platform/pki/code-signing/signers.mdx
@@ -65,7 +65,7 @@ In **Certificate Manager → Code Signing → Signers**, click **Create Signer**
| **Certificate Authority** | The CA that issues the certificate. Internal CAs issue immediately. External CAs (AWS Private CA, Azure AD CS) issue asynchronously and the Signer enters **Pending** until the cert lands. |
| **Key source** | Where the signing key is generated. **Infisical** (default) lets Infisical generate and manage the key for you. **HSM** generates the key inside your own HSM through an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors). |
| **Common Name** | The legal name shown on the certificate, for example `Acme Mobile, Inc.`. Fixed once the certificate is issued. To change it you must reissue. |
- | **Key algorithm** | The signing key algorithm. With **Key source = Infisical**: `RSA-2048`, `RSA-3072`, `RSA-4096`, `ECDSA P-256`, `ECDSA P-384`, or `ECDSA P-521`. With **Key source = HSM**: `RSA_2048`, `RSA_4096`, `ECC_P256`, or `ECC_P384`. |
+ | **Key algorithm** | The signing key algorithm: `RSA-2048`, `RSA-3072`, `RSA-4096`, `ECDSA P-256`, `ECDSA P-384`, or `ECDSA P-521`. When **Key source = HSM** the choice is restricted to `RSA-2048`, `RSA-4096`, `ECDSA P-256`, or `ECDSA P-384`. |
| **HSM Connector** | The HSM Connector Infisical uses to reach your HSM. Set the Connector up first under **Certificate Manager > Settings > HSM Connectors**. Shown only when **Key source = HSM**. See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors). |
| **Validity (days)** | How long each issued certificate is valid for. Default 365. |
| **Renew before (days)** | Optional, 1 to 30. Auto-renew this many days before expiry. Must be less than Validity. Leave empty to disable auto-renewal. |
@@ -97,11 +97,11 @@ In **Certificate Manager → Code Signing → Signers**, click **Create Signer**
## HSM-backed Signers
-When you pick **Key source = HSM** on the Certificate step, pick the [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) Infisical should use and the HSM key algorithm. The private key never leaves the HSM and every sign operation routes through the linked Connector. Infisical only holds the public key and the issued certificate.
+When you pick **Key source = HSM** on the Certificate step, pick the [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) Infisical should use. The Key algorithm choices narrow to the HSM-supported subset. The private key never leaves the HSM and every sign operation routes through the linked Connector. Infisical only holds the public key and the issued certificate.
-You can later switch an existing Signer between Infisical and HSM by reissuing the certificate with a different key source. Hit the [reissue endpoint](/api-reference/endpoints/code-signing/signers/reissue) with a `certificate.keySource` body, plus `hsmConnectorId` and `hsmKeyAlgorithm` when switching to HSM. The signer keeps its name, members, policy, and CA. Only the underlying key and the cert wrapping it change.
+You can later switch an existing Signer between Infisical and HSM by reissuing the certificate with a different key source. Hit the [reissue endpoint](/api-reference/endpoints/code-signing/signers/reissue) with a `certificate.keySource` body, plus `hsmConnectorId` when switching to HSM. The signer keeps its name, members, policy, and CA. Only the underlying key and the cert wrapping it change.
-See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors) for the setup an HSM-backed Signer depends on.
+See [HSM Connectors](/documentation/platform/pki/settings/hsm-connectors) for the setup.
## Signer statuses
@@ -178,9 +178,11 @@ To sign with a Signer, pick the integration that matches your tooling:
Artifacts already signed remain valid as long as the certificate they were signed with is still valid and the verifier trusts the issuing CA's chain. Deleting the Signer in Infisical only removes Infisical's ability to sign new artifacts with that certificate. It does not invalidate past signatures.
</Accordion>
<Accordion title="Can I migrate an existing Signer between Infisical and an HSM?">
- Yes. Reissue the Signer's certificate with a different `certificate.keySource` via the [reissue endpoint](/api-reference/endpoints/code-signing/signers/reissue). When switching to HSM you also pass `hsmConnectorId` and `hsmKeyAlgorithm`. The signer keeps its name, members, approval policy, and CA. Only the key and the cert wrapping it change.
+ Yes. From the Signer detail page, open **Edit Signer > Certificate** and change **Key source**. When switching to HSM, pick an HSM Connector and a supported algorithm (RSA-2048, RSA-4096, ECDSA P-256, or ECDSA P-384). Saving reissues the certificate with the new key. The signer keeps its name, members, approval policy, and CA. Only the key and the cert wrapping it change.
- The previous certificate stays in the inventory and still references its original HSM key (the HSM key itself is not deleted, only the Infisical-side reference). Delete or retire the old certificate before you try to delete the HSM Connector it referenced.
+ The same operation is available via the [reissue endpoint](/api-reference/endpoints/code-signing/signers/reissue) by passing `certificate.keySource` and (when switching to HSM) `hsmConnectorId`.
+
+ The previous certificate stays in the inventory. Delete or retire the old certificate before you try to delete the HSM Connector it referenced.
</Accordion>
</AccordionGroup>
diff --git a/docs/documentation/platform/pki/settings/hsm-connectors-fortanix-dsm.mdx b/docs/documentation/platform/pki/settings/hsm-connectors-fortanix-dsm.mdx
index 6f3f3249e6..a32d8f6ffb 100644
--- a/docs/documentation/platform/pki/settings/hsm-connectors-fortanix-dsm.mdx
+++ b/docs/documentation/platform/pki/settings/hsm-connectors-fortanix-dsm.mdx
@@ -8,78 +8,106 @@ This page covers the end-to-end setup for connecting Fortanix Data Security Mana
## Prerequisites
-- A Fortanix DSM account with at least one group and an application configured for PKCS#11 access.
+- A Fortanix DSM account with at least one group and an application configured for PKCS#11 access. In **Apps > _your app_ > API Keys**, generate an API key. You will need both the **API key** itself and the **slot label** (visible under **Groups > _your group_**) below.
- A host inside your network that can reach your DSM endpoint over HTTPS, where you can install the Fortanix PKCS#11 client and run an [Infisical Gateway](/documentation/platform/gateways/overview).
-- Project-level permission to create HSM Connectors in Infisical (`HSM Connectors > Create`).
+- Permission to create HSM Connectors in Infisical (`HSM Connectors > Create`).
-## Step 1: Install the Fortanix PKCS#11 driver on the Gateway host
+## How the Fortanix credentials map to Infisical
-Download the Fortanix PKCS#11 client from the Fortanix DSM dashboard (Settings -> Client configurations) for the OS that will run the Gateway. Install it and confirm the driver file path is readable by the Gateway user:
+The Fortanix API key plays two roles, so you plug it in twice:
-```bash
-ls -l /opt/fortanix/pkcs11/fortanix_pkcs11.so
-```
+1. **Fortanix client config on the Gateway host** (`/etc/fortanix/pkcs11/pkcs11.conf`, set up in Step 1). The PKCS#11 driver reads this file at load time and uses the API key to authenticate to your DSM endpoint.
+2. **Connector PIN in Infisical** (set up in Step 3). Fortanix surfaces the same API key as the PKCS#11 user PIN, so paste it into the Connector's **PIN** field.
-The default install path on Linux is `/opt/fortanix/pkcs11/fortanix_pkcs11.so`. If you put it somewhere else, use that path everywhere in the steps below.
+The **slot label** is your Fortanix group name, visible under **Groups** in the DSM dashboard or via `pkcs11-tool --list-slots` once the driver is loaded.
-Create or copy the Fortanix client configuration file at `/etc/fortanix/pkcs11/pkcs11.conf`. The minimum keys are the DSM endpoint and the API key for the application that will be used as the PKCS#11 user. Fortanix provides the file content directly from the dashboard.
+<Steps>
+ <Step title="Install the Fortanix PKCS#11 driver on the Gateway host">
+ Download the Fortanix PKCS#11 client from the Fortanix DSM dashboard (**Settings > Client configurations**) for the OS that will run the Gateway. Install it and confirm the driver file path is readable by the Gateway user:
-Verify the driver loads:
-
-```bash
-pkcs11-tool --module /opt/fortanix/pkcs11/fortanix_pkcs11.so --list-slots
-```
-
-You should see one slot per Fortanix DSM group your application is a member of, each with a slot label and a serial number.
+ ```bash
+ ls -l /opt/fortanix/pkcs11/fortanix_pkcs11.so
+ ```
-## Step 2: Start the Gateway with the driver attached
+ The default install path on Linux is `/opt/fortanix/pkcs11/fortanix_pkcs11.so`. If you put it somewhere else, use that path everywhere in the steps below.
-Append `--pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so` to the Gateway start (or systemd install) command:
+ Create the Fortanix client configuration file at `/etc/fortanix/pkcs11/pkcs11.conf`. Minimum keys are the DSM endpoint and your application's API key, for example:
-<Tabs>
- <Tab title="Linux (systemd)">
- ```bash
- sudo infisical gateway systemd install <gateway-name> \
- --enroll-method=token \
- --token=<enrollment-token> \
- --domain=<your-infisical-domain> \
- --pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so
- sudo systemctl start <gateway-name>
+ ```toml
+ api_endpoint = "https://amer.smartkey.io"
+ api_key = "<your-fortanix-app-api-key>"
```
- </Tab>
- <Tab title="Foreground">
- ```bash
- infisical gateway start <gateway-name> \
- --enroll-method=token \
- --token=<enrollment-token> \
- --domain=<your-infisical-domain> \
- --pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so
- ```
- </Tab>
-</Tabs>
-
-Check the Gateway logs for a confirmation that the PKCS#11 module loaded.
-## Step 3: Create the HSM Connector in Infisical
+ The Fortanix dashboard generates the exact file content for you (the "Client configurations" page). This file is what the **driver** uses to talk to DSM. You will paste the same API key into Infisical later as the Connector's PIN.
-In **Certificate Manager > Settings > HSM Connectors**, click **Add HSM Connector** and fill in:
+ Verify the driver loads and surfaces your slot:
-| Field | Value |
-|-------|-------|
-| **Name** | Slug-friendly identifier, e.g. `fortanix-prod`. |
-| **Gateway** | The Gateway you started above (or a Pool that contains it). |
-| **Slot label** | The Fortanix slot label from `pkcs11-tool --list-slots`. |
-| **PIN** | The Fortanix application's PKCS#11 PIN. |
-| **Key label prefix** | Optional. Useful if your DSM hosts keys for multiple environments. |
+ ```bash
+ pkcs11-tool --module /opt/fortanix/pkcs11/fortanix_pkcs11.so --list-slots
+ ```
-On submit Infisical runs a Verify round-trip through the Gateway. A wrong PIN, missing slot label, or unreachable Gateway is caught here and the Connector is not persisted.
+ You should see one slot per Fortanix DSM group your application is a member of, each with a slot label that matches the group name. Note the label. You will plug it into the Connector in the final step.
+ </Step>
+
+ <Step title="Start the Gateway with the driver attached">
+ Append `--pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so` to the Gateway start (or systemd install) command:
+
+ <Tabs>
+ <Tab title="Linux (systemd)">
+ ```bash
+ sudo infisical gateway systemd install <gateway-name> \
+ --enroll-method=token \
+ --token=<enrollment-token> \
+ --domain=<your-infisical-domain> \
+ --pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so
+ sudo systemctl start <gateway-name>
+ ```
+ </Tab>
+ <Tab title="Foreground">
+ ```bash
+ infisical gateway start <gateway-name> \
+ --enroll-method=token \
+ --token=<enrollment-token> \
+ --domain=<your-infisical-domain> \
+ --pkcs11-module=/opt/fortanix/pkcs11/fortanix_pkcs11.so
+ ```
+ </Tab>
+ </Tabs>
+
+ Check the Gateway logs for a confirmation that the PKCS#11 module loaded.
+ </Step>
+
+ <Step title="Create the HSM Connector in Infisical">
+ In **Certificate Manager > Settings > HSM Connectors**, click **Add HSM Connector** and fill in:
+
+ | Field | Value |
+ |-------|-------|
+ | **Name** | Slug-friendly identifier, e.g. `fortanix-prod`. |
+ | **Gateway** | The Gateway you started above (or a Pool that contains it). |
+ | **Slot label** | The Fortanix group name. Same value `pkcs11-tool --list-slots` shows under "label". |
+ | **PIN** | The Fortanix API key you put in `pkcs11.conf` above. Fortanix uses it as the PKCS#11 user PIN. |
+ | **Key label prefix** | Optional. Useful if your DSM hosts keys for multiple environments. |
+
+ On submit Infisical runs a Verify round-trip through the Gateway. A wrong PIN, missing slot label, or unreachable Gateway is caught here and the Connector is not persisted.
+ </Step>
+</Steps>
## Troubleshooting
-- **"slot not found" on Verify**: confirm the slot label matches what `pkcs11-tool --list-slots` reports. Fortanix slot labels are case-sensitive.
-- **"login failed" on Verify**: re-check the PIN. The PIN is the Fortanix application's PKCS#11 PIN, not the DSM account password.
-- **"gateway unreachable"**: the Gateway must be running with HSM support enabled. Check the Gateway log for the PKCS#11 module load line.
-- **Slow operations**: if the Gateway host can't reach DSM over HTTPS with low latency, every sign call pays the round-trip. Run the Gateway in the same network as DSM whenever possible.
+<AccordionGroup>
+ <Accordion title='"slot not found" on Verify'>
+ Confirm the slot label matches what `pkcs11-tool --list-slots` reports. Fortanix slot labels are case-sensitive.
+ </Accordion>
+ <Accordion title='"login failed" on Verify'>
+ Re-check the PIN. The PIN must be the same Fortanix API key you put in `pkcs11.conf` (not the DSM account password). If you rotated the API key in the Fortanix dashboard, update both `pkcs11.conf` on the Gateway host and the Connector's PIN in Infisical.
+ </Accordion>
+ <Accordion title='"gateway unreachable"'>
+ The Gateway must be running with HSM support enabled. Check the Gateway log for the PKCS#11 module load line.
+ </Accordion>
+ <Accordion title="Slow operations">
+ If the Gateway host can't reach DSM over HTTPS with low latency, every sign call pays the round-trip. Run the Gateway in the same network as DSM whenever possible.
+ </Accordion>
+</AccordionGroup>
## What's next?
diff --git a/frontend/src/hooks/api/hsmConnectors/mutations.tsx b/frontend/src/hooks/api/hsmConnectors/mutations.tsx
index f006cec58a..0a2203ed6a 100644
--- a/frontend/src/hooks/api/hsmConnectors/mutations.tsx
+++ b/frontend/src/hooks/api/hsmConnectors/mutations.tsx
@@ -15,7 +15,7 @@ export const useCreateHsmConnector = () => {
return useMutation({
mutationFn: async (payload: TCreateHsmConnectorPayload) => {
const { data } = await apiRequest.post<{ hsmConnector: THsmConnector }>(
- "/api/v1/hsm-connectors",
+ "/api/v1/cert-manager/hsm-connectors",
payload
);
return data.hsmConnector;
@@ -31,7 +31,7 @@ export const useUpdateHsmConnector = () => {
return useMutation({
mutationFn: async ({ connectorId, ...patch }: TUpdateHsmConnectorPayload) => {
const { data } = await apiRequest.patch<{ hsmConnector: THsmConnector }>(
- `/api/v1/hsm-connectors/${connectorId}`,
+ `/api/v1/cert-manager/hsm-connectors/${connectorId}`,
patch
);
return data.hsmConnector;
@@ -51,7 +51,7 @@ export const useDeleteHsmConnector = () => {
return useMutation({
mutationFn: async ({ connectorId }: { connectorId: string }) => {
const { data } = await apiRequest.delete<{ id: string }>(
- `/api/v1/hsm-connectors/${connectorId}`
+ `/api/v1/cert-manager/hsm-connectors/${connectorId}`
);
return data;
},
@@ -65,7 +65,7 @@ export const useTestHsmConnector = () => {
return useMutation({
mutationFn: async ({ connectorId }: { connectorId: string }) => {
const { data } = await apiRequest.post<THsmConnectorTestResult>(
- `/api/v1/hsm-connectors/${connectorId}/test`
+ `/api/v1/cert-manager/hsm-connectors/${connectorId}/test`
);
return data;
}
diff --git a/frontend/src/hooks/api/hsmConnectors/queries.tsx b/frontend/src/hooks/api/hsmConnectors/queries.tsx
index 7449e26881..a2658f0aa7 100644
--- a/frontend/src/hooks/api/hsmConnectors/queries.tsx
+++ b/frontend/src/hooks/api/hsmConnectors/queries.tsx
@@ -6,7 +6,7 @@ import { THsmConnector, THsmConnectorLinkedCertificate } from "./types";
export const hsmConnectorKeys = {
all: ["hsm-connectors"] as const,
- listByProject: (projectId: string) => [...hsmConnectorKeys.all, "list", projectId] as const,
+ list: () => [...hsmConnectorKeys.all, "list"] as const,
byId: (id: string) => [...hsmConnectorKeys.all, "by-id", id] as const,
linkedResourcesAll: (id: string) => [...hsmConnectorKeys.all, "linked-resources", id] as const,
linkedResources: (id: string, pagination: { offset: number; limit: number }) =>
@@ -14,20 +14,17 @@ export const hsmConnectorKeys = {
};
export const useListHsmConnectors = (
- projectId: string | undefined,
options?: Omit<UseQueryOptions<THsmConnector[]>, "queryKey" | "queryFn">
) => {
return useQuery({
...options,
- queryKey: hsmConnectorKeys.listByProject(projectId ?? ""),
+ queryKey: hsmConnectorKeys.list(),
queryFn: async () => {
const { data } = await apiRequest.get<{ hsmConnectors: THsmConnector[] }>(
- "/api/v1/hsm-connectors",
- { params: { projectId } }
+ "/api/v1/cert-manager/hsm-connectors"
);
return data.hsmConnectors;
- },
- enabled: Boolean(projectId) && (options?.enabled ?? true)
+ }
});
};
@@ -40,7 +37,7 @@ export const useGetHsmConnectorById = (
queryKey: hsmConnectorKeys.byId(connectorId ?? ""),
queryFn: async () => {
const { data } = await apiRequest.get<{ hsmConnector: THsmConnector }>(
- `/api/v1/hsm-connectors/${connectorId}`
+ `/api/v1/cert-manager/hsm-connectors/${connectorId}`
);
return data.hsmConnector;
},
@@ -65,7 +62,7 @@ export const useListHsmConnectorLinkedResources = (
const { data } = await apiRequest.get<{
certificates: THsmConnectorLinkedCertificate[];
totalCount: number;
- }>(`/api/v1/hsm-connectors/${connectorId}/linked-resources`, {
+ }>(`/api/v1/cert-manager/hsm-connectors/${connectorId}/linked-resources`, {
params: { offset, limit }
});
return {
diff --git a/frontend/src/hooks/api/hsmConnectors/types.ts b/frontend/src/hooks/api/hsmConnectors/types.ts
index bb56e41621..327b6b5110 100644
--- a/frontend/src/hooks/api/hsmConnectors/types.ts
+++ b/frontend/src/hooks/api/hsmConnectors/types.ts
@@ -14,7 +14,6 @@ export type THsmConnector = {
};
export type TCreateHsmConnectorPayload = {
- projectId: string;
name: string;
description?: string;
gatewayId?: string;
diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.ts
index 79d6edf336..b13481b96c 100644
--- a/frontend/src/hooks/api/signers/types.ts
+++ b/frontend/src/hooks/api/signers/types.ts
@@ -24,12 +24,12 @@ export enum CertKeySource {
Hsm = "hsm"
}
-export enum HsmKeyAlgorithm {
- RSA_2048 = "RSA_2048",
- RSA_4096 = "RSA_4096",
- ECC_P256 = "ECC_P256",
- ECC_P384 = "ECC_P384"
-}
+export const HSM_SUPPORTED_KEY_ALGORITHMS: readonly SignerKeyAlgorithm[] = [
+ SignerKeyAlgorithm.RSA_2048,
+ SignerKeyAlgorithm.RSA_4096,
+ SignerKeyAlgorithm.ECDSA_P256,
+ SignerKeyAlgorithm.ECDSA_P384
+];
export const signerKeyAlgorithmLabels: Record<SignerKeyAlgorithm, string> = {
[SignerKeyAlgorithm.RSA_2048]: "RSA-2048",
@@ -98,6 +98,8 @@ export type TSigner = {
certificateCommonName?: string | null;
certificateSerialNumber?: string | null;
certificateNotAfter?: string | null;
+ certificateKeySource?: CertKeySource | string | null;
+ certificateHsmConnectorId?: string | null;
approvalPolicyName?: string | null;
certificateFailureReason?: string | null;
};
@@ -247,7 +249,6 @@ export type TCreateSignerApprovalPolicyInput = {
export type TSignerCertificateInput = {
keySource?: CertKeySource;
hsmConnectorId?: string;
- hsmKeyAlgorithm?: HsmKeyAlgorithm;
};
export type TCreateSignerDTO = {
@@ -286,7 +287,6 @@ export type TReissueSignerCertificateDTO = {
certificate?: {
keySource: CertKeySource;
hsmConnectorId?: string;
- hsmKeyAlgorithm?: HsmKeyAlgorithm;
};
};
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 5acb01458a..10603b85ba 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx
@@ -25,7 +25,7 @@ import {
} from "@app/context/ProjectPermissionContext/types";
import {
CertKeySource,
- HsmKeyAlgorithm,
+ HSM_SUPPORTED_KEY_ALGORITHMS,
SignerKeyAlgorithm,
signerKeyAlgorithmLabels
} from "@app/hooks/api/signers";
@@ -33,13 +33,6 @@ import {
import { CertificateForm } from "./schemas";
import { CaGroup, CaOption } from "./types";
-const HSM_KEY_ALGORITHM_LABELS: Record<HsmKeyAlgorithm, string> = {
- [HsmKeyAlgorithm.RSA_2048]: "RSA 2048",
- [HsmKeyAlgorithm.RSA_4096]: "RSA 4096",
- [HsmKeyAlgorithm.ECC_P256]: "ECDSA P-256",
- [HsmKeyAlgorithm.ECC_P384]: "ECDSA P-384"
-};
-
export type HsmConnectorOption = { id: string; name: string; slotLabel: string };
type CertificateStepProps = {
@@ -178,11 +171,16 @@ export const CertificateStep = ({
)}
/>
- {!isHsm && (
- <Controller
- name="keyAlgorithm"
- control={form.control}
- render={({ field, fieldState: { error } }) => (
+ <Controller
+ name="keyAlgorithm"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => {
+ const options = isHsm
+ ? Object.values(SignerKeyAlgorithm).filter((v) =>
+ HSM_SUPPORTED_KEY_ALGORITHMS.includes(v)
+ )
+ : Object.values(SignerKeyAlgorithm);
+ return (
<Field>
<FieldLabel>
Key algorithm <span className="text-danger">*</span>
@@ -193,7 +191,7 @@ export const CertificateStep = ({
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
- {Object.values(SignerKeyAlgorithm).map((value) => (
+ {options.map((value) => (
<SelectItem key={value} value={value}>
{signerKeyAlgorithmLabels[value]}
</SelectItem>
@@ -201,83 +199,52 @@ export const CertificateStep = ({
</SelectContent>
</Select>
<FieldDescription>
- Algorithm used to generate the signer&apos;s private key. RSA is widely
- compatible, ECDSA produces smaller signatures and is faster.
+ Algorithm used to generate the signing key. RSA is widely compatible, ECDSA
+ produces smaller signatures and is faster.
</FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
</Field>
- )}
- />
- )}
+ );
+ }}
+ />
{isHsm && (
- <>
- <Controller
- name="hsmConnectorId"
- control={form.control}
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>
- HSM Connector <span className="text-danger">*</span>
- </FieldLabel>
- <FieldContent>
- <FilterableSelect<HsmConnectorOption>
- isLoading={isHsmConnectorsLoading}
- options={hsmConnectorOptions}
- value={hsmConnectorOptions.find((o) => o.id === field.value) ?? null}
- onChange={(selected) => {
- const opt = selected as HsmConnectorOption | null;
- field.onChange(opt?.id ?? null);
- }}
- getOptionLabel={(opt) => `${opt.name} (slot ${opt.slotLabel})`}
- getOptionValue={(opt) => opt.id}
- placeholder="Select an HSM Connector..."
- noOptionsMessage={() =>
- hsmConnectorOptions.length === 0
- ? "No HSM Connectors configured. Add one in Cert Manager Settings → HSM Connectors."
- : "No match."
- }
- isError={Boolean(error)}
- />
- <FieldDescription>
- The HSM on which Infisical will generate the signing key.
- </FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
- />
- <Controller
- name="hsmKeyAlgorithm"
- control={form.control}
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>
- Key algorithm <span className="text-danger">*</span>
- </FieldLabel>
- <FieldContent>
- <Select value={field.value} onValueChange={field.onChange}>
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent position="popper">
- {Object.values(HsmKeyAlgorithm).map((value) => (
- <SelectItem key={value} value={value}>
- {HSM_KEY_ALGORITHM_LABELS[value]}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FieldDescription>
- Algorithm the HSM will generate for this signer&apos;s keypair.
- </FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
- />
- </>
+ <Controller
+ name="hsmConnectorId"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ HSM Connector <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <FilterableSelect<HsmConnectorOption>
+ isLoading={isHsmConnectorsLoading}
+ options={hsmConnectorOptions}
+ value={hsmConnectorOptions.find((o) => o.id === field.value) ?? null}
+ onChange={(selected) => {
+ const opt = selected as HsmConnectorOption | null;
+ field.onChange(opt?.id ?? null);
+ }}
+ getOptionLabel={(opt) => `${opt.name} (slot ${opt.slotLabel})`}
+ getOptionValue={(opt) => opt.id}
+ placeholder="Select an HSM Connector..."
+ noOptionsMessage={() =>
+ hsmConnectorOptions.length === 0
+ ? "No HSM Connectors configured. Add one in Cert Manager Settings → HSM Connectors."
+ : "No match."
+ }
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ The HSM on which Infisical will generate the signing key.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
)}
<Controller
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 f7d8a80d42..9ed075d6ac 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx
@@ -24,7 +24,6 @@ import { useListProjectIdentityMemberships } from "@app/hooks/api/projectIdentit
import { ProjectType } from "@app/hooks/api/projects/types";
import {
CertKeySource,
- HsmKeyAlgorithm,
SignerKeyAlgorithm,
SignerMemberRole,
useCreateSigner
@@ -69,12 +68,9 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
});
const groupsQuery = useGetOrganizationGroups(orgId);
const { subscription } = useSubscription();
- const { data: hsmConnectors = [], isPending: isHsmConnectorsLoading } = useListHsmConnectors(
- projectId,
- {
- enabled: Boolean(subscription?.hsm)
- }
- );
+ const { data: hsmConnectors = [], isPending: isHsmConnectorsLoading } = useListHsmConnectors({
+ enabled: Boolean(subscription?.hsm)
+ });
const createSigner = useCreateSigner();
@@ -141,8 +137,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
certificateRenewBeforeDays: state.certificateRenewBeforeDays,
keyAlgorithm: state.keyAlgorithm,
keySource: state.keySource,
- hsmConnectorId: state.hsmConnectorId,
- hsmKeyAlgorithm: state.hsmKeyAlgorithm
+ hsmConnectorId: state.hsmConnectorId
}
});
@@ -157,8 +152,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
certificateRenewBeforeDays: null,
keyAlgorithm: SignerKeyAlgorithm.RSA_2048,
keySource: CertKeySource.Infisical,
- hsmConnectorId: null,
- hsmKeyAlgorithm: HsmKeyAlgorithm.RSA_2048
+ hsmConnectorId: null
});
};
@@ -191,8 +185,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
state.keySource === CertKeySource.Hsm && state.hsmConnectorId
? {
keySource: CertKeySource.Hsm,
- hsmConnectorId: state.hsmConnectorId,
- hsmKeyAlgorithm: state.hsmKeyAlgorithm
+ hsmConnectorId: state.hsmConnectorId
}
: undefined;
@@ -248,8 +241,7 @@ export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) =
certificateRenewBeforeDays: values.certificateRenewBeforeDays,
keyAlgorithm: values.keyAlgorithm,
keySource: values.keySource,
- hsmConnectorId: values.hsmConnectorId ?? null,
- hsmKeyAlgorithm: values.hsmKeyAlgorithm
+ hsmConnectorId: values.hsmConnectorId ?? null
}));
setStep(2);
return;
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 35612bc788..3661e9f77d 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts
@@ -1,6 +1,10 @@
import { z } from "zod";
-import { CertKeySource, HsmKeyAlgorithm, SignerKeyAlgorithm } from "@app/hooks/api/signers";
+import {
+ CertKeySource,
+ HSM_SUPPORTED_KEY_ALGORITHMS,
+ SignerKeyAlgorithm
+} from "@app/hooks/api/signers";
import { slugSchema } from "@app/lib/schemas";
export const basicsSchema = z.object({
@@ -33,8 +37,7 @@ export const certificateSchema = z
.default(null),
keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048),
keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),
- hsmConnectorId: z.string().uuid().optional().nullable(),
- hsmKeyAlgorithm: z.nativeEnum(HsmKeyAlgorithm).default(HsmKeyAlgorithm.RSA_2048)
+ hsmConnectorId: z.string().uuid().optional().nullable()
})
.refine(
(data) =>
@@ -48,5 +51,15 @@ export const certificateSchema = z
.refine((data) => data.keySource !== CertKeySource.Hsm || Boolean(data.hsmConnectorId), {
message: "Pick an HSM Connector.",
path: ["hsmConnectorId"]
- });
+ })
+ .refine(
+ (data) =>
+ data.keySource !== CertKeySource.Hsm ||
+ HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm),
+ {
+ message:
+ "This algorithm is not supported by HSM-backed keys. Pick RSA-2048, RSA-4096, ECDSA P-256, or ECDSA P-384.",
+ path: ["keyAlgorithm"]
+ }
+ );
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 1050246dff..7698cbca38 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts
@@ -1,9 +1,4 @@
-import {
- CertKeySource,
- HsmKeyAlgorithm,
- SignerKeyAlgorithm,
- SignerMemberRole
-} from "@app/hooks/api/signers";
+import { CertKeySource, SignerKeyAlgorithm, SignerMemberRole } from "@app/hooks/api/signers";
import { PkiDocsUrls } from "../../../pki-docs-urls";
@@ -48,7 +43,6 @@ export type WizardState = {
keyAlgorithm: SignerKeyAlgorithm;
keySource: CertKeySource;
hsmConnectorId: string | null;
- hsmKeyAlgorithm: HsmKeyAlgorithm;
pendingMembers: PendingMember[];
policySteps: PolicyStep[];
maxSignings: number | null;
@@ -65,7 +59,6 @@ export const INITIAL_WIZARD_STATE: WizardState = {
keyAlgorithm: SignerKeyAlgorithm.RSA_2048,
keySource: CertKeySource.Infisical,
hsmConnectorId: null,
- hsmKeyAlgorithm: HsmKeyAlgorithm.RSA_2048,
pendingMembers: [],
policySteps: [],
maxSignings: null,
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/AccessStep.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/AccessStep.tsx
index 16bbe5bebf..6502f3e12d 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/AccessStep.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/AccessStep.tsx
@@ -25,10 +25,10 @@ export const AccessStep = ({ form }: Props) => (
Slot label <span className="text-danger">*</span>
</FieldLabel>
<FieldContent>
- <Input {...field} placeholder="production-signing" isError={Boolean(error)} />
+ <Input {...field} placeholder="fortanix-prod" isError={Boolean(error)} />
<FieldDescription>
- The PKCS#11 token label of the slot on the HSM where signing keys will live. Ask your
- HSM administrator if you are not sure.
+ The PKCS#11 token label of the slot Infisical will use on the HSM. Ask your HSM
+ administrator if you are not sure.
</FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/BasicsStep.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/BasicsStep.tsx
index d2d0d3628e..285084fbf1 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/BasicsStep.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/BasicsStep.tsx
@@ -46,7 +46,7 @@ export const BasicsStep = ({ form }: Props) => (
<TextArea
{...field}
value={field.value ?? ""}
- placeholder="What this HSM is used for (e.g. production signing keys)."
+ placeholder="What this HSM is used for (e.g. production environment)."
rows={3}
isError={Boolean(error)}
/>
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx
index 34f60b5c40..8c9f601e1e 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx
@@ -33,12 +33,11 @@ import {
import { INITIAL_WIZARD_STATE, STEPS, WizardState } from "./types";
type Props = {
- projectId: string;
isOpen: boolean;
onOpenChange: (open: boolean) => void;
};
-export const CreateHsmConnectorWizard = ({ projectId, isOpen, onOpenChange }: Props) => {
+export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange }: Props) => {
const [step, setStep] = useState(0);
const [state, setState] = useState<WizardState>(INITIAL_WIZARD_STATE);
const [submitting, setSubmitting] = useState(false);
@@ -96,7 +95,6 @@ export const CreateHsmConnectorWizard = ({ projectId, isOpen, onOpenChange }: Pr
try {
const [kind, id] = finalState.reachedFrom.split(":");
await createMutation.mutateAsync({
- projectId,
name: finalState.name,
description: finalState.description.trim() || undefined,
gatewayId: kind === "gateway" ? id : undefined,
@@ -181,7 +179,8 @@ export const CreateHsmConnectorWizard = ({ projectId, isOpen, onOpenChange }: Pr
Add HSM Connector
</div>
<p className="text-sm leading-4 text-mineshaft-400">
- Register the hardware security module that holds your signing keys.
+ Register a hardware security module so Infisical can route key operations through
+ it.
</p>
</div>
</div>
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/types.ts b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/types.ts
index 296824e439..3327b114e5 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/types.ts
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/types.ts
@@ -42,7 +42,7 @@ export const STEPS: WizardStep[] = [
subtitle: "Choose the Gateway that connects Infisical to your HSM.",
rightLabel: "CONNECTION",
rightDescription:
- "Select which Gateway will route signing requests to your HSM. Only Gateways with PKCS#11 support enabled appear in the list."
+ "Select which Gateway will route key operations to your HSM. Only Gateways with PKCS#11 support enabled appear in the list."
},
{
name: "Credentials",
@@ -51,6 +51,6 @@ export const STEPS: WizardStep[] = [
subtitle: "How Infisical signs in to your HSM.",
rightLabel: "CREDENTIALS",
rightDescription:
- "The slot label is the PKCS#11 token label of the slot on the HSM where signing keys will live. The PIN authenticates Infisical to that slot. The key label prefix is prepended to every key Infisical creates so you can identify them in your HSM tooling."
+ "The slot label is the PKCS#11 token label of the slot Infisical will use on the HSM. The PIN authenticates Infisical to that slot. The key label prefix is prepended to every key Infisical creates so you can identify them in your HSM tooling."
}
];
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx
index cf3ea8a636..a6eb7c621e 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/HsmConnectorsTab.tsx
@@ -85,7 +85,7 @@ export const HsmConnectorsTab = () => {
});
};
- const { data: connectors = [], isPending } = useListHsmConnectors(projectId, {
+ const { data: connectors = [], isPending } = useListHsmConnectors({
enabled: isLicensed
});
const testMutation = useTestHsmConnector();
@@ -111,8 +111,8 @@ export const HsmConnectorsTab = () => {
<div className="mb-3 text-2xl">&#x1f6e1;&#xfe0f;</div>
<h4 className="mb-2 text-lg font-medium text-mineshaft-100">Enterprise Feature</h4>
<p className="mx-auto mb-4 max-w-md text-sm text-mineshaft-300">
- HSM Connectors let you back signing keys with a Hardware Security Module. The keypair
- stays inside your HSM and every signature is performed there.
+ HSM Connectors let Infisical use keys backed by a Hardware Security Module. Every
+ cryptographic operation is routed through your HSM.
</p>
<Button onClick={() => setUpgradeOpen(true)}>Upgrade to Enterprise</Button>
</div>
@@ -173,7 +173,7 @@ export const HsmConnectorsTab = () => {
HSM Connectors
<DocumentationLinkBadge href={PkiDocsUrls.settings.hsmConnectors} />
</CardTitle>
- <CardDescription>Hardware security modules that hold your signing keys.</CardDescription>
+ <CardDescription>Connect hardware security modules to Infisical.</CardDescription>
<CardAction>
<ProjectPermissionCan
I={ProjectPermissionHsmConnectorActions.Create}
@@ -308,13 +308,7 @@ export const HsmConnectorsTab = () => {
</>
)}
</CardContent>
- {projectId && (
- <CreateHsmConnectorWizard
- projectId={projectId}
- isOpen={addOpen}
- onOpenChange={setAddOpen}
- />
- )}
+ <CreateHsmConnectorWizard isOpen={addOpen} onOpenChange={setAddOpen} />
<EditHsmConnectorSheet connector={editing} onClose={() => setEditing(null)} />
<DeleteHsmConnectorDialog connector={deleting} onClose={() => setDeleting(null)} />
</Card>
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 99002799f3..bb1cc68da7 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx
@@ -1,6 +1,7 @@
import { Controller, useForm } from "react-hook-form";
import {
+ Badge,
Field,
FieldContent,
FieldDescription,
@@ -8,21 +9,41 @@ import {
FieldGroup,
FieldLabel,
FilterableSelect,
- Input
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
} from "@app/components/v3";
+import { useProjectPermission, useSubscription } from "@app/context";
+import {
+ ProjectPermissionHsmConnectorActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import {
+ CertKeySource,
+ HSM_SUPPORTED_KEY_ALGORITHMS,
+ SignerKeyAlgorithm,
+ signerKeyAlgorithmLabels
+} from "@app/hooks/api/signers";
import { CertificateForm } from "./schemas";
import { CaGroup, CaOption } from "./types";
+export type HsmConnectorOption = { id: string; name: string; slotLabel: string };
+
type CertificateStepProps = {
form: ReturnType<typeof useForm<CertificateForm>>;
caOptions: CaOption[];
isCasLoading: boolean;
commonName: string;
certificateTtlDays: number | null;
- keyAlgorithmLabel: string;
+ hsmConnectorOptions: HsmConnectorOption[];
+ isHsmConnectorsLoading: boolean;
caSwap: boolean;
canEditSubject: boolean;
+ keySourceChanged: boolean;
};
export const CertificateStep = ({
@@ -31,169 +52,285 @@ export const CertificateStep = ({
isCasLoading,
commonName,
certificateTtlDays,
- keyAlgorithmLabel,
+ hsmConnectorOptions,
+ isHsmConnectorsLoading,
caSwap,
- canEditSubject
-}: CertificateStepProps) => (
- <FieldGroup>
- <Controller
- name="caId"
- control={form.control}
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>
- Certificate Authority <span className="text-danger">*</span>
- </FieldLabel>
- <FieldContent>
- <FilterableSelect<CaOption>
- isLoading={isCasLoading}
- options={caOptions}
- value={caOptions.find((o) => o.id === field.value) ?? null}
- onChange={(selected) => {
- const opt = selected as CaOption | null;
- field.onChange(opt?.id ?? "");
- }}
- getOptionLabel={(opt) => opt.name}
- getOptionValue={(opt) => opt.id}
- groupBy={caOptions.length > 0 ? "groupType" : undefined}
- getGroupHeaderLabel={
- caOptions.length > 0
- ? (groupType: CaGroup) =>
- groupType === "internal" ? "Internal CAs" : "External CAs"
- : undefined
- }
- placeholder="Select a Certificate Authority..."
- noOptionsMessage={() => "No active CAs available."}
- isError={Boolean(error)}
- />
- <FieldDescription>
- Changing the CA reissues the certificate immediately.
- </FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
- />
+ canEditSubject,
+ keySourceChanged
+}: CertificateStepProps) => {
+ const { subscription } = useSubscription();
+ const isHsmLicensed = Boolean(subscription?.hsm);
+ const { permission } = useProjectPermission();
+ const canAttachHsm = permission.can(
+ ProjectPermissionHsmConnectorActions.Attach,
+ ProjectPermissionSub.HsmConnectors
+ );
- {canEditSubject ? (
+ const keySource = form.watch("keySource");
+ const isHsm = keySource === CertKeySource.Hsm;
+
+ return (
+ <FieldGroup>
<Controller
- name="commonName"
+ name="caId"
control={form.control}
render={({ field, fieldState: { error } }) => (
<Field>
<FieldLabel>
- Common Name <span className="text-danger">*</span>
+ Certificate Authority <span className="text-danger">*</span>
</FieldLabel>
<FieldContent>
- <Input
- {...field}
- value={field.value ?? ""}
- placeholder="Acme Mobile, Inc."
+ <FilterableSelect<CaOption>
+ isLoading={isCasLoading}
+ options={caOptions}
+ value={caOptions.find((o) => o.id === field.value) ?? null}
+ onChange={(selected) => {
+ const opt = selected as CaOption | null;
+ field.onChange(opt?.id ?? "");
+ }}
+ getOptionLabel={(opt) => opt.name}
+ getOptionValue={(opt) => opt.id}
+ groupBy={caOptions.length > 0 ? "groupType" : undefined}
+ getGroupHeaderLabel={
+ caOptions.length > 0
+ ? (groupType: CaGroup) =>
+ groupType === "internal" ? "Internal CAs" : "External CAs"
+ : undefined
+ }
+ placeholder="Select a Certificate Authority..."
+ noOptionsMessage={() => "No active CAs available."}
isError={Boolean(error)}
/>
<FieldDescription>
- The legal name shown on the certificate. Editable while no certificate has been
- issued. Locked once the signer becomes Active.
+ Changing the CA reissues the certificate immediately.
</FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
</Field>
)}
/>
- ) : (
- <Field>
- <FieldLabel>Common Name</FieldLabel>
- <FieldContent>
- <Input value={commonName} readOnly disabled />
- <FieldDescription>The legal name shown on the certificate.</FieldDescription>
- </FieldContent>
- </Field>
- )}
- {canEditSubject ? (
+ {canEditSubject ? (
+ <Controller
+ name="commonName"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Common Name <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ placeholder="Acme Mobile, Inc."
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ The legal name shown on the certificate. Editable while no certificate has been
+ issued. Locked once the signer becomes Active.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ ) : (
+ <Field>
+ <FieldLabel>Common Name</FieldLabel>
+ <FieldContent>
+ <Input value={commonName} readOnly disabled />
+ <FieldDescription>The legal name shown on the certificate.</FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+
+ {canEditSubject ? (
+ <Controller
+ name="certificateTtlDays"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ Validity (days) <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ type="number"
+ min={1}
+ max={3650}
+ value={field.value ?? ""}
+ onChange={(e) => field.onChange(Number(e.target.value))}
+ placeholder="365"
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ How long each issued certificate stays valid. Locked once the signer becomes
+ Active.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ ) : (
+ <Field>
+ <FieldLabel>Validity (days)</FieldLabel>
+ <FieldContent>
+ <Input
+ value={certificateTtlDays != null ? String(certificateTtlDays) : "—"}
+ readOnly
+ disabled
+ />
+ <FieldDescription>How long each issued certificate stays valid.</FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+
+ <Controller
+ name="keySource"
+ control={form.control}
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Key source</FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value={CertKeySource.Infisical}>Infisical</SelectItem>
+ <SelectItem value={CertKeySource.Hsm} disabled={!isHsmLicensed || !canAttachHsm}>
+ <div className="flex items-center gap-2">
+ HSM
+ {!isHsmLicensed && <Badge variant="info">Enterprise</Badge>}
+ {isHsmLicensed && !canAttachHsm && (
+ <Badge variant="warning">Permission required</Badge>
+ )}
+ </div>
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ Switching key source reissues the certificate with a new key.
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
<Controller
- name="certificateTtlDays"
+ name="keyAlgorithm"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => {
+ const options = isHsm
+ ? Object.values(SignerKeyAlgorithm).filter((v) =>
+ HSM_SUPPORTED_KEY_ALGORITHMS.includes(v)
+ )
+ : Object.values(SignerKeyAlgorithm);
+ return (
+ <Field>
+ <FieldLabel>Key algorithm</FieldLabel>
+ <FieldContent>
+ <Select
+ value={field.value}
+ onValueChange={field.onChange}
+ disabled={!keySourceChanged}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {options.map((value) => (
+ <SelectItem key={value} value={value}>
+ {signerKeyAlgorithmLabels[value]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ {keySourceChanged
+ ? "Pick the algorithm for the new key."
+ : "Algorithm of the signer's current key. Switch key source to generate a new one."}
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ );
+ }}
+ />
+
+ {isHsm && (
+ <Controller
+ name="hsmConnectorId"
+ control={form.control}
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>
+ HSM Connector <span className="text-danger">*</span>
+ </FieldLabel>
+ <FieldContent>
+ <FilterableSelect<HsmConnectorOption>
+ isLoading={isHsmConnectorsLoading}
+ options={hsmConnectorOptions}
+ value={hsmConnectorOptions.find((o) => o.id === field.value) ?? null}
+ onChange={(selected) => {
+ const opt = selected as HsmConnectorOption | null;
+ field.onChange(opt?.id ?? null);
+ }}
+ getOptionLabel={(opt) => `${opt.name} (slot ${opt.slotLabel})`}
+ getOptionValue={(opt) => opt.id}
+ placeholder="Select an HSM Connector..."
+ noOptionsMessage={() =>
+ hsmConnectorOptions.length === 0
+ ? "No HSM Connectors configured. Add one in Cert Manager Settings → HSM Connectors."
+ : "No match."
+ }
+ isError={Boolean(error)}
+ />
+ <FieldDescription>
+ The HSM on which Infisical will generate the signing key.
+ </FieldDescription>
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+
+ <Controller
+ name="certificateRenewBeforeDays"
control={form.control}
render={({ field, fieldState: { error } }) => (
<Field>
- <FieldLabel>
- Validity (days) <span className="text-danger">*</span>
- </FieldLabel>
+ <FieldLabel>Renew before (days)</FieldLabel>
<FieldContent>
<Input
type="number"
min={1}
- max={3650}
+ max={30}
value={field.value ?? ""}
- onChange={(e) => field.onChange(Number(e.target.value))}
- placeholder="365"
+ onChange={(e) => {
+ const raw = e.target.value;
+ field.onChange(raw === "" ? null : Number(raw));
+ }}
+ placeholder="Leave empty to disable auto-renewal"
isError={Boolean(error)}
/>
<FieldDescription>
- How long each issued certificate stays valid. Locked once the signer becomes Active.
+ Renew the certificate this many days before it expires.
</FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
</Field>
)}
/>
- ) : (
- <Field>
- <FieldLabel>Validity (days)</FieldLabel>
- <FieldContent>
- <Input
- value={certificateTtlDays != null ? String(certificateTtlDays) : "—"}
- readOnly
- disabled
- />
- <FieldDescription>How long each issued certificate stays valid.</FieldDescription>
- </FieldContent>
- </Field>
- )}
- <Field>
- <FieldLabel>Key algorithm</FieldLabel>
- <FieldContent>
- <Input value={keyAlgorithmLabel} readOnly disabled />
- <FieldDescription>
- Algorithm of the signer&apos;s private key. Fixed at creation; create a new signer to use
- a different one.
- </FieldDescription>
- </FieldContent>
- </Field>
-
- <Controller
- name="certificateRenewBeforeDays"
- control={form.control}
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>Renew before (days)</FieldLabel>
- <FieldContent>
- <Input
- type="number"
- min={1}
- max={30}
- value={field.value ?? ""}
- onChange={(e) => {
- const raw = e.target.value;
- field.onChange(raw === "" ? null : Number(raw));
- }}
- placeholder="Leave empty to disable auto-renewal"
- isError={Boolean(error)}
- />
- <FieldDescription>
- Renew the certificate this many days before it expires.
- </FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
+ {(caSwap || keySourceChanged) && (
+ <div className="rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning">
+ Saving will issue a new certificate right away.
+ </div>
)}
- />
-
- {caSwap && (
- <div className="rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning">
- Saving will issue a new certificate from the selected CA right away.
- </div>
- )}
- </FieldGroup>
-);
+ </FieldGroup>
+ );
+};
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 5f04f1e379..0571312d7f 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx
@@ -15,11 +15,13 @@ import {
StepperList,
StepperStep
} from "@app/components/v3";
+import { useSubscription } from "@app/context";
import { useListCasByProjectId } from "@app/hooks/api/ca";
import { CaStatus, CaType } from "@app/hooks/api/ca/enums";
+import { useListHsmConnectors } from "@app/hooks/api/hsmConnectors";
import {
+ CertKeySource,
SignerKeyAlgorithm,
- signerKeyAlgorithmLabels,
SignerStatus,
TSigner,
useReissueSignerCertificate,
@@ -45,6 +47,16 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
const cas = useListCasByProjectId();
const updateSigner = useUpdateSigner();
const reissueCertificate = useReissueSignerCertificate();
+ const { subscription } = useSubscription();
+ const { data: hsmConnectors = [], isPending: isHsmConnectorsLoading } = useListHsmConnectors({
+ enabled: Boolean(subscription?.hsm)
+ });
+
+ const currentKeySource =
+ (signer.certificateKeySource as CertKeySource | undefined) ?? CertKeySource.Infisical;
+ const currentHsmConnectorId = signer.certificateHsmConnectorId ?? null;
+ const currentKeyAlgorithm =
+ (signer.keyAlgorithm as SignerKeyAlgorithm | undefined) ?? SignerKeyAlgorithm.RSA_2048;
const caOptions: CaOption[] = useMemo(() => {
const list = cas.data ?? [];
@@ -77,20 +89,39 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
caId: signer.caId ?? "",
certificateRenewBeforeDays: signer.certificateRenewBeforeDays ?? null,
commonName: signer.commonName ?? "",
- certificateTtlDays: signer.certificateTtlDays ?? 365
+ certificateTtlDays: signer.certificateTtlDays ?? 365,
+ keySource: currentKeySource,
+ keyAlgorithm: currentKeyAlgorithm,
+ hsmConnectorId: currentHsmConnectorId
}
});
+ const hsmConnectorOptions = useMemo(
+ () =>
+ hsmConnectors.map((c) => ({
+ id: c.id,
+ name: c.name,
+ slotLabel: c.slotLabel
+ })),
+ [hsmConnectors]
+ );
+
const watchedCaId = certificateForm.watch("caId");
const watchedCommonName = certificateForm.watch("commonName");
const watchedTtl = certificateForm.watch("certificateTtlDays");
+ const watchedKeySource = certificateForm.watch("keySource");
+ const watchedHsmConnectorId = certificateForm.watch("hsmConnectorId");
const caSwap = Boolean(watchedCaId) && watchedCaId !== signer.caId;
const subjectChanged =
canEditSubject &&
((watchedCommonName ?? "") !== (signer.commonName ?? "") ||
(watchedTtl ?? 0) !== (signer.certificateTtlDays ?? 0));
- const shouldReissue = caSwap || subjectChanged;
+ const keySourceChanged =
+ watchedKeySource !== currentKeySource ||
+ (watchedKeySource === CertKeySource.Hsm &&
+ (watchedHsmConnectorId ?? null) !== currentHsmConnectorId);
+ const shouldReissue = caSwap || subjectChanged || keySourceChanged;
const handleOpenChange = (open: boolean) => {
if (!open) {
@@ -100,7 +131,10 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
caId: signer.caId ?? "",
certificateRenewBeforeDays: signer.certificateRenewBeforeDays ?? null,
commonName: signer.commonName ?? "",
- certificateTtlDays: signer.certificateTtlDays ?? 365
+ certificateTtlDays: signer.certificateTtlDays ?? 365,
+ keySource: currentKeySource,
+ keyAlgorithm: currentKeyAlgorithm,
+ hsmConnectorId: currentHsmConnectorId
});
}
onOpenChange(open);
@@ -123,7 +157,18 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
signerId: signer.id,
caId: cert.caId,
commonName: canEditSubject && subjectChanged ? cert.commonName : undefined,
- certificateTtlDays: canEditSubject && subjectChanged ? cert.certificateTtlDays : undefined
+ certificateTtlDays:
+ canEditSubject && subjectChanged ? cert.certificateTtlDays : undefined,
+ keyAlgorithm: keySourceChanged ? cert.keyAlgorithm : undefined,
+ certificate: keySourceChanged
+ ? {
+ keySource: cert.keySource,
+ hsmConnectorId:
+ cert.keySource === CertKeySource.Hsm
+ ? (cert.hsmConnectorId ?? undefined)
+ : undefined
+ }
+ : undefined
});
}
@@ -232,14 +277,11 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {
isCasLoading={cas.isPending}
commonName={signer.commonName ?? signer.certificateCommonName ?? "—"}
certificateTtlDays={signer.certificateTtlDays ?? null}
- keyAlgorithmLabel={
- signer.keyAlgorithm
- ? (signerKeyAlgorithmLabels[signer.keyAlgorithm as SignerKeyAlgorithm] ??
- String(signer.keyAlgorithm))
- : "RSA-2048"
- }
+ hsmConnectorOptions={hsmConnectorOptions}
+ isHsmConnectorsLoading={isHsmConnectorsLoading}
caSwap={caSwap}
canEditSubject={canEditSubject}
+ keySourceChanged={keySourceChanged}
/>
)}
</div>
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 4c5784c5b0..85ca229867 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts
@@ -1,5 +1,10 @@
import { z } from "zod";
+import {
+ CertKeySource,
+ HSM_SUPPORTED_KEY_ALGORITHMS,
+ SignerKeyAlgorithm
+} from "@app/hooks/api/signers";
import { slugSchema } from "@app/lib/schemas";
export const basicsSchema = z.object({
@@ -29,7 +34,10 @@ export const certificateSchema = z
)
.default(null),
commonName: z.string().trim().min(1, "Common Name is required").max(256).optional(),
- certificateTtlDays: z.coerce.number().int().min(1).max(3650).optional()
+ certificateTtlDays: z.coerce.number().int().min(1).max(3650).optional(),
+ keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),
+ keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048),
+ hsmConnectorId: z.string().uuid().optional().nullable()
})
.refine(
(data) =>
@@ -40,5 +48,19 @@ export const certificateSchema = z
message: "Renew before must be less than the certificate validity (days).",
path: ["certificateRenewBeforeDays"]
}
+ )
+ .refine((data) => data.keySource !== CertKeySource.Hsm || Boolean(data.hsmConnectorId), {
+ message: "Pick an HSM Connector.",
+ path: ["hsmConnectorId"]
+ })
+ .refine(
+ (data) =>
+ data.keySource !== CertKeySource.Hsm ||
+ HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm),
+ {
+ message:
+ "This algorithm is not supported by HSM-backed keys. Pick RSA-2048, RSA-4096, ECDSA P-256, or ECDSA P-384.",
+ path: ["keyAlgorithm"]
+ }
);
export type CertificateForm = z.infer<typeof certificateSchema>;