fix(ecr): enforce immutable image tags (#3009)

Route Docker Distribution traffic through Floci so repository mutability applies to manifest writes. Keep legacy registry storage reachable while moving public ECR endpoints to the guarded listener.
This commit is contained in:
Simone Primarosa authored and GitHub committed 2026-09-14 12:07:40 -04:00
1 parent a03c4d6160
commit 95079965a8
26 files changed
+909 -156

No files matched your search

@@ -270,7 +270,7 @@ floci:
enabled: true
registry-image: "registry:2"
registry-container-name: floci-ecr-registry
registry-base-port: 5100
registry-base-port: 5100 # private loopback backing port range
registry-max-port: 5199
data-path: ./data/ecr
tls-enabled: false
+2 -2
View File
@@ -73,8 +73,8 @@ volumes:
!!! warning "Docker socket"
Lambda, ElastiCache, RDS, OpenSearch, and MSK require access to the Docker socket (`/var/run/docker.sock`) to spawn and manage containers. If you don't use these services, you can omit that volume.
!!! note "ECR port"
ECR is backed by a `registry:2` sidecar container (`floci-ecr-registry`) that Floci starts and manages. That container binds its own host port (default `5100`) directly — do not add `5100-5199` to the Floci service's `ports` list. See [Ports Reference → ECR](./ports.md#ports-51005199--ecr-registry).
!!! note "ECR data plane"
ECR uses Floci's `4566` listener for Docker push and pull. The `registry:2` sidecar has a loopback-only implementation port; no ECR port range belongs in the Floci service's `ports` list. See [Ports Reference: ECR](./ports.md#ports-51005199--ecr-registry-backing-ports).
## Multi-container Networking
+2 -2
View File
@@ -417,8 +417,8 @@ These services spawn Docker containers. They require access to the Docker socket
| `FLOCI_SERVICES_ECR_ENABLED` | `true` | Enable the ECR service |
| `FLOCI_SERVICES_ECR_REGISTRY_IMAGE` | `registry:2` | Docker image for the ECR registry sidecar |
| `FLOCI_SERVICES_ECR_REGISTRY_CONTAINER_NAME` | `floci-ecr-registry` | Name of the ECR registry sidecar container |
| `FLOCI_SERVICES_ECR_REGISTRY_BASE_PORT` | `5100` | First port in the ECR registry range |
| `FLOCI_SERVICES_ECR_REGISTRY_MAX_PORT` | `5199` | Last port in the ECR registry range |
| `FLOCI_SERVICES_ECR_REGISTRY_BASE_PORT` | `5100` | First private loopback port for the backing registry |
| `FLOCI_SERVICES_ECR_REGISTRY_MAX_PORT` | `5199` | Last private loopback port for the backing registry |
| `FLOCI_SERVICES_ECR_TLS_ENABLED` | `false` | Enable TLS for the ECR registry |
| `FLOCI_SERVICES_ECR_KEEP_RUNNING_ON_SHUTDOWN` | `true` | Keep the ECR registry container running when Floci stops |
| `FLOCI_SERVICES_ECR_URI_STYLE` | `hostname` | Repository URI style: `hostname` (`<account>.dkr.ecr.<region>.localhost`) or `path` |
+10 -16
View File
@@ -4,8 +4,8 @@
| Port / Range | Protocol | Purpose | docker-compose mapping required? |
|---|---|---|---|
| `4566` | HTTP | All AWS API calls (every service) | Yes |
| `5100–5199` | HTTP | ECR Registry sidecar — bound directly by the `registry:2` container | **No** (see note) |
| `4566` | HTTP | AWS APIs and ECR Docker Distribution | Yes |
| `5100–5199` | HTTP | ECR Registry backing container, loopback-only implementation ports | No |
| `5672–5699` | AMQP | Amazon MQ (RabbitMQ) AMQP listener, bound directly by each broker container | **No** |
| `6379–6399` | TCP | ElastiCache Redis proxy (inside Floci) | Yes |
| `6400–6419` | TCP | MemoryDB proxy (inside Floci) | Yes |
@@ -31,7 +31,7 @@ host:6379 → [docker-compose ports mapping] → Floci container:6379 →
Because the listener is inside the Floci container, `ports:` in `docker-compose.yml` is required to make it reachable from the host.
### Direct container binding (ECR, EKS, OpenSearch, Amazon MQ)
### Direct container binding (EKS, OpenSearch, Amazon MQ)
Floci tells the Docker daemon to start a sidecar/service container and bind its port **directly on the host**. Floci itself communicates with the container via the shared Docker network (container name + internal port). The host port is bound by Docker, not by Floci.
@@ -158,22 +158,16 @@ aws mq create-broker --broker-name my-broker --engine-type RABBITMQ \
!!! note
Configure the ranges with `FLOCI_SERVICES_AMAZONMQ_AMQP_HOST_PORT_BASE` / `_MAX` and `FLOCI_SERVICES_AMAZONMQ_CONSOLE_HOST_PORT_BASE` / `_MAX`.
## Ports 5100–5199 — ECR Registry
## Ports 5100–5199: ECR Registry backing ports
ECR is backed by a separate `registry:2` sidecar container (`floci-ecr-registry`) that Floci starts on the first ECR API call. That container binds its port directly on the host — **do not** add `5100-5199` to the floci service's `ports` in Docker Compose. Doing so pre-allocates those ports on the Floci container and prevents the sidecar from binding them.
```
host:5100 ←── floci-ecr-registry (registry:2 container, started by Floci)
```
`docker login localhost:5100` works because the sidecar has a direct host port binding.
!!! warning "Do not expose ECR port range on the floci service"
Adding `- "5100-5199:5100-5199"` to the floci service ports will conflict with the ECR sidecar and break `docker push` / `docker pull`.
ECR uses the Floci `4566` listener for Docker Distribution and AWS API traffic. The `registry:2`
backing container binds a loopback-only implementation port in `5100-5199`; clients must use the
repository URI returned by `CreateRepository`, for example
`000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo`.
## Exposing Ports in Docker Compose
Only the proxy-based services (ElastiCache, MemoryDB, RDS, Neptune, MWAA) need port mappings in `docker-compose.yml`. Direct-binding services (ECR, EKS, OpenSearch, Amazon MQ) bind their ports on the host automatically via Docker:
Only the proxy-based services (ElastiCache, MemoryDB, RDS, Neptune, MWAA) need port mappings in `docker-compose.yml`. Direct-binding services (EKS, OpenSearch, Amazon MQ) bind their ports on the host automatically via Docker:
```yaml
services:
@@ -190,6 +184,6 @@ services:
- /var/run/docker.sock:/var/run/docker.sock
```
EKS (6500–6599), OpenSearch (9400–9499) and Amazon MQ (5672–5699, 15672–15699) ports are bound directly on the host by Docker and are accessible without any `ports:` entry. ECR (5100–5199) must not be added.
EKS (6500–6599), OpenSearch (9400–9499) and Amazon MQ (5672–5699, 15672–15699) ports are bound directly on the host by Docker and are accessible without any `ports:` entry. ECR uses the existing `4566` mapping.
If your application runs inside the same Docker Compose network, it can reach Floci directly on container port `4566` — the host port mapping is only needed for tools running on the host (CLI, IDE plugins, etc.).
+7 -7
View File
@@ -170,16 +170,16 @@ aws ecr create-repository --repository-name floci-it/app --endpoint-url $AWS_END
# Authenticate
aws ecr get-login-password --endpoint-url $AWS_ENDPOINT_URL \
| docker login --username AWS --password-stdin \
000000000000.dkr.ecr.us-east-1.localhost:5100
000000000000.dkr.ecr.us-east-1.localhost:4566
# Push
docker pull alpine:3.19
docker tag alpine:3.19 000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app:v1
docker push 000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app:v1
docker tag alpine:3.19 000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app:v1
docker push 000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app:v1
# Pull from a clean local image store
docker rmi 000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app:v1
docker pull 000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app:v1
docker rmi 000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app:v1
docker pull 000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app:v1
```
See the [ECR service docs](../services/ecr.md) for the full action surface, image-backed Lambda integration, and CDK `DockerImageFunction` support.
@@ -194,11 +194,11 @@ When Floci runs **natively on a Linux host** (not Docker Desktop), Lambda functi
sudo ufw allow in on docker0 comment 'floci: containers reach host'
```
If you want to scope it tighter to just the Lambda Runtime API and the ECR registry port ranges:
If you want to scope it tighter to the Lambda Runtime API and Floci's ECR data plane:
```bash
sudo ufw allow in on docker0 to any port 12000:12499 proto tcp comment 'floci lambda runtime api'
sudo ufw allow in on docker0 to any port 5100:5199 proto tcp comment 'floci ecr registry'
sudo ufw allow in on docker0 to any port 4566 proto tcp comment 'floci ecr data plane'
```
**Docker Desktop** (macOS / Windows / Linux) does not need this — it routes container → host through the Docker VM, which Floci's `DockerHostResolver` detects automatically.
+22 -22
View File
@@ -1,8 +1,8 @@
# ECR
**Protocol:** JSON 1.1 (`X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*`) for the control plane.
**Data plane:** OCI Distribution Spec v2 (`/v2/...`), served by a real `registry:2` container managed by Floci.
**Endpoint:** `POST http://localhost:4566/` for the control plane; `<account>.dkr.ecr.<region>.localhost:<port>/<repo>` for `docker push` / `docker pull`.
**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`.
## Supported Actions
@@ -16,7 +16,7 @@
| `DescribeImages` | Image metadata: digest, size, push timestamp, manifest media type |
| `BatchGetImage` | Fetch image manifests, honoring `acceptedMediaTypes` |
| `BatchDeleteImage` | Delete images by tag or digest |
| `PutImageTagMutability` | Set tag mutability (round-trip; not enforced on push) |
| `PutImageTagMutability` | Set tag mutability and reject replacement pushes to immutable tags |
| `TagResource` / `UntagResource` / `ListTagsForResource` | Resource tagging |
| `PutLifecyclePolicy` / `GetLifecyclePolicy` / `DeleteLifecyclePolicy` | Lifecycle policy round-trip (stored, not enforced) |
| `SetRepositoryPolicy` / `GetRepositoryPolicy` / `DeleteRepositoryPolicy` | Repository policy round-trip (stored, not enforced) |
@@ -29,13 +29,15 @@
## Emulation Behavior
- **Real OCI registry backing.** A single shared `registry:2` container per Floci instance serves all repositories. The container is started lazily on the first ECR API call and reused across Floci restarts (`keep-running-on-shutdown: true` by default), so pushed image bytes survive restarts.
- **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.
- **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:<registryPort>/<repoName>`. RFC 6761 reserves `*.localhost` to resolve to the loopback address, and the docker daemon auto-trusts loopback as an insecure registry, so **no daemon configuration changes are required** — `docker push` and `docker pull` work out of the box. A `path` URI style fallback (`localhost:<port>/<account>/<region>/<repo>`) is available via `floci.services.ecr.uri-style: path` for environments where `*.localhost` resolution misbehaves.
- **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.
- **Authorization.** `GetAuthorizationToken` returns `Base64("AWS:floci")` plus a proxy endpoint. The backing `registry:2` runs without auth, so any `aws ecr get-login-password | docker login` succeeds.
- **Manifest format negotiation.** `BatchGetImage` forwards the caller's `acceptedMediaTypes` as the upstream `Accept` header. Modern OCI manifests (`application/vnd.oci.image.manifest.v1+json`) and Docker v2 schema 2 are both supported.
- **Cross-account / cross-region isolation.** Internally the registry namespaces repositories as `<account>/<region>/<repoName>`, 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 and ECS integration.** Image-backed Lambda functions (`PackageType=Image`) and ECS task containers reference the same loopback `repositoryUri`. Floci rewrites real-AWS-shaped `<account>.dkr.ecr.<region>.amazonaws.com/...` URIs to the loopback registry at pull time, so 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 <account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag> .`) 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 `<base>/<account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag>`.
@@ -46,8 +48,8 @@
| `FLOCI_SERVICES_ECR_ENABLED` | `true` | Enable the ECR control plane and lazy registry start |
| `FLOCI_SERVICES_ECR_REGISTRY_IMAGE` | `registry:2` | Backing OCI registry image |
| `FLOCI_SERVICES_ECR_REGISTRY_CONTAINER_NAME` | `floci-ecr-registry` | Container name used for idempotent reuse across restarts |
| `FLOCI_SERVICES_ECR_REGISTRY_BASE_PORT` | `5100` | First port in the registry port range |
| `FLOCI_SERVICES_ECR_REGISTRY_MAX_PORT` | `5199` | Last port in the registry port range |
| `FLOCI_SERVICES_ECR_REGISTRY_BASE_PORT` | `5100` | First private loopback port for the backing registry |
| `FLOCI_SERVICES_ECR_REGISTRY_MAX_PORT` | `5199` | Last private loopback port for the backing registry |
| `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>` |
@@ -56,10 +58,10 @@
### Docker Compose port mapping
The ECR registry sidecar container binds its host port directly — do **not** add `5100-5199` to the floci service's `ports` in `docker-compose.yml`. Adding that range pre-allocates those ports on the floci container and prevents the sidecar from binding them:
ECR uses Floci's existing `4566` listener. The backing registry binds a loopback-only implementation port, so no ECR range belongs in `docker-compose.yml`:
```yaml
# Correct — no ECR port range on the floci service
# ECR uses the existing Floci API port
services:
floci:
image: floci/floci:latest
@@ -71,7 +73,7 @@ services:
- /var/run/docker.sock:/var/run/docker.sock
```
`docker login localhost:5100` works automatically once Floci starts the registry sidecar — no additional port mapping is needed.
`docker login 000000000000.dkr.ecr.us-east-1.localhost:4566` works once Floci starts the registry sidecar.
## Examples
@@ -85,7 +87,7 @@ aws ecr create-repository \
# {
# "repository": {
# "repositoryArn": "arn:aws:ecr:us-east-1:000000000000:repository/floci-it/app",
# "repositoryUri": "000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app",
# "repositoryUri": "000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app",
# "imageTagMutability": "MUTABLE",
# ...
# }
@@ -94,27 +96,27 @@ aws ecr create-repository \
# Authenticate stock docker against the emulated registry
aws ecr get-login-password --endpoint-url $AWS_ENDPOINT \
| docker login --username AWS --password-stdin \
000000000000.dkr.ecr.us-east-1.localhost:5100
000000000000.dkr.ecr.us-east-1.localhost:4566
# Push an image
docker pull alpine:3.19
docker tag alpine:3.19 \
000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app:v1
docker push 000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app:v1
000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app:v1
docker push 000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app:v1
# Inspect via the AWS CLI
aws ecr list-images --repository-name floci-it/app --endpoint-url $AWS_ENDPOINT
aws ecr describe-images --repository-name floci-it/app --endpoint-url $AWS_ENDPOINT
# Pull from a clean local image store
docker rmi 000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app:v1
docker pull 000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app:v1
docker rmi 000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app:v1
docker pull 000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app:v1
# Use the image as a Lambda function
aws lambda create-function \
--function-name my-image-fn \
--package-type Image \
--code ImageUri=000000000000.dkr.ecr.us-east-1.localhost:5100/floci-it/app:v1 \
--code ImageUri=000000000000.dkr.ecr.us-east-1.localhost:4566/floci-it/app:v1 \
--role arn:aws:iam::000000000000:role/lambda-role \
--endpoint-url $AWS_ENDPOINT
@@ -128,11 +130,9 @@ aws ecr delete-repository --repository-name floci-it/app --force \
```
!!! note "Pulling from other containers (EKS, same-network consumers)"
The `localhost`-based repository URI only works from the host. From other containers
on the Docker network, the registry is reachable at `http://floci-ecr-registry:5000`
(container name + container-internal port — not the published `5100+` host port).
[Floci EKS](eks.md#pulling-images-from-floci-ecr) clusters get a containerd mirror
for this automatically, so Helm charts can reference the pushed URI as-is.
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
pushed URI as-is.
## SDK Example (Java)
+11 -12
View File
@@ -119,41 +119,40 @@ back (for example Docker is unavailable), the cluster is marked `FAILED` instead
### Pulling images from Floci ECR
Images pushed to the [Floci ECR registry](ecr.md) use `localhost`-based repository URIs
(for example `000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:tag`). Inside a k3s
(for example `000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:tag`). Inside a k3s
cluster that hostname would resolve to the k3s container itself, and containerd insists
on HTTPS for anything it doesn't recognize as loopback — so, out of the box, k3s cannot
pull from the registry even though `docker push` from the host works.
Floci solves this at cluster creation: each new k3s container gets a generated
`/etc/rancher/k3s/registries.yaml` that mirrors every repository hostname the emulator
can mint — the default account across the full region catalog, plus the path-style
`localhost:<port>` form used by `FLOCI_SERVICES_ECR_URI_STYLE=path` — to the registry
container's in-network endpoint (`http://floci-ecr-registry:5000`). The same image
can mint: the default account across the full region catalog, plus the path-style
`localhost:<port>` form used by `FLOCI_SERVICES_ECR_URI_STYLE=path`, to Floci's
in-network data plane. The same image
reference then works for the host-side push and the in-cluster pull, with no retagging
and no manual containerd configuration:
```bash
aws ecr create-repository --repository-name my-repo
docker build -t 000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:v1 .
docker push 000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:v1
docker build -t 000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:v1 .
docker push 000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:v1
aws eks create-cluster --name demo ...
helm install my-app ./chart \
--set image.repository=000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo \
--set image.repository=000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo \
--set image.tag=v1
```
Requirements and limits:
- The k3s and registry containers must share a Docker network — set the global
`FLOCI_SERVICES_DOCKER_NETWORK` (as in the standard `docker-compose.yml`) or the
per-service network variables.
- The k3s container must reach Floci's Docker-network address. Set the global
`FLOCI_SERVICES_DOCKER_NETWORK` as in the standard `docker-compose.yml` or the
EKS service network variable.
- Only Floci-mintable hostnames are mirrored; public registries (docker.io, ghcr.io, …)
are never touched.
- Repository URIs using a non-default `registryId` (account) are not covered.
- The mirror set is snapshotted when the cluster is created. Clusters created before this
feature (or after the registry was re-created on a different port) can be fixed
manually — the k3s container filesystem survives a restart:
feature can be fixed manually because the k3s container filesystem survives a restart:
```bash
docker cp registries.yaml floci-eks-<cluster>:/etc/rancher/k3s/registries.yaml
+2 -2
View File
@@ -81,7 +81,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 78 |
| [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions |
| [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 12 |
| [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane via `registry:2`) | JSON 1.1 + OCI Distribution | 17 |
| [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane proxied to `registry:2`) | JSON 1.1 + OCI Distribution | 17 |
| [Resource Groups Tagging API](resource-groups-tagging.md) | `POST /` + `X-Amz-Target: ResourceGroupsTaggingAPI_20170126.*` | JSON 1.1 | 5 |
| [Resource Explorer](resource-explorer.md) | `POST /{OperationName}`, rewritten to `/re2/*` for the four paths S3 Vectors also claims | REST JSON | 32 |
| [SES](ses.md) | `POST /` with `Action=` param | Query | 16 |
@@ -140,7 +140,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
**Lambda, ElastiCache, RDS, MSK, MWAA, ECS, EKS, and OpenSearch** spin up real Docker containers and support IAM authentication and SigV4 request signing, the same auth flow as production AWS. **RDS Data API** executes SQL against the local RDS containers through AWS-compatible REST JSON routes.
**ECR** runs a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane. **EKS** (real mode) starts a k3s container per cluster and exposes the Kubernetes API server on a host port. **OpenSearch** (real mode) starts an `opensearchproject/opensearch` container per domain and exposes the data-plane REST API on a host port. **DocumentDB** starts a real `mongo` container per cluster and returns its host and port as the cluster endpoint, so any MongoDB driver can connect against the MongoDB-compatible wire protocol.
**ECR** proxies Docker Distribution traffic to a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane. **EKS** (real mode) starts a k3s container per cluster and exposes the Kubernetes API server on a host port. **OpenSearch** (real mode) starts an `opensearchproject/opensearch` container per domain and exposes the data-plane REST API on a host port. **DocumentDB** starts a real `mongo` container per cluster and returns its host and port as the cluster endpoint, so any MongoDB driver can connect against the MongoDB-compatible wire protocol.
## Common Setup
@@ -115,6 +115,7 @@ public class ContainerBuilder {
private String workingDir;
private Long memoryBytes;
private final Map<Integer, Integer> portBindings = new HashMap<>();
private final List<Integer> loopbackPortBindings = new ArrayList<>();
private final List<Integer> exposedPorts = new ArrayList<>();
private String networkMode;
private final List<Mount> mounts = new ArrayList<>();
@@ -219,6 +220,19 @@ public class ContainerBuilder {
return this;
}
/**
* Publishes a container port to the host loopback interface only.
*
* <p>Use this for implementation backends reached through Floci's public data plane,
* not for customer-facing service endpoints.
*/
public Builder withLoopbackPortBinding(int containerPort, int hostPort) {
this.portBindings.put(containerPort, hostPort);
this.loopbackPortBindings.add(containerPort);
this.exposedPorts.add(containerPort);
return this;
}
/**
* Adds a port binding with dynamic host port allocation.
* Use this when you don't care which host port is used.
@@ -440,6 +454,7 @@ public class ContainerBuilder {
entrypoint != null ? List.copyOf(entrypoint) : null,
memoryBytes,
Map.copyOf(portBindings),
List.copyOf(loopbackPortBindings),
List.copyOf(exposedPorts),
networkMode,
List.copyOf(mounts),
@@ -882,7 +882,10 @@ public class ContainerLifecycleManager {
hostPort = portAllocator.allocateAny();
}
ports.bind(ExposedPort.tcp(containerPort), Ports.Binding.bindPort(hostPort));
Ports.Binding binding = spec.loopbackPortBindings().contains(containerPort)
? Ports.Binding.bindIpAndPort("127.0.0.1", hostPort)
: Ports.Binding.bindPort(hostPort);
ports.bind(ExposedPort.tcp(containerPort), binding);
LOG.debugv("Port binding: {0} -> {1}", String.valueOf(containerPort), String.valueOf(hostPort));
}
hostConfig.withPortBindings(ports);
@@ -18,6 +18,7 @@ import java.util.Map;
* @param entrypoint Entrypoint to use (overrides image ENTRYPOINT)
* @param memoryBytes Memory limit in bytes (null = no limit)
* @param portBindings Map of container port to host port (0 = dynamic allocation)
* @param loopbackPortBindings Container ports whose host bindings accept loopback traffic only
* @param exposedPorts Ports to expose (required for port bindings)
* @param networkMode Docker network name or mode (null = default bridge)
* @param mounts Volume mounts (named volumes, bind mounts, tmpfs)
@@ -40,6 +41,7 @@ public record ContainerSpec(
List<String> entrypoint,
Long memoryBytes,
Map<Integer, Integer> portBindings,
List<Integer> loopbackPortBindings,
List<Integer> exposedPorts,
String networkMode,
List<Mount> mounts,
@@ -59,7 +61,35 @@ public record ContainerSpec(
* All other fields will be null or empty lists.
*/
public ContainerSpec(String image) {
this(image, null, List.of(), null, null, null, Map.of(), List.of(), null, List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), null, null, List.of());
this(image, null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null, List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), null, null, List.of());
}
/**
* Backward-compatible constructor that defaults {@code loopbackPortBindings} to empty.
*/
public ContainerSpec(
String image,
String name,
List<String> env,
List<String> cmd,
List<String> entrypoint,
Long memoryBytes,
Map<Integer, Integer> portBindings,
List<Integer> exposedPorts,
String networkMode,
List<Mount> mounts,
List<Bind> binds,
List<String> extraHosts,
Map<String, String> labels,
LogConfig logConfig,
boolean privileged,
String cgroupnsMode,
List<String> dnsServers,
String workingDir,
String user,
List<String> groupAdd
) {
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, List.of(), exposedPorts, networkMode, mounts, binds, extraHosts, labels, logConfig, privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd);
}
/**
@@ -73,25 +73,43 @@ public class EcrService implements ResourceProvider {
}
/**
* Recreates {@link Repository} metadata entries for any internal-namespaced
* repos found in the registry catalog that are missing from local storage.
* Internal names are of the form {@code <account>/<region>/<repoName>}.
* Recreates {@link Repository} metadata entries for registry namespaces found in the catalog.
* Namespaces created by Floci are {@code <account>/<region>/<repoName>}; pre-proxy registry
* namespaces are recovered for the default account and region without moving image storage.
*/
void reconcileFromCatalog(List<String> catalog) {
if (catalog == null || catalog.isEmpty()) {
return;
}
int recreated = 0;
for (String internal : catalog) {
String[] parts = internal.split("/", 3);
if (parts.length < 3) {
for (String registryRepositoryName : catalog) {
String defaultAccount = regionResolver.getAccountId();
String defaultRegion = regionResolver.getDefaultRegion();
String legacyKey = key(defaultRegion, defaultAccount, registryRepositoryName);
var legacyRepository = repoStore.get(legacyKey);
if (legacyRepository.isPresent()) {
Repository repo = legacyRepository.get();
repo.setRepositoryUri(registryManager.getRepositoryUri(
defaultAccount, defaultRegion, repo.getRepositoryName()));
repo.setRegistryRepositoryName(registryRepositoryName);
repoStore.put(legacyKey, repo);
continue;
}
String account = parts[0];
String region = parts[1];
String repoName = parts[2];
String[] parts = registryRepositoryName.split("/", 3);
boolean namespaced = parts.length == 3 && parts[0].matches("[0-9]{12}")
&& parts[1].matches("[a-z0-9-]+");
String account = namespaced ? parts[0] : defaultAccount;
String region = namespaced ? parts[1] : defaultRegion;
String repoName = namespaced ? parts[2] : registryRepositoryName;
String key = key(region, account, repoName);
if (repoStore.get(key).isPresent()) {
var existing = repoStore.get(key);
if (existing.isPresent()) {
Repository repo = existing.get();
repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repoName));
if (!namespaced) {
repo.setRegistryRepositoryName(registryRepositoryName);
}
repoStore.put(key, repo);
continue;
}
Repository repo = new Repository();
@@ -99,6 +117,9 @@ public class EcrService implements ResourceProvider {
repo.setRegistryId(account);
repo.setRepositoryArn(AwsArnUtils.Arn.of("ecr", region, account, "repository/" + repoName).toString());
repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repoName));
if (!namespaced) {
repo.setRegistryRepositoryName(registryRepositoryName);
}
repo.setCreatedAt(Instant.now());
repoStore.put(key, repo);
recreated++;
@@ -171,14 +192,16 @@ public class EcrService implements ResourceProvider {
String prefix = region + "::" + account + "::";
if (repositoryNames == null || repositoryNames.isEmpty()) {
return repoStore.scan(k -> k.startsWith(prefix));
return repoStore.scan(k -> k.startsWith(prefix)).stream()
.map(repo -> refreshRepositoryUri(repo, region))
.toList();
}
List<Repository> out = new ArrayList<>();
for (String name : repositoryNames) {
String key = key(region, account, name);
Repository repo = repoStore.get(key).orElseThrow(() -> notFound(name, account));
out.add(repo);
out.add(refreshRepositoryUri(repo, region));
}
return out;
}
@@ -195,7 +218,7 @@ public class EcrService implements ResourceProvider {
String key = key(region, account, repositoryName);
Repository repo = repoStore.get(key).orElseThrow(() -> notFound(repositoryName, account));
List<String> tags = listTagsBestEffort(account, region, repositoryName);
List<String> tags = listTagsBestEffort(repo, region);
if (!force && !tags.isEmpty()) {
throw new AwsException("RepositoryNotEmptyException",
"The repository with name '" + repositoryName
@@ -204,7 +227,7 @@ public class EcrService implements ResourceProvider {
}
if (force) {
deleteRepositoryStorage(account, region, repositoryName);
deleteRepositoryStorage(registryRepositoryName(repo, region));
}
repoStore.delete(key);
@@ -240,7 +263,7 @@ public class EcrService implements ResourceProvider {
public List<ImageIdentifier> listImages(String repositoryName, String registryId, String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String internal = registryManager.internalRepoName(repo.getRegistryId(), region, repositoryName);
String internal = registryRepositoryName(repo, region);
try {
RegistryHttpClient http = registryManager.httpClient();
List<String> tags = http.listTags(internal);
@@ -262,7 +285,7 @@ public class EcrService implements ResourceProvider {
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String internal = registryManager.internalRepoName(repo.getRegistryId(), region, repositoryName);
String internal = registryRepositoryName(repo, region);
RegistryHttpClient http = registryManager.httpClient();
List<String> refs = new ArrayList<>();
@@ -337,7 +360,7 @@ public class EcrService implements ResourceProvider {
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String internal = registryManager.internalRepoName(repo.getRegistryId(), region, repositoryName);
String internal = registryRepositoryName(repo, region);
RegistryHttpClient http = registryManager.httpClient();
List<Image> images = new ArrayList<>();
@@ -377,7 +400,7 @@ public class EcrService implements ResourceProvider {
String region) {
Repository repo = requireRepo(repositoryName, registryId, region);
requireRegistry();
String internal = registryManager.internalRepoName(repo.getRegistryId(), region, repositoryName);
String internal = registryRepositoryName(repo, region);
RegistryHttpClient http = registryManager.httpClient();
List<ImageIdentifier> deleted = new ArrayList<>();
@@ -424,6 +447,23 @@ public class EcrService implements ResourceProvider {
return repo;
}
/** Returns whether the repository rejects a second manifest write for an existing tag. */
public boolean isImageTagImmutable(String repositoryName, String registryId, String region) {
String account = effectiveAccount(registryId);
return repoStore.get(key(region, account, repositoryName))
.map(Repository::getImageTagMutability)
.filter("IMMUTABLE"::equals)
.isPresent();
}
/** Returns the physical registry namespace selected for an ECR repository. */
public String registryRepositoryName(String repositoryName, String registryId, String region) {
String account = effectiveAccount(registryId);
return repoStore.get(key(region, account, repositoryName))
.map(repo -> registryRepositoryName(repo, region))
.orElseGet(() -> registryManager.internalRepoName(account, region, repositoryName));
}
public void tagResource(String repoName, String registryId, Map<String, String> tags, String region) {
Repository repo = requireRepo(repoName, registryId, region);
if (tags != null) {
@@ -530,7 +570,8 @@ public class EcrService implements ResourceProvider {
private Repository requireRepo(String name, String registryId, String region) {
String account = effectiveAccount(registryId);
return repoStore.get(key(region, account, name)).orElseThrow(() -> notFound(name, account));
Repository repo = repoStore.get(key(region, account, name)).orElseThrow(() -> notFound(name, account));
return refreshRepositoryUri(repo, region);
}
private static String imageMetaKey(String region, String account, String repoName, String digest) {
@@ -552,21 +593,35 @@ public class EcrService implements ResourceProvider {
}
}
private List<String> listTagsBestEffort(String account, String region, String repoName) {
private Repository refreshRepositoryUri(Repository repo, String region) {
repo.setRepositoryUri(registryManager.getRepositoryUri(repo.getRegistryId(), region, repo.getRepositoryName()));
repoStore.put(key(region, repo.getRegistryId(), repo.getRepositoryName()), repo);
return repo;
}
private String registryRepositoryName(Repository repo, String region) {
String registryRepositoryName = repo.getRegistryRepositoryName();
if (registryRepositoryName != null && !registryRepositoryName.isBlank()) {
return registryRepositoryName;
}
return registryManager.internalRepoName(repo.getRegistryId(), region, repo.getRepositoryName());
}
private List<String> listTagsBestEffort(Repository repo, String region) {
try {
return registryManager.httpClient()
.listTags(registryManager.internalRepoName(account, region, repoName));
return registryManager.httpClient().listTags(registryRepositoryName(repo, region));
} catch (Exception e) {
LOG.debugv("Could not list tags for {0} (registry not available): {1}", repoName, e.getMessage());
LOG.debugv("Could not list tags for {0} (registry not available): {1}",
repo.getRepositoryName(), e.getMessage());
return List.of();
}
}
private void deleteRepositoryStorage(String account, String region, String repositoryName) {
private void deleteRepositoryStorage(String registryRepositoryName) {
try {
registryManager.deleteRepositoryStorage(account, region, repositoryName);
registryManager.deleteRepositoryStorage(registryRepositoryName);
} catch (Exception e) {
throw registryFailure(repositoryName, e);
throw registryFailure(registryRepositoryName, e);
}
}
@@ -17,6 +17,7 @@ public class Repository {
private String registryId;
private String repositoryName;
private String repositoryUri;
private String registryRepositoryName;
private Instant createdAt;
private String imageTagMutability = "MUTABLE";
private boolean scanOnPush;
@@ -40,6 +41,11 @@ public class Repository {
public String getRepositoryUri() { return repositoryUri; }
public void setRepositoryUri(String repositoryUri) { this.repositoryUri = repositoryUri; }
public String getRegistryRepositoryName() { return registryRepositoryName; }
public void setRegistryRepositoryName(String registryRepositoryName) {
this.registryRepositoryName = registryRepositoryName;
}
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
@@ -0,0 +1,333 @@
package io.github.hectorvent.floci.services.ecr.registry;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ecr.EcrService;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Proxies OCI Distribution traffic through Floci so ECR repository policy applies to Docker pushes.
* Docker clients use the AWS-shaped repository URI while {@code registry:2} retains image storage.
*/
@ApplicationScoped
public class EcrRegistryDataPlane {
private static final Pattern ECR_HOST = Pattern.compile(
"^([0-9]{12})\\.dkr\\.ecr\\.([a-z0-9-]+)\\.localhost(?::[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",
"te", "trailers", "transfer-encoding", "upgrade");
private final EcrRegistryManager registryManager;
private final EcrService ecrService;
private final EmulatorConfig config;
private final Vertx vertx;
private final HttpClient proxyClient;
private final Set<String> inFlightImmutableTags = ConcurrentHashMap.newKeySet();
@Inject
public EcrRegistryDataPlane(EcrRegistryManager registryManager,
EcrService ecrService,
EmulatorConfig config,
Vertx vertx) {
this.registryManager = registryManager;
this.ecrService = ecrService;
this.config = config;
this.vertx = vertx;
this.proxyClient = vertx.createHttpClient(new HttpClientOptions()
.setConnectTimeout(5_000)
.setKeepAlive(true));
}
void register(@Observes Router router) {
router.route("/v2").handler(this::handle);
router.route("/v2/*").handler(this::handle);
}
private void handle(RoutingContext context) {
Optional<RegistryRequest> request = requestFor(
context.request().host(), context.request().path(), context.request().query(),
config.services().ecr().uriStyle());
if (request.isEmpty() || !config.services().ecr().enabled()) {
context.next();
return;
}
context.request().pause();
RegistryRequest registryRequest = request.get();
if (!registryRequest.repositoryName().isEmpty()) {
registryRequest = registryRequest.withStorageRepositoryName(
ecrService.registryRepositoryName(
registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region()));
}
String immutableTag = immutableTag(context, registryRequest);
if (immutableTag != null && !inFlightImmutableTags.add(immutableTag)) {
context.request().resume();
imageTagAlreadyExists(context, registryRequest);
return;
}
checkTagAndProxy(context, registryRequest, immutableTag);
}
private String immutableTag(RoutingContext context, RegistryRequest request) {
if (request.tag() == null || !"PUT".equals(context.request().method().name())
|| !ecrService.isImageTagImmutable(request.repositoryName(), request.accountId(), request.region())) {
return null;
}
return request.accountId() + "/" + request.region() + "/" + request.repositoryName() + ":" + request.tag();
}
private void checkTagAndProxy(RoutingContext context, RegistryRequest request, String immutableTag) {
vertx.<Boolean>executeBlocking(promise -> {
try {
registryManager.ensureStarted();
if (immutableTag == null) {
promise.complete(false);
return;
}
String existing = registryManager.httpClient().headManifestDigest(
request.storageRepositoryName(),
request.tag(), null);
promise.complete(existing != null);
} catch (Exception e) {
promise.fail(e);
}
}).onComplete(result -> {
if (result.failed()) {
context.request().resume();
release(immutableTag);
context.response().setStatusCode(503).end();
} else if (result.result()) {
context.request().resume();
release(immutableTag);
imageTagAlreadyExists(context, request);
} else {
proxy(context, request, immutableTag);
}
});
}
private void proxy(RoutingContext context, RegistryRequest request, String immutableTag) {
URI backend = URI.create(registryManager.httpClient().baseUrl());
RequestOptions options = new RequestOptions()
.setHost(backend.getHost())
.setPort(backend.getPort() == -1 ? 80 : backend.getPort())
.setURI(request.backendUri())
.setMethod(context.request().method());
proxyClient.request(options).onComplete(upstreamRequest -> {
if (upstreamRequest.failed()) {
context.request().resume();
release(immutableTag);
context.response().setStatusCode(503).end();
return;
}
HttpClientRequest clientReq = upstreamRequest.result();
copyRequestHeaders(context, clientReq);
clientReq.response().onComplete(upstreamResponse -> {
if (upstreamResponse.failed()) {
release(immutableTag);
if (!context.response().ended()) {
context.response().setStatusCode(502).end();
}
return;
}
copyResponseHeaders(context, upstreamResponse.result(), request);
upstreamResponse.result().pipeTo(context.response()).onComplete(ignored -> release(immutableTag));
});
clientReq.send(context.request()).onFailure(ignored -> {
release(immutableTag);
if (!context.response().ended()) {
context.response().setStatusCode(502).end();
}
});
context.request().resume();
});
}
private static void copyRequestHeaders(RoutingContext context, HttpClientRequest upstream) {
context.request().headers().forEach(header -> {
if (!HOP_BY_HOP_HEADERS.contains(header.getKey().toLowerCase())
&& !"host".equalsIgnoreCase(header.getKey())) {
upstream.putHeader(header.getKey(), header.getValue());
}
});
if (context.request().getHeader("Content-Length") == null
&& ("chunked".equalsIgnoreCase(context.request().getHeader("Transfer-Encoding"))
|| context.request().method() == HttpMethod.POST
|| context.request().method() == HttpMethod.PUT
|| context.request().method() == HttpMethod.PATCH)) {
upstream.setChunked(true);
}
}
private static void copyResponseHeaders(RoutingContext context,
io.vertx.core.http.HttpClientResponse upstream,
RegistryRequest request) {
context.response().setStatusCode(upstream.statusCode());
upstream.headers().forEach(header -> {
if (!HOP_BY_HOP_HEADERS.contains(header.getKey().toLowerCase())) {
String value = "location".equalsIgnoreCase(header.getKey())
? externalLocation(header.getValue(), request)
: header.getValue();
context.response().putHeader(header.getKey(), value);
}
});
}
static String externalLocation(String location, RegistryRequest request) {
String prefix = "/v2/" + request.storageRepositoryName();
return location.replace(prefix, "/v2/" + request.clientRepositoryName());
}
private static void imageTagAlreadyExists(RoutingContext context, RegistryRequest request) {
String tag = request.tag() != null ? request.tag() : "";
String repository = request.repositoryName() != null ? request.repositoryName() : "";
String message = String.format(
"The image tag %s already exists in the %s repository and cannot be overwritten because the tag is immutable.",
tag, repository);
String body = new JsonObject()
.put("errors", new JsonArray().add(new JsonObject()
.put("code", "TAG_INVALID")
.put("message", message)))
.encode();
context.response().setStatusCode(400)
.putHeader("Content-Type", "application/json")
.end(body);
}
private void release(String immutableTag) {
if (immutableTag != null) {
inFlightImmutableTags.remove(immutableTag);
}
}
static Optional<RegistryRequest> requestFor(String host, String path, String query, String uriStyle) {
String registryPath = "/v2".equals(path) ? "/v2/" : path;
if (!registryPath.startsWith("/v2/")) {
return Optional.empty();
}
Matcher hostMatch = ECR_HOST.matcher(host == null ? "" : host);
if (!hostMatch.matches()) {
hostMatch = ECR_HOST.matcher(queryParameter(query, "ns"));
}
if (hostMatch.matches()) {
String repository = "/v2/".equals(registryPath) ? "" : repositoryName(registryPath.substring("/v2/".length()));
String storageRepositoryName = hostMatch.group(1) + "/" + hostMatch.group(2) + "/" + repository;
String backendUri = repository.isEmpty()
? registryPath + querySuffix(query, true)
: "/v2/" + storageRepositoryName
+ registryPath.substring("/v2/".length() + repository.length())
+ querySuffix(query, true);
return Optional.of(new RegistryRequest(hostMatch.group(1), hostMatch.group(2), repository,
storageRepositoryName, repository, backendUri,
tag(path)));
}
if (!"path".equalsIgnoreCase(uriStyle)) {
return Optional.empty();
}
if ("/v2/".equals(registryPath)) {
return Optional.of(new RegistryRequest("", "", "", "", "", registryPath + querySuffix(query, true), null));
}
String[] segments = registryPath.substring("/v2/".length()).split("/", 3);
if (segments.length < 3 || !segments[0].matches("[0-9]{12}")
|| !segments[1].matches("[a-z0-9-]+")) {
return Optional.empty();
}
String repository = repositoryName(segments[2]);
String storageRepositoryName = segments[0] + "/" + segments[1] + "/" + repository;
return Optional.of(new RegistryRequest(segments[0], segments[1], repository,
storageRepositoryName, storageRepositoryName,
registryPath + querySuffix(query, true), tag(registryPath)));
}
private static String querySuffix(String query, boolean removeNamespace) {
if (query == null || query.isEmpty()) {
return "";
}
StringBuilder forwarded = new StringBuilder();
for (String parameter : query.split("&")) {
if (removeNamespace && parameter.startsWith("ns=")) {
continue;
}
if (!forwarded.isEmpty()) {
forwarded.append('&');
}
forwarded.append(parameter);
}
return forwarded.isEmpty() ? "" : "?" + forwarded;
}
private static String queryParameter(String query, String name) {
if (query == null || query.isEmpty()) {
return "";
}
for (String parameter : query.split("&")) {
int separator = parameter.indexOf('=');
if (separator > 0 && name.equals(parameter.substring(0, separator))) {
return URLDecoder.decode(parameter.substring(separator + 1), StandardCharsets.UTF_8);
}
}
return "";
}
private static String repositoryName(String path) {
int manifests = path.indexOf(MANIFESTS_PATH);
if (manifests >= 0) {
return path.substring(0, manifests);
}
int blobs = path.indexOf("/blobs/");
if (blobs >= 0) {
return path.substring(0, blobs);
}
int tags = path.indexOf("/tags/");
return tags >= 0 ? path.substring(0, tags) : path;
}
private static String tag(String path) {
int manifests = path.indexOf(MANIFESTS_PATH);
if (manifests < 0) {
return null;
}
String reference = path.substring(manifests + MANIFESTS_PATH.length());
return reference.isEmpty() || reference.contains("/") || reference.contains(":") ? null : reference;
}
record RegistryRequest(String accountId,
String region,
String repositoryName,
String storageRepositoryName,
String clientRepositoryName,
String backendUri,
String tag) {
RegistryRequest withStorageRepositoryName(String storageRepositoryName) {
return new RegistryRequest(accountId, region, repositoryName, storageRepositoryName,
clientRepositoryName,
backendUri.replace("/v2/" + this.storageRepositoryName, "/v2/" + storageRepositoryName), tag);
}
}
}
@@ -18,6 +18,7 @@ import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.InspectExecResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerPort;
import com.github.dockerjava.api.model.Frame;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -142,7 +143,7 @@ public class EcrRegistryManager {
/** Returns the docker-pullable repository URI for the given account/region/name. */
public String getRepositoryUri(String accountId, String region, String repoName) {
int port = effectivePort();
int port = config.port();
String style = config.services().ecr().uriStyle();
if ("path".equalsIgnoreCase(style)) {
return "localhost:" + port + "/" + accountId + "/" + region + "/" + repoName;
@@ -153,7 +154,8 @@ public class EcrRegistryManager {
/** Returns the proxy endpoint a docker daemon should log into for any ECR repo. */
public String getProxyEndpoint() {
String scheme = config.services().ecr().tlsEnabled() ? "https" : "http";
return scheme + "://localhost:" + effectivePort();
return scheme + "://" + regionResolver.getAccountId() + ".dkr.ecr."
+ regionResolver.getDefaultRegion() + ".localhost:" + config.port();
}
/** Returns the effective registry port. Stable across calls once {@link #ensureStarted} runs. */
@@ -244,9 +246,13 @@ public class EcrRegistryManager {
// Check for existing container to adopt
var existing = lifecycleManager.findByName(name);
if (existing.isPresent()) {
adoptExisting(existing.get());
runReconcileOnce();
return;
if (hasLoopbackBinding(existing.get())) {
adoptExisting(existing.get());
runReconcileOnce();
return;
}
LOG.infov("Recreating ECR backing registry {0} with a loopback-only port binding", name);
lifecycleManager.stopAndRemove(existing.get().getId(), null);
}
// Allocate port
@@ -260,14 +266,15 @@ public class EcrRegistryManager {
// Build environment variables
List<String> env = new ArrayList<>(List.of(
"REGISTRY_STORAGE_DELETE_ENABLED=true",
"REGISTRY_HTTP_ADDR=0.0.0.0:" + CONTAINER_INTERNAL_PORT
"REGISTRY_HTTP_ADDR=0.0.0.0:" + CONTAINER_INTERNAL_PORT,
"REGISTRY_HTTP_RELATIVEURLS=true"
));
// Build container spec
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(name)
.withEnv(env)
.withPortBinding(CONTAINER_INTERNAL_PORT, chosenPort)
.withLoopbackPortBinding(CONTAINER_INTERNAL_PORT, chosenPort)
.withDockerNetwork(resolveRegistryDockerNetwork())
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
@@ -448,11 +455,15 @@ public class EcrRegistryManager {
/** Removes repository manifest storage without removing descendant repository directories. */
public synchronized void deleteRepositoryStorage(String accountId, String region, String repositoryName) {
deleteRepositoryStorage(internalRepoName(accountId, region, repositoryName));
}
/** Removes storage for a registry namespace selected by the ECR control plane. */
public synchronized void deleteRepositoryStorage(String repository) {
ensureStarted();
if (!started || containerId == null) {
throw new IllegalStateException("ECR registry is not started");
}
String repository = internalRepoName(accountId, region, repositoryName);
String path = repositoryStoragePath(repository);
StringBuilder output = new StringBuilder();
DockerClient dockerClient = lifecycleManager.getDockerClient();
@@ -546,9 +557,8 @@ public class EcrRegistryManager {
this.containerId = existing.getId();
try {
ContainerInfo info = lifecycleManager.adopt(containerId, List.of(CONTAINER_INTERNAL_PORT));
// getRepositoryUri/getProxyEndpoint are consumed by the host-side docker
// daemon, so hostPort must be the published binding — adopt's endpoint
// resolves to the container-internal port when Floci runs inside Docker.
// The control plane reaches the backing registry through this published loopback
// binding when Floci runs on the host. In Docker, httpClient() uses container DNS.
var published = info.publishedHostPort(CONTAINER_INTERNAL_PORT);
if (published.isPresent()) {
this.hostPort = published.getAsInt();
@@ -568,6 +578,23 @@ public class EcrRegistryManager {
}
}
private static boolean hasLoopbackBinding(Container container) {
ContainerPort[] ports = container.getPorts();
if (ports == null) {
return false;
}
boolean found = false;
for (ContainerPort port : ports) {
if (port.getPrivatePort() != null && port.getPrivatePort() == CONTAINER_INTERNAL_PORT) {
if (port.getPublicPort() == null || !"127.0.0.1".equals(port.getIp())) {
return false;
}
found = true;
}
}
return found;
}
private void ensureDataDir() {
try {
Path dir = Paths.get(config.services().ecr().dataPath(), "registry");
@@ -175,6 +175,10 @@ public class EksClusterManager {
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"eks", cluster.getName(), labelAccountId, regionResolver.getDefaultRegion()));
if (config.services().eks().ecrRegistryMirror() && config.services().ecr().enabled()) {
specBuilder.withHostDockerInternalOnLinux();
}
// Wire a token-authentication webhook so `aws eks get-token` bearer tokens are validated by
// Floci and mapped to cluster-admin. The k3s API server POSTs a TokenReview to Floci's
// _floci/eks/clusters/<cluster-name>/token-webhook endpoint. The kubeconfig is copied into
@@ -566,9 +570,9 @@ 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 — default account across
* the full region catalog, plus the path-style {@code localhost:<port>} form — to the registry
* container's in-network endpoint. Public registries are never matched. A failure disables the
* 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
* 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.
*/
void injectEcrRegistryMirror(String containerId, String clusterName) {
@@ -586,8 +590,8 @@ public class EksClusterManager {
if (!regions.contains(config.defaultRegion())) {
regions.add(config.defaultRegion());
}
String content = buildRegistriesYaml(config.defaultAccountId(), regions,
ecrRegistryManager.effectivePort(), ecrRegistryManager.internalEndpoint());
String endpoint = "http://" + dockerHostResolver.resolve() + ":" + config.port();
String content = buildRegistriesYaml(config.defaultAccountId(), regions, config.port(), endpoint);
writeRegistriesYaml(clusterName, content);
try {
lifecycleManager.getDockerClient()
@@ -595,8 +599,7 @@ public class EksClusterManager {
.withTarInputStream(new ByteArrayInputStream(tarSingleFile(REGISTRIES_TAR_ENTRY, content)))
.withRemotePath("/etc")
.exec();
LOG.infov("Injected ECR registry mirror ({0}) into k3s cluster {1}",
ecrRegistryManager.internalEndpoint(), clusterName);
LOG.infov("Injected ECR registry mirror ({0}) into k3s cluster {1}", endpoint, clusterName);
} catch (Exception e) {
LOG.warnv("EKS cluster {0} gets no ECR registry mirror: could not copy registries.yaml "
+ "into the k3s container: {1}", clusterName, e.getMessage());
@@ -637,16 +640,16 @@ 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 the registry's in-network endpoint. k3s supports
* ({@code localhost:<port>}), all pointing at Floci's in-network data plane. 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 hostPort, String endpoint) {
static String buildRegistriesYaml(String accountId, List<String> regions, int dataPlanePort, String endpoint) {
StringBuilder yaml = new StringBuilder("mirrors:\n");
for (String region : regions) {
appendMirror(yaml, accountId + ".dkr.ecr." + region + ".localhost:" + hostPort, endpoint);
appendMirror(yaml, accountId + ".dkr.ecr." + region + ".localhost:" + dataPlanePort, endpoint);
}
appendMirror(yaml, "localhost:" + hostPort, endpoint);
appendMirror(yaml, "localhost:" + dataPlanePort, endpoint);
return yaml.toString();
}
@@ -196,7 +196,7 @@ class ContainerLifecycleManagerLabelsTest {
private static ContainerSpec specWithLabels(Map<String, String> labels) {
return new ContainerSpec(
"busybox:stable", null, List.of(), null, null, null, Map.of(), List.of(), null,
"busybox:stable", null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null,
List.of(), List.of(), List.of(), labels, null, false, null, List.of(), null,
null, List.of());
}
@@ -8186,7 +8186,7 @@ class CloudFormationIntegrationTest {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Image",
"ImageUri": "000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:latest"
"ImageUri": "000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:latest"
}
}
}
@@ -8223,7 +8223,7 @@ class CloudFormationIntegrationTest {
.then()
.statusCode(200)
.body("Configuration.PackageType", equalTo("Image"))
.body("Code.ImageUri", equalTo("000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:latest"));
.body("Code.ImageUri", equalTo("000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:latest"));
}
@Test
@@ -8240,7 +8240,7 @@ class CloudFormationIntegrationTest {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Image",
"ImageUri": "000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:latest",
"ImageUri": "000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:latest",
"ImageConfig": {
"EntryPoint": ["/bootstrap"],
"Command": ["handler.main"],
@@ -262,7 +262,7 @@ class SamTransformProcessorTest {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Image",
"ImageUri": "000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:latest"
"ImageUri": "000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:latest"
}
}
}
@@ -273,7 +273,7 @@ class SamTransformProcessorTest {
JsonNode lambdaProps = expanded.path("Resources").path("MyFunc").path("Properties");
assertEquals("Image", lambdaProps.path("PackageType").asText());
assertEquals("000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:latest",
assertEquals("000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:latest",
lambdaProps.path("Code").path("ImageUri").asText());
// No Handler/Runtime were declared and none should be synthesized by the transform itself —
// CloudFormationResourceProvisioner is responsible for not defaulting them once it sees
@@ -337,7 +337,7 @@ class SamTransformProcessorTest {
"Type": "AWS::Serverless::Function",
"Properties": {
"PackageType": "Image",
"ImageUri": "000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:latest",
"ImageUri": "000000000000.dkr.ecr.us-east-1.localhost:4566/my-repo:latest",
"ImageConfig": {
"EntryPoint": ["/bootstrap"],
"Command": ["handler.main"],
@@ -51,8 +51,8 @@ class EcrServiceTest {
registryManager = Mockito.mock(EcrRegistryManager.class);
when(registryManager.getRepositoryUri(anyString(), anyString(), anyString()))
.thenAnswer(inv -> inv.getArgument(0) + ".dkr.ecr." + inv.getArgument(1)
+ ".localhost:5000/" + inv.getArgument(2));
when(registryManager.getProxyEndpoint()).thenReturn("http://localhost:5000");
+ ".localhost:4566/" + inv.getArgument(2));
when(registryManager.getProxyEndpoint()).thenReturn("http://localhost:4566");
when(registryManager.internalRepoName(anyString(), anyString(), anyString()))
.thenAnswer(inv -> inv.getArgument(0) + "/" + inv.getArgument(1) + "/" + inv.getArgument(2));
// The mock never talks to Docker; report the backing registry as available so the
@@ -117,6 +117,44 @@ class EcrServiceTest {
assertEquals("platform", repo.getTags().get("team"));
}
@Test
void immutableRepositoryIsMarkedForDataPlaneTagProtection() {
service.createRepository(REPO, null, "IMMUTABLE", null, null, null, null, REGION);
assertTrue(service.isImageTagImmutable(REPO, ACCOUNT, REGION));
}
@Test
void mutableRepositoryIsNotMarkedForDataPlaneTagProtection() {
service.createRepository(REPO, null, "MUTABLE", null, null, null, null, REGION);
assertFalse(service.isImageTagImmutable(REPO, ACCOUNT, REGION));
}
@Test
void reconcilePreProxyRegistryNamespacePreservesItsStoragePath() {
String repositoryName = "legacy/service";
service.reconcileFromCatalog(List.of(repositoryName));
Repository repository = service.describeRepositories(List.of(repositoryName), null, REGION).getFirst();
assertEquals(repositoryName, repository.getRepositoryName());
assertEquals(repositoryName, service.registryRepositoryName(repositoryName, ACCOUNT, REGION));
}
@Test
void reconcilePreProxyRepositoryWithNamespaceShapedNamePreservesItsIdentity() {
String repositoryName = ACCOUNT + "/" + REGION + "/legacy";
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
service.reconcileFromCatalog(List.of(repositoryName));
assertEquals(repositoryName,
service.describeRepositories(List.of(repositoryName), null, REGION).getFirst().getRepositoryName());
assertEquals(repositoryName, service.registryRepositoryName(repositoryName, ACCOUNT, REGION));
assertThrows(AwsException.class, () -> service.describeRepositories(List.of("legacy"), null, REGION));
}
// ------------------------------------------------------------
// Registry unavailable (Floci inside Docker with no Docker daemon)
// ------------------------------------------------------------
@@ -231,7 +269,7 @@ class EcrServiceTest {
service.deleteRepository(REPO, null, true, REGION);
verify(registryManager).deleteRepositoryStorage(ACCOUNT, REGION, REPO);
verify(registryManager).deleteRepositoryStorage(ACCOUNT + "/" + REGION + "/" + REPO);
verify(registryManager).pruneStorage();
}
@@ -248,7 +286,7 @@ class EcrServiceTest {
@Test
void deleteRepository_forceRetainsMetadataWhenRegistryCleanupFails() {
Mockito.doThrow(new IllegalStateException("registry unavailable"))
.when(registryManager).deleteRepositoryStorage(ACCOUNT, REGION, REPO);
.when(registryManager).deleteRepositoryStorage(ACCOUNT + "/" + REGION + "/" + REPO);
service.createRepository(REPO, null, null, null, null, null, null, REGION);
AwsException ex = assertThrows(AwsException.class,
@@ -439,11 +477,12 @@ class EcrServiceTest {
service.reconcileFromCatalog(List.of(
ACCOUNT + "/" + REGION + "/recovered/one",
ACCOUNT + "/" + REGION + "/recovered/two",
"malformed-no-slashes"));
"legacy/repository"));
List<Repository> repos = service.describeRepositories(null, null, REGION);
assertEquals(2, repos.size());
assertEquals(3, repos.size());
assertTrue(repos.stream().anyMatch(r -> "recovered/one".equals(r.getRepositoryName())));
assertTrue(repos.stream().anyMatch(r -> "recovered/two".equals(r.getRepositoryName())));
assertTrue(repos.stream().anyMatch(r -> "legacy/repository".equals(r.getRepositoryName())));
}
@Test
@@ -0,0 +1,209 @@
package io.github.hectorvent.floci.services.ecr.registry;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ecr.EcrService;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
/** Unit tests for routing AWS-shaped ECR repository URIs through Floci's data plane. */
class EcrRegistryDataPlaneTest {
private Vertx vertx;
@BeforeEach
void setUp() {
vertx = Vertx.vertx();
}
@AfterEach
void tearDown() throws Exception {
vertx.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
@Test
void hostnameStyleManifestWriteUsesInternalRegistryNamespace() {
var request = EcrRegistryDataPlane.requestFor(
"000000000000.dkr.ecr.us-east-1.localhost:4566",
"/v2/platform/api/manifests/v1", null, "hostname").orElseThrow();
assertEquals("000000000000", request.accountId());
assertEquals("us-east-1", request.region());
assertEquals("platform/api", request.repositoryName());
assertEquals("000000000000/us-east-1/platform/api", request.storageRepositoryName());
assertEquals("v1", request.tag());
assertEquals("/v2/000000000000/us-east-1/platform/api/manifests/v1", request.backendUri());
}
@Test
void digestManifestWriteDoesNotAcquireAnImmutableTagLock() {
var request = EcrRegistryDataPlane.requestFor(
"000000000000.dkr.ecr.us-east-1.localhost:4566",
"/v2/platform/api/manifests/sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
null, "hostname").orElseThrow();
assertNull(request.tag());
}
@Test
void pathStyleRequestRetainsItsExistingInternalNamespace() {
var request = EcrRegistryDataPlane.requestFor("localhost:4566",
"/v2/000000000000/us-east-1/platform/api/blobs/uploads/", "mount=sha256:abc", "path").orElseThrow();
assertEquals("platform/api", request.repositoryName());
assertEquals("/v2/000000000000/us-east-1/platform/api/blobs/uploads/?mount=sha256:abc",
request.backendUri());
}
@Test
void mirrorNamespaceRoutesAnInNetworkK3sPullThroughTheSameDataPlane() {
var request = EcrRegistryDataPlane.requestFor("floci:4566", "/v2/platform/api/manifests/v1",
"ns=000000000000.dkr.ecr.us-east-1.localhost%3A4566", "hostname").orElseThrow();
assertEquals("000000000000", request.accountId());
assertEquals("us-east-1", request.region());
assertEquals("platform/api", request.repositoryName());
assertEquals("/v2/000000000000/us-east-1/platform/api/manifests/v1", request.backendUri());
}
@Test
void unrelatedV2RouteDoesNotClaimTheRequest() {
assertFalse(EcrRegistryDataPlane.requestFor("localhost:4566", "/v2/apis", null, "hostname").isPresent());
assertTrue(EcrRegistryDataPlane.requestFor("000000000000.dkr.ecr.us-east-1.localhost:4566", "/v2/", null,
"hostname").isPresent());
}
@Test
void registryPingDoesNotAcquireARepositoryNamespace() {
var hostnameRequest = EcrRegistryDataPlane.requestFor(
"000000000000.dkr.ecr.us-east-1.localhost:4566", "/v2/", null, "hostname").orElseThrow();
var pathRequest = EcrRegistryDataPlane.requestFor("localhost:4566", "/v2/", null, "path").orElseThrow();
assertEquals("/v2/", hostnameRequest.backendUri());
assertEquals("/v2/", pathRequest.backendUri());
}
@Test
void uploadContinuationRetainsTheClientRepositoryNamespace() {
var request = EcrRegistryDataPlane.requestFor(
"000000000000.dkr.ecr.us-east-1.localhost:4566",
"/v2/platform/api/blobs/uploads/", null, "hostname").orElseThrow();
assertEquals("/v2/platform/api/blobs/uploads/upload-id",
EcrRegistryDataPlane.externalLocation(
"/v2/000000000000/us-east-1/platform/api/blobs/uploads/upload-id", request));
}
@Test
void immutableTagRejectsReplacementBeforeItReachesTheRegistry() throws Exception {
AtomicBoolean tagExists = new AtomicBoolean();
AtomicInteger manifestWrites = new AtomicInteger();
AtomicReference<String> headPath = new AtomicReference<>();
AtomicReference<String> manifestBody = new AtomicReference<>();
AtomicReference<String> manifestPath = new AtomicReference<>();
HttpServer registry = vertx.createHttpServer()
.requestHandler(request -> {
if (request.method() == HttpMethod.HEAD) {
headPath.set(request.path());
request.response().setStatusCode(tagExists.get() ? 200 : 404)
.putHeader("Docker-Content-Digest", "sha256:existing")
.end();
} else if (request.method() == HttpMethod.PUT) {
request.bodyHandler(body -> {
manifestPath.set(request.path());
manifestBody.set(body.toString());
manifestWrites.incrementAndGet();
tagExists.set(true);
request.response().setStatusCode(201).end();
});
} else {
request.response().setStatusCode(405).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);
assertEquals(201, putManifest(dataPlane.actualPort()).statusCode());
var rejected = putManifest(dataPlane.actualPort());
assertEquals(400, rejected.statusCode());
String responseBody = rejected.body()
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS).toString();
JsonObject json = new JsonObject(responseBody);
JsonArray errors = json.getJsonArray("errors");
assertNotNull(errors);
assertEquals(1, errors.size());
JsonObject error = errors.getJsonObject(0);
assertEquals("TAG_INVALID", error.getString("code"));
assertEquals("The image tag v1 already exists in the platform/api repository and cannot be overwritten because the tag is immutable.",
error.getString("message"));
assertEquals(1, manifestWrites.get());
assertEquals("/v2/legacy/platform-api/manifests/v1", headPath.get());
assertEquals("/v2/legacy/platform-api/manifests/v1", manifestPath.get());
assertEquals("{}", manifestBody.get());
} finally {
if (dataPlane != null) {
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
registry.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
}
private io.vertx.core.http.HttpClientResponse putManifest(int port) throws Exception {
HttpClient client = vertx.createHttpClient();
return client.request(new RequestOptions()
.setHost("127.0.0.1")
.setPort(port)
.setMethod(HttpMethod.PUT)
.setURI("/v2/platform/api/manifests/v1"))
.compose(request -> {
request.putHeader("Host", "000000000000.dkr.ecr.us-east-1.localhost:4566");
request.setChunked(true);
return request.send(Buffer.buffer("{}"));
})
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
}
@@ -22,6 +22,7 @@ import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
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;
@@ -38,7 +39,9 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -99,6 +102,7 @@ class EcrRegistryManagerTest {
storage = Mockito.mock(EmulatorConfig.StorageConfig.class);
when(config.services()).thenReturn(Mockito.mock(EmulatorConfig.ServicesConfig.class));
when(config.services().ecr()).thenReturn(ecr);
when(config.port()).thenReturn(4566);
when(config.docker()).thenReturn(docker);
when(config.storage()).thenReturn(storage);
when(docker.resourceNamespace()).thenReturn(Optional.empty());
@@ -130,6 +134,16 @@ class EcrRegistryManagerTest {
"io.floci.region", "us-east-1"));
}
@Test
void ensureStartedBindsTheBackingRegistryToLoopbackOnly() {
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
manager.ensureStarted();
verify(builder).withLoopbackPortBinding(eq(5000), anyInt());
}
@Test
void ensureStarted_releasesPortWhenDockerStartFails_soPoolIsNotExhausted() {
when(lifecycleManager.createAndStart(any()))
@@ -186,7 +200,7 @@ class EcrRegistryManagerTest {
assertTrue(manager.tryEnsureStarted());
verify(lifecycleManager, Mockito.times(2)).createAndStart(any());
verify(builder, Mockito.times(2)).withPortBinding(5000, BASE_PORT);
verify(builder, Mockito.times(2)).withLoopbackPortBinding(5000, BASE_PORT);
verify(firstLogStream).close();
}
@@ -198,6 +212,9 @@ class EcrRegistryManagerTest {
Container existing = Mockito.mock(Container.class);
when(existing.getId()).thenReturn("container-id");
when(existing.getPorts()).thenReturn(new ContainerPort[] {
new ContainerPort().withIp("127.0.0.1").withPrivatePort(5000).withPublicPort(BASE_PORT)
});
when(lifecycleManager.presenceOf("container-id")).thenReturn(ContainerPresence.STOPPED);
when(lifecycleManager.findByName(REGISTRY_NAME)).thenReturn(Optional.of(existing));
when(lifecycleManager.adopt("container-id", List.of(5000)))
@@ -232,13 +249,15 @@ class EcrRegistryManagerTest {
}
@Test
void adoptUsesPublishedHostPortEvenWhenRunningInsideDocker() {
// Regression: in container mode adopt()'s endpoint resolves to the registry's
// internal port (5000); the advertised proxy endpoint must use the published
// host binding instead, or docker login from the host daemon fails.
void adoptTracksPrivateBackingPortWhenRunningInsideDocker() {
// In container mode httpClient() uses the registry's in-network port. The adopted
// published binding remains the host-mode fallback for control-plane image operations.
when(containerDetector.isRunningInContainer()).thenReturn(true);
Container existing = Mockito.mock(Container.class);
when(existing.getId()).thenReturn("0123456789abcdef");
when(existing.getPorts()).thenReturn(new ContainerPort[] {
new ContainerPort().withIp("127.0.0.1").withPrivatePort(5000).withPublicPort(BASE_PORT + 1)
});
when(lifecycleManager.findByName(REGISTRY_NAME)).thenReturn(Optional.of(existing));
when(lifecycleManager.adopt("0123456789abcdef", List.of(5000)))
.thenReturn(new ContainerLifecycleManager.ContainerInfo("0123456789abcdef",
@@ -248,13 +267,16 @@ class EcrRegistryManagerTest {
manager.ensureStarted();
assertEquals(BASE_PORT + 1, manager.effectivePort());
assertEquals("http://localhost:" + (BASE_PORT + 1), manager.getProxyEndpoint());
assertEquals("http://000000000000.dkr.ecr.us-east-1.localhost:4566", manager.getProxyEndpoint());
}
@Test
void adoptKeepsConfiguredPortWhenNoPublishedBindingExists() {
Container existing = Mockito.mock(Container.class);
when(existing.getId()).thenReturn("0123456789abcdef");
when(existing.getPorts()).thenReturn(new ContainerPort[] {
new ContainerPort().withIp("127.0.0.1").withPrivatePort(5000).withPublicPort(BASE_PORT)
});
when(lifecycleManager.findByName(REGISTRY_NAME)).thenReturn(Optional.of(existing));
when(lifecycleManager.adopt("0123456789abcdef", List.of(5000)))
.thenReturn(new ContainerLifecycleManager.ContainerInfo("0123456789abcdef", Map.of()));
@@ -264,6 +286,23 @@ class EcrRegistryManagerTest {
assertEquals(BASE_PORT, manager.effectivePort());
}
@Test
void legacyPublicBackingRegistryIsRecreatedWithLoopbackBinding() {
Container existing = Mockito.mock(Container.class);
when(existing.getId()).thenReturn("0123456789abcdef");
when(existing.getPorts()).thenReturn(new ContainerPort[] {
new ContainerPort().withIp("0.0.0.0").withPrivatePort(5000).withPublicPort(BASE_PORT)
});
when(lifecycleManager.findByName(REGISTRY_NAME)).thenReturn(Optional.of(existing));
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
manager.ensureStarted();
verify(lifecycleManager).stopAndRemove("0123456789abcdef", null);
verify(builder).withLoopbackPortBinding(eq(5000), anyInt());
}
@Test
void httpClient_usesNamespacedRegistryContainerDnsWhenConfigured() {
when(containerDetector.isRunningInContainer()).thenReturn(true);
@@ -279,7 +318,7 @@ class EcrRegistryManagerTest {
String rewritten = manager.rewriteImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1");
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:" + BASE_PORT + "/backend-user:1", rewritten);
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1", rewritten);
verify(lifecycleManager).createAndStart(any());
}
@@ -291,7 +330,7 @@ class EcrRegistryManagerTest {
String rewritten = manager.rewriteImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1");
assertEquals("localhost:" + BASE_PORT + "/123456789012/us-east-1/backend-user:1", rewritten);
assertEquals("localhost:4566/123456789012/us-east-1/backend-user:1", rewritten);
}
@Test
@@ -327,7 +366,7 @@ class EcrRegistryManagerTest {
String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE);
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:" + BASE_PORT + "/backend-user:1", rewritten);
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1", rewritten);
verify(dockerClient, Mockito.never()).inspectImageCmd(anyString());
}
@@ -357,7 +396,7 @@ class EcrRegistryManagerTest {
String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE);
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:" + BASE_PORT + "/backend-user:1", rewritten);
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1", rewritten);
verify(dockerClient).inspectImageCmd(mirrored);
verify(lifecycleManager).createAndStart(any());
}
@@ -370,7 +409,7 @@ class EcrRegistryManagerTest {
String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE);
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:" + BASE_PORT + "/backend-user:1", rewritten);
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1", rewritten);
verify(lifecycleManager).createAndStart(any());
}
@@ -48,7 +48,7 @@ import static org.mockito.Mockito.when;
class EcsContainerManagerEcrRewriteTest {
private static final String ECR_IMAGE = "123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1";
private static final String REWRITTEN_IMAGE = "123456789012.dkr.ecr.us-east-1.localhost:5100/backend-user:1";
private static final String REWRITTEN_IMAGE = "123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1";
private ContainerBuilder containerBuilder;
private ContainerLifecycleManager lifecycleManager;
@@ -94,28 +94,28 @@ class EksClusterManagerTest {
@Test
void registriesYamlMirrorsEveryRegionHostnameAndThePathStyleForm() {
String yaml = EksClusterManager.buildRegistriesYaml(
"000000000000", AwsRegions.ALL, 5100, "http://floci-ecr-registry:5000");
"000000000000", AwsRegions.ALL, 4566, "http://floci:4566");
assertTrue(yaml.startsWith("mirrors:\n"));
for (String region : AwsRegions.ALL) {
assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".localhost:5100\":"),
assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".localhost:4566\":"),
"should mirror the " + region + " hostname");
}
assertTrue(yaml.contains("\"localhost:5100\":"), "should mirror the path-style form");
assertTrue(yaml.contains("\"localhost:4566\":"), "should mirror the path-style form");
assertFalse(yaml.contains("\"*\""), "must not catch-all public registries");
long endpoints = yaml.lines().filter(l -> l.contains("- \"http://floci-ecr-registry:5000\"")).count();
long endpoints = yaml.lines().filter(l -> l.contains("- \"http://floci:4566\"")).count();
assertEquals(AwsRegions.ALL.size() + 1, endpoints,
"every mirror should point at the registry's in-network endpoint");
"every mirror should point at Floci's in-network data plane");
}
@Test
void registriesYamlUsesTheActualRegistryPortAndEndpoint() {
String yaml = EksClusterManager.buildRegistriesYaml(
"111122223333", List.of("eu-central-1"), 5142, "http://my-registry:5000");
"111122223333", List.of("eu-central-1"), 4566, "http://floci:4566");
assertTrue(yaml.contains("\"111122223333.dkr.ecr.eu-central-1.localhost:5142\":"));
assertTrue(yaml.contains("\"localhost:5142\":"));
assertTrue(yaml.contains("- \"http://my-registry:5000\""));
assertTrue(yaml.contains("\"111122223333.dkr.ecr.eu-central-1.localhost:4566\":"));
assertTrue(yaml.contains("\"localhost:4566\":"));
assertTrue(yaml.contains("- \"http://floci:4566\""));
}
@Test
@@ -528,8 +528,6 @@ class EksClusterManagerTest {
when(dockerClient.copyArchiveToContainerCmd(anyString())).thenReturn(copyCmd);
registryManager = Mockito.mock(EcrRegistryManager.class);
when(registryManager.effectivePort()).thenReturn(5100);
when(registryManager.internalEndpoint()).thenReturn("http://floci-ecr-registry:5000");
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class);
@@ -537,16 +535,19 @@ class EksClusterManagerTest {
when(config.services()).thenReturn(Mockito.mock(EmulatorConfig.ServicesConfig.class));
when(config.services().eks()).thenReturn(eks);
when(config.services().ecr()).thenReturn(ecr);
when(config.port()).thenReturn(4566);
when(config.defaultRegion()).thenReturn("us-east-1");
when(config.defaultAccountId()).thenReturn("000000000000");
when(eks.ecrRegistryMirror()).thenReturn(true);
when(eks.dataPath()).thenReturn(tempDir.toString());
when(ecr.enabled()).thenReturn(true);
DockerHostResolver dockerHostResolver = Mockito.mock(DockerHostResolver.class);
when(dockerHostResolver.resolve()).thenReturn("floci");
manager = new EksClusterManager(
Mockito.mock(ContainerBuilder.class), lifecycleManager,
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
Mockito.mock(DockerHostResolver.class), registryManager, config,
dockerHostResolver, registryManager, config,
Mockito.mock(RegionResolver.class));
}
@@ -623,13 +623,13 @@ class ContainerLauncherTest {
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1");
when(ecrRegistryManager.rewriteImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1"))
.thenReturn("123456789012.dkr.ecr.us-east-1.localhost:5100/backend-user:1");
.thenReturn("123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1");
launcher.launch(fn);
ContainerSpec spec = captureRealContainerSpec();
verify(ecrRegistryManager).rewriteImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1");
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:5100/backend-user:1",
assertEquals("123456789012.dkr.ecr.us-east-1.localhost:4566/backend-user:1",
spec.image());
}
@@ -641,13 +641,13 @@ class ContainerLauncherTest {
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1");
when(ecrRegistryManager.rewriteImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1"))
.thenReturn("localhost:5100/123456789012/us-east-1/backend-user:1");
.thenReturn("localhost:4566/123456789012/us-east-1/backend-user:1");
launcher.launch(fn);
ContainerSpec spec = captureRealContainerSpec();
verify(ecrRegistryManager).rewriteImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/backend-user:1");
assertEquals("localhost:5100/123456789012/us-east-1/backend-user:1",
assertEquals("localhost:4566/123456789012/us-east-1/backend-user:1",
spec.image());
}
@@ -549,7 +549,7 @@ class S3VirtualHostFilterTest {
@CsvSource({
// ECR registry, as EcrRegistryManager emits it
"123456789012.dkr.ecr.us-east-1.localhost, localhost",
"123456789012.dkr.ecr.us-east-1.localhost:5100, localhost",
"123456789012.dkr.ecr.us-east-1.localhost:4566, localhost",
"123456789012.dkr.ecr.eu-central-1.localhost.floci.io, localhost",
// OpenSearch / Elasticsearch domain endpoints
"search-mydomain-abc.us-east-1.es.localhost, localhost",