From fd8be9afee33da378f90982d3b13cdcce4bb05a4 Mon Sep 17 00:00:00 2001 From: Mario Toffia Date: Sun, 8 Nov 2026 10:19:22 +0100 Subject: [PATCH] fix(ecr): pull rewritten ECR images from an address Docker Desktop reaches (#7752) * fix(ecr): pull rewritten ECR images from an address Docker Desktop reaches Docker Desktop's daemon runs in a VM and dials localhost there, where a host port Docker chose for Floci is not bound, so pulls of rewritten ECR images timed out. On Docker Desktop, rewrite to .dkr.ecr..localhost:, which Desktop sends through its host proxy and pulls over plain HTTP. * fix(ecr): warn when the Docker daemon's operating system cannot be read The rewrite then falls back to localhost, which Docker Desktop cannot reach, so the later pull timeout needs this cause next to it. --- docs/services/ecr.md | 8 +- .../ecr/registry/EcrRegistryDataPlane.java | 5 +- .../ecr/registry/EcrRegistryManager.java | 40 ++++++++-- .../registry/EcrRegistryDataPlaneTest.java | 11 +++ .../ecr/registry/EcrRegistryManagerTest.java | 73 +++++++++++++++++++ 5 files changed, 125 insertions(+), 12 deletions(-) diff --git a/docs/services/ecr.md b/docs/services/ecr.md index ac8fc821a0..ee3b9fc780 100644 --- a/docs/services/ecr.md +++ b/docs/services/ecr.md @@ -75,7 +75,7 @@ the optional `filter` fields. - **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 `.dkr.ecr..localhost.floci.io:/`. The server certificate automatically includes regional wildcards `*.dkr.ecr..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 (`.dkr.ecr..localhost:`) 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:///` and the login endpoint is `https://localhost.floci.io:`. 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 `.dkr.ecr..localhost:/`. RFC 6761 reserves `*.localhost` to resolve to the loopback address, and a Docker daemon with the classic image store auto-trusts loopback as an insecure registry, so `docker push` and `docker pull` work without daemon configuration. A daemon with the containerd image store, the default from Docker Engine 29, reaches only `localhost` and `127.0.0.1` over plain HTTP and takes `*.localhost` for an HTTPS registry: use the `path` URI style (`localhost:///`, `floci.services.ecr.uri-style: path`) there, as well as where `*.localhost` resolution misbehaves. +- **Loopback URI scheme.** Repository URIs follow `.dkr.ecr..localhost:/`. RFC 6761 reserves `*.localhost` to resolve to the loopback address, and a Docker daemon with the classic image store auto-trusts loopback as an insecure registry, so `docker push` and `docker pull` work without daemon configuration. A Linux daemon with the containerd image store, the default from Docker Engine 29, reaches only `localhost` and `127.0.0.1` over plain HTTP and takes `*.localhost` for an HTTPS registry: use the `path` URI style (`localhost:///`, `floci.services.ecr.uri-style: path`) there, as well as 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. `PutImage` follows the same rule and answers `ImageTagAlreadyExistsException`; a `docker push` and a `PutImage` of the same tag cannot both succeed. - **Pushing through the API.** `PutImage` and the layer API write to the same `registry:2` container as `docker push`, so an image written through the API is the one `docker pull` and `BatchGetImage` return. Retagging without Docker works as on AWS: read the manifest with `batch-get-image`, then write it with `put-image --image-tag `. - `PutImage` takes the media type from `imageManifestMediaType`, else from the manifest's own `mediaType`; a manifest with neither is `InvalidParameterException`, as on AWS. A tag outside ECR's rule (`[a-zA-Z0-9-_.]+`, at most 300 characters) is `InvalidParameterException` with ECR's message. The backing registry follows the OCI tag grammar, so Floci also refuses two kinds of tag ECR takes, with a message naming the limit: one starting with `.` or `-`, and one longer than 128 characters. A manifest whose layers the repository does not hold answers `LayersNotFoundException`; writing the manifest a tag already points at answers `ImageAlreadyExistsException`. @@ -97,7 +97,7 @@ the optional `filter` fields. - **Cross-account / cross-region isolation.** Internally the registry namespaces repositories as `//`, so the same repository name in different accounts or regions cannot collide. - **Reconcile on first start.** When the registry container starts, Floci queries `GET /v2/_catalog` and recreates `Repository` metadata entries for any namespaces present in the registry but missing from local storage. This means image bytes are never orphaned across restarts. - **Upgrade from direct registry access.** Floci recreates an older backing container with the same volume and a loopback-only port binding. Repositories written through the former direct endpoint retain their physical paths and map to the default account and Region; their returned URI moves to port `4566`. -- **Lambda, ECS and EMR Serverless integration.** Image-backed Lambda functions (`PackageType=Image`), ECS task containers and the custom images of EMR Serverless applications (in its `docker` runner mode) reference the same loopback `repositoryUri`. Floci rewrites real-AWS-shaped `.dkr.ecr..amazonaws.com/...` URIs to the loopback registry at pull time, path style on `localhost` (`localhost:///`) in either URI style and with or without TLS, the one address every Docker daemon pulls from over plain HTTP, so CDK's `DockerImageFunction` (which generates AWS-shaped URIs in CloudFormation templates) works without any user-side rewriting. +- **Lambda, ECS and EMR Serverless integration.** Image-backed Lambda functions (`PackageType=Image`), ECS task containers and the custom images of EMR Serverless applications (in its `docker` runner mode) reference the same loopback `repositoryUri`. Floci rewrites real-AWS-shaped `.dkr.ecr..amazonaws.com/...` URIs to the loopback registry at pull time, path style on `localhost` (`localhost:///`) in either URI style and with or without TLS, an address a Linux Docker daemon pulls from over plain HTTP. On Docker Desktop the rewrite is `.dkr.ecr..localhost:/` instead: Desktop's daemon runs in a VM and dials `localhost` there, where a host port Docker chose for Floci is not bound, while it sends `*.localhost` through its host proxy to the port Floci publishes. Floci asks the daemon once whether it is Docker Desktop. CDK's `DockerImageFunction` (which generates AWS-shaped URIs in CloudFormation templates) works without any user-side rewriting. - **Locally built images win.** An AWS-shaped URI that names an image already present on the Docker daemon is used as-is instead of being rewritten (`FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES`, default `true`). Build the image under the exact URI your function or task definition declares (`docker build -t .dkr.ecr..amazonaws.com/: .`) and it runs without a push to the emulated registry, and without the registry container being started. The check uses the reference Floci would launch, so with `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set the image must be present as `/.dkr.ecr..amazonaws.com/:`. ## Pull-time update exclusions @@ -148,7 +148,7 @@ services: `docker login 000000000000.dkr.ecr.us-east-1.localhost:4566` works once Floci starts the registry sidecar. -When Floci runs in a container that publishes its port on another host port (for example `docker run -p 54321:4566`), the `repositoryUri`, the `GetAuthorizationToken` `proxyEndpoint` and the rewritten Lambda, ECS and EMR Serverless image URIs all name that host port (`000000000000.dkr.ecr.us-east-1.localhost:54321`, and `localhost:54321/...` for a rewrite), because the Docker daemon performs login, push and pull through it. Floci reads the published port from its own container through the mounted Docker socket, and uses `floci.port` (`4566`) when it does not run in a container or the port is not published. +When Floci runs in a container that publishes its port on another host port (for example `docker run -p 54321:4566`), the `repositoryUri`, the `GetAuthorizationToken` `proxyEndpoint` and the rewritten Lambda, ECS and EMR Serverless image URIs all name that host port (`000000000000.dkr.ecr.us-east-1.localhost:54321`, and `localhost:54321/...` for a rewrite, or `000000000000.dkr.ecr.us-east-1.localhost:54321/...` on Docker Desktop), because the Docker daemon performs login, push and pull through it. Floci reads the published port from its own container through the mounted Docker socket, and uses `floci.port` (`4566`) when it does not run in a container or the port is not published. ## Examples @@ -325,4 +325,4 @@ See [Docker's bridge network documentation](https://docs.docker.com/engine/netwo **Disk not reclaimed after deleting images.** Deleting the last tag of an image, or deleting by digest, removes its manifest, 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). -**`*.localhost` does not resolve to loopback on this platform.** Set `floci.services.ecr.uri-style: path` to fall back to `localhost:///` URIs. +**`*.localhost` does not resolve to loopback on this platform.** Set `floci.services.ecr.uri-style: path` to fall back to `localhost:///` URIs. On Docker Desktop the rewrite of AWS-shaped Lambda, ECS and EMR Serverless images keeps `.dkr.ecr..localhost`; there, build the image under the AWS-shaped URI the function or task definition names, and Floci uses it as-is (`FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES`). diff --git a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java index a3bb2a93ad..746bcd7c95 100644 --- a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java +++ b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java @@ -473,8 +473,9 @@ public class EcrRegistryDataPlane { storageRepositoryName, repository, backendUri, tag(path))); } - // A loopback host is the address Floci itself hands the Docker daemon for the ECS, Lambda - // and EMR Serverless images it pulls, path style in either URI style (see rewriteImageUri). + // A loopback host is the address Floci itself hands a Docker daemon other than Docker Desktop + // for the ECS, Lambda and EMR Serverless images it pulls, path style in either URI style + // (see rewriteImageUri). if (!"path".equalsIgnoreCase(uriStyle) && !isLoopbackHost(host)) { return Optional.empty(); } diff --git a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java index bc08ec301b..4fb02c3107 100644 --- a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java +++ b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java @@ -35,6 +35,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Optional; import java.util.OptionalInt; import java.util.concurrent.TimeUnit; @@ -107,6 +108,8 @@ public class EcrRegistryManager { private volatile String containerId; private volatile Closeable logStream; private volatile Consumer> reconcileHook; + /** Whether the Docker daemon is Docker Desktop; null until the daemon has answered. */ + private volatile Boolean dockerDesktop; @Inject public EcrRegistryManager(ContainerBuilder containerBuilder, @@ -160,12 +163,20 @@ public class EcrRegistryManager { String region = m.group(2); String repoAndTag = m.group(3); ensureStarted(); - // Path style on localhost whatever style the API advertises. A daemon with the - // containerd image store, the default from Docker Engine 29, reaches only localhost and - // 127.0.0.1 over plain HTTP and takes every other name, *.localhost included, for an - // HTTPS registry: Floci's plain port cannot answer that, and its TLS port cannot prove - // itself to a daemon that does not trust Floci's CA. - String rewritten = "localhost:" + advertisedPort() + "/" + internalRepoName(account, region, repoAndTag); + String rewritten; + if (dockerDesktop()) { + // Docker Desktop's daemon runs in a VM and dials localhost there, where a host port Docker + // chose for Floci's container is not bound. It sends any other registry name through its + // host proxy, which reaches the port, and pulls *.localhost over plain HTTP. + rewritten = account + ".dkr.ecr." + region + ".localhost:" + advertisedPort() + "/" + repoAndTag; + } else { + // Path style on localhost whatever style the API advertises. A daemon with the + // containerd image store, the default from Docker Engine 29, reaches only localhost and + // 127.0.0.1 over plain HTTP and takes every other name, *.localhost included, for an + // HTTPS registry: Floci's plain port cannot answer that, and its TLS port cannot prove + // itself to a daemon that does not trust Floci's CA. + rewritten = "localhost:" + advertisedPort() + "/" + internalRepoName(account, region, repoAndTag); + } LOG.infov("Rewriting ECR image URI {0} -> {1}", image, rewritten); return rewritten; } @@ -195,6 +206,23 @@ public class EcrRegistryManager { } } + private boolean dockerDesktop() { + Boolean cached = dockerDesktop; + if (cached != null) { + return cached; + } + try { + String os = lifecycleManager.getDockerClient().infoCmd().exec().getOperatingSystem(); + cached = os != null && os.toLowerCase(Locale.ROOT).contains("docker desktop"); + } catch (RuntimeException e) { + LOG.warnv("Could not read the operating system of the Docker daemon ({0}); pulling ECR images from localhost", + e.getMessage()); + return false; + } + dockerDesktop = cached; + return cached; + } + /** 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"); diff --git a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java index 3efa6e9b4b..5dba7b8c08 100644 --- a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java +++ b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java @@ -78,6 +78,17 @@ class EcrRegistryDataPlaneTest { assertEquals("/v2/000000000000/us-east-1/platform/api/manifests/v1", request.backendUri()); } + @Test + void hostnameStyleHostKeepsItsNamespaceWhenPathStyleIsConfigured() { + // Docker Desktop pulls the ECS, Lambda and EMR Serverless images Floci rewrites from this host in either URI style. + EcrRegistryDataPlane.RegistryRequest request = EcrRegistryDataPlane.requestFor( + "000000000000.dkr.ecr.us-east-1.localhost:54321", + "/v2/platform/api/manifests/v1", null, "path").orElseThrow(); + + assertEquals("000000000000/us-east-1/platform/api", request.storageRepositoryName()); + assertEquals("/v2/000000000000/us-east-1/platform/api/manifests/v1", request.backendUri()); + } + @Test void hostnameStyleWithTlsDomainMatchesAndCapturesAccountAndRegion() { EcrRegistryDataPlane.RegistryRequest request = EcrRegistryDataPlane.requestFor( diff --git a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java index 573d4d5c58..a0e042a7c1 100644 --- a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java +++ b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java @@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.ExecCreateCmd; import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.github.dockerjava.api.command.ExecStartCmd; +import com.github.dockerjava.api.command.InfoCmd; import com.github.dockerjava.api.command.InspectExecCmd; import com.github.dockerjava.api.command.InspectExecResponse; import com.github.dockerjava.api.command.InspectImageCmd; @@ -16,6 +17,7 @@ import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.ContainerNetworkSettings; import com.github.dockerjava.api.model.ContainerPort; import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.Info; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; @@ -645,6 +647,77 @@ class EcrRegistryManagerTest { assertEquals(expectedImage, manager.rewriteImageUri(AWS_ECR_IMAGE)); } + @ParameterizedTest + @CsvSource({ + "hostname, false", + "path, false", + "hostname, true", + "path, true" + }) + void rewriteImageUri_dockerDesktop_pointsTheDaemonAtTheHostnameItProxiesToTheHost(String style, + boolean tlsUris) { + EmulatorConfig.TlsConfig tls = Mockito.mock(EmulatorConfig.TlsConfig.class); + when(config.tls()).thenReturn(tls); + when(tls.enabled()).thenReturn(tlsUris); + when(ecr.uriStyle()).thenReturn(style); + when(ecr.tlsUri()).thenReturn(tlsUris); + when(currentContainerNetworkResolver.resolvePublishedPort(4566)).thenReturn(OptionalInt.of(54321)); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + dockerOperatingSystem("Docker Desktop"); + + // Desktop's daemon dials localhost inside its VM, where a host port Docker chose is not bound. + assertEquals("123456789012.dkr.ecr.us-east-1.localhost:54321/backend-user:1", + manager.rewriteImageUri(AWS_ECR_IMAGE)); + } + + @Test + void rewriteImageUri_linuxDaemon_keepsLocalhost() { + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + dockerOperatingSystem("Ubuntu 24.04.1 LTS"); + + assertEquals("localhost:4566/123456789012/us-east-1/backend-user:1", + manager.rewriteImageUri(AWS_ECR_IMAGE)); + } + + @Test + void rewriteImageUri_daemonInfoFails_keepsLocalhostAndAsksAgain() { + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + InfoCmd infoCmd = Mockito.mock(InfoCmd.class); + Info info = Mockito.mock(Info.class); + when(dockerClient.infoCmd()).thenReturn(infoCmd); + when(infoCmd.exec()).thenThrow(new DockerClientException("daemon unavailable")).thenReturn(info); + when(info.getOperatingSystem()).thenReturn("Docker Desktop"); + + assertEquals("localhost:4566/123456789012/us-east-1/backend-user:1", + manager.rewriteImageUri(AWS_ECR_IMAGE)); + assertEquals("123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1", + manager.rewriteImageUri(AWS_ECR_IMAGE)); + } + + @Test + void rewriteImageUri_dockerDesktop_asksTheDaemonOnce() { + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + dockerOperatingSystem("Docker Desktop"); + + manager.rewriteImageUri(AWS_ECR_IMAGE); + assertEquals("123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1", + manager.rewriteImageUri(AWS_ECR_IMAGE)); + + verify(dockerClient, times(1)).infoCmd(); + } + + private void dockerOperatingSystem(String operatingSystem) { + InfoCmd infoCmd = Mockito.mock(InfoCmd.class); + Info info = Mockito.mock(Info.class); + when(dockerClient.infoCmd()).thenReturn(infoCmd); + when(infoCmd.exec()).thenReturn(info); + when(info.getOperatingSystem()).thenReturn(operatingSystem); + } + @Test void advertisedUrisKeepFlociPortWhenItIsNotPublishedFromAContainer() { when(config.port()).thenReturn(4577);