fix(codeartifact): enforce publish:BLOCK on native Maven, npm, pypi and NuGet publishes (#7304)

This commit is contained in:
David authored and GitHub committed 2026-11-03 14:24:23 -04:00
1 parent bb6f46c104
commit 0454c354f7
12 files changed
+627 -27

No files matched your search

@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
import io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient.DeployOutcome;
import io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient.FetchedArtifact;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
@@ -8,10 +10,15 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -21,7 +28,9 @@ import static org.mockito.Mockito.when;
* {@link CodeArtifactMavenController#fetch}'s own decision of when to ask {@link
* CodeArtifactMavenExternalConnectionImporter} to attempt an external-connection import at all,
* not the importer's or {@link ReposiliteSidecarClient}'s own logic, which each have their own
* tests. Both collaborators are mocked, so no real sidecar or network call ever happens here.
* tests, and {@link CodeArtifactMavenController#deploy}'s refusal of a package whose origin
* configuration blocks publish. Both collaborators are mocked, so no real sidecar or network call
* ever happens here.
*/
class CodeArtifactMavenControllerTest {
@@ -95,4 +104,111 @@ class CodeArtifactMavenControllerTest {
assertEquals(200, response.getStatus());
verify(externalConnectionImporter, never()).tryImport(any(), any(), any(), any(), any(), any());
}
/**
* Issue #7116: a package whose origin configuration sets publish:BLOCK must refuse a real mvn
* deploy the way PublishPackageVersion already refuses it for the generic format, before
* anything reaches Reposilite, so not even a byte-identical redeploy gets through.
*/
@Test
void aDeployToAPackageWhoseOriginConfigurationBlocksPublishIsRefusedWithoutReachingReposilite() {
blockPublish("com.example", "widget");
Response response = controller.deploy(headers, DOMAIN, REPOSITORY, "com/example/widget/1.0/widget-1.0.jar",
"jar-bytes".getBytes(StandardCharsets.UTF_8));
assertEquals(409, response.getStatus());
verify(reposilite, never()).deployArtifact(any(), any(), any());
verify(service, never()).recordContainerBackedAssetBytes(any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyLong());
}
/**
* The restriction is per package, not per version, so the bare maven-metadata.xml PUT every
* mvn deploy also sends (no version segment, so the Archived/Disposed guard skips it) is
* refused too.
*/
@Test
void aBareMetadataDeployToABlockedPackageIsRefusedToo() {
blockPublish("com.example", "widget");
Response response = controller.deploy(headers, DOMAIN, REPOSITORY, METADATA_GAV,
"<metadata/>".getBytes(StandardCharsets.UTF_8));
assertEquals(409, response.getStatus());
verify(reposilite, never()).deployArtifact(any(), any(), any());
}
/**
* A snapshot's version-level maven-metadata.xml (and each checksum sibling) belongs to the
* artifact above its version directory, so a block on that artifact refuses it as well. Raised
* by Greptile and pgermosen's review: this path used to resolve to package {@code 1.0-SNAPSHOT}
* in namespace {@code com.example.widget}, which no block ever names.
*/
@Test
void aSnapshotVersionMetadataDeployToABlockedPackageIsRefusedToo() {
blockPublish("com.example", "widget");
for (String gav : List.of("com/example/widget/1.0-SNAPSHOT/maven-metadata.xml",
"com/example/widget/1.0-SNAPSHOT/maven-metadata.xml.sha1")) {
Response response = controller.deploy(headers, DOMAIN, REPOSITORY, gav,
"<metadata/>".getBytes(StandardCharsets.UTF_8));
assertEquals(409, response.getStatus(), gav);
}
verify(reposilite, never()).deployArtifact(any(), any(), any());
}
@Test
void parseNamespaceAndPackageNameResolvesSnapshotVersionMetadataToItsArtifact() {
String[] snapshot = CodeArtifactMavenController
.parseNamespaceAndPackageName("com/example/widget/1.0-SNAPSHOT/maven-metadata.xml").orElseThrow();
String[] bare = CodeArtifactMavenController
.parseNamespaceAndPackageName("com/example/widget/maven-metadata.xml").orElseThrow();
assertArrayEquals(new String[] {"com.example", "widget", "1.0-SNAPSHOT"}, snapshot);
assertArrayEquals(new String[] {"com.example", "widget", null}, bare);
}
/**
* Greptile and pgermosen's review: {@code com/example/widget-SNAPSHOT/maven-metadata.xml} is
* also the bare metadata of an artifact named {@code widget-SNAPSHOT}, so a block on that
* artifact refuses it even though the path parses as a snapshot's version metadata.
*/
@Test
void bareMetadataOfAnArtifactWhoseNameEndsInSnapshotIsRefusedWhenThatArtifactIsBlocked() {
blockPublish("com.example", "widget-SNAPSHOT");
Response response = controller.deploy(headers, DOMAIN, REPOSITORY,
"com/example/widget-SNAPSHOT/maven-metadata.xml", "<metadata/>".getBytes(StandardCharsets.UTF_8));
assertEquals(409, response.getStatus());
verify(reposilite, never()).deployArtifact(any(), any(), any());
}
@Test
void publishCheckedPackagesNamesBothReadingsOnlyForAmbiguousMetadata() {
assertEquals(List.of("com.example:widget", "com.example.widget:1.0-SNAPSHOT"),
readings("com/example/widget/1.0-SNAPSHOT/maven-metadata.xml.sha1"));
assertEquals(List.of("com.example:widget"), readings("com/example/widget/maven-metadata.xml"));
assertEquals(List.of("com.example:widget"),
readings("com/example/widget/1.0-SNAPSHOT/widget-1.0-SNAPSHOT.jar"));
}
private static List<String> readings(String gav) {
return CodeArtifactMavenController.publishCheckedPackages(gav).stream()
.map(pair -> pair[0] + ":" + pair[1])
.toList();
}
private void blockPublish(String namespace, String packageName) {
// What Reposilite would answer if the deploy got through, so a missing refusal fails on
// the status assertion rather than on a null outcome.
when(reposilite.deployArtifact(any(), any(), any()))
.thenReturn(new DeployOutcome(201, true));
doThrow(new AwsException("ConflictException", "Package '" + packageName + "' cannot be published because "
+ "its origin configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("maven"), eq(namespace), eq(packageName));
}
}
@@ -419,6 +419,78 @@ class CodeArtifactNpmDataPlaneTest {
any(), any(), any(), any());
}
/**
* Issue #7116: a package whose origin configuration sets publish:BLOCK refuses an npm publish
* the way PublishPackageVersion already refuses it for the generic format, ahead of the
* byte-identical shortcut: Verdaccio already holds this exact tarball, which would otherwise
* answer 200 without forwarding.
*/
@Test
void aByteIdenticalRepublishToAPackageWhoseOriginConfigurationBlocksPublishIsRefused() throws Exception {
byte[] content = "tarball bytes".getBytes(StandardCharsets.UTF_8);
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
upstream = startUpstreamRecordingPuts(upstreamReceivedPut);
CodeArtifactService service = blockedPublishService(null, "my-pkg");
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
givenStoredVersion(verdaccioClient, null, "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content, Map.of());
startDataPlane(service, verdaccioClient);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
publishEnvelope("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content));
assertEquals(409, response.statusCode());
assertEquals(false, upstreamReceivedPut.get());
}
/**
* The restriction needs nothing from the envelope, so a body too malformed to scan (which is
* otherwise forwarded unchanged for Verdaccio to reject) is refused too, scoped package
* included.
*/
@Test
void anUnscannablePublishToAScopedPackageWhoseOriginConfigurationBlocksPublishIsRefused() throws Exception {
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
upstream = startUpstreamRecordingPuts(upstreamReceivedPut);
CodeArtifactService service = blockedPublishService("scope", "my-pkg");
VerdaccioSidecarClient verdaccioClient = mock(VerdaccioSidecarClient.class);
when(verdaccioClient.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
startDataPlane(service, verdaccioClient);
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/@scope%2fmy-pkg",
"good-token", "{not json");
assertEquals(409, response.statusCode());
assertEquals(false, upstreamReceivedPut.get());
}
private HttpServer startUpstreamRecordingPuts(AtomicReference<Boolean> receivedPut) throws Exception {
return vertx.createHttpServer()
.requestHandler(request -> {
if (request.method() == HttpMethod.PUT) {
receivedPut.set(true);
}
request.response().setStatusCode(201).end();
})
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
private static CodeArtifactService blockedPublishService(String namespace, String packageName) {
CodeArtifactService service = mock(CodeArtifactService.class);
when(service.resolveAuthorizationToken("good-token", DOMAIN))
.thenReturn(Optional.of(new AuthorizationTokenScope("000000000000", "us-east-1")));
when(service.ensureFormatContainerId("npm", "us-east-1", DOMAIN, "000000000000", REPOSITORY))
.thenReturn(NPM_REPOSITORY_ID);
doThrow(new AwsException("ConflictException", "Package '" + packageName + "' cannot be published because "
+ "its origin configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq("us-east-1"), eq(DOMAIN),
eq("000000000000"), eq(REPOSITORY), eq("npm"), eq(namespace), eq(packageName));
return service;
}
/**
* Raised by Greptile's review: a real publish whose per-version {@code readme} exceeds
* {@code NpmPublishEnvelopeScanner}'s own stricter 1,000,000-character limit makes {@code
@@ -561,6 +561,61 @@ class CodeArtifactNuGetDockerIntegrationTest {
assertArrayEquals(nupkg, fetchedAfterUnarchive);
}
/**
* Issue #7116: publish:BLOCK set through the real PutPackageOriginConfiguration route used to
* stop only the generic format's PublishPackageVersion, never a real dotnet nuget push. Set
* under the nuspec id's own mixed-case spelling (the push path lowercases it), it now refuses
* a byte-identical re-push and a new version alike before BaGetter sees either, and lifting it
* lets the new version through. Its own package, so no other ordered test is disturbed.
*/
@Test
@Order(18)
void publishBlockedByOriginConfigurationRefusesARealPushUntilItIsLifted() {
String packageId = "Origin.Blocked.Package";
byte[] published = buildNupkg(packageId, VERSION, "Origin block throwaway.", null, null);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", published))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(201);
setOriginRestrictions(packageId, "BLOCK");
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", published))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(409)
.body(containsString("blocks direct publish"));
byte[] nextVersion = buildNupkg(packageId, "2.0.0", "Origin block throwaway.", null, null);
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", nextVersion))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(409);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/v3/package/"
+ packageId.toLowerCase(Locale.ROOT) + "/index.json")
.then().statusCode(200)
.body("versions", equalTo(List.of(VERSION)));
setOriginRestrictions(packageId, "ALLOW");
given().header("Authorization", "Bearer " + bearerToken)
.contentType("multipart/form-data; boundary=boundary123")
.body(pushBody("boundary123", nextVersion))
.put("/codeartifact/nuget/" + DOMAIN + "/" + REPO + "/api/v2/package")
.then().statusCode(201);
}
private static void setOriginRestrictions(String packageId, String publish) {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"restrictions\":{\"publish\":\"" + publish + "\",\"upstream\":\"BLOCK\"}}")
.post("/v1/package?domain=" + DOMAIN + "&repository=" + REPO + "&format=nuget&package=" + packageId)
.then().statusCode(200)
.body("originConfiguration.restrictions.publish", equalTo(publish));
}
private static long describeDomainAssetSizeBytes() {
return given().header("Authorization", AUTH)
.get("/v1/domain?domain=" + DOMAIN)
@@ -403,6 +403,111 @@ class CodeArtifactPypiControllerTest {
assertEquals(false, uploadReceived.get());
}
/**
* Issue #7116: a package whose origin configuration sets publish:BLOCK refuses a twine upload
* the way PublishPackageVersion already refuses it for the generic format, ahead of the
* byte-identical shortcut above: the stored file here matches the upload exactly, and it is
* still a 409 with nothing forwarded.
*/
@Test
void uploadToAPackageWhoseOriginConfigurationBlocksPublishIsRefusedEvenForByteIdenticalContent() {
String sameContent = "same content";
backend.createContext("/simple/my-pkg/",
exchange -> respond(exchange, 200, "text/html", "<a href=\"my_pkg-1.0.tar.gz\">my_pkg-1.0.tar.gz</a>"));
backend.createContext("/packages/my_pkg-1.0.tar.gz",
exchange -> respond(exchange, 200, "application/octet-stream", sameContent));
AtomicBoolean uploadReceived = new AtomicBoolean();
backend.createContext("/", exchange -> {
uploadReceived.set(true);
respond(exchange, 200, "text/plain", "");
});
// The name pypiserver files my_pkg-1.0.tar.gz under; the service normalizes it to my-pkg.
doThrow(new AwsException("ConflictException", "Package 'my_pkg' cannot be published because its origin "
+ "configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq("my_pkg"));
byte[] body = multipartWithFile("boundary123", "my-pkg", "my_pkg-1.0.tar.gz", sameContent);
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
verify(service, never()).recordContainerBackedAssetBytes(any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyLong());
}
/**
* Raised by Greptile and pgermosen's review: without a version field nothing ties the form's
* name to the filename pypiserver files the upload under, so a block on the package the
* filename names still refuses it when the form names an unrelated package.
*/
@Test
void uploadWithoutAVersionFieldIsCheckedAgainstThePackageItsFilenameNames() {
backend.createContext("/simple/other-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
AtomicBoolean uploadReceived = new AtomicBoolean();
backend.createContext("/", exchange -> {
uploadReceived.set(true);
respond(exchange, 200, "text/plain", "");
});
doThrow(new AwsException("ConflictException", "Package 'my_pkg' cannot be published because its origin "
+ "configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq("my_pkg"));
byte[] body = multipartWithFile("boundary123", "other-pkg", "my_pkg-1.0.tar.gz", "new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
}
/**
* pgermosen's review: pypiserver files {@code foo-1.0-bar-2.0.tar.gz} under {@code foo} even
* when the form names {@code foo-1.0-bar} at {@code 2.0}, so a block on {@code foo} refuses it.
*/
@Test
void uploadIsCheckedAgainstThePackagePypiserverFilesItUnderEvenWithAVersionField() {
AtomicBoolean uploadReceived = new AtomicBoolean();
backend.createContext("/", exchange -> {
uploadReceived.set(true);
respond(exchange, 200, "text/plain", "");
});
doThrow(new AwsException("ConflictException", "Package 'foo' cannot be published because its origin "
+ "configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq("foo"));
byte[] body = multipartWithFileAndVersion("boundary123", "foo-1.0-bar", "2.0", "foo-1.0-bar-2.0.tar.gz",
"new content");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(409, response.getStatus());
assertEquals(false, uploadReceived.get());
}
/**
* Greptile's review: {@code demo-1.0-1-py3-none-any.whl} is a wheel of {@code demo} with build
* tag {@code 1}, so a block on {@code demo-1.0} must not refuse it.
*/
@Test
void aBuildTaggedWheelIsNotRefusedByABlockOnALongerName() {
backend.createContext("/simple/demo/", exchange -> respond(exchange, 404, "text/plain", ""));
backend.createContext("/", exchange -> respond(exchange, 200, "text/plain", ""));
doThrow(new AwsException("ConflictException", "Package 'demo-1.0' cannot be published because its origin "
+ "configuration blocks direct publish.", 409))
.when(service).requireContainerBackedPackagePublishAllowed(eq(REGION), eq(DOMAIN), eq(OWNER),
eq(REPOSITORY), eq("pypi"), isNull(), eq("demo-1.0"));
byte[] body = multipartWithFile("boundary123", "demo", "demo-1.0-1-py3-none-any.whl", "wheel bytes");
Response response = controller.upload(
headers("Bearer good", "multipart/form-data; boundary=boundary123"), DOMAIN, REPOSITORY, body);
assertEquals(200, response.getStatus());
}
@Test
void uploadForwardsANewFileToTheBackendWhenNothingConflicts() {
backend.createContext("/simple/my-pkg/", exchange -> respond(exchange, 404, "text/plain", ""));
@@ -840,6 +840,75 @@ class CodeArtifactServiceTest {
assertEquals("Published", published.packageVersion().getStatus());
}
/**
* The check each native publish path (mvn deploy, npm publish, twine upload, dotnet nuget
* push) runs before its sidecar write: refused exactly while the package's origin
* configuration says publish:BLOCK, the same rule publishPackageVersion applies to generic.
*/
@Test
void containerBackedPackagePublishIsRefusedOnlyWhilePublishIsBlocked() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget",
"BLOCK", "ALLOW");
AwsException blocked = assertThrows(AwsException.class, () -> service
.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "maven", "com.example",
"widget"));
assertEquals("ConflictException", blocked.getErrorCode());
// Scoped to that one package: a sibling in the same namespace still publishes.
service.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "maven", "com.example",
"other");
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "maven", "com.example", "widget",
"ALLOW", "ALLOW");
service.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "maven", "com.example",
"widget");
}
/**
* pypi and nuget names are case/punctuation insensitive, and PutPackageOriginConfiguration
* keys by the normalized spelling, so a restriction set under one spelling must block a
* publish that names the package under another (twine sends the name as typed in the
* project metadata, the nuget controller lowercases the nuspec id).
*/
@Test
void containerBackedPackagePublishBlockMatchesAnyNormalizedSpellingOfTheName() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "pypi", null, "My_Pkg", "BLOCK",
"BLOCK");
service.putPackageOriginConfiguration(REGION, "dom", null, "repo", "nuget", null, "Demo.Package", "BLOCK",
"BLOCK");
assertThrows(AwsException.class, () -> service.requireContainerBackedPackagePublishAllowed(REGION, "dom",
null, "repo", "pypi", null, "my-pkg"));
assertThrows(AwsException.class, () -> service.requireContainerBackedPackagePublishAllowed(REGION, "dom",
null, "repo", "nuget", null, "demo.package"));
}
/**
* A package first retained from an external connection defaults to publish:BLOCK (the User
* Guide's "Default package origin control settings"), so a later direct publish of it is
* refused without anyone calling PutPackageOriginConfiguration.
*/
@Test
void containerBackedPackagePublishIsRefusedForAPackageFirstRetainedFromAnExternalConnection() {
service.createDomain(REGION, "dom", null, Map.of());
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
long fence = service.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "npm", "scope",
"left-pad");
service.ensureRetainedPackageOriginDefault(REGION, "dom", null, "repo", "npm", "scope", "left-pad", fence);
AwsException blocked = assertThrows(AwsException.class, () -> service
.requireContainerBackedPackagePublishAllowed(REGION, "dom", null, "repo", "npm", "scope",
"left-pad"));
assertEquals("ConflictException", blocked.getErrorCode());
}
@Test
void createRepositoryAcceptsExistingUpstream() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -549,4 +549,26 @@ class PypiserverSidecarClientTest {
(ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer>) containersField.get(pool);
containers.put(key, new PerKeyContainerPool.StartedContainer(containerId, url));
}
/**
* Each expected name is what pypiserver 2.4.2's own guess_pkgname_and_version returns for the
* same filename, run inside the pinned image: the port must file an upload under exactly the
* package pypiserver does, build-tagged wheels and names with a {@code -<digit>} run included.
*/
@Test
void guessPackageNameMatchesPypiserversOwnFilenameParser() {
assertEquals(Optional.of("my_pkg"), PypiserverSidecarClient.guessPackageName("my_pkg-1.0.tar.gz"));
assertEquals(Optional.of("foo"), PypiserverSidecarClient.guessPackageName("foo-1.0-bar-2.0.tar.gz"));
assertEquals(Optional.of("mypkg"), PypiserverSidecarClient.guessPackageName("mypkg-dev.tar.gz"));
assertEquals(Optional.of("demo"), PypiserverSidecarClient.guessPackageName("demo-1.0-1-py3-none-any.whl"));
assertEquals(Optional.of("demo"), PypiserverSidecarClient.guessPackageName("demo-1.0-py3-none-any.whl"));
assertEquals(Optional.of("My.Pkg"), PypiserverSidecarClient.guessPackageName("My.Pkg-2.0b1.zip"));
assertEquals(Optional.of("pkg"), PypiserverSidecarClient.guessPackageName("pkg-1.0-py3.11-linux.egg"));
assertEquals(Optional.of("pkg"), PypiserverSidecarClient.guessPackageName("pkg-1.0.win-amd64-py3.9.exe"));
assertEquals(Optional.of("pkg"), PypiserverSidecarClient.guessPackageName("pkg.tar.gz"));
assertEquals(Optional.of("pkg"), PypiserverSidecarClient.guessPackageName("pkg-1.0.tar.gz.asc"));
assertEquals(Optional.of("a-b"), PypiserverSidecarClient.guessPackageName("a-b-c.tgz"));
assertEquals(Optional.empty(), PypiserverSidecarClient.guessPackageName("notapackage.txt"));
assertEquals(Optional.empty(), PypiserverSidecarClient.guessPackageName("pkg-1.0.whl"));
}
}