mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(codeartifact): serve the npm format through a real Verdaccio proxy (#4336)
GetRepositoryEndpoint for format=npm now returns a working registry endpoint: real npm/yarn/pnpm clients can publish to and install from it, proxied straight through to a real Verdaccio instance rather than reimplemented. Every request needs Authorization: Bearer <token> from GetAuthorizationToken, matching npm's own _authToken config and, unlike Maven's HTTP Basic support, Bearer only. Unlike Reposilite, Verdaccio has no native concept of multiple named repositories inside one instance, so each CodeArtifact repository gets its own container instead of sharing one, started lazily on first use and identified by a fresh id assigned at CreateRepository time so a repository deleted and recreated under the same name never inherits the previous one's packages. Each container is started with VERDACCIO_PUBLIC_URL set to that repository's own proxy URL so package metadata it returns (dist.tarball) points back through Floci instead of the container's own internal, client-unreachable address. VerdaccioSidecarManager implements the RepositorySidecarManager interface CodeArtifactService already generalized DeleteRepository's cleanup over, so a deleted repository's Verdaccio container is stopped and removed the same generic way Maven's Reposilite storage is released. The per-key container lifecycle (map of running containers, per-key start lock, health poll, restart-on-unhealthy, stop-all) has nothing Verdaccio-specific in it, so it is pulled out into PerKeyContainerPool for a future per-repository sidecar to reuse directly. CodeArtifactNpmDataPlane is a raw streaming proxy rather than a JAX-RS controller, since npm's wire protocol has no fixed path shape the way Maven's GAV layout does; Verdaccio already speaks that protocol correctly, so this only needs to authenticate the request and forward it. The publish/fetch integration test replays a real request the npm CLI sent during manual verification, captured with a tiny Node.js capture server, so it exercises the exact envelope shape (including a real gzip tarball attachment) npm publish actually produces; the full round trip was additionally verified by hand with the real npm CLI against a live Floci instance.
This commit is contained in:
1 parent
d2c0705ea9
commit
3e6c7a3472
17 files changed
+1554
-71
No files matched your search
@@ -825,6 +825,15 @@ public interface EmulatorConfig {
|
||||
|
||||
@WithDefault("dzikoysk/reposilite:3.6.3")
|
||||
String mavenImage();
|
||||
|
||||
/**
|
||||
* Image used for the per-repository Verdaccio container backing the {@code npm} format.
|
||||
* No URL/token override like {@link #mavenUrl()}: unlike Reposilite's one shared instance,
|
||||
* npm gets one container per CodeArtifact repository, so there is no single external
|
||||
* instance to point at.
|
||||
*/
|
||||
@WithDefault("verdaccio/verdaccio:6.10.4")
|
||||
String npmImage();
|
||||
}
|
||||
|
||||
interface ConnectServiceConfig {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Lazily starts, health-checks, and reuses one container per arbitrary key. Pulled out of
|
||||
* {@code VerdaccioSidecarManager} (one Verdaccio container per CodeArtifact npm repository) since
|
||||
* that lifecycle logic (map of running containers, per-key start lock so concurrent first-use of
|
||||
* two different keys never blocks on each other, health poll, restart-on-unhealthy, stop-all on
|
||||
* shutdown) has nothing Verdaccio-specific in it; only how to actually build and start a container
|
||||
* for a given key does. A future per-repository sidecar (pypiserver, BaGet) can reuse this
|
||||
* directly instead of re-deriving the same map/lock/poll skeleton.
|
||||
*
|
||||
* <p>Callers own the health-check path and the actual container creation (image, config, env),
|
||||
* supplied per call since those are exactly the format-specific parts.
|
||||
*/
|
||||
public class PerKeyContainerPool {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(PerKeyContainerPool.class);
|
||||
|
||||
/** What a {@link Starter} hands back once its container is created and started. */
|
||||
public record StartedContainer(String containerId, String baseUrl) {}
|
||||
|
||||
/** Builds and starts a fresh container for the key {@link #ensureReady} was called with. */
|
||||
@FunctionalInterface
|
||||
public interface Starter {
|
||||
StartedContainer start();
|
||||
}
|
||||
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final String healthPath;
|
||||
private final ConcurrentHashMap<String, StartedContainer> containers = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object> startLocks = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* @param healthPath path (e.g. {@code /-/ping}) appended to a container's base URL to probe
|
||||
* readiness; expected to return HTTP 200 once the container can serve
|
||||
*/
|
||||
public PerKeyContainerPool(ContainerLifecycleManager lifecycleManager, String healthPath) {
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.healthPath = healthPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base URL of a ready container for {@code key}, starting one via {@code starter} if this is
|
||||
* the first use or the previous container is no longer healthy. Concurrent calls for
|
||||
* different keys never block on each other; concurrent calls for the same key serialize so
|
||||
* only one container is ever started for it.
|
||||
*/
|
||||
public String ensureReady(String key, Starter starter) {
|
||||
StartedContainer existing = containers.get(key);
|
||||
if (existing != null && SidecarHealthHelper.probeHealth(existing.baseUrl(), healthPath)) {
|
||||
return existing.baseUrl();
|
||||
}
|
||||
Object lock = startLocks.computeIfAbsent(key, k -> new Object());
|
||||
synchronized (lock) {
|
||||
existing = containers.get(key);
|
||||
if (existing != null && SidecarHealthHelper.probeHealth(existing.baseUrl(), healthPath)) {
|
||||
return existing.baseUrl();
|
||||
}
|
||||
if (existing != null) {
|
||||
LOG.warnv("Sidecar container for key {0} is no longer healthy; restarting it", key);
|
||||
lifecycleManager.stopAndRemove(existing.containerId(), null);
|
||||
}
|
||||
StartedContainer started = starter.start();
|
||||
// Tracked before the health wait, not after: a timeout below must not stop
|
||||
// stopContainer()/stopAll() from ever finding this already-running container again.
|
||||
containers.put(key, started);
|
||||
SidecarHealthHelper.waitForHealth(started.baseUrl(), healthPath);
|
||||
return started.baseUrl();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops and removes the container for one key, if one was ever started. No-op otherwise.
|
||||
* Shares {@link #ensureReady}'s per-key lock so a stop racing a concurrent first-use of the
|
||||
* same key serializes against it, instead of running between the moment that start commits to
|
||||
* a container and the moment it becomes visible here: without the shared lock, a stop that
|
||||
* finds nothing to remove could be immediately followed by that start's own container
|
||||
* registration, orphaning it since nothing calls stop for the key again.
|
||||
*/
|
||||
public void stopContainer(String key) {
|
||||
if (key == null) {
|
||||
return;
|
||||
}
|
||||
Object lock = startLocks.computeIfAbsent(key, k -> new Object());
|
||||
synchronized (lock) {
|
||||
StartedContainer container = containers.remove(key);
|
||||
if (container != null) {
|
||||
lifecycleManager.stopAndRemove(container.containerId(), null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stops and removes every container this pool has started, then forgets them all. */
|
||||
public void stopAll() {
|
||||
if (containers.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
LOG.infov("Stopping {0} pooled sidecar container(s)", containers.size());
|
||||
containers.forEach((key, container) -> {
|
||||
try {
|
||||
lifecycleManager.stopAndRemove(container.containerId(), null);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv(e, "Failed to stop pooled sidecar container for key {0}", key);
|
||||
}
|
||||
});
|
||||
containers.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* A single HTTP GET health probe, and a bounded poll built on it, shared by every sidecar manager
|
||||
* that waits for its own container to come up: {@link PerKeyContainerPool} and
|
||||
* {@code ReposiliteSidecarManager} both had their own copy of this before it moved here.
|
||||
*/
|
||||
public final class SidecarHealthHelper {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SidecarHealthHelper.class);
|
||||
private static final int HEALTH_POLL_MAX_MS = 30_000;
|
||||
private static final int HEALTH_POLL_INTERVAL_MS = 500;
|
||||
private static final int PROBE_TIMEOUT_MS = 500;
|
||||
|
||||
private SidecarHealthHelper() {
|
||||
}
|
||||
|
||||
/** {@code true} once a GET to {@code baseUrl + healthPath} returns HTTP 200. */
|
||||
public static boolean probeHealth(String baseUrl, String healthPath) {
|
||||
try {
|
||||
HttpURLConnection connection = (HttpURLConnection) URI.create(baseUrl + healthPath).toURL()
|
||||
.openConnection();
|
||||
connection.setConnectTimeout(PROBE_TIMEOUT_MS);
|
||||
connection.setReadTimeout(PROBE_TIMEOUT_MS);
|
||||
return connection.getResponseCode() == 200;
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Sidecar health probe failed for {0}", baseUrl);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls {@link #probeHealth} every {@value #HEALTH_POLL_INTERVAL_MS} ms until it succeeds or
|
||||
* {@value #HEALTH_POLL_MAX_MS} ms have passed, in which case this throws.
|
||||
*/
|
||||
public static void waitForHealth(String baseUrl, String healthPath) {
|
||||
long deadline = System.currentTimeMillis() + HEALTH_POLL_MAX_MS;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
if (probeHealth(baseUrl, healthPath)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(HEALTH_POLL_INTERVAL_MS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Interrupted while waiting for sidecar container", e);
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Sidecar container at " + baseUrl + " did not become healthy within "
|
||||
+ HEALTH_POLL_MAX_MS + " ms");
|
||||
}
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
|
||||
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.HttpClientResponse;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
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.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Proxies the real npm registry protocol through Floci to the per-repository Verdaccio container
|
||||
* backing {@code GetRepositoryEndpoint}'s {@code npm} format
|
||||
* ({@code /codeartifact/npm/<domain>/<repository>/}). A raw streaming proxy, not a JAX-RS
|
||||
* controller, since npm's wire protocol has no fixed path shape (package metadata, scoped
|
||||
* packages with an encoded slash, tarball downloads, publish) the way Maven's GAV layout does;
|
||||
* Verdaccio already speaks that protocol correctly, so this only needs to authenticate the
|
||||
* request and forward it.
|
||||
*
|
||||
* <p>Real CodeArtifact npm auth is {@code Authorization: Bearer <token>} (npm's own
|
||||
* {@code _authToken} config always sends Bearer, unlike Maven's HTTP wagon), so unlike
|
||||
* {@code CodeArtifactMavenController} there is no Basic-auth form to also accept here.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CodeArtifactNpmDataPlane {
|
||||
|
||||
private static final String PREFIX = "/codeartifact/npm/";
|
||||
private static final String SERVICE_KEY = "codeartifact";
|
||||
private static final String BEARER_PREFIX = "Bearer ";
|
||||
private static final Set<String> HOP_BY_HOP_HEADERS = Set.of(
|
||||
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
|
||||
"te", "trailers", "transfer-encoding", "upgrade", "authorization", "host");
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final VerdaccioSidecarManager verdaccioManager;
|
||||
private final ServiceConfigAccess serviceConfigAccess;
|
||||
private final EmulatorConfig config;
|
||||
private final Vertx vertx;
|
||||
private final HttpClient proxyClient;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactNpmDataPlane(CodeArtifactService service, VerdaccioSidecarManager verdaccioManager,
|
||||
ServiceConfigAccess serviceConfigAccess, EmulatorConfig config, Vertx vertx) {
|
||||
this.service = service;
|
||||
this.verdaccioManager = verdaccioManager;
|
||||
this.serviceConfigAccess = serviceConfigAccess;
|
||||
this.config = config;
|
||||
this.vertx = vertx;
|
||||
this.proxyClient = vertx.createHttpClient(new HttpClientOptions()
|
||||
.setConnectTimeout(5_000)
|
||||
.setKeepAlive(true));
|
||||
}
|
||||
|
||||
void register(@Observes Router router) {
|
||||
router.route(PREFIX + "*").handler(this::handle);
|
||||
}
|
||||
|
||||
/**
|
||||
* A raw Vert.x route, unlike {@code CodeArtifactMavenController}, never passes through
|
||||
* {@code ServiceEnabledFilter} (a JAX-RS {@code ContainerRequestFilter}), so a disabled
|
||||
* {@code codeartifact} service has to be checked here explicitly or this route would keep
|
||||
* serving npm reads and publishes regardless.
|
||||
*/
|
||||
private void handle(RoutingContext context) {
|
||||
if (!serviceConfigAccess.isEnabled(SERVICE_KEY)) {
|
||||
context.next();
|
||||
return;
|
||||
}
|
||||
Optional<NpmRequest> request = requestFor(context.request().path());
|
||||
if (request.isEmpty()) {
|
||||
context.next();
|
||||
return;
|
||||
}
|
||||
NpmRequest npmRequest = request.get();
|
||||
|
||||
String token = extractToken(context);
|
||||
Optional<AuthorizationTokenScope> scope =
|
||||
token == null ? Optional.empty() : service.resolveAuthorizationToken(token, npmRequest.domain());
|
||||
if (scope.isEmpty()) {
|
||||
context.response().putHeader("WWW-Authenticate", "Bearer").setStatusCode(401).end();
|
||||
return;
|
||||
}
|
||||
|
||||
String npmRepositoryId;
|
||||
try {
|
||||
npmRepositoryId = service.ensureFormatContainerId("npm", scope.get().region(), npmRequest.domain(),
|
||||
scope.get().owner(), npmRequest.repository());
|
||||
} catch (AwsException e) {
|
||||
context.response().setStatusCode(404).end();
|
||||
return;
|
||||
}
|
||||
|
||||
context.request().pause();
|
||||
String publicUrl = config.effectiveBaseUrl() + PREFIX + npmRequest.domain() + "/" + npmRequest.repository()
|
||||
+ "/";
|
||||
String repoId = npmRepositoryId;
|
||||
vertx.<String>executeBlocking(promise -> promise.complete(verdaccioManager.ensureReady(repoId, publicUrl)))
|
||||
.onComplete(result -> {
|
||||
if (result.failed()) {
|
||||
context.request().resume();
|
||||
context.response().setStatusCode(503).end();
|
||||
return;
|
||||
}
|
||||
proxy(context, result.result(), npmRequest.rest() + querySuffix(context));
|
||||
});
|
||||
}
|
||||
|
||||
private void proxy(RoutingContext context, String backendBaseUrl, String backendPath) {
|
||||
URI backend = URI.create(backendBaseUrl);
|
||||
RequestOptions options = new RequestOptions()
|
||||
.setHost(backend.getHost())
|
||||
.setPort(backend.getPort())
|
||||
.setURI(backendPath)
|
||||
.setMethod(context.request().method());
|
||||
proxyClient.request(options).onComplete(upstreamRequest -> {
|
||||
if (upstreamRequest.failed()) {
|
||||
context.request().resume();
|
||||
context.response().setStatusCode(503).end();
|
||||
return;
|
||||
}
|
||||
HttpClientRequest clientReq = upstreamRequest.result();
|
||||
copyRequestHeaders(context, clientReq);
|
||||
clientReq.response().onComplete(upstreamResponse -> {
|
||||
if (upstreamResponse.failed()) {
|
||||
if (!context.response().ended()) {
|
||||
context.response().setStatusCode(502).end();
|
||||
}
|
||||
return;
|
||||
}
|
||||
copyResponseHeaders(context, upstreamResponse.result());
|
||||
upstreamResponse.result().pipeTo(context.response());
|
||||
});
|
||||
clientReq.send(context.request()).onFailure(ignored -> {
|
||||
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())) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips {@code Content-Length} and always streams chunked, rather than copying the upstream
|
||||
* length through: Quarkus's own response filters can commit this response to chunked framing
|
||||
* before this handler ever runs, and a Content-Length header set after that point makes Vert.x
|
||||
* throw on the first {@code pipeTo} write instead of silently doing the right thing.
|
||||
*/
|
||||
private static void copyResponseHeaders(RoutingContext context, HttpClientResponse upstream) {
|
||||
context.response().setStatusCode(upstream.statusCode());
|
||||
upstream.headers().forEach(header -> {
|
||||
if (!HOP_BY_HOP_HEADERS.contains(header.getKey().toLowerCase())
|
||||
&& !"content-length".equalsIgnoreCase(header.getKey())) {
|
||||
context.response().putHeader(header.getKey(), header.getValue());
|
||||
}
|
||||
});
|
||||
context.response().setChunked(true);
|
||||
}
|
||||
|
||||
private static String extractToken(RoutingContext context) {
|
||||
String authorization = context.request().getHeader("Authorization");
|
||||
if (authorization == null || !authorization.startsWith(BEARER_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
return authorization.substring(BEARER_PREFIX.length());
|
||||
}
|
||||
|
||||
private static String querySuffix(RoutingContext context) {
|
||||
String query = context.request().query();
|
||||
return query == null || query.isEmpty() ? "" : "?" + query;
|
||||
}
|
||||
|
||||
static Optional<NpmRequest> requestFor(String path) {
|
||||
if (path == null || !path.startsWith(PREFIX)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String remainder = path.substring(PREFIX.length());
|
||||
String[] segments = remainder.split("/", 3);
|
||||
if (segments.length < 2 || segments[0].isEmpty() || segments[1].isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String rest = segments.length == 3 ? "/" + segments[2] : "/";
|
||||
return Optional.of(new NpmRequest(segments[0], segments[1], rest));
|
||||
}
|
||||
|
||||
record NpmRequest(String domain, String repository, String rest) {}
|
||||
}
|
||||
+27
-6
@@ -71,7 +71,7 @@ public class CodeArtifactService implements Resettable {
|
||||
* and the backfill in {@link #ensureFormatContainerId} already handle it, including for
|
||||
* repositories created before that format's proxy existed.
|
||||
*/
|
||||
private static final List<String> CONTAINER_BACKED_FORMATS = List.of("maven");
|
||||
private static final List<String> CONTAINER_BACKED_FORMATS = List.of("maven", "npm");
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CodeArtifactService.class);
|
||||
|
||||
@@ -313,16 +313,26 @@ public class CodeArtifactService implements Resettable {
|
||||
String key = repositoryKey(region, domain, repository);
|
||||
CodeArtifactRepository r = requireRepository(owner, key, repository);
|
||||
repositories.deleteForAccount(owner, key);
|
||||
// Generic over whatever formats this repository actually has sidecar ids for: adding the
|
||||
// next format's sidecar needs no change here, only a new RepositorySidecarManager
|
||||
// implementation that CodeArtifactSidecarRegistry discovers.
|
||||
//
|
||||
// Best-effort: the metadata delete above already committed, matching real CodeArtifact's
|
||||
// own DeleteRepository (synchronous and always succeeds once the repository exists; actual
|
||||
// content cleanup is an internal detail never exposed to the caller). A sidecar that is
|
||||
// unreachable when this runs must not turn an already-successful delete into a 500, and
|
||||
// must not leave the repository stuck: a retry would just 404, since the record above is
|
||||
// already gone.
|
||||
releaseSidecarStorage(r, domain, repository);
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic over whatever formats a repository actually has sidecar ids for: adding the next
|
||||
* format's sidecar needs no change here, only a new {@link RepositorySidecarManager}
|
||||
* implementation that {@link CodeArtifactSidecarRegistry} discovers. Shared by
|
||||
* {@link #deleteRepository} and {@link #beforeReset}, both of which forget the repository's
|
||||
* record right after calling this and so must not leave its sidecar storage (a Docker
|
||||
* container, for a per-repository sidecar such as Verdaccio) running with nothing left able to
|
||||
* ever release it again.
|
||||
*/
|
||||
private void releaseSidecarStorage(CodeArtifactRepository r, String domain, String repository) {
|
||||
r.getSidecarContainerIds().forEach((format, containerId) ->
|
||||
sidecarRegistry.forFormat(format).ifPresent(manager -> {
|
||||
try {
|
||||
@@ -332,7 +342,6 @@ public class CodeArtifactService implements Resettable {
|
||||
format, domain, repository, e.getMessage());
|
||||
}
|
||||
}));
|
||||
return r;
|
||||
}
|
||||
|
||||
public CodeArtifactRepository describeRepository(String region, String domain, String domainOwner,
|
||||
@@ -750,6 +759,18 @@ public class CodeArtifactService implements Resettable {
|
||||
ref.repository()).getTags();
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases every repository's sidecar storage before {@link #clear} wipes the records that
|
||||
* name it. Without this, an emulator reset forgets which sidecar container backs a repository
|
||||
* without ever stopping it: harmless for Maven's one shared Reposilite instance, but a real
|
||||
* Docker container leak for a per-repository sidecar such as Verdaccio, one abandoned
|
||||
* container per repository that existed at reset time.
|
||||
*/
|
||||
@Override
|
||||
public void beforeReset() {
|
||||
repositories.scanAllAccounts().forEach(r -> releaseSidecarStorage(r, r.getDomainName(), r.getName()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
domains.clear();
|
||||
|
||||
+5
-38
@@ -7,15 +7,13 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.C
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.core.common.docker.SidecarHealthHelper;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
@@ -42,8 +40,7 @@ public class ReposiliteSidecarManager {
|
||||
private static final Logger LOG = Logger.getLogger(ReposiliteSidecarManager.class);
|
||||
private static final String CONTAINER_NAME = "floci-reposilite";
|
||||
private static final int REPOSILITE_PORT = 8080;
|
||||
private static final int HEALTH_POLL_MAX_MS = 30_000;
|
||||
private static final int HEALTH_POLL_INTERVAL_MS = 500;
|
||||
private static final String HEALTH_PATH = "/api/status/health";
|
||||
private static final int GENERATED_SECRET_BYTES = 24;
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
@@ -93,7 +90,7 @@ public class ReposiliteSidecarManager {
|
||||
/** Base URL of a ready Reposilite instance, starting the managed container if needed. */
|
||||
public synchronized String ensureReady() {
|
||||
if (resolvedUrl != null) {
|
||||
if (containerId == null || probeHealth(resolvedUrl)) {
|
||||
if (containerId == null || SidecarHealthHelper.probeHealth(resolvedUrl, HEALTH_PATH)) {
|
||||
return resolvedUrl;
|
||||
}
|
||||
discardStaleManagedEndpoint();
|
||||
@@ -109,7 +106,7 @@ public class ReposiliteSidecarManager {
|
||||
}
|
||||
resolvedTokenName = token.substring(0, separator);
|
||||
resolvedTokenSecret = token.substring(separator + 1);
|
||||
probeHealth(url);
|
||||
SidecarHealthHelper.probeHealth(url, HEALTH_PATH);
|
||||
resolvedUrl = url;
|
||||
LOG.infov("Using pre-configured Reposilite sidecar URL: {0}", resolvedUrl);
|
||||
return resolvedUrl;
|
||||
@@ -159,41 +156,11 @@ public class ReposiliteSidecarManager {
|
||||
resolvedTokenName = MANAGED_TOKEN_NAME;
|
||||
resolvedTokenSecret = managedSecret;
|
||||
String url = "http://" + endpoint;
|
||||
waitForHealth(url);
|
||||
SidecarHealthHelper.waitForHealth(url, HEALTH_PATH);
|
||||
resolvedUrl = url;
|
||||
LOG.infov("Reposilite sidecar is ready at {0}", resolvedUrl);
|
||||
}
|
||||
|
||||
private boolean probeHealth(String baseUrl) {
|
||||
try {
|
||||
HttpURLConnection connection = (HttpURLConnection) URI.create(baseUrl + "/api/status/health").toURL()
|
||||
.openConnection();
|
||||
connection.setConnectTimeout(500);
|
||||
connection.setReadTimeout(500);
|
||||
return connection.getResponseCode() == 200;
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Reposilite sidecar health probe failed for {0}", baseUrl);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void waitForHealth(String baseUrl) {
|
||||
long deadline = System.currentTimeMillis() + HEALTH_POLL_MAX_MS;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
if (probeHealth(baseUrl)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(HEALTH_POLL_INTERVAL_MS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Interrupted while waiting for Reposilite sidecar", e);
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Reposilite sidecar did not become healthy within " + HEALTH_POLL_MAX_MS
|
||||
+ " ms");
|
||||
}
|
||||
|
||||
void onStop(@Observes ShutdownEvent event) {
|
||||
if (containerId == null) {
|
||||
return;
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.core.common.docker.PerKeyContainerPool;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* Lazily starts and manages one Verdaccio container per CodeArtifact repository backing the
|
||||
* {@code npm} format. Unlike Reposilite (Maven), Verdaccio has no native concept of multiple
|
||||
* named repositories inside one instance, so npm repositories each get their own container
|
||||
* instead of sharing one the way {@link ReposiliteSidecarManager} does. The actual per-key
|
||||
* container lifecycle (map of running containers, per-key start lock, health poll,
|
||||
* restart-on-unhealthy, stop-all on shutdown) is generic and lives in
|
||||
* {@link PerKeyContainerPool}; this class only knows how to build and configure a Verdaccio
|
||||
* container specifically.
|
||||
*
|
||||
* <p>Each container is configured with open access (no auth, no upstream proxying) since the
|
||||
* real CodeArtifact authorization check happens once at Floci's proxy layer
|
||||
* ({@code CodeArtifactNpmDataPlane}), before a request ever reaches the container; the container
|
||||
* itself is never reachable directly by a client.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class VerdaccioSidecarManager implements RepositorySidecarManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(VerdaccioSidecarManager.class);
|
||||
private static final String FORMAT = "npm";
|
||||
private static final int VERDACCIO_PORT = 4873;
|
||||
private static final String HEALTH_PATH = "/-/ping";
|
||||
private static final String CONFIG_REMOTE_DIR = "/verdaccio/conf";
|
||||
private static final String CONFIG_FILE_NAME = "config.yaml";
|
||||
|
||||
/**
|
||||
* Open access for both read and publish (real CodeArtifact auth is already enforced before a
|
||||
* request reaches this container) and no uplinks, matching the Maven proxy's own deliberate
|
||||
* choice not to resolve upstream repositories or external connections.
|
||||
*/
|
||||
private static final String CONFIG_YAML = """
|
||||
storage: /verdaccio/storage/data
|
||||
plugins: /verdaccio/plugins
|
||||
auth:
|
||||
htpasswd:
|
||||
file: /verdaccio/storage/htpasswd
|
||||
uplinks: {}
|
||||
packages:
|
||||
'**':
|
||||
access: $all
|
||||
publish: $all
|
||||
unpublish: $all
|
||||
listen: 0.0.0.0:4873
|
||||
log:
|
||||
type: stdout
|
||||
format: pretty
|
||||
level: warn
|
||||
""";
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final EmulatorConfig config;
|
||||
private final PerKeyContainerPool pool;
|
||||
|
||||
@Inject
|
||||
public VerdaccioSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
EmulatorConfig config) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String format() {
|
||||
return FORMAT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base URL of a ready Verdaccio instance for this npm repository, starting its container if
|
||||
* this is the first use. Each repository's container is independent, so concurrent first-use
|
||||
* of two different repositories never blocks on each other (unlike Reposilite's one shared
|
||||
* instance, which does need a single lock around every provisioning call).
|
||||
*
|
||||
* @param publicUrl the externally reachable proxy URL for this specific repository (e.g.
|
||||
* {@code http://localhost:4566/codeartifact/npm/<domain>/<repository>/}),
|
||||
* passed to the container as {@code VERDACCIO_PUBLIC_URL} so package metadata
|
||||
* it returns (notably {@code dist.tarball}) points back through Floci's proxy
|
||||
* instead of the container's own internal, unreachable-by-the-client address.
|
||||
*/
|
||||
@Override
|
||||
public String ensureReady(String npmRepositoryId, String publicUrl) {
|
||||
return pool.ensureReady(npmRepositoryId, () -> startContainer(npmRepositoryId, publicUrl));
|
||||
}
|
||||
|
||||
/** Stops and removes the container for one npm repository, if one was ever started. */
|
||||
@Override
|
||||
public void release(String npmRepositoryId) {
|
||||
pool.stopContainer(npmRepositoryId);
|
||||
}
|
||||
|
||||
private PerKeyContainerPool.StartedContainer startContainer(String npmRepositoryId, String publicUrl) {
|
||||
String image = config.services().codeartifact().npmImage();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-verdaccio-" + npmRepositoryId);
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
|
||||
// Loopback-only: this container has no auth of its own (open $all access, matching the
|
||||
// Maven proxy's own deliberate choice not to resolve upstreams), so the Bearer check in
|
||||
// CodeArtifactNpmDataPlane is the only thing standing between a client and the backing
|
||||
// storage. Publishing this to every interface would let anyone who can reach the host
|
||||
// bypass that check entirely.
|
||||
ContainerSpec spec = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withEnv("VERDACCIO_PUBLIC_URL", publicUrl)
|
||||
.withLoopbackPortBinding(VERDACCIO_PORT, 0)
|
||||
.withDockerNetwork(config.services().dockerNetwork())
|
||||
.withEmbeddedDns()
|
||||
.withLogRotation()
|
||||
.build();
|
||||
String containerId = lifecycleManager.create(spec);
|
||||
try {
|
||||
copyConfig(containerId);
|
||||
ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
|
||||
EndpointInfo endpoint = info.getEndpoint(VERDACCIO_PORT);
|
||||
String url = "http://" + endpoint;
|
||||
LOG.infov("Verdaccio sidecar for npm repository {0} is ready at {1}", npmRepositoryId, url);
|
||||
return new PerKeyContainerPool.StartedContainer(containerId, url);
|
||||
} catch (RuntimeException e) {
|
||||
lifecycleManager.stopAndRemove(containerId, null);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies {@code config.yaml} into the created, not yet started, container. A copy rather than
|
||||
* a bind mount for the same reason {@code ContainerLifecycleManager} copies in the CA bundle:
|
||||
* when Floci itself runs in Docker, its own persistent path is not a host path the daemon can
|
||||
* mount into a sibling container.
|
||||
*/
|
||||
private void copyConfig(String containerId) {
|
||||
byte[] content = CONFIG_YAML.getBytes(StandardCharsets.UTF_8);
|
||||
try {
|
||||
ByteArrayOutputStream archive = new ByteArrayOutputStream(content.length + 512);
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(archive)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry(CONFIG_FILE_NAME);
|
||||
entry.setSize(content.length);
|
||||
entry.setMode(0644);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(content);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
lifecycleManager.getDockerClient().copyArchiveToContainerCmd(containerId)
|
||||
.withRemotePath(CONFIG_REMOTE_DIR)
|
||||
.withTarInputStream(new ByteArrayInputStream(archive.toByteArray()))
|
||||
.exec();
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Could not write the Verdaccio config into container " + containerId, e);
|
||||
}
|
||||
}
|
||||
|
||||
void onStop(@Observes ShutdownEvent ignored) {
|
||||
pool.stopAll();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user