diff --git a/CHANGELOG.md b/CHANGELOG.md index f11b0a54..4c3c1c22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ * Reject X.509-SVID leaf certificates with a root SPIFFE ID path in `X509SvidValidator.verifyChain`, which `SpiffeTrustManager` uses for peer certificates (#510) * Ignore JWKs with an unsupported key type when parsing a JWT bundle instead of rejecting the whole bundle, per the SPIFFE bundle spec (#512) * Serialize `java-spiffe-helper` KeyStore and TrustStore files to memory before writing them, so a store or encoding failure no longer leaves an empty or partial file (#490) +* Stage every `java-spiffe-helper` KeyStore and TrustStore update in a copy and adopt it in memory only after the file write succeeds, so a failed private key or authority update is no longer persisted by a later write, and an entry that cannot be serialized no longer makes every later write fail (#490) * Stop splitting the `io.spiffe.workloadapi.internal` package between `java-spiffe-core` and the `grpc-netty-*` modules, which broke builds on the Java module path. Each `grpc-netty-*` module now registers a channel provider in its own package that core loads with `ServiceLoader`, picking the one for the current OS and architecture (#108). Upgrade `java-spiffe-core` and the `grpc-netty-*` artifact together, since an older `grpc-netty-*` jar still contains the shared package ### Build diff --git a/java-spiffe-helper/README.md b/java-spiffe-helper/README.md index ac9fd223..863c9feb 100644 --- a/java-spiffe-helper/README.md +++ b/java-spiffe-helper/README.md @@ -111,6 +111,9 @@ Each X.509 context update replaces all Helper-managed authorities with the compl and authorities for trust domains no longer present. The replacement is prepared in a separate in-memory KeyStore and the TrustStore is written once per update. If preparing or serializing the replacement fails, the live in-memory TrustStore and existing file remain unchanged. The replacement becomes the live store only after the write succeeds. +The private key entry in the KeyStore is updated the same way. If any update fails, including an I/O failure while +writing the file, the live in-memory store keeps its previous entries, so a later successful write does not persist +the failed update. Files are still written in place, so an I/O failure or crash during writing can leave a partial file. The KeyStore and TrustStore are written separately; the two files are not updated atomically together. diff --git a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStore.java b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStore.java index 3bca5fe1..ba45b8c1 100644 --- a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStore.java +++ b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStore.java @@ -110,24 +110,22 @@ private java.security.KeyStore loadKeyStoreFromFile() * @param keyEntry contains the alias, privateKey, chain, privateKey password */ void storePrivateKeyEntry(final PrivateKeyEntry keyEntry) throws KeyStoreException { - javaKeyStore.setKeyEntry( + update(candidate -> candidate.setKeyEntry( keyEntry.getAlias(), keyEntry.getPrivateKey(), keyEntry.getPassword().toCharArray(), keyEntry.getCertificateChain() - ); - this.flush(); + )); } /** * Store an Authority Entry in the KeyStore. */ void storeAuthorityEntry(final AuthorityEntry authorityEntry) throws KeyStoreException { - this.javaKeyStore.setCertificateEntry( + update(candidate -> candidate.setCertificateEntry( authorityEntry.getAlias(), authorityEntry.getCertificate() - ); - this.flush(); + )); } /** @@ -136,7 +134,11 @@ void storeAuthorityEntry(final AuthorityEntry authorityEntry) throws KeyStoreExc * File writes remain in place, so an I/O failure can still leave a partial file. */ void replaceAuthorityEntries(final List authorityEntries) throws KeyStoreException { - java.security.KeyStore replacement = copyKeyStore(); + update(replacement -> setAuthorityEntries(replacement, authorityEntries)); + } + + private void setAuthorityEntries(final java.security.KeyStore replacement, + final List authorityEntries) throws KeyStoreException { List aliasesToDelete = new ArrayList<>(); Enumeration aliases = replacement.aliases(); while (aliases.hasMoreElements()) { @@ -156,9 +158,27 @@ void replaceAuthorityEntries(final List authorityEntries) throws authorityEntry.getCertificate() ); } + } - flush(replacement); - javaKeyStore = replacement; + /** + * A change applied to a candidate copy of the live KeyStore. + */ + @FunctionalInterface + private interface Change { + void applyTo(java.security.KeyStore candidate) throws KeyStoreException; + } + + /** + * Applies a change to a copy of the live KeyStore, writes the copy to disk and only then makes it the live + * in-memory store. If applying the change or writing the file fails, the live store keeps its previous entries, so + * a later successful write never persists a failed update. + * Updates of the same KeyStore run one at a time, so the file and the live store always end up with the same content. + */ + private synchronized void update(final Change change) throws KeyStoreException { + java.security.KeyStore candidate = copyKeyStore(); + change.applyTo(candidate); + flush(candidate); + javaKeyStore = candidate; } private java.security.KeyStore copyKeyStore() throws KeyStoreException { @@ -196,10 +216,6 @@ private boolean isAuthorityAlias(final String alias) { // Flush KeyStore to disk, to the configured keyStoreFilePath. The KeyStore is serialized to memory before the file // is opened, so a store or encoding failure leaves the existing file as it was. An I/O failure while writing the // bytes can still leave a partial file. - private void flush() throws KeyStoreException { - flush(javaKeyStore); - } - private void flush(final java.security.KeyStore keyStore) throws KeyStoreException { try { KeyStoreFileWriter.write(keyStoreFilePath, outputStream -> keyStore.store(outputStream, keyStorePassword.toCharArray())); diff --git a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreTest.java b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreTest.java index d825b9e6..f1900f27 100644 --- a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreTest.java +++ b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreTest.java @@ -29,8 +29,15 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import static io.spiffe.utils.TestUtils.toUri; import static org.junit.jupiter.api.Assertions.assertArrayEquals; @@ -55,6 +62,7 @@ public class KeyStoreTest { Path tempDirectory; private static final String STORE_PASSWORD = "truststore123"; + private static final String PRIVATE_KEY_PASSWORD = "privatekey123"; @BeforeEach void setup() throws X509SvidException, URISyntaxException, X509BundleException { @@ -262,6 +270,125 @@ void testReplaceAuthorityEntries_failedWriteDoesNotChangeLiveStore(KeyStoreType assertEquals(2, stored.size()); } + @ParameterizedTest + @EnumSource(KeyStoreType.class) + void testStorePrivateKeyEntry_failedWriteDoesNotChangeLiveStore(KeyStoreType type) throws Exception { + KeyStore keyStore = newTestKeyStore(type); + X509Certificate authority = x509Bundle.getX509Authorities().iterator().next(); + keyStore.storeAuthorityEntry(authorityEntry("example.org.0", authority)); + keyStore.storeAuthorityEntry(authorityEntry("federated.org.0", authority)); + keyStore.storePrivateKeyEntry(privateKeyEntry(ENTRY_ALIAS)); + + failWritesDuring(() -> assertThrows(KeyStoreException.class, + () -> keyStore.storePrivateKeyEntry(privateKeyEntry("rejected")))); + + // A later successful write must not persist the failed update. + keyStore.storeAuthorityEntry(authorityEntry("manual", authority)); + java.security.KeyStore stored = loadTestKeyStore(type); + assertFalse(stored.containsAlias("rejected")); + assertEquals(x509Svid.getPrivateKey(), stored.getKey(ENTRY_ALIAS, PRIVATE_KEY_PASSWORD.toCharArray())); + assertEquals(authority, stored.getCertificate("example.org.0")); + assertEquals(authority, stored.getCertificate("federated.org.0")); + assertEquals(authority, stored.getCertificate("manual")); + assertEquals(4, stored.size()); + } + + @ParameterizedTest + @EnumSource(KeyStoreType.class) + void testStoreAuthorityEntry_overlappingUpdatesKeepEveryEntry(KeyStoreType type) throws Exception { + KeyStore keyStore = newTestKeyStore(type); + X509Certificate authority = x509Bundle.getX509Authorities().iterator().next(); + int updates = 8; + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(updates); + try { + List> results = new ArrayList<>(); + for (int i = 0; i < updates; i++) { + String alias = "domain" + i + ".org.0"; + results.add(executor.submit(() -> { + start.await(); + keyStore.storeAuthorityEntry(authorityEntry(alias, authority)); + return null; + })); + } + start.countDown(); + for (Future result : results) { + result.get(30, TimeUnit.SECONDS); + } + } finally { + executor.shutdownNow(); + } + + // The file holds the same entries as the live store, so one more write keeps all of them. + java.security.KeyStore stored = loadTestKeyStore(type); + assertEquals(updates, stored.size()); + keyStore.storeAuthorityEntry(authorityEntry("last.org.0", authority)); + assertEquals(updates + 1, loadTestKeyStore(type).size()); + } + + @ParameterizedTest + @EnumSource(KeyStoreType.class) + void testStoreAuthorityEntry_failedWriteDoesNotChangeLiveStore(KeyStoreType type) throws Exception { + KeyStore keyStore = newTestKeyStore(type); + X509Certificate authority = x509Bundle.getX509Authorities().iterator().next(); + keyStore.storeAuthorityEntry(authorityEntry("example.org.0", authority)); + keyStore.storeAuthorityEntry(authorityEntry("federated.org.0", authority)); + keyStore.storePrivateKeyEntry(privateKeyEntry(ENTRY_ALIAS)); + + failWritesDuring(() -> assertThrows(KeyStoreException.class, + () -> keyStore.storeAuthorityEntry(authorityEntry("example.org.0", x509Svid.getLeaf())))); + + // A later successful write must not persist the failed update. + keyStore.storeAuthorityEntry(authorityEntry("other.org.0", authority)); + java.security.KeyStore stored = loadTestKeyStore(type); + assertEquals(authority, stored.getCertificate("example.org.0")); + assertEquals(authority, stored.getCertificate("federated.org.0")); + assertEquals(authority, stored.getCertificate("other.org.0")); + assertEquals(x509Svid.getPrivateKey(), stored.getKey(ENTRY_ALIAS, PRIVATE_KEY_PASSWORD.toCharArray())); + assertEquals(4, stored.size()); + } + + @ParameterizedTest + @EnumSource(KeyStoreType.class) + void testStoreAuthorityEntry_serializationFailureDoesNotChangeLiveStore(KeyStoreType type) throws Exception { + KeyStore keyStore = newTestKeyStore(type); + X509Certificate authority = x509Bundle.getX509Authorities().iterator().next(); + keyStore.storeAuthorityEntry(authorityEntry("example.org.0", authority)); + keyStore.storeAuthorityEntry(authorityEntry("federated.org.0", authority)); + byte[] original = Files.readAllBytes(keyStoreFilePath); + + assertThrows(KeyStoreException.class, () -> keyStore.storeAuthorityEntry( + authorityEntry("broken.org.0", new UnencodableCertificate(authority)))); + + assertArrayEquals(original, Files.readAllBytes(keyStoreFilePath)); + // If the unencodable entry stayed in the live store, every later write would fail too. + keyStore.storeAuthorityEntry(authorityEntry("other.org.0", authority)); + java.security.KeyStore stored = loadTestKeyStore(type); + assertFalse(stored.containsAlias("broken.org.0")); + assertEquals(authority, stored.getCertificate("example.org.0")); + assertEquals(authority, stored.getCertificate("federated.org.0")); + assertEquals(authority, stored.getCertificate("other.org.0")); + assertEquals(3, stored.size()); + } + + // Swaps the store file for a directory so opening it for writing fails, then puts the original file back. + private void failWritesDuring(Runnable action) throws IOException { + byte[] original = Files.readAllBytes(keyStoreFilePath); + Files.delete(keyStoreFilePath); + Files.createDirectory(keyStoreFilePath); + try { + action.run(); + } finally { + Files.delete(keyStoreFilePath); + Files.write(keyStoreFilePath, original); + } + } + + private PrivateKeyEntry privateKeyEntry(String alias) { + return PrivateKeyEntry.builder().alias(alias).privateKey(x509Svid.getPrivateKey()) + .certificateChain(x509Svid.getChainArray()).password(PRIVATE_KEY_PASSWORD).build(); + } + private KeyStore newTestKeyStore(KeyStoreType type) throws KeyStoreException { keyStoreFilePath = tempDirectory.resolve("truststore"); return KeyStore.builder().keyStoreFilePath(keyStoreFilePath).keyStoreType(type) diff --git a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/UnencodableCertificate.java b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/UnencodableCertificate.java new file mode 100644 index 00000000..68d49024 --- /dev/null +++ b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/UnencodableCertificate.java @@ -0,0 +1,181 @@ +package io.spiffe.helper.keystore; + +import javax.security.auth.x500.X500Principal; +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Principal; +import java.security.PublicKey; +import java.security.SignatureException; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateExpiredException; +import java.security.cert.CertificateNotYetValidException; +import java.security.cert.CertificateParsingException; +import java.security.cert.X509Certificate; +import java.util.Date; +import java.util.List; +import java.util.Set; + +/** + * An X.509 certificate that behaves like the wrapped one, except that it cannot be encoded. Storing a KeyStore that + * contains it fails, which lets tests inject a serialization failure. + */ +final class UnencodableCertificate extends X509Certificate { + + private final X509Certificate delegate; + + UnencodableCertificate(X509Certificate delegate) { + this.delegate = delegate; + } + + @Override + public byte[] getEncoded() throws CertificateEncodingException { + throw new CertificateEncodingException("test: certificate cannot be encoded"); + } + + @Override + public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException { + delegate.checkValidity(); + } + + @Override + public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException { + delegate.checkValidity(date); + } + + @Override + public int getVersion() { + return delegate.getVersion(); + } + + @Override + public BigInteger getSerialNumber() { + return delegate.getSerialNumber(); + } + + @Override + @SuppressWarnings("deprecation") + public Principal getIssuerDN() { + return delegate.getIssuerDN(); + } + + @Override + @SuppressWarnings("deprecation") + public Principal getSubjectDN() { + return delegate.getSubjectDN(); + } + + @Override + public X500Principal getIssuerX500Principal() { + return delegate.getIssuerX500Principal(); + } + + @Override + public X500Principal getSubjectX500Principal() { + return delegate.getSubjectX500Principal(); + } + + @Override + public Date getNotBefore() { + return delegate.getNotBefore(); + } + + @Override + public Date getNotAfter() { + return delegate.getNotAfter(); + } + + @Override + public byte[] getTBSCertificate() throws CertificateEncodingException { + return delegate.getTBSCertificate(); + } + + @Override + public byte[] getSignature() { + return delegate.getSignature(); + } + + @Override + public String getSigAlgName() { + return delegate.getSigAlgName(); + } + + @Override + public String getSigAlgOID() { + return delegate.getSigAlgOID(); + } + + @Override + public byte[] getSigAlgParams() { + return delegate.getSigAlgParams(); + } + + @Override + public boolean[] getIssuerUniqueID() { + return delegate.getIssuerUniqueID(); + } + + @Override + public boolean[] getSubjectUniqueID() { + return delegate.getSubjectUniqueID(); + } + + @Override + public boolean[] getKeyUsage() { + return delegate.getKeyUsage(); + } + + @Override + public List getExtendedKeyUsage() throws CertificateParsingException { + return delegate.getExtendedKeyUsage(); + } + + @Override + public int getBasicConstraints() { + return delegate.getBasicConstraints(); + } + + @Override + public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException { + delegate.verify(key); + } + + @Override + public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, + InvalidKeyException, NoSuchProviderException, SignatureException { + delegate.verify(key, sigProvider); + } + + @Override + public PublicKey getPublicKey() { + return delegate.getPublicKey(); + } + + @Override + public boolean hasUnsupportedCriticalExtension() { + return delegate.hasUnsupportedCriticalExtension(); + } + + @Override + public Set getCriticalExtensionOIDs() { + return delegate.getCriticalExtensionOIDs(); + } + + @Override + public Set getNonCriticalExtensionOIDs() { + return delegate.getNonCriticalExtensionOIDs(); + } + + @Override + public byte[] getExtensionValue(String oid) { + return delegate.getExtensionValue(oid); + } + + @Override + public String toString() { + return delegate.toString(); + } +}