misc: improved docs and added support for curl clients

This commit is contained in:
Sheen Capadngan
2024-08-27 02:05:35 +08:00
parent 00f86cfd00
commit 0809da33e0
6 changed files with 27 additions and 18 deletions
@@ -11,7 +11,15 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
// add support for CSR bodies
server.addContentTypeParser("application/pkcs10", { parseAs: "string" }, (_, body, done) => {
try {
done(null, (body as string).replace(/\n/g, "").replace(/ /g, ""));
let csrBody = body as string;
// some EST clients send CSRs in PEM format and some in base64 format
// for CSRs sent in PEM, we leave them as is
// for CSRs sent in base64, we preprocess them to remove new lines and spaces
if (!csrBody.includes("BEGIN CERTIFICATE REQUEST")) {
csrBody = csrBody.replace(/\n/g, "").replace(/ /g, "");
}
done(null, csrBody);
} catch (err) {
const error = err as Error;
done(error, undefined);
@@ -16,7 +16,9 @@ export const convertRawCertsToPkcs7 = (rawCertificate: ArrayBuffer[]) => {
});
const derBuffer = cmsContent.toSchema().toBER(false);
const base64Pkcs7 = Buffer.from(derBuffer).toString("base64");
const base64Pkcs7 = Buffer.from(derBuffer)
.toString("base64")
.replace(/(.{64})/g, "$1\n"); // we add a linebreak for CURL clients
return base64Pkcs7;
};
@@ -158,7 +158,9 @@ export const certificateEstServiceFactory = ({
return new x509.X509Certificate(cert);
});
if (!caCerts) throw new BadRequestError({ message: "Failed to parse certificate chain" });
if (!caCerts) {
throw new BadRequestError({ message: "Failed to parse certificate chain" });
}
const leafCertificate = decodeURIComponent(sslClientCert).match(
/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g
@@ -213,14 +215,11 @@ export const certificateEstServiceFactory = ({
.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g)
?.map((cert) => new x509.X509Certificate(cert));
if (!certificates) throw new BadRequestError({ message: "Failed to parse certificate chain" });
const caCertificate = new x509.X509Certificate(caCert);
if (!(await isCertChainValid([caCertificate, ...certificates]))) {
throw new BadRequestError({ message: "Invalid certificate chain" });
if (!certificates) {
throw new BadRequestError({ message: "Failed to parse certificate chain" });
}
const caCertificate = new x509.X509Certificate(caCert);
return convertRawCertsToPkcs7([caCertificate.rawData, ...certificates.map((cert) => cert.rawData)]);
};
@@ -30,11 +30,6 @@ export const isCertChainValid = async (certificates: x509.X509Certificate[]) =>
return true;
}
// check for self-signed
if (certificates.length === 2 && certificates[0].equal(certificates[1])) {
return true;
}
const leafCert = certificates[0];
const chain = new x509.X509ChainBuilder({
certificates: certificates.slice(1)