mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(codeartifact): compute DescribeDomain's assetSizeBytes for every format (#5484)
Was hardcoded to 0L unconditionally. Generic-format bytes are summed live from the still-existing PublishPackageVersion records (packageVersions), the same lazily-computed-not-cached pattern repositoryCount already uses. Scoped per still-live repository rather than one scan over the whole domain, matching every other read path's own per-repository prefix. Maven, npm, and pypi have no such record to sum: their publishes go straight to their own sidecar (Reposilite/Verdaccio/pypiserver) and never create one. Each proxy now reports its own successfully-written byte count directly through a new recordContainerBackedAssetBytes, keyed exactly like packageOriginConfigs (region/domain/repository/format/namespace/package, no version), only once it has already decided, in its own terms, that a real write just happened: - Maven: ReposiliteSidecarClient.deployArtifact now returns a DeployOutcome (status plus whether it actually wrote new content), so the idempotent-match short-circuit and a genuine redeployment:false conflict both correctly add nothing. CodeArtifactMavenController parses the GAV path into namespace/package name, including a group/artifact-level maven-metadata.xml upload, which it attributes correctly once the metadata filename itself (not the segment count) tells it apart from a real versioned asset. - npm: NpmPublishEnvelopeScanner's attachment digest loop now also counts the real decoded byte count alongside its SHA-512, so a multi-attachment publish is sized by its actual tarball bytes, not the base64-and-JSON envelope. Recorded only after Verdaccio's own response confirms a 200/201, off the event loop (vertx.executeBlocking, on principle, even though the call itself is cheap); the confirmed-republish short-circuit and a native Verdaccio rejection both add nothing. A native npm unpublish (Verdaccio's unpublish:$all, bypassing this service entirely) is detected separately and cleaned up the same way DeletePackage would have. - pypi: recorded after a real forwarded upload succeeds, under pypiserver's own PEP 503 normalized name so an upload and a later delete spelled differently still address the same count; the byte-identical idempotent short-circuit and the different-content 409 both add nothing. DeleteRepository and DeletePackage both clean up every format's own records (packageVersions and its asset content included) by the same name-based prefix/key, so a repository or package recreated under the same name never inherits a predecessor's bytes. A per-package deletion fence, bumped only by an actual delete (DeletePackage, or a native npm unpublish), replaces a sidecar existence re-check for the race between an in-flight publish's own accounting and a concurrent delete: comparing a snapshot taken before the real write against the fence's current value catches "deleted" and "deleted and republished under the same name" alike, with no network round trip needed to do it, so nothing here holds the service-wide lock across a sidecar call. containerBackedAssetBytes itself is kept in memory only, like the fence, not through StorageFactory: the sidecar content it counts does not survive a Floci restart either, so neither does the count. Verified against real Reposilite, Verdaccio, and pypiserver containers (not just mocks): each Docker-gated integration suite asserts assetSizeBytes increases by exactly the real published/uploaded byte count, stays unchanged across an idempotent retry, and drops back down after a real delete, native unpublish included. Known limitations documented: a maven-metadata.xml for a versioned snapshot is attributed to its version string rather than its real artifact name (still counted correctly in the domain total, just under a misnamed bucket nothing else looks up by name); unpublishing a single version of a multi-version npm package is not detected (this accounting is per-package, not per-version, so there is no narrower count to subtract from regardless). Addresses hectorvent's review on the PR: rebased to pick up #5102's Digests.sha256Hex (the tests were merging clean but failing to compile against current main), stopped containerBackedAssetBytes from surviving a restart the content it counts does not, and closed the native-npm-unpublish gap in the fence's own soundness argument.
This commit is contained in:
1 parent
ebae2ba0e0
commit
6b0d0bc378
15 files changed
+1109
-70
No files matched your search
+24
@@ -87,6 +87,30 @@ class CodeArtifactAssetPersistenceTest {
|
||||
assertEquals(published.packageVersion().getRevision(), result.packageVersionRevision());
|
||||
}
|
||||
|
||||
/**
|
||||
* The fix for a real finding (hectorvent, PR #5484): {@code containerBackedAssetBytes} used
|
||||
* to be wired through {@code StorageFactory} like every other durable store here, but the
|
||||
* Maven/npm/pypi content it counts lives only in the sidecar containers themselves, which do
|
||||
* not survive a Floci restart either (no volume attached, removed on shutdown; see this
|
||||
* service's own Known limitations doc). A persisted count surviving a restart the content
|
||||
* itself does not would leave a stale total with nothing to ever clean it up.
|
||||
*/
|
||||
@Test
|
||||
void containerBackedAssetBytesDoesNotSurviveRestart(@TempDir Path dir) {
|
||||
CodeArtifactService first = newService(dir);
|
||||
first.createDomain(REGION, "dom", null, Map.of());
|
||||
first.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
long fence = first.currentContainerBackedPackageFence(REGION, "dom", null, "repo", "maven", "com.example",
|
||||
"my-pkg");
|
||||
first.recordContainerBackedAssetBytes(REGION, "dom", null, "repo", "maven", "com.example", "my-pkg", 4096L,
|
||||
fence);
|
||||
assertEquals(4096L, first.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
|
||||
CodeArtifactService restarted = newService(dir);
|
||||
|
||||
assertEquals(0L, restarted.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code packageOriginConfigs} is wired through {@code StorageFactory} the same way
|
||||
* {@code domains}/{@code repositories}/{@code packageVersions} are, but that similarity had
|
||||
|
||||
+56
@@ -438,6 +438,62 @@ class CodeArtifactMavenDockerIntegrationTest {
|
||||
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts the delta rather than an absolute total: this class shares one domain across every
|
||||
* ordered test, so other artifacts already contribute to the running total by this point.
|
||||
* {@code assetSizeBytes} used to be hardcoded to {@code 0} regardless of what was actually
|
||||
* published; this is the real Reposilite round trip proving a Maven deploy now counts.
|
||||
*/
|
||||
@Test
|
||||
@Order(14)
|
||||
void describeDomainAssetSizeBytesIncreasesByExactlyWhatWasDeployed() {
|
||||
long before = given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
|
||||
byte[] content = "asset-size-accounting-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
given().header("Authorization", "Bearer " + bearerToken).body(content)
|
||||
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/sizecheck/1.0.0/sizecheck-1.0.0.jar")
|
||||
.then().statusCode(200);
|
||||
|
||||
long after = given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
|
||||
assertEquals(before + content.length, after);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code mvn deploy} always PUTs a {@code maven-metadata.xml} straight to the group/artifact
|
||||
* directory too, with no version segment: {@code com/example/metacheck/maven-metadata.xml} is
|
||||
* only one segment shorter than a real versioned asset path, the same four segments as the
|
||||
* shortest real GAV ({@code group/artifact/version/filename}). It must not be mistaken for
|
||||
* one and misattributed one groupId component too shallow; it is still a real, successful
|
||||
* write, so its bytes still belong in the total.
|
||||
*/
|
||||
@Test
|
||||
@Order(15)
|
||||
void describeDomainAssetSizeBytesCountsAGroupLevelMavenMetadataUpload() {
|
||||
long before = given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
|
||||
byte[] metadata = "<metadata><groupId>com.example</groupId></metadata>".getBytes(StandardCharsets.UTF_8);
|
||||
given().header("Authorization", "Bearer " + bearerToken).body(metadata)
|
||||
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/metacheck/maven-metadata.xml")
|
||||
.then().statusCode(200);
|
||||
|
||||
long after = given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
|
||||
assertEquals(before + metadata.length, after);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the real Reposilite instance's own {@code maven} settings domain directly (the same
|
||||
* shared container {@link ReposiliteSidecarManager} started for every test in this class).
|
||||
|
||||
+62
@@ -98,11 +98,18 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
@Test
|
||||
@Order(1)
|
||||
void publishThenFetchRoundTripsTheRealNpmEnvelope() throws IOException {
|
||||
long assetSizeBytesBeforePublish = describeDomainAssetSizeBytes();
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json")
|
||||
.body(publishFixture)
|
||||
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
|
||||
.then().statusCode(anyOf201Or200());
|
||||
|
||||
// assetSizeBytes used to be hardcoded to 0 regardless of what was actually published; this
|
||||
// is the real Verdaccio round trip proving a real npm publish now counts, by exactly the
|
||||
// tarball's own decoded byte count (not the envelope's base64-and-JSON-wrapped size).
|
||||
assertEquals(assetSizeBytesBeforePublish + expectedTarballBytes.length, describeDomainAssetSizeBytes());
|
||||
|
||||
String metadataBody = given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
|
||||
.then().statusCode(200)
|
||||
@@ -139,10 +146,23 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
@Test
|
||||
@Order(2)
|
||||
void republishingTheSameEnvelopeASecondTimeIsStillIdempotent() {
|
||||
long assetSizeBytesBeforeRepublish = describeDomainAssetSizeBytes();
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json")
|
||||
.body(publishFixture)
|
||||
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
|
||||
.then().statusCode(anyOf201Or200());
|
||||
|
||||
// The confirmed-republish short-circuit never reaches Verdaccio, so no new bytes were
|
||||
// written; assetSizeBytes must not count this tarball a second time.
|
||||
assertEquals(assetSizeBytesBeforeRepublish, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
private static long describeDomainAssetSizeBytes() {
|
||||
return given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -373,6 +393,48 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The fix for a real finding (hectorvent, PR #5484): the pinned Verdaccio image is configured
|
||||
* with {@code unpublish: $all}, so a real npm client's native {@code DELETE} straight to the
|
||||
* packument ({@code npm unpublish <pkg> --force}) bypasses {@code DeletePackage} entirely and
|
||||
* goes straight through this proxy's own transparent passthrough for any non-publish request.
|
||||
* Without detecting this one wire shape, the byte count this package's publish added would
|
||||
* survive the unpublish forever, with nothing to ever clean it up ({@code DeletePackage} never
|
||||
* runs; {@code DeleteRepository} only cleans it up if the whole repository is later deleted
|
||||
* too). A throwaway package, not {@link #PACKAGE_NAME}, for the same reason as the test above.
|
||||
*/
|
||||
@Test
|
||||
@Order(12)
|
||||
void nativeNpmUnpublishCleansUpTheByteCountToo() {
|
||||
String packageName = "unpublish-me-pkg";
|
||||
byte[] tarball = "unpublish throwaway tarball".getBytes(StandardCharsets.UTF_8);
|
||||
String envelope = "{\"name\":\"" + packageName + "\",\"versions\":{\"1.0.0\":{\"name\":\"" + packageName
|
||||
+ "\",\"version\":\"1.0.0\",\"dist\":{\"tarball\":\"http://ignored/" + packageName + "-1.0.0.tgz\""
|
||||
+ "}}},\"_attachments\":{\"" + packageName + "-1.0.0.tgz\":{\"content_type\":"
|
||||
+ "\"application/octet-stream\",\"data\":\""
|
||||
+ Base64.getEncoder().encodeToString(tarball) + "\",\"length\":" + tarball.length + "}}}";
|
||||
|
||||
long assetSizeBytesBeforePublish = describeDomainAssetSizeBytes();
|
||||
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json").body(envelope)
|
||||
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName)
|
||||
.then().statusCode(anyOf201Or200());
|
||||
assertEquals(assetSizeBytesBeforePublish + tarball.length, describeDomainAssetSizeBytes());
|
||||
|
||||
String rev = given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("_rev");
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.delete("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName + "/-rev/" + rev)
|
||||
.then().statusCode(anyOf201Or200());
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + packageName)
|
||||
.then().statusCode(404);
|
||||
assertEquals(assetSizeBytesBeforePublish, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Proves the actual mechanism, not just that {@code VerdaccioSidecarManager} has a method
|
||||
* named right: {@code ContainerTeardowns.stopAll} runs every {@code ContainerTeardown} on
|
||||
|
||||
+17
@@ -77,6 +77,7 @@ class CodeArtifactPypiDockerIntegrationTest {
|
||||
@Order(1)
|
||||
void uploadThenDownloadRoundTripsTheExactBytesThroughTheSimpleIndex() {
|
||||
byte[] content = "real-sdist-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
long assetSizeBytesBeforeUpload = describeDomainAssetSizeBytes();
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.contentType("multipart/form-data; boundary=boundary123")
|
||||
@@ -84,6 +85,10 @@ class CodeArtifactPypiDockerIntegrationTest {
|
||||
.post("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/")
|
||||
.then().statusCode(200);
|
||||
|
||||
// assetSizeBytes used to be hardcoded to 0 regardless of what was actually published; this
|
||||
// is the real pypiserver round trip proving a real twine upload now counts.
|
||||
assertEquals(assetSizeBytesBeforeUpload + content.length, describeDomainAssetSizeBytes());
|
||||
|
||||
String indexHtml = given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/pypi/" + DOMAIN + "/" + REPO + "/simple/" + PACKAGE_NAME + "/")
|
||||
.then().statusCode(200)
|
||||
@@ -112,6 +117,8 @@ class CodeArtifactPypiDockerIntegrationTest {
|
||||
@Test
|
||||
@Order(2)
|
||||
void reuploadingTheExactSameFileSucceedsIdempotently() {
|
||||
long assetSizeBytesBeforeReupload = describeDomainAssetSizeBytes();
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.contentType("multipart/form-data; boundary=boundary123")
|
||||
.body(twineUploadBody("boundary123", PACKAGE_NAME, FILENAME, "real-sdist-bytes".getBytes(StandardCharsets.UTF_8)))
|
||||
@@ -123,6 +130,16 @@ class CodeArtifactPypiDockerIntegrationTest {
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertEquals("real-sdist-bytes", new String(fetched, StandardCharsets.UTF_8));
|
||||
// The idempotent-match short-circuit never forwards to pypiserver, so no new bytes were
|
||||
// written; assetSizeBytes must not count this file a second time.
|
||||
assertEquals(assetSizeBytesBeforeReupload, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
private static long describeDomainAssetSizeBytes() {
|
||||
return given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+330
@@ -210,6 +210,336 @@ class CodeArtifactServiceTest {
|
||||
assertEquals(2, service.describeDomain(REGION, "counted", null).repositoryCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndDeleteDomainReportZeroAssetSizeBytes() {
|
||||
DomainView created = service.createDomain(REGION, "fresh", null, Map.of());
|
||||
assertEquals(0L, created.assetSizeBytes());
|
||||
DomainView deleted = service.deleteDomain(REGION, "fresh", null);
|
||||
assertEquals(0L, deleted.assetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDomainAssetSizeBytesSumsGenericAssetsAcrossRepositoriesAndVersions() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo-b", null, null, Map.of());
|
||||
byte[] first = "first-package".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] second = "second-package-longer".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] third = "third".getBytes(StandardCharsets.UTF_8);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo-a", "generic", "ns", "pkg-a", "1.0.0", "a.txt",
|
||||
Digests.sha256Hex(first), "false", first);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo-a", "generic", "ns", "pkg-a", "2.0.0", "a.txt",
|
||||
Digests.sha256Hex(second), "false", second);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo-b", "generic", "ns", "pkg-b", "1.0.0", "a.txt",
|
||||
Digests.sha256Hex(third), "false", third);
|
||||
|
||||
long expected = first.length + second.length + third.length;
|
||||
assertEquals(expected, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDomainAssetSizeBytesDropsByExactlyWhatDeletePackageRemoves() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
byte[] kept = "kept-package".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] removed = "removed-package-content".getBytes(StandardCharsets.UTF_8);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "kept", "1.0.0", "a.txt",
|
||||
Digests.sha256Hex(kept), "false", kept);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "removed", "1.0.0", "a.txt",
|
||||
Digests.sha256Hex(removed), "false", removed);
|
||||
assertEquals(kept.length + removed.length, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
|
||||
service.deletePackage(REGION, "dom", null, "repo", "generic", "ns", "removed");
|
||||
|
||||
assertEquals(kept.length, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code deleteRepository} does not clean up a generic package's {@code packageVersions}
|
||||
* records or asset bytes today, so they are only unreachable through the normal API, not
|
||||
* actually gone. Without scoping the sum to each still-live repository's own key prefix, the
|
||||
* domain total would keep counting a deleted repository's orphaned bytes forever.
|
||||
*/
|
||||
@Test
|
||||
void describeDomainAssetSizeBytesExcludesADeletedRepositorysOrphanedBytes() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo-b", null, null, Map.of());
|
||||
byte[] inDeletedRepo = "goes-away-with-repo-a".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] inLiveRepo = "stays-in-repo-b".getBytes(StandardCharsets.UTF_8);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo-a", "generic", "ns", "pkg-a", "1.0.0", "a.txt",
|
||||
Digests.sha256Hex(inDeletedRepo), "false", inDeletedRepo);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo-b", "generic", "ns", "pkg-b", "1.0.0", "a.txt",
|
||||
Digests.sha256Hex(inLiveRepo), "false", inLiveRepo);
|
||||
|
||||
service.deleteRepository(REGION, "dom", null, "repo-a");
|
||||
|
||||
assertEquals(inLiveRepo.length, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* A Maven/npm/pypi package merely existing on its sidecar (confirmed here via a stubbed
|
||||
* {@code packageExists}) contributes nothing on its own: {@code CodeArtifactService} never
|
||||
* queries a sidecar for size, only the running total each format's own proxy explicitly
|
||||
* reports through {@link CodeArtifactService#recordContainerBackedAssetBytes}, which nothing
|
||||
* in this test ever calls. The next tests below exercise that path directly.
|
||||
*/
|
||||
@Test
|
||||
void aContainerBackedPackageExistingWithNoRecordedBytesContributesNothing() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
byte[] generic = "generic-package".getBytes(StandardCharsets.UTF_8);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "generic-pkg", "1.0.0", "a.txt",
|
||||
Digests.sha256Hex(generic), "false", generic);
|
||||
when(reposiliteClient.packageExists(anyString(), eq("dom"), eq("repo"), eq("com.example"), eq("maven-pkg")))
|
||||
.thenReturn(true);
|
||||
|
||||
assertEquals(generic.length, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors exactly what each real proxy does: snapshot {@code currentContainerBackedPackageFence}
|
||||
* before the (here, simulated) real write, then report it alongside the byte count, the way
|
||||
* {@code CodeArtifactMavenController}/the npm data plane/{@code CodeArtifactPypiController}
|
||||
* all do for real.
|
||||
*/
|
||||
private void recordBytes(String domain, String repository, String format, String namespace, String packageName,
|
||||
long bytes) {
|
||||
long fence = service.currentContainerBackedPackageFence(REGION, domain, null, repository, format, namespace,
|
||||
packageName);
|
||||
service.recordContainerBackedAssetBytes(REGION, domain, null, repository, format, namespace, packageName,
|
||||
bytes, fence);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code recordContainerBackedAssetBytes} is what each of the three sidecar-backed proxies
|
||||
* calls after a real (non-idempotent, non-rejected) write; this is the unit-level proof that
|
||||
* it feeds {@code assetSizeBytes} correctly across all three formats plus generic at once,
|
||||
* accumulating repeated calls for the same package the way a multi-file Maven deploy
|
||||
* (jar + pom as separate PUTs) needs.
|
||||
*/
|
||||
@Test
|
||||
void describeDomainAssetSizeBytesSumsContainerBackedBytesAcrossEveryFormat() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
byte[] generic = "generic".getBytes(StandardCharsets.UTF_8);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "generic-pkg", "1.0.0", "a.txt",
|
||||
Digests.sha256Hex(generic), "false", generic);
|
||||
recordBytes("dom", "repo", "maven", "com.example", "maven-pkg", 100L);
|
||||
recordBytes("dom", "repo", "maven", "com.example", "maven-pkg", 50L);
|
||||
recordBytes("dom", "repo", "npm", null, "npm-pkg", 200L);
|
||||
recordBytes("dom", "repo", "pypi", null, "pypi-pkg", 300L);
|
||||
|
||||
long expected = generic.length + 100L + 50L + 200L + 300L;
|
||||
assertEquals(expected, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlike every JSON-API package operation's own namespace/packageName, the wire-protocol
|
||||
* proxies (Maven's GAV path, npm's scope/name, twine's form field) never validate theirs
|
||||
* before calling this: a crafted namespace spelling out another namespace's already-escaped
|
||||
* form (here, raw {@code "a#cb"} vs. legitimate {@code "a:b"}, see
|
||||
* {@code newEscapedKeysNeverCollideWithAPreExistingRawKeyThatHappenedToContainABackslash} for
|
||||
* the same invariant proven on the JSON API side) must not be allowed to land in
|
||||
* {@code containerBackedAssetBytes} under the legitimate package's own key at all.
|
||||
*/
|
||||
@Test
|
||||
void recordContainerBackedAssetBytesIgnoresANamespaceContainingTheEscapeCharacter() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
recordBytes("dom", "repo", "maven", "a:b", "legit", 10L);
|
||||
|
||||
recordBytes("dom", "repo", "maven", "a#cb", "legit", 999L);
|
||||
|
||||
assertEquals(10L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordContainerBackedAssetBytesIgnoresAPackageNameContainingTheEscapeCharacter() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
|
||||
recordBytes("dom", "repo", "pypi", null, "bad#name", 999L);
|
||||
|
||||
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDomainAssetSizeBytesDropsWhenDeletePackageRemovesAContainerBackedPackage() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
when(reposiliteClient.packageExists(anyString(), eq("dom"), eq("repo"), eq("com.example"), eq("removed")))
|
||||
.thenReturn(true);
|
||||
recordBytes("dom", "repo", "maven", "com.example", "kept", 40L);
|
||||
recordBytes("dom", "repo", "maven", "com.example", "removed", 60L);
|
||||
assertEquals(100L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
|
||||
service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "removed");
|
||||
|
||||
assertEquals(40L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Same orphan-exclusion property as generic (see the backslash/collision test above), proven
|
||||
* here for the sidecar ledger: {@code deleteRepository} actually does clean this one up (unlike
|
||||
* {@code packageVersions}), but the sum is scoped per live repository regardless, so this holds
|
||||
* either way.
|
||||
*/
|
||||
@Test
|
||||
void describeDomainAssetSizeBytesExcludesADeletedRepositorysContainerBackedBytes() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo-a", null, null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo-b", null, null, Map.of());
|
||||
recordBytes("dom", "repo-a", "npm", null, "pkg-a", 70L);
|
||||
recordBytes("dom", "repo-b", "npm", null, "pkg-b", 30L);
|
||||
|
||||
service.deleteRepository(REGION, "dom", null, "repo-a");
|
||||
|
||||
assertEquals(30L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code assetSizeBytesForDomain} scans generic {@code packageVersions} by each live
|
||||
* repository's name-based prefix, not by a freshly minted id, so a repository recreated under
|
||||
* this same name would otherwise sum right back into any orphaned record
|
||||
* {@code deleteRepository} failed to clean up: unlike {@code containerBackedAssetBytes}, there
|
||||
* was never any cleanup of {@code packageVersions} on {@code deleteRepository} before this,
|
||||
* since nothing before {@code assetSizeBytes} existed ever looked an old repository's
|
||||
* generic-format records up by name alone the way this domain-wide sum does.
|
||||
*/
|
||||
@Test
|
||||
void describeDomainAssetSizeBytesDoesNotResurrectAGenericPackagesBytesAfterRepositoryRecreation() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
byte[] content = "generic content".getBytes(StandardCharsets.UTF_8);
|
||||
service.publishPackageVersion(REGION, "dom", null, "repo", "generic", "ns", "generic-pkg", "1.0.0", "a.txt",
|
||||
Digests.sha256Hex(content), "false", content);
|
||||
assertEquals(content.length, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
|
||||
service.deleteRepository(REGION, "dom", null, "repo");
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
|
||||
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reproduces the one window where a real publish and a real {@code DeleteRepository} could
|
||||
* interleave: the sidecar-backed proxies check the repository exists in one {@code
|
||||
* synchronized} call ({@code ensureFormatContainerId}), then do the real HTTP write to the
|
||||
* sidecar with no lock held at all, and only then call this method in a second, separate
|
||||
* {@code synchronized} call. A {@code DeleteRepository} landing in that gap would otherwise
|
||||
* resurrect a key it just cleaned up. Calling {@code recordContainerBackedAssetBytes} after
|
||||
* {@code deleteRepository} reproduces exactly that interleaving deterministically (both methods
|
||||
* are themselves {@code synchronized}, so there is no actual race to simulate, only the order
|
||||
* the two calls land in): the resurrected entry must not survive, and in particular must not
|
||||
* be inherited by a same-named repository created afterward, the same invariant
|
||||
* {@code deleteRepository}'s own cleanup already protects against for every ordering but this
|
||||
* one.
|
||||
*/
|
||||
@Test
|
||||
void recordContainerBackedAssetBytesAfterTheRepositoryIsAlreadyDeletedIsIgnored() {
|
||||
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", "maven", "com.example",
|
||||
"late");
|
||||
service.deleteRepository(REGION, "dom", null, "repo");
|
||||
|
||||
service.recordContainerBackedAssetBytes(REGION, "dom", null, "repo", "maven", "com.example", "late", 999L,
|
||||
fence);
|
||||
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* The same window, but for {@code DeletePackage} instead of {@code DeleteRepository}: the
|
||||
* repository stays alive, only the package underneath it is gone, so a resurrected entry
|
||||
* would be counted by {@code DescribeDomain} immediately rather than only after a repository
|
||||
* is recreated. Snapshotting the fence before the delete, exactly like a real proxy snapshots
|
||||
* it before its real write, reproduces exactly the interleaving a delayed accounting callback
|
||||
* racing a concurrent {@code DeletePackage} would see.
|
||||
*/
|
||||
@Test
|
||||
void recordContainerBackedAssetBytesAfterAConcurrentDeletePackageIsIgnored() {
|
||||
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", "maven", "com.example",
|
||||
"late");
|
||||
when(reposiliteClient.packageExists(anyString(), eq("dom"), eq("repo"), eq("com.example"), eq("late")))
|
||||
.thenReturn(true);
|
||||
service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "late");
|
||||
|
||||
service.recordContainerBackedAssetBytes(REGION, "dom", null, "repo", "maven", "com.example", "late", 999L,
|
||||
fence);
|
||||
|
||||
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* The harder version of the same race: the package is deleted {@code and} a different publish
|
||||
* recreates it under the same name, both completing before the first publish's own delayed
|
||||
* accounting call runs. A sidecar existence check alone could not tell these two packages
|
||||
* apart (the name exists either way); the fence can, since only an actual deletion bumps it.
|
||||
*/
|
||||
@Test
|
||||
void recordContainerBackedAssetBytesAfterDeleteAndRepublishUnderTheSameNameIsIgnored() {
|
||||
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", "maven", "com.example",
|
||||
"late");
|
||||
when(reposiliteClient.packageExists(anyString(), eq("dom"), eq("repo"), eq("com.example"), eq("late")))
|
||||
.thenReturn(true);
|
||||
service.deletePackage(REGION, "dom", null, "repo", "maven", "com.example", "late");
|
||||
// The republish: a different publish, same coordinates, after the first one's snapshot.
|
||||
recordBytes("dom", "repo", "maven", "com.example", "late", 10L);
|
||||
|
||||
service.recordContainerBackedAssetBytes(REGION, "dom", null, "repo", "maven", "com.example", "late", 999L,
|
||||
fence);
|
||||
|
||||
assertEquals(10L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code currentContainerBackedPackageFence}/{@code recordContainerBackedAssetBytes} never
|
||||
* touch a sidecar at all, so there is no failure mode left to fail open on: the fence
|
||||
* comparison is a plain in-memory read, always available, closing the same race the sidecar
|
||||
* round trip this replaced used to close, at the cost of a thrown exception whenever it
|
||||
* couldn't reach the sidecar.
|
||||
*/
|
||||
@Test
|
||||
void recordContainerBackedAssetBytesNeverNeedsTheSidecarAtAll() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
when(reposiliteClient.packageExists(any(), any(), any(), any(), any()))
|
||||
.thenThrow(new IllegalStateException("sidecar unreachable"));
|
||||
|
||||
recordBytes("dom", "repo", "maven", "com.example", "never-asked", 55L);
|
||||
|
||||
assertEquals(55L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
verify(reposiliteClient, never()).packageExists(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code packageOriginConfigs} keeps the caller's raw spelling (pre-existing, unrelated to byte
|
||||
* accounting); {@code containerBackedAssetBytes}/the fence use pypiserver's own PEP 503
|
||||
* normalization instead, so an upload spelled one way and a {@code DeletePackage} spelled a
|
||||
* case/punctuation-equivalent way still address the one byte count pypiserver itself would
|
||||
* treat as a single package.
|
||||
*/
|
||||
@Test
|
||||
void pypiAccountingNormalizesThePackageNameLikePypiserverItself() {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
recordBytes("dom", "repo", "pypi", null, "My.Package", 42L);
|
||||
assertEquals(42L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
when(pypiserverClient.packageExists(anyString(), eq("dom"), eq("repo"), isNull(), eq("my_package")))
|
||||
.thenReturn(true);
|
||||
|
||||
service.deletePackage(REGION, "dom", null, "repo", "pypi", null, "my_package");
|
||||
|
||||
assertEquals(0L, service.describeDomain(REGION, "dom", null).assetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentCreateDomainWithSameNameOnlyOneWins() throws InterruptedException {
|
||||
int attempts = 8;
|
||||
|
||||
+41
-5
@@ -33,7 +33,7 @@ class NpmPublishEnvelopeScannerTest {
|
||||
NpmPublishEnvelopeScanner.Version version = envelope.versions().get("1.0.0");
|
||||
assertEquals(raw.at("/versions/1.0.0/dist/integrity").asText(), version.integrity());
|
||||
String filename = raw.at("/versions/1.0.0/dist/tarball").asText().replaceAll(".*/", "");
|
||||
assertEquals(version.integrity(), envelope.attachmentIntegrity().get(filename));
|
||||
assertEquals(version.integrity(), envelope.attachments().get(filename).integrity());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -55,7 +55,8 @@ class NpmPublishEnvelopeScannerTest {
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = scan(json);
|
||||
|
||||
assertEquals("sha512-" + Base64.getEncoder().encodeToString(sha512(tarball)),
|
||||
envelope.attachmentIntegrity().get("a.tgz"));
|
||||
envelope.attachments().get("a.tgz").integrity());
|
||||
assertEquals(tarball.length, envelope.attachments().get("a.tgz").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -68,7 +69,8 @@ class NpmPublishEnvelopeScannerTest {
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = scan(json);
|
||||
|
||||
assertEquals("sha512-" + Base64.getEncoder().encodeToString(sha512(tarball)),
|
||||
envelope.attachmentIntegrity().get("big.tgz"));
|
||||
envelope.attachments().get("big.tgz").integrity());
|
||||
assertEquals(tarball.length, envelope.attachments().get("big.tgz").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -110,9 +112,43 @@ class NpmPublishEnvelopeScannerTest {
|
||||
assertInvalid("{\"_attachments\":{\"a.tgz\":{\"data\":\"abcde\"}}}");
|
||||
}
|
||||
|
||||
/**
|
||||
* A real finding turned out not to be one: a review raised whether a JSON-escaped attachment
|
||||
* (most plausibly {@code \/}, the one base64 character JSON permits escaping, though no real
|
||||
* npm client's own {@code JSON.stringify} ever actually produces one) would be silently
|
||||
* undercounted here. Checked directly rather than assumed either way: {@code
|
||||
* JsonParser#readBinaryValue} already resolves the escape before decoding, so a validly
|
||||
* escaped, valid-length attachment decodes correctly, digest and byte count both exactly
|
||||
* right. {@code 0xFF 0xFF 0xFF} is a deliberately chosen fixture: its base64 encoding is
|
||||
* exactly {@code "////"}, four real {@code /} characters with no padding, so every character
|
||||
* of the escaped payload below actually exercises the escape-resolution path, not just one
|
||||
* character buried among ordinary ones.
|
||||
*/
|
||||
@Test
|
||||
void attachmentDataContainingAnEscapeIsRejected() {
|
||||
assertInvalid("{\"_attachments\":{\"a.tgz\":{\"data\":\"ab\\/cd\"}}}");
|
||||
void attachmentDataContainingAnEscapedSlashIsDecodedCorrectly() throws Exception {
|
||||
byte[] tarball = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
|
||||
String base64 = Base64.getEncoder().encodeToString(tarball);
|
||||
assertEquals("////", base64);
|
||||
String escaped = base64.replace("/", "\\/");
|
||||
String json = "{\"_attachments\":{\"a.tgz\":{\"data\":\"" + escaped + "\"}}}";
|
||||
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = scan(json);
|
||||
|
||||
assertEquals("sha512-" + Base64.getEncoder().encodeToString(sha512(tarball)),
|
||||
envelope.attachments().get("a.tgz").integrity());
|
||||
assertEquals(tarball.length, envelope.attachments().get("a.tgz").size());
|
||||
}
|
||||
|
||||
/**
|
||||
* An escape sequence present is not, on its own, a pass: decoded, this is {@code "a/bcd"},
|
||||
* 5 characters, not a multiple of 4, so still genuinely invalid base64 regardless of the
|
||||
* escape. (This is also what the older, differently-reasoned version of this test actually
|
||||
* exercised: {@code "ab\/cd"} decodes to {@code "ab/cd"}, 5 characters, rejected for the same
|
||||
* length reason, not because it contained an escape at all.)
|
||||
*/
|
||||
@Test
|
||||
void attachmentDataContainingAnEscapeButStillInvalidBase64IsRejected() {
|
||||
assertInvalid("{\"_attachments\":{\"a.tgz\":{\"data\":\"a\\/bcd\"}}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+16
-10
@@ -262,9 +262,11 @@ class ReposiliteSidecarClientTest {
|
||||
respond(exchange, 200, "");
|
||||
});
|
||||
|
||||
int status = client.deployArtifact("dom--repo", "com/example/a/1.0/a-1.0.jar", "hello".getBytes(StandardCharsets.UTF_8));
|
||||
ReposiliteSidecarClient.DeployOutcome outcome = client.deployArtifact("dom--repo",
|
||||
"com/example/a/1.0/a-1.0.jar", "hello".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertThat(status, is(200));
|
||||
assertThat(outcome.status(), is(200));
|
||||
assertTrue(outcome.wroteNewContent());
|
||||
assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), received.get());
|
||||
assertThat(authHeader.get(), equalTo("Basic dGVzdDp0ZXN0"));
|
||||
}
|
||||
@@ -278,9 +280,11 @@ class ReposiliteSidecarClientTest {
|
||||
respond(exchange, 200, "hello");
|
||||
});
|
||||
|
||||
int status = client.deployArtifact("dom--repo", "com/example/a/1.0/a-1.0.jar", content);
|
||||
ReposiliteSidecarClient.DeployOutcome outcome = client.deployArtifact("dom--repo",
|
||||
"com/example/a/1.0/a-1.0.jar", content);
|
||||
|
||||
assertThat(status, is(200));
|
||||
assertThat(outcome.status(), is(200));
|
||||
assertFalse(outcome.wroteNewContent());
|
||||
assertThat(methodsSeen, equalTo(List.of("GET")));
|
||||
}
|
||||
|
||||
@@ -300,10 +304,11 @@ class ReposiliteSidecarClientTest {
|
||||
}
|
||||
});
|
||||
|
||||
int status = client.deployArtifact("dom--repo", "com/example/a/1.0/a-1.0.jar",
|
||||
"hello".getBytes(StandardCharsets.UTF_8));
|
||||
ReposiliteSidecarClient.DeployOutcome outcome = client.deployArtifact("dom--repo",
|
||||
"com/example/a/1.0/a-1.0.jar", "hello".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertThat(status, is(409));
|
||||
assertThat(outcome.status(), is(409));
|
||||
assertFalse(outcome.wroteNewContent());
|
||||
assertThat(methodsSeen, equalTo(List.of("GET", "PUT")));
|
||||
assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), putBody.get());
|
||||
}
|
||||
@@ -328,10 +333,11 @@ class ReposiliteSidecarClientTest {
|
||||
}
|
||||
});
|
||||
|
||||
int status = client.deployArtifact("dom--repo", "com/example/a/1.0/a-1.0.jar",
|
||||
"hello".getBytes(StandardCharsets.UTF_8));
|
||||
ReposiliteSidecarClient.DeployOutcome outcome = client.deployArtifact("dom--repo",
|
||||
"com/example/a/1.0/a-1.0.jar", "hello".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertThat(status, is(200));
|
||||
assertThat(outcome.status(), is(200));
|
||||
assertTrue(outcome.wroteNewContent());
|
||||
assertTrue(methodsSeen.stream().allMatch(m -> m.equals("GET") || m.equals("PUT")));
|
||||
assertThat(methodsSeen.get(methodsSeen.size() - 1), equalTo("PUT"));
|
||||
assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), putBody.get());
|
||||
|
||||
Reference in new issue
Block a user