feat(codeartifact): serve the maven format through a real Reposilite-backed proxy (#4059)

GetRepositoryEndpoint for format=maven now returns a URL real Maven clients
(mvn deploy, mvn dependency:get, Gradle) can publish to and resolve from
directly, backed by a shared Reposilite sidecar container started lazily on
first use. A CodeArtifact repository maps to its own Reposilite repository,
provisioned automatically and never reused even across delete/recreate of a
same-named repository, so a fresh repository can never inherit a previous
one's artifacts.

Adds GetAuthorizationToken (a token scoped to a domain, with the 900-43200s
custom range; 0 falls back to 12 hours) and requires it on every Maven proxy
request, either as the password of HTTP Basic credentials, the form AWS's
Maven guide configures with username aws, or as a Bearer token. Maven
requests are not SigV4-signed, so the region and account come from the token.

Also enforces AWS's 5 GB asset size quota on the Maven endpoint, matching the
existing PublishPackageVersion check. Artifacts do not survive a Floci
restart; the service page documents this as a known limitation.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-22 07:42:05 -05:00
1 parent 06007deea8
commit 0524d156d4
17 files changed
+1525 -11

No files matched your search

@@ -217,6 +217,27 @@ class CodeArtifactIntegrationTest {
.then().statusCode(400).body("__type", equalTo("ValidationException"));
}
@Test
void getAuthorizationTokenReturnsATokenAndExpiration() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/domain?domain=token-domain")
.then().statusCode(200);
given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=token-domain")
.then().statusCode(200)
.body("authorizationToken", notNullValue())
.body("expiration", notNullValue());
given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=does-not-exist")
.then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=token-domain&duration=899")
.then().statusCode(400).body("__type", equalTo("ValidationException"));
}
private static String sha256Hex(byte[] content) {
try {
return SigV4RequestValidator.sha256Hex(content);
@@ -0,0 +1,252 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Runs a real Maven-shaped GET/PUT/HEAD round trip against the shared Reposilite sidecar,
* started by {@link ReposiliteSidecarManager} exactly as in production. Verified separately with
* the real Maven client ({@code mvn deploy:deploy-file} / {@code mvn dependency:get}) by hand;
* this test covers the same round trip plus the concurrent-first-use case in an automated,
* Docker-gated form.
*/
@QuarkusTest
@TestProfile(CodeArtifactMavenSidecarProfile.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CodeArtifactMavenDockerIntegrationTest {
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
private static final String DOMAIN = "maven-sidecar-domain";
private static final String REPO = "maven-sidecar-repo";
private static final String GAV = "com/example/spike/1.0.0/spike-1.0.0.jar";
private static String bearerToken;
@BeforeAll
static void setUp() {
CodeArtifactMavenSidecarProfile.requireDockerAndTheSidecarImage();
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(0)
void createDomainRepositoryAndAuthorizationToken() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/domain?domain=" + DOMAIN)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO)
.then().statusCode(200);
bearerToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=" + DOMAIN)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
}
@Test
@Order(1)
void deployThenFetchRoundTripsTheExactBytes() {
byte[] content = "real-jar-bytes".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + bearerToken).body(content)
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + GAV)
.then().statusCode(200);
byte[] fetched = given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + GAV)
.then().statusCode(200)
.extract().asByteArray();
assertEquals(new String(content, StandardCharsets.UTF_8), new String(fetched, StandardCharsets.UTF_8));
given().header("Authorization", "Bearer " + bearerToken)
.head("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + GAV)
.then().statusCode(200);
}
@Test
@Order(2)
void missingArtifactAndMissingRepositoryAreNotFound() {
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/does/not/exist.jar")
.then().statusCode(404);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/no-such-repo/does/not/exist.jar")
.then().statusCode(404);
}
@Test
@Order(3)
void repositoriesAreIsolatedFromEachOther() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=other-repo")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/other-repo/" + GAV)
.then().statusCode(404);
}
@Test
@Order(4)
void missingOrWrongDomainTokensAreUnauthorized() {
// Challenges as Basic, not Bearer: a real Maven wagon client only retries a 401 with its
// configured settings.xml credentials when the challenge scheme matches what it sent.
given().get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + GAV)
.then().statusCode(401)
.header("WWW-Authenticate", org.hamcrest.Matchers.startsWith("Basic"));
given().header("Authorization", "Bearer not-a-real-token")
.get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + GAV)
.then().statusCode(401);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/domain?domain=other-token-domain")
.then().statusCode(200);
String otherDomainToken = given().header("Authorization", AUTH)
.post("/v1/authorization-token?domain=other-token-domain")
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
given().header("Authorization", "Bearer " + otherDomainToken)
.get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/" + GAV)
.then().statusCode(401);
}
@Test
@Order(5)
void concurrentFirstUseOfANewRepositoryOnlyProvisionsItOnce() throws InterruptedException {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=concurrent-repo")
.then().statusCode(200);
int attempts = 8;
ExecutorService pool = Executors.newFixedThreadPool(attempts);
CountDownLatch ready = new CountDownLatch(attempts);
CountDownLatch go = new CountDownLatch(1);
AtomicInteger successes = new AtomicInteger();
try {
for (int i = 0; i < attempts; i++) {
String gav = "com/example/concurrent/1.0.0/concurrent-" + i + ".jar";
pool.submit(() -> {
ready.countDown();
try {
go.await();
given().header("Authorization", "Bearer " + bearerToken)
.body("x".getBytes(StandardCharsets.UTF_8))
.put("/codeartifact/maven/" + DOMAIN + "/concurrent-repo/" + gav)
.then().statusCode(200);
successes.incrementAndGet();
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
});
}
ready.await(5, TimeUnit.SECONDS);
go.countDown();
} finally {
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS));
}
assertEquals(attempts, successes.get());
for (int i = 0; i < attempts; i++) {
given().header("Authorization", "Bearer " + bearerToken)
.head("/codeartifact/maven/" + DOMAIN + "/concurrent-repo/com/example/concurrent/1.0.0/concurrent-"
+ i + ".jar")
.then().statusCode(200);
}
}
@Test
@Order(6)
void recreatingASameNamedRepositoryDoesNotInheritThePreviousOnesArtifacts() {
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken).body("first-generation".getBytes(StandardCharsets.UTF_8))
.put("/codeartifact/maven/" + DOMAIN + "/reused-name/" + GAV)
.then().statusCode(200);
given().header("Authorization", AUTH)
.delete("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
.then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH).body("{}")
.post("/v1/repository?domain=" + DOMAIN + "&repository=reused-name")
.then().statusCode(200);
given().header("Authorization", "Bearer " + bearerToken)
.get("/codeartifact/maven/" + DOMAIN + "/reused-name/" + GAV)
.then().statusCode(404);
}
@Test
@Order(7)
void aRealMavenClientsBasicAuthCredentialsAreAcceptedWithTheTokenAsThePassword() {
String basic = "Basic " + Base64.getEncoder().encodeToString(("aws:" + bearerToken).getBytes(StandardCharsets.UTF_8));
byte[] content = "basic-auth-bytes".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", basic).body(content)
.put("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/basic/1.0.0/basic-1.0.0.jar")
.then().statusCode(200);
byte[] fetched = given().header("Authorization", basic)
.get("/codeartifact/maven/" + DOMAIN + "/" + REPO + "/com/example/basic/1.0.0/basic-1.0.0.jar")
.then().statusCode(200)
.extract().asByteArray();
assertEquals(new String(content, StandardCharsets.UTF_8), new String(fetched, StandardCharsets.UTF_8));
}
@Test
@Order(8)
void aDomainCreatedInANonDefaultRegionIsServedThroughTheTokensOwnRegionNotTheDefault() {
// The default region here is us-east-1 (application.yml). Every other test in this class
// creates its domain under an AUTH header whose SigV4 scope is also us-east-1, so those
// tests would still pass even if the Maven proxy silently ignored the token's actual
// region and fell back to the default - exactly the bug this test exists to catch.
String nonDefaultRegionAuth =
"AWS4-HMAC-SHA256 Credential=AKID/20260904/us-west-2/codeartifact/aws4_request";
String domain = "maven-sidecar-non-default-region-domain";
given().contentType("application/json").header("Authorization", nonDefaultRegionAuth).body("{}")
.post("/v1/domain?domain=" + domain)
.then().statusCode(200);
given().contentType("application/json").header("Authorization", nonDefaultRegionAuth).body("{}")
.post("/v1/repository?domain=" + domain + "&repository=" + REPO)
.then().statusCode(200);
String token = given().header("Authorization", nonDefaultRegionAuth)
.post("/v1/authorization-token?domain=" + domain)
.then().statusCode(200)
.extract().jsonPath().getString("authorizationToken");
byte[] content = "non-default-region-bytes".getBytes(StandardCharsets.UTF_8);
given().header("Authorization", "Bearer " + token).body(content)
.put("/codeartifact/maven/" + domain + "/" + REPO + "/" + GAV)
.then().statusCode(200);
byte[] fetched = given().header("Authorization", "Bearer " + token)
.get("/codeartifact/maven/" + domain + "/" + REPO + "/" + GAV)
.then().statusCode(200)
.extract().asByteArray();
assertEquals(new String(content, StandardCharsets.UTF_8), new String(fetched, StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,50 @@
package io.github.hectorvent.floci.services.codeartifact;
import io.quarkus.test.junit.QuarkusTestProfile;
import org.eclipse.microprofile.config.ConfigProvider;
import org.junit.jupiter.api.Assumptions;
import java.util.Map;
/**
* Shared by every CodeArtifact integration test that needs the real Reposilite sidecar container,
* started by {@link ReposiliteSidecarManager} exactly as in production. Namespaces the container
* as {@code floci-codeartifact-maven-test-reposilite} so the manager's remove-before-start never
* touches a developer's real running Floci. Needs Docker; skipped without it. Locally it is also
* skipped when the pinned image is not present, so a developer without registry access is not
* stuck; in CI a missing image is a failure, since a vanished tag must not pass silently.
*/
public class CodeArtifactMavenSidecarProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.docker.resource-namespace", "codeartifact-maven-test");
}
public static void requireDockerAndTheSidecarImage() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for CodeArtifact Maven "
+ "sidecar integration tests");
String image = ConfigProvider.getConfig().getValue("floci.services.codeartifact.maven-image", String.class);
Assumptions.assumeTrue(imageUsable(image), "Reposilite sidecar image " + image + " is not present locally");
}
private static boolean isDockerAvailable() {
return run("docker", "version", "--format", "{{.Server.Version}}");
}
private static boolean imageUsable(String image) {
if ("true".equals(System.getenv("CI"))) {
return true;
}
return run("docker", "image", "inspect", image);
}
private static boolean run(String... command) {
try {
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
return process.waitFor() == 0;
} catch (Exception e) {
return false;
}
}
}
@@ -6,6 +6,8 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationToken;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.DomainView;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.ResourcePolicy;
import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.PackageVersionAssetResult;
@@ -21,6 +23,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -28,6 +31,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
@@ -41,11 +45,12 @@ class CodeArtifactServiceTest {
private CodeArtifactService service;
private RegionResolver regionResolver;
private AccountAwareStorageBackend<CodeArtifactRepository> repoStore;
@BeforeEach
void setUp() {
AccountAwareStorageBackend<CodeArtifactDomain> domainStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
AccountAwareStorageBackend<CodeArtifactRepository> repoStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
repoStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
AccountAwareStorageBackend<CodeArtifactPackageVersion> packageVersionStore =
AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
@@ -281,6 +286,53 @@ class CodeArtifactServiceTest {
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void createRepositoryAssignsAFreshMavenRepositoryIdEvenAfterDeleteAndRecreate() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository first = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
assertTrue(first.getMavenRepositoryId() != null && !first.getMavenRepositoryId().isBlank());
service.deleteRepository(REGION, "dom", null, "repo");
CodeArtifactRepository recreated = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
assertTrue(!first.getMavenRepositoryId().equals(recreated.getMavenRepositoryId()),
"a recreated repository must never reuse the previous one's Maven repository id, "
+ "or it would inherit its leftover artifacts");
}
@Test
void ensureMavenRepositoryIdBackfillsALegacyRepositoryMissingOne() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
// Simulates a repository persisted before mavenRepositoryId existed: Jackson would
// deserialize the missing field as null exactly like this.
created.setMavenRepositoryId(null);
repoStore.putForAccount(ACCOUNT_ID, REGION + "::dom::repo", created);
String backfilled = service.ensureMavenRepositoryId(REGION, "dom", null, "repo");
assertTrue(backfilled != null && !backfilled.isBlank());
assertEquals(backfilled, service.describeRepository(REGION, "dom", null, "repo").getMavenRepositoryId());
}
@Test
void ensureMavenRepositoryIdIsIdempotentForAnAlreadyAssignedRepository() {
service.createDomain(REGION, "dom", null, Map.of());
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
String result = service.ensureMavenRepositoryId(REGION, "dom", null, "repo");
assertEquals(created.getMavenRepositoryId(), result);
}
@Test
void ensureMavenRepositoryIdRequiresExistingRepository() {
service.createDomain(REGION, "dom", null, Map.of());
AwsException e = assertThrows(AwsException.class,
() -> service.ensureMavenRepositoryId(REGION, "dom", null, "missing-repo"));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void createRepositoryAcceptsExistingUpstream() {
service.createDomain(REGION, "dom", null, Map.of());
@@ -524,6 +576,59 @@ class CodeArtifactServiceTest {
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
// ---------------------------------------------------- authorization tokens
@Test
void getAuthorizationTokenRequiresExistingDomain() {
AwsException e = assertThrows(AwsException.class,
() -> service.getAuthorizationToken(REGION, "missing-domain", null, null));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void getAuthorizationTokenDefaultsToTwelveHoursAndValidatesForItsDomain() {
service.createDomain(REGION, "dom", null, Map.of());
AuthorizationToken token = service.getAuthorizationToken(REGION, "dom", null, null);
Optional<AuthorizationTokenScope> scope = service.resolveAuthorizationToken(token.token(), "dom");
assertTrue(scope.isPresent());
assertEquals(REGION, scope.get().region());
assertEquals(ACCOUNT_ID, scope.get().owner());
assertTrue(service.resolveAuthorizationToken(token.token(), "other-dom").isEmpty());
assertTrue(service.resolveAuthorizationToken("not-a-real-token", "dom").isEmpty());
assertTrue(service.resolveAuthorizationToken(null, "dom").isEmpty());
}
@Test
void getAuthorizationTokenAcceptsZeroAndTheDocumentedRange() {
service.createDomain(REGION, "dom", null, Map.of());
service.getAuthorizationToken(REGION, "dom", null, 0L);
service.getAuthorizationToken(REGION, "dom", null, 900L);
service.getAuthorizationToken(REGION, "dom", null, 43200L);
}
@Test
void getAuthorizationTokenRejectsDurationsOutsideTheDocumentedRange() {
service.createDomain(REGION, "dom", null, Map.of());
AwsException tooShort = assertThrows(AwsException.class,
() -> service.getAuthorizationToken(REGION, "dom", null, 899L));
assertEquals("ValidationException", tooShort.getErrorCode());
AwsException tooLong = assertThrows(AwsException.class,
() -> service.getAuthorizationToken(REGION, "dom", null, 43201L));
assertEquals("ValidationException", tooLong.getErrorCode());
}
@Test
void clearInvalidatesOutstandingAuthorizationTokens() {
service.createDomain(REGION, "dom", null, Map.of());
AuthorizationToken token = service.getAuthorizationToken(REGION, "dom", null, null);
service.clear();
assertTrue(service.resolveAuthorizationToken(token.token(), "dom").isEmpty());
}
// -------------------------------------------------------- package versions
@Test
@@ -0,0 +1,174 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The wire contract Floci owns towards the Reposilite sidecar: provisioning a repository through
* its {@code maven} settings domain, and deploying/fetching/checking artifacts through it.
* Reposilite's own behaviour (Maven repository semantics) is not re-tested here.
*/
class ReposiliteSidecarClientTest {
private final ObjectMapper mapper = new ObjectMapper();
private final List<String> requestedPaths = new CopyOnWriteArrayList<>();
private final AtomicReference<String> settingsBody = new AtomicReference<>("{\"repositories\":[]}");
private HttpServer server;
private ReposiliteSidecarClient client;
@BeforeEach
void startServer() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.start();
ReposiliteSidecarManager manager = mock(ReposiliteSidecarManager.class);
when(manager.ensureReady()).thenReturn("http://127.0.0.1:" + server.getAddress().getPort());
when(manager.basicAuthHeader()).thenReturn("Basic dGVzdDp0ZXN0");
client = new ReposiliteSidecarClient(manager, mapper);
}
@AfterEach
void stopServer() {
server.stop(0);
}
@Test
void ensureRepositoryCreatesAMissingRepository() throws Exception {
AtomicReference<JsonNode> putBody = new AtomicReference<>();
server.createContext("/api/settings/domain/maven", exchange -> {
requestedPaths.add(exchange.getRequestURI().getPath());
if ("PUT".equals(exchange.getRequestMethod())) {
putBody.set(mapper.readTree(exchange.getRequestBody()));
respond(exchange, 200, "{}");
} else {
respond(exchange, 200, settingsBody.get());
}
});
server.createContext("/api/maven/details/dom--repo/.floci-repository-ready-probe",
exchange -> respond(exchange, 404, "{\"status\":404,\"message\":\"File not found\"}"));
client.ensureRepository("dom--repo");
assertThat(requestedPaths, hasSize(2));
JsonNode created = putBody.get().path("repositories").get(0);
assertThat(created.path("id").asText(), equalTo("dom--repo"));
assertThat(created.path("visibility").asText(), equalTo("PUBLIC"));
assertFalse(created.path("redeployment").asBoolean());
}
@Test
void ensureRepositoryFailsClearlyWhenTheSidecarNeverRecognizesTheNewRepository() {
// Settings accept the repository (200) but the sidecar never actually instantiates it,
// exactly what happens when Reposilite silently rejects an otherwise well-formed entry
// (a repository id over its own 64-character limit was a real case this caught).
server.createContext("/api/settings/domain/maven", exchange -> {
if ("PUT".equals(exchange.getRequestMethod())) {
respond(exchange, 200, "{}");
} else {
respond(exchange, 200, settingsBody.get());
}
});
server.createContext("/api/maven/details/dom--repo/.floci-repository-ready-probe",
exchange -> respond(exchange, 404, "{\"status\":404,\"message\":\"Repository dom--repo not found\"}"));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> client.ensureRepository("dom--repo"));
assertThat(e.getMessage(), containsString("did not become servable"));
}
@Test
void ensureRepositoryIsIdempotentForAnExistingRepository() {
settingsBody.set("{\"repositories\":[{\"id\":\"dom--repo\",\"visibility\":\"PUBLIC\",\"redeployment\":false}]}");
AtomicReference<String> lastMethod = new AtomicReference<>();
server.createContext("/api/settings/domain/maven", exchange -> {
lastMethod.set(exchange.getRequestMethod());
respond(exchange, 200, settingsBody.get());
});
client.ensureRepository("dom--repo");
assertThat(lastMethod.get(), equalTo("GET"));
}
@Test
void deployArtifactPutsTheBytesAndReturnsTheStatus() throws Exception {
AtomicReference<byte[]> received = new AtomicReference<>();
AtomicReference<String> authHeader = new AtomicReference<>();
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> {
authHeader.set(exchange.getRequestHeaders().getFirst("Authorization"));
received.set(exchange.getRequestBody().readAllBytes());
respond(exchange, 200, "");
});
int status = client.deployArtifact("dom--repo", "com/example/a/1.0/a-1.0.jar", "hello".getBytes(StandardCharsets.UTF_8));
assertThat(status, is(200));
assertArrayEquals("hello".getBytes(StandardCharsets.UTF_8), received.get());
assertThat(authHeader.get(), equalTo("Basic dGVzdDp0ZXN0"));
}
@Test
void fetchArtifactReturnsBytesAndContentTypeOnSuccess() {
server.createContext("/dom--repo/com/example/a/1.0/a-1.0.jar", exchange -> {
exchange.getResponseHeaders().set("Content-Type", "application/java-archive");
respond(exchange, 200, "jar-bytes");
});
Optional<ReposiliteSidecarClient.FetchedArtifact> artifact =
client.fetchArtifact("dom--repo", "com/example/a/1.0/a-1.0.jar");
assertTrue(artifact.isPresent());
assertArrayEquals("jar-bytes".getBytes(StandardCharsets.UTF_8), artifact.get().content());
assertThat(artifact.get().contentType(), equalTo("application/java-archive"));
}
@Test
void fetchArtifactIsEmptyOnNotFound() {
server.createContext("/dom--repo/missing.jar", exchange -> respond(exchange, 404, ""));
Optional<ReposiliteSidecarClient.FetchedArtifact> artifact = client.fetchArtifact("dom--repo", "missing.jar");
assertTrue(artifact.isEmpty());
}
@Test
void artifactExistsReflectsAHeadResponse() {
server.createContext("/dom--repo/present.jar", exchange -> respond(exchange, 200, ""));
server.createContext("/dom--repo/absent.jar", exchange -> respond(exchange, 404, ""));
assertTrue(client.artifactExists("dom--repo", "present.jar"));
assertFalse(client.artifactExists("dom--repo", "absent.jar"));
}
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
}
}
@@ -0,0 +1,121 @@
package io.github.hectorvent.floci.services.codeartifact;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
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.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class ReposiliteSidecarManagerTest {
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
private final EmulatorConfig.CodeArtifactServiceConfig codeArtifact = mock(EmulatorConfig.CodeArtifactServiceConfig.class);
private final EmulatorConfig config = config(codeArtifact);
private HttpServer fakeSidecar;
@AfterEach
void stopFakeSidecar() {
if (fakeSidecar != null) {
fakeSidecar.stop(0);
}
}
@Test
void configuredUrlSkipsContainerManagementAndUsesTheConfiguredToken() throws IOException {
String url = startFakeSidecar(200, "{\"status\":\"UP\"}");
when(codeArtifact.mavenUrl()).thenReturn(Optional.of(url));
when(codeArtifact.mavenToken()).thenReturn(Optional.of("alice:s3cr3t"));
ReposiliteSidecarManager manager = manager();
assertEquals(url, manager.ensureReady());
assertThat(manager.basicAuthHeader(), equalTo("Basic " + Base64.getEncoder()
.encodeToString("alice:s3cr3t".getBytes(StandardCharsets.UTF_8))));
verifyNoInteractions(containerBuilder, lifecycleManager);
}
@Test
void configuredUrlWithoutAMatchingTokenFailsFast() {
when(codeArtifact.mavenUrl()).thenReturn(Optional.of("http://reposilite.internal:8080"));
when(codeArtifact.mavenToken()).thenReturn(Optional.empty());
ReposiliteSidecarManager manager = manager();
IllegalStateException e = assertThrows(IllegalStateException.class, manager::ensureReady);
assertThat(e.getMessage(), equalTo(ReposiliteSidecarManager.URL_ENV
+ " is set but the matching token property (name:secret) is missing or malformed."));
}
@Test
void staleManagedEndpointIsDiscardedAndFallsBackToTheConfiguredUrl() throws Exception {
String freshUrl = startFakeSidecar(200, "{\"status\":\"UP\"}");
when(codeArtifact.mavenUrl()).thenReturn(Optional.of(freshUrl));
when(codeArtifact.mavenToken()).thenReturn(Optional.of("alice:s3cr3t"));
ReposiliteSidecarManager manager = manager();
setField(manager, "resolvedUrl", "http://127.0.0.1:1");
setField(manager, "containerId", "stale-reposilite");
assertEquals(freshUrl, manager.ensureReady());
verify(lifecycleManager).stopAndRemove("stale-reposilite", null);
assertNull(getField(manager, "containerId"));
verifyNoInteractions(containerBuilder);
}
private ReposiliteSidecarManager manager() {
return new ReposiliteSidecarManager(containerBuilder, lifecycleManager, config, "unused-managed-secret");
}
private static EmulatorConfig config(EmulatorConfig.CodeArtifactServiceConfig codeArtifact) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
when(config.services()).thenReturn(services);
when(services.codeartifact()).thenReturn(codeArtifact);
return config;
}
private String startFakeSidecar(int status, String healthBody) throws IOException {
fakeSidecar = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
fakeSidecar.createContext("/api/status/health", exchange -> {
byte[] bytes = healthBody.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
});
fakeSidecar.start();
return "http://127.0.0.1:" + fakeSidecar.getAddress().getPort();
}
private static void setField(Object target, String name, Object value) throws Exception {
Field field = target.getClass().getDeclaredField(name);
field.setAccessible(true);
field.set(target, value);
}
private static Object getField(Object target, String name) throws Exception {
Field field = target.getClass().getDeclaredField(name);
field.setAccessible(true);
return field.get(target);
}
}