Skip to content

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

chore(pki): trim comments in PKCS#12 keystore import

Saifd449024d0439
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 2a35fd28fa..6820a29456 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -3128,7 +3128,6 @@ interface ExtractCertPkcs12 {
type: EventType.EXTRACT_CERT_PKCS12;
metadata: {
entryCount: number;
- // Truncated: these come from the uploaded keystore, not from us.
subjects: string[];
applicationId?: string;
};
diff --git a/backend/src/server/config/rateLimiter.ts b/backend/src/server/config/rateLimiter.ts
index 16fa767a83..8e1360a22d 100644
--- a/backend/src/server/config/rateLimiter.ts
+++ b/backend/src/server/config/rateLimiter.ts
@@ -99,9 +99,7 @@ export const invalidateCacheLimit: RateLimitOptions = {
keyGenerator: (req) => req.realIp
};
-// Opening a PKCS#12 keystore is CPU work whose cost the uploaded file chooses, through its
-// key-derivation round count. A worker and a timeout keep any single request bounded; this keeps a
-// caller from spending the extraction workers back to back.
+// Opening a keystore is CPU work whose cost the uploaded file chooses
export const pkcs12ExtractionLimit: RateLimitOptions = {
timeWindow: 60 * 1000,
hook: "preValidation",
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index 533c8595de..652a49eccf 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -1591,13 +1591,9 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
}
});
- // Reads an uploaded keystore and returns what is inside it; it stores nothing. This is an action
- // rather than a resource, so it deviates from REST deliberately, in the same way as its
- // neighbours /import-certificate and /:id/revoke.
+ // An action rather than a resource, so a deliberate REST deviation, as with /import-certificate.
server.route({
method: "POST",
- // A keystore is small, but base64 plus the JSON envelope still clears Fastify's 1MB default,
- // which would reject the body before schema validation could name the problem.
bodyLimit: MAX_PKCS12_BODY_LIMIT_BYTES,
url: "/pkcs12/extract",
config: {
@@ -1611,7 +1607,6 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
description: "Read the certificates and private keys held in a PKCS#12 keystore",
body: z.object({
pkcs12: createBase64Schema("pkcs12", MAX_PKCS12_BYTES).describe(CERTIFICATES.EXTRACT_PKCS12.pkcs12),
- // Keystores exported without a password are common, so an empty string is valid here.
password: z.string().max(1024).describe(CERTIFICATES.EXTRACT_PKCS12.password),
applicationId: z.string().trim().uuid().optional().describe(CERTIFICATES.EXTRACT_PKCS12.applicationId)
}),
diff --git a/backend/src/services/certificate/certificate-pkcs12-fixtures.ts b/backend/src/services/certificate/certificate-pkcs12-fixtures.ts
index 924f2ae1c5..2a5c404b67 100644
--- a/backend/src/services/certificate/certificate-pkcs12-fixtures.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-fixtures.ts
@@ -1,20 +1,7 @@
/* eslint-disable */
-// Base64 PKCS#12 keystores used by certificate-pkcs12-fns.test.ts. Regenerate with openssl 3.x and
-// keytool. Passwords differ per keystore and are declared alongside each one in the test.
-//
-// # a two-level CA, a leaf, and the keystores built from them
-// openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 3650 -subj "/CN=Test Root CA"
-// openssl req -newkey rsa:2048 -nodes -keyout int.key -out int.csr -subj "/CN=Test Intermediate CA"
-// openssl x509 -req -in int.csr -CA ca.crt -CAkey ca.key -days 1825 -out int.crt \
-// -extfile <(printf "basicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign")
-// openssl pkcs12 -export -inkey leaf.key -in leaf.crt -certfile chain.pem -out rsa-modern.p12 # AES-256/PBES2
-// openssl pkcs12 -export -legacy ... # RC2-40/3DES
-// openssl pkcs12 -export -nomac ... # no integrity MAC
-// openssl pkcs12 -export -iter 5000000 ... # hostile
-// keytool -importkeystore ... # multi-entry; -genseckey adds the secret key entry
-//
-// The keystores are committed rather than generated at test time so the suite needs no openssl,
-// no keytool and no key generation to run.
+// Committed rather than generated so the suite needs no openssl, keytool or key generation.
+// Regenerate with openssl 3.x (-legacy for RC2-40/3DES, -nomac for no integrity MAC, -iter 5000000
+// for the hostile one) and keytool (-importkeystore for multi-entry, -genseckey for the secret key).
export const rsaModern =
"MIIJ9wIBAzCCCaUGCSqGSIb3DQEHAaCCCZYEggmSMIIJjjCCA/oGCSqGSIb3DQEHBqCCA+swggPnAgEAMIID4AYJKoZIhvcNAQcBMF8GCSqGSI" +
diff --git a/backend/src/services/certificate/certificate-pkcs12-fns.test.ts b/backend/src/services/certificate/certificate-pkcs12-fns.test.ts
index ce8825013f..30db1a0010 100644
--- a/backend/src/services/certificate/certificate-pkcs12-fns.test.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-fns.test.ts
@@ -40,7 +40,6 @@ describe("extractPkcs12Entries", () => {
expect(entries).toHaveLength(1);
expect(entries[0].keyAlgorithm).toBe("ECDSA P-256");
- // The proof that the ASN.1 fallback produced usable material rather than a plausible blob.
expect(() => crypto.createPrivateKey(entries[0].privateKeyPem ?? "")).not.toThrow();
});
@@ -71,7 +70,6 @@ describe("extractPkcs12Entries chain building", () => {
const { entries } = await extract(fixtures.sharedCaBundle, "test");
expect(entries).toHaveLength(2);
- // Consuming certificates globally would leave the second entry chainless.
entries.forEach((entry) => {
expect(countCertsIn(entry.chainPem ?? "")).toBe(2);
expect(entry.chainWarning).toBeNull();
@@ -79,7 +77,6 @@ describe("extractPkcs12Entries chain building", () => {
});
test("picks the issuer that signed, not the one whose name matches", async () => {
- // Two intermediates share a subject name; only one signed the leaf.
const { entries } = await extract(fixtures.renewedCa, "test");
expect(entries).toHaveLength(1);
@@ -88,7 +85,6 @@ describe("extractPkcs12Entries chain building", () => {
});
test("imports a keystore of certificates with no private keys, like the PEM form does", async () => {
- // The PEM form accepts a certificate without a key, so a trust store is not an error here.
const { entries } = await extract(fixtures.truststore, "changeit");
expect(entries.length).toBeGreaterThan(0);
@@ -99,9 +95,6 @@ describe("extractPkcs12Entries chain building", () => {
});
test("returns an expired certificate without its chain, and says why", async () => {
- // The import endpoint verifies the leaf against its issuer including validity dates, so an
- // expired certificate sent with a chain is always rejected. Returning it alone is the only
- // form of it that imports.
const { entries } = await extract(fixtures.expiredLeaf, "test");
expect(entries).toHaveLength(1);
@@ -111,9 +104,6 @@ describe("extractPkcs12Entries chain building", () => {
});
test("drops the chain when an issuer in it has expired, not just the leaf", async () => {
- // The import endpoint date-checks every certificate whose signature it verifies, which includes
- // chain members. A valid leaf under an expired intermediate would otherwise come back with a
- // chain that import always rejects as a broken trust chain.
const { entries } = await extract(fixtures.expiredIntermediate, "test");
expect(entries).toHaveLength(1);
@@ -131,8 +121,6 @@ describe("extractPkcs12Entries chain building", () => {
});
test("collapses the same pair stored under two aliases", async () => {
- // keytool happily holds one key and certificate under several aliases. Returning it twice would
- // give two entries the same fingerprint, which the dialog uses as the identity of a row.
const { entries } = await extract(fixtures.duplicateAliases, "changeit");
expect(entries).toHaveLength(1);
@@ -149,9 +137,7 @@ describe("extractPkcs12Entries chain building", () => {
});
describe("extractPkcs12Entries produces entries the import endpoint accepts", () => {
- // Extraction is only useful if what comes out survives importCert's own validation. These mirror
- // the checks in certificate-service.ts: the chain is verified link by link *including validity
- // dates*, and the private key has to sign something the certificate can verify.
+ // Mirrors importCert's own validation.
const splitPem = (pem: string) => pem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ?? [];
const assertImportable = async (entry: { certificatePem: string; chainPem?: string; privateKeyPem?: string }) => {
@@ -200,8 +186,6 @@ describe("extractPkcs12Entries failures", () => {
});
test("reports a wrong password on a MAC-less keystore as a password problem too", async () => {
- // Without an integrity MAC the failure surfaces as an ASN.1 error, which must not be reported
- // to the user as a corrupt file.
await expectFailure(fixtures.noMac, "not-the-password", Pkcs12ErrorCode.BadPassword);
});
@@ -210,7 +194,6 @@ describe("extractPkcs12Entries failures", () => {
});
test("reports entry types we cannot read, rather than failing as corrupt", async () => {
- // A keytool keystore carrying a secret key alongside its key pairs.
await expectFailure(fixtures.secretKeyBag, "changeit", Pkcs12ErrorCode.UnsupportedEntries);
});
});
diff --git a/backend/src/services/certificate/certificate-pkcs12-fns.ts b/backend/src/services/certificate/certificate-pkcs12-fns.ts
index 1912abc5cd..df5876c6f1 100644
--- a/backend/src/services/certificate/certificate-pkcs12-fns.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-fns.ts
@@ -4,12 +4,8 @@ import * as x509 from "@peculiar/x509";
import forge from "node-forge";
import RE2 from "re2";
-// This module is loaded inside a worker thread, so it must not reach into services, DALs or
-// anything that touches config at import time. Keep the imports above to leaf libraries only.
-
-// Deliberately a const object rather than an enum: this module is loaded by the extraction worker,
-// which in development is read straight off disk by Node's type stripping. That rejects enums and
-// anything else non-erasable.
+// The extraction worker imports this module directly, and in development Node strips its types
+// without a compiler: no enums or other non-erasable TypeScript anywhere this module reaches.
export const Pkcs12ErrorCode = {
NotAKeystore: "not_a_keystore",
BadPassword: "bad_password",
@@ -45,8 +41,6 @@ export type TPkcs12Entry = {
chainWarning: string | null;
certificatePem: string;
chainPem?: string;
- // Absent for a keystore that holds certificates only, which imports the same way a certificate
- // pasted into the PEM form without a key does.
privateKeyPem?: string;
};
@@ -58,13 +52,8 @@ const MAX_KEY_BAGS = 20;
const MAX_CERT_BAGS = 100;
const MAX_CHAIN_DEPTH = 10;
-// Every reason a chain is missing leads to the same outcome, so they read the same. Which reason it
-// was stays in the shape of the result: no chainPem.
const CHAIN_WARNING = "No usable issuer chain was found in the keystore, so this will be imported on its own.";
-// Subject and serial come from the uploaded file and have no useful bound of their own. A
-// certificate with dozens of subject attributes would otherwise fail the response schema, which
-// surfaces as a 500 rather than as anything the caller can act on.
const MAX_SUBJECT_LENGTH = 2048;
const MAX_SERIAL_LENGTH = 256;
const MAX_ALIAS_LENGTH = 1024;
@@ -76,11 +65,8 @@ const bagAttribute = (bag: forge.pkcs12.Bag, name: "friendlyName" | "localKeyId"
return values?.length ? values[0] : null;
};
-/**
- * forge cannot build key or certificate objects for EC (and anything else non-RSA): it leaves
- * `bag.key` / `bag.cert` null and hands back the decrypted ASN.1 instead. Reading the ASN.1 is
- * what makes EC, Ed25519 and PQC keystores work, so never consume the parsed objects directly.
- */
+// forge leaves `bag.key` / `bag.cert` null for anything non-RSA and hands back the decrypted ASN.1
+// instead, so never consume its parsed objects: the ASN.1 is what makes EC, Ed25519 and PQC work.
const certBagToPem = (bag: forge.pkcs12.Bag) => {
const asn1 = bag.cert ? forge.pki.certificateToAsn1(bag.cert) : bag.asn1;
if (!asn1) return null;
@@ -88,8 +74,6 @@ const certBagToPem = (bag: forge.pkcs12.Bag) => {
};
const keyBagToPem = (bag: forge.pkcs12.Bag) => {
- // bag.asn1 is already a PKCS#8 PrivateKeyInfo; an RSA key parsed into an object has to be
- // wrapped back into one so both paths hand out the same PEM type.
const asn1 = bag.asn1 ?? (bag.key ? forge.pki.wrapRsaPrivateKey(forge.pki.privateKeyToAsn1(bag.key)) : null);
if (!asn1) return null;
return toPem("PRIVATE KEY", forge.asn1.toDer(asn1).getBytes());
@@ -123,10 +107,6 @@ const EC_CURVE_LABELS: Record<string, string> = {
secp256k1: "secp256k1"
};
-/**
- * Label the key from the private key object rather than from the certificate's WebCrypto
- * algorithm name, which reads as "RSASSA-PKCS1-v1_5" and degrades to a bare OID for PQC.
- */
const describeKey = (key: crypto.KeyObject) => {
const type = key.asymmetricKeyType ?? "unknown";
const details = key.asymmetricKeyDetails;
@@ -166,8 +146,6 @@ const parseCertBags = (certBags: forge.pkcs12.Bag[]) => {
try {
const cert = new x509.X509Certificate(pem);
const fingerprint = sha256Fingerprint(Buffer.from(cert.rawData));
- // keytool writes one copy of each CA certificate per entry, so the same certificate shows
- // up several times in a bundle.
if (!byFingerprint.has(fingerprint)) {
byFingerprint.set(fingerprint, {
pem,
@@ -178,8 +156,7 @@ const parseCertBags = (certBags: forge.pkcs12.Bag[]) => {
});
}
} catch {
- // A certificate we cannot parse is not something we can import; the keystore's other
- // entries are still usable.
+ // A malformed entry must not fail the rest.
}
});
@@ -213,25 +190,15 @@ const parseKeyBags = (keyBags: forge.pkcs12.Bag[]) => {
return keys;
};
-/**
- * Pair on the public key rather than on localKeyId. A mangled or duplicated localKeyId otherwise
- * pairs a key with the wrong certificate, which only surfaces later as a confusing "private key
- * does not match certificate" at import. localKeyId is used only to break ties.
- */
const findLeafForKey = (key: TParsedKey, certs: TParsedCert[]) => {
const matches = certs.filter((c) => Buffer.from(c.cert.publicKey.rawData).toString("hex") === key.spki);
if (matches.length <= 1) return matches[0] ?? null;
return matches.find((c) => c.localKeyId && c.localKeyId === key.localKeyId) ?? matches[0];
};
-/**
- * Walk from the leaf to the root by signature, not by matching issuer and subject names. A
- * keystore that has been through a CA renewal carries two intermediates with the same subject and
- * different keys, and picking by name silently produces a chain that fails verification at import.
- *
- * `signatureOnly` is required: the default also checks validity dates, so an expired certificate
- * would lose its chain entirely.
- */
+// Issuers are matched by signature, not by name: a keystore that has been through a CA renewal
+// carries two intermediates with the same subject, and picking by name builds a chain that fails at
+// import. `signatureOnly` matters too, or an expired certificate loses its chain here.
const buildChain = async (leaf: TParsedCert, certs: TParsedCert[]) => {
const chain: TParsedCert[] = [];
const visited = new Set<string>([leaf.fingerprint]);
@@ -242,7 +209,6 @@ const buildChain = async (leaf: TParsedCert, certs: TParsedCert[]) => {
const subject = current;
if (subject.cert.subject === subject.cert.issuer) break;
- // Name matches first: this only orders the search, the signature decides.
const candidates = certs
.filter((c) => !visited.has(c.fingerprint))
.sort((a, b) => {
@@ -255,11 +221,9 @@ const buildChain = async (leaf: TParsedCert, certs: TParsedCert[]) => {
// eslint-disable-next-line no-restricted-syntax
for (const candidate of candidates) {
// eslint-disable-next-line no-await-in-loop
- const signed = await subject.cert.verify({ publicKey: candidate.cert.publicKey, signatureOnly: true }).catch(
- // A key type WebCrypto cannot verify (ML-DSA, secp256k1) is not a failed match, it is an
- // unanswerable question; treat it as no match and let the caller warn.
- () => false
- );
+ const signed = await subject.cert
+ .verify({ publicKey: candidate.cert.publicKey, signatureOnly: true })
+ .catch(() => false);
if (signed) {
issuer = candidate;
break;
@@ -298,14 +262,12 @@ export const extractPkcs12Entries = async ({
try {
p12 = forge.pkcs12.pkcs12FromAsn1(asn1, password);
} catch (err) {
- // forge aborts the whole parse on a bag type it does not model (secret keys from keytool, for
- // one). Stripping those bags would mean re-encoding the authSafe, which invalidates the MAC
- // and would let any password through, so the keystore is refused by name instead.
+ // Skipping the bags forge cannot model would mean re-encoding the authSafe, invalidating the
+ // MAC and letting any password through. Refuse the keystore instead.
if (err instanceof Error && err.message.includes("Unsupported PKCS#12 SafeBag type")) {
throw new Pkcs12ExtractionError(Pkcs12ErrorCode.UnsupportedEntries);
}
- // Everything from here on is a decryption failure of some kind. MAC-less keystores surface a
- // wrong password as an ASN.1 error, so this must not be reported as a corrupt file.
+ // A MAC-less keystore surfaces a wrong password as an ASN.1 error, so this is not "corrupt".
throw new Pkcs12ExtractionError(Pkcs12ErrorCode.BadPassword);
}
@@ -326,8 +288,6 @@ export const extractPkcs12Entries = async ({
certificatePem: cert.pem
});
- // A keystore holding only certificates is a trust store. The PEM form accepts a certificate
- // without a private key, so this does too: each certificate becomes its own entry, flat.
if (!keys.length) {
if (keyBags.length) throw new Pkcs12ExtractionError(Pkcs12ErrorCode.NoPairs, keyBags.length);
if (!certs.length) throw new Pkcs12ExtractionError(Pkcs12ErrorCode.NoEntries);
@@ -347,19 +307,14 @@ export const extractPkcs12Entries = async ({
const leaf = findLeafForKey(key, certs);
const pairId = leaf ? `${leaf.fingerprint}:${key.spki}` : null;
- // The same pair stored under two aliases is one certificate; importing it twice would just
- // fail on the duplicate serial.
if (leaf && pairId && !seenPairs.has(pairId)) {
seenPairs.add(pairId);
// eslint-disable-next-line no-await-in-loop
const { chain, truncated } = await buildChain(leaf, certs);
- // The import endpoint verifies each link including validity dates, and it checks the dates of
- // every certificate whose signature it verifies: the leaf and every chain member except the
- // last. An expired certificate in any of those positions makes the whole chain fail there, so
- // the entry is sent on its own instead. The last chain member is only used as a verifying key,
- // so its own expiry does not matter.
+ // importCert date-checks every certificate whose signature it verifies, so one expired member
+ // would fail the whole chain. Send the entry on its own instead.
const dateChecked = [leaf, ...chain.slice(0, -1)];
const anyExpired = dateChecked.some((c) => c.cert.notAfter.getTime() < Date.now());
const keepChain = chain.length > 0 && !anyExpired && !truncated;
diff --git a/backend/src/services/certificate/certificate-pkcs12-runner.test.ts b/backend/src/services/certificate/certificate-pkcs12-runner.test.ts
index 332d408d9e..3c738d741e 100644
--- a/backend/src/services/certificate/certificate-pkcs12-runner.test.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-runner.test.ts
@@ -14,9 +14,8 @@ describe("runPkcs12Extraction", () => {
});
test("gives up on a keystore built to be expensive to open", async () => {
- // 2.6KB, five million key-derivation rounds. Parsed inline this blocks the event loop for over
- // a minute, and a wrong password costs the same because the integrity check runs the same
- // derivation, so the bound has to be a wall clock rather than an inspection of the file.
+ // 2.6KB with five million key-derivation rounds, which parsed inline blocks the event loop for
+ // over a minute.
const started = Date.now();
await expect(run(fixtures.hostileIterations, "test")).rejects.toThrow(/takes too long to open/);
diff --git a/backend/src/services/certificate/certificate-pkcs12-runner.ts b/backend/src/services/certificate/certificate-pkcs12-runner.ts
index 7e8fd3f77e..7d347fcac6 100644
--- a/backend/src/services/certificate/certificate-pkcs12-runner.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-runner.ts
@@ -6,24 +6,15 @@ import { logger } from "@app/lib/logger";
import { Pkcs12ErrorCode, TExtractPkcs12Result, TPkcs12ErrorCode } from "./certificate-pkcs12-fns";
-// Two clocks. The keystore only controls how long *decryption* takes, so that is what gets the
-// tight budget. Starting the thread and loading its modules is our cost, not the file's, and on a
-// cold or busy host it can take seconds — charging that to the file produced false "takes too long"
-// failures on ordinary keystores. The startup ceiling is generous and only catches a stuck thread.
+// The uploaded file picks its own decryption cost through its key-derivation round count, and
+// node-forge decrypts synchronously, so extraction runs in a worker under a wall clock. Only
+// decryption gets the tight budget: charging thread startup to the file failed ordinary keystores.
const DECRYPTION_TIMEOUT_MS = 3_000;
const STARTUP_TIMEOUT_MS = 30_000;
const MAX_CONCURRENT_EXTRACTIONS = 2;
-// Queue a little, then refuse. Waiting is not free: each caller holds its keystore in memory for
-// the whole wait, and a queue that only grows turns a burst into a slow failure for everyone
-// instead of a fast one for the callers past the line.
+// Each waiter holds its keystore in memory for the whole wait.
const MAX_QUEUED_EXTRACTIONS = 8;
-// The keystore itself chooses how much work its own decryption costs, through the PBKDF2 iteration
-// count, and node-forge decrypts synchronously. A 2.6KB keystore built with five million rounds
-// blocks the event loop for over a minute, and a wrong password costs exactly the same because the
-// integrity check runs the same derivation. No pre-flight inspection can bound this: the rounds for
-// a shrouded key bag are inside the encrypted blob and only become readable once the outer layer is
-// already decrypted. So the work runs on a worker with a wall clock, and too many at once queue.
let inFlight = 0;
const waiting: (() => void)[] = [];
@@ -50,16 +41,13 @@ const releaseSlot = () => {
waiting.shift()?.();
};
-// In development the server runs straight off the TypeScript sources; in production it runs the
-// ESM build, where every source file has a sibling .mjs. Anchor on this module's own extension so
-// both resolve without a build-time special case.
+// Dev runs the TypeScript sources, production the ESM build; anchor on this module's own extension.
const isRunningFromSource = __filename.endsWith(".ts");
const moduleExtension = isRunningFromSource ? ".ts" : ".mjs";
const workerPath = path.join(__dirname, `certificate-pkcs12-worker${moduleExtension}`);
const extractionModulePath = path.join(__dirname, `certificate-pkcs12-fns${moduleExtension}`);
-// Loading a .ts file directly makes Node sniff the module type and warn about it on every spawn,
-// which would bury the dev log. The build output is unambiguous, so only silence the source path.
+// Node sniffs the module type of a .ts file and warns on every spawn, burying the dev log.
const workerExecArgv = isRunningFromSource ? ["--no-warnings"] : undefined;
type TWorkerResponse =
diff --git a/backend/src/services/certificate/certificate-pkcs12-worker.ts b/backend/src/services/certificate/certificate-pkcs12-worker.ts
index 03838abbd0..3514199f9a 100644
--- a/backend/src/services/certificate/certificate-pkcs12-worker.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-worker.ts
@@ -2,14 +2,8 @@ import { parentPort, workerData } from "node:worker_threads";
import type { TExtractPkcs12Result } from "./certificate-pkcs12-fns";
-// Runs on a worker thread. Decrypting a PKCS#12 keystore is synchronous CPU work whose cost is
-// chosen inside the uploaded file (the PBKDF2 iteration count), so on the main thread one crafted
-// keystore stalls every other request on the instance for as long as it likes.
-//
-// The extraction module is imported by absolute path supplied by the parent, because the parent is
-// the only side that knows whether it is running from TypeScript sources or from the build output.
-// Keep this file, and everything it pulls in at runtime, free of non-erasable TypeScript: in
-// development Node loads it directly and strips types without a compiler.
+// In development Node loads this file directly and strips its types without a compiler, so keep it
+// free of non-erasable TypeScript.
type TWorkerInput = { pkcs12: string; password: string; modulePath: string };
@@ -23,9 +17,7 @@ type TExtractionModule = {
const run = async () => {
const mod = (await import(modulePath)) as TExtractionModule;
- // Loading this thread's modules is not decryption, and on a busy or cold host it can take
- // seconds. Tell the parent we are ready so its clock measures only the work the keystore
- // controls, instead of blaming the file for a slow start.
+ // Starts the parent's decryption clock, so thread startup is not charged to the file.
parentPort?.postMessage({ ready: true });
try {
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index ad86372dce..ae1f577e5e 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -709,11 +709,6 @@ export const certificateServiceFactory = ({
};
};
- /**
- * Read a PKCS#12 keystore and hand back the certificates, chains and private keys it holds, so
- * the caller can import them. Nothing is stored: this is gated on the same Import permission as
- * the import itself, so it can never reach a keystore the caller could not import anyway.
- */
const extractPkcs12 = async ({
projectId,
applicationId,
diff --git a/frontend/src/hooks/api/certificates/mutations.tsx b/frontend/src/hooks/api/certificates/mutations.tsx
index 19dbecadc9..214831d972 100644
--- a/frontend/src/hooks/api/certificates/mutations.tsx
+++ b/frontend/src/hooks/api/certificates/mutations.tsx
@@ -113,8 +113,6 @@ export const useImportCertificate = () => {
});
};
-// Reads a keystore and hands back its contents for review. Nothing is created, and nothing is
-// cached: the response carries private keys.
export const useExtractPkcs12 = () =>
useMutation<TExtractPkcs12Response, object, TExtractPkcs12DTO>({
meta: { handledErrorCodes: ["BadRequest"] },
@@ -127,10 +125,8 @@ export const useExtractPkcs12 = () =>
}
});
-// Imports the entries chosen from a keystore, one at a time, and reports the outcome of each.
-// It resolves even when some entries fail, because a keystore whose third certificate is already
-// in the project should still import the other two. Failures are returned rather than thrown so
-// the global handler does not raise a toast per entry on top of the summary the dialog renders.
+// Failures are returned rather than thrown, so one bad entry neither aborts the rest nor raises a
+// toast from the global error handler.
export const useImportPkcs12Entries = () => {
const queryClient = useQueryClient();
return useMutation<TImportPkcs12EntriesResult[], object, TImportPkcs12EntriesDTO>({
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
index cdd41d8b0d..2040c493c6 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
@@ -83,8 +83,7 @@ type TImportOutcome = {
error?: string;
};
-// Reading the file in one go and spreading it into String.fromCharCode overflows the call stack
-// around a megabyte, which is inside the size we accept.
+// Spreading the whole buffer into String.fromCharCode overflows the stack near a megabyte.
const toBase64 = (buffer: ArrayBuffer) => {
const bytes = new Uint8Array(buffer);
let binary = "";
@@ -123,9 +122,6 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
resolver: zodResolver(schema)
});
- // Prefilling from a keystore calls reset(values), which makes those values the form's new
- // defaults — so a bare reset() would restore the previous keystore's certificate and private key
- // instead of clearing them.
const clearFields = () => reset({ certificatePem: "", chainPem: "", privateKeyPem: "" });
const resetAll = () => {
@@ -228,8 +224,7 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
const isOpen = Boolean(popUp?.certificateImport?.isOpen);
const wasOpen = useRef(isOpen);
useEffect(() => {
- // Radix fires onOpenChange only for interactions it owns, so a dialog closed by one of our own
- // buttons never reaches the handler below. Clearing on the way in covers every close path.
+ // Radix fires onOpenChange only for its own interactions, so our footer buttons never reach it.
if (isOpen && !wasOpen.current) resetAll();
wasOpen.current = isOpen;
});
@@ -279,8 +274,6 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
const failures = outcomes?.filter((outcome) => outcome.error) ?? [];
- // Every entry the user selected gets a row, and every row carries a description, so a success and
- // a failure are the same shape and nothing is left to infer.
const renderOutcomes = () => (
<ItemGroup className="gap-2">
{outcomes?.map((outcome, index) => (
@@ -394,8 +387,6 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
placeholder="Leave blank if the keystore has no password"
/>
</Field>
- {/* The failure can belong to either field above (a file we cannot read, a password that does
- not open it), so it is reported once for the pair rather than under one of them. */}
{keystoreError && (
<Field data-invalid>
<FieldError>{keystoreError}</FieldError>
@@ -428,7 +419,6 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
if (outcomes) return renderOutcomes();
- // Viewing an existing certificate reuses this dialog, and there is nothing to import then.
if (cert) return renderPemFields();
return (
@@ -443,10 +433,6 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
</form>
</TabsContent>
<TabsContent value="pkcs12">
- {/* One presentation whether the keystore holds one pair or five. The certificates are
- never pushed into the PEM fields: nobody reviews base64, and the table says what each
- certificate actually is. A keystore with nothing importable is refused by the
- endpoint, so there is no empty state to render. */}
{entries ? renderEntriesTable() : renderKeystorePicker()}
</TabsContent>
</Tabs>
@@ -478,7 +464,6 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle, applicationId
const renderFooter = () => {
if (certificateDetails || cert) return null;
- // The keystore step has its own action in the body, and no form for a submit button to target.
if (format === "pkcs12" && !entries) return null;
if (outcomes) {