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

View File

@@ -34,7 +34,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid
estConfig: z
.object({
disableBootstrapCaValidation: z.boolean().default(false),
passphrase: z.string().min(1),
passphraseInput: z.string().min(1),
encryptedCaChain: z.string()
})
.optional(),
@@ -332,7 +332,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid
estConfig: z
.object({
disableBootstrapCaValidation: z.boolean().default(false),
passphrase: z.string().min(1),
passphraseInput: z.string().min(1),
encryptedCaChain: z.string()
})
.optional(),

View File

@@ -26,6 +26,21 @@ import {
import { mapEnumsForValidation } from "@app/services/certificate-common/certificate-utils";
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) => {
server.route({
method: "POST",
@@ -49,30 +64,13 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) =>
signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(),
keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional()
})
.refine(
(data) => {
const hasDateFields = data.notBefore || data.notAfter;
const hasTtl = data.ttl;
return !(hasDateFields && hasTtl);
},
{
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"
}
),
.refine(validateTtlAndDateFields, {
message:
"Cannot specify both TTL and notBefore/notAfter. Use either TTL for duration-based validity or notBefore/notAfter for explicit date range."
})
.refine(validateDateOrder, {
message: "notBefore must be earlier than notAfter"
}),
response: {
200: z.object({
certificate: z.string().trim(),
@@ -169,30 +167,13 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) =>
notBefore: validateCaDateField.optional(),
notAfter: validateCaDateField.optional()
})
.refine(
(data) => {
const hasDateFields = data.notBefore || data.notAfter;
const hasTtl = data.ttl;
return !(hasDateFields && hasTtl);
},
{
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"
}
),
.refine(validateTtlAndDateFields, {
message:
"Cannot specify both TTL and notBefore/notAfter. Use either TTL for duration-based validity or notBefore/notAfter for explicit date range."
})
.refine(validateDateOrder, {
message: "notBefore must be earlier than notAfter"
}),
response: {
200: z.object({
certificate: z.string().trim(),
@@ -266,30 +247,13 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) =>
signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(),
keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional()
})
.refine(
(data) => {
const hasDateFields = data.notBefore || data.notAfter;
const hasTtl = data.ttl;
return !(hasDateFields && hasTtl);
},
{
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"
}
),
.refine(validateTtlAndDateFields, {
message:
"Cannot specify both TTL and notBefore/notAfter. Use either TTL for duration-based validity or notBefore/notAfter for explicit date range."
})
.refine(validateDateOrder, {
message: "notBefore must be earlier than notAfter"
}),
response: {
200: z.object({
orderId: z.string(),

View File

@@ -3,7 +3,12 @@ import { z } from "zod";
import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
import { TProjectPermission } from "@app/lib/types";
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 { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -131,8 +136,8 @@ export type TIssueCertFromCaDTO = {
notAfter?: string;
keyUsages?: CertKeyUsage[];
extendedKeyUsages?: CertExtendedKeyUsage[];
signatureAlgorithm?: string;
keyAlgorithm?: string;
signatureAlgorithm?: CertSignatureAlgorithm;
keyAlgorithm?: CertKeyAlgorithm;
} & Omit<TProjectPermission, "projectId">;
export type TSignCertFromCaDTO =

View File

@@ -94,14 +94,13 @@ export const certificateEstV3ServiceFactory = ({
kmsId: certificateManagerKmsId
});
let decryptedCaChain = "";
if (estConfig.encryptedCaChain) {
decryptedCaChain = (
await kmsDecryptor({
cipherTextBlob: estConfig.encryptedCaChain
})
).toString();
}
const decryptedCaChain = estConfig.encryptedCaChain
? (
await kmsDecryptor({
cipherTextBlob: estConfig.encryptedCaChain
})
).toString()
: "";
const caCerts = extractX509CertFromChain(decryptedCaChain)?.map((cert) => {
return new x509.X509Certificate(cert);
@@ -114,7 +113,7 @@ export const certificateEstV3ServiceFactory = ({
const leafCertificate = extractX509CertFromChain(decodeURIComponent(sslClientCert))?.[0];
if (!leafCertificate) {
throw new BadRequestError({ message: "Missing client certificate" });
throw new UnauthorizedError({ message: "Missing client certificate" });
}
const certObj = new x509.X509Certificate(leafCertificate);

View File

@@ -711,7 +711,7 @@ describe("CertificateProfileService", () => {
certificateTemplateId: "template-123",
estConfig: {
disableBootstrapCaValidation: false,
passphrase: "secret-passphrase",
passphraseInput: "secret-passphrase",
encryptedCaChain: Buffer.from("test-ca-chain-data").toString("base64")
}
};

View File

@@ -27,6 +27,21 @@ import {
TCertificateProfileWithRawMetrics
} 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"> & {
estConfig?: TEstConfigData;
apiConfig?: TApiConfigData;
@@ -125,7 +140,7 @@ export const certificateProfileServiceFactory = ({
if (data.enrollmentType === EnrollmentType.EST && data.estConfig) {
const appCfg = getConfig();
// 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;
try {
@@ -243,24 +258,10 @@ export const certificateProfileServiceFactory = ({
existingProfile.estConfigId,
{
disableBootstrapCaValidation: estConfig.disableBootstrapCaValidation,
...(estConfig.passphrase && {
hashedPassphrase: await crypto.hashing().createHash(estConfig.passphrase, getConfig().SALT_ROUNDS)
...(estConfig.passphraseInput && {
hashedPassphrase: await crypto.hashing().createHash(estConfig.passphraseInput, getConfig().SALT_ROUNDS)
}),
...(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" });
}
})())
...(estConfig.caChain && validateAndEncodeBase64CaChain(estConfig.caChain))
},
tx
);

View File

@@ -21,7 +21,7 @@ export type TCertificateProfileUpdate = Omit<TPkiCertificateProfilesUpdate, "enr
enrollmentType?: EnrollmentType;
estConfig?: {
disableBootstrapCaValidation?: boolean;
passphrase?: string;
passphraseInput?: string;
caChain?: string;
};
apiConfig?: {

View File

@@ -10,7 +10,11 @@ import {
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
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 {
TCertificateAuthorityDALFactory,
TCertificateAuthorityWithAssociatedCa
@@ -119,6 +123,9 @@ const validateAlgorithmCompatibility = (
const compatibleAlgorithms =
template.algorithms?.signature?.filter((sigAlg: string) => {
const parts = sigAlg.split("-");
if (parts.length === 0) {
return false;
}
const keyType = parts[parts.length - 1];
if (caKeyAlgorithm.startsWith("RSA")) {
@@ -221,8 +228,8 @@ export const certificateV3ServiceFactory = ({
validateAlgorithmCompatibility(ca, template);
const effectiveSignatureAlgorithm = certificateRequest.signatureAlgorithm;
const effectiveKeyAlgorithm = certificateRequest.keyAlgorithm;
const effectiveSignatureAlgorithm = certificateRequest.signatureAlgorithm as CertSignatureAlgorithm | undefined;
const effectiveKeyAlgorithm = certificateRequest.keyAlgorithm as CertKeyAlgorithm | undefined;
if (template.algorithms?.keyAlgorithm && !effectiveKeyAlgorithm) {
throw new BadRequestError({
@@ -350,7 +357,7 @@ export const certificateV3ServiceFactory = ({
caId: ca.id,
csr,
ttl: validity.ttl,
altNames: "",
altNames: undefined,
notBefore: normalizeDateForApi(notBefore),
notAfter: normalizeDateForApi(notAfter),
signatureAlgorithm: effectiveSignatureAlgorithm,

View File

@@ -114,6 +114,13 @@ export type TGetCertificateCredentialsDTO = {
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
};
export enum CertSubjectAlternativeNameType {
DNS_NAME = "dns_name",
IP_ADDRESS = "ip_address",
EMAIL = "email",
URI = "uri"
}
export enum TAltNameType {
EMAIL = "email",
DNS = "dns",
@@ -121,12 +128,21 @@ export enum TAltNameType {
URL = "url"
}
export enum CertSubjectAlternativeNameType {
DNS_NAME = "dns_name",
IP_ADDRESS = "ip_address",
EMAIL = "email",
URI = "uri"
}
export const mapLegacyAltNameType = (legacyType: TAltNameType): CertSubjectAlternativeNameType => {
switch (legacyType) {
case TAltNameType.EMAIL:
return CertSubjectAlternativeNameType.EMAIL;
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 = {
type: TAltNameType;
value: string;

View File

@@ -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 {
const profiles = await (tx || db)(TableName.PkiCertificateProfile)
let query = (tx || db)(TableName.PkiCertificateProfile)
.join(
TableName.PkiApiEnrollmentConfig,
`${TableName.PkiCertificateProfile}.apiConfigId`,
`${TableName.PkiApiEnrollmentConfig}.id`
)
.where(`${TableName.PkiApiEnrollmentConfig}.autoRenew`, true)
.where((query) => {
void query.where((qb) => {
void qb
.whereNull(`${TableName.PkiApiEnrollmentConfig}.autoRenewDays`)
.orWhere(`${TableName.PkiApiEnrollmentConfig}.autoRenewDays`, "<=", renewalThresholdDays);
});
.where(`${TableName.PkiApiEnrollmentConfig}.autoRenew`, true);
if (projectId) {
query = query.where(`${TableName.PkiCertificateProfile}.projectId`, projectId);
}
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("name").withSchema(TableName.PkiCertificateProfile))
@@ -83,7 +87,20 @@ export const apiEnrollmentConfigDALFactory = (db: TDbClient) => {
try {
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) {
throw new DatabaseError({ error, name: "Check if API enrollment config is in use" });
}

View File

@@ -19,7 +19,7 @@ export type TApiEnrollmentConfigUpdate = TPkiApiEnrollmentConfigsUpdate;
export interface TEstConfigData {
disableBootstrapCaValidation: boolean;
passphrase: string;
passphraseInput: string;
encryptedCaChain: string;
}

View File

@@ -129,7 +129,8 @@ export enum ProjectPermissionCertificateProfileActions {
Create = "create",
Edit = "edit",
Delete = "delete",
IssueCert = "issue-cert"
IssueCert = "issue-cert",
ListCerts = "list-certs"
}
export enum ProjectPermissionSecretRotationActions {

View File

@@ -176,7 +176,7 @@ export const PkiManagerLayout = () => {
}}
>
{({ isActive }) => (
<MenuItem isSelected={isActive}>
<MenuItem isSelected={isActive} variant="project">
<div className="mx-1 flex gap-2">
<div className="w-6">
<FontAwesomeIcon icon={faSitemap} />
@@ -195,7 +195,7 @@ export const PkiManagerLayout = () => {
}}
>
{({ isActive }) => (
<MenuItem isSelected={isActive}>
<MenuItem isSelected={isActive} variant="project">
<div className="mx-1 flex gap-2">
<div className="w-6">
<FontAwesomeIcon icon={faFileLines} />

View File

@@ -140,8 +140,8 @@ export const CaModal = ({ popUp, handlePopUpToggle }: Props) => {
maxPathLength: ca.configuration.maxPathLength
? String(ca.configuration.maxPathLength)
: "",
keyAlgorithm: (Object.values(CertKeyAlgorithm) as string[]).includes(
ca.configuration.keyAlgorithm
keyAlgorithm: Object.values(CertKeyAlgorithm).includes(
ca.configuration.keyAlgorithm as CertKeyAlgorithm
)
? ca.configuration.keyAlgorithm
: CertKeyAlgorithm.RSA_2048

View File

@@ -25,7 +25,7 @@ export const CertificatesSection = () => {
const { subscription } = useSubscription();
const { mutateAsync: deleteCert } = useDeleteCert();
const useOldCertificateFlow = subscription.pkiLegacyTemplates;
const isLegacyTemplatesEnabled = subscription.pkiLegacyTemplates;
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"certificateIssuance",
@@ -80,7 +80,7 @@ export const CertificatesSection = () => {
type="submit"
leftIcon={<FontAwesomeIcon icon={faPlus} />}
onClick={() =>
handlePopUpOpen(useOldCertificateFlow ? "certificate" : "certificateIssuance")
handlePopUpOpen(isLegacyTemplatesEnabled ? "certificate" : "certificateIssuance")
}
isDisabled={!isAllowed}
>
@@ -91,7 +91,7 @@ export const CertificatesSection = () => {
</ProjectPermissionCan>
</div>
<CertificatesTable handlePopUpOpen={handlePopUpOpen} />
{useOldCertificateFlow ? (
{isLegacyTemplatesEnabled ? (
<CertificateModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
) : (
<CertificateIssuanceModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />

View File

@@ -22,7 +22,7 @@ export const PkiSubscriberSection = () => {
const { subscription } = useSubscription();
const projectId = currentProject.id;
const allowNewSubscriberCreation = subscription.pkiLegacyTemplates;
const canCreateLegacySubscribers = subscription.pkiLegacyTemplates;
const { mutateAsync: deletePkiSubscriber } = useDeletePkiSubscriber();
const { mutateAsync: updatePkiSubscriber } = useUpdatePkiSubscriber();
@@ -104,7 +104,7 @@ export const PkiSubscriberSection = () => {
/>
</span>
</a>
{allowNewSubscriberCreation && (
{canCreateLegacySubscribers && (
<ProjectPermissionCan
I={ProjectPermissionPkiSubscriberActions.Create}
a={ProjectPermissionSub.PkiSubscribers}

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-nested-ternary */
import { useCallback } from "react";
import {
faCheck,
@@ -34,6 +33,59 @@ import { TCertificateProfile } from "@app/hooks/api/certificateProfiles";
import { useGetCertificateTemplateV2ById } from "@app/hooks/api/certificateTemplates/queries";
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 {
profile: TCertificateProfile;
onEditProfile: (profile: TCertificateProfile) => void;
@@ -58,11 +110,8 @@ export const ProfileRow = ({ profile, onEditProfile, onDeleteProfile }: Props) =
type: "info"
});
const timer = setTimeout(() => setIsIdCopied.off(), 2000);
// eslint-disable-next-line consistent-return
return () => clearTimeout(timer);
}, [isIdCopied, setIsIdCopied]);
setTimeout(() => setIsIdCopied.off(), 2000);
}, [setIsIdCopied]);
const { data: templateData } = useGetCertificateTemplateV2ById({
templateId: profile.certificateTemplateId
@@ -122,40 +171,7 @@ export const ProfileRow = ({ profile, onEditProfile, onDeleteProfile }: Props) =
</Td>
<Td>
<div className="flex flex-wrap gap-1">
{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>
)}
<MetricsBadges metrics={profile.metrics} />
</div>
</Td>
<Td className="text-right">

View File

@@ -6,7 +6,7 @@ import { createNotification } from "@app/components/notifications";
import { Button, DeleteActionModal } from "@app/components/v2";
import { useProjectPermission } from "@app/context";
import {
ProjectPermissionActions,
ProjectPermissionPkiTemplateActions,
ProjectPermissionSub
} from "@app/context/ProjectPermissionContext/types";
import { useDeleteCertificateTemplateV2New } from "@app/hooks/api/certificateTemplates/mutations";
@@ -26,8 +26,8 @@ export const CertificateTemplatesV2Tab = () => {
const deleteTemplateV2 = useDeleteCertificateTemplateV2New();
const canCreateTemplate = permission.can(
ProjectPermissionActions.Create,
ProjectPermissionSub.CertificateAuthorities
ProjectPermissionPkiTemplateActions.Create,
ProjectPermissionSub.CertificateTemplates
);
const handleCreateTemplate = () => {

View File

@@ -42,6 +42,10 @@ export const TemplateList = ({ onEditTemplate, onDeleteTemplate }: Props) => {
const templates = data?.certificateTemplates || [];
if (!currentProject?.id) {
return null;
}
const canEditTemplate = permission.can(
ProjectPermissionPkiTemplateActions.Edit,
ProjectPermissionSub.CertificateTemplates

View File

@@ -114,17 +114,7 @@ export const apiTemplateSchema = z.object({
.object({
max: z
.string()
.refine((val) => {
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'")
.regex(/^[1-9]\d*[dhmy]$/, "Must be in format like '365d', '12m', '1y', or '24h'")
.optional()
})
.optional()