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
.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(),
@@ -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(),
@@ -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 =
@@ -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);
@@ -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")
}
};
@@ -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
);
@@ -21,7 +21,7 @@ export type TCertificateProfileUpdate = Omit<TPkiCertificateProfilesUpdate, "enr
enrollmentType?: EnrollmentType;
estConfig?: {
disableBootstrapCaValidation?: boolean;
passphrase?: string;
passphraseInput?: string;
caChain?: string;
};
apiConfig?: {
@@ -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,
@@ -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;
@@ -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" });
}
@@ -19,7 +19,7 @@ export type TApiEnrollmentConfigUpdate = TPkiApiEnrollmentConfigsUpdate;
export interface TEstConfigData {
disableBootstrapCaValidation: boolean;
passphrase: string;
passphraseInput: string;
encryptedCaChain: string;
}