mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
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:
1 parent
a03c4d6160
commit
95079965a8
26 files changed
+909
-156
No files matched your search
@@ -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),
|
||||
|
||||
+4
-1
@@ -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; }
|
||||
|
||||
|
||||
+333
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-11
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user