diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeArtifactTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeArtifactTest.java index 26dd037761..c75aed6eb0 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeArtifactTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeArtifactTest.java @@ -12,6 +12,7 @@ import software.amazon.awssdk.services.codeartifact.model.Tag; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.time.Instant; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -84,6 +85,32 @@ class CodeArtifactTest { }); } + @Test + @Order(12) + @DisplayName("GetAuthorizationToken - returns a bearer token and a future expiration") + void getAuthorizationTokenReturnsATokenAndExpiration() { + GetAuthorizationTokenResponse resp = codeArtifact.getAuthorizationToken(r -> r.domain(DOMAIN)); + + assertThat(resp.authorizationToken()).isNotBlank(); + assertThat(resp.expiration()).isAfter(Instant.now()); + } + + @Test + @Order(13) + @DisplayName("GetAuthorizationToken - fails against a domain that does not exist") + void getAuthorizationTokenMissingDomainFails() { + assertThatThrownBy(() -> codeArtifact.getAuthorizationToken(r -> r.domain("does-not-exist-domain"))) + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + @Order(14) + @DisplayName("GetAuthorizationToken - rejects a duration outside 0 or 900-43200") + void getAuthorizationTokenRejectsAnInvalidDuration() { + assertThatThrownBy(() -> codeArtifact.getAuthorizationToken(r -> r.domain(DOMAIN).durationSeconds(60L))) + .isInstanceOf(ValidationException.class); + } + @Test @Order(20) @DisplayName("CreateRepository - fails against a domain that does not exist") diff --git a/docs/services/codeartifact.md b/docs/services/codeartifact.md index aa44c60f12..4ad044867b 100644 --- a/docs/services/codeartifact.md +++ b/docs/services/codeartifact.md @@ -5,9 +5,11 @@ **Endpoint:** `http://localhost:4566` Floci supports the CodeArtifact control plane: domains, repositories, resource policies, tags, -and public upstream (external) connections. Package publish/fetch is implemented for the -`generic` format only, matching AWS's own restriction that `PublishPackageVersion` accepts only -`generic`; the other formats (npm, PyPI, Maven, NuGet, etc.) have no real package-manager-protocol +and public upstream (external) connections. Package publish/fetch through the CodeArtifact API +itself is implemented for the `generic` format only, matching AWS's own restriction that +`PublishPackageVersion` accepts only `generic`. The `maven` format is served through its own real +package-manager-protocol proxy (`mvn`/Gradle publish and resolve both work against the URL +`GetRepositoryEndpoint` returns); the remaining formats (npm, PyPI, NuGet, etc.) have no real proxy behind them yet. ## Supported Actions @@ -19,6 +21,7 @@ proxy behind them yet. | `DeleteDomain` | Deletes a domain; fails with `ConflictException` while it still contains repositories, and with `ResourceNotFoundException` for a missing domain (as AWS does, although the API reference does not list it). | | `DescribeDomain` | Returns a domain's full description, including its repository count. | | `ListDomains` | Lists domain summaries for the account and Region, paginated. | +| `GetAuthorizationToken` | Issues a bearer token scoped to a domain, valid for 0 (12 hours) or 900-43200 seconds, required by the `maven` repository endpoint. | | `PutDomainPermissionsPolicy` | Attaches or replaces a domain's resource policy, versioned by `policyRevision`. | | `GetDomainPermissionsPolicy` | Returns a domain's current resource policy and revision. | | `DeleteDomainPermissionsPolicy` | Removes a domain's resource policy, optionally checked against `policyRevision`. | @@ -65,6 +68,30 @@ the bytes Floci actually received, not echoed from the request. Floci enforces A quotas for this action: a 5 GB max asset file size and a 350-asset cap per package version, both returning `ServiceQuotaExceededException`. +## The Maven repository endpoint + +`GetRepositoryEndpoint` for `format=maven` returns `http://localhost:4566/codeartifact/maven///`. +Real Maven clients (`mvn deploy`, `mvn dependency:get`, Gradle) can publish to and resolve from +that URL directly, the same way they would against real AWS CodeArtifact; it speaks the raw Maven +repository layout (GET/PUT/HEAD over a group/artifact/version path), not the CodeArtifact JSON API. +Every request needs a token from `GetAuthorizationToken` scoped to the domain being accessed, +either as `Authorization: Bearer ` or as HTTP Basic with the token as the password (the +username is ignored). Basic is what a real `settings.xml`, configured the way +[AWS documents for `mvn`](https://docs.aws.amazon.com/codeartifact/latest/ug/maven-mvn.html) +(`aws${env.CODEARTIFACT_AUTH_TOKEN}`), +actually sends: Maven's HTTP wagon authenticates with Basic, not a custom header. A missing, +invalid, expired, or wrong-domain token gets a 401 challenging `Basic`. + +It is backed by a shared [Reposilite](https://reposilite.com) container that Floci starts lazily +on first use and reuses for every CodeArtifact repository; a CodeArtifact repository maps to its +own Reposilite repository, provisioned automatically the first time it is published to or fetched +from, and identified internally by a fresh id generated at `CreateRepository` time rather than a +name derived from the domain/repository, so a repository deleted and recreated under the same name +never inherits the previous one's artifacts. Two config knobs, +`FLOCI_SERVICES_CODEARTIFACT_MAVEN_IMAGE` and `FLOCI_SERVICES_CODEARTIFACT_MAVEN_URL`, pin the +image version or point at an already-running instance and skip container management, matching the +pattern used elsewhere in Floci for sidecars. + ## AWS-compatible failures Domain and repository names, tags, pagination, duplicate names, missing upstreams, policy-revision @@ -99,11 +126,35 @@ state. `DisposePackageVersions`, and `UpdatePackageVersionsStatus` don't exist yet; the only way to move a version from `Unfinished` to `Published` today is a follow-up `PublishPackageVersion` call that omits the `unfinished` flag. -- **The 5 GB asset size quota is nominal.** `PublishPackageVersion` receives the request body as - a single byte array before Floci ever checks its length, so a request already large enough to - exhaust available heap fails before the quota check runs. The `ServiceQuotaExceededException` - behavior is correct for anything that does fit in memory; it is not itself a streaming size - limit. +- **The 5 GB asset size quota is nominal.** `PublishPackageVersion` and the Maven repository + endpoint both receive the request body as a single byte array before Floci ever checks its + length, so a request already large enough to exhaust available heap fails before the quota check + runs. The rejection (`ServiceQuotaExceededException` from `PublishPackageVersion`, HTTP 413 from + the Maven endpoint) is correct for anything that does fit in memory; it is not itself a streaming + size limit. +- **Deleting a CodeArtifact repository does not remove its Maven artifacts.** The backing + Reposilite repository and everything published to it are left behind (though never reused: see + above); only the CodeArtifact-side metadata is deleted. This wastes storage inside the sidecar + container over a long-running Floci process but is otherwise inert, since a deleted repository's + endpoint already returns 404 through the proxy regardless of what Reposilite still holds. +- **Maven artifacts do not survive a Floci restart, even under persistent storage.** The Reposilite + sidecar container has no volume attached and is removed on shutdown along with everything + published to it. CodeArtifact repository/domain metadata (including the stored + `mavenRepositoryId`) survives a restart the same way any other Floci state does under persistent + storage mode; the artifacts themselves do not, so the first Maven request after a restart + re-provisions an empty Reposilite repository and returns 404 for anything published before the + restart. +- **`GetAuthorizationToken` tokens are not revocable and are not tied to any IAM identity.** Real + CodeArtifact tokens are scoped to the calling principal's permissions; Floci's are scoped only to + the domain named in the request; anyone who obtains one keeps the same domain-scoped access for + its full lifetime. +- **The Maven repository endpoint does not resolve through upstream repositories or external + connections.** On real CodeArtifact, a repository with another repository configured as an + upstream (`UpdateRepository`'s `upstreams`) or with an `AssociateExternalConnection` to a public + repository (`public:maven-central`, etc.) serves packages from those sources too, not just its + own. Floci's Maven proxy only ever looks up the repository's own backing storage: a package that + exists solely in an upstream, or only through an external connection, returns 404 through a + repository that has it configured as one. See the [CodeArtifact API Reference](https://docs.aws.amazon.com/codeartifact/latest/APIReference/Welcome.html). @@ -112,3 +163,6 @@ See the [CodeArtifact API Reference](https://docs.aws.amazon.com/codeartifact/la | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_CODEARTIFACT_ENABLED` | `true` | Enable or disable CodeArtifact | +| `FLOCI_SERVICES_CODEARTIFACT_MAVEN_IMAGE` | `dzikoysk/reposilite:3.6.3` | Reposilite image used to serve the `maven` format | +| `FLOCI_SERVICES_CODEARTIFACT_MAVEN_URL` | unset | When set, use this URL and skip Reposilite container management | +| `FLOCI_SERVICES_CODEARTIFACT_MAVEN_TOKEN` | unset | `name:secret` access token for a pre-configured `MAVEN_URL` | diff --git a/docs/services/index.md b/docs/services/index.md index dff2c106fc..2f5a48ce00 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -119,7 +119,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 | | [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 | | [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 | -| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package/version*`, `/v1/tag*` | REST JSON | 25 | +| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*` | REST JSON | 26 | | [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 | | [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 25 | | [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 18 | diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index c712122066..7d94f7d675 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -803,6 +803,15 @@ public interface EmulatorConfig { interface CodeArtifactServiceConfig { @WithDefault("true") boolean enabled(); + + /** When set, Floci uses this URL and skips Reposilite sidecar container management. */ + Optional mavenUrl(); + + /** {@code name:secret} access token for a pre-configured {@link #mavenUrl()}. */ + Optional mavenToken(); + + @WithDefault("dzikoysk/reposilite:3.6.3") + String mavenImage(); } interface ConnectServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java index eba721b01f..f8d1bbe01f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactController.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationToken; import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.DomainView; import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.PackageVersionAssetResult; import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.PublishPackageVersionResult; @@ -101,6 +102,32 @@ public class CodeArtifactController { return ok(response); } + @POST + @Path("/v1/authorization-token") + @Consumes(MediaType.WILDCARD) + public Response getAuthorizationToken(@Context HttpHeaders headers, @QueryParam("domain") String domain, + @QueryParam("domain-owner") String domainOwner, + @QueryParam("duration") String durationSeconds) { + String region = regionResolver.resolveRegion(headers); + AuthorizationToken token = service.getAuthorizationToken(region, domain, domainOwner, + parseDuration(durationSeconds)); + ObjectNode response = objectMapper.createObjectNode(); + response.put("authorizationToken", token.token()); + response.put("expiration", token.expirationEpochSeconds()); + return ok(response); + } + + private static Long parseDuration(String value) { + if (value == null || value.isBlank()) { + return null; + } + try { + return Long.parseLong(value); + } catch (NumberFormatException e) { + throw new AwsException("ValidationException", "duration must be an integer.", 400); + } + } + @PUT @Path("/v1/domain/permissions/policy") public Response putDomainPermissionsPolicy(@Context HttpHeaders headers, String body) { diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenController.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenController.java new file mode 100644 index 0000000000..6b946b17d7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenController.java @@ -0,0 +1,140 @@ +package io.github.hectorvent.floci.services.codeartifact; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.codeartifact.CodeArtifactService.AuthorizationTokenScope; +import io.github.hectorvent.floci.services.codeartifact.ReposiliteSidecarClient.FetchedArtifact; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.HEAD; +import jakarta.ws.rs.NotAuthorizedException; +import jakarta.ws.rs.NotFoundException; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Optional; + +/** + * Serves the real Maven repository wire protocol behind the URL {@code GetRepositoryEndpoint} + * returns for the {@code maven} format: plain GET/PUT/HEAD over a GAV path, not a CodeArtifact + * API action. Backed by the shared Reposilite sidecar; a CodeArtifact repository maps to its own + * Reposilite repository, provisioned on first use. + * + *

Requires the bearer token real CodeArtifact requires here, obtained from + * {@code GetAuthorizationToken} and scoped to the domain being accessed. Accepted either as + * {@code Authorization: Bearer } or as HTTP Basic with the token as the password (any + * username): AWS's own documented {@code settings.xml} configuration for {@code mvn} + * (Use CodeArtifact + * with mvn) sets a {@code aws...}, which Maven's HTTP + * wagon sends as Basic, not Bearer. + * + *

A Maven request carries no SigV4 {@code Authorization} header, so there is no account or + * Region to resolve from it the way the CodeArtifact JSON API does; the token itself supplies + * both, since it was issued under a specific account and Region. + */ +@Path("/codeartifact/maven/{domain}/{repository}/{gav:.+}") +public class CodeArtifactMavenController { + + private static final String BEARER_PREFIX = "Bearer "; + private static final String BASIC_PREFIX = "Basic "; + + private final CodeArtifactService service; + private final ReposiliteSidecarClient reposilite; + + @Inject + public CodeArtifactMavenController(CodeArtifactService service, ReposiliteSidecarClient reposilite) { + this.service = service; + this.reposilite = reposilite; + } + + @PUT + @Consumes(MediaType.WILDCARD) + public Response deploy(@Context HttpHeaders headers, @PathParam("domain") String domain, + @PathParam("repository") String repository, @PathParam("gav") String gav, + byte[] body) { + byte[] content = body != null ? body : new byte[0]; + // Same 5 GB AWS quota PublishPackageVersion enforces, and just as nominal: RESTEasy + // Reactive has already buffered the full body into this byte[] before the method runs, so + // this rejects anything that made it this far rather than bounding memory use upfront. + if (content.length > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) { + return Response.status(413).build(); + } + String repoId = requireRepositoryId(headers, domain, repository); + int status = reposilite.deployArtifact(repoId, gav, content); + return Response.status(status).build(); + } + + @GET + @Produces(MediaType.WILDCARD) + public Response fetch(@Context HttpHeaders headers, @PathParam("domain") String domain, + @PathParam("repository") String repository, @PathParam("gav") String gav) { + String repoId = requireRepositoryId(headers, domain, repository); + return reposilite.fetchArtifact(repoId, gav) + .map(this::toResponse) + .orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build()); + } + + @HEAD + public Response head(@Context HttpHeaders headers, @PathParam("domain") String domain, + @PathParam("repository") String repository, @PathParam("gav") String gav) { + String repoId = requireRepositoryId(headers, domain, repository); + return reposilite.artifactExists(repoId, gav) + ? Response.ok().build() + : Response.status(Response.Status.NOT_FOUND).build(); + } + + private Response toResponse(FetchedArtifact artifact) { + return Response.ok(artifact.content(), artifact.contentType()).build(); + } + + private String requireRepositoryId(HttpHeaders headers, String domain, String repository) { + String token = extractToken(headers); + AuthorizationTokenScope scope = service.resolveAuthorizationToken(token, domain) + .orElseThrow(() -> new NotAuthorizedException("Basic realm=\"floci-codeartifact\"")); + String repoId; + try { + repoId = service.ensureMavenRepositoryId(scope.region(), domain, scope.owner(), repository); + } catch (AwsException e) { + throw new NotFoundException(); + } + reposilite.ensureRepository(repoId); + return repoId; + } + + /** + * {@code null} when neither scheme is present, malformed, or the Basic credentials have no + * password field; {@link CodeArtifactService#resolveAuthorizationToken} treats a null token + * the same as any other invalid one. + */ + private static String extractToken(HttpHeaders headers) { + String authorization = headers.getHeaderString(HttpHeaders.AUTHORIZATION); + if (authorization == null) { + return null; + } + if (authorization.startsWith(BEARER_PREFIX)) { + return authorization.substring(BEARER_PREFIX.length()); + } + if (authorization.startsWith(BASIC_PREFIX)) { + return passwordFromBasicCredentials(authorization.substring(BASIC_PREFIX.length())); + } + return null; + } + + private static String passwordFromBasicCredentials(String base64Credentials) { + try { + String decoded = new String(Base64.getDecoder().decode(base64Credentials), StandardCharsets.UTF_8); + int separator = decoded.indexOf(':'); + return separator >= 0 ? decoded.substring(separator + 1) : null; + } catch (IllegalArgumentException e) { + return null; + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java index 461bfad89f..6c57906601 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactService.java @@ -30,8 +30,10 @@ import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.time.Instant; import java.util.ArrayList; +import java.util.Base64; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; @@ -74,16 +76,25 @@ public class CodeArtifactService implements Resettable { // containing '\r'/'\n' would be echoed back verbatim in the X-AssetName response header. private static final Pattern ASSET_NAME = Pattern.compile("\\P{C}+"); private static final List ASSET_HASH_ALGORITHMS = List.of("MD5", "SHA-1", "SHA-256", "SHA-512"); - private static final long MAX_ASSET_FILE_SIZE_BYTES = 5L * 1024 * 1024 * 1024; + // Package-private: reused by CodeArtifactMavenController so the Maven proxy enforces the same + // documented 5 GB AWS quota rather than duplicating the constant. + static final long MAX_ASSET_FILE_SIZE_BYTES = 5L * 1024 * 1024 * 1024; private static final int MAX_ASSETS_PER_PACKAGE_VERSION = 350; private static final int MAX_DOMAINS_PER_ACCOUNT = 10; private static final int MAX_REPOSITORIES_PER_DOMAIN = 1000; private static final String ASSET_STORAGE_DIR = "codeartifact-assets"; + private static final long MIN_TOKEN_DURATION_SECONDS = 900; + private static final long MAX_TOKEN_DURATION_SECONDS = 43200; + private static final long DEFAULT_TOKEN_DURATION_SECONDS = 43200; + private static final int TOKEN_RANDOM_BYTES = 32; public record DomainView(CodeArtifactDomain domain, int repositoryCount) {} public record ResourcePolicy(String resourceArn, String revision, String document) {} public record PublishPackageVersionResult(CodeArtifactPackageVersion packageVersion, PackageAsset asset) {} public record PackageVersionAssetResult(PackageAsset asset, String packageVersionRevision) {} + public record AuthorizationToken(String token, long expirationEpochSeconds) {} + public record AuthorizationTokenScope(String owner, String region) {} + private record AuthorizationTokenRecord(String owner, String region, String domain, Instant expiration) {} private final AccountAwareStorageBackend domains; private final AccountAwareStorageBackend repositories; @@ -96,6 +107,9 @@ public class CodeArtifactService implements Resettable { private final boolean inMemory; private final Path assetRoot; private final ConcurrentHashMap memoryAssetStore = new ConcurrentHashMap<>(); + // Bearer tokens are ephemeral security material, not durable emulator state: kept in memory + // only, the same way IamService keeps STS session credentials, regardless of storage mode. + private final ConcurrentHashMap authorizationTokens = new ConcurrentHashMap<>(); @Inject public CodeArtifactService(StorageFactory storageFactory, RegionResolver regionResolver, EmulatorConfig config, @@ -266,6 +280,11 @@ public class CodeArtifactService implements Resettable { r.setUpstreams(upstreams != null ? new ArrayList<>(upstreams) : new ArrayList<>()); r.setCreatedTime(Instant.now().getEpochSecond()); r.setTags(validateTags(tags, Map.of(), repository, "repository")); + // A bare UUID, not a domain/repository-derived name: Reposilite rejects any repository id + // over 64 characters, and CodeArtifact domain (max 50) and repository (max 100) names can + // easily exceed that combined. The id is purely internal and never surfaced by the public + // API, so readability doesn't matter here, only fitting the limit and staying unique. + r.setMavenRepositoryId(newRevision()); repositories.putForAccount(owner, key, r); return r; } @@ -287,6 +306,24 @@ public class CodeArtifactService implements Resettable { return requireRepository(owner, repositoryKey(region, domain, repository), repository); } + /** + * {@code mavenRepositoryId} is assigned at {@link #createRepository}, but a repository + * persisted before that field existed has none; backfills it lazily on first Maven-format use + * rather than leaving every caller of {@link CodeArtifactRepository#getMavenRepositoryId()} to + * handle a null it can otherwise never see. + */ + public synchronized String ensureMavenRepositoryId(String region, String domain, String domainOwner, + String repository) { + String owner = effectiveOwner(domainOwner); + String key = repositoryKey(region, domain, repository); + CodeArtifactRepository r = requireRepository(owner, key, repository); + if (r.getMavenRepositoryId() == null) { + r.setMavenRepositoryId(newRevision()); + repositories.putForAccount(owner, key, r); + } + return r.getMavenRepositoryId(); + } + public synchronized CodeArtifactRepository updateRepository(String region, String domain, String domainOwner, String repository, String description, List upstreams) { @@ -571,6 +608,61 @@ public class CodeArtifactService implements Resettable { return new PackageVersionAssetResult(asset, pv.getRevision()); } + // ------------------------------------------------------------ authorization + + public AuthorizationToken getAuthorizationToken(String region, String domain, String domainOwner, + Long durationSeconds) { + String owner = effectiveOwner(domainOwner); + requireDomain(owner, domainKey(region, domain), domain); + long duration = validateTokenDuration(durationSeconds); + Instant expiration = Instant.now().plusSeconds(duration); + String token = generateAuthorizationToken(); + authorizationTokens.put(token, new AuthorizationTokenRecord(owner, region, domain, expiration)); + return new AuthorizationToken(token, expiration.getEpochSecond()); + } + + /** + * Resolves a live token issued for exactly this domain, returning the account and Region it + * was issued under. A Maven request carries no SigV4 header, so there is nothing else to + * derive the caller's Region or account from: the token itself is both the credential and, on + * this path, the only source of that scope, the same way a real CodeArtifact authorization + * token is. + */ + public Optional resolveAuthorizationToken(String token, String domain) { + if (token == null) { + return Optional.empty(); + } + AuthorizationTokenRecord record = authorizationTokens.get(token); + if (record == null) { + return Optional.empty(); + } + if (Instant.now().isAfter(record.expiration())) { + authorizationTokens.remove(token); + return Optional.empty(); + } + if (!record.domain().equals(domain)) { + return Optional.empty(); + } + return Optional.of(new AuthorizationTokenScope(record.owner(), record.region())); + } + + private static long validateTokenDuration(Long durationSeconds) { + if (durationSeconds == null || durationSeconds == 0) { + return DEFAULT_TOKEN_DURATION_SECONDS; + } + if (durationSeconds < MIN_TOKEN_DURATION_SECONDS || durationSeconds > MAX_TOKEN_DURATION_SECONDS) { + throw validation("durationSeconds must be 0, or between " + MIN_TOKEN_DURATION_SECONDS + " and " + + MAX_TOKEN_DURATION_SECONDS + "."); + } + return durationSeconds; + } + + private static String generateAuthorizationToken() { + byte[] bytes = new byte[TOKEN_RANDOM_BYTES]; + new SecureRandom().nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + // -------------------------------------------------------------------- tags public synchronized void tagResource(String resourceArn, Map newTags) { @@ -621,6 +713,7 @@ public class CodeArtifactService implements Resettable { domains.clear(); repositories.clear(); packageVersions.clear(); + authorizationTokens.clear(); if (inMemory) { memoryAssetStore.clear(); } else { diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java new file mode 100644 index 0000000000..fb3cf86a3b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClient.java @@ -0,0 +1,231 @@ +package io.github.hectorvent.floci.services.codeartifact; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.BodyPublishers; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.time.Duration; +import java.util.Optional; + +/** + * HTTP client for the shared Reposilite sidecar. A CodeArtifact repository maps to a named + * Reposilite repository ({@link #ensureRepository}), provisioned lazily via Reposilite's + * {@code maven} settings domain, which hot-reloads without a restart. + */ +@ApplicationScoped +public class ReposiliteSidecarClient { + private static final Logger LOG = Logger.getLogger(ReposiliteSidecarClient.class); + private static final String MAVEN_SETTINGS_PATH = "/api/settings/domain/maven"; + private static final int REPOSITORY_READY_POLL_MAX_MS = 3_000; + private static final int REPOSITORY_READY_POLL_INTERVAL_MS = 50; + + private final ReposiliteSidecarManager manager; + private final ObjectMapper mapper; + private final HttpClient httpClient; + /** + * Every {@link #ensureRepository} call does a read-modify-write of the *same* single settings + * document (Reposilite has no per-repository create endpoint, only a full-list replace), so a + * per-repoId lock is not enough: two different repositories provisioned concurrently can each + * read the list before the other's write lands, and the second PUT silently drops the first + * repository from the list (confirmed against a real Reposilite instance). One lock serializes + * every provisioning call regardless of which repository it is for. + */ + private final Object provisioningLock = new Object(); + + @Inject + public ReposiliteSidecarClient(ReposiliteSidecarManager manager, ObjectMapper mapper) { + this(manager, mapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()); + } + + ReposiliteSidecarClient(ReposiliteSidecarManager manager, ObjectMapper mapper, HttpClient httpClient) { + this.manager = manager; + this.mapper = mapper; + this.httpClient = httpClient; + } + + /** Ensures a Reposilite repository named {@code repoId} exists, creating it if not. */ + public void ensureRepository(String repoId) { + String baseUrl = manager.ensureReady(); + synchronized (provisioningLock) { + ArrayNode repositories = currentRepositories(baseUrl); + for (JsonNode repository : repositories) { + if (repoId.equals(repository.path("id").asText())) { + return; + } + } + ObjectNode newRepository = mapper.createObjectNode(); + newRepository.put("id", repoId); + newRepository.put("visibility", "PUBLIC"); + newRepository.put("redeployment", false); + repositories.add(newRepository); + putMavenSettings(baseUrl, repositories); + waitUntilRepositoryIsServable(baseUrl, repoId); + LOG.infov("Provisioned Reposilite repository {0}", repoId); + } + } + + /** + * Reposilite's settings PUT returning 200 only means the shared-configuration document was + * written; it does not mean the repository actually instantiated. A repository whose settings + * are individually valid but that {@code RepositoryFactory} rejects for a reason the settings + * endpoint itself never validates (an id over Reposilite's own 64-character limit was one real + * case here) is silently dropped, logged as an error inside the container, and every later + * deploy to it 404s with a confusing "Repository not found" that gives no hint why. Polling a + * side-effect-free read endpoint here turns that into an immediate, clear failure at + * provisioning time instead. + */ + private void waitUntilRepositoryIsServable(String baseUrl, String repoId) { + long deadline = System.currentTimeMillis() + REPOSITORY_READY_POLL_MAX_MS; + while (System.currentTimeMillis() < deadline) { + if (isRepositoryServable(baseUrl, repoId)) { + return; + } + try { + Thread.sleep(REPOSITORY_READY_POLL_INTERVAL_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for Reposilite repository " + repoId + + " to become servable", e); + } + } + throw new IllegalStateException("Reposilite repository " + repoId + " did not become servable within " + + REPOSITORY_READY_POLL_MAX_MS + " ms"); + } + + /** + * {@code /api/maven/details/{repository}/{gav}} answers "File not found" for a path missing + * from a repository Reposilite actually knows about, and "Repository ... not found" for one it + * doesn't yet, which is exactly the distinction needed here; a probe path that can never be a + * real artifact makes the "found" case impossible, so only the message text is ever compared. + */ + private boolean isRepositoryServable(String baseUrl, String repoId) { + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(baseUrl + "/api/maven/details/" + repoId + "/.floci-repository-ready-probe")) + .timeout(Duration.ofSeconds(5)) + .header("Authorization", manager.basicAuthHeader()) + .GET() + .build(); + HttpResponse response = send(request, BodyHandlers.ofString()); + if (response.statusCode() == 200) { + return true; + } + String message = readTree(response.body()).path("message").asText(""); + return !message.startsWith("Repository "); + } + + /** Deploys {@code content} to {@code repoId}'s {@code gav} path, returning the HTTP status. */ + public int deployArtifact(String repoId, String gav, byte[] content) { + String baseUrl = manager.ensureReady(); + HttpRequest request = authenticated(baseUrl, repoId, gav) + .PUT(BodyPublishers.ofByteArray(content)) + .build(); + return send(request, BodyHandlers.discarding()).statusCode(); + } + + /** Fetches {@code repoId}'s {@code gav} path, or {@link Optional#empty()} on a non-200 response. */ + public Optional fetchArtifact(String repoId, String gav) { + String baseUrl = manager.ensureReady(); + HttpRequest request = authenticated(baseUrl, repoId, gav).GET().build(); + HttpResponse response = send(request, BodyHandlers.ofByteArray()); + if (response.statusCode() != 200) { + return Optional.empty(); + } + String contentType = response.headers().firstValue("Content-Type").orElse("application/octet-stream"); + return Optional.of(new FetchedArtifact(response.body(), contentType)); + } + + public record FetchedArtifact(byte[] content, String contentType) {} + + /** {@code true} if {@code repoId}'s {@code gav} path exists. */ + public boolean artifactExists(String repoId, String gav) { + String baseUrl = manager.ensureReady(); + HttpRequest request = authenticated(baseUrl, repoId, gav).method("HEAD", BodyPublishers.noBody()).build(); + return send(request, BodyHandlers.discarding()).statusCode() == 200; + } + + private ArrayNode currentRepositories(String baseUrl) { + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(baseUrl + MAVEN_SETTINGS_PATH)) + .timeout(Duration.ofSeconds(10)) + .header("Authorization", manager.basicAuthHeader()) + .GET() + .build(); + HttpResponse response = send(request, BodyHandlers.ofString()); + if (response.statusCode() != 200) { + throw new IllegalStateException("Failed to read Reposilite maven settings: HTTP " + + response.statusCode()); + } + JsonNode settings = readTree(response.body()); + return settings.path("repositories").isArray() + ? ((ArrayNode) settings.path("repositories")).deepCopy() + : mapper.createArrayNode(); + } + + private void putMavenSettings(String baseUrl, ArrayNode repositories) { + ObjectNode settings = mapper.createObjectNode(); + settings.set("repositories", repositories); + String payload = writeValue(settings); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(baseUrl + MAVEN_SETTINGS_PATH)) + .timeout(Duration.ofSeconds(10)) + .header("Authorization", manager.basicAuthHeader()) + .header("Content-Type", "application/json") + .PUT(BodyPublishers.ofString(payload)) + .build(); + HttpResponse response = send(request, BodyHandlers.ofString()); + if (response.statusCode() != 200) { + throw new IllegalStateException("Failed to update Reposilite maven settings: HTTP " + + response.statusCode() + " " + response.body()); + } + } + + private HttpRequest.Builder authenticated(String baseUrl, String repoId, String gav) { + return HttpRequest.newBuilder() + .uri(URI.create(baseUrl + "/" + repoId + "/" + gav)) + .timeout(Duration.ofSeconds(30)) + .header("Authorization", manager.basicAuthHeader()); + } + + private HttpResponse send(HttpRequest request, HttpResponse.BodyHandler bodyHandler) { + try { + return httpClient.send(request, bodyHandler); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while calling Reposilite sidecar", e); + } catch (IOException e) { + throw new IllegalStateException("Failed to call Reposilite sidecar: " + safeMessage(e), e); + } + } + + private JsonNode readTree(String body) { + try { + return mapper.readTree(body); + } catch (IOException e) { + throw new IllegalStateException("Reposilite maven settings response was not valid JSON", e); + } + } + + private String writeValue(ObjectNode value) { + try { + return mapper.writeValueAsString(value); + } catch (IOException e) { + throw new IllegalStateException("Failed to serialize Reposilite maven settings", e); + } + } + + private static String safeMessage(Exception e) { + String message = e.getMessage(); + return message == null || message.isBlank() ? e.getClass().getSimpleName() : message; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarManager.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarManager.java new file mode 100644 index 0000000000..dffa26434c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarManager.java @@ -0,0 +1,194 @@ +package io.github.hectorvent.floci.services.codeartifact; + +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 io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo; +import io.github.hectorvent.floci.core.common.docker.ContainerSpec; +import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper; +import io.quarkus.runtime.ShutdownEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Optional; + +/** + * Lazily starts and manages the shared Reposilite container that backs CodeArtifact's Maven + * format. Unlike the floci-io/floci-sidecars contract sidecars (Cedar, GraphQL), Reposilite is a + * stock upstream image: there is no sidecar contract to speak, so readiness is just its own + * {@code GET /api/status/health} and management calls authenticate with a token this manager + * bootstraps the container with, generated fresh per process. + * + *

One repository-agnostic container backs every CodeArtifact domain/repository pair; a + * CodeArtifact repository maps to a named Reposilite repository provisioned on first use (see + * {@link ReposiliteSidecarClient#ensureRepository}), not to its own container. + */ +@ApplicationScoped +public class ReposiliteSidecarManager { + static final String IMAGE_ENV = "FLOCI_SERVICES_CODEARTIFACT_MAVEN_IMAGE"; + static final String URL_ENV = "FLOCI_SERVICES_CODEARTIFACT_MAVEN_URL"; + static final String MANAGED_TOKEN_NAME = "floci-manager"; + + private static final Logger LOG = Logger.getLogger(ReposiliteSidecarManager.class); + private static final String CONTAINER_NAME = "floci-reposilite"; + private static final int REPOSILITE_PORT = 8080; + private static final int HEALTH_POLL_MAX_MS = 30_000; + private static final int HEALTH_POLL_INTERVAL_MS = 500; + private static final int GENERATED_SECRET_BYTES = 24; + + private final ContainerBuilder containerBuilder; + private final ContainerLifecycleManager lifecycleManager; + private final EmulatorConfig config; + private final String managedSecret; + + private volatile String resolvedUrl; + private volatile String containerId; + private volatile String resolvedTokenName; + private volatile String resolvedTokenSecret; + + @Inject + public ReposiliteSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager, + EmulatorConfig config) { + this(containerBuilder, lifecycleManager, config, generateSecret()); + } + + ReposiliteSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager, + EmulatorConfig config, String managedSecret) { + this.containerBuilder = containerBuilder; + this.lifecycleManager = lifecycleManager; + this.config = config; + this.managedSecret = managedSecret; + } + + /** Base URL of a ready Reposilite instance, starting the managed container if needed. */ + public synchronized String ensureReady() { + if (resolvedUrl != null) { + if (containerId == null || probeHealth(resolvedUrl)) { + return resolvedUrl; + } + discardStaleManagedEndpoint(); + } + Optional configuredUrl = config.services().codeartifact().mavenUrl(); + if (configuredUrl.isPresent() && !configuredUrl.get().isBlank()) { + String url = trimTrailingSlash(configuredUrl.get()); + String token = config.services().codeartifact().mavenToken().orElse(""); + int separator = token.indexOf(':'); + if (separator <= 0) { + throw new IllegalStateException(URL_ENV + " is set but " + "the matching token property " + + "(name:secret) is missing or malformed."); + } + resolvedTokenName = token.substring(0, separator); + resolvedTokenSecret = token.substring(separator + 1); + probeHealth(url); + resolvedUrl = url; + LOG.infov("Using pre-configured Reposilite sidecar URL: {0}", resolvedUrl); + return resolvedUrl; + } + startContainer(); + return resolvedUrl; + } + + /** {@code Authorization} header value for the token {@link #ensureReady()} authenticated with. */ + public String basicAuthHeader() { + String credentials = resolvedTokenName + ":" + resolvedTokenSecret; + return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + } + + private void discardStaleManagedEndpoint() { + String staleUrl = resolvedUrl; + String staleContainerId = containerId; + resolvedUrl = null; + containerId = null; + LOG.warnv("Reposilite sidecar at {0} is no longer healthy; restarting the managed container", staleUrl); + if (staleContainerId != null) { + try { + lifecycleManager.stopAndRemove(staleContainerId, null); + } catch (Exception e) { + LOG.debugv(e, "Failed to remove stale Reposilite sidecar container {0}", staleContainerId); + } + } + } + + private void startContainer() { + String image = config.services().codeartifact().mavenImage(); + LOG.infov("Starting Reposilite sidecar container using image {0}", image); + String containerName = ContainerStorageHelper.dockerName(config, CONTAINER_NAME); + lifecycleManager.removeIfExists(containerName); + + ContainerSpec spec = containerBuilder.newContainer(image) + .withName(containerName) + .withEnv("REPOSILITE_OPTS", "--token " + MANAGED_TOKEN_NAME + ":" + managedSecret) + .withDynamicPort(REPOSILITE_PORT) + .withDockerNetwork(config.services().dockerNetwork()) + .withEmbeddedDns() + .withLogRotation() + .build(); + ContainerInfo info = lifecycleManager.createAndStart(spec); + EndpointInfo endpoint = info.getEndpoint(REPOSILITE_PORT); + containerId = info.containerId(); + resolvedTokenName = MANAGED_TOKEN_NAME; + resolvedTokenSecret = managedSecret; + String url = "http://" + endpoint; + waitForHealth(url); + resolvedUrl = url; + LOG.infov("Reposilite sidecar is ready at {0}", resolvedUrl); + } + + private boolean probeHealth(String baseUrl) { + try { + HttpURLConnection connection = (HttpURLConnection) URI.create(baseUrl + "/api/status/health").toURL() + .openConnection(); + connection.setConnectTimeout(500); + connection.setReadTimeout(500); + return connection.getResponseCode() == 200; + } catch (IOException e) { + LOG.debugv(e, "Reposilite sidecar health probe failed for {0}", baseUrl); + return false; + } + } + + private void waitForHealth(String baseUrl) { + long deadline = System.currentTimeMillis() + HEALTH_POLL_MAX_MS; + while (System.currentTimeMillis() < deadline) { + if (probeHealth(baseUrl)) { + return; + } + try { + Thread.sleep(HEALTH_POLL_INTERVAL_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for Reposilite sidecar", e); + } + } + throw new IllegalStateException("Reposilite sidecar did not become healthy within " + HEALTH_POLL_MAX_MS + + " ms"); + } + + void onStop(@Observes ShutdownEvent event) { + if (containerId == null) { + return; + } + LOG.info("Stopping Reposilite sidecar container"); + lifecycleManager.stopAndRemove(containerId, null); + } + + private static String trimTrailingSlash(String url) { + return url.endsWith("/") ? url.substring(0, url.length() - 1) : url; + } + + private static String generateSecret() { + byte[] bytes = new byte[GENERATED_SECRET_BYTES]; + new SecureRandom().nextBytes(bytes); + return HexFormat.of().formatHex(bytes); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/CodeArtifactRepository.java b/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/CodeArtifactRepository.java index 19cbd800e2..f37f0d43d2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/CodeArtifactRepository.java +++ b/src/main/java/io/github/hectorvent/floci/services/codeartifact/model/CodeArtifactRepository.java @@ -25,6 +25,12 @@ public class CodeArtifactRepository { private Map tags = new LinkedHashMap<>(); private String policyDocument; private String policyRevision; + /** + * The Reposilite repository backing this repository's {@code maven} format, unique per + * creation so a deleted-and-recreated repository of the same name never inherits a previous + * repository's leftover artifacts. Internal; never surfaced in the public API response. + */ + private String mavenRepositoryId; public String getName() { return name; @@ -129,4 +135,12 @@ public class CodeArtifactRepository { public void setPolicyRevision(String policyRevision) { this.policyRevision = policyRevision; } + + public String getMavenRepositoryId() { + return mavenRepositoryId; + } + + public void setMavenRepositoryId(String mavenRepositoryId) { + this.mavenRepositoryId = mavenRepositoryId; + } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 508159a438..43140afca8 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -831,6 +831,8 @@ floci: enabled: true codeartifact: enabled: true + # maven-url: http://floci-reposilite:8080 # set to skip Reposilite sidecar container management + maven-image: "dzikoysk/reposilite:3.6.3" marketplace: enabled: true dms: diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java index 08aa34be1a..c2094ad3a6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactIntegrationTest.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenDockerIntegrationTest.java new file mode 100644 index 0000000000..6f94dbf75d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenDockerIntegrationTest.java @@ -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)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenSidecarProfile.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenSidecarProfile.java new file mode 100644 index 0000000000..b2359ada23 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactMavenSidecarProfile.java @@ -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 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; + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java index 36bf6ecf82..aa9b0f86ec 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/CodeArtifactServiceTest.java @@ -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 repoStore; @BeforeEach void setUp() { AccountAwareStorageBackend domainStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); - AccountAwareStorageBackend repoStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); + repoStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); AccountAwareStorageBackend 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 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 diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java new file mode 100644 index 0000000000..1d1519bd3a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarClientTest.java @@ -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 requestedPaths = new CopyOnWriteArrayList<>(); + private final AtomicReference 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 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 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 received = new AtomicReference<>(); + AtomicReference 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 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 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); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarManagerTest.java new file mode 100644 index 0000000000..9b3b07234d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codeartifact/ReposiliteSidecarManagerTest.java @@ -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); + } +}