From 7b58a38c5a5bf4e2e84991c5400ec3abbab90264 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 8 Oct 2026 21:29:02 -0500 Subject: [PATCH] feat(az): configure the az CLI against floci-az with floci az setup (#29) --- AGENTS.md | 4 +- README.md | 62 ++- src/main/java/io/floci/cli/GlobalOptions.java | 41 ++ .../java/io/floci/cli/ProductProfile.java | 16 +- src/main/java/io/floci/cli/azcli/AzCli.java | 27 ++ .../cli/azcli/AzCliNotFoundException.java | 7 + .../java/io/floci/cli/azcli/CaBundle.java | 58 +++ .../java/io/floci/cli/azcli/ProcessAzCli.java | 72 ++++ .../io/floci/cli/commands/StartCommand.java | 3 + .../io/floci/cli/commands/az/AzCommand.java | 4 +- .../floci/cli/commands/az/AzEnvCommand.java | 75 ++++ .../floci/cli/commands/az/AzSetupCommand.java | 386 ++++++++++++++++++ .../io/floci/cli/config/InstanceState.java | 45 ++ .../io/floci/cli/http/FlociHttpClient.java | 42 +- .../cli/http/TlsUnavailableException.java | 19 + .../java/io/floci/cli/output/ShellExport.java | 9 + .../io/floci/cli/unit/AzEnvCommandTest.java | 159 ++++++++ .../io/floci/cli/unit/AzSetupCommandTest.java | 352 ++++++++++++++++ .../java/io/floci/cli/unit/AzTestCerts.java | 23 ++ .../java/io/floci/cli/unit/CaBundleTest.java | 31 ++ .../cli/unit/FlociHttpClientTlsCertTest.java | 67 +++ .../io/floci/cli/unit/GlobalOptionsTest.java | 40 ++ .../io/floci/cli/unit/InstanceStateTest.java | 29 ++ .../io/floci/cli/unit/ProductProfileTest.java | 6 + .../cli/unit/ProductTreesParsingTest.java | 3 +- .../floci/cli/unit/ProfileDefaultsTest.java | 6 + .../floci/cli/unit/StartCommandArgsTest.java | 13 + 27 files changed, 1587 insertions(+), 12 deletions(-) create mode 100644 src/main/java/io/floci/cli/azcli/AzCli.java create mode 100644 src/main/java/io/floci/cli/azcli/AzCliNotFoundException.java create mode 100644 src/main/java/io/floci/cli/azcli/CaBundle.java create mode 100644 src/main/java/io/floci/cli/azcli/ProcessAzCli.java create mode 100644 src/main/java/io/floci/cli/commands/az/AzSetupCommand.java create mode 100644 src/main/java/io/floci/cli/config/InstanceState.java create mode 100644 src/main/java/io/floci/cli/http/TlsUnavailableException.java create mode 100644 src/test/java/io/floci/cli/unit/AzEnvCommandTest.java create mode 100644 src/test/java/io/floci/cli/unit/AzSetupCommandTest.java create mode 100644 src/test/java/io/floci/cli/unit/AzTestCerts.java create mode 100644 src/test/java/io/floci/cli/unit/CaBundleTest.java create mode 100644 src/test/java/io/floci/cli/unit/FlociHttpClientTlsCertTest.java create mode 100644 src/test/java/io/floci/cli/unit/InstanceStateTest.java diff --git a/AGENTS.md b/AGENTS.md index 73a9c1d..ebe5b9a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,7 +63,7 @@ Rules for the unified tree: - **Per-product option defaults are constructor-set field values**, not annotation `defaultValue`s (annotation strings are compile-time constants). Use `(default: ${DEFAULT-VALUE})` in the option description to render them in help. - **Never subclass a group command** (`GcpCommand`, `*ConfigCommand`, `*SnapshotCommand` groups): picocli registers the `subcommands` arrays of both super and subclass — instant duplicate-name crash. Groups stay standalone registration-only classes. - Product-varying strings come from the profile: `displayName()` for banners, `commandPrefix()` for hint strings, `envVar("SERVICES")` for container env vars, `controlPrefix()` for `FlociHttpClient`, `serverRepo()` for issue-tracker links. -- Only `EnvCommand`/`GcpEnvCommand`/`AzEnvCommand`/`OciEnvCommand` are genuinely product-specific (not shims), plus the OCI-only `OciSetupCommand` (the OCI CLI/SDKs require a config file + signing key, so `floci oci setup` scaffolds them; no other tree needs an equivalent). +- Only `EnvCommand`/`GcpEnvCommand`/`AzEnvCommand`/`OciEnvCommand` are genuinely product-specific (not shims), plus two product-only `setup` commands: `OciSetupCommand` (the OCI CLI/SDKs require a config file + signing key, so `floci oci setup` scaffolds them) and `AzSetupCommand` (the `az` CLI needs a registered cloud, the emulator's CA trusted and a login, so `floci az setup` does that through `io.floci.cli.azcli`). AWS and GCP need no equivalent. `add-command/checklist.sh setup` reports the shared-tree rows as MISSING for these by design. Commands call `global.printer()` at the start of `call()` — never store a `Printer` as a field. @@ -71,7 +71,7 @@ Commands call `global.printer()` at the start of `call()` — never store a `Pri **Docker:** `DockerClient` wraps `docker` CLI subprocesses — no docker-java library. This is a deliberate native-image trade-off. `DockerClient` returns plain records (`ContainerInfo`, `ImageInfo`) and throws `DockerException` on non-zero exit codes. -**Floci server:** `FlociHttpClient` wraps `java.net.http.HttpClient` against the Floci REST API. All methods throw `FlociException`. The control-plane prefix is constructor-configurable: AWS and Azure use `/_floci`, GCP uses `/_floci-gcp`. Known live endpoints: `/_floci/health`, `/_floci/info`, `/_floci/init`. Snapshot endpoints (`/_floci/snapshots/*`) do not exist on the server yet. +**Floci server:** `FlociHttpClient` wraps `java.net.http.HttpClient` against the Floci REST API. All methods throw `FlociException`. The control-plane prefix is constructor-configurable: AWS and Azure use `/_floci`, GCP uses `/_floci-gcp`. Known live endpoints: `/_floci/health`, `/_floci/info`, `/_floci/init`, and on floci-az only `/_floci/tls-cert` (`tlsCert()`, the PEM CA; 404 when TLS is off). Snapshot endpoints (`/_floci/snapshots/*`) do not exist on the server yet. ### Output pipeline diff --git a/README.md b/README.md index 0ac26b7..13bb82f 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,10 @@ gcloud storage buckets create gs://my-bucket # Azure floci az start +floci az setup eval $(floci az env) az storage container create --name mycontainer +az group create -n my-rg -l westeurope # OCI floci oci start @@ -127,12 +129,16 @@ floci az start # Check environment floci az doctor -# Export Azure connection string +# Point the az CLI at the emulator (certificate, cloud, login) +floci az setup + +# Export the connection string and the az CLI config eval $(floci az env) # Use Azure services az storage container create --name mycontainer az storage blob upload --container-name mycontainer --name hello.txt --data "hello" +az group create -n my-rg -l westeurope # Stop Floci Azure floci az stop @@ -237,6 +243,7 @@ Commands are organized into four product groups — `floci aws` (or bare `floci` | `floci az services` | List enabled Azure services | | `floci az doctor` | Run Azure environment diagnostics | | `floci az env` | Print Azure connection string / SDK env vars | +| `floci az setup` | Point the `az` CLI at the emulator: trust its certificate, register the cloud, log in | | `floci az snapshot` | Snapshot commands (coming soon) | ### OCI commands (`floci oci`) @@ -481,6 +488,59 @@ floci az env -o json # structured output | `AZURE_APP_CONFIGURATION_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1-appconfig` | | `AZURE_KEY_VAULT_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1-keyvault` | +**After `floci az setup`**, both modes also export: + +| Variable | Value | +|----------|-------| +| `AZURE_CONFIG_DIR` | `~/.floci/az//azure-config`, the instance's isolated az config; after `--global` it is unset instead, so a value left by another instance's `eval` does not linger | +| `REQUESTS_CA_BUNDLE` | `~/.floci/az//ca-bundle.pem`, the public roots plus that instance's certificate | + +If the instance's certificate changed since setup (a container recreated without `--persist`), +`floci az env` warns on stderr and tells you to re-run `floci az setup`. + +### `floci az setup` + +`az group create`, `az login` and every other control-plane command go to public Azure +unless the `az` CLI is told otherwise. `floci az setup` does it in one step: + +1. fetches the emulator's CA certificate from `/_floci/tls-cert` and writes a CA bundle + (the JDK's public roots plus that certificate); +2. registers (or updates) an az cloud named after the container (`floci-az` by default) whose ARM and Entra endpoints point at + `https://localhost:`, and makes it the active cloud; +3. turns off `core.instance_discovery`, which otherwise fails the login with `invalid_instance`; +4. logs in as a service principal with the dev identity (tenant + `00000000-0000-0000-0000-000000000002`, subscription `00000000-0000-0000-0000-000000000001`). + +Everything is kept per instance, in `~/.floci/az//`, so instances started from +different profiles never share a certificate, cloud or login (see +[Running several instances side by side](#running-several-instances-side-by-side)). By default the +az config itself is isolated there too and `~/.azure` is left untouched; `eval $(floci az env)` +then points `az` at it in the current shell only. `--global` writes to your default az config +instead, and removes that instance's earlier isolated config. Re-running is safe: the cloud is updated, not registered twice. + +The az CLI only logs in over HTTPS, so `floci az start` always starts Floci Azure with +`FLOCI_AZ_TLS_ENABLED=true` (HTTP keeps working on the same port). A container started by an +older floci has TLS off; run `floci az restart` once. + +```sh +floci az setup # isolated config under ~/.floci/az/floci-az +eval $(floci az env) # AZURE_CONFIG_DIR + REQUESTS_CA_BUNDLE + connection string +az group create -n my-rg -l westeurope + +floci az setup --profile team-b # a second instance: ~/.floci/az/ +eval $(floci az env --profile team-b) + +floci az setup --global # use your default az config (~/.azure) +eval $(floci az env) # REQUESTS_CA_BUNDLE, and clears a stale AZURE_CONFIG_DIR + +floci az setup --reset # delete the isolated config +floci az setup --reset --global # switch the default az config back to AzureCloud +floci az setup -o json # structured output +``` + +Requires the `az` CLI on your `PATH`. `--tenant`, `--subscription`, `--client-id` and +`--client-secret` override the dev identity; Floci Azure never checks the secret. + ### `floci oci env` Prints OCI endpoint variables for the running Floci OCI instance. OCI SDKs and the diff --git a/src/main/java/io/floci/cli/GlobalOptions.java b/src/main/java/io/floci/cli/GlobalOptions.java index 9b212fd..2864e56 100644 --- a/src/main/java/io/floci/cli/GlobalOptions.java +++ b/src/main/java/io/floci/cli/GlobalOptions.java @@ -4,10 +4,13 @@ import io.floci.cli.docker.DockerClient; import io.floci.cli.output.Ansi; import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; +import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Option; +import picocli.CommandLine.Spec; import java.net.URI; import java.util.function.UnaryOperator; +import java.util.regex.Pattern; /** * Shared global options for every product tree, parameterized by {@link ProductProfile}. @@ -24,6 +27,13 @@ import java.util.function.UnaryOperator; */ public class GlobalOptions { + // The command this mixin belongs to, so hints can tell which flags were actually typed. + // Null for commands built by hand (restart's start), which were never parsed. + @Spec(Spec.Target.MIXEE) + CommandSpec mixee; + + private static final Pattern PLAIN_WORD = Pattern.compile("[A-Za-z0-9._@%+=:,/-]+"); + public final ProductProfile product; @Option(names = {"--endpoint"}, @@ -77,6 +87,37 @@ public class GlobalOptions { return value != null ? value : fallback; } + /** + * The flags that select this instance again in a hint string: {@code " --profile x"} when a + * profile was used (plus {@code " --container y"} when that was typed too, since it overrides + * the profile's container), {@code " --container y"} for a non-default container, else + * empty. Values are shell-quoted, because hints are meant to be pasted. + */ + public String instanceSelector() { + if (profile != null) { + String selector = " --profile " + shellWord(profile); + return typed("--container") ? selector + " --container " + shellWord(container) : selector; + } + if (!product.defaultContainer().equals(container)) return " --container " + shellWord(container); + return ""; + } + + private boolean typed(String option) { + try { + return mixee != null && mixee.commandLine() != null + && mixee.commandLine().getParseResult() != null + && mixee.commandLine().getParseResult().hasMatchedOption(option); + } catch (RuntimeException e) { + return false; + } + } + + // POSIX single quotes: the hints are shell command lines like the CLI's other 'Run ...' hints. + private static String shellWord(String value) { + if (PLAIN_WORD.matcher(value).matches()) return value; + return "'" + value.replace("'", "'\\''") + "'"; + } + public Printer printer() { if (noColor || !isStdoutTty()) { Ansi.disable(); diff --git a/src/main/java/io/floci/cli/ProductProfile.java b/src/main/java/io/floci/cli/ProductProfile.java index 02b36a3..ec3c06b 100644 --- a/src/main/java/io/floci/cli/ProductProfile.java +++ b/src/main/java/io/floci/cli/ProductProfile.java @@ -1,5 +1,7 @@ package io.floci.cli; +import java.util.Map; + /** * The single source of per-product configuration for the unified command tree. * Every value that differs between the AWS, GCP, Azure, and OCI emulators lives here; @@ -12,7 +14,8 @@ public record ProductProfile( String defaultContainer, int defaultPort, String envPrefix, // FLOCI | FLOCI_GCP | FLOCI_AZ | FLOCI_OCI - String controlPrefix // control-plane path prefix on the server + String controlPrefix, // control-plane path prefix on the server + Map startEnv // extra container env on 'start', keyed by envVar suffix ) { public String defaultEndpoint() { @@ -39,16 +42,19 @@ public record ProductProfile( } public static final ProductProfile AWS = new ProductProfile( - "aws", "Floci AWS", "floci/floci", "floci", 4566, "FLOCI", "/_floci"); + "aws", "Floci AWS", "floci/floci", "floci", 4566, "FLOCI", "/_floci", Map.of()); public static final ProductProfile GCP = new ProductProfile( - "gcp", "Floci GCP", "floci/floci-gcp", "floci-gcp", 4588, "FLOCI_GCP", "/_floci-gcp"); + "gcp", "Floci GCP", "floci/floci-gcp", "floci-gcp", 4588, "FLOCI_GCP", "/_floci-gcp", Map.of()); // AZ intentionally shares the AWS control prefix /_floci — the floci-az server // exposes /_floci/*, NOT /_floci-az. Do not "fix" this to match the name. + // TLS is always on: the az CLI's MSAL refuses an HTTP authority, so 'floci az setup' needs + // HTTPS. floci-az serves HTTP and HTTPS on the same port, so HTTP clients are unaffected. public static final ProductProfile AZ = new ProductProfile( - "az", "Floci Azure", "floci/floci-az", "floci-az", 4577, "FLOCI_AZ", "/_floci"); + "az", "Floci Azure", "floci/floci-az", "floci-az", 4577, "FLOCI_AZ", "/_floci", + Map.of("TLS_ENABLED", "true")); public static final ProductProfile OCI = new ProductProfile( - "oci", "Floci OCI", "floci/floci-oci", "floci-oci", 4599, "FLOCI_OCI", "/_floci-oci"); + "oci", "Floci OCI", "floci/floci-oci", "floci-oci", 4599, "FLOCI_OCI", "/_floci-oci", Map.of()); } diff --git a/src/main/java/io/floci/cli/azcli/AzCli.java b/src/main/java/io/floci/cli/azcli/AzCli.java new file mode 100644 index 0000000..90c1afc --- /dev/null +++ b/src/main/java/io/floci/cli/azcli/AzCli.java @@ -0,0 +1,27 @@ +package io.floci.cli.azcli; + +import java.util.List; +import java.util.Map; + +/** + * Runs the {@code az} CLI. An interface so 'floci az setup' can be tested without {@code az} + * installed: tests pass a fake that records the calls. + */ +@FunctionalInterface +public interface AzCli { + + /** + * Runs {@code az } with {@code env} applied over the inherited environment; a + * {@code null} value removes that variable. + * + * @throws AzCliNotFoundException when no {@code az} executable is on the PATH + */ + Result run(List args, Map env) throws AzCliNotFoundException; + + /** Exit code plus stdout and stderr, interleaved. */ + record Result(int exit, String output) { + public boolean ok() { + return exit == 0; + } + } +} diff --git a/src/main/java/io/floci/cli/azcli/AzCliNotFoundException.java b/src/main/java/io/floci/cli/azcli/AzCliNotFoundException.java new file mode 100644 index 0000000..fcf46d7 --- /dev/null +++ b/src/main/java/io/floci/cli/azcli/AzCliNotFoundException.java @@ -0,0 +1,7 @@ +package io.floci.cli.azcli; + +public class AzCliNotFoundException extends Exception { + public AzCliNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/io/floci/cli/azcli/CaBundle.java b/src/main/java/io/floci/cli/azcli/CaBundle.java new file mode 100644 index 0000000..8c8ef2b --- /dev/null +++ b/src/main/java/io/floci/cli/azcli/CaBundle.java @@ -0,0 +1,58 @@ +package io.floci.cli.azcli; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +/** + * Builds the PEM bundle the az CLI is pointed at through {@code REQUESTS_CA_BUNDLE}. + * + *

That variable replaces the trust store of az's Python runtime rather than adding to it, so a + * bundle holding only the floci-az CA would break every other HTTPS call az (or anything else in + * the same shell) makes. The bundle is the JDK's default trust anchors followed by the floci-az CA, + * which needs no Python and no certifi lookup. + */ +public final class CaBundle { + + private CaBundle() { + } + + /** The JDK default trust anchors, PEM encoded, then {@code flociCaPem}. */ + public static String build(String flociCaPem) throws Exception { + parse(flociCaPem); // fail here, not inside az, on a malformed certificate + StringBuilder sb = new StringBuilder(); + for (X509Certificate cert : defaultTrustAnchors()) { + sb.append(toPem(cert)); + } + sb.append(flociCaPem.strip()).append('\n'); + return sb.toString(); + } + + static X509Certificate[] defaultTrustAnchors() throws Exception { + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init((KeyStore) null); + for (TrustManager tm : tmf.getTrustManagers()) { + if (tm instanceof X509TrustManager x509) { + return x509.getAcceptedIssuers(); + } + } + return new X509Certificate[0]; + } + + static X509Certificate parse(String pem) throws Exception { + return (X509Certificate) CertificateFactory.getInstance("X.509") + .generateCertificate(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII))); + } + + private static String toPem(X509Certificate cert) throws Exception { + String base64 = Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)) + .encodeToString(cert.getEncoded()); + return "-----BEGIN CERTIFICATE-----\n" + base64 + "\n-----END CERTIFICATE-----\n"; + } +} diff --git a/src/main/java/io/floci/cli/azcli/ProcessAzCli.java b/src/main/java/io/floci/cli/azcli/ProcessAzCli.java new file mode 100644 index 0000000..f26f6fe --- /dev/null +++ b/src/main/java/io/floci/cli/azcli/ProcessAzCli.java @@ -0,0 +1,72 @@ +package io.floci.cli.azcli; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +/** {@link AzCli} backed by a real {@code az} subprocess. */ +public class ProcessAzCli implements AzCli { + + // az login can take a while on a cold start; anything past this is a hang, not slowness. + private static final long TIMEOUT_SECONDS = 120; + + // On Windows az is a batch file, which ProcessBuilder only resolves by its full name. + private static final String EXECUTABLE = + System.getProperty("os.name", "").toLowerCase().startsWith("windows") ? "az.cmd" : "az"; + + @Override + public Result run(List args, Map env) throws AzCliNotFoundException { + List command = new ArrayList<>(); + command.add(EXECUTABLE); + command.addAll(args); + ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true); + env.forEach((key, value) -> { + if (value == null) pb.environment().remove(key); + else pb.environment().put(key, value); + }); + + Process process; + try { + process = pb.start(); + } catch (IOException e) { + throw new AzCliNotFoundException("az CLI not found in PATH (" + e.getMessage() + ")"); + } + closeQuietly(process); + // Drain on another thread: az can print more than the pipe buffer holds, and an + // undrained pipe would block it forever. + CompletableFuture output = CompletableFuture.supplyAsync(() -> readAll(process.getInputStream())); + try { + if (!process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + process.destroyForcibly(); + return new Result(124, "az " + String.join(" ", args.subList(0, Math.min(2, args.size()))) + + " timed out after " + TIMEOUT_SECONDS + "s"); + } + return new Result(process.exitValue(), output.join()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + process.destroyForcibly(); + return new Result(130, "interrupted"); + } + } + + // az never reads stdin here; closing it means a prompt fails fast instead of hanging. + private static void closeQuietly(Process process) { + try { + process.getOutputStream().close(); + } catch (IOException ignored) { + } + } + + private static String readAll(InputStream in) { + try (in) { + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + return ""; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 348acb1..03829e0 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -14,6 +14,7 @@ import picocli.CommandLine.*; import java.net.URI; import java.util.ArrayList; import java.util.List; +import java.util.TreeMap; import java.util.concurrent.Callable; @Command( @@ -115,6 +116,8 @@ public class StartCommand implements Callable { if (services != null && !services.isBlank()) { args.addAll(List.of("-e", profile.envVar("SERVICES") + "=" + services)); } + new TreeMap<>(profile.startEnv()).forEach((suffix, value) -> + args.addAll(List.of("-e", profile.envVar(suffix) + "=" + value))); args.add(image); return args; } diff --git a/src/main/java/io/floci/cli/commands/az/AzCommand.java b/src/main/java/io/floci/cli/commands/az/AzCommand.java index eb80d5f..d847d57 100644 --- a/src/main/java/io/floci/cli/commands/az/AzCommand.java +++ b/src/main/java/io/floci/cli/commands/az/AzCommand.java @@ -13,7 +13,8 @@ import picocli.CommandLine.*; " floci az stop — stop the container%n" + " floci az status — show health and version%n" + " floci az doctor — diagnose environment issues%n" + - " floci az env — print Azure environment variables%n", + " floci az env — print Azure environment variables%n" + + " floci az setup — point the az CLI at the emulator (cert, cloud, login)%n", mixinStandardHelpOptions = true, subcommands = { AzStartCommand.class, @@ -26,6 +27,7 @@ import picocli.CommandLine.*; AzServicesCommand.class, AzDoctorCommand.class, AzEnvCommand.class, + AzSetupCommand.class, AzConfigCommand.class, AzSnapshotCommand.class, CompletionCommand.class, diff --git a/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java b/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java index 2451230..53a14d4 100644 --- a/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java +++ b/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java @@ -2,8 +2,10 @@ package io.floci.cli.commands.az; import io.floci.cli.GlobalOptions; import io.floci.cli.ProductProfile; +import io.floci.cli.config.InstanceState; import io.floci.cli.docker.DockerClient; import io.floci.cli.doctor.checks.AzCliConnectionStringCheck; +import io.floci.cli.http.FlociHttpClient; import io.floci.cli.output.Ansi; import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; @@ -11,6 +13,8 @@ import io.floci.cli.output.ShellExport; import picocli.CommandLine.*; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -64,6 +68,23 @@ public class AzEnvCommand implements Callable { paramLabel = "bash|fish|powershell") String shell; + private final Path stateRoot; + private final AzSetupCommand.CertSource certSource; + + public AzEnvCommand() { + this(InstanceState.defaultRoot(), + endpoint -> new FlociHttpClient(endpoint, ProductProfile.AZ.controlPrefix()).tlsCert()); + } + + /** + * Test seam: {@code stateRoot} stands in for {@code ~/.floci}, where 'floci az setup' wrote + * each instance's config dir and CA; {@code certSource} reads the running server's CA. + */ + public AzEnvCommand(Path stateRoot, AzSetupCommand.CertSource certSource) { + this.stateRoot = stateRoot; + this.certSource = certSource; + } + @Override public Integer call() { Printer printer = global.printer(); @@ -72,6 +93,7 @@ public class AzEnvCommand implements Callable { boolean sdkVarsMode = "sdk-vars".equals(format) || serviceFilter != null; List requestedServices = resolveServices(); + Map azCliVars = azCliVars(printer, effectiveEndpoint); if (printer.format() != OutputFormat.text) { Map out = new LinkedHashMap<>(); @@ -85,6 +107,7 @@ public class AzEnvCommand implements Callable { out.put(envVarName(svc), buildEndpointUrl(svc, host, port, account)); } } + out.putAll(azCliVars); printer.structured(out); return 0; } @@ -92,6 +115,7 @@ public class AzEnvCommand implements Callable { if (!sdkVarsMode) { String connStr = AzCliConnectionStringCheck.buildConnectionString(account, host, port); printer.println(ShellExport.formatExport(shell, "AZURE_STORAGE_CONNECTION_STRING", connStr)); + printAzCliVars(printer, azCliVars); printer.println(""); printer.println(Ansi.gray("# Run: eval $(floci az env)")); } else { @@ -100,6 +124,7 @@ public class AzEnvCommand implements Callable { for (String svc : requestedServices) { printer.println(ShellExport.formatExport(shell, envVarName(svc), buildEndpointUrl(svc, host, port, account))); } + printAzCliVars(printer, azCliVars); printer.println(""); printer.println(Ansi.gray("# Run: eval $(floci az env --format sdk-vars)")); } @@ -107,6 +132,56 @@ public class AzEnvCommand implements Callable { return 0; } + // Only after 'floci az setup' has run: point a plain 'az' in this shell at the isolated config + // and make it trust floci-az's certificate. A --global setup leaves no config dir, so the + // bundle is exported and AZURE_CONFIG_DIR is cleared (a null value). + // The state is per instance (keyed by container), so --profile and --container pick the + // setup that belongs to the emulator this env points at. + private Map azCliVars(Printer printer, String endpoint) { + Map vars = new LinkedHashMap<>(); + Path dir; + try { + dir = InstanceState.dir(stateRoot, ProductProfile.AZ, global.container); + } catch (IllegalArgumentException e) { + return vars; // not a usable container name; the storage variables still stand + } + Path configDir = dir.resolve(AzSetupCommand.CONFIG_DIR_NAME); + Path bundle = dir.resolve(AzSetupCommand.BUNDLE_NAME); + if (Files.isDirectory(configDir)) { + vars.put("AZURE_CONFIG_DIR", configDir.toAbsolutePath().toString()); + } else if (Files.isRegularFile(bundle)) { + // Set up with --global: clear an AZURE_CONFIG_DIR a previous 'eval $(floci az env)' + // left in this shell, or plain 'az' keeps using that other instance's isolated login. + vars.put("AZURE_CONFIG_DIR", null); + } + if (Files.isRegularFile(bundle)) vars.put("REQUESTS_CA_BUNDLE", bundle.toAbsolutePath().toString()); + warnIfCertificateChanged(printer, dir.resolve(AzSetupCommand.CA_NAME), endpoint); + return vars; + } + + // A container recreated without a persist dir generates a new CA, and the saved bundle then + // fails every az call with a TLS error that says nothing about why. Warn on stderr, which + // 'eval $(floci az env)' leaves visible. Any failure to fetch stays silent: env must keep + // working with the emulator stopped. + private void warnIfCertificateChanged(Printer printer, Path savedCa, String endpoint) { + if (!Files.isRegularFile(savedCa)) return; + try { + String live = certSource.fetch(endpoint); + if (!live.strip().equals(Files.readString(savedCa).strip())) { + printer.warn("The Floci Azure certificate changed since 'floci az setup' ran.\n" + + "Run 'floci az setup" + global.instanceSelector() + "' to trust the new one."); + } + } catch (Exception ignored) { + } + } + + + private void printAzCliVars(Printer printer, Map vars) { + vars.forEach((key, value) -> printer.println(value == null + ? ShellExport.formatUnset(shell, key) + : ShellExport.formatExport(shell, key, value))); + } + private List resolveServices() { if (serviceFilter != null && !serviceFilter.isBlank()) { List result = new ArrayList<>(); diff --git a/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java b/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java new file mode 100644 index 0000000..1353968 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java @@ -0,0 +1,386 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.ProductProfile; +import io.floci.cli.azcli.AzCli; +import io.floci.cli.azcli.AzCliNotFoundException; +import io.floci.cli.azcli.CaBundle; +import io.floci.cli.azcli.ProcessAzCli; +import io.floci.cli.config.InstanceState; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.http.FlociException; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.http.TlsUnavailableException; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.stream.Stream; + +@Command( + name = "setup", + description = "Point the az CLI at Floci Azure: trust its certificate, register the cloud and log in", + mixinStandardHelpOptions = true +) +public class AzSetupCommand implements Callable { + + // Dev identity: floci-az's default tenant and subscription. The client id is any value (the + // server echoes it back as appid) and the secret is never checked; these match floci-az's + // compat-azcli suite. + static final String TENANT = "00000000-0000-0000-0000-000000000002"; + static final String SUBSCRIPTION = "00000000-0000-0000-0000-000000000001"; + static final String CLIENT_ID = "00000000-0000-0000-0000-000000000003"; + static final String CLIENT_SECRET = "fake-secret"; + + /** Under the instance dir: the isolated az config, read by {@code floci az env}. */ + public static final String CONFIG_DIR_NAME = "azure-config"; + /** Under the instance dir: the CA bundle, read by {@code floci az env}. */ + public static final String BUNDLE_NAME = "ca-bundle.pem"; + /** Under the instance dir: the floci-az CA alone, compared by {@code floci az env}. */ + public static final String CA_NAME = "floci-az-ca.pem"; + + private static final int CERT_ATTEMPTS = 15; + + /** Fetches the floci-az CA PEM from an endpoint. A test seam. */ + @FunctionalInterface + public interface CertSource { + String fetch(String endpoint) throws FlociException; + } + + @Mixin + GlobalOptions global = new GlobalOptions(ProductProfile.AZ); + + @Option(names = {"--global"}, + description = "Configure your default az config (~/.azure) instead of an isolated one under ~/.floci/az") + boolean globalConfig; + + @Option(names = {"--reset"}, + description = "Undo a previous setup: delete the isolated config, or with --global switch az back to AzureCloud") + boolean reset; + + @Option(names = {"--tenant"}, description = "Tenant id to log in to (default: ${DEFAULT-VALUE})", + defaultValue = TENANT, paramLabel = "") + String tenant; + + @Option(names = {"--subscription"}, description = "Subscription to select (default: ${DEFAULT-VALUE})", + defaultValue = SUBSCRIPTION, paramLabel = "") + String subscription; + + @Option(names = {"--client-id"}, description = "Service principal client id (default: ${DEFAULT-VALUE})", + defaultValue = CLIENT_ID, paramLabel = "") + String clientId; + + @Option(names = {"--client-secret"}, description = "Service principal secret; floci-az does not check it (default: ${DEFAULT-VALUE})", + defaultValue = CLIENT_SECRET, paramLabel = "") + String clientSecret; + + private final Path stateRoot; + private final AzCli az; + private final CertSource certSource; + private final DockerClient docker; + private final Duration certRetryDelay; + + public AzSetupCommand() { + this(InstanceState.defaultRoot(), new ProcessAzCli(), + endpoint -> new FlociHttpClient(endpoint, ProductProfile.AZ.controlPrefix()).tlsCert(), + new DockerClient(), Duration.ofSeconds(2)); + } + + /** Test seam: {@code stateRoot} stands in for {@code ~/.floci}. */ + public AzSetupCommand(Path stateRoot, AzCli az, CertSource certSource, DockerClient docker, + Duration certRetryDelay) { + this.stateRoot = stateRoot; + this.az = az; + this.certSource = certSource; + this.docker = docker; + this.certRetryDelay = certRetryDelay; + } + + @Override + public Integer call() { + Printer printer = global.printer(); + // One setup per instance: the container name keys both the state dir and the az cloud, + // so '--profile team-b' never touches team-a's config, certificate or login. + String cloud = global.container; + Path flociAzDir; + try { + flociAzDir = InstanceState.dir(stateRoot, ProductProfile.AZ, cloud); + } catch (IllegalArgumentException e) { + printer.error(e.getMessage()); + return 1; + } + try { + return reset ? reset(printer, flociAzDir, cloud) : setup(printer, flociAzDir, cloud); + } catch (AzCliNotFoundException e) { + printer.error("az CLI not found in PATH.\n" + + "Install it from https://learn.microsoft.com/cli/azure/install-azure-cli, then re-run 'floci az setup'."); + return 1; + } catch (StepFailedException e) { + printer.error(e.getMessage() + + "\nFix the error above and re-run 'floci az setup', or run 'floci az setup --reset' to start over."); + return 1; + } + } + + private int setup(Printer printer, Path flociAzDir, String cloud) throws AzCliNotFoundException, StepFailedException { + String httpEndpoint = global.resolvedEndpoint(docker); + String httpsEndpoint = httpsOf(httpEndpoint); + Path configDir = flociAzDir.resolve(CONFIG_DIR_NAME); + Path caFile = flociAzDir.resolve(CA_NAME); + Path bundleFile = flociAzDir.resolve(BUNDLE_NAME); + + String caPem; + try { + caPem = fetchWithRetry(certSource, httpEndpoint, CERT_ATTEMPTS, certRetryDelay); + } catch (TlsUnavailableException e) { + printer.error(e.notYet() + ? "Floci Azure is still generating its TLS certificate.\nWait a few seconds and re-run 'floci az setup'." + : "Floci Azure is running without TLS, which the az CLI needs to log in.\n" + + "Run 'floci az restart' to enable it, then re-run 'floci az setup'."); + return 1; + } catch (FlociException e) { + printer.error(e.getMessage() + "\nRun 'floci az start', then re-run 'floci az setup'."); + return 1; + } + + try { + Files.createDirectories(flociAzDir); + Files.writeString(caFile, caPem.strip() + "\n"); + Files.writeString(bundleFile, CaBundle.build(caPem)); + if (!globalConfig) { + Files.createDirectories(configDir); + // The az config dir holds the login's token cache. + restrictPermissions(configDir); + } + } catch (Exception e) { + printer.error("Could not write the az configuration: " + e.getMessage() + + "\nCheck that " + flociAzDir + " is writable and re-run 'floci az setup'."); + return 1; + } + + Map env = azEnv(configDir, bundleFile); + + boolean cloudExisted = az.run(List.of("cloud", "show", "-n", cloud, "-o", "none"), env).ok(); + List cloudArgs = new ArrayList<>(List.of("cloud", cloudExisted ? "update" : "register", "-n", cloud)); + cloudArgs.addAll(cloudEndpointArgs(httpsEndpoint)); + require(az.run(cloudArgs, env), "az cloud " + (cloudExisted ? "update" : "register")); + require(az.run(List.of("cloud", "set", "-n", cloud), env), "az cloud set"); + // Without this MSAL validates the authority against login.microsoftonline.com and fails + // with invalid_instance. + require(az.run(List.of("config", "set", "core.instance_discovery=false"), env), "az config set"); + + List login = List.of("login", "--service-principal", + "-u", clientId, "-p", clientSecret, "--tenant", tenant, "-o", "none"); + AzCli.Result loggedIn = az.run(login, env); + if (!loggedIn.ok()) { + List retry = new ArrayList<>(login); + retry.add("--allow-no-subscriptions"); + require(az.run(retry, env), "az login"); + } + boolean subscriptionSet = az.run(List.of("account", "set", "--subscription", subscription), env).ok(); + + // This instance now uses the default az config. An isolated config left by an earlier + // setup would otherwise keep 'floci az env' selecting its old login. + boolean isolatedRemoved = false; + if (globalConfig && Files.isDirectory(configDir)) { + try { + deleteRecursively(configDir); + isolatedRemoved = true; + } catch (IOException e) { + printer.warn("Could not remove the old isolated az config " + configDir.toAbsolutePath() + ": " + + e.getMessage() + "\nDelete it by hand, or 'floci az env' keeps selecting it."); + } + } + + if (printer.format() != OutputFormat.text) { + Map out = new LinkedHashMap<>(); + out.put("container", global.container); + out.put("configDir", globalConfig ? null : configDir.toAbsolutePath().toString()); + out.put("global", globalConfig); + out.put("caBundle", bundleFile.toAbsolutePath().toString()); + out.put("cloud", cloud); + out.put("cloudRegistered", !cloudExisted); + out.put("endpoint", httpsEndpoint); + out.put("tenant", tenant); + out.put("subscription", subscription); + out.put("subscriptionSet", subscriptionSet); + if (globalConfig) out.put("isolatedConfigRemoved", isolatedRemoved); + printer.structured(out); + return 0; + } + + printer.println(Ansi.green("Trusted ") + "the Floci Azure certificate " + Ansi.gray("(" + caFile.toAbsolutePath() + ")")); + printer.println((cloudExisted ? Ansi.gray("Updated ") : Ansi.green("Registered ")) + "cloud " + + Ansi.bold(cloud) + " at " + httpsEndpoint); + printer.println(Ansi.green("Logged in ") + "as " + clientId + " in tenant " + tenant + + Ansi.gray(globalConfig ? " (default az config)" : " (" + configDir.toAbsolutePath() + ")")); + if (isolatedRemoved) { + printer.println(Ansi.gray("Removed the earlier isolated az config " + configDir.toAbsolutePath())); + } + if (!subscriptionSet) { + printer.warn("Could not select subscription " + subscription + + ". Run 'az account list' to see the available ones."); + } + printer.println(""); + printer.println("Connect with:"); + // The same line for both modes: after --global, env exports the CA bundle and unsets an + // AZURE_CONFIG_DIR an earlier isolated setup left in the shell (now deleted above). + // A profile may set output: json, which env would inherit and print instead of exports. + String textOnly = global.profile != null ? " -o text" : ""; + printer.println(" " + Ansi.bold("eval $(floci az env" + global.instanceSelector() + textOnly + ")")); + printer.println(" " + Ansi.bold("az group list")); + return 0; + } + + private int reset(Printer printer, Path flociAzDir, String cloud) throws AzCliNotFoundException, StepFailedException { + Map out = new LinkedHashMap<>(); + out.put("container", global.container); + out.put("global", globalConfig); + + if (globalConfig) { + Map env = azEnv(null, null); + AzCli.Result active = az.run(List.of("cloud", "show", "--query", "name", "-o", "tsv"), env); + boolean wasActive = active.ok() && cloud.equals(active.output().strip()); + if (wasActive) { + require(az.run(List.of("cloud", "set", "-n", "AzureCloud"), env), "az cloud set"); + require(az.run(List.of("config", "set", "core.instance_discovery=true"), env), "az config set"); + } + out.put("reset", wasActive); + if (printer.format() != OutputFormat.text) { + printer.structured(out); + } else if (wasActive) { + printer.println(Ansi.green("Switched ") + "the default az config back to " + Ansi.bold("AzureCloud")); + } else { + printer.println(Ansi.gray("Nothing to reset: ") + cloud + " is not the active az cloud."); + } + return 0; + } + + boolean existed = Files.exists(flociAzDir.resolve(CONFIG_DIR_NAME)); + try { + deleteRecursively(flociAzDir.resolve(CONFIG_DIR_NAME)); + Files.deleteIfExists(flociAzDir.resolve(BUNDLE_NAME)); + Files.deleteIfExists(flociAzDir.resolve(CA_NAME)); + deleteIfEmpty(flociAzDir); + } catch (IOException e) { + printer.error("Could not remove " + flociAzDir + ": " + e.getMessage() + + "\nDelete it by hand, then re-run 'floci az setup' if you need it again."); + return 1; + } + out.put("reset", existed); + if (printer.format() != OutputFormat.text) { + printer.structured(out); + } else if (existed) { + printer.println(Ansi.green("Removed ") + "the isolated az config in " + flociAzDir.toAbsolutePath()); + } else { + printer.println(Ansi.gray("Nothing to reset: ") + "no isolated az config in " + flociAzDir.toAbsolutePath()); + } + return 0; + } + + + /** + * The extra environment for every az call. A null value removes the variable, so a shell that + * already ran {@code eval $(floci az env)} cannot redirect a {@code --global} setup into the + * isolated config. + */ + private Map azEnv(Path configDir, Path bundleFile) { + Map env = new HashMap<>(); + env.put("AZURE_CONFIG_DIR", globalConfig || configDir == null ? null : configDir.toAbsolutePath().toString()); + if (bundleFile != null) { + env.put("REQUESTS_CA_BUNDLE", bundleFile.toAbsolutePath().toString()); + } + env.put("AZURE_CORE_ONLY_SHOW_ERRORS", "true"); + return env; + } + + /** The {@code az cloud register|update} endpoint arguments, as floci-az's compat suite uses them. */ + static List cloudEndpointArgs(String httpsEndpoint) { + return List.of( + "--endpoint-resource-manager", httpsEndpoint + "/", + "--endpoint-active-directory", httpsEndpoint, + "--endpoint-active-directory-resource-id", httpsEndpoint + "/", + "--endpoint-active-directory-graph-resource-id", httpsEndpoint + "/", + "--suffix-storage-endpoint", "core.windows.net", + "--suffix-keyvault-dns", ".vault.azure.net", + "--suffix-acr-login-server-endpoint", ".azurecr.io"); + } + + /** {@code http://host:port} to {@code https://host:port}: floci-az serves both on one port. */ + public static String httpsOf(String endpoint) { + URI uri = URI.create(endpoint); + int port = uri.getPort() == -1 ? ProductProfile.AZ.defaultPort() : uri.getPort(); + String host = uri.getHost() == null ? "localhost" : uri.getHost(); + return "https://" + (host.contains(":") ? "[" + host + "]" : host) + ":" + port; + } + + /** Fetches the certificate, waiting while the server reports it is still being generated. */ + public static String fetchWithRetry(CertSource source, String endpoint, int attempts, Duration delay) + throws FlociException { + for (int i = 1; ; i++) { + try { + return source.fetch(endpoint); + } catch (TlsUnavailableException e) { + if (!e.notYet() || i >= attempts) throw e; + } + try { + Thread.sleep(delay.toMillis()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new FlociException("Interrupted while waiting for the TLS certificate."); + } + } + } + + private static void require(AzCli.Result result, String step) throws StepFailedException { + if (result.ok()) return; + List lines = result.output().strip().lines().toList(); + String tail = String.join("\n", lines.subList(Math.max(0, lines.size() - 10), lines.size())); + throw new StepFailedException(step + " failed (exit " + result.exit() + ")" + + (tail.isEmpty() ? "." : ":\n" + tail)); + } + + private static void deleteRecursively(Path dir) throws IOException { + if (!Files.exists(dir)) return; + try (Stream paths = Files.walk(dir)) { + for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) { + Files.delete(p); + } + } + } + + private static void deleteIfEmpty(Path dir) throws IOException { + if (!Files.isDirectory(dir)) return; + try (Stream entries = Files.list(dir)) { + if (entries.findAny().isEmpty()) Files.delete(dir); + } + } + + private static void restrictPermissions(Path dir) { + try { + Files.setPosixFilePermissions(dir, PosixFilePermissions.fromString("rwx------")); + } catch (UnsupportedOperationException | IOException ignored) { + // Windows: no POSIX permissions; the directory inherits the user's ACLs. + } + } + + private static class StepFailedException extends Exception { + StepFailedException(String message) { + super(message); + } + } +} diff --git a/src/main/java/io/floci/cli/config/InstanceState.java b/src/main/java/io/floci/cli/config/InstanceState.java new file mode 100644 index 0000000..7ba3249 --- /dev/null +++ b/src/main/java/io/floci/cli/config/InstanceState.java @@ -0,0 +1,45 @@ +package io.floci.cli.config; + +import io.floci.cli.ProductProfile; + +import java.nio.file.Path; + +/** + * Where the CLI keeps local state about one emulator instance. + * + *

An instance is identified by its container name (a profile selects it through + * {@code container:}), so two instances of the same product never share state: + * {@code ~/.floci///}. Every command that keeps state about a specific + * running emulator goes through here; see AGENTS.md, "Multiple instances". + */ +public final class InstanceState { + + private InstanceState() { + } + + /** {@code ~/.floci}: the default root. */ + public static Path defaultRoot() { + return Path.of(System.getProperty("user.home"), ".floci"); + } + + /** {@code ~/.floci///}. */ + public static Path dir(ProductProfile product, String container) { + return dir(defaultRoot(), product, container); + } + + /** As above under {@code root}; the test seam. */ + public static Path dir(Path root, ProductProfile product, String container) { + return root.resolve(product.name()).resolve(validateContainer(container)); + } + + // Docker already restricts container names to [a-zA-Z0-9][a-zA-Z0-9_.-]*, but a name typed + // into --container or a profile reaches here before docker sees it, and it becomes a path. + static String validateContainer(String container) { + if (container == null || container.isBlank() || ".".equals(container) || "..".equals(container) + || container.contains("/") || container.contains("\\")) { + throw new IllegalArgumentException("Invalid container name '" + container + "'.\n" + + "Use letters, digits, '_', '.' or '-', as docker does, and re-run the command."); + } + return container; + } +} diff --git a/src/main/java/io/floci/cli/http/FlociHttpClient.java b/src/main/java/io/floci/cli/http/FlociHttpClient.java index ec33fb7..44d330b 100644 --- a/src/main/java/io/floci/cli/http/FlociHttpClient.java +++ b/src/main/java/io/floci/cli/http/FlociHttpClient.java @@ -3,6 +3,7 @@ package io.floci.cli.http; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.ConnectException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -108,6 +109,43 @@ public class FlociHttpClient { } } + /** + * The PEM CA certificate the server's HTTPS listener chains to. Only floci-az serves it, and + * only with TLS enabled; a 404 becomes {@link TlsUnavailableException}. + */ + public String tlsCert() throws FlociException { + String path = controlPrefix + "/tls-cert"; + try { + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create(endpoint + path)) + .timeout(Duration.ofSeconds(10)) + .GET() + .build(); + HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString()); + if (resp.statusCode() == 404) { + String message = ""; + try { + message = MAPPER.readTree(resp.body()).path("message").asText(""); + } catch (Exception ignored) { + // Not JSON: an older server without the endpoint at all. + } + throw new TlsUnavailableException( + message.isEmpty() ? "TLS certificate not available at " + path : message, + message.contains("not available yet")); + } + if (resp.statusCode() >= 400) { + throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path); + } + return resp.body(); + } catch (FlociException e) { + throw e; + } catch (ConnectException e) { + throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try 'floci status' or 'floci start'."); + } catch (Exception e) { + throw new FlociException("Request failed: " + e.getMessage()); + } + } + public Map postSnapshot(String name) throws FlociException { return postJson(controlPrefix + "/snapshots/" + name, "{}"); } @@ -143,7 +181,7 @@ public class FlociHttpClient { return MAPPER.readTree(resp.body()); } catch (FlociException e) { throw e; - } catch (java.net.ConnectException e) { + } catch (ConnectException e) { throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try 'floci status' or 'floci start'."); } catch (Exception e) { throw new FlociException("Request failed: " + e.getMessage()); @@ -167,7 +205,7 @@ public class FlociHttpClient { return MAPPER.readValue(resp.body(), Map.class); } catch (FlociException e) { throw e; - } catch (java.net.ConnectException e) { + } catch (ConnectException e) { throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try 'floci start'."); } catch (Exception e) { throw new FlociException("Request failed: " + e.getMessage()); diff --git a/src/main/java/io/floci/cli/http/TlsUnavailableException.java b/src/main/java/io/floci/cli/http/TlsUnavailableException.java new file mode 100644 index 0000000..b9065d8 --- /dev/null +++ b/src/main/java/io/floci/cli/http/TlsUnavailableException.java @@ -0,0 +1,19 @@ +package io.floci.cli.http; + +/** + * The server answered {@code /tls-cert} with 404: either TLS is off, or it is on and the + * certificate is still being generated ({@link #notYet()}), which is worth waiting for. + */ +public class TlsUnavailableException extends FlociException { + + private final boolean notYet; + + public TlsUnavailableException(String message, boolean notYet) { + super(message); + this.notYet = notYet; + } + + public boolean notYet() { + return notYet; + } +} diff --git a/src/main/java/io/floci/cli/output/ShellExport.java b/src/main/java/io/floci/cli/output/ShellExport.java index 9bab23d..78288ba 100644 --- a/src/main/java/io/floci/cli/output/ShellExport.java +++ b/src/main/java/io/floci/cli/output/ShellExport.java @@ -25,4 +25,13 @@ public final class ShellExport { default -> "export " + key + "='" + value.replace("'", "'\\''") + "'"; }; } + + /** Renders the line that removes {@code key} from the environment in the given shell. */ + public static String formatUnset(String shell, String key) { + return switch (shell.toLowerCase()) { + case "fish" -> "set -e " + key; + case "powershell", "ps1" -> "Remove-Item Env:" + key + " -ErrorAction SilentlyContinue"; + default -> "unset " + key; + }; + } } diff --git a/src/test/java/io/floci/cli/unit/AzEnvCommandTest.java b/src/test/java/io/floci/cli/unit/AzEnvCommandTest.java new file mode 100644 index 0000000..d324120 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/AzEnvCommandTest.java @@ -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); + } +} diff --git a/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java b/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java new file mode 100644 index 0000000..1107b8b --- /dev/null +++ b/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java @@ -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> calls = new ArrayList<>(); + final List> envs = new ArrayList<>(); + final Set failing = new HashSet<>(); + final Set clouds = new HashSet<>(); + String activeCloud = "AzureCloud"; + boolean installed = true; + + @Override + public Result run(List args, Map 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 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 inspectContainer(String name) { + return Optional.empty(); + } + } + + /** Where an instance's state lands: {@code /az//}. */ + 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 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 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 args, Map 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 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")); + } +} diff --git a/src/test/java/io/floci/cli/unit/AzTestCerts.java b/src/test/java/io/floci/cli/unit/AzTestCerts.java new file mode 100644 index 0000000..4888eb7 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/AzTestCerts.java @@ -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"; + } +} diff --git a/src/test/java/io/floci/cli/unit/CaBundleTest.java b/src/test/java/io/floci/cli/unit/CaBundleTest.java new file mode 100644 index 0000000..08678a2 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/CaBundleTest.java @@ -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("not found")); + } +} diff --git a/src/test/java/io/floci/cli/unit/FlociHttpClientTlsCertTest.java b/src/test/java/io/floci/cli/unit/FlociHttpClientTlsCertTest.java new file mode 100644 index 0000000..3c1579a --- /dev/null +++ b/src/test/java/io/floci/cli/unit/FlociHttpClientTlsCertTest.java @@ -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, "no such route"); + + assertFalse(assertThrows(TlsUnavailableException.class, client::tlsCert).notYet()); + } +} diff --git a/src/test/java/io/floci/cli/unit/GlobalOptionsTest.java b/src/test/java/io/floci/cli/unit/GlobalOptionsTest.java index 796ab5d..1b971a3 100644 --- a/src/test/java/io/floci/cli/unit/GlobalOptionsTest.java +++ b/src/test/java/io/floci/cli/unit/GlobalOptionsTest.java @@ -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(); + } } diff --git a/src/test/java/io/floci/cli/unit/InstanceStateTest.java b/src/test/java/io/floci/cli/unit/InstanceStateTest.java new file mode 100644 index 0000000..59d0af0 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/InstanceStateTest.java @@ -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)); + } +} diff --git a/src/test/java/io/floci/cli/unit/ProductProfileTest.java b/src/test/java/io/floci/cli/unit/ProductProfileTest.java index 42efa79..08fb08e 100644 --- a/src/test/java/io/floci/cli/unit/ProductProfileTest.java +++ b/src/test/java/io/floci/cli/unit/ProductProfileTest.java @@ -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()); } } diff --git a/src/test/java/io/floci/cli/unit/ProductTreesParsingTest.java b/src/test/java/io/floci/cli/unit/ProductTreesParsingTest.java index 7889215..e7c4929 100644 --- a/src/test/java/io/floci/cli/unit/ProductTreesParsingTest.java +++ b/src/test/java/io/floci/cli/unit/ProductTreesParsingTest.java @@ -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"))); } diff --git a/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java b/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java index 1e0c710..a735992 100644 --- a/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java +++ b/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java @@ -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", diff --git a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java index d1543e8..c18dd4b 100644 --- a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java +++ b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java @@ -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));