From 404aafcdddd7741ec99f77414e3ab17094a6595d Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Tue, 17 Nov 2026 14:33:35 -0800 Subject: [PATCH 1/4] fix(helper): write keystore files atomically KeyStore.flush opened the destination with Files.newOutputStream, which truncates it before KeyStore.store runs. A serialization or I/O failure left an empty or partial keystore or truststore on disk. Write to a temporary file next to the destination, sync it, and move it over the old file, atomically where supported. On failure the temp file is removed and the old file stays as it was. The temp file is created with the existing file's POSIX permissions, owner and group are copied where allowed, and symlinked paths replace the link target. Refs #490 Signed-off-by: Srinivas Chippagiri --- CHANGELOG.md | 1 + .../helper/keystore/AtomicFileWriter.java | 151 ++++++++++++++++++ .../io/spiffe/helper/keystore/KeyStore.java | 13 +- .../helper/keystore/AtomicFileWriterTest.java | 146 +++++++++++++++++ 4 files changed, 306 insertions(+), 5 deletions(-) create mode 100644 java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java create mode 100644 java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index ad58a1dd..55be64e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,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) +* Write `java-spiffe-helper` KeyStore and TrustStore files through a temporary file that replaces the old one atomically, so a failed write no longer leaves an empty or partial file, and keep the existing file's permissions (#490) ### Build diff --git a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java new file mode 100644 index 00000000..4fb7ff76 --- /dev/null +++ b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java @@ -0,0 +1,151 @@ +package io.spiffe.helper.keystore; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.OpenOption; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFileAttributeView; +import java.nio.file.attribute.PosixFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +/** + * Replaces a file with new content without leaving it empty or partially written. + *

+ * The content is written to a temporary file next to the destination, synced to disk, and then moved over the + * destination, atomically where the file system supports it. If writing fails, the destination is left untouched. + *

+ * When the destination exists, the temporary file is created with its POSIX permissions, so key material is never + * readable by more users than before, and its owner and group are copied where the process is allowed to. When the + * destination is a symbolic link, the file it points to is replaced and the link is kept. + *

+ * Temporary files are named {@code ...tmp}. If the process dies while writing, one may be left + * behind; it is never read, and can be deleted. + *

+ * Package private, to be used by the KeyStore. + */ +final class AtomicFileWriter { + + private AtomicFileWriter() { + } + + /** + * Writes content to an output stream. + */ + @FunctionalInterface + interface ContentWriter { + void writeTo(OutputStream outputStream) throws IOException, GeneralSecurityException; + } + + /** + * Replaces the file at {@code target} with the content written by {@code contentWriter}. + * + * @param target the file to create or replace + * @param contentWriter writes the new content + * @throws IOException if the content cannot be written or the file cannot be replaced + * @throws GeneralSecurityException if thrown by {@code contentWriter} + */ + static void write(final Path target, final ContentWriter contentWriter) throws IOException, GeneralSecurityException { + final Path destination = Files.exists(target) ? target.toRealPath() : target.toAbsolutePath(); + final Path tempFile = destination.resolveSibling("." + destination.getFileName() + "." + UUID.randomUUID() + ".tmp"); + final PosixFileAttributes destinationAttributes = readPosixAttributes(destination); + + boolean moved = false; + try { + try (FileChannel channel = openTempFile(tempFile, destinationAttributes)) { + final OutputStream outputStream = Channels.newOutputStream(channel); + contentWriter.writeTo(outputStream); + outputStream.flush(); + channel.force(true); + } + + if (destinationAttributes != null) { + copyPosixAttributes(destinationAttributes, tempFile); + } + + move(tempFile, destination); + moved = true; + } finally { + if (!moved) { + deleteQuietly(tempFile); + } + } + } + + private static PosixFileAttributes readPosixAttributes(final Path path) throws IOException { + if (!Files.exists(path) || Files.getFileAttributeView(path, PosixFileAttributeView.class) == null) { + return null; + } + return Files.readAttributes(path, PosixFileAttributes.class); + } + + private static FileChannel openTempFile(final Path tempFile, final PosixFileAttributes destinationAttributes) throws IOException { + final Set options = new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)); + if (destinationAttributes == null) { + return FileChannel.open(tempFile, options); + } + + // Create the file with the destination's permissions right away, instead of changing them after the content + // is written, so the content is never readable by more users than the destination is. + final FileAttribute> permissions = + PosixFilePermissions.asFileAttribute(withOwnerWrite(destinationAttributes.permissions())); + return FileChannel.open(tempFile, options, permissions); + } + + // The owner needs write permission to fill the temporary file. A read-only destination gets its own + // permissions back in copyPosixAttributes, before the move. + private static Set withOwnerWrite(final Set permissions) { + final Set result = EnumSet.of(PosixFilePermission.OWNER_WRITE); + result.addAll(permissions); + return result; + } + + private static void copyPosixAttributes(final PosixFileAttributes source, final Path target) throws IOException { + final PosixFileAttributeView view = Files.getFileAttributeView(target, PosixFileAttributeView.class); + + // Changing the owner or group needs privileges the process may not have. The file then keeps the + // process's owner and group, as a newly created file would. + try { + view.setGroup(source.group()); + } catch (IOException | SecurityException e) { + // keep the default group + } + try { + view.setOwner(source.owner()); + } catch (IOException | SecurityException e) { + // keep the default owner + } + + // Set after the owner and group, since changing them can clear the setuid and setgid bits. + view.setPermissions(source.permissions()); + } + + private static void move(final Path source, final Path destination) throws IOException { + try { + Files.move(source, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING); + } + } + + private static void deleteQuietly(final Path path) { + try { + Files.deleteIfExists(path); + } catch (IOException e) { + // the temporary file is never read, leaving it behind is harmless + } + } +} 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 514ca84a..22f44e0e 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 @@ -4,9 +4,9 @@ import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; +import java.security.GeneralSecurityException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; @@ -143,11 +143,14 @@ void deleteEntriesByAliasPrefix(final String aliasPrefix) throws KeyStoreExcepti this.flush(); } - // Flush KeyStore to disk, to the configured keyStoreFilePath + // Flush KeyStore to disk, to the configured keyStoreFilePath. The file is replaced atomically, so a failed + // write leaves the previous KeyStore file in place instead of an empty or partial one. private void flush() throws KeyStoreException { - try (OutputStream outputStream = Files.newOutputStream(keyStoreFilePath)) { - javaKeyStore.store(outputStream, keyStorePassword.toCharArray()); - } catch (IOException | NoSuchAlgorithmException | CertificateException e) { + try { + AtomicFileWriter.write(keyStoreFilePath, outputStream -> javaKeyStore.store(outputStream, keyStorePassword.toCharArray())); + } catch (KeyStoreException e) { + throw e; + } catch (IOException | GeneralSecurityException e) { throw new KeyStoreException(e); } } diff --git a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java new file mode 100644 index 00000000..a9a446bf --- /dev/null +++ b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java @@ -0,0 +1,146 @@ +package io.spiffe.helper.keystore; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.GeneralSecurityException; +import java.security.KeyStoreException; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +class AtomicFileWriterTest { + + private static final byte[] OLD_CONTENT = "old content".getBytes(StandardCharsets.UTF_8); + private static final byte[] NEW_CONTENT = "new content".getBytes(StandardCharsets.UTF_8); + + @TempDir + Path dir; + + @Test + void write_createsFile() throws Exception { + Path target = dir.resolve("keystore.p12"); + + AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); + + assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target)); + assertEquals(Collections.singletonList(target), listFiles()); + } + + @Test + void write_replacesExistingFile() throws Exception { + Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); + + AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); + + assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target)); + assertEquals(Collections.singletonList(target), listFiles()); + } + + @Test + void write_ioFailure_keepsExistingFile() throws Exception { + Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); + IOException failure = new IOException("disk full"); + + IOException thrown = assertThrows(IOException.class, () -> AtomicFileWriter.write(target, out -> { + out.write(NEW_CONTENT, 0, 3); + throw failure; + })); + + assertSame(failure, thrown); + assertArrayEquals(OLD_CONTENT, Files.readAllBytes(target)); + assertEquals(Collections.singletonList(target), listFiles()); + } + + @Test + void write_serializationFailure_keepsExistingFile() throws Exception { + Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); + KeyStoreException failure = new KeyStoreException("cannot encode entry"); + + GeneralSecurityException thrown = assertThrows(GeneralSecurityException.class, () -> AtomicFileWriter.write(target, out -> { + out.write(NEW_CONTENT, 0, 3); + throw failure; + })); + + assertSame(failure, thrown); + assertArrayEquals(OLD_CONTENT, Files.readAllBytes(target)); + assertEquals(Collections.singletonList(target), listFiles()); + } + + @Test + void write_failureOnNewFile_leavesNothingBehind() throws Exception { + Path target = dir.resolve("keystore.p12"); + + assertThrows(IOException.class, () -> AtomicFileWriter.write(target, out -> { + throw new IOException("disk full"); + })); + + assertEquals(Collections.emptyList(), listFiles()); + } + + @Test + void write_preservesPosixPermissions() throws Exception { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + + Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); + Set permissions = PosixFilePermissions.fromString("rw-r-----"); + Files.setPosixFilePermissions(target, permissions); + + AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); + + assertEquals(permissions, Files.getPosixFilePermissions(target)); + assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target)); + } + + @Test + void write_readOnlyFile_keepsItReadOnly() throws Exception { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + + Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); + Set permissions = PosixFilePermissions.fromString("r--------"); + Files.setPosixFilePermissions(target, permissions); + + AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); + + assertEquals(permissions, Files.getPosixFilePermissions(target)); + assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target)); + } + + @Test + void write_symbolicLink_replacesLinkTarget() throws Exception { + Path realFile = Files.write(dir.resolve("real.p12"), OLD_CONTENT); + Path link = dir.resolve("link.p12"); + try { + Files.createSymbolicLink(link, realFile); + } catch (IOException | UnsupportedOperationException e) { + assumeTrue(false, "symbolic links are not supported: " + e); + } + + AtomicFileWriter.write(link, out -> out.write(NEW_CONTENT)); + + assertTrue(Files.isSymbolicLink(link)); + assertArrayEquals(NEW_CONTENT, Files.readAllBytes(realFile)); + } + + private List listFiles() throws IOException { + try (Stream files = Files.list(dir)) { + return files.sorted().collect(Collectors.toList()); + } + } +} From e6d0185adab548be810ef14511d5d8a64f62fc1f Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Tue, 17 Nov 2026 15:42:26 -0800 Subject: [PATCH 2/4] Keep the original NoSuchFileException when the keystore directory is missing Signed-off-by: Srinivas Chippagiri --- .../io/spiffe/helper/keystore/AtomicFileWriter.java | 6 ++++++ .../spiffe/helper/keystore/AtomicFileWriterTest.java | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java index 4fb7ff76..7b57b82f 100644 --- a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java +++ b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java @@ -6,6 +6,7 @@ import java.nio.channels.FileChannel; import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; @@ -60,6 +61,11 @@ interface ContentWriter { */ static void write(final Path target, final ContentWriter contentWriter) throws IOException, GeneralSecurityException { final Path destination = Files.exists(target) ? target.toRealPath() : target.toAbsolutePath(); + final Path parent = destination.getParent(); + if (parent != null && !Files.isDirectory(parent)) { + // Fail the same way writing to the file directly would, naming the file rather than the temporary one. + throw new NoSuchFileException(target.toString()); + } final Path tempFile = destination.resolveSibling("." + destination.getFileName() + "." + UUID.randomUUID() + ".tmp"); final PosixFileAttributes destinationAttributes = readPosixAttributes(destination); diff --git a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java index a9a446bf..9ae05d93 100644 --- a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java +++ b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java @@ -7,6 +7,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; @@ -53,6 +54,17 @@ void write_replacesExistingFile() throws Exception { assertEquals(Collections.singletonList(target), listFiles()); } + @Test + void write_missingParentDirectory_namesTheTarget() { + Path target = dir.resolve("missing").resolve("keystore.p12"); + + NoSuchFileException e = assertThrows(NoSuchFileException.class, + () -> AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT))); + + assertEquals(target.toString(), e.getMessage()); + assertTrue(Files.notExists(dir.resolve("missing"))); + } + @Test void write_ioFailure_keepsExistingFile() throws Exception { Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); From 65e2808d8b53bce26ee92f86a539ccd7e258b459 Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Tue, 17 Nov 2026 19:22:56 -0800 Subject: [PATCH 3/4] Keep group, owner and ACL on atomic keystore writes, follow dangling symlinks The temporary file is now created owner-only and gets the destination's group, owner, ACL and permissions before the move. If they can't be reproduced, the destination is overwritten in place instead. A symlink to a file that doesn't exist yet is followed so the target is created and the link stays. Signed-off-by: Srinivas Chippagiri --- .../helper/keystore/AtomicFileWriter.java | 105 +++++++++++++----- .../helper/keystore/AtomicFileWriterTest.java | 28 +++++ 2 files changed, 103 insertions(+), 30 deletions(-) diff --git a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java index 7b57b82f..e9389514 100644 --- a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java +++ b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java @@ -11,6 +11,7 @@ import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFileAttributes; @@ -29,9 +30,12 @@ * The content is written to a temporary file next to the destination, synced to disk, and then moved over the * destination, atomically where the file system supports it. If writing fails, the destination is left untouched. *

- * When the destination exists, the temporary file is created with its POSIX permissions, so key material is never - * readable by more users than before, and its owner and group are copied where the process is allowed to. When the - * destination is a symbolic link, the file it points to is replaced and the link is kept. + * When the destination exists, the temporary file is created readable by its owner only, and gets the destination's + * group, owner, ACL and permissions before it is moved into place, so key material is never readable by more users + * than before. If the process is not allowed to reproduce the destination's group, owner or ACL, the destination is + * overwritten in place instead, which keeps them as they are but is not atomic. When the destination is a symbolic + * link, including one whose target does not exist yet, the file it points to is replaced or created and the link is + * kept. *

* Temporary files are named {@code ...tmp}. If the process dies while writing, one may be left * behind; it is never read, and can be deleted. @@ -40,6 +44,8 @@ */ final class AtomicFileWriter { + private static final int MAX_LINK_HOPS = 40; + private AtomicFileWriter() { } @@ -60,7 +66,7 @@ interface ContentWriter { * @throws GeneralSecurityException if thrown by {@code contentWriter} */ static void write(final Path target, final ContentWriter contentWriter) throws IOException, GeneralSecurityException { - final Path destination = Files.exists(target) ? target.toRealPath() : target.toAbsolutePath(); + final Path destination = resolveDestination(target); final Path parent = destination.getParent(); if (parent != null && !Files.isDirectory(parent)) { // Fail the same way writing to the file directly would, naming the file rather than the temporary one. @@ -78,8 +84,11 @@ static void write(final Path target, final ContentWriter contentWriter) throws I channel.force(true); } - if (destinationAttributes != null) { - copyPosixAttributes(destinationAttributes, tempFile); + if (destinationAttributes != null && !copyAttributes(destinationAttributes, destination, tempFile)) { + // The replacement would end up with a different group, owner or ACL. Overwrite the destination + // itself, which keeps all of them. + overwriteInPlace(tempFile, destination); + return; } move(tempFile, destination); @@ -104,39 +113,75 @@ private static FileChannel openTempFile(final Path tempFile, final PosixFileAttr return FileChannel.open(tempFile, options); } - // Create the file with the destination's permissions right away, instead of changing them after the content - // is written, so the content is never readable by more users than the destination is. - final FileAttribute> permissions = - PosixFilePermissions.asFileAttribute(withOwnerWrite(destinationAttributes.permissions())); + // Readable by the owner only until the group, owner and permissions are set, so the content is never exposed + // to more users than the destination allows. + final FileAttribute> permissions = PosixFilePermissions.asFileAttribute( + EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); return FileChannel.open(tempFile, options, permissions); } - // The owner needs write permission to fill the temporary file. A read-only destination gets its own - // permissions back in copyPosixAttributes, before the move. - private static Set withOwnerWrite(final Set permissions) { - final Set result = EnumSet.of(PosixFilePermission.OWNER_WRITE); - result.addAll(permissions); - return result; - } - - private static void copyPosixAttributes(final PosixFileAttributes source, final Path target) throws IOException { - final PosixFileAttributeView view = Files.getFileAttributeView(target, PosixFileAttributeView.class); + /** + * Gives the temporary file the destination's group, owner, ACL and permissions. + * + * @return false if the group, owner or ACL could not be reproduced, in which case the temporary file must not + * replace the destination + */ + private static boolean copyAttributes(final PosixFileAttributes source, final Path destination, final Path tempFile) throws IOException { + final PosixFileAttributeView view = Files.getFileAttributeView(tempFile, PosixFileAttributeView.class); + final PosixFileAttributes current = view.readAttributes(); - // Changing the owner or group needs privileges the process may not have. The file then keeps the - // process's owner and group, as a newly created file would. try { - view.setGroup(source.group()); - } catch (IOException | SecurityException e) { - // keep the default group - } - try { - view.setOwner(source.owner()); - } catch (IOException | SecurityException e) { - // keep the default owner + if (!current.group().equals(source.group())) { + view.setGroup(source.group()); + } + if (!current.owner().equals(source.owner())) { + view.setOwner(source.owner()); + } + copyAcl(destination, tempFile); + } catch (IOException | SecurityException | UnsupportedOperationException e) { + return false; } // Set after the owner and group, since changing them can clear the setuid and setgid bits. view.setPermissions(source.permissions()); + return true; + } + + private static void copyAcl(final Path source, final Path target) throws IOException { + final AclFileAttributeView sourceView = Files.getFileAttributeView(source, AclFileAttributeView.class); + final AclFileAttributeView targetView = Files.getFileAttributeView(target, AclFileAttributeView.class); + if (sourceView != null && targetView != null) { + targetView.setAcl(sourceView.getAcl()); + } + } + + private static void overwriteInPlace(final Path tempFile, final Path destination) throws IOException { + try (OutputStream out = Files.newOutputStream(destination)) { + Files.copy(tempFile, out); + } finally { + deleteQuietly(tempFile); + } + } + + /** + * Follows symbolic links to the file that should be replaced. A link whose target does not exist yet resolves to + * that target, so it gets created and the link is kept. + */ + private static Path resolveDestination(final Path target) throws IOException { + if (Files.exists(target)) { + return target.toRealPath(); + } + Path current = target.toAbsolutePath(); + for (int hops = 0; Files.isSymbolicLink(current); hops++) { + if (hops >= MAX_LINK_HOPS) { + throw new IOException("Too many levels of symbolic links: " + target); + } + current = current.resolveSibling(Files.readSymbolicLink(current)).normalize(); + if (Files.exists(current)) { + return current.toRealPath(); + } + } + return current; } private static void move(final Path source, final Path destination) throws IOException { diff --git a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java index 9ae05d93..77087565 100644 --- a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java +++ b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java @@ -9,6 +9,7 @@ import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; +import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.security.GeneralSecurityException; @@ -150,6 +151,33 @@ void write_symbolicLink_replacesLinkTarget() throws Exception { assertArrayEquals(NEW_CONTENT, Files.readAllBytes(realFile)); } + @Test + void write_danglingRelativeSymbolicLink_createsLinkTargetAndKeepsLink() throws Exception { + Path link = dir.resolve("link.p12"); + try { + Files.createSymbolicLink(link, Paths.get("real.p12")); + } catch (IOException | UnsupportedOperationException e) { + assumeTrue(false, "symbolic links are not supported: " + e); + } + + AtomicFileWriter.write(link, out -> out.write(NEW_CONTENT)); + + assertTrue(Files.isSymbolicLink(link)); + assertArrayEquals(NEW_CONTENT, Files.readAllBytes(dir.resolve("real.p12"))); + } + + @Test + void write_newPosixFileDoesNotLeaveGroupOrOtherAccessOnTemporaryFile() throws Exception { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + + Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); + Files.setPosixFilePermissions(target, PosixFilePermissions.fromString("rw-------")); + + AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); + + assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(target)); + } + private List listFiles() throws IOException { try (Stream files = Files.list(dir)) { return files.sorted().collect(Collectors.toList()); From 47c3c818b47f062469a10e5d9b915bbcc4fa5aaa Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Tue, 17 Nov 2026 21:30:00 -0800 Subject: [PATCH 4/4] Serialize the keystore to memory and write it in place Drop the temporary file and rename. flush() now serializes the KeyStore to a byte array first and then writes the bytes into the existing file, so a store or encoding failure never touches the file, and links, owner, group, mode and ACLs stay as they are. An I/O error or crash halfway through the write can still leave a partial file. Signed-off-by: Srinivas Chippagiri --- CHANGELOG.md | 2 +- .../helper/keystore/AtomicFileWriter.java | 202 ------------------ .../io/spiffe/helper/keystore/KeyStore.java | 7 +- .../helper/keystore/KeyStoreFileWriter.java | 48 +++++ ...rTest.java => KeyStoreFileWriterTest.java} | 119 ++++++----- 5 files changed, 113 insertions(+), 265 deletions(-) delete mode 100644 java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java create mode 100644 java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStoreFileWriter.java rename java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/{AtomicFileWriterTest.java => KeyStoreFileWriterTest.java} (56%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 55be64e9..b71e0f97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,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) -* Write `java-spiffe-helper` KeyStore and TrustStore files through a temporary file that replaces the old one atomically, so a failed write no longer leaves an empty or partial file, and keep the existing file's permissions (#490) +* 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) ### Build diff --git a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java deleted file mode 100644 index e9389514..00000000 --- a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/AtomicFileWriter.java +++ /dev/null @@ -1,202 +0,0 @@ -package io.spiffe.helper.keystore; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.channels.Channels; -import java.nio.channels.FileChannel; -import java.nio.file.AtomicMoveNotSupportedException; -import java.nio.file.Files; -import java.nio.file.NoSuchFileException; -import java.nio.file.OpenOption; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.AclFileAttributeView; -import java.nio.file.attribute.FileAttribute; -import java.nio.file.attribute.PosixFileAttributeView; -import java.nio.file.attribute.PosixFileAttributes; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.GeneralSecurityException; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -/** - * Replaces a file with new content without leaving it empty or partially written. - *

- * The content is written to a temporary file next to the destination, synced to disk, and then moved over the - * destination, atomically where the file system supports it. If writing fails, the destination is left untouched. - *

- * When the destination exists, the temporary file is created readable by its owner only, and gets the destination's - * group, owner, ACL and permissions before it is moved into place, so key material is never readable by more users - * than before. If the process is not allowed to reproduce the destination's group, owner or ACL, the destination is - * overwritten in place instead, which keeps them as they are but is not atomic. When the destination is a symbolic - * link, including one whose target does not exist yet, the file it points to is replaced or created and the link is - * kept. - *

- * Temporary files are named {@code ...tmp}. If the process dies while writing, one may be left - * behind; it is never read, and can be deleted. - *

- * Package private, to be used by the KeyStore. - */ -final class AtomicFileWriter { - - private static final int MAX_LINK_HOPS = 40; - - private AtomicFileWriter() { - } - - /** - * Writes content to an output stream. - */ - @FunctionalInterface - interface ContentWriter { - void writeTo(OutputStream outputStream) throws IOException, GeneralSecurityException; - } - - /** - * Replaces the file at {@code target} with the content written by {@code contentWriter}. - * - * @param target the file to create or replace - * @param contentWriter writes the new content - * @throws IOException if the content cannot be written or the file cannot be replaced - * @throws GeneralSecurityException if thrown by {@code contentWriter} - */ - static void write(final Path target, final ContentWriter contentWriter) throws IOException, GeneralSecurityException { - final Path destination = resolveDestination(target); - final Path parent = destination.getParent(); - if (parent != null && !Files.isDirectory(parent)) { - // Fail the same way writing to the file directly would, naming the file rather than the temporary one. - throw new NoSuchFileException(target.toString()); - } - final Path tempFile = destination.resolveSibling("." + destination.getFileName() + "." + UUID.randomUUID() + ".tmp"); - final PosixFileAttributes destinationAttributes = readPosixAttributes(destination); - - boolean moved = false; - try { - try (FileChannel channel = openTempFile(tempFile, destinationAttributes)) { - final OutputStream outputStream = Channels.newOutputStream(channel); - contentWriter.writeTo(outputStream); - outputStream.flush(); - channel.force(true); - } - - if (destinationAttributes != null && !copyAttributes(destinationAttributes, destination, tempFile)) { - // The replacement would end up with a different group, owner or ACL. Overwrite the destination - // itself, which keeps all of them. - overwriteInPlace(tempFile, destination); - return; - } - - move(tempFile, destination); - moved = true; - } finally { - if (!moved) { - deleteQuietly(tempFile); - } - } - } - - private static PosixFileAttributes readPosixAttributes(final Path path) throws IOException { - if (!Files.exists(path) || Files.getFileAttributeView(path, PosixFileAttributeView.class) == null) { - return null; - } - return Files.readAttributes(path, PosixFileAttributes.class); - } - - private static FileChannel openTempFile(final Path tempFile, final PosixFileAttributes destinationAttributes) throws IOException { - final Set options = new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)); - if (destinationAttributes == null) { - return FileChannel.open(tempFile, options); - } - - // Readable by the owner only until the group, owner and permissions are set, so the content is never exposed - // to more users than the destination allows. - final FileAttribute> permissions = PosixFilePermissions.asFileAttribute( - EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); - return FileChannel.open(tempFile, options, permissions); - } - - /** - * Gives the temporary file the destination's group, owner, ACL and permissions. - * - * @return false if the group, owner or ACL could not be reproduced, in which case the temporary file must not - * replace the destination - */ - private static boolean copyAttributes(final PosixFileAttributes source, final Path destination, final Path tempFile) throws IOException { - final PosixFileAttributeView view = Files.getFileAttributeView(tempFile, PosixFileAttributeView.class); - final PosixFileAttributes current = view.readAttributes(); - - try { - if (!current.group().equals(source.group())) { - view.setGroup(source.group()); - } - if (!current.owner().equals(source.owner())) { - view.setOwner(source.owner()); - } - copyAcl(destination, tempFile); - } catch (IOException | SecurityException | UnsupportedOperationException e) { - return false; - } - - // Set after the owner and group, since changing them can clear the setuid and setgid bits. - view.setPermissions(source.permissions()); - return true; - } - - private static void copyAcl(final Path source, final Path target) throws IOException { - final AclFileAttributeView sourceView = Files.getFileAttributeView(source, AclFileAttributeView.class); - final AclFileAttributeView targetView = Files.getFileAttributeView(target, AclFileAttributeView.class); - if (sourceView != null && targetView != null) { - targetView.setAcl(sourceView.getAcl()); - } - } - - private static void overwriteInPlace(final Path tempFile, final Path destination) throws IOException { - try (OutputStream out = Files.newOutputStream(destination)) { - Files.copy(tempFile, out); - } finally { - deleteQuietly(tempFile); - } - } - - /** - * Follows symbolic links to the file that should be replaced. A link whose target does not exist yet resolves to - * that target, so it gets created and the link is kept. - */ - private static Path resolveDestination(final Path target) throws IOException { - if (Files.exists(target)) { - return target.toRealPath(); - } - Path current = target.toAbsolutePath(); - for (int hops = 0; Files.isSymbolicLink(current); hops++) { - if (hops >= MAX_LINK_HOPS) { - throw new IOException("Too many levels of symbolic links: " + target); - } - current = current.resolveSibling(Files.readSymbolicLink(current)).normalize(); - if (Files.exists(current)) { - return current.toRealPath(); - } - } - return current; - } - - private static void move(final Path source, final Path destination) throws IOException { - try { - Files.move(source, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); - } catch (AtomicMoveNotSupportedException e) { - Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING); - } - } - - private static void deleteQuietly(final Path path) { - try { - Files.deleteIfExists(path); - } catch (IOException e) { - // the temporary file is never read, leaving it behind is harmless - } - } -} 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 22f44e0e..5424dd67 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 @@ -143,11 +143,12 @@ void deleteEntriesByAliasPrefix(final String aliasPrefix) throws KeyStoreExcepti this.flush(); } - // Flush KeyStore to disk, to the configured keyStoreFilePath. The file is replaced atomically, so a failed - // write leaves the previous KeyStore file in place instead of an empty or partial one. + // 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 { try { - AtomicFileWriter.write(keyStoreFilePath, outputStream -> javaKeyStore.store(outputStream, keyStorePassword.toCharArray())); + KeyStoreFileWriter.write(keyStoreFilePath, outputStream -> javaKeyStore.store(outputStream, keyStorePassword.toCharArray())); } catch (KeyStoreException e) { throw e; } catch (IOException | GeneralSecurityException e) { diff --git a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStoreFileWriter.java b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStoreFileWriter.java new file mode 100644 index 00000000..8a8763c8 --- /dev/null +++ b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStoreFileWriter.java @@ -0,0 +1,48 @@ +package io.spiffe.helper.keystore; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; + +/** + * Writes a KeyStore file by serializing it to memory first and then writing the bytes into the file in place. + *

+ * If serializing fails, the file is not touched. Writing in place follows symbolic links and keeps the file's owner, + * group, permissions and ACLs. An I/O error or a crash while the bytes are being written can still leave the file + * partially written. + *

+ * Package private, to be used by the KeyStore. + */ +final class KeyStoreFileWriter { + + private KeyStoreFileWriter() { + } + + /** + * Writes content to an output stream. + */ + @FunctionalInterface + interface ContentWriter { + void writeTo(OutputStream outputStream) throws IOException, GeneralSecurityException; + } + + /** + * Serializes the content written by {@code contentWriter} to memory, then writes it to {@code path}, creating the + * file if it doesn't exist. + * + * @param path the file to write + * @param contentWriter writes the new content + * @throws IOException if thrown by {@code contentWriter} or the file cannot be written + * @throws GeneralSecurityException if thrown by {@code contentWriter} + */ + static void write(final Path path, final ContentWriter contentWriter) throws IOException, GeneralSecurityException { + final ByteArrayOutputStream content = new ByteArrayOutputStream(); + contentWriter.writeTo(content); + try (OutputStream outputStream = Files.newOutputStream(path)) { + content.writeTo(outputStream); + } + } +} diff --git a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreFileWriterTest.java similarity index 56% rename from java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java rename to java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreFileWriterTest.java index 77087565..1318c731 100644 --- a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/AtomicFileWriterTest.java +++ b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreFileWriterTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.io.TempDir; import java.io.IOException; +import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; @@ -14,23 +15,29 @@ import java.nio.file.attribute.PosixFilePermissions; import java.security.GeneralSecurityException; import java.security.KeyStoreException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import static io.spiffe.utils.TestUtils.toUri; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; -class AtomicFileWriterTest { +class KeyStoreFileWriterTest { private static final byte[] OLD_CONTENT = "old content".getBytes(StandardCharsets.UTF_8); private static final byte[] NEW_CONTENT = "new content".getBytes(StandardCharsets.UTF_8); + private static final char[] PASSWORD = "password".toCharArray(); + private static final String ALIAS = "bundle"; @TempDir Path dir; @@ -39,7 +46,7 @@ class AtomicFileWriterTest { void write_createsFile() throws Exception { Path target = dir.resolve("keystore.p12"); - AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); + KeyStoreFileWriter.write(target, out -> out.write(NEW_CONTENT)); assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target)); assertEquals(Collections.singletonList(target), listFiles()); @@ -49,133 +56,127 @@ void write_createsFile() throws Exception { void write_replacesExistingFile() throws Exception { Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); - AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); + KeyStoreFileWriter.write(target, out -> out.write(NEW_CONTENT)); assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target)); assertEquals(Collections.singletonList(target), listFiles()); } @Test - void write_missingParentDirectory_namesTheTarget() { + void write_missingParentDirectory_throwsNoSuchFile() { Path target = dir.resolve("missing").resolve("keystore.p12"); - NoSuchFileException e = assertThrows(NoSuchFileException.class, - () -> AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT))); + assertThrows(NoSuchFileException.class, () -> KeyStoreFileWriter.write(target, out -> out.write(NEW_CONTENT))); - assertEquals(target.toString(), e.getMessage()); assertTrue(Files.notExists(dir.resolve("missing"))); } @Test - void write_ioFailure_keepsExistingFile() throws Exception { - Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); - IOException failure = new IOException("disk full"); + void write_serializationFailure_keepsExistingKeyStore_thenUpdates() throws Exception { + Path target = dir.resolve("keystore.p12"); + java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12"); + keyStore.load(null, PASSWORD); + KeyStoreFileWriter.write(target, out -> keyStore.store(out, PASSWORD)); + byte[] original = Files.readAllBytes(target); - IOException thrown = assertThrows(IOException.class, () -> AtomicFileWriter.write(target, out -> { - out.write(NEW_CONTENT, 0, 3); + keyStore.setCertificateEntry(ALIAS, loadCertificate()); + KeyStoreException failure = new KeyStoreException("cannot encode entry"); + GeneralSecurityException thrown = assertThrows(GeneralSecurityException.class, () -> KeyStoreFileWriter.write(target, out -> { + keyStore.store(out, PASSWORD); throw failure; })); assertSame(failure, thrown); - assertArrayEquals(OLD_CONTENT, Files.readAllBytes(target)); - assertEquals(Collections.singletonList(target), listFiles()); + assertArrayEquals(original, Files.readAllBytes(target)); + assertFalse(load(target).containsAlias(ALIAS)); + + KeyStoreFileWriter.write(target, out -> keyStore.store(out, PASSWORD)); + + assertTrue(load(target).containsAlias(ALIAS)); } @Test - void write_serializationFailure_keepsExistingFile() throws Exception { + void write_ioFailureWhileSerializing_keepsExistingFile() throws Exception { Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); - KeyStoreException failure = new KeyStoreException("cannot encode entry"); + IOException failure = new IOException("encoding failed"); - GeneralSecurityException thrown = assertThrows(GeneralSecurityException.class, () -> AtomicFileWriter.write(target, out -> { + IOException thrown = assertThrows(IOException.class, () -> KeyStoreFileWriter.write(target, out -> { out.write(NEW_CONTENT, 0, 3); throw failure; })); assertSame(failure, thrown); assertArrayEquals(OLD_CONTENT, Files.readAllBytes(target)); - assertEquals(Collections.singletonList(target), listFiles()); } @Test void write_failureOnNewFile_leavesNothingBehind() throws Exception { Path target = dir.resolve("keystore.p12"); - assertThrows(IOException.class, () -> AtomicFileWriter.write(target, out -> { - throw new IOException("disk full"); + assertThrows(IOException.class, () -> KeyStoreFileWriter.write(target, out -> { + throw new IOException("encoding failed"); })); assertEquals(Collections.emptyList(), listFiles()); } @Test - void write_preservesPosixPermissions() throws Exception { - assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); - - Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); - Set permissions = PosixFilePermissions.fromString("rw-r-----"); - Files.setPosixFilePermissions(target, permissions); - - AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); - - assertEquals(permissions, Files.getPosixFilePermissions(target)); - assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target)); - } - - @Test - void write_readOnlyFile_keepsItReadOnly() throws Exception { + void write_keepsOwnerOnlyPermissions() throws Exception { assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); - Set permissions = PosixFilePermissions.fromString("r--------"); + Set permissions = PosixFilePermissions.fromString("rw-------"); Files.setPosixFilePermissions(target, permissions); - AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); + KeyStoreFileWriter.write(target, out -> out.write(NEW_CONTENT)); assertEquals(permissions, Files.getPosixFilePermissions(target)); assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target)); } @Test - void write_symbolicLink_replacesLinkTarget() throws Exception { + void write_symbolicLink_writesLinkTarget() throws Exception { Path realFile = Files.write(dir.resolve("real.p12"), OLD_CONTENT); Path link = dir.resolve("link.p12"); - try { - Files.createSymbolicLink(link, realFile); - } catch (IOException | UnsupportedOperationException e) { - assumeTrue(false, "symbolic links are not supported: " + e); - } + createSymbolicLink(link, realFile); - AtomicFileWriter.write(link, out -> out.write(NEW_CONTENT)); + KeyStoreFileWriter.write(link, out -> out.write(NEW_CONTENT)); assertTrue(Files.isSymbolicLink(link)); assertArrayEquals(NEW_CONTENT, Files.readAllBytes(realFile)); } @Test - void write_danglingRelativeSymbolicLink_createsLinkTargetAndKeepsLink() throws Exception { + void write_danglingSymbolicLink_createsLinkTargetAndKeepsLink() throws Exception { Path link = dir.resolve("link.p12"); - try { - Files.createSymbolicLink(link, Paths.get("real.p12")); - } catch (IOException | UnsupportedOperationException e) { - assumeTrue(false, "symbolic links are not supported: " + e); - } + createSymbolicLink(link, Paths.get("real.p12")); - AtomicFileWriter.write(link, out -> out.write(NEW_CONTENT)); + KeyStoreFileWriter.write(link, out -> out.write(NEW_CONTENT)); assertTrue(Files.isSymbolicLink(link)); assertArrayEquals(NEW_CONTENT, Files.readAllBytes(dir.resolve("real.p12"))); } - @Test - void write_newPosixFileDoesNotLeaveGroupOrOtherAccessOnTemporaryFile() throws Exception { - assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); - - Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT); - Files.setPosixFilePermissions(target, PosixFilePermissions.fromString("rw-------")); + private static void createSymbolicLink(Path link, Path target) { + try { + Files.createSymbolicLink(link, target); + } catch (IOException | UnsupportedOperationException e) { + assumeTrue(false, "symbolic links are not supported: " + e); + } + } - AtomicFileWriter.write(target, out -> out.write(NEW_CONTENT)); + private static Certificate loadCertificate() throws Exception { + try (InputStream in = Files.newInputStream(Paths.get(toUri("testdata/bundle.pem")))) { + return CertificateFactory.getInstance("X.509").generateCertificate(in); + } + } - assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(target)); + private static java.security.KeyStore load(Path path) throws Exception { + java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12"); + try (InputStream in = Files.newInputStream(path)) { + keyStore.load(in, PASSWORD); + } + return keyStore; } private List listFiles() throws IOException {