mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(codeartifact): bridge GetPackageVersionAsset to Maven, npm, and pypi sidecars (#5019)
This commit is contained in:
1 parent
2e87534941
commit
583b2baf7f
13 files changed
+1613
-24
No files matched your search
+58
@@ -674,6 +674,17 @@ public class CodeArtifactService implements Resettable {
|
||||
requireNonBlank(version, "packageVersion");
|
||||
requireNonBlank(assetName, "asset");
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
|
||||
// Maven, npm, and pypi are metadata-free passthroughs straight to their own sidecar
|
||||
// (ReposiliteSidecarClient/VerdaccioSidecarManager/PypiserverSidecarManager): publish for
|
||||
// these formats never goes through publishPackageVersion (it only ever accepts "generic"),
|
||||
// so packageVersions can never hold a record for them. Bridge straight to the sidecar
|
||||
// that actually has the asset instead of always 404ing here.
|
||||
if (CONTAINER_BACKED_FORMATS.contains(format)) {
|
||||
return getContainerBackedPackageVersionAsset(region, domain, owner, repository, format, namespace,
|
||||
packageName, version, assetName, packageVersionRevision);
|
||||
}
|
||||
|
||||
String key = packageVersionKey(region, domain, repository, format, namespace, packageName, version);
|
||||
CodeArtifactPackageVersion pv = packageVersions.getForAccount(owner, key)
|
||||
.orElseThrow(() -> notFound("Package version '" + version + "' of package '" + packageName
|
||||
@@ -695,6 +706,53 @@ public class CodeArtifactService implements Resettable {
|
||||
return new PackageVersionAssetResult(asset, pv.getRevision());
|
||||
}
|
||||
|
||||
/**
|
||||
* There's no stored revision for a sidecar-backed format to compare against, so one is
|
||||
* synthesized from the version coordinate itself (this repository's own sidecar container id,
|
||||
* plus namespace/package/version), not the fetched asset's own bytes: a real revision is
|
||||
* shared by every asset of one package version (a Maven version's JAR and POM alike), so
|
||||
* hashing per-asset content would give a client that described the version once, then tried
|
||||
* to fetch a second asset at that same revision, a spurious not-found on the second call even
|
||||
* though both assets genuinely exist. Keying on the sidecar container id, not just the bare
|
||||
* namespace/package/version strings, keeps two different repositories (even two with the
|
||||
* identical coordinates) from ever synthesizing the same revision.
|
||||
*
|
||||
* <p>Doesn't change when a new asset is published to the version afterward, unlike a real
|
||||
* stored revision: tracking that would mean enumerating every asset a sidecar holds for a
|
||||
* version on every call, the same capability {@code DescribePackageVersion} would need and
|
||||
* doesn't have either for these formats (see the Known limitations doc). Accepted for the
|
||||
* same reason: nothing before this change ever let a client obtain a revision for these
|
||||
* formats in the first place (not even a stale one), so this isn't a regression against any
|
||||
* previously working staleness check.
|
||||
*/
|
||||
private PackageVersionAssetResult getContainerBackedPackageVersionAsset(String region, String domain,
|
||||
String owner, String repository, String format, String namespace, String packageName, String version,
|
||||
String assetName, String packageVersionRevision) {
|
||||
if ("maven".equals(format) && (namespace == null || namespace.isBlank())) {
|
||||
throw validation("namespace is required when requesting an asset from a maven package version.");
|
||||
}
|
||||
String repoId = ensureFormatContainerId(format, region, domain, owner, repository);
|
||||
String revisionKey = repoId + "/" + (namespace == null ? "" : namespace) + "/" + packageName + "/" + version;
|
||||
String revision = sha256Hex(revisionKey.getBytes(StandardCharsets.UTF_8));
|
||||
if (packageVersionRevision != null && !packageVersionRevision.equals(revision)) {
|
||||
throw notFound("Package version '" + version + "' was not found at revision '"
|
||||
+ packageVersionRevision + "'.", version, "package-version");
|
||||
}
|
||||
RepositorySidecarManager manager = sidecarRegistry.forFormat(format)
|
||||
.orElseThrow(() -> notFound("Package version '" + version + "' of package '" + packageName
|
||||
+ "' was not found.", version, "package-version"));
|
||||
byte[] content = manager.fetchPackageVersionAsset(repoId, domain, repository, namespace, packageName,
|
||||
version, assetName)
|
||||
.orElseThrow(() -> notFound("Asset '" + assetName + "' was not found on package version '"
|
||||
+ version + "'.", assetName, "asset"));
|
||||
PackageAsset asset = new PackageAsset();
|
||||
asset.setName(assetName);
|
||||
asset.setSize(content.length);
|
||||
asset.setContent(content);
|
||||
asset.setHashes(computeHashes(content));
|
||||
return new PackageVersionAssetResult(asset, revision);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ authorization
|
||||
|
||||
public AuthorizationToken getAuthorizationToken(String region, String domain, String domainOwner,
|
||||
|
||||
+261
@@ -13,7 +13,17 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Lazily starts and manages one pypiserver container per CodeArtifact repository backing the
|
||||
@@ -47,11 +57,13 @@ public class PypiserverSidecarManager implements RepositorySidecarManager, Conta
|
||||
private static final int PYPISERVER_PORT = 8080;
|
||||
private static final String HEALTH_PATH = "/health";
|
||||
private static final String PACKAGES_DIR = "/data/packages";
|
||||
private static final Pattern SIMPLE_INDEX_HREF = Pattern.compile("href=\"([^\"]*)\"");
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final EmulatorConfig config;
|
||||
private final PerKeyContainerPool pool;
|
||||
private final HttpClient httpClient;
|
||||
|
||||
@Inject
|
||||
public PypiserverSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
@@ -60,6 +72,7 @@ public class PypiserverSidecarManager implements RepositorySidecarManager, Conta
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
|
||||
this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -83,6 +96,254 @@ public class PypiserverSidecarManager implements RepositorySidecarManager, Conta
|
||||
pool.stopContainer(pypiRepositoryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* PyPI packages have no namespace (AWS: "Python ... package versions do not have a
|
||||
* corresponding component"). pypiserver serves every file it holds flatly at
|
||||
* {@code /packages/<filename>} regardless of which package or version it belongs to,
|
||||
* confirmed against a live container, so both are verified before serving anything: that
|
||||
* {@code packageName}'s own simple index genuinely lists {@code assetName}, and that
|
||||
* {@code assetName} itself embeds {@code version} the way every real PyPI filename does
|
||||
* (PEP 427/517 naming) rather than trusting the caller's {@code version} argument on its own.
|
||||
*
|
||||
* <p>{@code assetName} is percent-encoded via {@link #encodeSegment} before joining it to
|
||||
* the fixed {@code /packages/} prefix: without that, a {@code /} inside it would be
|
||||
* indistinguishable from a real path separator and could splice in extra path segments.
|
||||
*/
|
||||
@Override
|
||||
public Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
if (!filenameEmbedsVersion(assetName, packageName, version)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
if (!packageIndexListsAsset(baseUrl, packageName, assetName)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
URI uri = combine(URI.create(baseUrl), "/packages/" + encodeSegment(assetName));
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
|
||||
HttpResponse<byte[]> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofByteArray());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the pypiserver sidecar to fetch " + assetName, e);
|
||||
}
|
||||
if (response.statusCode() == 404) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not fetch " + assetName + " from the pypiserver sidecar: "
|
||||
+ "upstream returned " + response.statusCode());
|
||||
}
|
||||
return Optional.of(response.body());
|
||||
}
|
||||
|
||||
/**
|
||||
* Combines {@code base}'s scheme, authority, and own path prefix (this manager's own {@code
|
||||
* baseUrl} is always a bare container address today with no path, but the sibling Reposilite
|
||||
* client's equivalent helper does need this for its externally configurable URL, so this
|
||||
* stays consistent with it) with an already percent-encoded {@code encodedPath}, built from
|
||||
* {@link #encodeSegment}-encoded, caller-supplied segments. {@code encodedPath} must be fully
|
||||
* encoded going in: this hands the combined string straight to {@link URI#create}, which
|
||||
* only parses, rather than running it through a constructor that would try to quote it a
|
||||
* second time and corrupt any {@code %} it finds (double-encoding, e.g. turning a deliberate
|
||||
* {@code %2F} into {@code %252F}).
|
||||
*/
|
||||
private static URI combine(URI base, String encodedPath) {
|
||||
// getRawPath(), not getPath(): if baseUrl's own path carries any encoding, it must
|
||||
// survive untouched rather than being decoded and re-encoded alongside the new path.
|
||||
// getRawAuthority() below is the same reasoning applied to userinfo/host.
|
||||
String prefix = base.getRawPath();
|
||||
if (prefix == null || prefix.equals("/")) {
|
||||
prefix = "";
|
||||
} else if (prefix.endsWith("/")) {
|
||||
prefix = prefix.substring(0, prefix.length() - 1);
|
||||
}
|
||||
return URI.create(base.getScheme() + "://" + base.getRawAuthority() + prefix + encodedPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent-encodes a single untrusted path segment so it can never be mistaken for a
|
||||
* structural separator or a dot-segment. Every byte outside the unreserved set is escaped,
|
||||
* including {@code /} (otherwise legal inside a path, and so otherwise indistinguishable
|
||||
* from one of the real separators this class inserts around it). A segment that is exactly
|
||||
* {@code .} or {@code ..} gets its dots escaped too: those are themselves otherwise-legal
|
||||
* unreserved characters, but a bare {@code ..} between two real {@code /} separators is a
|
||||
* dot-segment that something in front of the sidecar could resolve by walking back out of
|
||||
* the directory this method intends to confine the request to.
|
||||
*/
|
||||
private static String encodeSegment(String segment) {
|
||||
if (segment.equals(".") || segment.equals("..")) {
|
||||
return segment.replace(".", "%2E");
|
||||
}
|
||||
StringBuilder encoded = new StringBuilder();
|
||||
for (byte b : segment.getBytes(StandardCharsets.UTF_8)) {
|
||||
int v = b & 0xFF;
|
||||
char c = (char) v;
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
|
||||
|| c == '-' || c == '_' || c == '~' || c == '.') {
|
||||
encoded.append(c);
|
||||
} else {
|
||||
encoded.append('%').append(String.format("%02X", v));
|
||||
}
|
||||
}
|
||||
return encoded.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP 503 normalization: lowercase, runs of {@code -_.} collapsed to one {@code -}, same as
|
||||
* {@code CodeArtifactPypiController}'s own pre-upload index check. {@code -} and {@code _}
|
||||
* collapsing to the same character here is what lets this match a filename's own escaped
|
||||
* name portion (wheels, and modern sdists, replace a name's internal {@code -}/{@code .}
|
||||
* with {@code _}) against the caller-supplied, unescaped {@code packageName}.
|
||||
*/
|
||||
private static String normalizePackageName(String packageName) {
|
||||
return packageName.toLowerCase(Locale.ROOT).replaceAll("[-_.]+", "-");
|
||||
}
|
||||
|
||||
private boolean packageIndexListsAsset(String baseUrl, String packageName, String assetName) {
|
||||
String normalized = normalizePackageName(packageName);
|
||||
URI uri = combine(URI.create(baseUrl), "/simple/" + encodeSegment(normalized) + "/");
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the pypiserver sidecar to look up " + packageName, e);
|
||||
}
|
||||
if (response.statusCode() == 404) {
|
||||
return false;
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not look up " + packageName + " on the pypiserver sidecar: "
|
||||
+ "upstream returned " + response.statusCode());
|
||||
}
|
||||
// An exact entry match, not a substring search: a shorter real filename that happens to
|
||||
// be a substring of a different, longer real filename must not pass this check.
|
||||
return SIMPLE_INDEX_HREF.matcher(response.body()).results()
|
||||
.map(match -> {
|
||||
String href = match.group(1);
|
||||
String filename = href.substring(href.lastIndexOf('/') + 1);
|
||||
int fragment = filename.indexOf('#');
|
||||
return fragment < 0 ? filename : filename.substring(0, fragment);
|
||||
})
|
||||
.anyMatch(assetName::equals);
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP 440 multi-letter keywords that can introduce a continuation after a {@code -} or
|
||||
* {@code .}, per the {@code packaging} library's own {@code VERSION_PATTERN}: {@code
|
||||
* alpha}/{@code beta}/{@code preview}/{@code pre}/{@code rc} are all pre-release aliases,
|
||||
* {@code post}/{@code rev} are post-release aliases, {@code dev} is the dev-release keyword.
|
||||
* The matching single-letter aliases ({@code a}, {@code b}, {@code c}, {@code r}) are handled
|
||||
* separately in {@link #versionBoundaryEndsAt}, since a bare letter needs a following digit
|
||||
* to be treated as a continuation rather than an unrelated filename extension starting there.
|
||||
*/
|
||||
private static final List<String> PEP440_CONTINUATION_PREFIXES =
|
||||
List.of("alpha", "beta", "preview", "pre", "post", "rev", "dev", "rc");
|
||||
|
||||
/**
|
||||
* Real PyPI filenames always embed their own version right after a {@code -} (PEP 427/517
|
||||
* naming: {@code <name>-<version>.<ext>} for an sdist, {@code <name>-<version>-<tags>.whl}
|
||||
* for a wheel), so this is checked directly against the filename rather than trusted from the
|
||||
* caller's {@code version} argument alone, which a real file from a different version of the
|
||||
* same package would otherwise sail straight through.
|
||||
*
|
||||
* <p>Checks every {@code -<version>} occurrence and requires both that what follows it
|
||||
* actually ends the version field, handled by {@link #versionBoundaryEndsAt} (requesting
|
||||
* version {@code 1.0} against a real {@code pkg-1.0.1-py3-none-any.whl} contains the literal
|
||||
* text {@code -1.0.}, even though the file's actual version is {@code 1.0.1}, not {@code
|
||||
* 1.0}), and that what precedes it is exactly {@code packageName}, normalized the same way
|
||||
* the simple-index lookup normalizes it. Without that second check, a package name that
|
||||
* itself contains a run of digits could produce a false match inside the name portion of the
|
||||
* filename instead of the real version field: a package literally named {@code foo-1.0-bar}
|
||||
* at version {@code 2.0} produces {@code foo-1.0-bar-2.0.tar.gz}, and the text {@code -1.0-}
|
||||
* inside that name would otherwise look like a complete, valid version {@code 1.0} to a
|
||||
* caller who asked for the wrong one.
|
||||
*/
|
||||
private static boolean filenameEmbedsVersion(String assetName, String packageName, String version) {
|
||||
String normalizedPackageName = normalizePackageName(packageName);
|
||||
String marker = "-" + version;
|
||||
for (int idx = assetName.indexOf(marker); idx >= 0; idx = assetName.indexOf(marker, idx + 1)) {
|
||||
String prefix = assetName.substring(0, idx);
|
||||
if (normalizePackageName(prefix).equals(normalizedPackageName)
|
||||
&& versionBoundaryEndsAt(assetName, idx + marker.length())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code after} is where a candidate version match ends; true when the version field genuinely
|
||||
* ends there rather than continuing as a longer PEP 440 version. A {@code +} never does: PEP
|
||||
* 440 gives it exactly one meaning, introducing a non-empty local-version segment, so whatever
|
||||
* immediately follows it is always part of a longer, different version (e.g. {@code 1.0+linux}
|
||||
* is not {@code 1.0}), never an unrelated filename extension starting there.
|
||||
*
|
||||
* <p>A {@code -} or a {@code .} might not end it either, and both need the same continuation
|
||||
* check: PEP 440 allows either character to separate a release segment from a following
|
||||
* {@code <release segment>} ({@code 1.0.1}), a pre/post/dev-release suffix (every keyword in
|
||||
* {@link #PEP440_CONTINUATION_PREFIXES}, plus the single-letter aliases checked below), or,
|
||||
* only after a {@code -} specifically, an implicit post-release with no keyword at all
|
||||
* ({@code 1.0-1} means {@code 1.0.post1}) <em>unless</em> {@link #isWheelBuildTag} says the
|
||||
* digits are actually a PEP 427 wheel build tag instead, which looks identical but does end
|
||||
* the version right there. All of those start right after the matched text the same way, so
|
||||
* both separators are checked for and rejected as real continuations.
|
||||
*/
|
||||
private static boolean versionBoundaryEndsAt(String assetName, int after) {
|
||||
if (after == assetName.length()) {
|
||||
return true;
|
||||
}
|
||||
char next = assetName.charAt(after);
|
||||
if (next == '+' || (next != '-' && next != '.')) {
|
||||
return false;
|
||||
}
|
||||
String remainder = assetName.substring(after + 1);
|
||||
if (remainder.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
if (Character.isDigit(remainder.charAt(0))) {
|
||||
return next == '-' && isWheelBuildTag(assetName, remainder);
|
||||
}
|
||||
for (String continuation : PEP440_CONTINUATION_PREFIXES) {
|
||||
if (remainder.startsWith(continuation)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Single-letter PEP 440 aliases (a/alpha, b/beta, c/rc, r/rev/post) need a following
|
||||
// digit to count as a continuation; without one, a bare letter is far more likely to be
|
||||
// the start of an unrelated filename extension than a pre/post-release marker.
|
||||
char first = remainder.charAt(0);
|
||||
boolean singleLetterAlias = first == 'a' || first == 'b' || first == 'c' || first == 'r';
|
||||
return !(singleLetterAlias && remainder.length() > 1 && Character.isDigit(remainder.charAt(1)));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code remainder} is known to start with a digit, right after a {@code -}. PEP 440's
|
||||
* implicit, keyword-less post-release numeral ({@code 1.0-1} meaning {@code 1.0.post1}) and
|
||||
* PEP 427's wheel build tag ({@code digit+ letter*}, placed between the version and the
|
||||
* python/abi/platform tags, e.g. {@code 1.0-1-py3-none-any.whl}) look identical at this
|
||||
* point: both are a bare run of digits (optionally followed by letters) right after the
|
||||
* version. They're told apart by what comes after that run: a build tag is always followed
|
||||
* by another {@code -} introducing the next wheel tag, since wheels always have those three
|
||||
* trailing tags, whereas a post-release numeral is followed directly by the file extension.
|
||||
* Only a {@code .whl} filename can have a build tag at all; an sdist's {@code -<digits>} has
|
||||
* no other valid meaning than the post-release numeral.
|
||||
*/
|
||||
private static boolean isWheelBuildTag(String assetName, String remainder) {
|
||||
if (!assetName.endsWith(".whl")) {
|
||||
return false;
|
||||
}
|
||||
int i = 0;
|
||||
while (i < remainder.length() && Character.isDigit(remainder.charAt(i))) {
|
||||
i++;
|
||||
}
|
||||
while (i < remainder.length() && Character.isLetter(remainder.charAt(i))) {
|
||||
i++;
|
||||
}
|
||||
return i < remainder.length() && remainder.charAt(i) == '-';
|
||||
}
|
||||
|
||||
private PerKeyContainerPool.StartedContainer startContainer(String pypiRepositoryId) {
|
||||
String image = config.services().codeartifact().pypiImage();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-pypiserver-" + pypiRepositoryId);
|
||||
|
||||
+124
-1
@@ -11,11 +11,13 @@ import org.jboss.logging.Logger;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpRequest.BodyPublishers;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
@@ -80,6 +82,46 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
|
||||
releaseRepository(repositoryContainerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code namespace} is the Maven groupId; the caller is responsible for requiring it, since
|
||||
* every real Maven coordinate has one. Builds the standard Maven repository layout path
|
||||
* (groupId with dots as slashes, then artifactId, version, and the asset's own filename).
|
||||
*
|
||||
* <p>Unlike {@link #fetchArtifact(String, String)}, which the real wire-protocol GET route
|
||||
* uses with a single caller-supplied path that is legitimately allowed to contain {@code /}
|
||||
* (it's the whole relative GAV path), every one of this method's four coordinates is its own
|
||||
* independent, untrusted value that is only supposed to be one path segment. Concatenating
|
||||
* them with {@code +} the way the wire-protocol route concatenates its one path would let a
|
||||
* {@code /} inside, say, {@code assetName} splice in extra path segments, or a value of
|
||||
* exactly {@code ..} walk back out of the version directory it's supposed to be confined to.
|
||||
* Each coordinate is therefore percent-encoded on its own via {@link #encodeSegment}, which
|
||||
* escapes both of those, before being joined with the real {@code /} separators this method
|
||||
* supplies itself.
|
||||
*/
|
||||
@Override
|
||||
public Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
ensureRepository(repositoryContainerId);
|
||||
String baseUrl = manager.ensureReady();
|
||||
StringBuilder path = new StringBuilder("/").append(encodeSegment(repositoryContainerId));
|
||||
for (String namespacePart : namespace.split("\\.", -1)) {
|
||||
path.append('/').append(encodeSegment(namespacePart));
|
||||
}
|
||||
path.append('/').append(encodeSegment(packageName))
|
||||
.append('/').append(encodeSegment(version))
|
||||
.append('/').append(encodeSegment(assetName));
|
||||
HttpRequest request = HttpRequest.newBuilder(combine(URI.create(baseUrl), path.toString()))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Authorization", manager.basicAuthHeader())
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<byte[]> response = send(request, BodyHandlers.ofByteArray());
|
||||
if (response.statusCode() != 200) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(response.body());
|
||||
}
|
||||
|
||||
/** Ensures a Reposilite repository named {@code repoId} exists, creating it if not. */
|
||||
public void ensureRepository(String repoId) {
|
||||
String baseUrl = manager.ensureReady();
|
||||
@@ -365,13 +407,94 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code gav} isn't necessarily a trusted constant: a caller-supplied asset name can reach
|
||||
* here (via {@link #fetchPackageVersionAsset}'s bridge from {@code GetPackageVersionAsset}, or
|
||||
* the raw wire-protocol GAV path segment itself), so building the URI with a plain string
|
||||
* concatenation would let a {@code #} truncate the path at a URI fragment, or a {@code ?}
|
||||
* reinterpret the rest as a query string, silently fetching a different, unintended path
|
||||
* instead of the one actually requested. The three-argument {@link URI} constructor percent-
|
||||
* encodes whatever isn't already valid inside a path while leaving the real {@code /}
|
||||
* separators alone, unlike {@link URI#create}.
|
||||
*/
|
||||
private HttpRequest.Builder authenticated(String baseUrl, String repoId, String gav) {
|
||||
return HttpRequest.newBuilder()
|
||||
.uri(URI.create(baseUrl + "/" + repoId + "/" + gav))
|
||||
.uri(requestUri(baseUrl, "/" + repoId + "/" + gav))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Authorization", manager.basicAuthHeader());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code baseUrl} isn't always just scheme and authority: {@code FLOCI_SERVICES_CODEARTIFACT_
|
||||
* MAVEN_URL} can point at a pre-configured Reposilite instance behind its own path prefix, so
|
||||
* that prefix is carried over, and carried over with whatever encoding it was configured with
|
||||
* untouched, rather than dropped or re-encoded. {@code path} can separately carry
|
||||
* caller-supplied text (a package or asset name), so it's not safe to hand straight to
|
||||
* {@link URI#create} either: a raw string concatenation would let a {@code #} in that text
|
||||
* truncate the request at a URI fragment, or a {@code ?} reinterpret the rest as a query
|
||||
* string, silently fetching a different path than the one actually requested.
|
||||
*/
|
||||
private static URI requestUri(String baseUrl, String path) {
|
||||
try {
|
||||
String encodedPath = new URI(null, null, path, null, null).getRawPath();
|
||||
return combine(URI.create(baseUrl), encodedPath);
|
||||
} catch (URISyntaxException e) {
|
||||
throw new IllegalStateException("Could not build a request URI for " + path, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Combines {@code base}'s scheme, authority, and own path prefix with an already
|
||||
* percent-encoded {@code encodedPath}. {@code encodedPath} must be fully encoded going in:
|
||||
* this method hands the combined string straight to {@link URI#create}, which only parses,
|
||||
* rather than running it through a constructor that would try to quote it a second time and
|
||||
* corrupt any {@code %} it finds (double-encoding, e.g. turning a deliberate {@code %2F} into
|
||||
* {@code %252F}).
|
||||
*/
|
||||
private static URI combine(URI base, String encodedPath) {
|
||||
// getRawPath(), not getPath(): the configured prefix's own encoding (e.g. a literal %2F
|
||||
// standing for an escaped slash within one opaque segment) must survive untouched. Decoding
|
||||
// it and handing it to the URI constructor alongside the new path would re-encode the whole
|
||||
// thing together and could turn that %2F into a literal /, changing what the prefix means to
|
||||
// whatever sits in front of the sidecar. getRawAuthority() below is the same reasoning
|
||||
// applied to userinfo/host, e.g. a percent-encoded character inside HTTP Basic credentials.
|
||||
String prefix = base.getRawPath();
|
||||
if (prefix == null || prefix.equals("/")) {
|
||||
prefix = "";
|
||||
} else if (prefix.endsWith("/")) {
|
||||
prefix = prefix.substring(0, prefix.length() - 1);
|
||||
}
|
||||
return URI.create(base.getScheme() + "://" + base.getRawAuthority() + prefix + encodedPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent-encodes a single untrusted path segment so it can never be mistaken for a
|
||||
* structural separator or a dot-segment. Every byte outside the unreserved set is escaped,
|
||||
* including {@code /} (which the generic path-quoting {@link URI} constructor otherwise
|
||||
* leaves alone, since a real {@code /} is legal inside a path). A segment that is exactly
|
||||
* {@code .} or {@code ..} gets its dots escaped too: those are themselves otherwise-legal
|
||||
* unreserved characters, but a bare {@code ..} between two real {@code /} separators is a
|
||||
* dot-segment that something in front of the sidecar could resolve by walking back out of
|
||||
* the directory this method intends to confine the request to.
|
||||
*/
|
||||
private static String encodeSegment(String segment) {
|
||||
if (segment.equals(".") || segment.equals("..")) {
|
||||
return segment.replace(".", "%2E");
|
||||
}
|
||||
StringBuilder encoded = new StringBuilder();
|
||||
for (byte b : segment.getBytes(StandardCharsets.UTF_8)) {
|
||||
int v = b & 0xFF;
|
||||
char c = (char) v;
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
|
||||
|| c == '-' || c == '_' || c == '~' || c == '.') {
|
||||
encoded.append(c);
|
||||
} else {
|
||||
encoded.append('%').append(String.format("%02X", v));
|
||||
}
|
||||
}
|
||||
return encoded.toString();
|
||||
}
|
||||
|
||||
private <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> bodyHandler) {
|
||||
try {
|
||||
return httpClient.send(request, bodyHandler);
|
||||
|
||||
+17
@@ -1,5 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Common contract for a CodeArtifact sidecar backing one package format: get one repository ready
|
||||
* to serve that format, and release whatever backing storage it holds once the repository is
|
||||
@@ -39,4 +41,19 @@ public interface RepositorySidecarManager {
|
||||
* format is a no-op, not an error.
|
||||
*/
|
||||
void release(String repositoryContainerId);
|
||||
|
||||
/**
|
||||
* Fetches the bytes of one named asset already published to this sidecar's own backing
|
||||
* storage, for bridging {@code GetPackageVersionAsset} when there is no generic-format record
|
||||
* to serve it from: Maven, npm, and pypi are metadata-free passthroughs straight to their
|
||||
* sidecar, so nothing in {@code CodeArtifactService}'s own package-version store ever records
|
||||
* what they hold. {@code domain}/{@code repository} exist only for a sidecar whose
|
||||
* {@link #ensureReady} needs a public URL to self-start correctly the same way a real client's
|
||||
* first request would; most implementations ignore them. {@code namespace} is {@code null}
|
||||
* for a format or package that has none. Returns empty both when the asset genuinely isn't
|
||||
* there and when the repository was never started for this format, since an unstarted sidecar
|
||||
* has published nothing either way.
|
||||
*/
|
||||
Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName);
|
||||
}
|
||||
+150
-1
@@ -1,5 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.ContainerTeardown;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
@@ -18,7 +20,14 @@ import org.jboss.logging.Logger;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Lazily starts and manages one Verdaccio container per CodeArtifact repository backing the
|
||||
@@ -79,14 +88,18 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final EmulatorConfig config;
|
||||
private final PerKeyContainerPool pool;
|
||||
private final HttpClient httpClient;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public VerdaccioSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config, ObjectMapper mapper) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
|
||||
this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -117,6 +130,142 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
|
||||
pool.stopContainer(npmRepositoryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code namespace} is the npm scope without its leading {@code @}, or {@code null} for an
|
||||
* unscoped package; real npm (and Verdaccio, confirmed against a live container) serves every
|
||||
* version's tarball at {@code <scoped-or-plain-name>/-/<filename>}, with the scope, if any,
|
||||
* still carrying its {@code @} in that path even though the filename itself never includes it.
|
||||
*
|
||||
* <p>The tarball path alone is keyed by filename, not version: a package's own metadata is
|
||||
* checked first (its {@code versions.<version>.dist.tarball} entry) to confirm {@code version}
|
||||
* genuinely maps to {@code assetName} before fetching it, rather than serving whatever file
|
||||
* that name happens to resolve to under a version the caller never actually published.
|
||||
*
|
||||
* <p>{@code namespace}, {@code packageName}, and {@code assetName} are each their own
|
||||
* independently caller-supplied value, only meant to be one path segment; {@code
|
||||
* packagePath} and the final {@code /-/<assetName>} suffix supply the real {@code /}
|
||||
* separators themselves, around each value already percent-encoded on its own via {@link
|
||||
* #encodeSegment}. Without that, a {@code /} inside, say, {@code assetName} would be
|
||||
* indistinguishable from one of those real separators and could splice in extra path
|
||||
* segments.
|
||||
*/
|
||||
@Override
|
||||
public Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
String publicUrl = config.effectiveBaseUrl() + "/codeartifact/npm/" + domain + "/" + repository + "/";
|
||||
String baseUrl = ensureReady(repositoryContainerId, publicUrl);
|
||||
String packagePath = packagePath(namespace, packageName);
|
||||
if (!versionHasAsset(baseUrl, packagePath, version, assetName)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
URI uri = combine(URI.create(baseUrl), "/" + packagePath + "/-/" + encodeSegment(assetName));
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
|
||||
HttpResponse<byte[]> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofByteArray());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Verdaccio sidecar to fetch " + packagePath, e);
|
||||
}
|
||||
if (response.statusCode() == 404) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not fetch " + packagePath + "/-/" + assetName
|
||||
+ " from the Verdaccio sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
return Optional.of(response.body());
|
||||
}
|
||||
|
||||
private static String packagePath(String namespace, String packageName) {
|
||||
return namespace == null
|
||||
? encodeSegment(packageName)
|
||||
: "@" + encodeSegment(namespace) + "/" + encodeSegment(packageName);
|
||||
}
|
||||
|
||||
private boolean versionHasAsset(String baseUrl, String packagePath, String version, String assetName) {
|
||||
HttpRequest request = HttpRequest.newBuilder(combine(URI.create(baseUrl), "/" + packagePath))
|
||||
.timeout(Duration.ofSeconds(10)).GET().build();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Verdaccio sidecar to look up " + packagePath, e);
|
||||
}
|
||||
if (response.statusCode() == 404) {
|
||||
return false;
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not look up " + packagePath + " on the Verdaccio sidecar: "
|
||||
+ "upstream returned " + response.statusCode());
|
||||
}
|
||||
JsonNode versionNode;
|
||||
try {
|
||||
versionNode = mapper.readTree(response.body()).path("versions").path(version);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not parse Verdaccio's package metadata for " + packagePath, e);
|
||||
}
|
||||
if (versionNode.isMissingNode()) {
|
||||
return false;
|
||||
}
|
||||
String tarballUrl = versionNode.path("dist").path("tarball").asText("");
|
||||
String tarballFilename = tarballUrl.substring(tarballUrl.lastIndexOf('/') + 1);
|
||||
return assetName.equals(tarballFilename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Combines {@code base}'s scheme, authority, and own path prefix (this manager's own {@code
|
||||
* baseUrl} is always a bare container address today with no path, but the sibling Reposilite
|
||||
* client's equivalent helper does need this for its externally configurable URL, so this
|
||||
* stays consistent with it) with an already percent-encoded {@code encodedPath}, built from
|
||||
* {@link #encodeSegment}-encoded, caller-supplied segments. {@code encodedPath} must be fully
|
||||
* encoded going in: this hands the combined string straight to {@link URI#create}, which
|
||||
* only parses, rather than running it through a constructor that would try to quote it a
|
||||
* second time and corrupt any {@code %} it finds (double-encoding, e.g. turning a deliberate
|
||||
* {@code %2F} into {@code %252F}).
|
||||
*/
|
||||
private static URI combine(URI base, String encodedPath) {
|
||||
// getRawPath(), not getPath(): if baseUrl's own path carries any encoding (an escaped
|
||||
// slash within one opaque segment, say), it must survive untouched rather than being
|
||||
// decoded and re-encoded alongside the new path, which could change what it means to
|
||||
// whatever sits in front of the sidecar. getRawAuthority() below is the same reasoning
|
||||
// applied to userinfo/host.
|
||||
String prefix = base.getRawPath();
|
||||
if (prefix == null || prefix.equals("/")) {
|
||||
prefix = "";
|
||||
} else if (prefix.endsWith("/")) {
|
||||
prefix = prefix.substring(0, prefix.length() - 1);
|
||||
}
|
||||
return URI.create(base.getScheme() + "://" + base.getRawAuthority() + prefix + encodedPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent-encodes a single untrusted path segment so it can never be mistaken for a
|
||||
* structural separator or a dot-segment. Every byte outside the unreserved set is escaped,
|
||||
* including {@code /} (otherwise legal inside a path, and so otherwise indistinguishable
|
||||
* from one of the real separators this class inserts around it). A segment that is exactly
|
||||
* {@code .} or {@code ..} gets its dots escaped too: those are themselves otherwise-legal
|
||||
* unreserved characters, but a bare {@code ..} between two real {@code /} separators is a
|
||||
* dot-segment that something in front of the sidecar could resolve by walking back out of
|
||||
* the directory this method intends to confine the request to.
|
||||
*/
|
||||
private static String encodeSegment(String segment) {
|
||||
if (segment.equals(".") || segment.equals("..")) {
|
||||
return segment.replace(".", "%2E");
|
||||
}
|
||||
StringBuilder encoded = new StringBuilder();
|
||||
for (byte b : segment.getBytes(StandardCharsets.UTF_8)) {
|
||||
int v = b & 0xFF;
|
||||
char c = (char) v;
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
|
||||
|| c == '-' || c == '_' || c == '~' || c == '.') {
|
||||
encoded.append(c);
|
||||
} else {
|
||||
encoded.append('%').append(String.format("%02X", v));
|
||||
}
|
||||
}
|
||||
return encoded.toString();
|
||||
}
|
||||
|
||||
private PerKeyContainerPool.StartedContainer startContainer(String npmRepositoryId, String publicUrl) {
|
||||
String image = config.services().codeartifact().npmImage();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-verdaccio-" + npmRepositoryId);
|
||||
|
||||
Reference in new issue
Block a user