mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
feat(az): configure the az CLI against floci-az with floci az setup (#29)
This commit is contained in:
1 parent
dd38f6dc27
commit
7b58a38c5a
27 files changed
+1587
-12
No files matched your search
@@ -0,0 +1,159 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import io.floci.cli.commands.az.AzEnvCommand;
|
||||
import io.floci.cli.commands.az.AzSetupCommand;
|
||||
import io.floci.cli.http.FlociException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import picocli.CommandLine;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AzEnvCommandTest {
|
||||
|
||||
// Containers nobody runs, so the configured endpoint is used and Docker finds nothing.
|
||||
private static final String A = "floci-az-envtest-a";
|
||||
private static final String B = "floci-az-envtest-b";
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private AzSetupCommand.CertSource certs = endpoint -> {
|
||||
throw new FlociException("Connection refused");
|
||||
};
|
||||
|
||||
private String stderr;
|
||||
|
||||
private String run(String container, String... args) {
|
||||
PrintStream out = System.out;
|
||||
PrintStream err = System.err;
|
||||
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outBuf));
|
||||
System.setErr(new PrintStream(errBuf));
|
||||
try {
|
||||
String[] all = new String[args.length + 2];
|
||||
all[0] = "--container";
|
||||
all[1] = container;
|
||||
System.arraycopy(args, 0, all, 2, args.length);
|
||||
assertEquals(0, new CommandLine(new AzEnvCommand(tempDir, certs)).execute(all));
|
||||
} finally {
|
||||
System.setOut(out);
|
||||
System.setErr(err);
|
||||
}
|
||||
stderr = errBuf.toString();
|
||||
return outBuf.toString();
|
||||
}
|
||||
|
||||
private Path dir(String container) {
|
||||
return tempDir.resolve("az").resolve(container);
|
||||
}
|
||||
|
||||
private void setUpDone(String container) throws Exception {
|
||||
Files.createDirectories(dir(container).resolve("azure-config"));
|
||||
Files.writeString(dir(container).resolve("ca-bundle.pem"), "bundle");
|
||||
Files.writeString(dir(container).resolve("floci-az-ca.pem"), "saved-ca\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void beforeSetupOnlyTheStorageVariables() {
|
||||
String out = run(A);
|
||||
|
||||
assertTrue(out.contains("AZURE_STORAGE_CONNECTION_STRING"), out);
|
||||
assertFalse(out.contains("AZURE_CONFIG_DIR"), out);
|
||||
assertFalse(out.contains("REQUESTS_CA_BUNDLE"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void afterSetupPointsAzAtThatInstancesConfig() throws Exception {
|
||||
setUpDone(A);
|
||||
|
||||
String out = run(A);
|
||||
|
||||
assertTrue(out.contains("export AZURE_CONFIG_DIR='" + dir(A).resolve("azure-config").toAbsolutePath() + "'"), out);
|
||||
assertTrue(out.contains("export REQUESTS_CA_BUNDLE='" + dir(A).resolve("ca-bundle.pem").toAbsolutePath() + "'"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherInstanceDoesNotSeeIt() throws Exception {
|
||||
setUpDone(A);
|
||||
|
||||
assertFalse(run(B).contains("AZURE_CONFIG_DIR"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void afterAGlobalSetupOnlyTheBundle() throws Exception {
|
||||
Files.createDirectories(dir(A));
|
||||
Files.writeString(dir(A).resolve("ca-bundle.pem"), "bundle");
|
||||
|
||||
String out = run(A);
|
||||
|
||||
// No isolated config to point at, and a stale one from another instance is cleared.
|
||||
assertFalse(out.contains("export AZURE_CONFIG_DIR"), out);
|
||||
assertTrue(out.contains("unset AZURE_CONFIG_DIR"), out);
|
||||
assertTrue(out.contains("REQUESTS_CA_BUNDLE"), out);
|
||||
assertTrue(run(A, "--shell", "fish").contains("set -e AZURE_CONFIG_DIR"));
|
||||
assertTrue(run(A, "--shell", "powershell").contains("Remove-Item Env:AZURE_CONFIG_DIR"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void beforeAnySetupAnInheritedConfigDirIsLeftAlone() {
|
||||
// Nothing was set up for this instance, so a user's own AZURE_CONFIG_DIR is not ours to clear.
|
||||
assertFalse(run(A).contains("AZURE_CONFIG_DIR"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkVarsModeAndOtherShellsGetThemToo() throws Exception {
|
||||
setUpDone(A);
|
||||
|
||||
assertTrue(run(A, "--format", "sdk-vars").contains("export AZURE_CONFIG_DIR="));
|
||||
assertTrue(run(A, "--shell", "fish").contains("set -x REQUESTS_CA_BUNDLE '"));
|
||||
assertTrue(run(A, "--shell", "powershell").contains("$env:AZURE_CONFIG_DIR = '"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonCarriesThem() throws Exception {
|
||||
setUpDone(A);
|
||||
|
||||
String out = run(A, "-o", "json");
|
||||
|
||||
assertTrue(out.contains("\"AZURE_CONFIG_DIR\""), out);
|
||||
assertTrue(out.contains("\"REQUESTS_CA_BUNDLE\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void warnsOnStderrWhenTheServersCertificateChanged() throws Exception {
|
||||
setUpDone(A);
|
||||
certs = endpoint -> "a-new-ca\n";
|
||||
|
||||
String out = run(A);
|
||||
|
||||
assertTrue(stderr.contains("certificate changed"), stderr);
|
||||
assertTrue(stderr.contains("floci az setup --container " + A), stderr);
|
||||
assertFalse(out.contains("certificate changed"), "the warning must not reach eval: " + out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noWarningWhenTheCertificateMatches() throws Exception {
|
||||
setUpDone(A);
|
||||
certs = endpoint -> "saved-ca";
|
||||
|
||||
run(A);
|
||||
|
||||
assertFalse(stderr.contains("certificate changed"), stderr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noWarningWhenTheServerIsDown() throws Exception {
|
||||
setUpDone(A);
|
||||
|
||||
run(A);
|
||||
|
||||
assertFalse(stderr.contains("Warning"), stderr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import io.floci.cli.azcli.AzCli;
|
||||
import io.floci.cli.azcli.AzCliNotFoundException;
|
||||
import io.floci.cli.commands.az.AzSetupCommand;
|
||||
import io.floci.cli.docker.DockerClient;
|
||||
import io.floci.cli.docker.DockerClient.ContainerInfo;
|
||||
import io.floci.cli.http.FlociException;
|
||||
import io.floci.cli.http.TlsUnavailableException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import picocli.CommandLine;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AzSetupCommandTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private String pem;
|
||||
private FakeAz az;
|
||||
|
||||
/** Records every az call; a command line can be made to fail, and 'cloud show' output set. */
|
||||
static class FakeAz implements AzCli {
|
||||
final List<List<String>> calls = new ArrayList<>();
|
||||
final List<Map<String, String>> envs = new ArrayList<>();
|
||||
final Set<String> failing = new HashSet<>();
|
||||
final Set<String> clouds = new HashSet<>();
|
||||
String activeCloud = "AzureCloud";
|
||||
boolean installed = true;
|
||||
|
||||
@Override
|
||||
public Result run(List<String> args, Map<String, String> env) throws AzCliNotFoundException {
|
||||
if (!installed) throw new AzCliNotFoundException("nope");
|
||||
calls.add(List.copyOf(args));
|
||||
envs.add(new HashMap<>(env));
|
||||
String line = String.join(" ", args);
|
||||
if (failing.stream().anyMatch(line::startsWith)) return new Result(1, "ERROR: " + line);
|
||||
if (line.startsWith("cloud show --query name")) return new Result(0, activeCloud + "\n");
|
||||
if (line.startsWith("cloud show -n ")) return new Result(clouds.contains(args.get(3)) ? 0 : 3, "");
|
||||
if (line.startsWith("cloud register -n ")) clouds.add(args.get(3));
|
||||
if (line.startsWith("cloud set -n ")) activeCloud = args.get(3);
|
||||
return new Result(0, "");
|
||||
}
|
||||
|
||||
List<String> lines() {
|
||||
return calls.stream().map(c -> String.join(" ", c)).toList();
|
||||
}
|
||||
}
|
||||
|
||||
/** Never touches Docker: no container found, so the configured endpoint is used. */
|
||||
static class NoDocker extends DockerClient {
|
||||
@Override
|
||||
public Optional<ContainerInfo> inspectContainer(String name) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** Where an instance's state lands: {@code <root>/az/<container>/}. */
|
||||
private Path dir(String container) {
|
||||
return tempDir.resolve("az").resolve(container);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
pem = AzTestCerts.somePem();
|
||||
az = new FakeAz();
|
||||
}
|
||||
|
||||
private int run(AzSetupCommand.CertSource certs, String... args) {
|
||||
return new CommandLine(new AzSetupCommand(tempDir, az, certs, new NoDocker(), Duration.ZERO)).execute(args);
|
||||
}
|
||||
|
||||
private int run(String... args) {
|
||||
return run(endpoint -> pem, args);
|
||||
}
|
||||
|
||||
private String stdout(Runnable action) {
|
||||
PrintStream original = System.out;
|
||||
ByteArrayOutputStream buf = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(buf));
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
System.setOut(original);
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
void runsTheCompatSuiteRecipeAgainstTheIsolatedConfig() throws Exception {
|
||||
assertEquals(0, run("--endpoint", "http://localhost:4577"));
|
||||
|
||||
assertEquals(List.of(
|
||||
"cloud show -n floci-az -o none",
|
||||
"cloud register -n floci-az"
|
||||
+ " --endpoint-resource-manager https://localhost:4577/"
|
||||
+ " --endpoint-active-directory https://localhost:4577"
|
||||
+ " --endpoint-active-directory-resource-id https://localhost:4577/"
|
||||
+ " --endpoint-active-directory-graph-resource-id https://localhost:4577/"
|
||||
+ " --suffix-storage-endpoint core.windows.net"
|
||||
+ " --suffix-keyvault-dns .vault.azure.net"
|
||||
+ " --suffix-acr-login-server-endpoint .azurecr.io",
|
||||
"cloud set -n floci-az",
|
||||
"config set core.instance_discovery=false",
|
||||
"login --service-principal -u 00000000-0000-0000-0000-000000000003 -p fake-secret"
|
||||
+ " --tenant 00000000-0000-0000-0000-000000000002 -o none",
|
||||
"account set --subscription 00000000-0000-0000-0000-000000000001"), az.lines());
|
||||
|
||||
Path configDir = dir("floci-az").resolve("azure-config");
|
||||
Path bundle = dir("floci-az").resolve("ca-bundle.pem");
|
||||
assertTrue(Files.isDirectory(configDir));
|
||||
assertTrue(Files.readString(bundle).endsWith(pem.strip() + "\n"));
|
||||
for (Map<String, String> env : az.envs) {
|
||||
assertEquals(configDir.toAbsolutePath().toString(), env.get("AZURE_CONFIG_DIR"));
|
||||
assertEquals(bundle.toAbsolutePath().toString(), env.get("REQUESTS_CA_BUNDLE"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void reRunningUpdatesTheCloudInsteadOfRegisteringItAgain() {
|
||||
assertEquals(0, run());
|
||||
az.calls.clear();
|
||||
|
||||
assertEquals(0, run());
|
||||
|
||||
assertTrue(az.lines().get(1).startsWith("cloud update -n floci-az "), az.lines().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void globalLeavesTheDefaultConfigDirAndUnsetsAnInheritedOne() {
|
||||
assertEquals(0, run("--global"));
|
||||
|
||||
assertFalse(Files.exists(dir("floci-az").resolve("azure-config")));
|
||||
for (Map<String, String> env : az.envs) {
|
||||
// Present with a null value: the runner removes it, so an eval'd 'floci az env'
|
||||
// in the user's shell cannot send a --global setup into the isolated config.
|
||||
assertTrue(env.containsKey("AZURE_CONFIG_DIR"));
|
||||
assertNull(env.get("AZURE_CONFIG_DIR"));
|
||||
assertNotNull(env.get("REQUESTS_CA_BUNDLE"));
|
||||
}
|
||||
}
|
||||
|
||||
/** The printed next step must also clear a stale AZURE_CONFIG_DIR, which only az env does. */
|
||||
@Test
|
||||
void globalSetupTellsTheUserToEvalAzEnv() {
|
||||
String out = stdout(() -> assertEquals(0, run("--global")));
|
||||
|
||||
assertTrue(out.contains("eval $(floci az env)"), out);
|
||||
assertFalse(out.contains("export REQUESTS_CA_BUNDLE"), out);
|
||||
}
|
||||
|
||||
/** A profile can default to -o json, so the pasted env command must ask for shell exports. */
|
||||
@Test
|
||||
void theHintForAProfileForcesTextOutput() {
|
||||
String out = stdout(() -> assertEquals(0, run("--global", "--profile", "team-b")));
|
||||
|
||||
assertTrue(out.contains("eval $(floci az env --profile team-b -o text)"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchingAnInstanceToGlobalRemovesItsEarlierIsolatedConfig() {
|
||||
assertEquals(0, run());
|
||||
assertTrue(Files.isDirectory(dir("floci-az").resolve("azure-config")));
|
||||
|
||||
assertEquals(0, run("--global"));
|
||||
|
||||
// Otherwise 'floci az env' would keep selecting the old isolated login.
|
||||
assertFalse(Files.exists(dir("floci-az").resolve("azure-config")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginRetriesWithoutRequiringASubscription() {
|
||||
// Fails the first login only: FakeAz.failing matches by prefix, which would also catch the retry.
|
||||
AzCli failFirstLogin = new AzCli() {
|
||||
boolean failed;
|
||||
|
||||
@Override
|
||||
public Result run(List<String> args, Map<String, String> env) throws AzCliNotFoundException {
|
||||
if (args.get(0).equals("login") && !failed) {
|
||||
failed = true;
|
||||
az.calls.add(List.copyOf(args));
|
||||
return new Result(1, "No subscriptions found");
|
||||
}
|
||||
return az.run(args, env);
|
||||
}
|
||||
};
|
||||
int exit = new CommandLine(new AzSetupCommand(tempDir, failFirstLogin, e -> pem, new NoDocker(), Duration.ZERO))
|
||||
.execute();
|
||||
|
||||
assertEquals(0, exit);
|
||||
List<String> logins = az.lines().stream().filter(l -> l.startsWith("login")).toList();
|
||||
assertEquals(2, logins.size());
|
||||
assertTrue(logins.get(1).endsWith("--allow-no-subscriptions"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailingStepStopsTheSetupWithExitOne() {
|
||||
az.failing.add("cloud set");
|
||||
|
||||
assertEquals(1, run());
|
||||
|
||||
assertTrue(az.lines().stream().noneMatch(l -> l.startsWith("login")), az.lines().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSubscriptionThatCannotBeSelectedIsOnlyAWarning() {
|
||||
az.failing.add("account set");
|
||||
|
||||
assertEquals(0, run());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tlsOffFailsBeforeAnyAzCall() {
|
||||
assertEquals(1, run(e -> {
|
||||
throw new TlsUnavailableException("TLS is not enabled", false);
|
||||
}));
|
||||
assertTrue(az.calls.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreachableServerFailsBeforeAnyAzCall() {
|
||||
assertEquals(1, run(e -> {
|
||||
throw new FlociException("Connection refused at http://localhost:4577.");
|
||||
}));
|
||||
assertTrue(az.calls.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitsWhileTheCertificateIsStillBeingGenerated() throws Exception {
|
||||
AtomicInteger attempts = new AtomicInteger();
|
||||
AzSetupCommand.CertSource slow = e -> {
|
||||
if (attempts.incrementAndGet() < 3) throw new TlsUnavailableException("certificate not available yet", true);
|
||||
return pem;
|
||||
};
|
||||
|
||||
assertEquals(pem, AzSetupCommand.fetchWithRetry(slow, "http://x", 5, Duration.ZERO));
|
||||
assertEquals(3, attempts.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givesUpWaitingAfterTheLastAttempt() {
|
||||
AzSetupCommand.CertSource never = e -> {
|
||||
throw new TlsUnavailableException("certificate not available yet", true);
|
||||
};
|
||||
|
||||
TlsUnavailableException e = assertThrows(TlsUnavailableException.class,
|
||||
() -> AzSetupCommand.fetchWithRetry(never, "http://x", 3, Duration.ZERO));
|
||||
assertTrue(e.notYet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingAzCliExitsOne() {
|
||||
az.installed = false;
|
||||
|
||||
assertEquals(1, run());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonOutputReportsWhatWasConfigured() {
|
||||
String out = stdout(() -> assertEquals(0, run("-o", "json")));
|
||||
|
||||
for (String key : new String[]{"container", "configDir", "global", "caBundle", "cloud", "cloudRegistered",
|
||||
"endpoint", "tenant", "subscription", "subscriptionSet"}) {
|
||||
assertTrue(out.contains("\"" + key + "\""), key + " missing in " + out);
|
||||
}
|
||||
assertTrue(out.contains("\"endpoint\" : \"https://localhost:4577\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetRemovesTheIsolatedConfigWithoutCallingAz() {
|
||||
assertEquals(0, run());
|
||||
az.calls.clear();
|
||||
|
||||
assertEquals(0, run("--reset"));
|
||||
|
||||
assertFalse(Files.exists(dir("floci-az").resolve("azure-config")));
|
||||
assertFalse(Files.exists(dir("floci-az").resolve("ca-bundle.pem")));
|
||||
assertFalse(Files.exists(dir("floci-az")), "an emptied instance dir is removed too");
|
||||
assertTrue(az.calls.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void globalResetSwitchesBackOnlyWhenFlociAzIsActive() {
|
||||
az.activeCloud = "floci-az";
|
||||
assertEquals(0, run("--reset", "--global"));
|
||||
assertEquals(List.of(
|
||||
"cloud show --query name -o tsv",
|
||||
"cloud set -n AzureCloud",
|
||||
"config set core.instance_discovery=true"), az.lines());
|
||||
|
||||
az.calls.clear();
|
||||
assertEquals(0, run("--reset", "--global"));
|
||||
assertEquals(List.of("cloud show --query name -o tsv"), az.lines());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachContainerGetsItsOwnConfigAndCloud() {
|
||||
assertEquals(0, run("--container", "floci-az-a", "--endpoint", "http://localhost:14577"));
|
||||
assertEquals(0, run("--container", "floci-az-b", "--endpoint", "http://localhost:14578"));
|
||||
|
||||
assertTrue(Files.isDirectory(dir("floci-az-a").resolve("azure-config")));
|
||||
assertTrue(Files.isDirectory(dir("floci-az-b").resolve("azure-config")));
|
||||
assertTrue(az.lines().contains("cloud set -n floci-az-a"), az.lines().toString());
|
||||
assertTrue(az.lines().contains("cloud set -n floci-az-b"), az.lines().toString());
|
||||
assertTrue(az.lines().stream().anyMatch(l -> l.startsWith("cloud register -n floci-az-b")
|
||||
&& l.contains("https://localhost:14578/")), az.lines().toString());
|
||||
|
||||
assertEquals(0, run("--container", "floci-az-a", "--reset"));
|
||||
|
||||
assertFalse(Files.exists(dir("floci-az-a").resolve("azure-config")));
|
||||
assertTrue(Files.isDirectory(dir("floci-az-b").resolve("azure-config")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void globalResetOnlyUndoesItsOwnCloud() {
|
||||
az.activeCloud = "floci-az-b";
|
||||
|
||||
assertEquals(0, run("--container", "floci-az-a", "--reset", "--global"));
|
||||
|
||||
assertEquals(List.of("cloud show --query name -o tsv"), az.lines());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContainerNameThatWouldEscapeIsRefused() {
|
||||
assertEquals(1, run("--container", "../x"));
|
||||
assertTrue(az.calls.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpsKeepsTheHostAndPort() {
|
||||
assertEquals("https://localhost:4577", AzSetupCommand.httpsOf("http://localhost:4577"));
|
||||
assertEquals("https://127.0.0.1:14577", AzSetupCommand.httpsOf("http://127.0.0.1:14577/"));
|
||||
assertEquals("https://localhost:4577", AzSetupCommand.httpsOf("http://localhost"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import java.security.KeyStore;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Base64;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
/** A real certificate to stand in for the floci-az CA: the JDK cannot mint one without a library. */
|
||||
final class AzTestCerts {
|
||||
|
||||
private AzTestCerts() {
|
||||
}
|
||||
|
||||
static String somePem() throws Exception {
|
||||
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
tmf.init((KeyStore) null);
|
||||
X509Certificate cert = ((X509TrustManager) tmf.getTrustManagers()[0]).getAcceptedIssuers()[0];
|
||||
return "-----BEGIN CERTIFICATE-----\n"
|
||||
+ Base64.getMimeEncoder(64, "\n".getBytes()).encodeToString(cert.getEncoded())
|
||||
+ "\n-----END CERTIFICATE-----\n";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import io.floci.cli.azcli.CaBundle;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.cert.CertificateFactory;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CaBundleTest {
|
||||
|
||||
@Test
|
||||
void keepsThePublicRootsAndEndsWithTheFlociCa() throws Exception {
|
||||
String floci = AzTestCerts.somePem();
|
||||
|
||||
String bundle = CaBundle.build(floci);
|
||||
|
||||
// REQUESTS_CA_BUNDLE replaces Python's trust store, so the public roots must survive.
|
||||
int certs = CertificateFactory.getInstance("X.509")
|
||||
.generateCertificates(new ByteArrayInputStream(bundle.getBytes(StandardCharsets.US_ASCII))).size();
|
||||
assertTrue(certs > 1, "expected JDK roots plus the floci CA, got " + certs);
|
||||
assertTrue(bundle.endsWith(floci.strip() + "\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesSomethingThatIsNotACertificate() {
|
||||
assertThrows(Exception.class, () -> CaBundle.build("<html>not found</html>"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.cli.http.FlociHttpClient;
|
||||
import io.floci.cli.http.TlsUnavailableException;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** The three answers floci-az's /_floci/tls-cert gives, against a local JDK HTTP server. */
|
||||
class FlociHttpClientTlsCertTest {
|
||||
|
||||
private HttpServer server;
|
||||
|
||||
private FlociHttpClient serving(int status, String body) throws Exception {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/_floci/tls-cert", exchange -> {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
return new FlociHttpClient("http://127.0.0.1:" + server.getAddress().getPort(), "/_floci");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stop() {
|
||||
if (server != null) server.stop(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsThePem() throws Exception {
|
||||
String pem = "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n";
|
||||
|
||||
assertEquals(pem, serving(200, pem).tlsCert());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tlsOffIsFinal() throws Exception {
|
||||
FlociHttpClient client = serving(404,
|
||||
"{\"tlsEnabled\":false,\"error\":\"NotFound\",\"message\":\"TLS is not enabled\"}");
|
||||
|
||||
TlsUnavailableException e = assertThrows(TlsUnavailableException.class, client::tlsCert);
|
||||
assertFalse(e.notYet());
|
||||
assertEquals("TLS is not enabled", e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stillGeneratingIsWorthWaitingFor() throws Exception {
|
||||
FlociHttpClient client = serving(404,
|
||||
"{\"tlsEnabled\":true,\"error\":\"NotFound\",\"message\":\"certificate not available yet\"}");
|
||||
|
||||
assertTrue(assertThrows(TlsUnavailableException.class, client::tlsCert).notYet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerWithoutTheEndpointReadsAsTlsOff() throws Exception {
|
||||
FlociHttpClient client = serving(404, "<html>no such route</html>");
|
||||
|
||||
assertFalse(assertThrows(TlsUnavailableException.class, client::tlsCert).notYet());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import io.floci.cli.FlociCli;
|
||||
import io.floci.cli.GlobalOptions;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.config.ProfileStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import picocli.CommandLine.ParseResult;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
@@ -76,4 +81,39 @@ class GlobalOptionsTest {
|
||||
assertEquals("http://localhost:4588",
|
||||
gcp.endpointFromPorts("9999->1111/tcp", "http://localhost:4588"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceSelectorNamesTheProfileOrANonDefaultContainer() {
|
||||
GlobalOptions az = new GlobalOptions(ProductProfile.AZ, env(Map.of()));
|
||||
assertEquals("", az.instanceSelector());
|
||||
|
||||
az.container = "floci-az-b";
|
||||
assertEquals(" --container floci-az-b", az.instanceSelector());
|
||||
|
||||
az.profile = "team-b";
|
||||
assertEquals(" --profile team-b", az.instanceSelector());
|
||||
}
|
||||
|
||||
/** Hints are pasted into a shell: a profile name with a space must survive as one word. */
|
||||
@Test
|
||||
void instanceSelectorQuotesNamesThatAreNotPlainWords() throws Exception {
|
||||
Path store = Files.createTempDirectory("floci-profiles");
|
||||
Files.writeString(store.resolve("team alpha.yaml"), "container: floci-az-a\n");
|
||||
|
||||
GlobalOptions quoted = azOptions(store, "--profile", "team alpha");
|
||||
assertEquals(" --profile 'team alpha'", quoted.instanceSelector());
|
||||
|
||||
GlobalOptions withContainer = azOptions(store, "--profile", "team alpha", "--container", "floci-az-b");
|
||||
assertEquals(" --profile 'team alpha' --container floci-az-b", withContainer.instanceSelector());
|
||||
}
|
||||
|
||||
private static GlobalOptions azOptions(Path store, String... flags) {
|
||||
String[] args = new String[flags.length + 2];
|
||||
args[0] = "az";
|
||||
args[1] = "env";
|
||||
System.arraycopy(flags, 0, args, 2, flags.length);
|
||||
ParseResult r = FlociCli.buildCommandLine(new ProfileStore(store)).parseArgs(args);
|
||||
while (r.hasSubcommand()) r = r.subcommand();
|
||||
return (GlobalOptions) r.commandSpec().mixins().get("global").userObject();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.config.InstanceState;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class InstanceStateTest {
|
||||
|
||||
private static final Path ROOT = Path.of("/home/u/.floci");
|
||||
|
||||
@Test
|
||||
void oneDirectoryPerProductAndContainer() {
|
||||
assertEquals(ROOT.resolve("az/floci-az"), InstanceState.dir(ROOT, ProductProfile.AZ, "floci-az"));
|
||||
assertEquals(ROOT.resolve("az/floci-az-b"), InstanceState.dir(ROOT, ProductProfile.AZ, "floci-az-b"));
|
||||
assertEquals(ROOT.resolve("gcp/floci-gcp"), InstanceState.dir(ROOT, ProductProfile.GCP, "floci-gcp"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " ", ".", "..", "../x", "a/b", "a\\b"})
|
||||
void refusesNamesThatAreNotAContainerName(String name) {
|
||||
assertThrows(IllegalArgumentException.class, () -> InstanceState.dir(ROOT, ProductProfile.AZ, name));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package io.floci.cli.unit;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Pins every field of the four product constants — the drift firewall for the unified tree. */
|
||||
@@ -20,6 +22,7 @@ class ProductProfileTest {
|
||||
assertEquals("FLOCI_ENDPOINT", ProductProfile.AWS.envVar("ENDPOINT"));
|
||||
assertEquals("/_floci", ProductProfile.AWS.controlPrefix());
|
||||
assertEquals("floci", ProductProfile.AWS.commandPrefix());
|
||||
assertEquals(Map.of(), ProductProfile.AWS.startEnv());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -32,6 +35,7 @@ class ProductProfileTest {
|
||||
assertEquals("FLOCI_GCP_CONTAINER", ProductProfile.GCP.envVar("CONTAINER"));
|
||||
assertEquals("/_floci-gcp", ProductProfile.GCP.controlPrefix());
|
||||
assertEquals("floci gcp", ProductProfile.GCP.commandPrefix());
|
||||
assertEquals(Map.of(), ProductProfile.GCP.startEnv());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -45,6 +49,7 @@ class ProductProfileTest {
|
||||
// The floci-az server exposes /_floci/* (same as AWS), NOT /_floci-az.
|
||||
assertEquals("/_floci", ProductProfile.AZ.controlPrefix());
|
||||
assertEquals("floci az", ProductProfile.AZ.commandPrefix());
|
||||
assertEquals(Map.of("TLS_ENABLED", "true"), ProductProfile.AZ.startEnv());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -57,5 +62,6 @@ class ProductProfileTest {
|
||||
assertEquals("FLOCI_OCI_ENDPOINT", ProductProfile.OCI.envVar("ENDPOINT"));
|
||||
assertEquals("/_floci-oci", ProductProfile.OCI.controlPrefix());
|
||||
assertEquals("floci oci", ProductProfile.OCI.commandPrefix());
|
||||
assertEquals(Map.of(), ProductProfile.OCI.startEnv());
|
||||
}
|
||||
}
|
||||
@@ -81,8 +81,9 @@ class ProductTreesParsingTest {
|
||||
assertTrue(names.containsAll(LIFECYCLE_COMMANDS),
|
||||
tree + " is missing " + LIFECYCLE_COMMANDS.stream().filter(c -> !names.contains(c)).toList());
|
||||
}
|
||||
// oci additionally has setup; bare root additionally has update + the product groups
|
||||
// oci and az additionally have setup; bare root additionally has update + the product groups
|
||||
assertTrue(root.getSubcommands().get("oci").getSubcommands().containsKey("setup"));
|
||||
assertTrue(root.getSubcommands().get("az").getSubcommands().containsKey("setup"));
|
||||
assertTrue(root.getSubcommands().keySet().containsAll(Set.of("update", "aws", "gcp", "az", "oci")));
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,12 @@ class ProfileDefaultsTest {
|
||||
@ValueSource(strings = {
|
||||
"--service", // wait/logs/env filter — NOT the profile's 'services'
|
||||
"--profile-name", // the OCI CLI profile written by 'floci oci setup'
|
||||
"--global", // 'floci az setup' target, not a profile field
|
||||
"--reset",
|
||||
"--tenant",
|
||||
"--subscription",
|
||||
"--client-id",
|
||||
"--client-secret",
|
||||
"--profile",
|
||||
"--pull",
|
||||
"--timeout",
|
||||
|
||||
@@ -94,6 +94,19 @@ class StartCommandArgsTest {
|
||||
.dockerRunArgs(SOCKET).contains("/from-flag:/app/data"));
|
||||
}
|
||||
|
||||
/** 'floci az setup' needs HTTPS (MSAL refuses an HTTP authority), so az always starts with TLS. */
|
||||
@Test
|
||||
void onlyAzStartsWithTlsEnabled() {
|
||||
assertEquals(List.of("-d", "--name", "floci-az", "-p", "4577:4577",
|
||||
"-v", "/sock:/sock",
|
||||
"-e", "FLOCI_AZ_TLS_ENABLED=true",
|
||||
"floci/floci-az:latest"),
|
||||
parse("az", "start").dockerRunArgs(SOCKET));
|
||||
for (String tree : new String[]{"aws", "gcp", "oci"}) {
|
||||
assertFalse(parse(tree, "start").dockerRunArgs(SOCKET).stream().anyMatch(a -> a.contains("TLS")), tree);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void readinessPollKeepsTheHostFromTheEndpointWhenSwappingThePort() {
|
||||
assertEquals("http://floci.internal:4599", StartCommand.withPort("http://floci.internal:4566", 4599));
|
||||
|
||||
Reference in new issue
Block a user