Address greptile comments

This commit is contained in:
Carlos Monastyrski
2025-10-17 04:20:34 -03:00
parent 534ce7158b
commit 659086009d
20 changed files with 211 additions and 191 deletions
@@ -34,7 +34,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid
estConfig: z estConfig: z
.object({ .object({
disableBootstrapCaValidation: z.boolean().default(false), disableBootstrapCaValidation: z.boolean().default(false),
passphrase: z.string().min(1), passphraseInput: z.string().min(1),
encryptedCaChain: z.string() encryptedCaChain: z.string()
}) })
.optional(), .optional(),
@@ -332,7 +332,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid
estConfig: z estConfig: z
.object({ .object({
disableBootstrapCaValidation: z.boolean().default(false), disableBootstrapCaValidation: z.boolean().default(false),
passphrase: z.string().min(1), passphraseInput: z.string().min(1),
encryptedCaChain: z.string() encryptedCaChain: z.string()
}) })
.optional(), .optional(),
@@ -26,6 +26,21 @@ import {
import { mapEnumsForValidation } from "@app/services/certificate-common/certificate-utils"; import { mapEnumsForValidation } from "@app/services/certificate-common/certificate-utils";
import { validateTemplateRegexField } from "@app/services/certificate-template/certificate-template-validators"; import { validateTemplateRegexField } from "@app/services/certificate-template/certificate-template-validators";
const validateTtlAndDateFields = (data: { notBefore?: string; notAfter?: string; ttl?: string }) => {
const hasDateFields = data.notBefore || data.notAfter;
const hasTtl = data.ttl;
return !(hasDateFields && hasTtl);
};
const validateDateOrder = (data: { notBefore?: string; notAfter?: string }) => {
if (data.notBefore && data.notAfter) {
const notBefore = new Date(data.notBefore);
const notAfter = new Date(data.notAfter);
return notBefore < notAfter;
}
return true;
};
export const registerCertificatesRouter = async (server: FastifyZodProvider) => { export const registerCertificatesRouter = async (server: FastifyZodProvider) => {
server.route({ server.route({
method: "POST", method: "POST",
@@ -49,30 +64,13 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) =>
signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(), signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(),
keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional() keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional()
}) })
.refine( .refine(validateTtlAndDateFields, {
(data) => { message:
const hasDateFields = data.notBefore || data.notAfter; "Cannot specify both TTL and notBefore/notAfter. Use either TTL for duration-based validity or notBefore/notAfter for explicit date range."
const hasTtl = data.ttl; })
return !(hasDateFields && hasTtl); .refine(validateDateOrder, {
}, message: "notBefore must be earlier than notAfter"
{ }),
message:
"Cannot specify both TTL and notBefore/notAfter. Use either TTL for duration-based validity or notBefore/notAfter for explicit date range."
}
)
.refine(
(data) => {
if (data.notBefore && data.notAfter) {
const notBefore = new Date(data.notBefore);
const notAfter = new Date(data.notAfter);
return notBefore < notAfter;
}
return true;
},
{
message: "notBefore must be earlier than notAfter"
}
),
response: { response: {
200: z.object({ 200: z.object({
certificate: z.string().trim(), certificate: z.string().trim(),
@@ -169,30 +167,13 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) =>
notBefore: validateCaDateField.optional(), notBefore: validateCaDateField.optional(),
notAfter: validateCaDateField.optional() notAfter: validateCaDateField.optional()
}) })
.refine( .refine(validateTtlAndDateFields, {
(data) => { message:
const hasDateFields = data.notBefore || data.notAfter; "Cannot specify both TTL and notBefore/notAfter. Use either TTL for duration-based validity or notBefore/notAfter for explicit date range."
const hasTtl = data.ttl; })
return !(hasDateFields && hasTtl); .refine(validateDateOrder, {
}, message: "notBefore must be earlier than notAfter"
{ }),
message:
"Cannot specify both TTL and notBefore/notAfter. Use either TTL for duration-based validity or notBefore/notAfter for explicit date range."
}
)
.refine(
(data) => {
if (data.notBefore && data.notAfter) {
const notBefore = new Date(data.notBefore);
const notAfter = new Date(data.notAfter);
return notBefore < notAfter;
}
return true;
},
{
message: "notBefore must be earlier than notAfter"
}
),
response: { response: {
200: z.object({ 200: z.object({
certificate: z.string().trim(), certificate: z.string().trim(),
@@ -266,30 +247,13 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) =>
signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(), signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(),
keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional() keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional()
}) })
.refine( .refine(validateTtlAndDateFields, {
(data) => { message:
const hasDateFields = data.notBefore || data.notAfter; "Cannot specify both TTL and notBefore/notAfter. Use either TTL for duration-based validity or notBefore/notAfter for explicit date range."
const hasTtl = data.ttl; })
return !(hasDateFields && hasTtl); .refine(validateDateOrder, {
}, message: "notBefore must be earlier than notAfter"
{ }),
message:
"Cannot specify both TTL and notBefore/notAfter. Use either TTL for duration-based validity or notBefore/notAfter for explicit date range."
}
)
.refine(
(data) => {
if (data.notBefore && data.notAfter) {
const notBefore = new Date(data.notBefore);
const notAfter = new Date(data.notAfter);
return notBefore < notAfter;
}
return true;
},
{
message: "notBefore must be earlier than notAfter"
}
),
response: { response: {
200: z.object({ 200: z.object({
orderId: z.string(), orderId: z.string(),
@@ -3,7 +3,12 @@ import { z } from "zod";
import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal"; import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
import { TProjectPermission } from "@app/lib/types"; import { TProjectPermission } from "@app/lib/types";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal"; import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "@app/services/certificate/certificate-types"; import {
CertExtendedKeyUsage,
CertKeyAlgorithm,
CertKeyUsage,
CertSignatureAlgorithm
} from "@app/services/certificate/certificate-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service"; import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal"; import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -131,8 +136,8 @@ export type TIssueCertFromCaDTO = {
notAfter?: string; notAfter?: string;
keyUsages?: CertKeyUsage[]; keyUsages?: CertKeyUsage[];
extendedKeyUsages?: CertExtendedKeyUsage[]; extendedKeyUsages?: CertExtendedKeyUsage[];
signatureAlgorithm?: string; signatureAlgorithm?: CertSignatureAlgorithm;
keyAlgorithm?: string; keyAlgorithm?: CertKeyAlgorithm;
} & Omit<TProjectPermission, "projectId">; } & Omit<TProjectPermission, "projectId">;
export type TSignCertFromCaDTO = export type TSignCertFromCaDTO =
@@ -94,14 +94,13 @@ export const certificateEstV3ServiceFactory = ({
kmsId: certificateManagerKmsId kmsId: certificateManagerKmsId
}); });
let decryptedCaChain = ""; const decryptedCaChain = estConfig.encryptedCaChain
if (estConfig.encryptedCaChain) { ? (
decryptedCaChain = ( await kmsDecryptor({
await kmsDecryptor({ cipherTextBlob: estConfig.encryptedCaChain
cipherTextBlob: estConfig.encryptedCaChain })
}) ).toString()
).toString(); : "";
}
const caCerts = extractX509CertFromChain(decryptedCaChain)?.map((cert) => { const caCerts = extractX509CertFromChain(decryptedCaChain)?.map((cert) => {
return new x509.X509Certificate(cert); return new x509.X509Certificate(cert);
@@ -114,7 +113,7 @@ export const certificateEstV3ServiceFactory = ({
const leafCertificate = extractX509CertFromChain(decodeURIComponent(sslClientCert))?.[0]; const leafCertificate = extractX509CertFromChain(decodeURIComponent(sslClientCert))?.[0];
if (!leafCertificate) { if (!leafCertificate) {
throw new BadRequestError({ message: "Missing client certificate" }); throw new UnauthorizedError({ message: "Missing client certificate" });
} }
const certObj = new x509.X509Certificate(leafCertificate); const certObj = new x509.X509Certificate(leafCertificate);
@@ -711,7 +711,7 @@ describe("CertificateProfileService", () => {
certificateTemplateId: "template-123", certificateTemplateId: "template-123",
estConfig: { estConfig: {
disableBootstrapCaValidation: false, disableBootstrapCaValidation: false,
passphrase: "secret-passphrase", passphraseInput: "secret-passphrase",
encryptedCaChain: Buffer.from("test-ca-chain-data").toString("base64") encryptedCaChain: Buffer.from("test-ca-chain-data").toString("base64")
} }
}; };
@@ -27,6 +27,21 @@ import {
TCertificateProfileWithRawMetrics TCertificateProfileWithRawMetrics
} from "./certificate-profile-types"; } from "./certificate-profile-types";
const validateAndEncodeBase64CaChain = (caChain: unknown) => {
try {
if (typeof caChain !== "string") {
throw new BadRequestError({ message: "CA chain must be a string" });
}
const buffer = Buffer.from(caChain, "base64");
if (buffer.toString("base64") !== caChain) {
throw new BadRequestError({ message: "Invalid Base64 encoding in CA chain data" });
}
return { encryptedCaChain: buffer };
} catch (error) {
throw new BadRequestError({ message: "Failed to decode CA chain data: Invalid Base64 format" });
}
};
export type TCertificateProfileCreateData = Omit<TCertificateProfileInsert, "estConfigId" | "apiConfigId"> & { export type TCertificateProfileCreateData = Omit<TCertificateProfileInsert, "estConfigId" | "apiConfigId"> & {
estConfig?: TEstConfigData; estConfig?: TEstConfigData;
apiConfig?: TApiConfigData; apiConfig?: TApiConfigData;
@@ -125,7 +140,7 @@ export const certificateProfileServiceFactory = ({
if (data.enrollmentType === EnrollmentType.EST && data.estConfig) { if (data.enrollmentType === EnrollmentType.EST && data.estConfig) {
const appCfg = getConfig(); const appCfg = getConfig();
// Hash the passphrase // Hash the passphrase
const hashedPassphrase = await crypto.hashing().createHash(data.estConfig.passphrase, appCfg.SALT_ROUNDS); const hashedPassphrase = await crypto.hashing().createHash(data.estConfig.passphraseInput, appCfg.SALT_ROUNDS);
let encryptedCaChainBuffer: Buffer; let encryptedCaChainBuffer: Buffer;
try { try {
@@ -243,24 +258,10 @@ export const certificateProfileServiceFactory = ({
existingProfile.estConfigId, existingProfile.estConfigId,
{ {
disableBootstrapCaValidation: estConfig.disableBootstrapCaValidation, disableBootstrapCaValidation: estConfig.disableBootstrapCaValidation,
...(estConfig.passphrase && { ...(estConfig.passphraseInput && {
hashedPassphrase: await crypto.hashing().createHash(estConfig.passphrase, getConfig().SALT_ROUNDS) hashedPassphrase: await crypto.hashing().createHash(estConfig.passphraseInput, getConfig().SALT_ROUNDS)
}), }),
...(estConfig.caChain && ...(estConfig.caChain && validateAndEncodeBase64CaChain(estConfig.caChain))
(() => {
try {
if (typeof estConfig.caChain !== "string") {
throw new BadRequestError({ message: "CA chain must be a string" });
}
const buffer = Buffer.from(estConfig.caChain, "base64");
if (buffer.toString("base64") !== estConfig.caChain) {
throw new BadRequestError({ message: "Invalid Base64 encoding in CA chain data" });
}
return { encryptedCaChain: buffer };
} catch (error) {
throw new BadRequestError({ message: "Failed to decode CA chain data: Invalid Base64 format" });
}
})())
}, },
tx tx
); );
@@ -21,7 +21,7 @@ export type TCertificateProfileUpdate = Omit<TPkiCertificateProfilesUpdate, "enr
enrollmentType?: EnrollmentType; enrollmentType?: EnrollmentType;
estConfig?: { estConfig?: {
disableBootstrapCaValidation?: boolean; disableBootstrapCaValidation?: boolean;
passphrase?: string; passphraseInput?: string;
caChain?: string; caChain?: string;
}; };
apiConfig?: { apiConfig?: {
@@ -10,7 +10,11 @@ import {
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors"; import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type"; import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal"; import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { CertificateOrderStatus } from "@app/services/certificate/certificate-types"; import {
CertificateOrderStatus,
CertKeyAlgorithm,
CertSignatureAlgorithm
} from "@app/services/certificate/certificate-types";
import { import {
TCertificateAuthorityDALFactory, TCertificateAuthorityDALFactory,
TCertificateAuthorityWithAssociatedCa TCertificateAuthorityWithAssociatedCa
@@ -119,6 +123,9 @@ const validateAlgorithmCompatibility = (
const compatibleAlgorithms = const compatibleAlgorithms =
template.algorithms?.signature?.filter((sigAlg: string) => { template.algorithms?.signature?.filter((sigAlg: string) => {
const parts = sigAlg.split("-"); const parts = sigAlg.split("-");
if (parts.length === 0) {
return false;
}
const keyType = parts[parts.length - 1]; const keyType = parts[parts.length - 1];
if (caKeyAlgorithm.startsWith("RSA")) { if (caKeyAlgorithm.startsWith("RSA")) {
@@ -221,8 +228,8 @@ export const certificateV3ServiceFactory = ({
validateAlgorithmCompatibility(ca, template); validateAlgorithmCompatibility(ca, template);
const effectiveSignatureAlgorithm = certificateRequest.signatureAlgorithm; const effectiveSignatureAlgorithm = certificateRequest.signatureAlgorithm as CertSignatureAlgorithm | undefined;
const effectiveKeyAlgorithm = certificateRequest.keyAlgorithm; const effectiveKeyAlgorithm = certificateRequest.keyAlgorithm as CertKeyAlgorithm | undefined;
if (template.algorithms?.keyAlgorithm && !effectiveKeyAlgorithm) { if (template.algorithms?.keyAlgorithm && !effectiveKeyAlgorithm) {
throw new BadRequestError({ throw new BadRequestError({
@@ -350,7 +357,7 @@ export const certificateV3ServiceFactory = ({
caId: ca.id, caId: ca.id,
csr, csr,
ttl: validity.ttl, ttl: validity.ttl,
altNames: "", altNames: undefined,
notBefore: normalizeDateForApi(notBefore), notBefore: normalizeDateForApi(notBefore),
notAfter: normalizeDateForApi(notAfter), notAfter: normalizeDateForApi(notAfter),
signatureAlgorithm: effectiveSignatureAlgorithm, signatureAlgorithm: effectiveSignatureAlgorithm,
@@ -114,6 +114,13 @@ export type TGetCertificateCredentialsDTO = {
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">; kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
}; };
export enum CertSubjectAlternativeNameType {
DNS_NAME = "dns_name",
IP_ADDRESS = "ip_address",
EMAIL = "email",
URI = "uri"
}
export enum TAltNameType { export enum TAltNameType {
EMAIL = "email", EMAIL = "email",
DNS = "dns", DNS = "dns",
@@ -121,12 +128,21 @@ export enum TAltNameType {
URL = "url" URL = "url"
} }
export enum CertSubjectAlternativeNameType { export const mapLegacyAltNameType = (legacyType: TAltNameType): CertSubjectAlternativeNameType => {
DNS_NAME = "dns_name", switch (legacyType) {
IP_ADDRESS = "ip_address", case TAltNameType.EMAIL:
EMAIL = "email", return CertSubjectAlternativeNameType.EMAIL;
URI = "uri" case TAltNameType.DNS:
} return CertSubjectAlternativeNameType.DNS_NAME;
case TAltNameType.IP:
return CertSubjectAlternativeNameType.IP_ADDRESS;
case TAltNameType.URL:
return CertSubjectAlternativeNameType.URI;
default:
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Unknown legacy alt name type: ${legacyType}`);
}
};
export type TAltNameMapping = { export type TAltNameMapping = {
type: TAltNameType; type: TAltNameType;
value: string; value: string;
@@ -52,21 +52,25 @@ export const apiEnrollmentConfigDALFactory = (db: TDbClient) => {
} }
}; };
const findProfilesForAutoRenewal = async (renewalThresholdDays: number = 30, tx?: Knex) => { const findProfilesForAutoRenewal = async (renewalThresholdDays: number = 30, projectId?: string, tx?: Knex) => {
try { try {
const profiles = await (tx || db)(TableName.PkiCertificateProfile) let query = (tx || db)(TableName.PkiCertificateProfile)
.join( .join(
TableName.PkiApiEnrollmentConfig, TableName.PkiApiEnrollmentConfig,
`${TableName.PkiCertificateProfile}.apiConfigId`, `${TableName.PkiCertificateProfile}.apiConfigId`,
`${TableName.PkiApiEnrollmentConfig}.id` `${TableName.PkiApiEnrollmentConfig}.id`
) )
.where(`${TableName.PkiApiEnrollmentConfig}.autoRenew`, true) .where(`${TableName.PkiApiEnrollmentConfig}.autoRenew`, true);
.where((query) => {
void query.where((qb) => { if (projectId) {
void qb query = query.where(`${TableName.PkiCertificateProfile}.projectId`, projectId);
.whereNull(`${TableName.PkiApiEnrollmentConfig}.autoRenewDays`) }
.orWhere(`${TableName.PkiApiEnrollmentConfig}.autoRenewDays`, "<=", renewalThresholdDays);
}); const profiles = await query
.where((qb) => {
void qb
.whereNull(`${TableName.PkiApiEnrollmentConfig}.autoRenewDays`)
.orWhere(`${TableName.PkiApiEnrollmentConfig}.autoRenewDays`, "<=", renewalThresholdDays);
}) })
.select((tx || db).ref("id").withSchema(TableName.PkiCertificateProfile)) .select((tx || db).ref("id").withSchema(TableName.PkiCertificateProfile))
.select((tx || db).ref("name").withSchema(TableName.PkiCertificateProfile)) .select((tx || db).ref("name").withSchema(TableName.PkiCertificateProfile))
@@ -83,7 +87,20 @@ export const apiEnrollmentConfigDALFactory = (db: TDbClient) => {
try { try {
const doc = await (tx || db)(TableName.PkiCertificateProfile).where({ apiConfigId: configId }).count("*").first(); const doc = await (tx || db)(TableName.PkiCertificateProfile).where({ apiConfigId: configId }).count("*").first();
return parseInt((doc as { count?: string })?.count || "0", 10); if (!doc || typeof doc !== "object") {
return 0;
}
const countValue = (doc as Record<string, unknown>).count;
if (typeof countValue === "number") {
return countValue;
}
if (typeof countValue === "string") {
const parsed = parseInt(countValue, 10);
return Number.isNaN(parsed) ? 0 : parsed;
}
return 0;
} catch (error) { } catch (error) {
throw new DatabaseError({ error, name: "Check if API enrollment config is in use" }); throw new DatabaseError({ error, name: "Check if API enrollment config is in use" });
} }
@@ -19,7 +19,7 @@ export type TApiEnrollmentConfigUpdate = TPkiApiEnrollmentConfigsUpdate;
export interface TEstConfigData { export interface TEstConfigData {
disableBootstrapCaValidation: boolean; disableBootstrapCaValidation: boolean;
passphrase: string; passphraseInput: string;
encryptedCaChain: string; encryptedCaChain: string;
} }
@@ -129,7 +129,8 @@ export enum ProjectPermissionCertificateProfileActions {
Create = "create", Create = "create",
Edit = "edit", Edit = "edit",
Delete = "delete", Delete = "delete",
IssueCert = "issue-cert" IssueCert = "issue-cert",
ListCerts = "list-certs"
} }
export enum ProjectPermissionSecretRotationActions { export enum ProjectPermissionSecretRotationActions {
@@ -176,7 +176,7 @@ export const PkiManagerLayout = () => {
}} }}
> >
{({ isActive }) => ( {({ isActive }) => (
<MenuItem isSelected={isActive}> <MenuItem isSelected={isActive} variant="project">
<div className="mx-1 flex gap-2"> <div className="mx-1 flex gap-2">
<div className="w-6"> <div className="w-6">
<FontAwesomeIcon icon={faSitemap} /> <FontAwesomeIcon icon={faSitemap} />
@@ -195,7 +195,7 @@ export const PkiManagerLayout = () => {
}} }}
> >
{({ isActive }) => ( {({ isActive }) => (
<MenuItem isSelected={isActive}> <MenuItem isSelected={isActive} variant="project">
<div className="mx-1 flex gap-2"> <div className="mx-1 flex gap-2">
<div className="w-6"> <div className="w-6">
<FontAwesomeIcon icon={faFileLines} /> <FontAwesomeIcon icon={faFileLines} />
@@ -140,8 +140,8 @@ export const CaModal = ({ popUp, handlePopUpToggle }: Props) => {
maxPathLength: ca.configuration.maxPathLength maxPathLength: ca.configuration.maxPathLength
? String(ca.configuration.maxPathLength) ? String(ca.configuration.maxPathLength)
: "", : "",
keyAlgorithm: (Object.values(CertKeyAlgorithm) as string[]).includes( keyAlgorithm: Object.values(CertKeyAlgorithm).includes(
ca.configuration.keyAlgorithm ca.configuration.keyAlgorithm as CertKeyAlgorithm
) )
? ca.configuration.keyAlgorithm ? ca.configuration.keyAlgorithm
: CertKeyAlgorithm.RSA_2048 : CertKeyAlgorithm.RSA_2048
@@ -25,7 +25,7 @@ export const CertificatesSection = () => {
const { subscription } = useSubscription(); const { subscription } = useSubscription();
const { mutateAsync: deleteCert } = useDeleteCert(); const { mutateAsync: deleteCert } = useDeleteCert();
const useOldCertificateFlow = subscription.pkiLegacyTemplates; const isLegacyTemplatesEnabled = subscription.pkiLegacyTemplates;
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([ const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"certificateIssuance", "certificateIssuance",
@@ -80,7 +80,7 @@ export const CertificatesSection = () => {
type="submit" type="submit"
leftIcon={<FontAwesomeIcon icon={faPlus} />} leftIcon={<FontAwesomeIcon icon={faPlus} />}
onClick={() => onClick={() =>
handlePopUpOpen(useOldCertificateFlow ? "certificate" : "certificateIssuance") handlePopUpOpen(isLegacyTemplatesEnabled ? "certificate" : "certificateIssuance")
} }
isDisabled={!isAllowed} isDisabled={!isAllowed}
> >
@@ -91,7 +91,7 @@ export const CertificatesSection = () => {
</ProjectPermissionCan> </ProjectPermissionCan>
</div> </div>
<CertificatesTable handlePopUpOpen={handlePopUpOpen} /> <CertificatesTable handlePopUpOpen={handlePopUpOpen} />
{useOldCertificateFlow ? ( {isLegacyTemplatesEnabled ? (
<CertificateModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} /> <CertificateModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
) : ( ) : (
<CertificateIssuanceModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} /> <CertificateIssuanceModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
@@ -22,7 +22,7 @@ export const PkiSubscriberSection = () => {
const { subscription } = useSubscription(); const { subscription } = useSubscription();
const projectId = currentProject.id; const projectId = currentProject.id;
const allowNewSubscriberCreation = subscription.pkiLegacyTemplates; const canCreateLegacySubscribers = subscription.pkiLegacyTemplates;
const { mutateAsync: deletePkiSubscriber } = useDeletePkiSubscriber(); const { mutateAsync: deletePkiSubscriber } = useDeletePkiSubscriber();
const { mutateAsync: updatePkiSubscriber } = useUpdatePkiSubscriber(); const { mutateAsync: updatePkiSubscriber } = useUpdatePkiSubscriber();
@@ -104,7 +104,7 @@ export const PkiSubscriberSection = () => {
/> />
</span> </span>
</a> </a>
{allowNewSubscriberCreation && ( {canCreateLegacySubscribers && (
<ProjectPermissionCan <ProjectPermissionCan
I={ProjectPermissionPkiSubscriberActions.Create} I={ProjectPermissionPkiSubscriberActions.Create}
a={ProjectPermissionSub.PkiSubscribers} a={ProjectPermissionSub.PkiSubscribers}
@@ -1,4 +1,3 @@
/* eslint-disable no-nested-ternary */
import { useCallback } from "react"; import { useCallback } from "react";
import { import {
faCheck, faCheck,
@@ -34,6 +33,59 @@ import { TCertificateProfile } from "@app/hooks/api/certificateProfiles";
import { useGetCertificateTemplateV2ById } from "@app/hooks/api/certificateTemplates/queries"; import { useGetCertificateTemplateV2ById } from "@app/hooks/api/certificateTemplates/queries";
import { CertificateIssuanceModal } from "@app/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal"; import { CertificateIssuanceModal } from "@app/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal";
const MetricsBadges = ({
metrics
}: {
metrics?: {
totalCertificates: number;
activeCertificates: number;
expiringCertificates: number;
expiredCertificates: number;
revokedCertificates: number;
};
}) => {
if (!metrics) {
return (
<Badge variant="primary" className="text-xs">
No metrics
</Badge>
);
}
if (metrics.totalCertificates === 0) {
return (
<Badge variant="primary" className="text-xs">
No certificates
</Badge>
);
}
return (
<>
{metrics.activeCertificates > 0 && (
<Badge variant="success" className="text-xs">
{metrics.activeCertificates} active
</Badge>
)}
{metrics.expiringCertificates > 0 && (
<Badge variant="primary" className="text-xs">
{metrics.expiringCertificates} expiring
</Badge>
)}
{metrics.expiredCertificates > 0 && (
<Badge variant="danger" className="text-xs">
{metrics.expiredCertificates} expired
</Badge>
)}
{metrics.revokedCertificates > 0 && (
<Badge variant="danger" className="text-xs">
{metrics.revokedCertificates} revoked
</Badge>
)}
</>
);
};
interface Props { interface Props {
profile: TCertificateProfile; profile: TCertificateProfile;
onEditProfile: (profile: TCertificateProfile) => void; onEditProfile: (profile: TCertificateProfile) => void;
@@ -58,11 +110,8 @@ export const ProfileRow = ({ profile, onEditProfile, onDeleteProfile }: Props) =
type: "info" type: "info"
}); });
const timer = setTimeout(() => setIsIdCopied.off(), 2000); setTimeout(() => setIsIdCopied.off(), 2000);
}, [setIsIdCopied]);
// eslint-disable-next-line consistent-return
return () => clearTimeout(timer);
}, [isIdCopied, setIsIdCopied]);
const { data: templateData } = useGetCertificateTemplateV2ById({ const { data: templateData } = useGetCertificateTemplateV2ById({
templateId: profile.certificateTemplateId templateId: profile.certificateTemplateId
@@ -122,40 +171,7 @@ export const ProfileRow = ({ profile, onEditProfile, onDeleteProfile }: Props) =
</Td> </Td>
<Td> <Td>
<div className="flex flex-wrap gap-1"> <div className="flex flex-wrap gap-1">
{profile.metrics ? ( <MetricsBadges metrics={profile.metrics} />
profile.metrics.totalCertificates === 0 ? (
<Badge variant="primary" className="text-xs">
No certificates
</Badge>
) : (
<>
{profile.metrics.activeCertificates > 0 && (
<Badge variant="success" className="text-xs">
{profile.metrics.activeCertificates} active
</Badge>
)}
{profile.metrics.expiringCertificates > 0 && (
<Badge variant="primary" className="text-xs">
{profile.metrics.expiringCertificates} expiring
</Badge>
)}
{profile.metrics.expiredCertificates > 0 && (
<Badge variant="danger" className="text-xs">
{profile.metrics.expiredCertificates} expired
</Badge>
)}
{profile.metrics.revokedCertificates > 0 && (
<Badge variant="danger" className="text-xs">
{profile.metrics.revokedCertificates} revoked
</Badge>
)}
</>
)
) : (
<Badge variant="primary" className="text-xs">
No metrics
</Badge>
)}
</div> </div>
</Td> </Td>
<Td className="text-right"> <Td className="text-right">
@@ -6,7 +6,7 @@ import { createNotification } from "@app/components/notifications";
import { Button, DeleteActionModal } from "@app/components/v2"; import { Button, DeleteActionModal } from "@app/components/v2";
import { useProjectPermission } from "@app/context"; import { useProjectPermission } from "@app/context";
import { import {
ProjectPermissionActions, ProjectPermissionPkiTemplateActions,
ProjectPermissionSub ProjectPermissionSub
} from "@app/context/ProjectPermissionContext/types"; } from "@app/context/ProjectPermissionContext/types";
import { useDeleteCertificateTemplateV2New } from "@app/hooks/api/certificateTemplates/mutations"; import { useDeleteCertificateTemplateV2New } from "@app/hooks/api/certificateTemplates/mutations";
@@ -26,8 +26,8 @@ export const CertificateTemplatesV2Tab = () => {
const deleteTemplateV2 = useDeleteCertificateTemplateV2New(); const deleteTemplateV2 = useDeleteCertificateTemplateV2New();
const canCreateTemplate = permission.can( const canCreateTemplate = permission.can(
ProjectPermissionActions.Create, ProjectPermissionPkiTemplateActions.Create,
ProjectPermissionSub.CertificateAuthorities ProjectPermissionSub.CertificateTemplates
); );
const handleCreateTemplate = () => { const handleCreateTemplate = () => {
@@ -42,6 +42,10 @@ export const TemplateList = ({ onEditTemplate, onDeleteTemplate }: Props) => {
const templates = data?.certificateTemplates || []; const templates = data?.certificateTemplates || [];
if (!currentProject?.id) {
return null;
}
const canEditTemplate = permission.can( const canEditTemplate = permission.can(
ProjectPermissionPkiTemplateActions.Edit, ProjectPermissionPkiTemplateActions.Edit,
ProjectPermissionSub.CertificateTemplates ProjectPermissionSub.CertificateTemplates
@@ -114,17 +114,7 @@ export const apiTemplateSchema = z.object({
.object({ .object({
max: z max: z
.string() .string()
.refine((val) => { .regex(/^[1-9]\d*[dhmy]$/, "Must be in format like '365d', '12m', '1y', or '24h'")
if (!val) return true;
if (val.length < 2 || val.length > 10) return false;
const lastChar = val.slice(-1);
if (!["d", "h", "m", "y"].includes(lastChar)) return false;
const numberPart = val.slice(0, -1);
const num = parseInt(numberPart, 10);
return !Number.isNaN(num) && num > 0 && numberPart === num.toString();
}, "Must be in format like '365d', '12m', '1y', or '24h'")
.optional() .optional()
}) })
.optional() .optional()