Skip to content

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

feature(pki): jks output format

bernie-g8ddaf7a602b1
diff --git a/backend/src/services/certificate/certificate-jks-fns.test.ts b/backend/src/services/certificate/certificate-jks-fns.test.ts
new file mode 100644
index 0000000000..b461f17636
--- /dev/null
+++ b/backend/src/services/certificate/certificate-jks-fns.test.ts
@@ -0,0 +1,313 @@
+/* eslint-disable no-bitwise */
+import crypto, { webcrypto } from "node:crypto";
+
+import * as x509 from "@peculiar/x509";
+import forge from "node-forge";
+
+import {
+ generateJksFromCertificate,
+ generateJksTruststore,
+ getJksChainCertificates,
+ getJksTruststoreCertificates
+} from "./certificate-jks-fns";
+
+x509.cryptoProvider.set(webcrypto as unknown as Crypto);
+
+const issue = (commonName: string, issuer?: { cert: forge.pki.Certificate; key: forge.pki.rsa.PrivateKey }) => {
+ const keys = forge.pki.rsa.generateKeyPair(2048);
+ const cert = forge.pki.createCertificate();
+ cert.publicKey = keys.publicKey;
+ cert.serialNumber = "01";
+ cert.validity.notBefore = new Date(2026, 0, 1);
+ cert.validity.notAfter = new Date(2027, 0, 1);
+ cert.setSubject([{ name: "commonName", value: commonName }]);
+ cert.setIssuer(issuer ? issuer.cert.subject.attributes : [{ name: "commonName", value: commonName }]);
+ cert.sign(issuer?.key ?? keys.privateKey, forge.md.sha256.create());
+ return {
+ cert,
+ key: keys.privateKey,
+ certificate: forge.pki.certificateToPem(cert),
+ privateKey: forge.pki.privateKeyInfoToPem(forge.pki.wrapRsaPrivateKey(forge.pki.privateKeyToAsn1(keys.privateKey)))
+ };
+};
+
+const root = issue("Example Root CA");
+const intermediate = issue("Example Intermediate CA", root);
+const leaf = issue("api.example.com", intermediate);
+const PASSWORD = "changeit";
+
+// Generated by keytool (JDK 21): EC P-256 key under alias "fixture", store and key password "fixture-pass".
+const KEYTOOL_FIXTURE = Buffer.from(
+ "/u3+7QAAAAIAAAABAAAAAQAHZml4dHVyZQAAAaDqvUbzAAAAfTB7MAwGCisGAQQBKgIRAQEEa85lBxPO047apf5vE+Q70kjv1hJI" +
+ "vVuYy176lBXWM5C0pq5uWer4VNHz5S25ZCK7Yzkip67DZpg1kBaSbRYTUxPRfaNRemvdTQBfID+iIg05ULsMiM4uWcMIJ+GJoY/o" +
+ "iqXRRfquM67jRpo5AAAAAQAFWC41MDkAAAFXMIIBUzCB+6ADAgECAggIyWD0SLAoUTAKBggqhkjOPQQDAzAeMRwwGgYDVQQDExNm" +
+ "aXh0dXJlLmV4YW1wbGUuY29tMCAXDTI2MDkyOTAxMTc0OFoYDzIxMjYwOTA1MDExNzQ4WjAeMRwwGgYDVQQDExNmaXh0dXJlLmV4" +
+ "YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEpvjOKJwbb7CHO3P2eA7kxET9VKgloCXf/7iSNDiDLpif5F22PU8z" +
+ "P66TOX/rUp5IryrI1uU22vuOG2i5r1tBZKMhMB8wHQYDVR0OBBYEFH0Fjr3VmXu2GJxb7jL90kdUc164MAoGCCqGSM49BAMDA0cA" +
+ "MEQCIDwxloYbRpEDa+n3eZmBBxfIQsKVOhLNjovucKf+h4TMAiBlMHTBmX3NJMIO5Kt2/QLYbXmak+6tfW6YP6ko4LEH7fl5g6Nw" +
+ "olAes1EqrLjGErvQa1CK",
+ "base64"
+);
+
+type TParsedEntry =
+ | { tag: 1; alias: string; protectedKey: Buffer; chain: Buffer[] }
+ | { tag: 2; alias: string; certificate: Buffer };
+
+const javaPassword = (password: string) => Buffer.from(password, "utf16le").swap16();
+const sha1 = (...parts: Buffer[]) => parts.reduce((h, p) => h.update(p), crypto.createHash("sha1")).digest();
+
+const parseJks = (buf: Buffer, password: string) => {
+ let offset = 0;
+ const u16 = () => {
+ const v = buf.readUInt16BE(offset);
+ offset += 2;
+ return v;
+ };
+ const u32 = () => {
+ const v = buf.readUInt32BE(offset);
+ offset += 4;
+ return v;
+ };
+ const bytes = (n: number) => {
+ const v = buf.subarray(offset, offset + n);
+ offset += n;
+ return v;
+ };
+ const utf = () => bytes(u16()).toString("utf8");
+ const cert = () => {
+ expect(utf()).toBe("X.509");
+ return bytes(u32());
+ };
+
+ expect(u32()).toBe(0xfeedfeed);
+ expect(u32()).toBe(2);
+ const count = u32();
+ const entries: TParsedEntry[] = [];
+ for (let i = 0; i < count; i += 1) {
+ const tag = u32();
+ const alias = utf();
+ bytes(8);
+ if (tag === 1) {
+ const protectedKey = bytes(u32());
+ const chainLength = u32();
+ const chain = Array.from({ length: chainLength }, cert);
+ entries.push({ tag, alias, protectedKey, chain });
+ } else {
+ expect(tag).toBe(2);
+ entries.push({ tag: 2, alias, certificate: cert() });
+ }
+ }
+
+ const expectedDigest = sha1(javaPassword(password), Buffer.from("Mighty Aphrodite", "utf8"), buf.subarray(0, offset));
+ expect(bytes(20).equals(expectedDigest)).toBe(true);
+ expect(offset).toBe(buf.length);
+ return entries;
+};
+
+const recoverPrivateKey = (encryptedPrivateKeyInfo: Buffer, password: string) => {
+ const asn1 = forge.asn1.fromDer(forge.util.createBuffer(encryptedPrivateKeyInfo.toString("binary")));
+ const [algorithm, encryptedData] = asn1.value as forge.asn1.Asn1[];
+ const oid = forge.asn1.derToOid((algorithm.value as forge.asn1.Asn1[])[0].value as string);
+ expect(oid).toBe("1.3.6.1.4.1.42.2.17.1.1");
+
+ const protectedKey = Buffer.from(encryptedData.value as string, "binary");
+ const salt = protectedKey.subarray(0, 20);
+ const encrypted = protectedKey.subarray(20, protectedKey.length - 20);
+ const check = protectedKey.subarray(protectedKey.length - 20);
+ const passwordBytes = javaPassword(password);
+
+ const plain = Buffer.alloc(encrypted.length);
+ let digest = salt;
+ for (let i = 0; i < encrypted.length; i += 1) {
+ if (i % 20 === 0) digest = sha1(passwordBytes, digest);
+ plain[i] = encrypted[i] ^ digest[i % 20];
+ }
+ expect(sha1(passwordBytes, plain).equals(check)).toBe(true);
+ return plain;
+};
+
+const der = (pem: string) => new crypto.X509Certificate(pem).raw;
+
+const privateKeyEntry = (jks: Buffer, password: string) => {
+ const [entry] = parseJks(jks, password);
+ if (entry.tag !== 1) throw new Error("expected a private key entry");
+ return entry;
+};
+
+const expectKeyMatchesCertificate = (pkcs8: Buffer, certificateDer: Buffer) => {
+ const publicKey = crypto
+ .createPublicKey(crypto.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" }))
+ .export({ type: "spki", format: "der" });
+ const certificatePublicKey = new crypto.X509Certificate(certificateDer).publicKey.export({
+ type: "spki",
+ format: "der"
+ });
+ expect(publicKey.equals(certificatePublicKey)).toBe(true);
+};
+
+describe("test parser matches keytool output", () => {
+ test("reads a keystore generated by keytool", () => {
+ const entry = privateKeyEntry(KEYTOOL_FIXTURE, "fixture-pass");
+ expect(entry.alias).toBe("fixture");
+ expect(entry.chain).toHaveLength(1);
+ expectKeyMatchesCertificate(recoverPrivateKey(entry.protectedKey, "fixture-pass"), entry.chain[0]);
+ });
+});
+
+describe("generateJksFromCertificate", () => {
+ test("writes one private key entry holding the key, leaf, and chain", () => {
+ const jks = generateJksFromCertificate({
+ certificate: leaf.certificate,
+ certificateChain: `${intermediate.certificate}\n${root.certificate}`,
+ privateKey: leaf.privateKey,
+ password: PASSWORD,
+ alias: "API.Example.com"
+ });
+
+ const entry = privateKeyEntry(jks, PASSWORD);
+ expect(entry.alias).toBe("api.example.com");
+ expect(entry.chain.map((c) => c.toString("base64"))).toEqual(
+ [leaf, intermediate, root].map((c) => der(c.certificate).toString("base64"))
+ );
+
+ const pkcs8 = crypto.createPrivateKey(leaf.privateKey).export({ type: "pkcs8", format: "der" });
+ expect(recoverPrivateKey(entry.protectedKey, PASSWORD).equals(pkcs8)).toBe(true);
+ });
+
+ test("does not repeat the leaf when the stored chain already contains it", () => {
+ const jks = generateJksFromCertificate({
+ certificate: leaf.certificate,
+ certificateChain: `${leaf.certificate}\n${intermediate.certificate}`,
+ privateKey: leaf.privateKey,
+ password: PASSWORD,
+ alias: "a"
+ });
+
+ expect(privateKeyEntry(jks, PASSWORD).chain).toHaveLength(2);
+ });
+
+ test("encodes non-ASCII passwords as Java chars", () => {
+ const password = "pässwörd-秘密";
+ const jks = generateJksFromCertificate({ ...leaf, password, alias: "a" });
+ recoverPrivateKey(privateKeyEntry(jks, password).protectedKey, password);
+ });
+
+ test("exports an EC key with its certificate", async () => {
+ const keys = (await webcrypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
+ "sign",
+ "verify"
+ ])) as CryptoKeyPair;
+ const cert = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "02",
+ name: "CN=ec.example.com",
+ notBefore: new Date(2026, 0, 1),
+ notAfter: new Date(2027, 0, 1),
+ signingAlgorithm: { name: "ECDSA", hash: "SHA-256" },
+ keys
+ });
+ const pkcs8 = Buffer.from(await webcrypto.subtle.exportKey("pkcs8", keys.privateKey));
+
+ const jks = generateJksFromCertificate({
+ certificate: cert.toString("pem"),
+ privateKey: crypto.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" }).export({
+ type: "pkcs8",
+ format: "pem"
+ }) as string,
+ password: PASSWORD,
+ alias: "ec"
+ });
+
+ const entry = privateKeyEntry(jks, PASSWORD);
+ expectKeyMatchesCertificate(recoverPrivateKey(entry.protectedKey, PASSWORD), entry.chain[0]);
+ });
+
+ test("rejects a private key that does not belong to the certificate", () => {
+ expect(() =>
+ generateJksFromCertificate({
+ certificate: leaf.certificate,
+ privateKey: root.privateKey,
+ password: PASSWORD,
+ alias: "a"
+ })
+ ).toThrow("does not match its public key");
+ });
+
+ test("rejects key types other than RSA and EC", () => {
+ const { privateKey } = crypto.generateKeyPairSync("rsa-pss", { modulusLength: 2048 });
+ expect(() =>
+ generateJksFromCertificate({
+ certificate: leaf.certificate,
+ privateKey: privateKey.export({ type: "pkcs8", format: "pem" }) as string,
+ password: PASSWORD,
+ alias: "a"
+ })
+ ).toThrow("supports RSA and EC keys only");
+ });
+
+ test("requires a non-blank password", () => {
+ expect(() => generateJksFromCertificate({ ...leaf, password: "", alias: "a" })).toThrow("Password is required");
+ expect(() => generateJksFromCertificate({ ...leaf, password: " ", alias: "a" })).toThrow("Password is required");
+ });
+
+ test("reports an unreadable private key", () => {
+ expect(() =>
+ generateJksFromCertificate({ certificate: leaf.certificate, privateKey: "nope", password: PASSWORD, alias: "a" })
+ ).toThrow("private key could not be read");
+ });
+});
+
+describe("getJksChainCertificates", () => {
+ test("drops the leaf and duplicate certificates", () => {
+ expect(
+ getJksChainCertificates(
+ leaf.certificate,
+ `${leaf.certificate}\n${intermediate.certificate}\n${intermediate.certificate}`
+ )
+ ).toEqual([intermediate.certificate.trim()]);
+ });
+});
+
+describe("getJksTruststoreCertificates", () => {
+ test("includes the root from caCertificate when the delivered chain omits it", () => {
+ const trusted = getJksTruststoreCertificates({
+ certificate: leaf.certificate,
+ certificateChain: intermediate.certificate,
+ caCertificate: root.certificate
+ });
+ expect(trusted.map((c) => der(c).toString("base64"))).toEqual(
+ [intermediate, root].map((c) => der(c.certificate).toString("base64"))
+ );
+ });
+
+ test("never trusts the leaf and does not repeat the root", () => {
+ const trusted = getJksTruststoreCertificates({
+ certificate: leaf.certificate,
+ certificateChain: `${leaf.certificate}\n${intermediate.certificate}\n${root.certificate}`,
+ caCertificate: root.certificate
+ });
+ expect(trusted).toHaveLength(2);
+ });
+
+ test("is empty when there is nothing to trust", () => {
+ expect(getJksTruststoreCertificates({ certificate: leaf.certificate, certificateChain: " \n" })).toEqual([]);
+ });
+});
+
+describe("generateJksTruststore", () => {
+ test("writes each certificate as a trusted entry", () => {
+ const jks = generateJksTruststore({
+ trustedCertificates: [intermediate.certificate, root.certificate],
+ password: PASSWORD,
+ alias: "API"
+ });
+
+ const entries = parseJks(jks, PASSWORD);
+ expect(entries.map((e) => [e.tag, e.alias])).toEqual([
+ [2, "api-ca-1"],
+ [2, "api-ca-2"]
+ ]);
+ const [first] = entries;
+ if (first.tag !== 2) throw new Error("expected a trusted certificate entry");
+ expect(first.certificate.equals(der(intermediate.certificate))).toBe(true);
+ });
+});
diff --git a/backend/src/services/certificate/certificate-jks-fns.ts b/backend/src/services/certificate/certificate-jks-fns.ts
new file mode 100644
index 0000000000..9d19ee4bdd
--- /dev/null
+++ b/backend/src/services/certificate/certificate-jks-fns.ts
@@ -0,0 +1,242 @@
+/* eslint-disable no-bitwise */
+import { crypto } from "@app/lib/crypto/cryptography";
+import { BadRequestError } from "@app/lib/errors";
+
+import { splitPemChain } from "./certificate-fns";
+
+const JKS_MAGIC = 0xfeedfeed;
+const JKS_VERSION = 2;
+const JKS_PRIVATE_KEY_TAG = 1;
+const JKS_TRUSTED_CERT_TAG = 2;
+const JKS_CERT_TYPE = "X.509";
+const JKS_INTEGRITY_WHITENER = "Mighty Aphrodite";
+const SHA1_LENGTH = 20;
+const MAX_JKS_ALIAS_LENGTH = 0xffff;
+
+// DER of AlgorithmIdentifier { OID 1.3.6.1.4.1.42.2.17.1.1 (Sun JKS KeyProtector), NULL }.
+const JKS_KEY_PROTECTOR_ALGORITHM_ID = Buffer.from("300e060a2b060104012a021101010500", "hex");
+
+type TJksEntry =
+ | { type: "privateKey"; alias: string; privateKey: string; certificateChain: string[] }
+ | { type: "trustedCertificate"; alias: string; certificate: string };
+
+const sha1 = (...parts: Buffer[]) => {
+ const hash = crypto.nativeCrypto.createHash("sha1");
+ parts.forEach((part) => hash.update(part));
+ return hash.digest();
+};
+
+const toJavaPasswordBytes = (password: string) => Buffer.from(password, "utf16le").swap16();
+
+const derLength = (length: number): Buffer => {
+ if (length < 0x80) return Buffer.from([length]);
+ const bytes: number[] = [];
+ let remaining = length;
+ while (remaining > 0) {
+ bytes.unshift(remaining & 0xff);
+ remaining >>>= 8;
+ }
+ return Buffer.from([0x80 | bytes.length, ...bytes]);
+};
+
+const derTlv = (tag: number, value: Buffer) => Buffer.concat([Buffer.from([tag]), derLength(value.length), value]);
+
+const protectPrivateKey = (pkcs8Der: Buffer, passwordBytes: Buffer): Buffer => {
+ const salt = crypto.randomBytes(SHA1_LENGTH);
+ const keystream: Buffer[] = [];
+ let digest: Buffer = salt;
+ for (let produced = 0; produced < pkcs8Der.length; produced += SHA1_LENGTH) {
+ digest = sha1(passwordBytes, digest);
+ keystream.push(digest);
+ }
+ const xorKey = Buffer.concat(keystream);
+ const encrypted = Buffer.alloc(pkcs8Der.length);
+ for (let i = 0; i < pkcs8Der.length; i += 1) {
+ encrypted[i] = pkcs8Der[i] ^ xorKey[i];
+ }
+ const check = sha1(passwordBytes, pkcs8Der);
+
+ const protectedKey = Buffer.concat([salt, encrypted, check]);
+ return derTlv(0x30, Buffer.concat([JKS_KEY_PROTECTOR_ALGORITHM_ID, derTlv(0x04, protectedKey)]));
+};
+
+const u16 = (value: number) => {
+ const buf = Buffer.alloc(2);
+ buf.writeUInt16BE(value);
+ return buf;
+};
+
+const u32 = (value: number) => {
+ const buf = Buffer.alloc(4);
+ buf.writeUInt32BE(value);
+ return buf;
+};
+
+const u64 = (value: number) => {
+ const buf = Buffer.alloc(8);
+ buf.writeBigUInt64BE(BigInt(value));
+ return buf;
+};
+
+// Java's DataOutputStream.writeUTF; only differs from UTF-8 for NUL and supplementary characters.
+const javaUtf = (value: string) => {
+ const bytes = Buffer.from(value, "utf8");
+ if (bytes.length > MAX_JKS_ALIAS_LENGTH) {
+ throw new BadRequestError({ message: "JKS alias is too long" });
+ }
+ return Buffer.concat([u16(bytes.length), bytes]);
+};
+
+const certificateDer = (pem: string): Buffer => {
+ try {
+ return new crypto.nativeCrypto.X509Certificate(pem).raw;
+ } catch {
+ throw new BadRequestError({ message: "Failed to parse certificate for JKS export" });
+ }
+};
+
+const JKS_SUPPORTED_KEY_TYPES = new Set(["rsa", "ec"]);
+
+const privateKeyPkcs8Der = (privateKeyPem: string, leafCertificatePem: string): Buffer => {
+ let key;
+ try {
+ key = crypto.nativeCrypto.createPrivateKey({ key: privateKeyPem, format: "pem" });
+ } catch {
+ throw new BadRequestError({
+ message: "The certificate's private key could not be read, so it cannot be exported as a Java KeyStore"
+ });
+ }
+ if (!key.asymmetricKeyType || !JKS_SUPPORTED_KEY_TYPES.has(key.asymmetricKeyType)) {
+ throw new BadRequestError({
+ message: `Java KeyStore export supports RSA and EC keys only, and this certificate uses a '${key.asymmetricKeyType ?? "unknown"}' key. Use PEM format instead.`
+ });
+ }
+
+ const publicKeyDer = crypto.nativeCrypto.createPublicKey(key).export({ type: "spki", format: "der" });
+ const leafPublicKeyDer = new crypto.nativeCrypto.X509Certificate(leafCertificatePem).publicKey.export({
+ type: "spki",
+ format: "der"
+ });
+ if (!publicKeyDer.equals(leafPublicKeyDer)) {
+ throw new BadRequestError({
+ message: "The certificate's private key does not match its public key, so it cannot be exported"
+ });
+ }
+
+ return key.export({ type: "pkcs8", format: "der" });
+};
+
+const uniqueCertificates = (pems: string[], exclude: string[] = []): string[] => {
+ const seen = new Set(exclude.map((pem) => certificateDer(pem).toString("base64")));
+ return pems.filter((pem) => {
+ const fingerprint = certificateDer(pem).toString("base64");
+ if (seen.has(fingerprint)) return false;
+ seen.add(fingerprint);
+ return true;
+ });
+};
+
+// Stored chains can include the leaf (imported full chains), which must not be repeated or trusted.
+export const getJksChainCertificates = (certificate: string, certificateChain?: string): string[] =>
+ uniqueCertificates(splitPemChain(certificateChain ?? ""), [certificate]);
+
+// The trust anchor comes from caCertificate because the delivered chain may omit the root.
+export const getJksTruststoreCertificates = ({
+ certificate,
+ certificateChain,
+ caCertificate
+}: {
+ certificate: string;
+ certificateChain?: string;
+ caCertificate?: string;
+}): string[] =>
+ uniqueCertificates([...splitPemChain(certificateChain ?? ""), ...splitPemChain(caCertificate ?? "")], [certificate]);
+
+const encodeCertificate = (pem: string) => {
+ const der = certificateDer(pem);
+ return Buffer.concat([javaUtf(JKS_CERT_TYPE), u32(der.length), der]);
+};
+
+// Aliases are lowercased because JavaKeyStore lowercases every alias it looks up.
+const buildJavaKeyStore = ({ entries, password }: { entries: TJksEntry[]; password: string }): Buffer => {
+ if (!password || password.trim() === "") {
+ throw new BadRequestError({ message: "Password is required for JKS keystore generation" });
+ }
+
+ const passwordBytes = toJavaPasswordBytes(password);
+ const timestamp = Date.now();
+
+ const encodedEntries = entries.map((entry) => {
+ const alias = entry.alias.toLowerCase();
+
+ if (entry.type === "trustedCertificate") {
+ return Buffer.concat([
+ u32(JKS_TRUSTED_CERT_TAG),
+ javaUtf(alias),
+ u64(timestamp),
+ encodeCertificate(entry.certificate)
+ ]);
+ }
+
+ const protectedKey = protectPrivateKey(
+ privateKeyPkcs8Der(entry.privateKey, entry.certificateChain[0]),
+ passwordBytes
+ );
+ return Buffer.concat([
+ u32(JKS_PRIVATE_KEY_TAG),
+ javaUtf(alias),
+ u64(timestamp),
+ u32(protectedKey.length),
+ protectedKey,
+ u32(entry.certificateChain.length),
+ ...entry.certificateChain.map(encodeCertificate)
+ ]);
+ });
+
+ const body = Buffer.concat([u32(JKS_MAGIC), u32(JKS_VERSION), u32(entries.length), ...encodedEntries]);
+ const integrity = sha1(passwordBytes, Buffer.from(JKS_INTEGRITY_WHITENER, "utf8"), body);
+ return Buffer.concat([body, integrity]);
+};
+
+export const generateJksFromCertificate = ({
+ certificate,
+ certificateChain,
+ privateKey,
+ password,
+ alias
+}: {
+ certificate: string;
+ certificateChain?: string;
+ privateKey: string;
+ password: string;
+ alias: string;
+}): Buffer =>
+ buildJavaKeyStore({
+ password,
+ entries: [
+ {
+ type: "privateKey",
+ alias,
+ privateKey,
+ certificateChain: [certificate, ...getJksChainCertificates(certificate, certificateChain)]
+ }
+ ]
+ });
+
+export const generateJksTruststore = ({
+ trustedCertificates,
+ password,
+ alias
+}: {
+ trustedCertificates: string[];
+ password: string;
+ alias: string;
+}): Buffer =>
+ buildJavaKeyStore({
+ password,
+ entries: trustedCertificates.map((certificate, index) => ({
+ type: "trustedCertificate" as const,
+ alias: `${alias}-ca-${index + 1}`,
+ certificate
+ }))
+ });
diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
index fc5b7834b0..8bf9196b6b 100644
--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
@@ -26,7 +26,12 @@ import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certi
import { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-schemas";
import { PkiSyncError } from "../pki-sync-errors";
-import { exportCertificateForSync, PemCertificateExtension, PkiSyncExportFormat } from "../pki-sync-export-fns";
+import {
+ exportCertificateForSync,
+ isKeystoreExportFormat,
+ PemCertificateExtension,
+ PkiSyncExportFormat
+} from "../pki-sync-export-fns";
import {
buildHealthCheckCommandFailureMessage,
buildHealthCheckCommandPlan,
@@ -63,6 +68,8 @@ type TLinuxServerSyncOptions = {
exportFormat?: PkiSyncExportFormat;
pemCertificateExtension?: PemCertificateExtension;
combineCertificateChain?: boolean;
+ keystoreAlias?: string;
+ includeTruststore?: boolean;
includePrivateKey?: boolean;
canRemoveCertificates?: boolean;
fileMode?: string;
@@ -322,7 +329,8 @@ const resolveLinuxExportOptions = (options: TLinuxServerSyncOptions) => ({
format: options.exportFormat ?? PkiSyncExportFormat.Pem,
includePrivateKey: options.includePrivateKey ?? true,
pemCertificateExtension: options.pemCertificateExtension,
- combineCertificateChain: options.combineCertificateChain
+ combineCertificateChain: options.combineCertificateChain,
+ includeTruststore: options.includeTruststore
});
const executeLinuxServerHostCommand = (
@@ -363,8 +371,7 @@ const runLinuxServerHealthCheckCommand = async ({
certificateMap,
exportOptions,
joinPath: (directory, fileName) => path.posix.join(directory, fileName),
- pkcs12Password:
- exportOptions.format === PkiSyncExportFormat.Pkcs12 ? pkiSync.syncCredentials?.exportPassword : undefined
+ pkcs12Password: isKeystoreExportFormat(exportOptions.format) ? pkiSync.syncCredentials?.exportPassword : undefined
});
if (!plan) return undefined;
@@ -466,7 +473,7 @@ export const linuxServerPkiSyncFactory = ({
await removeStaleTempFiles(sftp, config.destinationPath);
for (const [baseName, certData] of Object.entries(certificateMap)) {
- const { cert, privateKey, certificateChain, certificateId } = certData;
+ const { cert, privateKey, certificateChain, caCertificate, certificateId } = certData;
if (!cert) {
skippedCertificates.push({ name: baseName, reason: "Missing certificate data" });
@@ -474,9 +481,9 @@ export const linuxServerPkiSyncFactory = ({
continue;
}
- // Private key is required for PKCS#12, and for PEM when the operator asked to include it.
+ // Private key is required for PKCS#12 and JKS, and for PEM when the operator asked to include it.
// If the key is not available (external CSR or HSM key), fail rather than deliver a keyless file.
- const keyRequired = format === PkiSyncExportFormat.Pkcs12 || includePrivateKey;
+ const keyRequired = isKeystoreExportFormat(format) || includePrivateKey;
if (keyRequired && !privateKey) {
failedUploads.push({
name: baseName,
@@ -492,9 +499,10 @@ export const linuxServerPkiSyncFactory = ({
...exportOptions,
certificate: cert,
certificateChain,
+ caCertificate,
privateKey,
password: exportPassword,
- alias: baseName
+ alias: options.keystoreAlias || baseName
});
const writtenPaths: string[] = [];
@@ -573,7 +581,7 @@ export const linuxServerPkiSyncFactory = ({
destinationDirectory: config.destinationPath,
deliveredPaths,
deliveredCertificates,
- pkcs12Password: format === PkiSyncExportFormat.Pkcs12 ? exportPassword : undefined
+ pkcs12Password: isKeystoreExportFormat(format) ? exportPassword : undefined
});
const postSyncCommand = postSyncCommandPlan
? await runLinuxServerPostSyncCommand({
diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts
index 784b06e695..8b35d183b0 100644
--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts
@@ -9,10 +9,17 @@ import {
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";
+import {
+ isKeystoreExportFormat,
+ KEYSTORE_PASSWORD_REQUIRED_MESSAGE,
+ PemCertificateExtension,
+ PkiSyncExportFormat
+} from "@app/services/pki-sync/pki-sync-export-fns";
import {
BaseHealthCheckTestSchema,
HostCommandSchema,
+ IncludeTruststoreSchema,
+ KeystoreAliasSchema,
PkiSyncFiltersField,
PkiSyncSchema,
PkiSyncTargetHostSchema,
@@ -63,6 +70,8 @@ export const LinuxServerPkiSyncOptionsSchema = z.object({
exportFormat: z.nativeEnum(PkiSyncExportFormat).default(PkiSyncExportFormat.Pem),
pemCertificateExtension: z.nativeEnum(PemCertificateExtension).default(PemCertificateExtension.Pem),
combineCertificateChain: z.boolean().default(false),
+ keystoreAlias: KeystoreAliasSchema,
+ includeTruststore: IncludeTruststoreSchema,
fileMode: z
.string()
.trim()
@@ -108,7 +117,7 @@ export const LinuxServerPkiSyncOptionsSchema = z.object({
)
});
-// Sync-level secrets (the PKCS#12 export password) accepted on create/update. Stored encrypted in
+// Sync-level secrets (the PKCS#12 / JKS export password) accepted on create/update. Stored encrypted in
// pki_syncs.encryptedCredentials and never returned.
export const LinuxServerPkiSyncCredentialsSchema = z.object({
exportPassword: z.string().min(1).optional()
@@ -135,11 +144,11 @@ export const CreateLinuxServerPkiSyncSchema = z
filters: PkiSyncFiltersField
})
.superRefine((data, ctx) => {
- if (data.syncOptions.exportFormat === PkiSyncExportFormat.Pkcs12 && !data.credentials?.exportPassword) {
+ if (isKeystoreExportFormat(data.syncOptions.exportFormat) && !data.credentials?.exportPassword) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["credentials", "exportPassword"],
- message: "A password is required when the export format is PKCS#12"
+ message: KEYSTORE_PASSWORD_REQUIRED_MESSAGE
});
}
});
diff --git a/backend/src/services/pki-sync/pki-sync-export-fns.test.ts b/backend/src/services/pki-sync/pki-sync-export-fns.test.ts
index 25752cf1ca..d0f9906070 100644
--- a/backend/src/services/pki-sync/pki-sync-export-fns.test.ts
+++ b/backend/src/services/pki-sync/pki-sync-export-fns.test.ts
@@ -102,7 +102,7 @@ describe("getExportedCertificateFileSuffixes matches the real export", () => {
);
const realPair = (() => {
- const keys = forge.pki.rsa.generateKeyPair(1024);
+ const keys = forge.pki.rsa.generateKeyPair(2048);
const cert = forge.pki.createCertificate();
cert.publicKey = keys.publicKey;
cert.serialNumber = "01";
@@ -158,4 +158,50 @@ describe("getExportedCertificateFileSuffixes matches the real export", () => {
})
).rejects.toThrow(/PKCS#12 export is not supported for this key type/);
});
+
+ const otherCa = (() => {
+ const keys = forge.pki.rsa.generateKeyPair(2048);
+ const cert = forge.pki.createCertificate();
+ cert.publicKey = keys.publicKey;
+ cert.serialNumber = "02";
+ cert.validity.notBefore = new Date(2026, 0, 1);
+ cert.validity.notAfter = new Date(2027, 0, 1);
+ const attrs = [{ name: "commonName", value: "Example CA" }];
+ cert.setSubject(attrs);
+ cert.setIssuer(attrs);
+ cert.sign(keys.privateKey);
+ return forge.pki.certificateToPem(cert);
+ })();
+
+ test.each([
+ [true, true, false],
+ [true, false, true],
+ [true, false, false],
+ [false, true, true]
+ ])("JKS truststore=%s chain=%s root=%s", async (includeTruststore, hasCertificateChain, hasRoot) => {
+ const shape = {
+ format: PkiSyncExportFormat.Jks as const,
+ includePrivateKey: true,
+ hasCertificateChain,
+ hasPrivateKey: true,
+ includeTruststore,
+ hasTruststoreCertificates: hasCertificateChain || hasRoot
+ };
+
+ const exported = await exportCertificateForSync({
+ format: shape.format,
+ certificate: realPair.certificate,
+ certificateChain: hasCertificateChain ? otherCa : undefined,
+ caCertificate: hasRoot ? otherCa : undefined,
+ privateKey: realPair.privateKey,
+ includePrivateKey: true,
+ includeTruststore,
+ password: "changeit",
+ alias: "api.example.com"
+ });
+
+ expect(getExportedCertificateFileSuffixes(shape).sort()).toEqual(suffixes(exported));
+ expect(exported.find((f) => f.suffix === ".jks")?.isPrivateKey).toBe(true);
+ expect(exported.find((f) => f.suffix === ".truststore.jks")?.isPrivateKey).toBeFalsy();
+ });
});
diff --git a/backend/src/services/pki-sync/pki-sync-export-fns.ts b/backend/src/services/pki-sync/pki-sync-export-fns.ts
index 40b3e21be1..c416848836 100644
--- a/backend/src/services/pki-sync/pki-sync-export-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-export-fns.ts
@@ -1,10 +1,24 @@
import { generatePkcs12FromCertificate } from "@app/services/certificate/certificate-fns";
+import {
+ generateJksFromCertificate,
+ generateJksTruststore,
+ getJksTruststoreCertificates
+} from "@app/services/certificate/certificate-jks-fns";
export enum PkiSyncExportFormat {
Pem = "pem",
- Pkcs12 = "pkcs12"
+ Pkcs12 = "pkcs12",
+ Jks = "jks"
}
+export const isKeystoreExportFormat = (format: unknown): boolean =>
+ format === PkiSyncExportFormat.Pkcs12 || format === PkiSyncExportFormat.Jks;
+
+export const KEYSTORE_PASSWORD_REQUIRED_MESSAGE = "A password is required when the export format is PKCS#12 or JKS";
+
+export const JKS_KEYSTORE_SUFFIX = ".jks";
+export const JKS_TRUSTSTORE_SUFFIX = ".truststore.jks";
+
export enum PemCertificateExtension {
Pem = "pem",
Crt = "crt"
@@ -22,10 +36,12 @@ export type TExportCertificateForSyncParams = {
certificateChain?: string;
privateKey?: string;
includePrivateKey: boolean;
- // Required for PKCS#12.
+ // Required for PKCS#12 and JKS.
password?: string;
- // Friendly name / alias used inside a PKCS#12 keystore.
+ // Friendly name / alias used inside a PKCS#12 or JKS keystore.
alias: string;
+ includeTruststore?: boolean;
+ caCertificate?: string;
// PEM only: the extension for the certificate and chain files. Defaults to ".pem".
pemCertificateExtension?: PemCertificateExtension;
// PEM only: when true, the certificate file holds the leaf certificate followed by the chain (a
@@ -40,6 +56,8 @@ export type TExportedCertificateFileShape = {
hasPrivateKey: boolean;
pemCertificateExtension?: PemCertificateExtension;
combineCertificateChain?: boolean;
+ includeTruststore?: boolean;
+ hasTruststoreCertificates?: boolean;
};
export const getExportedCertificateFileSuffixes = ({
@@ -48,9 +66,16 @@ export const getExportedCertificateFileSuffixes = ({
hasCertificateChain,
hasPrivateKey,
pemCertificateExtension,
- combineCertificateChain
+ combineCertificateChain,
+ includeTruststore,
+ hasTruststoreCertificates
}: TExportedCertificateFileShape): string[] => {
if (format === PkiSyncExportFormat.Pkcs12) return [".pfx"];
+ if (format === PkiSyncExportFormat.Jks) {
+ return includeTruststore && hasTruststoreCertificates
+ ? [JKS_KEYSTORE_SUFFIX, JKS_TRUSTSTORE_SUFFIX]
+ : [JKS_KEYSTORE_SUFFIX];
+ }
const certExtension = pemCertificateExtension ?? PemCertificateExtension.Pem;
const suffixes = [`.${certExtension}`];
@@ -69,10 +94,11 @@ export const getExportedCertificateFileSuffixes = ({
* - PEM -> "<base>.<pem|crt>" (cert), "<base>.chain.<pem|crt>" (chain), "<base>.key" (key, when included)
* - PEM (combined chain) -> "<base>.<pem|crt>" (leaf + chain), "<base>.key" (key, when included)
* - PKCS#12 -> "<base>.pfx" (cert + chain + key, password-protected)
+ * - JKS -> "<base>.jks" (key + cert + chain), plus "<base>.truststore.jks" when requested
*
* The caller is responsible for deciding whether the private key is available and whether it is
* required (see the destination factories, which fail the certificate when includePrivateKey is set
- * but the key cannot be exported). This helper assumes inputs are valid and only guards PKCS#12.
+ * but the key cannot be exported). This helper assumes inputs are valid and only guards the keystores.
*/
export const exportCertificateForSync = ({
format,
@@ -83,7 +109,9 @@ export const exportCertificateForSync = ({
password,
alias,
pemCertificateExtension,
- combineCertificateChain
+ combineCertificateChain,
+ includeTruststore,
+ caCertificate
}: TExportCertificateForSyncParams): Promise<TExportedCertificateFile[]> | TExportedCertificateFile[] => {
if (format === PkiSyncExportFormat.Pkcs12) {
return generatePkcs12FromCertificate({
@@ -95,6 +123,32 @@ export const exportCertificateForSync = ({
}).then((pfx) => [{ suffix: ".pfx", content: pfx, isPrivateKey: true }]);
}
+ if (format === PkiSyncExportFormat.Jks) {
+ const files: TExportedCertificateFile[] = [
+ {
+ suffix: JKS_KEYSTORE_SUFFIX,
+ content: generateJksFromCertificate({
+ certificate,
+ certificateChain,
+ privateKey: privateKey ?? "",
+ password: password ?? "",
+ alias
+ }),
+ isPrivateKey: true
+ }
+ ];
+ const trustedCertificates = includeTruststore
+ ? getJksTruststoreCertificates({ certificate, certificateChain, caCertificate })
+ : [];
+ if (trustedCertificates.length > 0) {
+ files.push({
+ suffix: JKS_TRUSTSTORE_SUFFIX,
+ content: generateJksTruststore({ trustedCertificates, password: password ?? "", alias })
+ });
+ }
+ return files;
+ }
+
const certExtension = pemCertificateExtension ?? PemCertificateExtension.Pem;
const files: TExportedCertificateFile[] = [];
diff --git a/backend/src/services/pki-sync/pki-sync-health-check-command-fns.ts b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.ts
index b3da0b5734..b98922709e 100644
--- a/backend/src/services/pki-sync/pki-sync-health-check-command-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-health-check-command-fns.ts
@@ -1,10 +1,11 @@
import { BadRequestError } from "@app/lib/errors";
+import { getJksTruststoreCertificates } from "@app/services/certificate/certificate-jks-fns";
import { HEALTH_CHECK_COMMAND_OPTION_KEY, PkiSyncStatus } from "./pki-sync-enums";
import {
getExportedCertificateFileSuffixes,
- PemCertificateExtension,
- PkiSyncExportFormat
+ PkiSyncExportFormat,
+ TExportedCertificateFileShape
} from "./pki-sync-export-fns";
import {
applyHostCommandOptionUpdate,
@@ -68,11 +69,27 @@ export const assertHealthCheckCommandIsTestable = (
return command;
};
-type THealthCheckExportOptions = {
- format: PkiSyncExportFormat;
- includePrivateKey: boolean;
- pemCertificateExtension?: PemCertificateExtension;
- combineCertificateChain?: boolean;
+type THealthCheckExportOptions = Omit<
+ TExportedCertificateFileShape,
+ "hasCertificateChain" | "hasPrivateKey" | "hasTruststoreCertificates"
+>;
+
+const hasTruststoreCertificates = (
+ exportOptions: THealthCheckExportOptions,
+ certData: TCertificateMap[string]
+): boolean => {
+ if (exportOptions.format !== PkiSyncExportFormat.Jks || !exportOptions.includeTruststore) return false;
+ try {
+ return (
+ getJksTruststoreCertificates({
+ certificate: certData.cert,
+ certificateChain: certData.certificateChain,
+ caCertificate: certData.caCertificate
+ }).length > 0
+ );
+ } catch {
+ return false;
+ }
};
const buildProspectiveCertificates = (args: {
@@ -87,7 +104,8 @@ const buildProspectiveCertificates = (args: {
paths: getExportedCertificateFileSuffixes({
...exportOptions,
hasCertificateChain: Boolean(certData.certificateChain),
- hasPrivateKey: Boolean(certData.privateKey)
+ hasPrivateKey: Boolean(certData.privateKey),
+ hasTruststoreCertificates: hasTruststoreCertificates(exportOptions, certData)
}).map((suffix) => joinPath(destinationDirectory, `${baseName}${suffix}`)),
commonName: certData.commonName ?? undefined
}));
diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.ts
index 5344da27d4..93f76518fe 100644
--- a/backend/src/services/pki-sync/pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts
@@ -16,6 +16,28 @@ export const HostCommandSchema = z
.nullable()
.optional();
+const KEYSTORE_ALIAS = new RE2("^[a-zA-Z0-9._-]+$");
+
+export const KeystoreAliasSchema = z
+ .string()
+ .trim()
+ .min(1)
+ .max(128)
+ .refine((v) => KEYSTORE_ALIAS.test(v), {
+ message: "Keystore alias may only contain letters, digits, dots (.), dashes (-), and underscores (_)"
+ })
+ .optional()
+ .describe(
+ "Alias of the private key entry in a PKCS#12 or JKS keystore. Defaults to the certificate's file base name. JKS stores aliases in lowercase."
+ );
+
+export const IncludeTruststoreSchema = z
+ .boolean()
+ .optional()
+ .describe(
+ "Java KeyStore only: also deliver '<name>.truststore.jks' holding the chain and root CA as trusted certificates."
+ );
+
export const PkiSyncTargetPortSchema = z.coerce
.number()
.int()
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index 4951ba26b1..d1900aab34 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -36,7 +36,7 @@ import { TSyncMetadata } from "../certificate-sync/certificate-sync-schemas";
import { encryptPkiSyncCredentials } from "./pki-sync-credentials-fns";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { HEALTH_CHECK_COMMAND_OPTION_KEY, PkiSync, PkiSyncStatus } from "./pki-sync-enums";
-import { PkiSyncExportFormat } from "./pki-sync-export-fns";
+import { isKeystoreExportFormat, KEYSTORE_PASSWORD_REQUIRED_MESSAGE } from "./pki-sync-export-fns";
import { hasAnyPkiSyncFilter, PKI_SYNC_FILTER_KINDS, PKI_SYNC_PREVIEW_PAGE_SIZE } from "./pki-sync-filter-fns";
import {
applyPkiSyncCertificateDiff,
@@ -970,11 +970,11 @@ export const pkiSyncServiceFactory = ({
}
if (
- effectiveSyncOptions?.exportFormat === PkiSyncExportFormat.Pkcs12 &&
+ isKeystoreExportFormat(effectiveSyncOptions?.exportFormat) &&
!credentials?.exportPassword &&
!pkiSync.encryptedCredentials
) {
- throw new BadRequestError({ message: "A password is required when the export format is PKCS#12" });
+ throw new BadRequestError({ message: KEYSTORE_PASSWORD_REQUIRED_MESSAGE });
}
const encryptedCredentials = credentials?.exportPassword
diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
index 077e683c8d..7fd88446f6 100644
--- a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
@@ -17,7 +17,12 @@ import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certi
import { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-schemas";
import { PkiSyncError } from "../pki-sync-errors";
-import { exportCertificateForSync, PemCertificateExtension, PkiSyncExportFormat } from "../pki-sync-export-fns";
+import {
+ exportCertificateForSync,
+ isKeystoreExportFormat,
+ PemCertificateExtension,
+ PkiSyncExportFormat
+} from "../pki-sync-export-fns";
import {
buildHealthCheckCommandFailureMessage,
buildHealthCheckCommandPlan,
@@ -55,6 +60,8 @@ type TWindowsServerSyncOptions = {
exportFormat?: PkiSyncExportFormat;
pemCertificateExtension?: PemCertificateExtension;
combineCertificateChain?: boolean;
+ keystoreAlias?: string;
+ includeTruststore?: boolean;
includePrivateKey?: boolean;
canRemoveCertificates?: boolean;
fileAccessRules?: Array<{ identity: string; access: string }>;
@@ -66,7 +73,8 @@ const resolveWindowsExportOptions = (options: TWindowsServerSyncOptions) => ({
format: options.exportFormat ?? PkiSyncExportFormat.Pkcs12,
includePrivateKey: options.includePrivateKey ?? true,
pemCertificateExtension: options.pemCertificateExtension,
- combineCertificateChain: options.combineCertificateChain
+ combineCertificateChain: options.combineCertificateChain,
+ includeTruststore: options.includeTruststore
});
const TRAILING_BACKSLASH = new RE2("\\\\+$");
@@ -260,8 +268,7 @@ const runWindowsServerHealthCheckCommand = async ({
certificateMap,
exportOptions,
joinPath: joinWindowsPath,
- pkcs12Password:
- exportOptions.format === PkiSyncExportFormat.Pkcs12 ? pkiSync.syncCredentials?.exportPassword : undefined
+ pkcs12Password: isKeystoreExportFormat(exportOptions.format) ? pkiSync.syncCredentials?.exportPassword : undefined
});
if (!plan) return undefined;
@@ -344,7 +351,7 @@ export const windowsServerPkiSyncFactory = ({
// Deliver each certificate over its own gateway operation so one certificate's failure is
// recorded against that certificate only, rather than failing the whole batch.
for (const [baseName, certData] of Object.entries(certificateMap)) {
- const { cert, privateKey, certificateChain, certificateId } = certData;
+ const { cert, privateKey, certificateChain, caCertificate, certificateId } = certData;
if (!cert) {
skippedCertificates.push({ name: baseName, reason: "Missing certificate data" });
@@ -352,7 +359,7 @@ export const windowsServerPkiSyncFactory = ({
continue;
}
- const keyRequired = format === PkiSyncExportFormat.Pkcs12 || includePrivateKey;
+ const keyRequired = isKeystoreExportFormat(format) || includePrivateKey;
if (keyRequired && !privateKey) {
failedUploads.push({
name: baseName,
@@ -368,9 +375,10 @@ export const windowsServerPkiSyncFactory = ({
...exportOptions,
certificate: cert,
certificateChain,
+ caCertificate,
privateKey,
password: exportPassword,
- alias: baseName
+ alias: options.keystoreAlias || baseName
});
const paths: string[] = [];
@@ -436,7 +444,7 @@ export const windowsServerPkiSyncFactory = ({
destinationDirectory: config.destinationPath,
deliveredPaths,
deliveredCertificates,
- pkcs12Password: format === PkiSyncExportFormat.Pkcs12 ? exportPassword : undefined
+ pkcs12Password: isKeystoreExportFormat(format) ? exportPassword : undefined
});
const postSyncCommand = postSyncCommandPlan
? await runWindowsServerPostSyncCommand({
diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts
index d9fe034db3..d03871a3f1 100644
--- a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts
@@ -5,10 +5,17 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";
+import {
+ isKeystoreExportFormat,
+ KEYSTORE_PASSWORD_REQUIRED_MESSAGE,
+ PemCertificateExtension,
+ PkiSyncExportFormat
+} from "@app/services/pki-sync/pki-sync-export-fns";
import {
BaseHealthCheckTestSchema,
HostCommandSchema,
+ IncludeTruststoreSchema,
+ KeystoreAliasSchema,
PkiSyncFiltersField,
PkiSyncSchema,
PkiSyncTargetHostSchema,
@@ -81,6 +88,8 @@ export const WindowsServerPkiSyncOptionsSchema = z.object({
exportFormat: z.nativeEnum(PkiSyncExportFormat).default(PkiSyncExportFormat.Pkcs12),
pemCertificateExtension: z.nativeEnum(PemCertificateExtension).default(PemCertificateExtension.Pem),
combineCertificateChain: z.boolean().default(false),
+ keystoreAlias: KeystoreAliasSchema,
+ includeTruststore: IncludeTruststoreSchema,
fileAccessRules: z
.array(
z.object({
@@ -118,7 +127,7 @@ export const WindowsServerPkiSyncOptionsSchema = z.object({
)
});
-// Sync-level secrets (the PKCS#12 export password) accepted on create/update. Stored encrypted in
+// Sync-level secrets (the PKCS#12 / JKS export password) accepted on create/update. Stored encrypted in
// pki_syncs.encryptedCredentials and never returned.
export const WindowsServerPkiSyncCredentialsSchema = z.object({
exportPassword: z.string().min(1).optional()
@@ -145,11 +154,11 @@ export const CreateWindowsServerPkiSyncSchema = z
filters: PkiSyncFiltersField
})
.superRefine((data, ctx) => {
- if (data.syncOptions.exportFormat === PkiSyncExportFormat.Pkcs12 && !data.credentials?.exportPassword) {
+ if (isKeystoreExportFormat(data.syncOptions.exportFormat) && !data.credentials?.exportPassword) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["credentials", "exportPassword"],
- message: "A password is required when the export format is PKCS#12"
+ message: KEYSTORE_PASSWORD_REQUIRED_MESSAGE
});
}
});
diff --git a/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt b/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
index ca6530be03..892089b162 100644
--- a/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
+++ b/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt
@@ -219,6 +219,7 @@ I
(?i)toolchain
(?i)toolset
(?i)tolerations
+(?i)truststore
(?i)uncontained
(?i)unconfigured
(?i)uncredentialed
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
index 2027e62058..d46caaeeef 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
@@ -40,12 +40,14 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi
- **Trusted Host Keys**: Optional. Paste the output of `ssh-keyscan <host>`. When set, the sync only connects if the host presents one of these keys.
5. Configure the **Sync Options**:
- - **Export Format**: Choose **PEM** to write separate certificate, chain, and key files, or **PKCS#12** to write a single password-protected `.pfx` bundle.
+ - **Export Format**: Choose **PEM** to write separate certificate, chain, and key files, **PKCS#12** to write a single password-protected `.pfx` bundle, or **Java KeyStore** to write a password-protected `.jks` keystore.
- **Certificate File Extension**: For PEM, choose `.pem` (default) or `.crt` for the certificate and chain files. Both hold the same PEM-encoded content, so pick the one the consuming service expects.
- **Combine Certificate and Chain**: For PEM, write the leaf certificate followed by the chain in a single file (a full-chain file, as nginx expects) and skip the separate chain file.
- **File Permissions** and **Private Key Permissions**: Octal modes for the delivered certificate and chain files (default `644`) and for the private key file (default `600`).
- **Owner** and **Group**: Optionally set the owner and group on the delivered files. Changing ownership requires the connection user to be root or to have passwordless sudo.
- - **PKCS#12 Password**: Required when the export format is PKCS#12. It protects the delivered bundle.
+ - **PKCS#12 Password** or **JKS Password**: Required when the export format is PKCS#12 or Java KeyStore. It protects the delivered bundle or keystore.
+ - **Keystore Alias**: For PKCS#12 and Java KeyStore, the alias of the private key entry, such as the value Tomcat expects in `certificateKeyAlias`. Leave it empty to use the base file name from the certificate name schema.
+ - **Deliver Truststore**: For Java KeyStore, also write a `.truststore.jks` file that holds the issuing CAs and the root CA as trusted certificates. It uses the same password as the keystore.
- **Include Private Key**: For PEM, controls whether the private key is written alongside the certificate. The sync fails for a certificate whose key is not available, for example one issued from an external CSR.
- **Include Root CA in Certificate Chain**: Include the root CA in the delivered chain. Leave it off when the consuming service only needs the intermediates.
- **Enable Removal of Certificates**: Delete the delivered files from the server when a certificate is removed from the sync, revoked, or expired.
@@ -142,6 +144,14 @@ The file extension is set by the export format, not by the name schema. The name
**PKCS#12** writes a single password-protected `.pfx` bundle that contains the certificate, chain, and private key.
+**Java KeyStore** writes a password-protected `.jks` keystore for Java servers such as Tomcat, WebLogic, and JBoss. The keystore holds one private key entry with the certificate, chain, and private key, and the key uses the same password as the keystore. If you turn on **Deliver Truststore**, the sync also writes a `.truststore.jks` file with each issuing CA and the root CA as trusted certificates. The truststore includes the root CA even when **Include Root CA in Certificate Chain** is off, and it never includes the certificate itself.
+
+Infisical writes a new keystore on every sync instead of adding to the file on the host. After a renewal, the keystore holds only the new certificate under the same alias, so old entries don't build up. Point your Java server at a keystore that only this sync writes to, because anything else in that file is replaced on the next sync.
+
+<Note>
+ Java KeyStore stores aliases in lowercase, so an alias of `Tomcat` is saved as `tomcat`. Java looks up aliases without regard to case, so configuring `Tomcat` in your server still finds the entry.
+</Note>
+
For a certificate whose common name is `app.example.com`, synced to `/etc/ssl/certs` with the default `{{commonName}}` name schema, the delivered files are:
```text
@@ -152,6 +162,10 @@ PEM (.pem extension)
PKCS#12
/etc/ssl/certs/app.example.com.pfx
+
+Java KeyStore
+ /etc/ssl/certs/app.example.com.jks keystore
+ /etc/ssl/certs/app.example.com.truststore.jks truststore (when delivered)
```
## How it works
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
index aa3fd2c99d..773f179e04 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
@@ -49,11 +49,13 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM
</Note>
5. Configure the **Sync Options**:
- - **Export Format**: Choose **PKCS#12** to write a single password-protected `.pfx` bundle, or **PEM** to write separate certificate, chain, and key files.
+ - **Export Format**: Choose **PKCS#12** to write a single password-protected `.pfx` bundle, **PEM** to write separate certificate, chain, and key files, or **Java KeyStore** to write a password-protected `.jks` keystore.
- **Certificate File Extension**: For PEM, choose `.pem` (default) or `.crt` for the certificate and chain files. Both hold the same PEM-encoded content, so pick the one the consuming service expects.
- **Combine Certificate and Chain**: For PEM, write the leaf certificate followed by the chain in a single file (a full-chain file) and skip the separate chain file.
- **File Permissions**: Optionally grant Windows users or groups (for example a service account) Read, Modify, or Full Control on the delivered files, so you can restrict who reads the private key. Rules are added on top of the destination folder's inherited permissions.
- - **PKCS#12 Password**: Required when the export format is PKCS#12. It protects the delivered bundle.
+ - **PKCS#12 Password** or **JKS Password**: Required when the export format is PKCS#12 or Java KeyStore. It protects the delivered bundle or keystore.
+ - **Keystore Alias**: For PKCS#12 and Java KeyStore, the alias of the private key entry, such as the value Tomcat expects in `certificateKeyAlias`. Leave it empty to use the base file name from the certificate name schema.
+ - **Deliver Truststore**: For Java KeyStore, also write a `.truststore.jks` file that holds the issuing CAs and the root CA as trusted certificates. It uses the same password as the keystore.
- **Include Private Key**: For PEM, controls whether the private key is written alongside the certificate. The sync fails for a certificate whose key is not available, for example one issued from an external CSR.
- **Include Root CA in Certificate Chain**: Include the root CA in the delivered chain. Leave it off when the consuming service only needs the intermediates.
- **Enable Removal of Certificates**: Delete the delivered files from the server when a certificate is removed from the sync, revoked, or expired.
@@ -151,6 +153,14 @@ The file extension is set by the export format, not by the name schema. The name
**PEM** writes the certificate, chain, and private key (when included) as separate files. The certificate and chain files use the extension you select, either `.pem` (default) or `.crt`.
+**Java KeyStore** writes a password-protected `.jks` keystore for Java servers such as Tomcat, WebLogic, and JBoss. The keystore holds one private key entry with the certificate, chain, and private key, and the key uses the same password as the keystore. If you turn on **Deliver Truststore**, the sync also writes a `.truststore.jks` file with each issuing CA and the root CA as trusted certificates. The truststore includes the root CA even when **Include Root CA in Certificate Chain** is off, and it never includes the certificate itself.
+
+Infisical writes a new keystore on every sync instead of adding to the file on the host. After a renewal, the keystore holds only the new certificate under the same alias, so old entries don't build up. Point your Java server at a keystore that only this sync writes to, because anything else in that file is replaced on the next sync.
+
+<Note>
+ Java KeyStore stores aliases in lowercase, so an alias of `Tomcat` is saved as `tomcat`. Java looks up aliases without regard to case, so configuring `Tomcat` in your server still finds the entry.
+</Note>
+
For a certificate whose common name is `app.example.com`, synced to `C:\certs` with the default `{{commonName}}` name schema, the delivered files are:
```text
@@ -161,6 +171,10 @@ PEM (.pem extension)
C:\certs\app.example.com.pem certificate
C:\certs\app.example.com.chain.pem chain
C:\certs\app.example.com.key private key (when included)
+
+Java KeyStore
+ C:\certs\app.example.com.jks keystore
+ C:\certs\app.example.com.truststore.jks truststore (when delivered)
```
## How it works
diff --git a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/command-variables.mdx b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/command-variables.mdx
index 45a126ec78..5b9602632a 100644
--- a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/command-variables.mdx
+++ b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/command-variables.mdx
@@ -6,7 +6,7 @@ Write a variable where you want this run's value. Infisical substitutes it befor
| `{{certificateDirectory}}` | The destination directory |
| `{{certificateFiles}}` | Every path this run writes, one per line |
| `{{commonName}}` | The certificate's common name. Single-certificate syncs only |
-| `{{pkcs12Password}}` | The PKCS#12 export password, set only when the export format is PKCS#12 |
+| `{{pkcs12Password}}` | The export password, set only when the export format is PKCS#12 or Java KeyStore |
The paths are the same for both commands, but a health check runs before anything is written, so they describe the files the run is *about to* write rather than files already on the host.
diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
index 704782f62a..adfbb05df7 100644
--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
@@ -33,6 +33,7 @@ import {
} from "@app/helpers/pkiSyncs";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
+ isKeystoreExportFormat,
PkiSync,
PkiSyncExportFormat,
TPkiSync,
@@ -42,6 +43,7 @@ import {
usePkiSyncOption
} from "@app/hooks/api/pkiSyncs";
+import { KEYSTORE_PASSWORD_REQUIRED_MESSAGE } from "./schemas/base-pki-sync-schema";
import { KEMP_DEFAULT_CA_NAME_SCHEMA } from "./schemas/kemp-loadmaster-pki-sync-destination-schema";
import { PkiSyncFormSchema, TPkiSyncForm } from "./schemas/pki-sync-schema";
import { PkiSyncCertificatesFields } from "./PkiSyncCertificatesFields";
@@ -305,12 +307,12 @@ export const CreatePkiSyncForm = ({
const requiresPassword =
(values.destination === PkiSync.WindowsServer ||
values.destination === PkiSync.LinuxServer) &&
- values.syncOptions?.exportFormat === PkiSyncExportFormat.Pkcs12 &&
+ isKeystoreExportFormat(values.syncOptions?.exportFormat) &&
!values.credentials?.exportPassword;
if (requiresPassword) {
setError("credentials.exportPassword" as FieldPath<TPkiSyncForm>, {
type: "manual",
- message: "A password is required for PKCS#12 exports"
+ message: KEYSTORE_PASSWORD_REQUIRED_MESSAGE
});
return false;
}
diff --git a/frontend/src/components/pki-syncs/forms/HostCommandField.tsx b/frontend/src/components/pki-syncs/forms/HostCommandField.tsx
index 8a3cf1a3d7..c46797bb39 100644
--- a/frontend/src/components/pki-syncs/forms/HostCommandField.tsx
+++ b/frontend/src/components/pki-syncs/forms/HostCommandField.tsx
@@ -3,7 +3,7 @@ import { Controller, FieldPath, useFormContext } from "react-hook-form";
import { Field, FieldDescription, FieldError, FieldLabel } from "@app/components/v3";
import { buildHostCommandTooltipDescriptions } from "@app/helpers/pkiSyncs";
-import { HostCommandVariable, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
+import { HostCommandVariable, isKeystoreExportFormat } from "@app/hooks/api/pkiSyncs";
import { TPkiSyncForm } from "./schemas/pki-sync-schema";
import { HostCommandInput } from "./HostCommandInput";
@@ -35,10 +35,10 @@ export const HostCommandField = ({
action
}: Props) => {
const { control, watch } = useFormContext<TPkiSyncForm>();
- const isPkcs12 = watch("syncOptions.exportFormat") === PkiSyncExportFormat.Pkcs12;
+ const isKeystore = isKeystoreExportFormat(watch("syncOptions.exportFormat"));
const variables = Object.values(HostCommandVariable).filter(
- (variable) => variable !== HostCommandVariable.Pkcs12Password || isPkcs12
+ (variable) => variable !== HostCommandVariable.Pkcs12Password || isKeystore
);
return (
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/ServerExportFormatFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/ServerExportFormatFields.tsx
index 27114fa070..b6fe2738b2 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/ServerExportFormatFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/ServerExportFormatFields.tsx
@@ -1,3 +1,4 @@
+import { useEffect } from "react";
import { Controller, useFormContext } from "react-hook-form";
import { Info } from "lucide-react";
@@ -19,7 +20,12 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
-import { PemCertificateExtension, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
+import {
+ isKeystoreExportFormat,
+ PemCertificateExtension,
+ PKI_SYNC_EXPORT_FORMAT_LABELS,
+ PkiSyncExportFormat
+} from "@app/hooks/api/pkiSyncs";
import { TPkiSyncForm } from "../schemas/pki-sync-schema";
@@ -28,7 +34,20 @@ type Props = {
};
export const ServerExportFormatFields = ({ isUpdate }: Props) => {
- const { control, watch } = useFormContext<TPkiSyncForm>();
+ const { control, watch, setValue, getValues } = useFormContext<TPkiSyncForm>();
+ const exportFormat = watch("syncOptions.exportFormat");
+ const isKeystore = isKeystoreExportFormat(exportFormat);
+
+ useEffect(() => {
+ if (!isKeystore && getValues("syncOptions.keystoreAlias")) {
+ setValue("syncOptions.keystoreAlias", undefined, { shouldDirty: true });
+ }
+ if (exportFormat !== PkiSyncExportFormat.Jks && getValues("syncOptions.includeTruststore")) {
+ setValue("syncOptions.includeTruststore", undefined, { shouldDirty: true });
+ }
+ }, [exportFormat, isKeystore]);
+ const keystoreLabel = exportFormat === PkiSyncExportFormat.Jks ? "JKS" : "PKCS#12";
+ const keystoreFile = exportFormat === PkiSyncExportFormat.Jks ? ".jks keystore" : ".pfx bundle";
return (
<>
@@ -45,7 +64,8 @@ export const ServerExportFormatFields = ({ isUpdate }: Props) => {
</TooltipTrigger>
<TooltipContent className="max-w-sm">
PEM writes separate certificate, chain, and key files. PKCS#12 writes a single
- password-protected .pfx bundle.
+ password-protected .pfx bundle. Java KeyStore writes a password-protected .jks
+ keystore for Java servers such as Tomcat and WebLogic.
</TooltipContent>
</Tooltip>
</FieldLabel>
@@ -57,15 +77,18 @@ export const ServerExportFormatFields = ({ isUpdate }: Props) => {
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
- <SelectItem value={PkiSyncExportFormat.Pem}>PEM</SelectItem>
- <SelectItem value={PkiSyncExportFormat.Pkcs12}>PKCS#12 (.pfx)</SelectItem>
+ {Object.values(PkiSyncExportFormat).map((format) => (
+ <SelectItem key={format} value={format}>
+ {PKI_SYNC_EXPORT_FORMAT_LABELS[format]}
+ </SelectItem>
+ ))}
</SelectContent>
</Select>
<FieldError errors={[error]} />
</Field>
)}
/>
- {watch("syncOptions.exportFormat") === PkiSyncExportFormat.Pem && (
+ {exportFormat === PkiSyncExportFormat.Pem && (
<Controller
control={control}
name="syncOptions.pemCertificateExtension"
@@ -100,7 +123,7 @@ export const ServerExportFormatFields = ({ isUpdate }: Props) => {
)}
/>
)}
- {watch("syncOptions.exportFormat") === PkiSyncExportFormat.Pem && (
+ {exportFormat === PkiSyncExportFormat.Pem && (
<Controller
control={control}
name="syncOptions.combineCertificateChain"
@@ -127,22 +150,22 @@ export const ServerExportFormatFields = ({ isUpdate }: Props) => {
)}
/>
)}
- {watch("syncOptions.exportFormat") === PkiSyncExportFormat.Pkcs12 && (
+ {isKeystore && (
<Controller
control={control}
name="credentials.exportPassword"
render={({ field: { value, onChange }, fieldState: { error } }) => (
<Field className="mb-4">
<FieldLabel>
- PKCS#12 password
+ {keystoreLabel} password
<Tooltip>
<TooltipTrigger asChild>
<Info />
</TooltipTrigger>
<TooltipContent className="max-w-sm">
{isUpdate
- ? "Protects the .pfx bundle. Leave blank to keep the current password."
- : "Protects the .pfx bundle."}
+ ? `Protects the ${keystoreFile}. Leave blank to keep the current password.`
+ : `Protects the ${keystoreFile}.`}
</TooltipContent>
</Tooltip>
</FieldLabel>
@@ -158,7 +181,64 @@ export const ServerExportFormatFields = ({ isUpdate }: Props) => {
)}
/>
)}
- {watch("syncOptions.exportFormat") !== PkiSyncExportFormat.Pkcs12 && (
+ {isKeystore && (
+ <Controller
+ control={control}
+ name="syncOptions.keystoreAlias"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>
+ Keystore alias
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ The alias of the private key entry, for example the value of Tomcat&apos;s
+ certificateKeyAlias. Defaults to the certificate&apos;s file name. Each renewal
+ replaces the entry under this alias.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <Input
+ value={value ?? ""}
+ onChange={onChange}
+ placeholder="Defaults to the certificate file name"
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ )}
+ {exportFormat === PkiSyncExportFormat.Jks && (
+ <Controller
+ control={control}
+ name="syncOptions.includeTruststore"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <Field orientation="horizontal">
+ <FieldContent>
+ <Label htmlFor="include-truststore">Deliver truststore</Label>
+ <FieldDescription>
+ When enabled, a separate .truststore.jks file holding the certificate&apos;s CA
+ chain and root CA as trusted entries is written next to the keystore. It uses
+ the same password.
+ </FieldDescription>
+ </FieldContent>
+ <Toggle
+ id="include-truststore"
+ variant="project"
+ checked={value ?? false}
+ onCheckedChange={onChange}
+ />
+ </Field>
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ )}
+ {!isKeystore && (
<Controller
control={control}
name="syncOptions.includePrivateKey"
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
index c5aaebe19c..97593c91fd 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
@@ -19,7 +19,12 @@ import {
VALUE_SYNC_OPTION_FIELDS
} from "@app/helpers/pkiSyncs";
import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
-import { usePkiSyncOption, usePkiSyncPreviewCertificates } from "@app/hooks/api/pkiSyncs";
+import {
+ PKI_SYNC_EXPORT_FORMAT_LABELS,
+ PkiSyncExportFormat,
+ usePkiSyncOption,
+ usePkiSyncPreviewCertificates
+} from "@app/hooks/api/pkiSyncs";
import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";
import { TPkiSyncForm } from "./schemas/pki-sync-schema";
@@ -224,7 +229,12 @@ export const PkiSyncReviewFields = ({ applicationId }: Props = {}) => {
return null;
return (
<ReviewFieldLabel key={key} label={label}>
- <Badge variant="neutral">{String(optionValue)}</Badge>
+ <Badge variant="neutral">
+ {key === "exportFormat"
+ ? (PKI_SYNC_EXPORT_FORMAT_LABELS[optionValue as PkiSyncExportFormat] ??
+ String(optionValue))
+ : String(optionValue)}
+ </Badge>
</ReviewFieldLabel>
);
})}
diff --git a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts
index 4efafa85ed..96405ed4f4 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts
@@ -6,6 +6,23 @@ export const HOST_COMMAND_MAX_LENGTH = 8192;
export const MAX_FILTER_CERTIFICATE_ORDERS = 10_000;
+const KEYSTORE_ALIAS_CHARACTERS =
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-";
+
+export const KEYSTORE_PASSWORD_REQUIRED_MESSAGE =
+ "A password is required for PKCS#12 and JKS exports";
+
+export const KeystoreAliasSchema = z
+ .string()
+ .trim()
+ .max(128, "Keystore alias must be at most 128 characters")
+ .refine((v) => [...v].every((c) => KEYSTORE_ALIAS_CHARACTERS.includes(c)), {
+ message:
+ "Keystore alias may only contain letters, digits, dots (.), dashes (-), and underscores (_)"
+ })
+ .transform((v) => v || undefined)
+ .optional();
+
export const HostCommandSchema = z
.string()
.trim()
diff --git a/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts
index 01941aa79d..9d31e2caf9 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts
@@ -5,6 +5,7 @@ import { PemCertificateExtension, PkiSync, PkiSyncExportFormat } from "@app/hook
import {
BasePkiSyncSchema,
HostCommandSchema,
+ KeystoreAliasSchema,
PkiSyncConnectionSchema,
PkiSyncTargetHostSchema,
PkiSyncTargetPortSchema
@@ -27,6 +28,8 @@ const LinuxServerSyncOptionsSchema = z.object({
.nativeEnum(PemCertificateExtension)
.default(PemCertificateExtension.Pem),
combineCertificateChain: z.boolean().default(false),
+ keystoreAlias: KeystoreAliasSchema,
+ includeTruststore: z.boolean().optional(),
includePrivateKey: z.boolean().default(true),
fileMode: z
.string()
diff --git a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts
index cb1de60701..7a2f154c71 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
-import { PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
+import { isKeystoreExportFormat, PkiSync } from "@app/hooks/api/pkiSyncs";
import { GCP_MAX_CERTIFICATES_PER_MAP_ENTRY } from "@app/hooks/api/pkiSyncs/types/gcp-certificate-manager-sync";
import {
@@ -20,6 +20,7 @@ import {
AzureKeyVaultPkiSyncDestinationSchema,
UpdateAzureKeyVaultPkiSyncDestinationSchema
} from "./azure-key-vault-pki-sync-destination-schema";
+import { KEYSTORE_PASSWORD_REQUIRED_MESSAGE } from "./base-pki-sync-schema";
import {
ChefPkiSyncDestinationSchema,
UpdateChefPkiSyncDestinationSchema
@@ -130,13 +131,13 @@ export const PkiSyncFormSchema = PkiSyncUnionSchema.superRefine((data, ctx) => {
if (
(data.destination === PkiSync.WindowsServer || data.destination === PkiSync.LinuxServer) &&
- data.syncOptions?.exportFormat === PkiSyncExportFormat.Pkcs12 &&
+ isKeystoreExportFormat(data.syncOptions?.exportFormat) &&
!data.credentials?.exportPassword
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["credentials", "exportPassword"],
- message: "A password is required for PKCS#12 exports"
+ message: KEYSTORE_PASSWORD_REQUIRED_MESSAGE
});
}
diff --git a/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts
index 4ad3083464..df0d041df8 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts
@@ -10,6 +10,7 @@ import {
import {
BasePkiSyncSchema,
HostCommandSchema,
+ KeystoreAliasSchema,
PkiSyncConnectionSchema,
PkiSyncTargetHostSchema,
PkiSyncTargetPortSchema
@@ -30,6 +31,8 @@ const WindowsServerSyncOptionsSchema = z.object({
.nativeEnum(PemCertificateExtension)
.default(PemCertificateExtension.Pem),
combineCertificateChain: z.boolean().default(false),
+ keystoreAlias: KeystoreAliasSchema,
+ includeTruststore: z.boolean().optional(),
fileAccessRules: z
.array(
z.object({
diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.ts
index 76eb0be609..599040243e 100644
--- a/frontend/src/helpers/pkiSyncs.ts
+++ b/frontend/src/helpers/pkiSyncs.ts
@@ -153,6 +153,7 @@ export const BOOLEAN_SYNC_OPTION_FIELDS = [
{ key: "preserveItemOnRenewal", label: "Preserve Item on Renewal" },
{ key: "updateExistingCertificates", label: "Update Existing Certificates" },
{ key: "combineCertificateChain", label: "Combine Certificate and Chain" },
+ { key: "includeTruststore", label: "Deliver JKS Truststore" },
{ key: "includePrivateKey", label: "Include Private Key" }
] as const;
@@ -176,6 +177,7 @@ export const VALUE_SYNC_OPTION_FIELDS = [
{ key: "caCertificateNameSchema", label: "CA Certificate Name Schema" },
{ key: "exportFormat", label: "Export Format" },
{ key: "pemCertificateExtension", label: "Certificate File Extension" },
+ { key: "keystoreAlias", label: "Keystore Alias" },
{ key: "fileMode", label: "File Permissions" },
{ key: "privateKeyFileMode", label: "Private Key Permissions" },
{ key: "owner", label: "Owner" },
@@ -187,7 +189,7 @@ export const POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS: Record<HostCommandVariable
[HostCommandVariable.CertificateDirectory]: "The destination directory",
[HostCommandVariable.CertificateFiles]: "Every path written this run, one per line",
[HostCommandVariable.CommonName]: "The certificate's common name",
- [HostCommandVariable.Pkcs12Password]: "The PKCS#12 export password"
+ [HostCommandVariable.Pkcs12Password]: "The PKCS#12 or JKS export password"
};
export const HEALTH_CHECK_COMMAND_VARIABLE_DESCRIPTIONS: Record<HostCommandVariable, string> = {
@@ -195,7 +197,7 @@ export const HEALTH_CHECK_COMMAND_VARIABLE_DESCRIPTIONS: Record<HostCommandVaria
[HostCommandVariable.CertificateDirectory]: "The directory the sync is about to write to",
[HostCommandVariable.CertificateFiles]: "Every path this run will write, one per line",
[HostCommandVariable.CommonName]: "The certificate's common name",
- [HostCommandVariable.Pkcs12Password]: "The PKCS#12 export password"
+ [HostCommandVariable.Pkcs12Password]: "The PKCS#12 or JKS export password"
};
const SINGLE_CERTIFICATE_HOST_COMMAND_VARIABLES = [
diff --git a/frontend/src/hooks/api/pkiSyncs/enums.ts b/frontend/src/hooks/api/pkiSyncs/enums.ts
index 0c94370f32..5f423133ef 100644
--- a/frontend/src/hooks/api/pkiSyncs/enums.ts
+++ b/frontend/src/hooks/api/pkiSyncs/enums.ts
@@ -16,9 +16,19 @@ export enum PkiSync {
export enum PkiSyncExportFormat {
Pem = "pem",
- Pkcs12 = "pkcs12"
+ Pkcs12 = "pkcs12",
+ Jks = "jks"
}
+export const PKI_SYNC_EXPORT_FORMAT_LABELS: Record<PkiSyncExportFormat, string> = {
+ [PkiSyncExportFormat.Pem]: "PEM",
+ [PkiSyncExportFormat.Pkcs12]: "PKCS#12 (.pfx)",
+ [PkiSyncExportFormat.Jks]: "Java KeyStore (.jks)"
+};
+
+export const isKeystoreExportFormat = (format?: PkiSyncExportFormat) =>
+ format === PkiSyncExportFormat.Pkcs12 || format === PkiSyncExportFormat.Jks;
+
export enum PemCertificateExtension {
Pem = "pem",
Crt = "crt"
diff --git a/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts
index 4fe6fef859..50e5a8999b 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts
@@ -14,6 +14,8 @@ export type TLinuxServerPkiSync = TRootPkiSync & {
exportFormat?: PkiSyncExportFormat;
pemCertificateExtension?: PemCertificateExtension;
combineCertificateChain?: boolean;
+ keystoreAlias?: string;
+ includeTruststore?: boolean;
includePrivateKey?: boolean;
fileMode?: string;
privateKeyFileMode?: string;
diff --git a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts
index 9ae7189340..39d02f347f 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts
@@ -17,6 +17,8 @@ export type TWindowsServerPkiSync = TRootPkiSync & {
exportFormat?: PkiSyncExportFormat;
pemCertificateExtension?: PemCertificateExtension;
combineCertificateChain?: boolean;
+ keystoreAlias?: string;
+ includeTruststore?: boolean;
includePrivateKey?: boolean;
fileAccessRules?: { identity: string; access: WindowsFileAccess }[];
healthCheckCommand?: string | null;
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx
index eca2d02729..6d38fd1677 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx
@@ -1,5 +1,5 @@
import { Detail, DetailLabel, DetailValue } from "@app/components/v3";
-import { PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
+import { PKI_SYNC_EXPORT_FORMAT_LABELS, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
import { TLinuxServerPkiSync } from "@app/hooks/api/pkiSyncs/types/linux-server-sync";
type Props = {
@@ -26,9 +26,7 @@ export const LinuxServerPkiSyncDestinationSection = ({ pkiSync }: Props) => {
</Detail>
<Detail>
<DetailLabel>Export Format</DetailLabel>
- <DetailValue>
- {exportFormat === PkiSyncExportFormat.Pkcs12 ? "PKCS#12 (.pfx)" : "PEM"}
- </DetailValue>
+ <DetailValue>{PKI_SYNC_EXPORT_FORMAT_LABELS[exportFormat] ?? exportFormat}</DetailValue>
</Detail>
</>
);
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx
index dd104d2372..16abb6abc0 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx
@@ -1,5 +1,5 @@
import { Detail, DetailLabel, DetailValue } from "@app/components/v3";
-import { PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
+import { PKI_SYNC_EXPORT_FORMAT_LABELS, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
import { TWindowsServerPkiSync } from "@app/hooks/api/pkiSyncs/types/windows-server-sync";
type Props = {
@@ -32,9 +32,7 @@ export const WindowsServerPkiSyncDestinationSection = ({ pkiSync }: Props) => {
</Detail>
<Detail>
<DetailLabel>Export Format</DetailLabel>
- <DetailValue>
- {exportFormat === PkiSyncExportFormat.Pkcs12 ? "PKCS#12 (.pfx)" : "PEM"}
- </DetailValue>
+ <DetailValue>{PKI_SYNC_EXPORT_FORMAT_LABELS[exportFormat] ?? exportFormat}</DetailValue>
</Detail>
</>
);