feat(az): configure the az CLI against floci-az with floci az setup (#29)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-08 21:29:02 -05:00
1 parent dd38f6dc27
commit 7b58a38c5a
27 files changed
+1587 -12

No files matched your search

@@ -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();
+11 -5
View File
@@ -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<String, String> 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());
}
@@ -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 <args>} 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<String> args, Map<String, String> env) throws AzCliNotFoundException;
/** Exit code plus stdout and stderr, interleaved. */
record Result(int exit, String output) {
public boolean ok() {
return exit == 0;
}
}
}
@@ -0,0 +1,7 @@
package io.floci.cli.azcli;
public class AzCliNotFoundException extends Exception {
public AzCliNotFoundException(String message) {
super(message);
}
}
@@ -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}.
*
* <p>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";
}
}
@@ -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<String> args, Map<String, String> env) throws AzCliNotFoundException {
List<String> 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<String> 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 "";
}
}
}
@@ -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<Integer> {
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;
}
@@ -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,
@@ -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<Integer> {
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<Integer> {
boolean sdkVarsMode = "sdk-vars".equals(format) || serviceFilter != null;
List<String> requestedServices = resolveServices();
Map<String, String> azCliVars = azCliVars(printer, effectiveEndpoint);
if (printer.format() != OutputFormat.text) {
Map<String, Object> out = new LinkedHashMap<>();
@@ -85,6 +107,7 @@ public class AzEnvCommand implements Callable<Integer> {
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<Integer> {
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<Integer> {
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<Integer> {
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<String, String> azCliVars(Printer printer, String endpoint) {
Map<String, String> 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<String, String> vars) {
vars.forEach((key, value) -> printer.println(value == null
? ShellExport.formatUnset(shell, key)
: ShellExport.formatExport(shell, key, value)));
}
private List<String> resolveServices() {
if (serviceFilter != null && !serviceFilter.isBlank()) {
List<String> result = new ArrayList<>();
@@ -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<Integer> {
// 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 = "<id>")
String tenant;
@Option(names = {"--subscription"}, description = "Subscription to select (default: ${DEFAULT-VALUE})",
defaultValue = SUBSCRIPTION, paramLabel = "<id>")
String subscription;
@Option(names = {"--client-id"}, description = "Service principal client id (default: ${DEFAULT-VALUE})",
defaultValue = CLIENT_ID, paramLabel = "<id>")
String clientId;
@Option(names = {"--client-secret"}, description = "Service principal secret; floci-az does not check it (default: ${DEFAULT-VALUE})",
defaultValue = CLIENT_SECRET, paramLabel = "<secret>")
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<String, String> env = azEnv(configDir, bundleFile);
boolean cloudExisted = az.run(List.of("cloud", "show", "-n", cloud, "-o", "none"), env).ok();
List<String> 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<String> 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<String> 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<String, Object> 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<String, Object> out = new LinkedHashMap<>();
out.put("container", global.container);
out.put("global", globalConfig);
if (globalConfig) {
Map<String, String> 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<String, String> azEnv(Path configDir, Path bundleFile) {
Map<String, String> 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<String> 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<String> 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<Path> 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<Path> 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);
}
}
}
@@ -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.
*
* <p>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/<product>/<container>/}. 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/<product>/<container>/}. */
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;
}
}
@@ -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<String> 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<String, Object> 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());
@@ -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;
}
}
@@ -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;
};
}
}