Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ecr): serve the registry data plane over TLS (#4040)

Simone Primarosa7777a97de9e4
diff --git a/docs/configuration/tls.md b/docs/configuration/tls.md
index 75534a29b7..cd0917630d 100644
--- a/docs/configuration/tls.md
+++ b/docs/configuration/tls.md
@@ -59,8 +59,9 @@ When `FLOCI_TLS_ENABLED=true` and no custom certificate is provided, Floci keeps
- Is persisted to `{persistent-path}/tls/` and reused across restarts
- Includes `localhost`, `127.0.0.1`, `0.0.0.0`, `*.localhost`, `localhost.floci.io`,
`*.localhost.floci.io`, `*.execute-api.localhost.floci.io`,
- `*.execute-api.localhost.localstack.cloud`, `*.cloudfront.localhost.floci.io`, and
- `*.cloudfront.localhost` as Subject Alternative Names (SANs)
+ `*.execute-api.localhost.localstack.cloud`, `*.cloudfront.localhost.floci.io`,
+ `*.cloudfront.localhost`, and `*.dkr.ecr.<region>.localhost.floci.io` for every advertised
+ AWS region as Subject Alternative Names (SANs)
- Automatically includes custom hostnames from `FLOCI_HOSTNAME`, `FLOCI_BASE_URL` and `FLOCI_SERVICES_IOT_ENDPOINT_ADDRESS` in the SANs
- Is regenerated when hostname configuration changes between restarts, or when it was not issued by the current CA
diff --git a/docs/services/ecr.md b/docs/services/ecr.md
index 8cd3062f55..ab5cc59694 100644
--- a/docs/services/ecr.md
+++ b/docs/services/ecr.md
@@ -2,7 +2,7 @@
**Protocol:** JSON 1.1 (`X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*`) for the control plane.
**Data plane:** OCI Distribution Spec v2 (`/v2/...`), proxied by Floci to a real `registry:2` container.
-**Endpoint:** `POST http://localhost:4566/` for the control plane; `<account>.dkr.ecr.<region>.localhost:4566/<repo>` for `docker push` / `docker pull`.
+**Endpoint:** `POST http://localhost:4566/` (or `https://...`) for the control plane; `<account>.dkr.ecr.<region>.localhost:4566/<repo>` (HTTP) or `<account>.dkr.ecr.<region>.localhost.floci.io:4566/<repo>` (TLS) for `docker push` / `docker pull`.
## Supported Actions
@@ -30,6 +30,7 @@
## Emulation Behavior
- **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.
- **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.
@@ -129,6 +130,31 @@ aws ecr delete-repository --repository-name floci-it/app --force \
--endpoint-url $AWS_ENDPOINT
```
+### 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:
+
+```bash
+# 1. Download and trust Floci's root CA
+curl -s http://localhost:4566/_floci/ca.pem -o floci-root-ca.pem
+export AWS_CA_BUNDLE=$PWD/floci-root-ca.pem
+export AWS_ENDPOINT=https://localhost:4566
+
+# 2. Authenticate Docker against the TLS endpoint
+aws ecr get-login-password --endpoint-url $AWS_ENDPOINT \
+ | docker login --username AWS --password-stdin \
+ 000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566
+
+# 3. Tag and push an image over TLS
+docker 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
+
+# 4. Pull over TLS
+docker pull 000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566/floci-it/app:v1
+```
+
!!! 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 the
diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
index e89cab9e7d..e0deb35efd 100644
--- a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
+++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.eclipse.microprofile.config.spi.ConfigSource;
@@ -64,13 +65,21 @@ public class TlsConfigSource implements ConfigSource {
// host.docker.internal: how Lambda containers reach Floci when it runs on the host (not in a container).
// A wildcard SAN covers one label, so every two-label service form needs its own entry.
// Package-private so the tests assert against this list instead of copying it.
- static final List<String> DEFAULT_SAN_HOSTNAMES = List.of(
- "localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
- "localhost.floci.io", "*.localhost.floci.io",
- "*.execute-api.localhost.floci.io",
- "*.execute-api.localhost.localstack.cloud",
- "*.cloudfront.localhost.floci.io", "*.cloudfront.localhost",
- "host.docker.internal");
+ static final List<String> DEFAULT_SAN_HOSTNAMES = defaultSanHostnames();
+
+ private static List<String> defaultSanHostnames() {
+ List<String> sans = new ArrayList<>(List.of(
+ "localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
+ "localhost.floci.io", "*.localhost.floci.io",
+ "*.execute-api.localhost.floci.io",
+ "*.execute-api.localhost.localstack.cloud",
+ "*.cloudfront.localhost.floci.io", "*.cloudfront.localhost",
+ "host.docker.internal"));
+ for (String region : AwsRegions.ALL) {
+ sans.add("*.dkr.ecr." + region + ".localhost.floci.io");
+ }
+ return List.copyOf(sans);
+ }
private static volatile Path resolvedTlsDir;
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlane.java b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlane.java
index fb894f94f6..3d7bde18e7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlane.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryDataPlane.java
@@ -33,7 +33,7 @@ import java.util.regex.Pattern;
public class EcrRegistryDataPlane {
private static final Pattern ECR_HOST = Pattern.compile(
- "^([0-9]{12})\\.dkr\\.ecr\\.([a-z0-9-]+)\\.localhost(?::[0-9]+)?$");
+ "^([0-9]{12})\\.dkr\\.ecr\\.([a-z0-9-]+)\\.localhost(?:\\.floci\\.io)?(?::[0-9]+)?$");
private static final String MANIFESTS_PATH = "/manifests/";
private static final Set<String> HOP_BY_HOP_HEADERS = Set.of(
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
diff --git a/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java
new file mode 100644
index 0000000000..3537576027
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java
@@ -0,0 +1,280 @@
+package io.github.hectorvent.floci.config;
+
+import io.github.hectorvent.floci.services.acm.CertificateGenerator.GeneratedCertificate;
+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import io.vertx.core.MultiMap;
+import io.vertx.core.Vertx;
+import io.vertx.core.buffer.Buffer;
+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.Assumptions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.GeneralSecurityException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Docker-gated integration test verifying OCI Distribution image push and pull
+ * over TLS against the ECR registry data plane, including hostname verification
+ * of the regional wildcard SANs and regression coverage for plain HTTP.
+ */
+@QuarkusTest
+@TestProfile(EcrTlsDataPlaneDockerIntegrationTest.Profile.class)
+class EcrTlsDataPlaneDockerIntegrationTest {
+
+ @ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
+ int sslPort;
+
+ @ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0")
+ int httpPort;
+
+ @Inject
+ Vertx vertx;
+
+ @BeforeAll
+ static void requireDocker() {
+ Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for ECR data plane tests");
+ }
+
+ private static boolean isDockerAvailable() {
+ try {
+ Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
+ .redirectErrorStream(true)
+ .start();
+ int exit = process.waitFor();
+ return exit == 0;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ @Test
+ void pushAndPullImageOverTlsAndVerifyPlainHttpRegression() throws Exception {
+ String tlsHost = "000000000000.dkr.ecr.us-east-1.localhost.floci.io";
+ HttpClient tlsClient = vertx.createHttpClient(new HttpClientOptions()
+ .setSsl(true)
+ .setForceSni(true)
+ .setTrustOptions(new PemTrustOptions().addCertPath(
+ FlociCertificateAuthority.loadOrCreate(Profile.TLS_DIR).certificatePath().toString()))
+ .setVerifyHost(true));
+
+ try {
+ // 1. Verify registry ping over TLS with hostname verification
+ SimpleResponse pingResponse = execute(tlsClient, HttpMethod.GET, sslPort, tlsHost, "/v2/", null, null, null);
+ assertEquals(200, pingResponse.statusCode());
+ assertEquals("registry/2.0", pingResponse.header("Docker-Distribution-Api-Version"));
+
+ // 2. Upload layer blob over TLS
+ byte[] layerBytes = "floci-ecr-tls-layer-content-v1".getBytes(StandardCharsets.UTF_8);
+ String layerDigest = "sha256:" + sha256Hex(layerBytes);
+
+ SimpleResponse startLayerUpload = execute(tlsClient, HttpMethod.POST, sslPort, tlsHost,
+ "/v2/tls-repo/blobs/uploads/", null, null, null);
+ assertEquals(202, startLayerUpload.statusCode());
+ String layerUploadLocation = startLayerUpload.header("Location");
+ assertNotNull(layerUploadLocation);
+
+ String layerUploadUri = layerUploadLocation + (layerUploadLocation.contains("?") ? "&" : "?")
+ + "digest=" + layerDigest;
+ SimpleResponse finishLayerUpload = execute(tlsClient, HttpMethod.PUT, sslPort, tlsHost,
+ layerUploadUri, "application/octet-stream", null, Buffer.buffer(layerBytes));
+ assertEquals(201, finishLayerUpload.statusCode());
+
+ // 3. Upload config blob over TLS
+ byte[] configBytes = "{\"architecture\":\"amd64\",\"os\":\"linux\"}".getBytes(StandardCharsets.UTF_8);
+ String configDigest = "sha256:" + sha256Hex(configBytes);
+
+ SimpleResponse startConfigUpload = execute(tlsClient, HttpMethod.POST, sslPort, tlsHost,
+ "/v2/tls-repo/blobs/uploads/", null, null, null);
+ assertEquals(202, startConfigUpload.statusCode());
+ String configUploadLocation = startConfigUpload.header("Location");
+ assertNotNull(configUploadLocation);
+
+ String configUploadUri = configUploadLocation + (configUploadLocation.contains("?") ? "&" : "?")
+ + "digest=" + configDigest;
+ SimpleResponse finishConfigUpload = execute(tlsClient, HttpMethod.PUT, sslPort, tlsHost,
+ configUploadUri, "application/octet-stream", null, Buffer.buffer(configBytes));
+ assertEquals(201, finishConfigUpload.statusCode());
+
+ // 4. Put manifest over TLS
+ String manifestJson = """
+ {
+ "schemaVersion": 2,
+ "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
+ "config": {
+ "mediaType": "application/vnd.docker.container.image.v1+json",
+ "size": %d,
+ "digest": "%s"
+ },
+ "layers": [
+ {
+ "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
+ "size": %d,
+ "digest": "%s"
+ }
+ ]
+ }
+ """.formatted(configBytes.length, configDigest, layerBytes.length, layerDigest);
+
+ SimpleResponse putManifestResponse = execute(tlsClient, HttpMethod.PUT, sslPort, tlsHost,
+ "/v2/tls-repo/manifests/v1",
+ "application/vnd.docker.distribution.manifest.v2+json",
+ null,
+ Buffer.buffer(manifestJson));
+ assertEquals(201, putManifestResponse.statusCode());
+ String manifestDigest = putManifestResponse.header("Docker-Content-Digest");
+ assertNotNull(manifestDigest);
+
+ // 5. Pull manifest over TLS
+ String manifestMediaType = "application/vnd.docker.distribution.manifest.v2+json";
+ SimpleResponse getManifestResponse = execute(tlsClient, HttpMethod.GET, sslPort, tlsHost,
+ "/v2/tls-repo/manifests/v1", null, manifestMediaType, null);
+ assertEquals(200, getManifestResponse.statusCode());
+ assertEquals(manifestDigest, getManifestResponse.header("Docker-Content-Digest"));
+
+ // 6. Pull layer blob over TLS
+ SimpleResponse getLayerResponse = execute(tlsClient, HttpMethod.GET, sslPort, tlsHost,
+ "/v2/tls-repo/blobs/" + layerDigest, null, null, null);
+ assertEquals(200, getLayerResponse.statusCode());
+ assertArrayEquals(layerBytes, getLayerResponse.body().getBytes());
+
+ // 7. List tags over TLS
+ SimpleResponse getTagsResponse = execute(tlsClient, HttpMethod.GET, sslPort, tlsHost,
+ "/v2/tls-repo/tags/list", null, null, null);
+ assertEquals(200, getTagsResponse.statusCode());
+ assertTrue(getTagsResponse.body().toString().contains("v1"));
+
+ // 8. Plain HTTP regression: verify the plain HTTP path still works on port
+ HttpClient httpClient = vertx.createHttpClient(new HttpClientOptions().setSsl(false));
+ try {
+ String httpHost = "000000000000.dkr.ecr.us-east-1.localhost:" + httpPort;
+ SimpleResponse httpPing = execute(httpClient, HttpMethod.GET, httpPort, httpHost,
+ "/v2/", null, null, null);
+ assertEquals(200, httpPing.statusCode());
+ assertEquals("registry/2.0", httpPing.header("Docker-Distribution-Api-Version"));
+
+ SimpleResponse httpManifestGet = execute(httpClient, HttpMethod.GET, httpPort, httpHost,
+ "/v2/tls-repo/manifests/v1", null, manifestMediaType, null);
+ assertEquals(200, httpManifestGet.statusCode());
+ assertEquals(manifestDigest, httpManifestGet.header("Docker-Content-Digest"));
+ } finally {
+ httpClient.close();
+ }
+ } finally {
+ tlsClient.close();
+ }
+ }
+
+ private SimpleResponse execute(HttpClient client, HttpMethod method, int port, String host,
+ String uri, String contentType, String accept, Buffer body) throws Exception {
+ String pureHost = host.contains(":") ? host.substring(0, host.indexOf(':')) : host;
+ RequestOptions options = new RequestOptions()
+ .setServer(SocketAddress.inetSocketAddress(port, "127.0.0.1"))
+ .setHost(pureHost)
+ .setPort(port)
+ .setMethod(method)
+ .setURI(uri);
+
+ return client.request(options)
+ .compose(request -> {
+ request.putHeader("Host", host);
+ if (contentType != null) {
+ request.putHeader("Content-Type", contentType);
+ }
+ if (accept != null) {
+ request.putHeader("Accept", accept);
+ }
+ if (body != null) {
+ request.putHeader("Content-Length", String.valueOf(body.length()));
+ return request.send(body);
+ }
+ return request.send();
+ })
+ .compose(response -> response.body().map(responseBody ->
+ new SimpleResponse(response.statusCode(), response.headers(), responseBody)))
+ .toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS);
+ }
+
+ private static String sha256Hex(byte[] data) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ byte[] hash = digest.digest(data);
+ StringBuilder hexString = new StringBuilder();
+ for (byte b : hash) {
+ String hex = Integer.toHexString(0xff & b);
+ if (hex.length() == 1) {
+ hexString.append('0');
+ }
+ hexString.append(hex);
+ }
+ return hexString.toString();
+ } catch (NoSuchAlgorithmException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private record SimpleResponse(int statusCode, MultiMap headers, Buffer body) {
+ String header(String name) {
+ return headers.get(name);
+ }
+ }
+
+ public static final class Profile implements QuarkusTestProfile {
+
+ static final Path DATA_DIR = Path.of("target", "floci-ecr-tls-dataplane-test").toAbsolutePath();
+ static final Path TLS_DIR = DATA_DIR.resolve("tls");
+ static final Path CERT_FILE = TLS_DIR.resolve("floci-server.crt");
+ static final Path KEY_FILE = TLS_DIR.resolve("floci-server.key");
+
+ static {
+ try {
+ Files.createDirectories(TLS_DIR);
+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
+ List<String> sans = new ArrayList<>(TlsConfigSource.DEFAULT_SAN_HOSTNAMES);
+ GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
+ Files.writeString(CERT_FILE, leaf.certificatePem());
+ Files.writeString(KEY_FILE, leaf.privateKeyPem());
+ ContainerCaBundle.write(TLS_DIR, ca.certificatePath());
+ } catch (IOException | GeneralSecurityException e) {
+ throw new IllegalStateException("Failed to prepare TLS test files", e);
+ }
+ }
+
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of(
+ "floci.tls.enabled", "true",
+ "floci.tls.self-signed", "true",
+ "floci.tls.aws-https-port", "0",
+ "floci.storage.persistent-path", DATA_DIR.toString(),
+ "quarkus.tls.key-store.pem.0.cert", CERT_FILE.toString(),
+ "quarkus.tls.key-store.pem.0.key", KEY_FILE.toString(),
+ "quarkus.http.insecure-requests", "enabled"
+ );
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java
index 9e464ce0c6..20c5d183cd 100644
--- a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java
+++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.bouncycastle.asn1.x500.X500Name;
@@ -471,6 +472,27 @@ class TlsCertificateHostnameTest {
leaf.verify(ca.getPublicKey());
}
+ @Test
+ void defaultSansIncludeEcrRegionalHostnamesForAllAwsRegions() throws Exception {
+ System.setProperty("floci.tls.enabled", "true");
+ System.setProperty("floci.tls.self-signed", "true");
+ System.setProperty("floci.storage.persistent-path", tempDir.toString());
+
+ new TlsConfigSource();
+
+ Path certFile = tempDir.resolve("tls/floci-server.crt");
+ X509Certificate cert = parseCertificate(certFile);
+ List<String> sans = extractSansFromCertificate(cert);
+
+ for (String region : AwsRegions.ALL) {
+ String expectedWildcard = "*.dkr.ecr." + region + ".localhost.floci.io";
+ assertTrue(TlsConfigSource.DEFAULT_SAN_HOSTNAMES.contains(expectedWildcard),
+ "DEFAULT_SAN_HOSTNAMES missing ECR wildcard for region " + region);
+ assertTrue(sans.contains(expectedWildcard),
+ "Certificate SANs missing ECR wildcard for region " + region);
+ }
+ }
+
// ==================== Helper Methods ====================
private X509Certificate parseCertificate(Path certFile) throws Exception {
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.java
index 7a85eec03a..7dc2582e09 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
@@ -57,6 +57,48 @@ class EcrRegistryDataPlaneTest {
assertEquals("/v2/000000000000/us-east-1/platform/api/manifests/v1", request.backendUri());
}
+ @Test
+ void hostnameStyleWithTlsDomainMatchesAndCapturesAccountAndRegion() {
+ EcrRegistryDataPlane.RegistryRequest request = EcrRegistryDataPlane.requestFor(
+ "123456789012.dkr.ecr.eu-west-1.localhost.floci.io:4566",
+ "/v2/team/app/manifests/v2", null, "hostname").orElseThrow();
+
+ assertEquals("123456789012", request.accountId());
+ assertEquals("eu-west-1", request.region());
+ assertEquals("team/app", request.repositoryName());
+ assertEquals("123456789012/eu-west-1/team/app", request.storageRepositoryName());
+ assertEquals("v2", request.tag());
+ assertEquals("/v2/123456789012/eu-west-1/team/app/manifests/v2", request.backendUri());
+
+ EcrRegistryDataPlane.RegistryRequest requestNoPort = EcrRegistryDataPlane.requestFor(
+ "123456789012.dkr.ecr.eu-west-1.localhost.floci.io",
+ "/v2/team/app/tags/list", null, "hostname").orElseThrow();
+
+ assertEquals("123456789012", requestNoPort.accountId());
+ assertEquals("eu-west-1", requestNoPort.region());
+ assertEquals("/v2/123456789012/eu-west-1/team/app/tags/list", requestNoPort.backendUri());
+ }
+
+ @Test
+ void malformedAccountOrNonEcrHostIsRejected() {
+ // Less than 12 digits
+ assertFalse(EcrRegistryDataPlane.requestFor(
+ "12345.dkr.ecr.us-east-1.localhost.floci.io:4566",
+ "/v2/repo/manifests/latest", null, "hostname").isPresent());
+ // Non-numeric account
+ assertFalse(EcrRegistryDataPlane.requestFor(
+ "abcdefghijkl.dkr.ecr.us-east-1.localhost.floci.io:4566",
+ "/v2/repo/manifests/latest", null, "hostname").isPresent());
+ // Non-ECR subdomain
+ assertFalse(EcrRegistryDataPlane.requestFor(
+ "s3.localhost.floci.io:4566",
+ "/v2/repo/manifests/latest", null, "hostname").isPresent());
+ // Default host
+ assertFalse(EcrRegistryDataPlane.requestFor(
+ "localhost.floci.io:4566",
+ "/v2/repo/manifests/latest", null, "hostname").isPresent());
+ }
+
@Test
void digestManifestWriteDoesNotAcquireAnImmutableTagLock() {
var request = EcrRegistryDataPlane.requestFor(
@@ -190,10 +232,72 @@ class EcrRegistryDataPlaneTest {
}
}
+ @Test
+ void immutableTagRejectsReplacementOverTlsDataPlane() throws Exception {
+ AtomicBoolean tagExists = new AtomicBoolean();
+ HttpServer registry = vertx.createHttpServer()
+ .requestHandler(request -> {
+ if (request.method() == HttpMethod.HEAD) {
+ request.response().setStatusCode(tagExists.get() ? 200 : 404)
+ .putHeader("Docker-Content-Digest", "sha256:existing")
+ .end();
+ } else if (request.method() == HttpMethod.PUT) {
+ tagExists.set(true);
+ request.response().setStatusCode(201).end();
+ } else {
+ request.response().setStatusCode(200).end();
+ }
+ })
+ .listen(0, "127.0.0.1")
+ .toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
+
+ HttpServer dataPlane = null;
+ try {
+ EcrRegistryManager registryManager = Mockito.mock(EcrRegistryManager.class);
+ EcrService ecrService = Mockito.mock(EcrService.class);
+ EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);
+ when(config.services().ecr().enabled()).thenReturn(true);
+ when(config.services().ecr().uriStyle()).thenReturn("hostname");
+ when(registryManager.httpClient())
+ .thenReturn(new RegistryHttpClient("http://127.0.0.1:" + registry.actualPort()));
+ when(ecrService.isImageTagImmutable("platform/api", "000000000000", "us-east-1"))
+ .thenReturn(true);
+ when(ecrService.registryRepositoryName("platform/api", "000000000000", "us-east-1"))
+ .thenReturn("legacy/platform-api");
+
+ Router router = Router.router(vertx);
+ new EcrRegistryDataPlane(registryManager, ecrService, config, vertx).register(router);
+ dataPlane = vertx.createHttpServer().requestHandler(router)
+ .listen(0, "127.0.0.1")
+ .toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
+
+ String tlsHost = "000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566";
+ assertEquals(201, putManifest(dataPlane.actualPort(), tlsHost).statusCode());
+
+ ManifestResponse rejected = putManifest(dataPlane.actualPort(), tlsHost);
+ assertEquals(400, rejected.statusCode());
+ JsonObject json = new JsonObject(rejected.body());
+ JsonArray errors = json.getJsonArray("errors");
+ assertNotNull(errors);
+ assertEquals(1, errors.size());
+ JsonObject error = errors.getJsonObject(0);
+ assertEquals("TAG_INVALID", error.getString("code"));
+ } finally {
+ if (dataPlane != null) {
+ dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
+ }
+ registry.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
+ }
+ }
+
private record ManifestResponse(int statusCode, String body) {
}
private ManifestResponse putManifest(int port) throws Exception {
+ return putManifest(port, "000000000000.dkr.ecr.us-east-1.localhost:4566");
+ }
+
+ private ManifestResponse putManifest(int port, String host) throws Exception {
HttpClient client = vertx.createHttpClient();
return client.request(new RequestOptions()
.setHost("127.0.0.1")
@@ -201,7 +305,7 @@ class EcrRegistryDataPlaneTest {
.setMethod(HttpMethod.PUT)
.setURI("/v2/platform/api/manifests/v1"))
.compose(request -> {
- request.putHeader("Host", "000000000000.dkr.ecr.us-east-1.localhost:4566");
+ request.putHeader("Host", host);
request.setChunked(true);
return request.send(Buffer.buffer("{}"));
})