diff --git a/src/main/java/io/floci/cli/config/AtomicFiles.java b/src/main/java/io/floci/cli/config/AtomicFiles.java new file mode 100644 index 0000000..e490452 --- /dev/null +++ b/src/main/java/io/floci/cli/config/AtomicFiles.java @@ -0,0 +1,35 @@ +package io.floci.cli.config; + +import java.io.IOException; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Replaces a file all at once: the bytes go to a temporary file in the same directory, which is + * then moved over the target. A crash or Ctrl-C mid-write leaves the old file intact rather than a + * truncated one. + */ +final class AtomicFiles { + + private AtomicFiles() {} + + static void write(Path target, byte[] bytes) throws IOException { + Path dir = target.toAbsolutePath().getParent(); + Files.createDirectories(dir); + // A short fixed prefix: one built from the target's name would push a name already near + // the file system's length limit over it. + Path temp = Files.createTempFile(dir, ".floci-", ".tmp"); + try { + Files.write(temp, bytes); + try { + Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); + } + } finally { + Files.deleteIfExists(temp); // only still there if the move failed + } + } +} diff --git a/src/main/java/io/floci/cli/config/GlobalConfigStore.java b/src/main/java/io/floci/cli/config/GlobalConfigStore.java index 8e1e545..780ea21 100644 --- a/src/main/java/io/floci/cli/config/GlobalConfigStore.java +++ b/src/main/java/io/floci/cli/config/GlobalConfigStore.java @@ -1,11 +1,15 @@ package io.floci.cli.config; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import io.floci.cli.output.Ansi; import java.io.IOException; +import java.nio.file.AccessDeniedException; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; public class GlobalConfigStore { @@ -23,29 +27,46 @@ public class GlobalConfigStore { } public String getDefaultProduct() { - if (!Files.exists(configFile)) return "aws"; try { - GlobalConfig config = YAML.readValue(configFile.toFile(), GlobalConfig.class); - if ("az".equals(config.defaultProduct)) return "az"; - if ("gcp".equals(config.defaultProduct)) return "gcp"; - if ("oci".equals(config.defaultProduct)) return "oci"; + // Read first and ask afterwards: Files.exists also answers false for a file it is not + // allowed to look at, which would skip the warning below. + GlobalConfig config = YAML.readValue(Files.readAllBytes(configFile), GlobalConfig.class); + String product = config == null ? null : config.defaultProduct; + if ("az".equals(product)) return "az"; + if ("gcp".equals(product)) return "gcp"; + if ("oci".equals(product)) return "oci"; return "aws"; + } catch (NoSuchFileException e) { + return "aws"; // never configured } catch (IOException e) { + // Not silent: every bare command would otherwise switch to AWS without a word. + System.err.println(Ansi.yellow("Warning: ") + "Could not read " + configFile + " (" + reason(e) + + "), so the default product is aws." + + "\nCheck the file and its permissions, or run 'floci config default-product ' to rewrite it."); return "aws"; } } + private static String reason(IOException e) { + if (e instanceof AccessDeniedException) return "permission denied"; + String message = e.getMessage(); + if (message == null) return e.getClass().getSimpleName(); + int newline = message.indexOf('\n'); + return newline >= 0 ? message.substring(0, newline) : message; + } + public void setDefaultProduct(String product) throws IOException { - Files.createDirectories(configFile.getParent()); GlobalConfig config = new GlobalConfig(); config.defaultProduct = product; - YAML.writeValue(configFile.toFile(), config); + AtomicFiles.write(configFile, YAML.writeValueAsBytes(config)); } public Path configFilePath() { return configFile; } + // Unknown keys are ignored, so a file written by a newer CLI still yields its default product. + @JsonIgnoreProperties(ignoreUnknown = true) public static class GlobalConfig { @JsonProperty("default-product") public String defaultProduct = "aws"; diff --git a/src/main/java/io/floci/cli/config/ProfileStore.java b/src/main/java/io/floci/cli/config/ProfileStore.java index 11feac2..a419605 100644 --- a/src/main/java/io/floci/cli/config/ProfileStore.java +++ b/src/main/java/io/floci/cli/config/ProfileStore.java @@ -2,6 +2,7 @@ package io.floci.cli.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import io.floci.cli.output.Ansi; import java.io.IOException; import java.nio.file.Files; @@ -69,7 +70,14 @@ public class ProfileStore { .forEach(p -> { try { profiles.add(read(p)); - } catch (IOException ignored) {} + } catch (IOException e) { + // Skipped, but not silently: --profile on the same name would fail. + // The cause is quoted, not guessed: this is a parse error or a + // file that could not be opened. + System.err.println(Ansi.yellow("Warning: ") + "Could not read profile file " + p + + ": " + firstLine(e.getMessage()) + + "\nCheck the file and its permissions, or delete it."); + } }); } return profiles; @@ -81,6 +89,12 @@ public class ProfileStore { return Optional.of(read(file)); } + private static String firstLine(String message) { + if (message == null) return "unreadable"; + int newline = message.indexOf('\n'); + return newline >= 0 ? message.substring(0, newline) : message; + } + // The one read path, so list and show agree on a profile's name. private static Profile read(Path file) throws IOException { Profile profile = YAML.readValue(file.toFile(), Profile.class); @@ -106,8 +120,7 @@ public class ProfileStore { } public void save(Profile profile) throws IOException { - Files.createDirectories(profilesDir); - YAML.writeValue(profileFile(profile.name).toFile(), profile); + AtomicFiles.write(profileFile(profile.name), YAML.writeValueAsBytes(profile)); } /** diff --git a/src/test/java/io/floci/cli/unit/GlobalConfigStoreTest.java b/src/test/java/io/floci/cli/unit/GlobalConfigStoreTest.java new file mode 100644 index 0000000..a26a53b --- /dev/null +++ b/src/test/java/io/floci/cli/unit/GlobalConfigStoreTest.java @@ -0,0 +1,155 @@ +package io.floci.cli.unit; + +import io.floci.cli.config.GlobalConfigStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +class GlobalConfigStoreTest { + + @TempDir + Path tempDir; + + private GlobalConfigStore store() { + return new GlobalConfigStore(tempDir.resolve("config.yaml")); + } + + @Test + void defaultsToAwsWithoutAFile() { + assertEquals("aws", store().getDefaultProduct()); + } + + @Test + void remembersTheProductItWasGiven() throws Exception { + store().setDefaultProduct("gcp"); + + assertEquals("gcp", store().getDefaultProduct()); + } + + /** BL-042: the write goes through a temporary file, and none is left behind. */ + @Test + void writesLeaveNoTemporaryFiles() throws Exception { + store().setDefaultProduct("oci"); + store().setDefaultProduct("az"); + + try (var files = Files.list(tempDir)) { + assertEquals(List.of("config.yaml"), files.map(p -> p.getFileName().toString()).toList()); + } + } + + /** BL-043: a key this version does not know must not reset the default product. */ + @Test + void anUnknownKeyKeepsTheProduct() throws Exception { + Files.writeString(tempDir.resolve("config.yaml"), "default-product: az\nsome-future-key: true\n"); + + assertEquals("az", store().getDefaultProduct()); + } + + /** BL-043: an unreadable file still falls back to aws, but says so. */ + @Test + void anUnreadableFileWarnsAndFallsBackToAws() throws Exception { + Files.writeString(tempDir.resolve("config.yaml"), "default-product: [unterminated\n"); + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errBuf)); + String product; + try { + product = store().getDefaultProduct(); + } finally { + System.setErr(err); + } + + assertEquals("aws", product); + assertTrue(errBuf.toString().contains("Could not read"), errBuf.toString()); + assertTrue(errBuf.toString().contains("floci config default-product"), errBuf.toString()); + } + + /** A config file the user may not look at is not a missing one: it warns like any failed read. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void aFileInADirectoryThatCannotBeSearchedWarns() throws Exception { + Path home = Files.createDirectory(tempDir.resolve("home")); + Files.writeString(home.resolve("config.yaml"), "default-product: gcp\n"); + Files.setPosixFilePermissions(home, PosixFilePermissions.fromString("---------")); + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + String product; + try { + assumeFalse(Files.isExecutable(home), "permissions do not bind this user (root)"); + System.setErr(new PrintStream(errBuf)); + product = new GlobalConfigStore(home.resolve("config.yaml")).getDefaultProduct(); + } finally { + System.setErr(err); + Files.setPosixFilePermissions(home, PosixFilePermissions.fromString("rwx------")); + } + + assertEquals("aws", product); + assertTrue(errBuf.toString().contains("Could not read"), errBuf.toString()); + assertTrue(errBuf.toString().contains("permission denied"), errBuf.toString()); + } + + @Test + void aMissingDirectoryIsSilentlyAws() { + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errBuf)); + String product; + try { + product = new GlobalConfigStore(tempDir.resolve("absent").resolve("config.yaml")).getDefaultProduct(); + } finally { + System.setErr(err); + } + + assertEquals("aws", product); + assertEquals("", errBuf.toString()); + } + + /** + * BL-042: a save that cannot complete leaves the old file byte for byte. An in-place write + * would pass through a read-only directory and overwrite it. + */ + @Test + @DisabledOnOs(OS.WINDOWS) + void aFailedSaveKeepsTheOldFile() throws Exception { + Path config = tempDir.resolve("config.yaml"); + Files.writeString(config, "default-product: gcp\n"); + Files.setPosixFilePermissions(tempDir, PosixFilePermissions.fromString("r-x------")); + try { + assumeFalse(Files.isWritable(tempDir), "permissions do not bind this user (root)"); + assertThrows(IOException.class, () -> store().setDefaultProduct("az")); + } finally { + Files.setPosixFilePermissions(tempDir, PosixFilePermissions.fromString("rwx------")); + } + + assertEquals("default-product: gcp\n", Files.readString(config)); + try (var files = Files.list(tempDir)) { + assertEquals(List.of("config.yaml"), files.map(p -> p.getFileName().toString()).toList()); + } + } + + /** BL-042: when the final move fails, the temporary file is removed and the target untouched. */ + @Test + void aFailedMoveRemovesTheTemporaryFile() throws Exception { + Path inTheWay = Files.createDirectory(tempDir.resolve("config.yaml")); + Files.writeString(inTheWay.resolve("keep"), "untouched"); + + assertThrows(IOException.class, () -> store().setDefaultProduct("az")); + + assertEquals("untouched", Files.readString(inTheWay.resolve("keep"))); + try (var files = Files.list(tempDir)) { + assertEquals(List.of("config.yaml"), files.map(p -> p.getFileName().toString()).toList()); + } + } +} diff --git a/src/test/java/io/floci/cli/unit/ProfileStoreTest.java b/src/test/java/io/floci/cli/unit/ProfileStoreTest.java index 9cac6f6..2f68d78 100644 --- a/src/test/java/io/floci/cli/unit/ProfileStoreTest.java +++ b/src/test/java/io/floci/cli/unit/ProfileStoreTest.java @@ -10,14 +10,19 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeFalse; /** First coverage of the profile persistence layer, including the path-traversal guard. */ class ProfileStoreTest { @@ -232,4 +237,85 @@ class ProfileStoreTest { .sorted().toList(); assertEquals(fields, Profile.KNOWN_KEYS.stream().sorted().toList()); } + + /** BL-042: saving goes through a temporary file, and none is left behind. */ + @Test + void saveLeavesNoTemporaryFiles() throws Exception { + store().save(new Profile(ProductProfile.AWS, "one")); + store().save(new Profile(ProductProfile.AWS, "one")); + + try (var files = Files.list(tempDir)) { + assertEquals(List.of("one.yaml"), files.map(p -> p.getFileName().toString()).toList()); + } + } + + /** BL-044: an unreadable profile is skipped by list, but reported. */ + @Test + void listReportsAProfileItCannotRead() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("broken.yaml"), "port: [unterminated\n"); + Files.writeString(tempDir.resolve("fine.yaml"), "port: 4599\n"); + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errBuf)); + List listed; + try { + listed = store().list(); + } finally { + System.setErr(err); + } + + assertEquals(List.of("fine"), listed.stream().map(p -> p.name).toList()); + assertTrue(errBuf.toString().contains("broken.yaml"), errBuf.toString()); + } + + /** BL-042: a save whose final move fails removes its temporary file and leaves the target alone. */ + @Test + void aFailedSaveRemovesTheTemporaryFile() throws Exception { + Path inTheWay = Files.createDirectories(tempDir.resolve("one.yaml")); + Files.writeString(inTheWay.resolve("keep"), "untouched"); + + assertThrows(IOException.class, () -> store().save(new Profile(ProductProfile.AWS, "one"))); + + assertEquals("untouched", Files.readString(inTheWay.resolve("keep"))); + try (var files = Files.list(tempDir)) { + assertEquals(List.of("one.yaml"), files.map(p -> p.getFileName().toString()).toList()); + } + } + + /** The temporary file's name does not grow with the profile's, so a name at the limit still saves. */ + @Test + void aNameAtTheFileNameLimitStillSaves() throws Exception { + String name = "n".repeat(250); // + ".yaml" = 255 bytes, the usual file name limit + + store().save(new Profile(ProductProfile.AWS, name)); + + assertEquals(name, store().get(name).orElseThrow().name); + } + + /** A profile that cannot be opened is reported as that, with the cause, not as bad YAML. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void listReportsWhyAProfileCouldNotBeOpened() throws Exception { + Files.createDirectories(tempDir); + Path locked = tempDir.resolve("locked.yaml"); + Files.writeString(locked, "port: 4599\n"); + Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("---------")); + assumeFalse(Files.isReadable(locked), "permissions do not bind this user (root)"); + PrintStream err = System.err; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errBuf)); + List listed; + try { + listed = store().list(); + } finally { + System.setErr(err); + } + + assertEquals(List.of(), listed); + assertTrue(errBuf.toString().contains("Could not read profile file"), errBuf.toString()); + assertTrue(errBuf.toString().contains("locked.yaml"), errBuf.toString()); + assertTrue(errBuf.toString().contains("Permission denied"), errBuf.toString()); + assertFalse(errBuf.toString().contains("not valid YAML"), errBuf.toString()); + } }