Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ecr): advertise TLS registry URIs on opt-in (#4252)
XuJian22c56157ee86
diff --git a/docs/services/ecr.md b/docs/services/ecr.mdindex ab5cc59694..c48be034fa 100644--- a/docs/services/ecr.md+++ b/docs/services/ecr.md@@ -31,6 +31,7 @@- **Real OCI registry backing.** A single shared `registry:2` container per Floci instance stores all repositories. Floci proxies Docker Distribution traffic to it and starts it lazily on the first ECR API call. The container is reused across Floci restarts (`keep-running-on-shutdown: true` by default), so pushed image bytes survive restarts.- **TLS registry data plane.** Real AWS ECR is HTTPS-only. When TLS is enabled (`FLOCI_TLS_ENABLED=true`), Floci serves the registry data plane over TLS at `<account>.dkr.ecr.<region>.localhost.floci.io:<port>/<repo>`. The server certificate automatically includes regional wildcards `*.dkr.ecr.<region>.localhost.floci.io` for every advertised AWS region as Subject Alternative Names (SANs). Container runtimes and tools (Docker, containerd, nerdctl, podman) connect over HTTPS after trusting Floci's root CA certificate (`GET /_floci/ca.pem` or system trust store). The plain HTTP loopback path (`<account>.dkr.ecr.<region>.localhost:<port>`) remains fully supported without changes.+- **Advertise TLS addresses.** Set `FLOCI_SERVICES_ECR_TLS_URI=true` together with `FLOCI_TLS_ENABLED=true` to return the TLS hostname in `repositoryUri` and an HTTPS `proxyEndpoint` from `GetAuthorizationToken`. This opt-in defaults to `false`. With `uri-style: path`, the URI becomes `localhost.floci.io:<port>/<account>/<region>/<repo>` and the login endpoint is `https://localhost.floci.io:<port>`. Existing repository records acquire the current URI when described or returned by deletion. If global TLS is disabled, the option has no effect. Clients must trust the Floci CA, or the configured certificate must cover the advertised names.- **Storage cleanup.** `DeleteRepository --force` removes repository manifests, including untagged manifests. When it deletes the final repository, or when a non-retained runtime stops, Floci removes the named registry volume only in `memory` mode or when `prune-volumes-on-delete: true`.- **Loopback URI scheme.** Repository URIs follow `<account>.dkr.ecr.<region>.localhost:<flociPort>/<repoName>`. RFC 6761 reserves `*.localhost` to resolve to the loopback address, and the docker daemon auto-trusts loopback as an insecure registry, so `docker push` and `docker pull` work without daemon configuration. A `path` URI style fallback (`localhost:<flociPort>/<account>/<region>/<repo>`) is available via `floci.services.ecr.uri-style: path` for environments where `*.localhost` resolution misbehaves.- **Image tag mutability.** `IMMUTABLE` repositories allow the first manifest write for a tag and reject every replacement, including a replacement with the same manifest. The proxy forwards blob uploads and digest-addressed manifests unchanged.@@ -54,6 +55,7 @@| `FLOCI_SERVICES_ECR_DATA_PATH` | `./data/ecr` | Bind-mount root for the registry data directory || `FLOCI_SERVICES_ECR_KEEP_RUNNING_ON_SHUTDOWN` | `true` | Leave the registry container running so the next Floci start adopts it || `FLOCI_SERVICES_ECR_URI_STYLE` | `hostname` | `hostname` = `*.dkr.ecr.<region>.localhost`; `path` = `localhost:<port>/<account>/<region>/<repo>` |+| `FLOCI_SERVICES_ECR_TLS_URI` | `false` | Report `localhost.floci.io` registry addresses and an HTTPS login endpoint when global `FLOCI_TLS_ENABLED` is also `true` || `FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES` | `true` | Use an AWS-shaped ECR image URI as-is when the Docker daemon already has that image, instead of rewriting it to the loopback registry || `FLOCI_SERVICES_ECR_TLS_ENABLED` | `false` | Reserved for future ACM-backed TLS |@@ -132,7 +134,7 @@ aws ecr delete-repository --repository-name floci-it/app --force \### Push and Pull over TLS-When TLS is enabled (`FLOCI_TLS_ENABLED=true`), trust Floci's root CA and authenticate against the TLS registry data plane:+Start Floci with `FLOCI_TLS_ENABLED=true` and `FLOCI_SERVICES_ECR_TLS_URI=true`, then trust Floci's root CA and use the repository address returned by the API:```bash# 1. Download and trust Floci's root CA@@ -140,26 +142,44 @@ curl -s http://localhost:4566/_floci/ca.pem -o floci-root-ca.pemexport AWS_CA_BUNDLE=$PWD/floci-root-ca.pemexport AWS_ENDPOINT=https://localhost:4566-# 2. Authenticate Docker against the TLS endpoint+# 2. Read the advertised repository and registry addresses+REPOSITORY_URI=$(aws ecr create-repository --repository-name floci-it/tls-app \+ --endpoint-url "$AWS_ENDPOINT" --query repository.repositoryUri --output text)+REGISTRY_HOST=${REPOSITORY_URI%%/*}++# 3. Trust the CA in Linux Docker Engine (separate from AWS_CA_BUNDLE)+sudo mkdir -p "/etc/docker/certs.d/$REGISTRY_HOST"+sudo cp floci-root-ca.pem "/etc/docker/certs.d/$REGISTRY_HOST/ca.crt"++# 4. Authenticate Docker against the TLS endpointaws ecr get-login-password --endpoint-url $AWS_ENDPOINT \| docker login --username AWS --password-stdin \- 000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566+ "$REGISTRY_HOST"-# 3. Tag and push an image over TLS+# 5. Tag and push an image over TLSdocker pull alpine:3.19-docker tag alpine:3.19 \- 000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566/floci-it/app:v1-docker push 000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566/floci-it/app:v1+docker tag alpine:3.19 "$REPOSITORY_URI:v1"+docker push "$REPOSITORY_URI:v1"-# 4. Pull over TLS-docker pull 000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566/floci-it/app:v1+# 6. Pull over TLS+docker pull "$REPOSITORY_URI:v1"```+For Docker Desktop, replace step 3 with installation of the Floci CA in the host trust store+and restart Docker Desktop, following [Docker's CA certificate instructions](https://docs.docker.com/engine/network/ca-certs/).+`AWS_CA_BUNDLE` affects the AWS CLI; it does not configure Docker's certificate trust.+!!! note "Pulling from other containers (EKS, same-network consumers)"The `localhost`-based repository URI only works from the host. [Floci EKS](eks.md#pulling-images-from-floci-ecr)configures a containerd mirror to reach Floci's data plane, so Helm charts can reference thepushed URI as-is.+ When TLS URI advertising is enabled, newly configured EKS registry mirrors accept both+ the loopback and TLS names and forward them to the same internal HTTP endpoint. Recreate+ existing clusters to pick up changed registry mirror settings. Automatic rewrites of+ AWS-shaped Lambda/ECS image references continue using loopback URIs; an explicitly supplied+ TLS image reference is used as supplied.+## SDK Example (Java)```java@@ -218,7 +238,7 @@ The following ECR features are **not** implemented. Stored values for policies a**`Function.TimedOut` when invoking image-backed Lambdas on native Linux Docker.** Lambda containers reach Floci's Runtime API server via the docker bridge gateway. On Ubuntu / Pop!_OS / Debian with UFW enabled, the default `INPUT DROP` policy blocks this path. See [Quick Start → Lambda on native Linux Docker](../getting-started/quick-start.md#lambda-on-native-linux-docker-ufw) for the one-line `ufw allow in on docker0` fix.-**`docker login` fails with TLS errors.** Floci's emulated registry serves plain HTTP. Docker auto-trusts loopback addresses (`127.0.0.1`, `*.localhost`) as insecure registries, so this should not normally happen. If your URIs end up pointing somewhere non-loopback (e.g. you set `FLOCI_HOSTNAME=floci` for Docker Compose), add the hostname to the daemon's `insecure-registries` array in `/etc/docker/daemon.json`.+**`docker login` fails with TLS errors.** When TLS URI advertising is enabled, Docker must trust the Floci CA independently of the AWS CLI, and the server certificate must cover the returned registry hostname. Follow the trust steps above; setting only `AWS_CA_BUNDLE` is insufficient. Default loopback URIs remain usable over HTTP without additional Docker trust configuration.**Disk not reclaimed after deleting images.** `BatchDeleteImage` removes manifests but blobs remain on disk until garbage collection runs. Trigger it with `curl -X POST http://localhost:4566/_floci/ecr/gc`. The endpoint runs `registry garbage-collect` inside the backing container and returns the reclaimed blob list. The operation is serialized — ECR API calls block for its duration (typically a few seconds).diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 4d9828839e..acbb20b626 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -2487,6 +2487,10 @@ public interface EmulatorConfig {@WithDefault("hostname")String uriStyle();+ /** Advertise TLS registry hostnames when Floci's global TLS listener is enabled. */+ @WithDefault("false")+ boolean tlsUri();+/*** When true, an AWS-shaped ECR image URI that names an image already present on the Docker* daemon is used as-is instead of being rewritten to Floci's loopback registry.diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.javaindex b8e2dc87a7..bdfbf20f4d 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java@@ -269,6 +269,7 @@ public class EcrService implements ResourceProvider {registryManager.pruneStorage();}LOG.infov("Deleted ECR repository {0}/{1}/{2}", region, account, repositoryName);+ repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repositoryName));return repo;}diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.javaindex 48c52c9566..de445114af 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java@@ -124,7 +124,7 @@ public class EcrRegistryManager {String region = m.group(2);String repoAndTag = m.group(3);ensureStarted();- String rewritten = getRepositoryUri(account, region, repoAndTag);+ String rewritten = repositoryUri(account, region, repoAndTag, "localhost");LOG.infov("Rewriting ECR image URI {0} -> {1}", image, rewritten);return rewritten;}@@ -144,16 +144,31 @@ public class EcrRegistryManager {/** Returns the docker-pullable repository URI for the given account/region/name. */public String getRepositoryUri(String accountId, String region, String repoName) {+ return repositoryUri(accountId, region, repoName, tlsUriEnabled() ? "localhost.floci.io" : "localhost");+ }++ private String repositoryUri(String accountId, String region, String repoName, String domain) {int port = config.port();String style = config.services().ecr().uriStyle();if ("path".equalsIgnoreCase(style)) {- return "localhost:" + port + "/" + accountId + "/" + region + "/" + repoName;+ return domain + ":" + port + "/" + accountId + "/" + region + "/" + repoName;}- return accountId + ".dkr.ecr." + region + ".localhost:" + port + "/" + repoName;+ return accountId + ".dkr.ecr." + region + "." + domain + ":" + port + "/" + repoName;+ }++ private boolean tlsUriEnabled() {+ return config.services().ecr().tlsUri() && config.tls().enabled();}/** Returns the proxy endpoint a docker daemon should log into for any ECR repo. */public String getProxyEndpoint() {+ if (tlsUriEnabled()) {+ String host = "path".equalsIgnoreCase(config.services().ecr().uriStyle())+ ? "localhost.floci.io"+ : regionResolver.getAccountId() + ".dkr.ecr."+ + regionResolver.getRegion() + ".localhost.floci.io";+ return "https://" + host + ":" + config.port();+ }String scheme = config.services().ecr().tlsEnabled() ? "https" : "http";return scheme + "://" + regionResolver.getAccountId() + ".dkr.ecr."+ regionResolver.getDefaultRegion() + ".localhost:" + config.port();diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.javaindex 8eac0533e6..6a0025278a 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java@@ -1357,7 +1357,8 @@ public class EksClusterManager {* Generates and injects {@code /etc/rancher/k3s/registries.yaml} into the (created,* not-yet-started) k3s container so its containerd can pull images pushed to the Floci ECR* registry. Mirrors every repository hostname the emulator can mint: the default account across- * the full region catalog and the path-style {@code localhost:<port>} form, to Floci's+ * the full region catalog and the path-style {@code localhost:<port>} form, including+ * {@code localhost.floci.io} aliases when TLS registry URIs are enabled, to Floci's* in-network data plane. Public registries are never matched. A failure disables the* mirror for this cluster but does not abort its startup, matching the webhook contract.*/@@ -1377,7 +1378,8 @@ public class EksClusterManager {regions.add(config.defaultRegion());}String endpoint = "http://" + dockerHostResolver.resolve() + ":" + config.port();- String content = buildRegistriesYaml(config.defaultAccountId(), regions, config.port(), endpoint);+ boolean tlsUri = config.services().ecr().tlsUri() && config.tls().enabled();+ String content = buildRegistriesYaml(config.defaultAccountId(), regions, config.port(), endpoint, tlsUri);writeLocalCopy(Paths.get(config.services().eks().dataPath(), "registries", clusterName,"registries.yaml"), content, clusterName);try {@@ -1516,16 +1518,28 @@ public class EksClusterManager {/*** Builds the k3s registries.yaml content. One mirror entry per hostname-style repository URI* ({@code <account>.dkr.ecr.<region>.localhost:<port>}) plus one for the path-style form- * ({@code localhost:<port>}), all pointing at Floci's in-network data plane. k3s supports+ * ({@code localhost:<port>}), all pointing at Floci's in-network data plane. The TLS URI+ * mode adds the corresponding {@code localhost.floci.io} aliases. k3s supports* no partial wildcards and a {@code "*"} catch-all would also intercept public registries,* so the hostnames are enumerated explicitly.*/static String buildRegistriesYaml(String accountId, List<String> regions, int dataPlanePort, String endpoint) {+ return buildRegistriesYaml(accountId, regions, dataPlanePort, endpoint, false);+ }++ static String buildRegistriesYaml(String accountId, List<String> regions, int dataPlanePort,+ String endpoint, boolean tlsUri) {StringBuilder yaml = new StringBuilder("mirrors:\n");for (String region : regions) {appendMirror(yaml, accountId + ".dkr.ecr." + region + ".localhost:" + dataPlanePort, endpoint);+ if (tlsUri) {+ appendMirror(yaml, accountId + ".dkr.ecr." + region + ".localhost.floci.io:" + dataPlanePort, endpoint);+ }}appendMirror(yaml, "localhost:" + dataPlanePort, endpoint);+ if (tlsUri) {+ appendMirror(yaml, "localhost.floci.io:" + dataPlanePort, endpoint);+ }return yaml.toString();}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 327725e64f..fd956db40b 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -572,6 +572,7 @@ floci:tls-enabled: falsekeep-running-on-shutdown: trueuri-style: hostname+ tls-uri: falseprefer-local-images: trueui:enabled: truediff --git a/src/test/java/io/github/hectorvent/floci/config/EcrTlsPathUriIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/EcrTlsPathUriIntegrationTest.javanew file mode 100644index 0000000000..7a82afba19--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/EcrTlsPathUriIntegrationTest.java@@ -0,0 +1,27 @@+package io.github.hectorvent.floci.config;++import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.TestProfile;++import java.util.LinkedHashMap;+import java.util.Map;++@QuarkusTest+@TestProfile(EcrTlsPathUriIntegrationTest.Profile.class)+class EcrTlsPathUriIntegrationTest extends EcrTlsUriIntegrationTest {++ @Override+ String expectedRepositoryUri(String repository) {+ return "localhost.floci.io:" + ADVERTISED_PORT + "/" + ACCOUNT + "/" + REGION + "/" + repository;+ }++ public static final class Profile extends EcrTlsUriIntegrationTest.Profile {++ @Override+ public Map<String, String> getConfigOverrides() {+ Map<String, String> overrides = new LinkedHashMap<>(super.getConfigOverrides());+ overrides.put("floci.services.ecr.uri-style", "path");+ return overrides;+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/EcrTlsUriIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/EcrTlsUriIntegrationTest.javanew file mode 100644index 0000000000..e5250342c9--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/EcrTlsUriIntegrationTest.java@@ -0,0 +1,219 @@+package io.github.hectorvent.floci.config;++import com.sun.net.httpserver.HttpServer;+import io.github.hectorvent.floci.services.acm.CertificateGenerator.GeneratedCertificate;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;+import io.github.hectorvent.floci.services.ecr.registry.RegistryHttpClient;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import io.quarkus.test.junit.mockito.InjectSpy;+import io.restassured.response.ValidatableResponse;+import io.vertx.core.Vertx;+import io.vertx.core.http.HttpClient;+import io.vertx.core.http.HttpClientOptions;+import io.vertx.core.http.HttpMethod;+import io.vertx.core.http.RequestOptions;+import io.vertx.core.net.PemTrustOptions;+import io.vertx.core.net.SocketAddress;+import jakarta.inject.Inject;+import org.eclipse.microprofile.config.inject.ConfigProperty;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.io.IOException;+import java.net.InetSocketAddress;+import java.net.URI;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.Map;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.LinkedBlockingQueue;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.doNothing;+import static org.mockito.Mockito.doReturn;++@QuarkusTest+@TestProfile(EcrTlsUriIntegrationTest.Profile.class)+class EcrTlsUriIntegrationTest {++ static final String ACCOUNT = "123456789012";+ static final String REGION = "eu-west-1";+ static final int ADVERTISED_PORT = 4566;+ private static final String MANIFEST = "{\"schemaVersion\":2}";+ private static final String DIGEST = "sha256:" + "1".repeat(64);++ @ConfigProperty(name = "quarkus.http.test-ssl-port")+ int sslPort;++ @Inject+ Vertx vertx;++ @InjectSpy+ EcrRegistryManager registryManager;++ private final BlockingQueue<String> backendRequests = new LinkedBlockingQueue<>();+ private HttpServer backend;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @BeforeEach+ void startRegistryBackend() throws IOException {+ backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ backend.createContext("/v2/", exchange -> {+ backendRequests.add(exchange.getRequestMethod() + " " + exchange.getRequestURI());+ exchange.getResponseHeaders().set("Docker-Distribution-Api-Version", "registry/2.0");+ exchange.getResponseHeaders().set("Docker-Content-Digest", DIGEST);+ exchange.getResponseHeaders().set("Content-Type", "application/vnd.oci.image.manifest.v1+json");+ byte[] body = MANIFEST.getBytes(StandardCharsets.UTF_8);+ if ("HEAD".equals(exchange.getRequestMethod())) {+ exchange.sendResponseHeaders(200, -1);+ } else {+ exchange.sendResponseHeaders(200, body.length);+ exchange.getResponseBody().write(body);+ }+ exchange.close();+ });+ backend.start();+ // Only container startup and its HTTP endpoint are replaced. URI generation stays real.+ doNothing().when(registryManager).ensureStarted();+ doReturn(true).when(registryManager).tryEnsureStarted();+ doReturn(new RegistryHttpClient("http://127.0.0.1:" + backend.getAddress().getPort()))+ .when(registryManager).httpClient();+ }++ @AfterEach+ void stopRegistryBackend() {+ if (backend != null) {+ backend.stop(0);+ }+ }++ @Test+ void advertisedRepositoryAndLoginEndpointReachTheRegistryWithVerifiedTls() throws Exception {+ String repository = "tls-uri/team-" + Long.toString(System.nanoTime(), 36);+ String expectedUri = expectedRepositoryUri(repository);+ String repositoryUri = request("CreateRepository", Map.of("repositoryName", repository))+ .body("repository.repositoryUri", equalTo(expectedUri))+ .body("repository.registryId", equalTo(ACCOUNT))+ .extract().path("repository.repositoryUri");+ request("DescribeRepositories", Map.of("repositoryNames", new String[]{repository}))+ .body("repositories[0].repositoryUri", equalTo(repositoryUri));++ URI image = URI.create("https://" + repositoryUri);+ String proxyEndpoint = request("GetAuthorizationToken", Map.of())+ .body("authorizationData[0].proxyEndpoint", equalTo("https://" + image.getAuthority()))+ .extract().path("authorizationData[0].proxyEndpoint");+ URI login = URI.create(proxyEndpoint);+ assertEquals("", login.getPath(), "Docker login uses the registry authority without a repository path");+ assertEquals(ADVERTISED_PORT, image.getPort());++ HttpClient client = vertx.createHttpClient(new HttpClientOptions()+ .setSsl(true)+ .setForceSni(true)+ .setTrustOptions(new PemTrustOptions().addCertPath(+ FlociCertificateAuthority.loadOrCreate(Profile.TLS_DIR).certificatePath().toString()))+ .setVerifyHost(true));+ try {+ RegistryResponse ping = execute(client, HttpMethod.GET, login, "/v2/");+ assertEquals(200, ping.status());+ assertEquals("GET /v2/", backendRequests.poll(5, TimeUnit.SECONDS));++ String manifestPath = "/v2" + image.getPath() + "/manifests/latest";+ RegistryResponse manifest = execute(client, HttpMethod.GET, image, manifestPath);+ assertEquals(200, manifest.status());+ assertEquals(MANIFEST, manifest.body());+ assertEquals(DIGEST, manifest.digest());+ String storagePath = "/v2/" + ACCOUNT + "/" + REGION + "/" + repository + "/manifests/latest";+ assertEquals("GET " + storagePath, backendRequests.poll(5, TimeUnit.SECONDS));++ RegistryResponse head = execute(client, HttpMethod.HEAD, image, manifestPath);+ assertEquals(200, head.status());+ assertEquals(DIGEST, head.digest());+ assertEquals("HEAD " + storagePath, backendRequests.poll(5, TimeUnit.SECONDS));+ } finally {+ client.close();+ }+ }++ String expectedRepositoryUri(String repository) {+ return ACCOUNT + ".dkr.ecr." + REGION + ".localhost.floci.io:" + ADVERTISED_PORT + "/" + repository;+ }++ private ValidatableResponse request(String action, Map<String, Object> body) {+ return given().contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921." + action)+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT+ + "/20260923/" + REGION + "/ecr/aws4_request")+ .body(body)+ .when().post("/")+ .then().statusCode(200);+ }++ private RegistryResponse execute(HttpClient client, HttpMethod method, URI advertised, String path)+ throws Exception {+ // Quarkus tests bind a random TLS port, while the production proxy uses fixed backend ports.+ // Override only the transport destination; retain the advertised authority and TLS hostname.+ RequestOptions options = new RequestOptions()+ .setServer(SocketAddress.inetSocketAddress(sslPort, "127.0.0.1"))+ .setHost(advertised.getHost())+ .setPort(advertised.getPort())+ .setMethod(method)+ .setURI(path);+ return client.request(options)+ .compose(request -> request.send())+ .compose(response -> response.body().map(body -> new RegistryResponse(+ response.statusCode(), body.toString(), response.getHeader("Docker-Content-Digest"))))+ .toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);+ }++ private record RegistryResponse(int status, String body, String digest) {}++ public static class Profile implements QuarkusTestProfile {++ static final Path DATA_DIR = Path.of("target", "floci-ecr-tls-uri-test").toAbsolutePath();+ static final Path TLS_DIR = DATA_DIR.resolve("tls");++ static {+ try {+ Files.createDirectories(TLS_DIR);+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);+ GeneratedCertificate leaf = ca.issueServerCertificate(+ "localhost", TlsConfigSource.DEFAULT_SAN_HOSTNAMES, KeyAlgorithm.RSA_2048, null);+ Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());+ Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());+ } catch (IOException e) {+ throw new IllegalStateException("Could not prepare ECR TLS URI test certificates", e);+ }+ }++ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.ofEntries(+ Map.entry("floci.services.ecr.tls-uri", "true"),+ Map.entry("floci.services.ecr.uri-style", "hostname"),+ Map.entry("floci.default-account-id", ACCOUNT),+ Map.entry("floci.default-region", "us-east-1"),+ Map.entry("floci.port", String.valueOf(ADVERTISED_PORT)),+ Map.entry("floci.tls.enabled", "true"),+ Map.entry("floci.tls.aws-https-port", "0"),+ Map.entry("floci.storage.persistent-path", DATA_DIR.toString()),+ Map.entry("quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString()),+ Map.entry("quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString()),+ Map.entry("quarkus.http.test-ssl-port", "0"),+ Map.entry("quarkus.http.insecure-requests", "enabled"));+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/EcrServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/EcrServiceTest.javaindex e71f5acd60..2d27dcb6a5 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecr/EcrServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecr/EcrServiceTest.java@@ -228,6 +228,40 @@ class EcrServiceTest {assertEquals(REPO, repos.get(0).getRepositoryName());}+ @Test+ void describeRepositoriesRefreshesStoredUrisForTheCurrentConfiguration() {+ String namedRepository = REPO + "-named";+ String listedRepository = REPO + "-listed";+ service.createRepository(namedRepository, null, null, null, null, null, null, REGION);+ service.createRepository(listedRepository, null, null, null, null, null, null, REGION);+ when(registryManager.getRepositoryUri(anyString(), anyString(), anyString()))+ .thenAnswer(invocation -> invocation.getArgument(0) + ".dkr.ecr." + invocation.getArgument(1)+ + ".localhost.floci.io:4566/" + invocation.getArgument(2));++ Repository named = service.describeRepositories(List.of(namedRepository), null, REGION).getFirst();+ assertEquals(ACCOUNT + ".dkr.ecr." + REGION + ".localhost.floci.io:4566/" + namedRepository,+ named.getRepositoryUri());+ List<Repository> listed = service.describeRepositories(null, null, REGION);+ assertEquals(2, listed.size());+ assertTrue(listed.stream().allMatch(repository -> repository.getRepositoryUri()+ .equals(ACCOUNT + ".dkr.ecr." + REGION + ".localhost.floci.io:4566/"+ + repository.getRepositoryName())));+ }++ @Test+ void deleteRepositoryRefreshesItsResponseWithoutRecreatingMetadata() {+ service.createRepository(REPO, null, null, null, null, null, null, REGION);+ String tlsUri = ACCOUNT + ".dkr.ecr." + REGION + ".localhost.floci.io:4566/" + REPO;+ when(registryManager.getRepositoryUri(ACCOUNT, REGION, REPO)).thenReturn(tlsUri);+ when(registryManager.tryEnsureStarted()).thenReturn(false);++ Repository deleted = service.deleteRepository(REPO, null, false, REGION);++ assertEquals(tlsUri, deleted.getRepositoryUri());+ assertThrows(AwsException.class, () -> service.describeRepositories(List.of(REPO), null, REGION));+ assertTrue(service.describeRepositories(null, null, REGION).isEmpty());+ }+@Testvoid describeRepositories_emptyList_returnsAllInRegion() {service.createRepository("a/one", null, null, null, null, null, null, REGION);diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlaneTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlaneTest.javaindex 7dc2582e09..2ac2ff38f8 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlaneTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlaneTest.java@@ -137,6 +137,29 @@ class EcrRegistryDataPlaneTest {"hostname").isPresent());}+ @Test+ void tlsMirrorNamespacePreservesTheAccountAndRegion() {+ EcrRegistryDataPlane.RegistryRequest request = EcrRegistryDataPlane.requestFor(+ "floci:4566", "/v2/team/app/manifests/v1",+ "ns=123456789012.dkr.ecr.eu-west-1.localhost.floci.io%3A4566", "hostname").orElseThrow();++ assertEquals("123456789012", request.accountId());+ assertEquals("eu-west-1", request.region());+ assertEquals("/v2/123456789012/eu-west-1/team/app/manifests/v1", request.backendUri());+ }++ @Test+ void tlsPathStyleMirrorPreservesTheRepositoryNamespace() {+ EcrRegistryDataPlane.RegistryRequest request = EcrRegistryDataPlane.requestFor(+ "floci:4566", "/v2/123456789012/eu-west-1/team/app/manifests/v1",+ "ns=localhost.floci.io%3A4566", "path").orElseThrow();++ assertEquals("123456789012", request.accountId());+ assertEquals("eu-west-1", request.region());+ assertEquals("team/app", request.repositoryName());+ assertEquals("/v2/123456789012/eu-west-1/team/app/manifests/v1", request.backendUri());+ }+@Testvoid registryPingDoesNotAcquireARepositoryNamespace() {var hostnameRequest = EcrRegistryDataPlane.requestFor(diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.javaindex 8d48f7a754..80d2c3f2ac 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManagerTest.java@@ -26,6 +26,8 @@ import com.github.dockerjava.api.model.ContainerPort;import com.github.dockerjava.api.model.Frame;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import org.mockito.Mockito;import java.io.Closeable;@@ -63,6 +65,7 @@ class EcrRegistryManagerTest {private ContainerLogStreamer logStreamer;private ContainerDetector containerDetector;private CurrentContainerNetworkResolver currentContainerNetworkResolver;+ private EmulatorConfig config;private EmulatorConfig.DockerConfig docker;private EmulatorConfig.EcrServiceConfig ecr;private EmulatorConfig.StorageConfig storage;@@ -97,7 +100,7 @@ class EcrRegistryManagerTest {currentContainerNetworkResolver = Mockito.mock(CurrentContainerNetworkResolver.class);RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");- EmulatorConfig config = Mockito.mock(EmulatorConfig.class);+ config = Mockito.mock(EmulatorConfig.class);ecr = Mockito.mock(EmulatorConfig.EcrServiceConfig.class);docker = Mockito.mock(EmulatorConfig.DockerConfig.class);storage = Mockito.mock(EmulatorConfig.StorageConfig.class);@@ -353,6 +356,59 @@ class EcrRegistryManagerTest {verify(lifecycleManager).createAndStart(any());}+ @ParameterizedTest+ @CsvSource({+ "hostname, false, false, 000000000000.dkr.ecr.us-east-1.localhost:4566/app, http://000000000000.dkr.ecr.us-east-1.localhost:4566",+ "hostname, true, false, 000000000000.dkr.ecr.us-east-1.localhost:4566/app, http://000000000000.dkr.ecr.us-east-1.localhost:4566",+ "hostname, false, true, 000000000000.dkr.ecr.us-east-1.localhost:4566/app, http://000000000000.dkr.ecr.us-east-1.localhost:4566",+ "hostname, true, true, 000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566/app, https://000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566",+ "path, false, false, localhost:4566/000000000000/us-east-1/app, http://000000000000.dkr.ecr.us-east-1.localhost:4566",+ "path, true, false, localhost:4566/000000000000/us-east-1/app, http://000000000000.dkr.ecr.us-east-1.localhost:4566",+ "path, false, true, localhost:4566/000000000000/us-east-1/app, http://000000000000.dkr.ecr.us-east-1.localhost:4566",+ "path, true, true, localhost.floci.io:4566/000000000000/us-east-1/app, https://localhost.floci.io:4566"+ })+ void advertisedUrisRequireBothTlsAndOptIn(String style, boolean globalTls, boolean tlsUris,+ String repositoryUri, String proxyEndpoint) {+ EmulatorConfig.TlsConfig tls = Mockito.mock(EmulatorConfig.TlsConfig.class);+ when(config.tls()).thenReturn(tls);+ when(tls.enabled()).thenReturn(globalTls);+ when(ecr.uriStyle()).thenReturn(style);+ when(ecr.tlsUri()).thenReturn(tlsUris);++ assertEquals(repositoryUri, manager.getRepositoryUri("000000000000", "us-east-1", "app"));+ assertEquals(proxyEndpoint, manager.getProxyEndpoint());+ verify(lifecycleManager, never()).createAndStart(any());+ }++ @ParameterizedTest+ @CsvSource({+ "hostname, 123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1",+ "path, localhost:4566/123456789012/us-east-1/backend-user:1"+ })+ void automaticImageRewritesKeepLoopbackWhenTlsUrisAreAdvertised(String style, String expectedImage) {+ EmulatorConfig.TlsConfig tls = Mockito.mock(EmulatorConfig.TlsConfig.class);+ when(config.tls()).thenReturn(tls);+ when(tls.enabled()).thenReturn(true);+ when(ecr.uriStyle()).thenReturn(style);+ when(ecr.tlsUri()).thenReturn(true);+ when(lifecycleManager.createAndStart(any())).thenReturn(+ new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));++ assertTrue(manager.getRepositoryUri("123456789012", "us-east-1", "backend-user")+ .contains("localhost.floci.io:"));+ assertEquals(expectedImage, manager.rewriteImageUri(AWS_ECR_IMAGE));+ }++ @Test+ void tlsUriOptInDoesNotReplaceTheLegacyEcrTlsSetting() {+ when(ecr.tlsEnabled()).thenReturn(true);++ assertEquals("http://" + REGISTRY_NAME + ":5000", manager.internalEndpoint());+ assertEquals("000000000000.dkr.ecr.us-east-1.localhost:4566/app",+ manager.getRepositoryUri("000000000000", "us-east-1", "app"));+ assertEquals("https://000000000000.dkr.ecr.us-east-1.localhost:4566", manager.getProxyEndpoint());+ }+@Testvoid rewriteImageUri_pathStyleConfig_usesPathStyleUri() {when(ecr.uriStyle()).thenReturn("path");diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.javaindex e33b51d271..6fe9fbf781 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java@@ -177,6 +177,43 @@ class EksClusterManagerTest {assertTrue(yaml.contains("- \"http://floci:4566\""));}+ @Test+ void registriesYamlTlsAliasesPreserveLoopbackMirrorsAndInternalHttpEndpoint() {+ String endpoint = "http://host.docker.internal:4577";+ String yaml = EksClusterManager.buildRegistriesYaml(+ "111122223333", AwsRegions.ALL, 4577, endpoint, true);++ for (String region : AwsRegions.ALL) {+ assertTrue(yaml.contains("\"111122223333.dkr.ecr." + region + ".localhost:4577\":"));+ assertTrue(yaml.contains("\"111122223333.dkr.ecr." + region + ".localhost.floci.io:4577\":"));+ }+ assertTrue(yaml.contains("\"localhost:4577\":"));+ assertTrue(yaml.contains("\"localhost.floci.io:4577\":"));+ assertFalse(yaml.contains("*"), "mirrors must not intercept unrelated registries");+ assertFalse(yaml.contains("amazonaws.com"));+ assertFalse(yaml.contains("docker.io"));+ assertFalse(yaml.contains("ghcr.io"));+ assertFalse(yaml.contains("https://"), "internal pulls still use the HTTP data plane");+ long endpoints = yaml.lines().filter(line -> line.contains("- \"" + endpoint + "\"")).count();+ assertEquals(2L * (AwsRegions.ALL.size() + 1), endpoints);+ }++ @Test+ void registriesYamlKeepsTheExistingOutputWhenTlsUrisAreDisabled() {+ String yaml = EksClusterManager.buildRegistriesYaml(+ "111122223333", List.of("eu-central-1"), 4566, "http://floci:4566", false);++ assertEquals("""+ mirrors:+ "111122223333.dkr.ecr.eu-central-1.localhost:4566":+ endpoint:+ - "http://floci:4566"+ "localhost:4566":+ endpoint:+ - "http://floci:4566"+ """, yaml);+ }+@Testvoid serverArgsOmitCniFlagsByDefault() {List<String> args = EksClusterManager.buildServerArgs(false);@@ -574,6 +611,7 @@ class EksClusterManagerTest {private DockerClient dockerClient;private CopyArchiveToContainerCmd copyCmd;private EcrRegistryManager registryManager;+ private EmulatorConfig config;private EmulatorConfig.EksServiceConfig eks;private EmulatorConfig.EcrServiceConfig ecr;private EksClusterManager manager;@@ -588,7 +626,7 @@ class EksClusterManagerTest {registryManager = Mockito.mock(EcrRegistryManager.class);- EmulatorConfig config = Mockito.mock(EmulatorConfig.class);+ config = Mockito.mock(EmulatorConfig.class);eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class);ecr = Mockito.mock(EmulatorConfig.EcrServiceConfig.class);when(config.services()).thenReturn(Mockito.mock(EmulatorConfig.ServicesConfig.class));@@ -611,12 +649,46 @@ class EksClusterManagerTest {}@Test- void injectsTheMirrorIntoTheContainer() {+ void injectsTheMirrorIntoTheContainer() throws Exception {manager.injectEcrRegistryMirror("container-1", "demo");verify(registryManager).ensureStarted();verify(copyCmd).withRemotePath("/etc");verify(copyCmd).exec();+ verify(config, never()).tls();+ String yaml = Files.readString(tempDir.resolve("registries/demo/registries.yaml"));+ assertFalse(yaml.contains("localhost.floci.io"));+ }++ @Test+ void injectsTlsAliasesWhenTlsAndTlsUrisAreEnabled() throws Exception {+ EmulatorConfig.TlsConfig tls = Mockito.mock(EmulatorConfig.TlsConfig.class);+ when(config.tls()).thenReturn(tls);+ when(tls.enabled()).thenReturn(true);+ when(ecr.tlsUri()).thenReturn(true);++ manager.injectEcrRegistryMirror("container-1", "demo");++ String yaml = Files.readString(tempDir.resolve("registries/demo/registries.yaml"));+ assertTrue(yaml.contains("\"000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566\":"));+ assertTrue(yaml.contains("\"localhost.floci.io:4566\":"));+ assertTrue(yaml.contains("- \"http://floci:4566\""));+ assertFalse(yaml.contains("https://"));+ verify(copyCmd).exec();+ }++ @Test+ void omitsTlsAliasesWhenTlsIsDisabled() throws Exception {+ EmulatorConfig.TlsConfig tls = Mockito.mock(EmulatorConfig.TlsConfig.class);+ when(config.tls()).thenReturn(tls);+ when(ecr.tlsUri()).thenReturn(true);++ manager.injectEcrRegistryMirror("container-1", "demo");++ String yaml = Files.readString(tempDir.resolve("registries/demo/registries.yaml"));+ assertFalse(yaml.contains("localhost.floci.io"));+ assertTrue(yaml.contains("\"localhost:4566\":"));+ verify(copyCmd).exec();}@Testdiff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 5db99bc4ba..39065f41b4 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -314,6 +314,7 @@ floci:enabled: trueecr:enabled: true+ tls-uri: falseui:enabled: truebedrock: