Files
floci-cli/src/test/java/io/floci/cli/unit/ProfileStoreTest.java
T
Hector Ventura 7343a539c2 fix(profile): keep legacy profile names usable and expand values consistently (#25)
* fix(profile): keep legacy profile names usable and expand values consistently

Two edges of the 0.2.2 profile work, both found by an oversight pass over what
landed since 0.2.1.

Profile names that earlier versions accepted became unreachable. The path
traversal guard added in #23 was an allow-list over the whole character set
([A-Za-z0-9._-]+), which also rejects names 0.2.1 created happily: a space, a
plus, an at sign. Such a profile stayed visible in 'config profile list' while
show, --profile and delete all refused it, so it could not even be removed
through the CLI.

The guard is now a deny-list on what actually traverses ('.', '..', and path
separators), and the guarantee is carried by resolving the file and asserting
its parent is the profiles directory. A name that is illegal on the running
platform but legal elsewhere, such as a colon on Windows, now reports a clean
message instead of InvalidPathException.

Profile values were expanded on one path and not the others. Interpolation of
${env:HOME} and friends is picocli's, applied when it fills an option default,
so 'start --profile p' expanded it while 'restart --profile p' and
'config show --profile p' read the Profile bean directly and got the literal
text. Restart therefore asked docker for a directory named '${env:HOME}/...',
which is the silent state loss #23 set out to fix.

Both now resolve through StartCommand.resolvedFor, the same provider and the
same precedence a real start invocation uses, so one profile cannot mean two
different directories. That also removes the duplicated field mapping in
RestartCommand: ProfileDefaults is the only place a profile field maps to a
flag again.

Restart now resolves the profile before stopping the container, so a profile
that fails to resolve no longer leaves the container stopped.

* fix(profile): stop denying backslash, and read the profile once in config show

Two P2s from the review on this PR, both correct.

Backslash is a separator on Windows and an ordinary file-name character on
Unix. Denying it outright orphaned a 'team\alpha' profile that 0.2.1 could
create and that list() still returns, which is the same bug class this PR
exists to fix, left half fixed. The character check is now forward slash only;
resolveInProfilesDir already rejects a real Windows traversal on the parent
assertion, so the guarantee is unchanged.

config show read the profile twice: key presence from one read, values from a
second through resolvedFor. A concurrent edit could print half of one version
next to half of another. ProfileDefaultValueProvider already memoizes the
profile it resolved, so exposing that memo gives both from one snapshot, and
resolvedFor gained a provider overload to pass it through. If the profile has
gone since the outer parse, the command now fails loudly instead of printing a
mixed row.

RestartCommand has the same shape between the outer parse and resolvedFor.
Closing it means making the outer provider reachable from commands, which is
wider than this fix; documented in place rather than left silent.
2026-09-14 21:50:32 -05:00

164 lines
6.2 KiB
Java

package io.floci.cli.unit;
import io.floci.cli.ProductProfile;
import io.floci.cli.config.Profile;
import io.floci.cli.config.ProfileStore;
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 org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/** First coverage of the profile persistence layer, including the path-traversal guard. */
class ProfileStoreTest {
@TempDir
Path tempDir;
private ProfileStore store() {
return new ProfileStore(tempDir);
}
@Test
void roundTripsEveryField() throws Exception {
Profile saved = new Profile();
saved.name = "probe";
saved.endpoint = "http://localhost:4566";
saved.container = "floci-probe";
saved.image = "floci/floci:enforced";
saved.port = 4599;
saved.persistDir = "/tmp/floci-persist-test";
saved.services = "s3,lambda";
saved.output = "json";
store().save(saved);
Profile loaded = store().get("probe").orElseThrow();
assertEquals("probe", loaded.name);
assertEquals("http://localhost:4566", loaded.endpoint);
assertEquals("floci-probe", loaded.container);
assertEquals("floci/floci:enforced", loaded.image);
assertEquals(4599, loaded.port);
assertEquals("/tmp/floci-persist-test", loaded.persistDir);
assertEquals("s3,lambda", loaded.services);
assertEquals("json", loaded.output);
}
@Test
void newProfileTakesItsProductsDefaults() throws Exception {
store().save(new Profile(ProductProfile.GCP, "g"));
Profile loaded = store().get("g").orElseThrow();
assertEquals("http://localhost:4588", loaded.endpoint);
assertEquals("floci-gcp", loaded.container);
assertEquals("floci/floci-gcp:latest", loaded.image);
assertEquals(4588, loaded.port);
}
@Test
void missingProfileIsEmptyAndDeleteReportsIt() throws Exception {
assertTrue(store().get("absent").isEmpty());
assertFalse(store().delete("absent"));
store().save(new Profile(ProductProfile.AWS, "here"));
assertTrue(store().delete("here"));
assertFalse(store().delete("here"));
}
@Test
void readsTheYmlSpellingThatListHasAlwaysAccepted() throws Exception {
Files.writeString(tempDir.resolve("staging.yml"), "container: floci-staging\n");
assertEquals("floci-staging", store().get("staging").orElseThrow().container);
assertTrue(store().delete("staging"));
}
@Test
void listBackfillsTheNameFromTheFileName() throws Exception {
Files.createDirectories(tempDir);
Files.writeString(tempDir.resolve("handwritten.yaml"), "container: floci-hand\n");
List<Profile> profiles = store().list();
assertEquals(1, profiles.size());
assertEquals("handwritten", profiles.get(0).name);
}
@ParameterizedTest
@ValueSource(strings = {"ok", "ok-1", "ok_1", "ok.1", "OK"})
void acceptsOrdinaryNames(String name) {
assertEquals(name, ProfileStore.validateName(name));
}
/**
* 0.2.1 resolved the raw name, so every one of these was creatable. An allow-list on the
* character set orphaned them: listed by 'config profile list', rejected by show, --profile
* and delete, with no way to remove them through the CLI.
*/
@ParameterizedTest
@ValueSource(strings = {"team alpha", "prod+eu", "dev@local", "staging(1)", "a b", "sam's"})
void keepsAcceptingNamesEarlierVersionsAllowed(String name) {
assertEquals(name, ProfileStore.validateName(name));
}
@Test
void aLegacyNameRoundTripsAndCanBeDeleted() throws Exception {
Files.createDirectories(tempDir);
Files.writeString(tempDir.resolve("team alpha.yaml"), "container: floci-team\n");
assertEquals("floci-team", store().get("team alpha").orElseThrow().container);
assertTrue(store().delete("team alpha"));
assertTrue(store().get("team alpha").isEmpty());
}
@ParameterizedTest
@ValueSource(strings = {"", " ", ".", "..", "../x", "../../etc/passwd", "a/b", "/abs"})
void rejectsNamesThatCouldEscapeTheProfilesDirectory(String name) {
assertThrows(IllegalArgumentException.class, () -> ProfileStore.validateName(name), name);
}
/**
* Backslash is a separator on Windows and an ordinary character on Unix, so 0.2.1 could
* create 'team\\alpha.yaml' here and list() still returns it. Denying it outright would
* orphan that profile exactly the way the character allow-list did. The escape check is
* resolveInProfilesDir, which rejects a real Windows traversal on the parent assertion.
*/
@Test
@DisabledOnOs(OS.WINDOWS)
void backslashIsAnOrdinaryCharacterOnUnix() throws Exception {
assertEquals("team\\alpha", ProfileStore.validateName("team\\alpha"));
Files.createDirectories(tempDir);
Files.writeString(tempDir.resolve("team\\alpha.yaml"), "container: floci-team\n");
assertEquals("floci-team", store().get("team\\alpha").orElseThrow().container);
assertEquals(tempDir.toAbsolutePath().normalize(),
store().profileFile("team\\alpha").getParent());
assertTrue(store().delete("team\\alpha"));
}
@Test
void rejectsNullName() {
assertThrows(IllegalArgumentException.class, () -> ProfileStore.validateName(null));
}
@Test
void traversalNeverEscapesTheProfilesDirectory() {
assertThrows(IllegalArgumentException.class, () -> store().profileFile("../../escaped"));
assertThrows(IllegalArgumentException.class, () -> store().delete("../../escaped"));
}
/** The guarantee is the resolved parent, not the character rules. */
@Test
void everyResolvedFileSitsDirectlyInTheProfilesDirectory() {
for (String name : new String[]{"ok", "team alpha", "prod+eu", "dev@local", "..leading"}) {
assertEquals(tempDir.toAbsolutePath().normalize(),
store().profileFile(name).getParent(), name);
}
}
}