mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(codeartifact): make npm republish of identical content idempotent (#5163)
Real AWS CodeArtifact documents PublishPackageVersion as idempotent: republishing an existing asset with identical content succeeds. Verdaccio, which backs the npm data plane, and real npm registries reject every republish of an existing version with 409, even for byte-identical content, so Floci inherited that behavior. A PUT to a bare package path is now spooled to a temp file in bounded chunks and scanned as a stream. Each attachment's base64 data is hashed as it passes, and the publish answers 200 without reaching Verdaccio only when every version's integrity matches the stored packument, every dist-tag the publish sends already points where it says, and no attachment is left unaccounted for. Anything else forwards the spooled body unchanged, so Verdaccio's response stays authoritative. Envelope size never has to fit on heap. At most four publishes run this check at once; a publish beyond that waits in a bounded queue, and when the queue is full it is answered 429 with Retry-After.
This commit is contained in:
1 parent
a5db3975c4
commit
2cf011f726
6 files changed
+1372
-44
No files matched your search
+529
-4
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
|
||||
@@ -17,17 +18,32 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -41,6 +57,7 @@ import static org.mockito.Mockito.when;
|
||||
*/
|
||||
class CodeArtifactNpmDataPlaneTest {
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final String DOMAIN = "dom";
|
||||
private static final String REPOSITORY = "repo";
|
||||
private static final String NPM_REPOSITORY_ID = "npm-repo-id-1";
|
||||
@@ -204,6 +221,513 @@ class CodeArtifactNpmDataPlaneTest {
|
||||
assertEquals("{\"name\":\"my-pkg\"}", upstreamBody.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirmed against the exact pinned Verdaccio image that
|
||||
* republishing a just-published, byte-identical tarball comes back {@code 409}, never a
|
||||
* success, unlike real AWS CodeArtifact's own documented idempotent-republish contract (same
|
||||
* rule Maven and PyPI already implement). Verdaccio must never see this PUT at all: the
|
||||
* preflight has to confirm the match and respond itself before ever reaching the backend.
|
||||
*/
|
||||
@Test
|
||||
void aRepublishOfByteIdenticalContentShortCircuitsWithoutReachingTheBackend() throws Exception {
|
||||
byte[] content = "tarball bytes".getBytes(StandardCharsets.UTF_8);
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(500).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
givenStoredVersion(verdaccioManager, null, "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content, Map.of());
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
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(200, response.statusCode());
|
||||
assertEquals(false, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Same finding, the other required half: a version that already exists but with genuinely
|
||||
* different content must still reach the backend and fail the way Verdaccio's own (correctly
|
||||
* strict) check says it should, not be silently treated the same as the identical-content case.
|
||||
*/
|
||||
@Test
|
||||
void aRepublishOfDifferentContentStillForwardsToTheBackendAndItsConflictResponseWins() throws Exception {
|
||||
byte[] existingContent = "old tarball bytes".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] newContent = "new tarball bytes".getBytes(StandardCharsets.UTF_8);
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(409).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
givenStoredVersion(verdaccioManager, null, "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", existingContent, Map.of());
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
|
||||
publishEnvelope("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", newContent));
|
||||
|
||||
assertEquals(409, response.statusCode());
|
||||
assertEquals(true, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* The non-republish baseline: a version Verdaccio has never seen before must always reach the
|
||||
* backend, same as today, since there is nothing yet to compare against.
|
||||
*/
|
||||
@Test
|
||||
void aPublishOfAGenuinelyNewVersionStillForwardsToTheBackend() throws Exception {
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(201).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
|
||||
publishEnvelope("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", "fresh bytes".getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
assertEquals(201, response.statusCode());
|
||||
assertEquals(true, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* The identity used to look up an existing match comes from the URL the publish was sent to,
|
||||
* not the envelope's own {@code name} field. A mismatched body must not be checked against
|
||||
* another package's stored copy; the stub here holds a match for that other package, and the
|
||||
* PUT must still reach the backend.
|
||||
*/
|
||||
@Test
|
||||
void aPublishEnvelopeNameThatDisagreesWithTheUrlIsNotTreatedAsAConfirmableRepublish() throws Exception {
|
||||
byte[] content = "tarball bytes".getBytes(StandardCharsets.UTF_8);
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(201).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
// A match exists for "other-pkg", the envelope's own (wrong) name, but the URL is
|
||||
// publishing to "my-pkg": this must never be consulted for this request at all.
|
||||
givenStoredVersion(verdaccioManager, null, "other-pkg", "1.0.0", "other-pkg-1.0.0.tgz", content, Map.of());
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
|
||||
publishEnvelope("other-pkg", "1.0.0", "other-pkg-1.0.0.tgz", content));
|
||||
|
||||
assertEquals(201, response.statusCode());
|
||||
assertEquals(true, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms the URL-derived identity {@link #aPublishEnvelopeNameThatDisagreesWithTheUrlIsNotTreatedAsAConfirmableRepublish}
|
||||
* relies on actually decodes a scoped package's {@code %2F} correctly: the scope separator
|
||||
* arrives percent-encoded in the URL (Netty leaves it that way specifically so it is never
|
||||
* confused with a real path separator), so this exercises the one, targeted decode that
|
||||
* undoes it.
|
||||
*/
|
||||
@Test
|
||||
void aRepublishOfAScopedPackageWithByteIdenticalContentShortCircuitsWithoutReachingTheBackend() throws Exception {
|
||||
byte[] content = "scoped tarball bytes".getBytes(StandardCharsets.UTF_8);
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(500).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
givenStoredVersion(verdaccioManager, "myscope", "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content, Map.of());
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/@myscope%2Fmy-pkg",
|
||||
"good-token", publishEnvelope("@myscope/my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content));
|
||||
|
||||
assertEquals(200, response.statusCode());
|
||||
assertEquals(false, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* The metadata can claim an integrity the stored bytes do not have, for instance a tarball that
|
||||
* was damaged or lost behind an intact packument. The retry must not be acknowledged on that claim.
|
||||
*/
|
||||
@Test
|
||||
void aRepublishWhoseStoredTarballDoesNotHashToItsIntegrityFallsThroughToTheBackend() throws Exception {
|
||||
byte[] content = "tarball bytes".getBytes(StandardCharsets.UTF_8);
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(409).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
givenStoredVersion(verdaccioManager, null, "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content, Map.of());
|
||||
when(verdaccioManager.storedTarballIntegrity(anyString(), isNull(), eq("my-pkg"), eq("my-pkg-1.0.0.tgz")))
|
||||
.thenReturn(Optional.of("sha512-" + Base64.getEncoder().encodeToString(new byte[64])));
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
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(true, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Every "can't confirm an identical republish" path must fall through to the real backend
|
||||
* rather than short-circuit: malformed JSON, a version whose tarball has no matching attachment,
|
||||
* and a sidecar lookup that fails outright.
|
||||
*/
|
||||
@Test
|
||||
void aPublishThatCannotBeConfirmedAsARepublishFallsThroughToTheBackend() throws Exception {
|
||||
assertForwardedWhenNotConfirmable("not json at all", verdaccioManager -> { });
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPublishWhoseVersionHasNoMatchingAttachmentFallsThroughToTheBackend() throws Exception {
|
||||
String envelopeWithoutAttachment = "{\"name\":\"my-pkg\",\"versions\":{\"1.0.0\":{\"name\":\"my-pkg\","
|
||||
+ "\"version\":\"1.0.0\",\"dist\":{\"tarball\":\"http://ignored/my-pkg-1.0.0.tgz\"}}},"
|
||||
+ "\"_attachments\":{}}";
|
||||
assertForwardedWhenNotConfirmable(envelopeWithoutAttachment, verdaccioManager ->
|
||||
givenStoredVersion(verdaccioManager, null, "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", new byte[0],
|
||||
Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPublishWhoseSidecarLookupFailsFallsThroughToTheBackend() throws Exception {
|
||||
assertForwardedWhenNotConfirmable(
|
||||
publishEnvelope("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", "tarball bytes".getBytes(StandardCharsets.UTF_8)),
|
||||
verdaccioManager -> when(verdaccioManager.fetchPackageDocument(anyString(), isNull(), eq("my-pkg")))
|
||||
.thenThrow(new IllegalStateException("sidecar unreachable")));
|
||||
}
|
||||
|
||||
private void assertForwardedWhenNotConfirmable(String body, Consumer<VerdaccioSidecarManager> arrange)
|
||||
throws Exception {
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(201).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
arrange.accept(verdaccioManager);
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token", body);
|
||||
|
||||
assertEquals(201, response.statusCode());
|
||||
assertEquals(true, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Arranges a package that already exists on the backend: its metadata document (with
|
||||
* {@code storedTags} and one version whose tarball is {@code filename}) and that tarball's bytes.
|
||||
*/
|
||||
private static void givenStoredVersion(VerdaccioSidecarManager verdaccioManager, String namespace, String name,
|
||||
String version, String filename, byte[] storedContent, Map<String, String> storedTags) {
|
||||
when(verdaccioManager.fetchPackageDocument(anyString(), eq(namespace), eq(name)))
|
||||
.thenReturn(Optional.of(storedDocument(name, version, filename, storedContent, storedTags)));
|
||||
when(verdaccioManager.storedTarballIntegrity(anyString(), eq(namespace), eq(name), eq(filename)))
|
||||
.thenReturn(Optional.of(integrity(storedContent)));
|
||||
}
|
||||
|
||||
/**
|
||||
* A publish far beyond any in-memory size still gets the idempotent answer: the envelope is
|
||||
* spooled and hashed as a stream, so its size never has to fit on heap.
|
||||
*/
|
||||
@Test
|
||||
void aLargeIdenticalRepublishIsStillConfirmedAsIdempotent() throws Exception {
|
||||
byte[] content = new byte[70 * 1024 * 1024];
|
||||
new Random(11).nextBytes(content);
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(409).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
givenStoredVersion(verdaccioManager, null, "big-pkg", "1.0.0", "big-pkg-1.0.0.tgz", content, Map.of());
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
HttpResponse response = put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/big-pkg", "good-token",
|
||||
publishEnvelope("big-pkg", "1.0.0", "big-pkg-1.0.0.tgz", content));
|
||||
|
||||
assertEquals(200, response.statusCode());
|
||||
assertEquals(false, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
private static ObjectNode storedDocument(String name, String version, String filename, byte[] content,
|
||||
Map<String, String> storedTags) {
|
||||
ObjectNode document = JSON.createObjectNode();
|
||||
document.put("name", name);
|
||||
ObjectNode tags = document.putObject("dist-tags");
|
||||
storedTags.forEach(tags::put);
|
||||
ObjectNode dist = document.putObject("versions").putObject(version).putObject("dist");
|
||||
dist.put("tarball", "http://ignored/" + filename);
|
||||
dist.put("integrity", integrity(content));
|
||||
return document;
|
||||
}
|
||||
|
||||
private static String integrity(byte[] content) {
|
||||
try {
|
||||
return "sha512-" + Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-512").digest(content));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private HttpResponse putUnchecked(String path, String body) {
|
||||
try {
|
||||
return put(path, "good-token", body);
|
||||
} catch (Exception e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Four publishes hold their preflight permits while blocked in the sidecar lookup. A fifth
|
||||
* identical publish must wait for one rather than bypass the check: bypassing would send it
|
||||
* straight to Verdaccio, which answers 409 for an existing version, so the same republish would
|
||||
* succeed or fail depending on load. The upstream answers 409 so that a bypass would show up.
|
||||
*/
|
||||
@Test
|
||||
void aPublishArrivingWhilePreflightsAreFullWaitsForAPermitInsteadOfBypassingTheCheck() throws Exception {
|
||||
byte[] content = "tarball bytes".getBytes(StandardCharsets.UTF_8);
|
||||
String envelope = publishEnvelope("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content);
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(409).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
CountDownLatch entered = new CountDownLatch(4);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
ObjectNode document = storedDocument("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content, Map.of());
|
||||
when(verdaccioManager.storedTarballIntegrity(anyString(), isNull(), eq("my-pkg"), eq("my-pkg-1.0.0.tgz")))
|
||||
.thenReturn(Optional.of(integrity(content)));
|
||||
when(verdaccioManager.fetchPackageDocument(anyString(), isNull(), eq("my-pkg"))).thenAnswer(invocation -> {
|
||||
entered.countDown();
|
||||
release.await(5, TimeUnit.SECONDS);
|
||||
return Optional.of(document);
|
||||
});
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
String path = "/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg";
|
||||
ExecutorService pool = Executors.newFixedThreadPool(5);
|
||||
try {
|
||||
List<CompletableFuture<HttpResponse>> held = new ArrayList<>();
|
||||
for (int i = 0; i < 4; i++) {
|
||||
held.add(CompletableFuture.supplyAsync(() -> putUnchecked(path, envelope), pool));
|
||||
}
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
CompletableFuture<HttpResponse> overflow = CompletableFuture.supplyAsync(
|
||||
() -> putUnchecked(path, envelope), pool);
|
||||
|
||||
assertThrows(TimeoutException.class, () -> overflow.get(300, TimeUnit.MILLISECONDS));
|
||||
release.countDown();
|
||||
|
||||
for (CompletableFuture<HttpResponse> response : held) {
|
||||
assertEquals(200, response.get(10, TimeUnit.SECONDS).statusCode());
|
||||
}
|
||||
assertEquals(200, overflow.get(10, TimeUnit.SECONDS).statusCode());
|
||||
assertEquals(false, upstreamReceivedPut.get());
|
||||
} finally {
|
||||
release.countDown();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
private static String publishEnvelope(String name, String version, String filename, byte[] content) {
|
||||
return publishEnvelopeWithDistTags(name, version, filename, content, null);
|
||||
}
|
||||
|
||||
private static String publishEnvelopeWithDistTags(String name, String version, String filename, byte[] content,
|
||||
String distTagsJson) {
|
||||
String base64Content = Base64.getEncoder().encodeToString(content);
|
||||
String distTags = distTagsJson == null ? "" : ",\"dist-tags\":" + distTagsJson;
|
||||
return "{\"name\":\"" + name + "\",\"versions\":{\"" + version + "\":{\"name\":\"" + name
|
||||
+ "\",\"version\":\"" + version + "\",\"dist\":{\"tarball\":\"http://ignored/" + filename
|
||||
+ "\",\"integrity\":\"" + integrity(content) + "\"}}}" + distTags + ",\"_attachments\":{\"" + filename
|
||||
+ "\":{\"content_type\":\"application/octet-stream\","
|
||||
+ "\"data\":\"" + base64Content + "\",\"length\":" + content.length + "}}}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Republishes byte-identical content whose envelope sends {@code distTagsJson}, against a
|
||||
* package whose tags Verdaccio already has as {@code storedTags}. The backend always answers 409
|
||||
* so a fall-through is visible as that response, and a short-circuit as no PUT reaching it.
|
||||
*/
|
||||
private HttpResponse republishWithDistTags(String distTagsJson, Map<String, String> storedTags,
|
||||
AtomicReference<Boolean> upstreamReceivedPut) throws Exception {
|
||||
byte[] content = "tarball bytes".getBytes(StandardCharsets.UTF_8);
|
||||
upstream = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (request.method() == HttpMethod.PUT) {
|
||||
upstreamReceivedPut.set(true);
|
||||
}
|
||||
request.response().setStatusCode(409).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
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);
|
||||
VerdaccioSidecarManager verdaccioManager = mock(VerdaccioSidecarManager.class);
|
||||
when(verdaccioManager.ensureReady(eq(NPM_REPOSITORY_ID), anyString()))
|
||||
.thenReturn("http://127.0.0.1:" + upstream.actualPort());
|
||||
givenStoredVersion(verdaccioManager, null, "my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content, storedTags);
|
||||
startDataPlane(service, verdaccioManager);
|
||||
|
||||
return put("/codeartifact/npm/" + DOMAIN + "/" + REPOSITORY + "/my-pkg", "good-token",
|
||||
publishEnvelopeWithDistTags("my-pkg", "1.0.0", "my-pkg-1.0.0.tgz", content, distTagsJson));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRepublishWhoseTagsAlreadyPointWhereItSendsThemStillShortCircuits() throws Exception {
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
HttpResponse response = republishWithDistTags("{\"latest\":\"1.0.0\"}", Map.of("latest", "1.0.0"),
|
||||
upstreamReceivedPut);
|
||||
|
||||
assertEquals(200, response.statusCode());
|
||||
assertEquals(false, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRepublishThatWouldMoveATagToAnotherVersionFallsThroughToTheBackend() throws Exception {
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
HttpResponse response = republishWithDistTags("{\"latest\":\"1.0.0\"}", Map.of("latest", "0.9.0"),
|
||||
upstreamReceivedPut);
|
||||
|
||||
assertEquals(409, response.statusCode());
|
||||
assertEquals(true, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRepublishThatAddsATagTheServerDoesNotHaveYetFallsThroughToTheBackend() throws Exception {
|
||||
AtomicReference<Boolean> upstreamReceivedPut = new AtomicReference<>(false);
|
||||
HttpResponse response = republishWithDistTags("{\"beta\":\"1.0.0\"}", Map.of("latest", "1.0.0"),
|
||||
upstreamReceivedPut);
|
||||
|
||||
assertEquals(409, response.statusCode());
|
||||
assertEquals(true, upstreamReceivedPut.get());
|
||||
}
|
||||
|
||||
private void startDataPlane(CodeArtifactService service, VerdaccioSidecarManager verdaccioManager)
|
||||
throws Exception {
|
||||
startDataPlane(service, verdaccioManager, true);
|
||||
@@ -211,12 +735,13 @@ class CodeArtifactNpmDataPlaneTest {
|
||||
|
||||
private void startDataPlane(CodeArtifactService service, VerdaccioSidecarManager verdaccioManager,
|
||||
boolean codeArtifactEnabled) throws Exception {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
when(verdaccioManager.publicUrl(DOMAIN, REPOSITORY)).thenReturn("http://localhost:4566/codeartifact/npm/"
|
||||
+ DOMAIN + "/" + REPOSITORY + "/");
|
||||
ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class);
|
||||
when(serviceConfigAccess.isEnabled("codeartifact")).thenReturn(codeArtifactEnabled);
|
||||
Router router = Router.router(vertx);
|
||||
new CodeArtifactNpmDataPlane(service, verdaccioManager, serviceConfigAccess, config, vertx).register(router);
|
||||
new CodeArtifactNpmDataPlane(service, verdaccioManager, serviceConfigAccess, vertx, new ObjectMapper())
|
||||
.register(router);
|
||||
dataPlane = vertx.createHttpServer().requestHandler(router)
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
|
||||
+25
-8
@@ -123,8 +123,25 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
assertArrayEquals(expectedTarballBytes, fetchedTarball);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirmed against this exact pinned Verdaccio image that
|
||||
* republishing a just-published, byte-identical tarball comes back {@code 409 "this package
|
||||
* is already present"} on its own, never a success, unlike real AWS CodeArtifact's own
|
||||
* documented idempotent-republish contract (the same rule Maven and PyPI already implement).
|
||||
* Republishing the identical fixture a second time against the real sidecar must still
|
||||
* succeed.
|
||||
*/
|
||||
@Test
|
||||
@Order(2)
|
||||
void republishingTheSameEnvelopeASecondTimeIsStillIdempotent() {
|
||||
given().header("Authorization", "Bearer " + bearerToken).contentType("application/json")
|
||||
.body(publishFixture)
|
||||
.put("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
|
||||
.then().statusCode(anyOf201Or200());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void missingPackageAndMissingRepositoryAreNotFound() {
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/does-not-exist")
|
||||
@@ -136,7 +153,7 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
@Order(4)
|
||||
void repositoriesAreIsolatedFromEachOther() {
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=other-repo")
|
||||
@@ -148,7 +165,7 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
@Order(5)
|
||||
void missingOrWrongDomainTokensAreUnauthorized() {
|
||||
given().get("/codeartifact/npm/" + DOMAIN + "/" + REPO + "/" + PACKAGE_NAME)
|
||||
.then().statusCode(401)
|
||||
@@ -172,7 +189,7 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
@Order(6)
|
||||
void concurrentFirstUseOfANewRepositoryOnlyStartsOneContainer() throws InterruptedException {
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=concurrent-repo")
|
||||
@@ -208,7 +225,7 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
@Order(7)
|
||||
void recreatingASameNamedRepositoryDoesNotInheritThePreviousOnesPackages() {
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
|
||||
@@ -231,7 +248,7 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
@Order(8)
|
||||
void aDomainCreatedInANonDefaultRegionIsServedThroughTheTokensOwnRegion() {
|
||||
String nonDefaultRegionAuth =
|
||||
"AWS4-HMAC-SHA256 Credential=AKID/20260904/us-west-2/codeartifact/aws4_request";
|
||||
@@ -259,7 +276,7 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
@Order(9)
|
||||
void aDomainCreatedUnderANonDefaultAccountIsServedThroughTheTokensOwnAccount() {
|
||||
String otherAccountAuth = "AWS4-HMAC-SHA256 Credential=111122223333/20260904/us-east-1/codeartifact/aws4_request";
|
||||
String domain = "npm-sidecar-cross-account-domain";
|
||||
@@ -293,7 +310,7 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
* already confirmed is really there, through the real sidecar, not a mock.
|
||||
*/
|
||||
@Test
|
||||
@Order(9)
|
||||
@Order(10)
|
||||
void getPackageVersionAssetBridgesToTheRealVerdaccioSidecar() throws IOException {
|
||||
byte[] fetched = given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version/asset?domain=" + DOMAIN + "&repository=" + REPO + "&format=npm"
|
||||
@@ -305,7 +322,7 @@ class CodeArtifactNpmDockerIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
@Order(10)
|
||||
void getPackageVersionAssetReturns404ForAnNpmAssetThatWasNeverPublished() {
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version/asset?domain=" + DOMAIN + "&repository=" + REPO + "&format=npm"
|
||||
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
package io.github.hectorvent.floci.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class NpmPublishEnvelopeScannerTest {
|
||||
|
||||
@Test
|
||||
void theRealPublishFixtureHashesToItsOwnDistIntegrity() throws Exception {
|
||||
Path fixture = Path.of("src/test/resources/codeartifact/npm-publish-fixture.json");
|
||||
JsonNode raw = new ObjectMapper().readTree(Files.readAllBytes(fixture));
|
||||
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = NpmPublishEnvelopeScanner.scan(Files.newInputStream(fixture));
|
||||
|
||||
assertEquals("floci-verdaccio-spike", envelope.name());
|
||||
assertEquals(Map.of("latest", "1.0.0"), envelope.distTags());
|
||||
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));
|
||||
}
|
||||
|
||||
@Test
|
||||
void escapesInTrackedValuesAreDecoded() throws Exception {
|
||||
String json = "{\"name\":\"my\\u002dpkg\",\"versions\":{}}";
|
||||
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = scan(json);
|
||||
|
||||
assertEquals("my-pkg", envelope.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachmentDataIsHashedAcrossAStreamOfAnyLength() throws Exception {
|
||||
byte[] tarball = new byte[3 * 1024 * 1024 + 1];
|
||||
new Random(7).nextBytes(tarball);
|
||||
String json = "{\"_attachments\":{\"a.tgz\":{\"data\":\"" + Base64.getEncoder().encodeToString(tarball)
|
||||
+ "\"}}}";
|
||||
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = scan(json);
|
||||
|
||||
assertEquals("sha512-" + Base64.getEncoder().encodeToString(sha512(tarball)),
|
||||
envelope.attachmentIntegrity().get("a.tgz"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAttachmentLargerThanTheStringLimitStillStreamsThroughTheDigest() throws Exception {
|
||||
byte[] tarball = new byte[30 * 1024 * 1024];
|
||||
new Random(9).nextBytes(tarball);
|
||||
String json = "{\"_attachments\":{\"big.tgz\":{\"data\":\"" + Base64.getEncoder().encodeToString(tarball)
|
||||
+ "\"}}}";
|
||||
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = scan(json);
|
||||
|
||||
assertEquals("sha512-" + Base64.getEncoder().encodeToString(sha512(tarball)),
|
||||
envelope.attachmentIntegrity().get("big.tgz"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUntrackedStringOfAnySizeIsSkippedAndTheTrackedFieldsAfterItStillRead() throws Exception {
|
||||
String huge = "a".repeat(25 * 1024 * 1024);
|
||||
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = scan("{\"readme\":\"" + huge + "\",\"name\":\"a\"}");
|
||||
|
||||
assertEquals("a", envelope.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrackedStringBeyondTheLimitIsRejected() {
|
||||
assertInvalid("{\"name\":\"" + "a".repeat(2 * 1024 * 1024) + "\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void untrackedStringsAreSkippedWithoutBeingKept() throws Exception {
|
||||
String json = "{\"readme\":\"anything \\\" at all\",\"versions\":{}}";
|
||||
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = scan(json);
|
||||
|
||||
assertNull(envelope.name());
|
||||
assertEquals(Map.of(), envelope.versions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateKeysAreRejected() {
|
||||
assertInvalid("{\"name\":\"a\",\"name\":\"b\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void base64WithAnInvalidCharacterIsRejected() {
|
||||
assertInvalid("{\"_attachments\":{\"a.tgz\":{\"data\":\"ab!d\"}}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void base64WhoseLengthIsNotAMultipleOfFourIsRejected() {
|
||||
assertInvalid("{\"_attachments\":{\"a.tgz\":{\"data\":\"abcde\"}}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachmentDataContainingAnEscapeIsRejected() {
|
||||
assertInvalid("{\"_attachments\":{\"a.tgz\":{\"data\":\"ab\\/cd\"}}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void trailingGarbageAfterTheEnvelopeIsRejected() {
|
||||
assertInvalid("{\"name\":\"a\"} extra");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnrecognizedLiteralIsRejected() {
|
||||
assertInvalid("{\"readme\":tru}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestingDeeperThanTheLimitIsRejected() {
|
||||
String json = "{\"x\":" + "[".repeat(40) + "]".repeat(40) + "}";
|
||||
|
||||
assertInvalid(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonStringDistTagIsRejectedRatherThanDropped() {
|
||||
assertInvalid("{\"dist-tags\":{\"latest\":1}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonStringNameIsRejected() {
|
||||
assertInvalid("{\"name\":null}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aValidNumberLongerThanAnyFixedLimitIsAccepted() throws Exception {
|
||||
String digits = "1".repeat(100_000);
|
||||
|
||||
NpmPublishEnvelopeScanner.Envelope envelope = scan("{\"readme\":" + digits + ".5e-10,\"name\":\"a\"}");
|
||||
|
||||
assertEquals("a", envelope.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedNumberIsRejected() {
|
||||
assertInvalid("{\"readme\":1.}");
|
||||
assertInvalid("{\"readme\":01}");
|
||||
assertInvalid("{\"readme\":-}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonObjectEnvelopeIsRejected() {
|
||||
assertInvalid("[1,2,3]");
|
||||
}
|
||||
|
||||
private static NpmPublishEnvelopeScanner.Envelope scan(String json) throws IOException {
|
||||
InputStream in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
|
||||
return NpmPublishEnvelopeScanner.scan(in);
|
||||
}
|
||||
|
||||
private static void assertInvalid(String json) {
|
||||
assertThrows(IOException.class, () -> scan(json));
|
||||
}
|
||||
|
||||
private static byte[] sha512(byte[] bytes) throws Exception {
|
||||
return MessageDigest.getInstance("SHA-512").digest(bytes);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user