Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions java-spiffe-helper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
));
}

/**
Expand All @@ -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<AuthorityEntry> authorityEntries) throws KeyStoreException {
java.security.KeyStore replacement = copyKeyStore();
update(replacement -> setAuthorityEntries(replacement, authorityEntries));
}

private void setAuthorityEntries(final java.security.KeyStore replacement,
final List<AuthorityEntry> authorityEntries) throws KeyStoreException {
List<String> aliasesToDelete = new ArrayList<>();
Enumeration<String> aliases = replacement.aliases();
while (aliases.hasMoreElements()) {
Expand All @@ -156,9 +158,27 @@ void replaceAuthorityEntries(final List<AuthorityEntry> 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 {
Expand Down Expand Up @@ -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()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -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<Future<?>> 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)
Expand Down
Loading
Loading