chore(codeartifact): share the sidecar request-URI encoding helpers (#5026)

ReposiliteSidecarClient, VerdaccioSidecarManager, and PypiserverSidecarManager
each carried an identical copy of combine/encodeSegment (added across the
GetPackageVersionAsset bridge's review cycle in #5019). Extracted into
SidecarUriUtils so the three clients can't drift apart on this again.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-03 15:53:52 -05:00
1 parent 290f952cb1
commit f8a721ce57
5 files changed
+185 -183

No files matched your search

@@ -18,7 +18,6 @@ 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;
@@ -105,9 +104,10 @@ public class PypiserverSidecarManager implements RepositorySidecarManager, Conta
* {@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.
* <p>{@code assetName} is percent-encoded via {@link SidecarUriUtils#encodeSegment(String)}
* 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,
@@ -119,7 +119,7 @@ public class PypiserverSidecarManager implements RepositorySidecarManager, Conta
if (!packageIndexListsAsset(baseUrl, packageName, assetName)) {
return Optional.empty();
}
URI uri = combine(URI.create(baseUrl), "/packages/" + encodeSegment(assetName));
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/packages/" + SidecarUriUtils.encodeSegment(assetName));
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<byte[]> response;
try {
@@ -137,58 +137,6 @@ public class PypiserverSidecarManager implements RepositorySidecarManager, Conta
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 _}
@@ -202,7 +150,8 @@ public class PypiserverSidecarManager implements RepositorySidecarManager, Conta
private boolean packageIndexListsAsset(String baseUrl, String packageName, String assetName) {
String normalized = normalizePackageName(packageName);
URI uri = combine(URI.create(baseUrl), "/simple/" + encodeSegment(normalized) + "/");
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/simple/" + SidecarUriUtils.encodeSegment(normalized)
+ "/");
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<String> response;
try {
@@ -17,7 +17,6 @@ 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;
@@ -94,23 +93,23 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
* 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.
* Each coordinate is therefore percent-encoded on its own via
* {@link SidecarUriUtils#encodeSegment(String)}, 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));
StringBuilder path = new StringBuilder("/").append(SidecarUriUtils.encodeSegment(repositoryContainerId));
for (String namespacePart : namespace.split("\\.", -1)) {
path.append('/').append(encodeSegment(namespacePart));
path.append('/').append(SidecarUriUtils.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()))
path.append('/').append(SidecarUriUtils.encodeSegment(packageName))
.append('/').append(SidecarUriUtils.encodeSegment(version))
.append('/').append(SidecarUriUtils.encodeSegment(assetName));
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), path.toString()))
.timeout(Duration.ofSeconds(30))
.header("Authorization", manager.basicAuthHeader())
.GET()
@@ -437,64 +436,12 @@ public class ReposiliteSidecarClient implements RepositorySidecarManager {
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);
return SidecarUriUtils.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);
@@ -0,0 +1,70 @@
package io.github.hectorvent.floci.services.codeartifact;
import java.net.URI;
import java.nio.charset.StandardCharsets;
/**
* Shared URI-construction helpers for the Maven, npm, and pypi sidecar clients, each of which
* builds a request URI out of its own {@code baseUrl} plus one or more caller-supplied path
* segments (a repository id, package coordinates, an asset filename). Package-private: every
* caller lives in this package, and {@link #combine} in particular requires its {@code
* encodedPath} argument to already be fully percent-encoded, a precondition not worth exposing
* to unrelated callers outside the three clients that know to uphold it.
*/
final class SidecarUriUtils {
private SidecarUriUtils() {}
/**
* Combines {@code base}'s scheme, authority, and own path prefix 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}).
*/
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 the caller intends to confine the request to.
*/
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();
}
}
@@ -144,10 +144,10 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
* <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.
* separators themselves, around each value already percent-encoded on its own via
* {@link SidecarUriUtils#encodeSegment(String)}. 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,
@@ -158,7 +158,8 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
if (!versionHasAsset(baseUrl, packagePath, version, assetName)) {
return Optional.empty();
}
URI uri = combine(URI.create(baseUrl), "/" + packagePath + "/-/" + encodeSegment(assetName));
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath + "/-/"
+ SidecarUriUtils.encodeSegment(assetName));
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<byte[]> response;
try {
@@ -178,12 +179,12 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
private static String packagePath(String namespace, String packageName) {
return namespace == null
? encodeSegment(packageName)
: "@" + encodeSegment(namespace) + "/" + encodeSegment(packageName);
? SidecarUriUtils.encodeSegment(packageName)
: "@" + SidecarUriUtils.encodeSegment(namespace) + "/" + SidecarUriUtils.encodeSegment(packageName);
}
private boolean versionHasAsset(String baseUrl, String packagePath, String version, String assetName) {
HttpRequest request = HttpRequest.newBuilder(combine(URI.create(baseUrl), "/" + packagePath))
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/" + packagePath))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<String> response;
try {
@@ -212,60 +213,6 @@ public class VerdaccioSidecarManager implements RepositorySidecarManager, Contai
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);