mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(codeartifact): support the cargo (crates.io) registry format (#8370)
CodeArtifact's Rust/Cargo repositories had no native support at all: no sidecar, no wire protocol, no external connection. Adds it following the same shape as the existing Maven/npm/pypi/NuGet container-backed formats. KellnrSidecarManager/KellnrSidecarClient run a real Kellnr container per cargo-enabled repository and speak its native HTTP API for publish, download, and the sparse index. CodeArtifactCargoController implements the real `cargo` sparse-registry wire protocol (publish, download, sparse index lookup, config.json) and forwards Kellnr's own publish rejections (e.g. republishing an existing version, which the Cargo Book documents as permanently disallowed) verbatim rather than swallowing them into an opaque error. Adds the `public:crates-io` external connection via CargoExternalConnectionClient (real index.crates.io/static.crates.io wire calls) and CodeArtifactCargoExternalConnectionImporter, reusing the existing claim/fence/retention-origin machinery the same way NuGet's own importer does. Cargo's sparse index covers every version of a crate name in one file and a real cargo client always consults it first, so unlike the other formats' importers this one also merges real upstream-only version lines into the local index response (mergeExternalVersions), a read-only proxy step with no retention write of its own, so an upstream-only crate is actually visible to a client's dependency resolution before anything is retained. Fixes against the live Kellnr/crates.io protocols found while addressing review: KellnrSidecarClient now implements listPackages (its absence made every ListPackages call 500 once cargo joined the container-backed formats); sparse-index bucket paths are lowercased per the Cargo Book's own spec (crates.io's own index is case-sensitive about this even though a crate's real name isn't); the admin account behind Kellnr's internal publish token is given a fresh random password per container rather than Kellnr's own shared default; a stale cached publish token (e.g. after a silent container restart) is retried once rather than 401ing forever; both publish-body parsing and the external sparse-index fetch are now bounded against an oversized allocation; a renamed dependency's alias and real name are mapped correctly between the index and publish shapes, and features2/links/rust_version now survive a retained crate's synthesized metadata; the Kellnr image is pinned to the exact version this was built and tested against rather than a floating major tag. Known gaps, called out in docs/services/codeartifact.md: no repository-to-repository upstream importer yet for cargo (every other native format already has one), and no yank/owner/search routes.
This commit is contained in:
1 parent
1b14d10b1f
commit
15a632e446
19 files changed
+4286
-79
No files matched your search
+155
-59
@@ -7,11 +7,11 @@
|
||||
Floci supports the CodeArtifact control plane: domains, repositories, resource policies, tags,
|
||||
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`, `npm`, `pypi`, and `nuget` formats are each
|
||||
served through their own real package-manager-protocol proxy (`mvn`/Gradle, `npm`/`yarn`/`pnpm`,
|
||||
`pip`/`twine`, and `nuget`/`dotnet` publish and resolve all work against the URL
|
||||
`GetRepositoryEndpoint` returns); the remaining formats (Ruby, Swift, Cargo) have no real proxy
|
||||
behind them yet.
|
||||
`PublishPackageVersion` accepts only `generic`. The `maven`, `npm`, `pypi`, `nuget`, and `cargo`
|
||||
formats are each served through their own real package-manager-protocol proxy (`mvn`/Gradle,
|
||||
`npm`/`yarn`/`pnpm`, `pip`/`twine`, `nuget`/`dotnet`, and `cargo` publish and resolve all work
|
||||
against the URL `GetRepositoryEndpoint` returns); the remaining formats (Ruby, Swift) have no real
|
||||
proxy behind them yet.
|
||||
|
||||
## Supported Actions
|
||||
|
||||
@@ -20,9 +20,9 @@ behind them yet.
|
||||
| --- | --- |
|
||||
| `CreateDomain` | Creates a domain (max 10 per account per Region), optionally with a KMS encryption key and initial tags, and its root package group `/*`, whose restrictions are all `ALLOW`. |
|
||||
| `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 and the total size of its assets (generic, Maven, npm, pypi, and NuGet; see Known limitations). |
|
||||
| `DescribeDomain` | Returns a domain's full description, including its repository count and the total size of its assets (generic, Maven, npm, pypi, NuGet, and Cargo; see Known limitations). |
|
||||
| `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`, `npm`, `pypi`, and `nuget` repository endpoints. |
|
||||
| `GetAuthorizationToken` | Issues a bearer token scoped to a domain, valid for 0 (12 hours) or 900-43200 seconds, required by the `maven`, `npm`, `pypi`, `nuget`, and `cargo` repository endpoints. |
|
||||
| `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`. |
|
||||
@@ -259,6 +259,55 @@ declared one with `<readme>`) addressable by exact version for as long as that v
|
||||
falling back to the nuspec's own `<description>` field when no readme file was embedded, matching
|
||||
AWS's documented "the readme file or descriptive text" wording for this action exactly.
|
||||
|
||||
## The cargo repository endpoint
|
||||
|
||||
`GetRepositoryEndpoint` for `format=cargo` returns `http://localhost:4566/codeartifact/cargo/<domain>/<repository>/`.
|
||||
A real `cargo` client reaches it through a `.cargo/config.toml` `[registries.<name>]` block whose
|
||||
`index` is `sparse+<that URL>` and whose `credential-provider` runs `aws codeartifact
|
||||
get-authorization-token` and feeds the token to Cargo via stdout (or, on Windows,
|
||||
`~/.cargo/credentials.toml`), the way [AWS documents configuring Cargo for
|
||||
CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/configure-use-cargo.html). AWS's
|
||||
own guide documents only `cargo add`/`cargo build` (resolution) and `cargo publish`/`cargo login`
|
||||
against CodeArtifact; this proxy serves exactly that surface and no `yank`/`owner`/search routes,
|
||||
since AWS's guide never mentions any of those three for Cargo.
|
||||
|
||||
Authentication is a bare `Authorization: <token>` header with no scheme prefix at all, confirmed
|
||||
from the Cargo Book's own registry-authentication page (the real `cargo` wire protocol has no
|
||||
named HTTP auth scheme, unlike Maven/pypi/nuget's Basic or npm's Bearer); a missing, invalid,
|
||||
expired, or wrong-domain token gets a 401 with no `WWW-Authenticate` challenge, since naming a
|
||||
scheme real Cargo doesn't send would be misleading.
|
||||
|
||||
It is backed by a shared registry server, [Kellnr](https://kellnr.io), the same per-repository
|
||||
container pattern as npm/pypi/nuget: each CodeArtifact repository gets its own Kellnr container,
|
||||
started lazily on first use and identified internally by a fresh id generated at
|
||||
`CreateRepository` time, so a repository deleted and recreated under the same name never inherits
|
||||
the previous one's crates. `DeleteRepository` stops and removes that repository's container
|
||||
immediately, the same as npm/pypi/nuget. One config knob, `FLOCI_SERVICES_CODEARTIFACT_CARGO_IMAGE`,
|
||||
pins the image version.
|
||||
|
||||
`GET .../config.json` is authored directly rather than proxied from Kellnr (whose own response
|
||||
would self-report its own internal container address): `{"dl":"<endpoint>api/v1/crates",
|
||||
"api":"<endpoint>","auth-required":true}`, `<endpoint>` being the exact same value
|
||||
`GetRepositoryEndpoint` returns, matching how real CodeArtifact serves Cargo from one combined
|
||||
endpoint for index, API, and downloads alike (unlike crates.io's own split between an index host
|
||||
and an API host). The sparse HTTP registry index itself (RFC 2789: one newline-delimited-JSON file
|
||||
per crate, bucketed by name length/prefix exactly as real crates.io buckets it) is proxied from
|
||||
Kellnr close to verbatim, real `deps`/`cksum`/`features` fields included. A real `cargo publish`
|
||||
(`PUT api/v1/crates/new`) forwards the client's own real binary wire body (the 4-byte
|
||||
length-prefixed metadata, then the 4-byte length-prefixed `.crate` file, confirmed from the Cargo
|
||||
Book's own spec text) to Kellnr verbatim, dependency list included, through the same
|
||||
`publish:BLOCK` origin-configuration gate and Archived/Disposed-version gate every other
|
||||
container-backed format already uses; `GET .../api/v1/crates/{name}/{version}/download` streams
|
||||
the real `.crate` back, blocked (404) for an Archived/Disposed version the same way.
|
||||
|
||||
Unlike every other format's publish, a `cargo publish` of an already-existing name/version is
|
||||
**rejected outright, even when the content is byte-identical**, not treated as an idempotent
|
||||
no-op the way Maven/pypi/nuget's publish paths are. This matches real Cargo: the Cargo Book's own
|
||||
documented rule is that "a publish is generally permanent. The version can never be overwritten,"
|
||||
confirmed live against Kellnr, which answers such a republish with a real `400` carrying the Cargo
|
||||
Book's own documented error shape (`{"errors":[{"detail":"..."}]}`); this proxy forwards that
|
||||
status and body to the client verbatim rather than reinterpreting it.
|
||||
|
||||
## AWS-compatible failures
|
||||
|
||||
Domain and repository names, tags, pagination, duplicate names, missing upstreams, policy-revision
|
||||
@@ -286,12 +335,19 @@ state.
|
||||
trust-policy or permissions-policy enforcement, consistent with Floci's IAM enforcement being
|
||||
opt-in elsewhere, but worth knowing if you rely on domain-sharing semantics.
|
||||
- **The native per-format download routes don't consult a container-backed version's status
|
||||
override.** `GetPackageVersionAsset` correctly blocks an Archived/Disposed version, but a plain
|
||||
`mvn`/`npm install`/`pip install`/`nuget` fetch against the Maven GAV, npm tarball, pypi
|
||||
filename, or nuget content route proxies straight to the sidecar and never checks it, so that
|
||||
same version's bytes are still fetchable through those routes.
|
||||
- **A container-backed (`maven`/`npm`/`pypi`/`nuget`) version's status override does not survive a
|
||||
Floci restart.** It's kept in memory only, for the same reason the byte-count and readme
|
||||
override, for Maven, npm, pypi, and nuget.** `GetPackageVersionAsset` correctly blocks an
|
||||
Archived/Disposed version, but a plain `mvn`/`npm install`/`pip install`/`nuget` fetch against
|
||||
the Maven GAV, npm tarball, pypi filename, or nuget content route proxies straight to the
|
||||
sidecar and never checks it, so that same version's bytes are still fetchable through those
|
||||
routes. `cargo`'s own download route (`GET .../api/v1/crates/{name}/{version}/download`) is the
|
||||
one exception: it calls the same `requireContainerBackedVersionDownloadable` check
|
||||
`GetPackageVersionAsset` uses and correctly 404s an Archived/Disposed version. The sparse index
|
||||
lookup (`GET .../{name}`) is not filtered this way, though: a real `cargo` client's own protocol
|
||||
keeps a yanked version listed in the index with a `yanked` flag rather than removing it, and
|
||||
mapping Floci's own Archived/Disposed status onto that field is a real design decision
|
||||
deliberately deferred, not yet built either way.
|
||||
- **A container-backed (`maven`/`npm`/`pypi`/`nuget`/`cargo`) version's status override does not
|
||||
survive a Floci restart.** It's kept in memory only, for the same reason the byte-count and readme
|
||||
bookkeeping those formats already need are: the sidecar content it describes doesn't survive a
|
||||
restart either (no volume attached, removed on shutdown), so persisting the override alone would
|
||||
leave it answering for a version that, after a restart, no longer exists anywhere real. A
|
||||
@@ -300,13 +356,19 @@ state.
|
||||
all once the sidecar itself restarts empty). `generic`'s status has no such gap: it's stored
|
||||
directly on the version's own persisted record.
|
||||
- **`CopyPackageVersions` has no full cross-call rollback on a mid-copy sidecar failure.**
|
||||
(`generic`, `maven`, `npm`, `pypi`, and `nuget` are all supported — matching real AWS, which
|
||||
places no `format` restriction on this action at all, unlike `PublishPackageVersion`'s own
|
||||
(`generic`, `maven`, `npm`, `pypi`, `nuget`, and `cargo` are all supported — matching real AWS,
|
||||
which places no `format` restriction on this action at all, unlike `PublishPackageVersion`'s own
|
||||
restriction to `generic`; `generic` copies through its own `packageVersions` record, while
|
||||
`maven`, `npm`, `pypi`, and `nuget` each bridge straight to their own sidecar's real wire
|
||||
protocol — `mvn deploy`, `npm publish`, `twine upload`, and `nuget push` respectively, confirmed
|
||||
against a live container for each — since none of the four keeps a `packageVersions` record
|
||||
this action could otherwise read from or write to.) A container-backed copy retains byte-for-byte
|
||||
`maven`, `npm`, `pypi`, `nuget`, and `cargo` each bridge straight to their own sidecar's storage,
|
||||
since none of the five keeps a `packageVersions` record this action could otherwise read from or
|
||||
write to. Maven, npm, pypi, and nuget bridge through their sidecar's real wire protocol — `mvn
|
||||
deploy`, `npm publish`, `twine upload`, and `nuget push` respectively, confirmed against a live
|
||||
container for each. `cargo` is the one exception: there is no real client request to replay for
|
||||
a copy, so this bridges through `KellnrSidecarClient`'s own asset-store path instead, which
|
||||
synthesizes fresh, dependency-free metadata rather than forwarding a real client's own `deps`
|
||||
list, since there is no real client involved to have sent one; a copied crate's sparse-index
|
||||
entry therefore always reports an empty dependency list, unlike one reached through a real
|
||||
`cargo publish`.) A container-backed copy retains byte-for-byte
|
||||
source assets, and a best-effort compensating cleanup restores or removes whatever one version's
|
||||
own write touched if a later step in that same version fails, preserving the original error, but
|
||||
a sidecar outage mid-cleanup can still leave a version in an inconsistent state, the same
|
||||
@@ -338,9 +400,10 @@ state.
|
||||
committed shape to split safely, a real design task rather than a mechanical move. A single
|
||||
call copying many large versions can therefore hold up every other CodeArtifact request for as
|
||||
long as that whole batch takes, not just slow down the one call itself.
|
||||
- **The 5 GB asset size quota is a real streaming limit for `generic`, Maven, pypi, and nuget,
|
||||
with two exceptions.** Every upload and download path (direct publish, the native Maven/pypi/
|
||||
nuget proxies, `GetPackageVersionAsset`, and `CopyPackageVersions`) stages an asset to disk and
|
||||
- **The 5 GB asset size quota is a real streaming limit for `generic`, Maven, pypi, nuget, and
|
||||
cargo, with two exceptions.** Every upload and download path (direct publish, the native
|
||||
Maven/pypi/nuget/cargo proxies, `GetPackageVersionAsset`, and `CopyPackageVersions`) stages an
|
||||
asset to disk and
|
||||
streams it rather than holding it as one JVM array, so none of them are bound by the ~2 GiB
|
||||
`byte[]` limit that would otherwise sit well under AWS's own 5 GB quota. Two things still cap a
|
||||
real upload below that:
|
||||
@@ -353,8 +416,8 @@ state.
|
||||
publish fails with an uncaught `OutOfMemoryError` rather than a clean rejection. Unlike S3,
|
||||
CodeArtifact has no per-service storage-mode override (`FLOCI_STORAGE_SERVICES_S3_MODE`'s own
|
||||
equivalent does not exist here): set the global `FLOCI_STORAGE_MODE=persistent` (or `hybrid`/
|
||||
`wal`) to lift this. Maven, npm, pypi, and nuget assets are unaffected either way, since their
|
||||
real bytes always live in their own sidecar container, never in this map.
|
||||
`wal`) to lift this. Maven, npm, pypi, nuget, and cargo assets are unaffected either way, since
|
||||
their real bytes always live in their own sidecar container, never in this map.
|
||||
- **npm has its own, separate, much lower ceiling that no Floci-side configuration changes:**
|
||||
real npm's publish protocol embeds the whole tarball as one base64 string inside a JSON
|
||||
document, and Verdaccio (the sidecar behind this proxy) converts the whole received body to a
|
||||
@@ -363,10 +426,10 @@ state.
|
||||
string length and crashes the Verdaccio process outright with an uncaught `RangeError: Invalid
|
||||
string length`, not a clean rejection either. This is a limitation of real npm's own wire
|
||||
protocol as Verdaccio implements it, not something this emulator's own code can stream around.
|
||||
- **Maven artifacts, npm packages, pypi packages, and NuGet packages do not survive a Floci
|
||||
restart, even under persistent storage.** The Reposilite instance and every per-repository
|
||||
Verdaccio, pypiserver, and BaGetter container have no volume attached and are removed on shutdown
|
||||
along with everything published to them. CodeArtifact repository/domain metadata (including each format's stored sidecar container
|
||||
- **Maven artifacts, npm packages, pypi packages, NuGet packages, and cargo crates do not survive a
|
||||
Floci restart, even under persistent storage.** The Reposilite instance and every per-repository
|
||||
Verdaccio, pypiserver, BaGetter, and Kellnr container have no volume attached and are removed on
|
||||
shutdown along with everything published to them. CodeArtifact repository/domain metadata (including each format's stored sidecar container
|
||||
id) survives a restart the same way any other Floci state does under persistent storage mode; the
|
||||
artifacts and packages themselves do not, so the first request after a restart re-provisions
|
||||
empty storage and returns 404 for anything published before the restart.
|
||||
@@ -385,10 +448,32 @@ state.
|
||||
example a Lambda, Batch, or ECS workload container) from reaching the sidecar on its
|
||||
container-internal address, bypassing the proxy's token check entirely. Closing this for real
|
||||
would mean isolating each sidecar on its own Docker network reachable only from Floci's own
|
||||
process, a change that would need to apply uniformly across all four sidecar-backed formats, not
|
||||
a one-off fix to any single proxy.
|
||||
- **Every native endpoint's own external connections and repository-to-repository upstreams both
|
||||
resolve, for all four formats.** On real CodeArtifact, a repository with another repository
|
||||
process, a change that would need to apply uniformly across all five sidecar-backed formats, not
|
||||
a one-off fix to any single proxy. Kellnr (cargo's own sidecar) is the one partial exception:
|
||||
confirmed live, it always demands a valid token for its own publish endpoint regardless of its
|
||||
`KELLNR_REGISTRY__AUTH_REQUIRED` setting, so reaching it directly on the Docker network still
|
||||
doesn't permit a publish without also obtaining the internal token Floci mints and caches for it;
|
||||
that token is never the real CodeArtifact token, but it is still a second, real barrier the other
|
||||
four sidecars don't have. That barrier only holds because the admin account behind it is never
|
||||
left at Kellnr's own shipped `admin`/`admin` default (which every Kellnr deployment shares
|
||||
publicly): a fresh, random password is minted per container at creation
|
||||
(`KELLNR_SETUP__ADMIN_PWD`, confirmed live to override that default) and read fresh on every
|
||||
admin login rather than cached, so it also stays correct across a container silently restarted
|
||||
under the same repository id.
|
||||
- **Every native endpoint's own external connections resolve, for Maven, npm, pypi, nuget, and now
|
||||
cargo (`public:crates-io`, against the real `index.crates.io`/`static.crates.io`); the
|
||||
repository-to-repository upstream side does not yet resolve for cargo.** A real `cargo build`/
|
||||
`cargo add` needs more than a plain on-demand fetch to work at all: its own sparse index for one
|
||||
crate name is a single file covering every version, so a cache miss on the download route alone
|
||||
would leave an upstream-only version invisible to its resolver. The native cargo endpoint's own
|
||||
sparse-index route merges in the real upstream index's own version lines not already known
|
||||
locally (read-only, nothing retained until a real download actually happens), the one thing none
|
||||
of the other four formats' own external-connection importers need, since their own clients can
|
||||
always ask for one already-known version directly. `cargo` is otherwise still a container-backed
|
||||
format like the other four (`DescribePackageVersion`, `ListPackages`, `DeletePackage`,
|
||||
`CopyPackageVersions`, and byte accounting all already work for it the same way), but has no
|
||||
repository-to-repository upstream resolution against its own native endpoint yet; that's its own
|
||||
future work. On real CodeArtifact, a repository with another repository
|
||||
configured as an upstream (`UpdateRepository`'s `upstreams`) or with an
|
||||
`AssociateExternalConnection` to a public repository serves packages from those sources too, not
|
||||
just its own; a repository has one or the other, never both. Floci's Maven endpoint does this
|
||||
@@ -456,18 +541,18 @@ state.
|
||||
requires clients to accept HTML as a fallback and pip/uv both do, but it is a real gap against
|
||||
AWS's documented surface, not just a quirk of the sidecar.
|
||||
- **`DescribePackageVersion` reports only format/namespace/packageName/version/revision/status/origin
|
||||
for Maven, npm, pypi, and nuget, same as it does for generic.** Real CodeArtifact's `PackageVersionDescription`
|
||||
for Maven, npm, pypi, nuget, and cargo, same as it does for generic.** Real CodeArtifact's `PackageVersionDescription`
|
||||
can also carry `displayName`, `summary`, `homePage`, `sourceCodeRepository`, `licenses`, and
|
||||
`publishedTime`, extracted from the package's own metadata; none of those are populated for any
|
||||
format today, container-backed or generic. For all four, the version's existence is
|
||||
format today, container-backed or generic. For all five, the version's existence is
|
||||
confirmed directly against its sidecar (`RepositorySidecarManager.packageVersionExists`) rather
|
||||
than through the generic-format-only `packageVersions` record `GetPackageVersionAsset`'s own
|
||||
bridge also moved past, and the revision is synthesized the same deterministic way
|
||||
`GetPackageVersionAsset`'s bridge already does, so describing a version and then fetching one of
|
||||
its assets see the same revision. Every sidecar-backed version reports `Published`: none of
|
||||
these four formats' native publish paths (`mvn deploy`, `npm publish`, `twine upload`, `nuget
|
||||
push`) can leave a version in any other status the way a generic publish deliberately can with
|
||||
`unfinished=true`.
|
||||
these five formats' native publish paths (`mvn deploy`, `npm publish`, `twine upload`, `nuget
|
||||
push`, `cargo publish`) can leave a version in any other status the way a generic publish
|
||||
deliberately can with `unfinished=true`.
|
||||
- **The nuget repository endpoint advertises no `RegistrationsBaseUrl` or `SearchQueryService`
|
||||
resource.** `nuget install`/`dotnet add package`/`dotnet restore` resolve a package's versions
|
||||
and dependencies from `PackageBaseAddress` alone (each version's own `.nuspec`, fetched directly,
|
||||
@@ -478,38 +563,43 @@ state.
|
||||
- **`DescribePackage`'s origin controls default to `publish: ALLOW`/`upstream: BLOCK`** (the
|
||||
default for a package whose first version was published directly) **until a caller sets them
|
||||
explicitly with `PutPackageOriginConfiguration`, or until the package's first version is
|
||||
retained from a Maven external connection, which instead defaults it to `publish: BLOCK`/
|
||||
`upstream: ALLOW`**, matching AWS's own documented "ingested from a public source" default. For
|
||||
Maven, npm, pypi, and nuget, `DescribePackage` asks the
|
||||
retained from an external connection, which instead defaults it to `publish: BLOCK`/
|
||||
`upstream: ALLOW`**, matching AWS's own documented "ingested from a public source" default
|
||||
(the same default now applies to a cargo crate retained from `public:crates-io`, since
|
||||
`ensureRetainedPackageOriginDefaultIfCurrentRepository` is already fully format-agnostic). For
|
||||
Maven, npm, pypi, nuget, and cargo, `DescribePackage` asks the
|
||||
repository's sidecar whether the package exists, which starts that sidecar if it is not already
|
||||
running; a package that exists only because `PutPackageOriginConfiguration` created it (no
|
||||
versions yet) is found without touching any sidecar.
|
||||
- **`PutPackageOriginConfiguration`'s `publish: BLOCK` is only enforced for the `generic`
|
||||
format.** `PublishPackageVersion`, the one path it actually gates, accepts only `generic` to
|
||||
begin with; Maven, npm, pypi, and nuget publishes go through their own native wire protocol (`mvn
|
||||
deploy`, `npm publish`, `twine upload`, `nuget push`) directly against the repository endpoint,
|
||||
which does not yet check this setting. `upstream` is stored and reported faithfully for every
|
||||
- **`PutPackageOriginConfiguration`'s `publish: BLOCK` is enforced for every format.**
|
||||
`PublishPackageVersion` is the direct-publish path for `generic`; Maven, npm, pypi, nuget, and
|
||||
cargo each check the same `requireContainerBackedPackagePublishAllowed` gate from their own
|
||||
native wire protocol (`mvn deploy`, `npm publish`, `twine upload`, `nuget push`, `cargo publish`)
|
||||
directly against the repository endpoint. `upstream` is stored and reported faithfully for every
|
||||
format, and gates every format's own external-connection retention and repository-to-repository
|
||||
upstream retention (both resolve for Maven, npm, pypi, and nuget; see above). `CopyPackageVersions`
|
||||
upstream retention (external-connection retention now resolves for cargo too, alongside Maven,
|
||||
npm, pypi, and nuget; cargo has no repository-to-repository upstream retention yet, see above).
|
||||
`CopyPackageVersions`
|
||||
deliberately does not check `publish: BLOCK`/`upstream: BLOCK` either, for any format, including
|
||||
its own `includeFromUpstream` search: the User Guide's own definition of both controls scopes
|
||||
them to direct publish/retention "using package managers or similar tools," a mechanism Copy is
|
||||
not.
|
||||
- **`DescribeDomain`'s `assetSizeBytes` only counts what was published after this field started
|
||||
being computed.** Generic-format bytes are summed live from the still-existing
|
||||
`PublishPackageVersion` records, so they're always current. Maven, npm, pypi, and nuget have no
|
||||
such record to sum (the same absent generic-format record `DescribePackageVersion`'s own bridge works
|
||||
around by asking the sidecar directly instead), so each proxy reports its own successfully-written
|
||||
byte count directly; a package published through one of those four formats
|
||||
`PublishPackageVersion` records, so they're always current. Maven, npm, pypi, nuget, and cargo
|
||||
have no such record to sum (the same absent generic-format record `DescribePackageVersion`'s own
|
||||
bridge works around by asking the sidecar directly instead), so each proxy reports its own
|
||||
successfully-written byte count directly; a package published through one of those five formats
|
||||
before this accounting existed was never reported and is not retroactively counted. A genuine
|
||||
conflict or an idempotent no-op retry (any of the four formats' own duplicate-publish protection)
|
||||
correctly adds nothing either way. Both `DeleteRepository` and `DeletePackage` clean
|
||||
conflict or an idempotent no-op retry (any of the four byte-identical-retry formats' own
|
||||
duplicate-publish protection; cargo's own publish rejects any republish outright instead, see
|
||||
above) correctly adds nothing either way. Both `DeleteRepository` and `DeletePackage` clean
|
||||
up every format's own records and byte counts (and, for `DeleteRepository`, the per-version
|
||||
asset content underneath them), so a repository or package recreated under the same name never
|
||||
inherits a predecessor's bytes. Maven/npm/pypi/nuget byte counts live only in memory, the same as the
|
||||
sidecar content they describe (see the restart limitation below), not through `StorageFactory`
|
||||
like every durable store here: the content these bytes count does not survive a restart either,
|
||||
so neither does the count.
|
||||
inherits a predecessor's bytes. Maven/npm/pypi/nuget/cargo byte counts live only in memory, the
|
||||
same as the sidecar content they describe (see the restart limitation below), not through
|
||||
`StorageFactory` like every durable store here: the content these bytes count does not survive a
|
||||
restart either, so neither does the count.
|
||||
- **A whole-package `npm unpublish` is accounted for; unpublishing a single version of a
|
||||
multi-version package is not.** The pinned Verdaccio image is configured to honor `npm
|
||||
unpublish` natively (`unpublish: $all`), bypassing `DeletePackage` entirely; the npm data plane
|
||||
@@ -528,9 +618,14 @@ state.
|
||||
- **Package groups enforce `PUBLISH`, `EXTERNAL_UPSTREAM`, and `INTERNAL_UPSTREAM`.** `PUBLISH` is
|
||||
wired into the one package-level origin check every direct-publish path already shares
|
||||
(`PublishPackageVersion`'s own `generic`-format path and every native proxy controller's own
|
||||
publish guard, `mvn deploy`/`npm publish`/`twine upload`/`nuget push` alike); every
|
||||
format's external-connection retention (Maven, npm, pypi, NuGet) is wired to the resolved
|
||||
`EXTERNAL_UPSTREAM` mode; and every format's repository-to-repository upstream retention
|
||||
publish guard, `mvn deploy`/`npm publish`/`twine upload`/`nuget push`/`cargo publish` alike);
|
||||
`EXTERNAL_UPSTREAM` and `INTERNAL_UPSTREAM` only apply where a format has retention to gate in
|
||||
the first place; cargo's own external-connection retention is gated by `EXTERNAL_UPSTREAM` the
|
||||
same way the other four formats' already are (`isUpstreamRetentionBlocked`'s own check is fully
|
||||
format-agnostic), but `INTERNAL_UPSTREAM` still never reaches cargo, since it has no
|
||||
repository-to-repository upstream resolution yet (see above). For the formats that do: every
|
||||
format's external-connection retention (Maven, npm, pypi, NuGet, and now cargo) is wired to the
|
||||
resolved `EXTERNAL_UPSTREAM` mode; and every format's repository-to-repository upstream retention
|
||||
(`UpdateRepository`'s `upstreams`) is wired to the resolved `INTERNAL_UPSTREAM` mode the same
|
||||
way. All three follow the "`BLOCK` always wins over `ALLOW`" interaction between a package's own
|
||||
origin configuration and its associated group's, and all three block a weak pattern match
|
||||
@@ -557,3 +652,4 @@ See the [CodeArtifact API Reference](https://docs.aws.amazon.com/codeartifact/la
|
||||
| `FLOCI_SERVICES_CODEARTIFACT_NPM_IMAGE` | `verdaccio/verdaccio:6.10.4` | Verdaccio image used to serve the `npm` format |
|
||||
| `FLOCI_SERVICES_CODEARTIFACT_PYPI_IMAGE` | `pypiserver/pypiserver:v2.4.2` | pypiserver image used to serve the `pypi` format |
|
||||
| `FLOCI_SERVICES_CODEARTIFACT_NUGET_IMAGE` | `bagetter/bagetter:1.6.5` | BaGetter image used to serve the `nuget` format |
|
||||
| `FLOCI_SERVICES_CODEARTIFACT_CARGO_IMAGE` | `ghcr.io/kellnr/kellnr:5.14.1` | Kellnr image used to serve the `cargo` format |
|
||||
@@ -945,6 +945,15 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
@WithDefault("bagetter/bagetter:1.6.5")
|
||||
String nugetImage();
|
||||
|
||||
/**
|
||||
* Image used for the per-repository Kellnr container backing the {@code cargo} format.
|
||||
* Same reasoning as {@link #npmImage()}: Kellnr has no native concept of multiple named
|
||||
* registries inside one instance either, so this gets one container per CodeArtifact
|
||||
* repository too, and there is no single external instance a URL override could name.
|
||||
*/
|
||||
@WithDefault("ghcr.io/kellnr/kellnr:5.14.1")
|
||||
String cargoImage();
|
||||
}
|
||||
|
||||
interface ConnectServiceConfig {
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.core.common.StreamingResponses;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A real outbound client for the one public Cargo (Rust) repository CodeArtifact's {@code
|
||||
* public:crates-io} external connection names (confirmed real and documented from AWS's own
|
||||
* {@code external-connection.html}, "Rust | Crates.io | public:crates-io"): the real sparse
|
||||
* HTTP index at {@code index.crates.io} and the real {@code .crate} download host at {@code
|
||||
* static.crates.io}, both confirmed live, not assumed:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code https://index.crates.io/config.json} (fetched live): {@code {"dl":
|
||||
* "https://static.crates.io/crates","api":"https://crates.io"}}, confirming the download
|
||||
* template below via the RFC 2789 "no markers" rule.</li>
|
||||
* <li>{@code https://index.crates.io/li/bc/libc} (fetched live): a real per-crate index file,
|
||||
* newline-delimited JSON, one line per version.</li>
|
||||
* <li>{@code https://static.crates.io/crates/libc/0.2.169/download} (fetched live): {@code
|
||||
* 200}, {@code application/gzip}, the real {@code .crate} bytes directly, no redirect observed
|
||||
* for this case (this client still follows redirects defensively, the same as {@link
|
||||
* NuGetExternalConnectionClient}).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Every failure mode (an unknown connection name, a real non-200 response, a network error)
|
||||
* resolves to {@link Optional#empty()} rather than throwing, the same reasoning {@link
|
||||
* NuGetExternalConnectionClient}'s own javadoc gives: a caller here is always deciding whether to
|
||||
* retain something from an external source, and the documented behavior for an unreachable
|
||||
* external repository is to behave exactly as if the content were not found.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CargoExternalConnectionClient {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CargoExternalConnectionClient.class);
|
||||
|
||||
private static final Map<String, String> INDEX_BASE_URLS = Map.of(
|
||||
"public:crates-io", "https://index.crates.io");
|
||||
private static final Map<String, String> DOWNLOAD_BASE_URLS = Map.of(
|
||||
"public:crates-io", "https://static.crates.io/crates");
|
||||
// A real sparse-index file is plain newline-delimited JSON, one short line per published
|
||||
// version; even crates.io's own most-published crates never approach this, but the real
|
||||
// upstream's own response size is otherwise unbounded, so this is checked during the read
|
||||
// itself rather than only after buffering an arbitrarily large response whole.
|
||||
private static final int MAX_SPARSE_INDEX_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final Map<String, String> indexBaseUrls;
|
||||
private final Map<String, String> downloadBaseUrls;
|
||||
|
||||
@Inject
|
||||
public CargoExternalConnectionClient() {
|
||||
this(HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL).build(), INDEX_BASE_URLS, DOWNLOAD_BASE_URLS);
|
||||
}
|
||||
|
||||
/** For tests: fake base-URL maps, so the wire contract can be exercised against a local
|
||||
* {@code HttpServer} fake instead of the real public registry. */
|
||||
CargoExternalConnectionClient(HttpClient httpClient, Map<String, String> indexBaseUrls,
|
||||
Map<String, String> downloadBaseUrls) {
|
||||
this.httpClient = httpClient;
|
||||
this.indexBaseUrls = indexBaseUrls;
|
||||
this.downloadBaseUrls = downloadBaseUrls;
|
||||
}
|
||||
|
||||
/**
|
||||
* The real, complete sparse-index bytes for {@code packageName} from the real public
|
||||
* registry {@code externalConnectionName} names: every version line this crate's real index
|
||||
* file currently carries, confirmed to be small enough to always buffer whole (a real crate's
|
||||
* own index file, unlike a {@code .crate} itself, is plain newline-delimited JSON text, never
|
||||
* sized anywhere near the asset quota).
|
||||
*/
|
||||
public Optional<byte[]> fetchSparseIndex(String externalConnectionName, String packageName) {
|
||||
String baseUrl = indexBaseUrls.get(externalConnectionName);
|
||||
if (baseUrl == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + SidecarUriUtils.cratesIoBucketPath(packageName));
|
||||
HttpResponse<InputStream> response;
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(20)).GET().build();
|
||||
response = httpClient.send(request, BodyHandlers.ofInputStream());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return Optional.empty();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not fetch {0}''s real sparse index from external connection {1}: {2}", packageName,
|
||||
externalConnectionName, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
StreamingResponses.closeQuietly(response.body());
|
||||
return Optional.empty();
|
||||
}
|
||||
try (InputStream body = response.body()) {
|
||||
byte[] bytes = body.readNBytes(MAX_SPARSE_INDEX_BYTES + 1);
|
||||
if (bytes.length > MAX_SPARSE_INDEX_BYTES) {
|
||||
LOG.warnv("Skipping {0}''s real sparse index from external connection {1}: larger than {2} bytes.",
|
||||
packageName, externalConnectionName, MAX_SPARSE_INDEX_BYTES);
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(bytes);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not read {0}''s real sparse index from external connection {1}: {2}", packageName,
|
||||
externalConnectionName, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** One crate version's real size and SHA-256, fetched straight to {@code destination} without
|
||||
* ever being held whole in memory: both come from the same streamed copy, via {@link
|
||||
* AssetDigestingInputStream}, rather than a second whole-file read just to hash it afterward. */
|
||||
public record FetchedFile(long size, String sha256) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches {@code packageName}/{@code version}'s real {@code .crate} bytes from the real
|
||||
* public registry {@code externalConnectionName} names, streamed straight to {@code
|
||||
* destination}. Capped at {@code CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES} during the
|
||||
* copy itself, via {@link AssetDigestingInputStream}, the same reasoning {@link
|
||||
* NuGetExternalConnectionClient#fetchPackage(String, String, String, Path)}'s own javadoc
|
||||
* gives: the real registry's own file size is otherwise unbounded and isn't known until the
|
||||
* download is already in progress.
|
||||
*/
|
||||
public Optional<FetchedFile> fetchCrate(String externalConnectionName, String packageName, String version,
|
||||
Path destination) {
|
||||
String baseUrl = downloadBaseUrls.get(externalConnectionName);
|
||||
if (baseUrl == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
URI uri = SidecarUriUtils.combine(URI.create(baseUrl), "/" + SidecarUriUtils.encodeSegment(packageName) + "/"
|
||||
+ SidecarUriUtils.encodeSegment(version) + "/download");
|
||||
HttpResponse<InputStream> response;
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(SidecarUriUtils.maxTransferTimeout()).GET()
|
||||
.build();
|
||||
response = httpClient.send(request, BodyHandlers.ofInputStream());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return Optional.empty();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not fetch {0} {1} from external connection {2}: {3}", packageName, version,
|
||||
externalConnectionName, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
StreamingResponses.closeQuietly(response.body());
|
||||
return Optional.empty();
|
||||
}
|
||||
try (InputStream body = response.body()) {
|
||||
AssetDigestingInputStream digesting = new AssetDigestingInputStream(body,
|
||||
CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES);
|
||||
Files.copy(digesting, destination, StandardCopyOption.REPLACE_EXISTING);
|
||||
return Optional.of(new FetchedFile(digesting.size(), digesting.hashesHex().get("SHA-256")));
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not read {0} {1} from external connection {2}: {3}", packageName, version,
|
||||
externalConnectionName, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.StreamingResponses;
|
||||
import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.GET;
|
||||
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.io.BufferedInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* Serves the real Cargo (Rust) wire protocol behind the URL {@code GetRepositoryEndpoint} returns
|
||||
* for the {@code cargo} format: the sparse HTTP registry index (RFC 2789) and the publish/download
|
||||
* REST API AWS's own "Configure and use Cargo with CodeArtifact" guide documents, not a
|
||||
* CodeArtifact API action. Backed by one Kellnr container per repository, provisioned on first
|
||||
* use (see {@link KellnrSidecarManager}/{@link KellnrSidecarClient} for the sidecar itself).
|
||||
*
|
||||
* <p>Authors its own {@code config.json} rather than proxying Kellnr's own: Kellnr's own response
|
||||
* self-reports its own internal container address (confirmed live), exactly the problem {@link
|
||||
* RepositorySidecarManager#ensureReady}'s {@code publicUrl} parameter exists for, and both the
|
||||
* {@code dl}/{@code api} it needs are a single combined base identical to this repository's own
|
||||
* real endpoint, matching how AWS's own CodeArtifact serves Cargo (one endpoint for index, API,
|
||||
* and downloads alike, unlike crates.io's own split between its index and its API host). The
|
||||
* sparse-index files themselves (one per crate) *are* proxied close to verbatim: unlike a
|
||||
* version's own downloadable asset, nothing in that response is self-referential (a real client
|
||||
* derives the download URL from {@code config.json}'s own {@code dl} template, never from a field
|
||||
* inside an index entry), so there is nothing here to rewrite.
|
||||
*
|
||||
* <p>Requires the token real CodeArtifact requires here, obtained from {@code
|
||||
* GetAuthorizationToken}. AWS's own Cargo configuration doc has the client send it as a bare
|
||||
* {@code Authorization} header with no scheme prefix at all (confirmed from the Cargo Book's own
|
||||
* registry-authentication page); {@link CodeArtifactTokenExtractor} accepts that alongside the
|
||||
* Bearer/Basic schemes every other format already uses.
|
||||
*
|
||||
* <p>Only the subcommands AWS's own guide documents against CodeArtofact: {@code cargo add}/
|
||||
* {@code cargo build} (the sparse index plus the download route) and {@code cargo publish}. No
|
||||
* {@code yank}/{@code owner}/search routes: AWS's own guide never mentions any of the three, so
|
||||
* this isn't filling a real, documented gap by building them.
|
||||
*/
|
||||
@Path("/codeartifact/cargo/{domain}/{repository}/{path:.+}")
|
||||
public class CodeArtifactCargoController {
|
||||
|
||||
private static final String PUBLISH_PATH = "api/v1/crates/new";
|
||||
private static final String DOWNLOAD_PREFIX = "api/v1/crates/";
|
||||
private static final String DOWNLOAD_SUFFIX = "/download";
|
||||
private static final String CONFIG_PATH = "config.json";
|
||||
// A real publish's own metadata (name, version, deps, features, authors, etc.) is plain JSON
|
||||
// text, always well under a megabyte even for a crate with an unusually large dependency
|
||||
// list; this is a generous ceiling, not a realistic average, against the wire body's own
|
||||
// 4-byte client-declared metadata length driving an allocation far larger than the staged
|
||||
// file could ever actually need before the crate's own size is checked.
|
||||
private static final int MAX_PUBLISH_METADATA_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final KellnrSidecarClient kellnr;
|
||||
private final CodeArtifactCargoExternalConnectionImporter externalConnectionImporter;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactCargoController(CodeArtifactService service, KellnrSidecarClient kellnr,
|
||||
CodeArtifactCargoExternalConnectionImporter externalConnectionImporter, ObjectMapper mapper) {
|
||||
this.service = service;
|
||||
this.kellnr = kellnr;
|
||||
this.externalConnectionImporter = externalConnectionImporter;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
private record RepositoryHandle(String repoId, String region, String owner, String publicBaseUrl) {
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.WILDCARD)
|
||||
public Response get(@Context HttpHeaders headers, @PathParam("domain") String domain,
|
||||
@PathParam("repository") String repository, @PathParam("path") String path) {
|
||||
RepositoryHandle handle = requireRepository(headers, domain, repository);
|
||||
AtomicBoolean leaseTransferred = new AtomicBoolean();
|
||||
try {
|
||||
return getWithLease(handle, domain, repository, path, leaseTransferred);
|
||||
} finally {
|
||||
if (!leaseTransferred.get()) {
|
||||
endUse(handle.repoId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Response getWithLease(RepositoryHandle handle, String domain, String repository, String path,
|
||||
AtomicBoolean leaseTransferred) {
|
||||
if (CONFIG_PATH.equals(path)) {
|
||||
return configJson(handle);
|
||||
}
|
||||
Optional<String[]> download = parseDownloadPath(path);
|
||||
if (download.isPresent()) {
|
||||
return downloadCrate(handle, domain, repository, download.get()[0], download.get()[1], leaseTransferred);
|
||||
}
|
||||
return sparseIndexLookup(handle, domain, repository, path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cargo's own sparse-index discovery document, authored directly rather than proxied (see
|
||||
* this class's own javadoc for why): {@code dl}/{@code api} both rooted at this repository's
|
||||
* own real {@code GetRepositoryEndpoint} value, the same "always the real, externally-reachable
|
||||
* address, never this emulator's own internal one" rule {@code CodeArtifactNuGetController
|
||||
* .serviceIndex} already follows. {@code auth-required: true} matches real CodeArtifact's own
|
||||
* behavior: every request here, read or write, already requires a valid token.
|
||||
*/
|
||||
private Response configJson(RepositoryHandle handle) {
|
||||
String body = """
|
||||
{
|
||||
"dl": "%1$s/api/v1/crates",
|
||||
"api": "%1$s",
|
||||
"auth-required": true
|
||||
}
|
||||
""".formatted(handle.publicBaseUrl());
|
||||
return Response.status(200).entity(body).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response downloadCrate(RepositoryHandle handle, String domain, String repository, String packageName,
|
||||
String version, AtomicBoolean leaseTransferred) {
|
||||
try {
|
||||
service.requireContainerBackedVersionDownloadable(handle.owner(), handle.region(), domain, repository,
|
||||
"cargo", null, packageName, version, handle.repoId());
|
||||
} catch (AwsException e) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
// A cache miss on this emulator's own Kellnr is exactly the trigger AWS's own docs
|
||||
// describe for an external connection: fetch the real crate from crates.io and retain it,
|
||||
// then let the stream below find it there, the same as any other request. Not attempted
|
||||
// at all when Kellnr already has it: the only extra cost on every other request is this
|
||||
// one cheap local existence check, the same pattern CodeArtifactNuGetController's own
|
||||
// .nupkg route already uses.
|
||||
if (!kellnr.packageVersionExists(handle.repoId(), domain, repository, null, packageName, version)) {
|
||||
externalConnectionImporter.tryImport(handle.region(), domain, handle.owner(), repository,
|
||||
handle.repoId(), packageName, version);
|
||||
}
|
||||
Optional<RepositorySidecarManager.StreamedAsset> streamed = kellnr.fetchPackageVersionAssetStreamed(
|
||||
handle.repoId(), domain, repository, null, packageName, version,
|
||||
packageName + "-" + version + ".crate");
|
||||
if (streamed.isEmpty()) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
leaseTransferred.set(true);
|
||||
InputStream body = StreamingResponses.closingWith(streamed.get().content(), () -> endUse(handle.repoId()));
|
||||
Response.ResponseBuilder builder = Response.status(200).type(MediaType.APPLICATION_OCTET_STREAM);
|
||||
if (streamed.get().contentLength() >= 0) {
|
||||
builder.header("Content-Length", streamed.get().contentLength());
|
||||
}
|
||||
return StreamingResponses.streamingResponse(body, stream -> builder.entity(stream).build());
|
||||
}
|
||||
|
||||
/**
|
||||
* The real sparse-index bytes for the crate {@code path}'s own last segment names (the real
|
||||
* crates.io bucketing scheme, confirmed live in part 1: a 1/2/3-character name buckets by its
|
||||
* own length or first character, a 4+-character name by its own first two then next two
|
||||
* characters: in every case, the crate's real name is the path's own final segment), proxied
|
||||
* close to verbatim. Not filtered by Archived/Disposed status here: see this class's own
|
||||
* javadoc for why that mapping is deliberately deferred rather than guessed at.
|
||||
*
|
||||
* <p>Merged with any real upstream-only version lines the repository's own {@code
|
||||
* public:crates-io} external connection can see (see {@link
|
||||
* CodeArtifactCargoExternalConnectionImporter}'s own javadoc for why this, unlike every other
|
||||
* format's own external-connection importer, needs a listing merge and not just an
|
||||
* on-demand download): a real {@code cargo} client's dependency resolver only ever sees a
|
||||
* version by first finding it here.
|
||||
*/
|
||||
private Response sparseIndexLookup(RepositoryHandle handle, String domain, String repository, String path) {
|
||||
int lastSlash = path.lastIndexOf('/');
|
||||
String packageName = lastSlash >= 0 ? path.substring(lastSlash + 1) : path;
|
||||
if (packageName.isEmpty()) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
Optional<byte[]> local = kellnr.fetchSparseIndexRaw(handle.repoId(), domain, repository, packageName);
|
||||
Optional<byte[]> merged = externalConnectionImporter.mergeExternalVersions(handle.region(), domain,
|
||||
handle.owner(), repository, packageName, local);
|
||||
return merged.map(bytes -> Response.status(200).entity(bytes).type(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.build())
|
||||
.orElseGet(() -> Response.status(404).build());
|
||||
}
|
||||
|
||||
/** {@code api/v1/crates/{name}/{version}/download} → {@code [name, version]}, else empty. */
|
||||
private static Optional<String[]> parseDownloadPath(String path) {
|
||||
if (!path.startsWith(DOWNLOAD_PREFIX) || !path.endsWith(DOWNLOAD_SUFFIX)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String middle = path.substring(DOWNLOAD_PREFIX.length(), path.length() - DOWNLOAD_SUFFIX.length());
|
||||
int lastSlash = middle.lastIndexOf('/');
|
||||
if (lastSlash <= 0 || lastSlash == middle.length() - 1) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new String[] {middle.substring(0, lastSlash), middle.substring(lastSlash + 1)});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a real {@code cargo publish}: {@code PUT} to {@code api/v1/crates/new}, the real
|
||||
* binary wire body (4-byte little-endian metadata length + JSON metadata, then 4-byte
|
||||
* little-endian crate length + the {@code .crate} itself) confirmed directly from the Cargo
|
||||
* Book's own spec text and live against Kellnr in part 1. The whole body is staged to disk
|
||||
* before anything else touches it (never a resident array: a {@code .crate} can approach the
|
||||
* same 5 GB AWS quota any other format's asset can), then forwarded to Kellnr verbatim via
|
||||
* {@link KellnrSidecarClient#publishRawWireBody}: the real client's own metadata, dependency
|
||||
* list included, must survive untouched, the reason that method exists separately from {@link
|
||||
* KellnrSidecarClient#storePackageVersionAsset}'s own reconstructed-metadata path.
|
||||
*/
|
||||
@PUT
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response publish(@Context HttpHeaders headers, @PathParam("domain") String domain,
|
||||
@PathParam("repository") String repository, @PathParam("path") String path,
|
||||
InputStream body) {
|
||||
if (!PUBLISH_PATH.equals(path)) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
RepositoryHandle handle = requireRepository(headers, domain, repository);
|
||||
try {
|
||||
return publishWithLease(handle, domain, repository, body);
|
||||
} finally {
|
||||
endUse(handle.repoId());
|
||||
}
|
||||
}
|
||||
|
||||
private Response publishWithLease(RepositoryHandle handle, String domain, String repository, InputStream body) {
|
||||
java.nio.file.Path staged;
|
||||
try {
|
||||
staged = service.stageAssetBody(
|
||||
new AssetDigestingInputStream(body, CodeArtifactService.MAX_MULTIPART_ENVELOPE_BYTES));
|
||||
} catch (AssetDigestingInputStream.AssetTooLargeException e) {
|
||||
return Response.status(413).build();
|
||||
}
|
||||
try {
|
||||
return publishStagedBody(handle, domain, repository, staged);
|
||||
} finally {
|
||||
service.deleteStagedAssetBody(staged);
|
||||
}
|
||||
}
|
||||
|
||||
private Response publishStagedBody(RepositoryHandle handle, String domain, String repository,
|
||||
java.nio.file.Path staged) {
|
||||
CargoPublishMetadata metadata;
|
||||
long stagedSize;
|
||||
try {
|
||||
stagedSize = Files.size(staged);
|
||||
metadata = readMetadataPrefix(staged);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return Response.status(400).entity(e.getMessage()).build();
|
||||
}
|
||||
// The crate's own real size, not the whole wire body (metadata included): the same 5 GB
|
||||
// AWS quota PublishPackageVersion enforces, checked against the real asset bytes alone,
|
||||
// the same way CodeArtifactNuGetController#pushExtractedForm checks the real .nupkg size
|
||||
// rather than the surrounding multipart envelope.
|
||||
long crateLength = stagedSize - 4 - metadata.metadataLength() - 4;
|
||||
if (crateLength > CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES) {
|
||||
return Response.status(413).build();
|
||||
}
|
||||
try {
|
||||
service.requireContainerBackedPackagePublishAllowed(handle.region(), domain, handle.owner(), repository,
|
||||
"cargo", null, metadata.name());
|
||||
} catch (AwsException e) {
|
||||
return Response.status(409).entity(e.getMessage()).build();
|
||||
}
|
||||
String beforeRevision;
|
||||
try {
|
||||
beforeRevision = service.requireContainerBackedVersionNotArchivedOrDisposed(handle.region(), domain,
|
||||
handle.owner(), repository, "cargo", null, metadata.name(), metadata.version());
|
||||
} catch (AwsException e) {
|
||||
return Response.status(409).entity(e.getMessage()).build();
|
||||
}
|
||||
long fenceSnapshot = service.currentContainerBackedPackageFence(handle.region(), domain, handle.owner(),
|
||||
repository, "cargo", null, metadata.name());
|
||||
KellnrSidecarClient.KellnrPublishResult result;
|
||||
synchronized (kellnr.lockFor(handle.repoId())) {
|
||||
result = kellnr.publishRawWireBody(handle.repoId(), staged, stagedSize);
|
||||
}
|
||||
if (result.statusCode() != 200) {
|
||||
// Kellnr's own real rejection (e.g. a republish of an already-existing name/version,
|
||||
// see KellnrSidecarClient#publishRawWireBody's own javadoc) is already shaped exactly
|
||||
// like the Cargo Book's own documented error response: forward it verbatim rather than
|
||||
// translating it into something this controller invents.
|
||||
return Response.status(result.statusCode()).entity(result.body()).type(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
}
|
||||
service.completeContainerBackedPublishIfCurrentRepository(handle.region(), domain, handle.owner(), repository,
|
||||
handle.repoId(), "cargo", metadata.name(), metadata.version(), crateLength, fenceSnapshot,
|
||||
beforeRevision, null, 0L);
|
||||
return Response.status(200).entity("{\"warnings\":null}").type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private record CargoPublishMetadata(String name, String version, int metadataLength) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads just the wire body's own leading length-prefixed JSON metadata (never the crate bytes
|
||||
* that follow it) to learn {@code name}/{@code version}, the same real binary layout {@link
|
||||
* KellnrSidecarClient#publishRawWireBody}'s own javadoc documents.
|
||||
*/
|
||||
private CargoPublishMetadata readMetadataPrefix(java.nio.file.Path staged) throws IOException {
|
||||
try (InputStream in = new BufferedInputStream(Files.newInputStream(staged))) {
|
||||
byte[] lengthBytes = in.readNBytes(4);
|
||||
if (lengthBytes.length != 4) {
|
||||
throw new IllegalArgumentException("Truncated publish body: missing the metadata length prefix.");
|
||||
}
|
||||
int metadataLength = ByteBuffer.wrap(lengthBytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
|
||||
if (metadataLength < 0 || metadataLength > MAX_PUBLISH_METADATA_BYTES) {
|
||||
throw new IllegalArgumentException("Publish body's own declared metadata length ("
|
||||
+ metadataLength + " bytes) is not a reasonable size.");
|
||||
}
|
||||
byte[] metadataBytes = in.readNBytes(metadataLength);
|
||||
if (metadataBytes.length != metadataLength) {
|
||||
throw new IllegalArgumentException("Truncated publish body: metadata shorter than its own "
|
||||
+ "declared length.");
|
||||
}
|
||||
JsonNode metadata;
|
||||
try {
|
||||
metadata = mapper.readTree(metadataBytes);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("Could not parse the publish body's own metadata as JSON.");
|
||||
}
|
||||
String name = metadata.path("name").asText(null);
|
||||
String version = metadata.path("vers").asText(null);
|
||||
if (name == null || name.isBlank() || version == null || version.isBlank()) {
|
||||
throw new IllegalArgumentException("Publish metadata is missing a crate name or version.");
|
||||
}
|
||||
return new CargoPublishMetadata(name, version, metadataLength);
|
||||
}
|
||||
}
|
||||
|
||||
private void endUse(String repoId) {
|
||||
kellnr.endUse(repoId);
|
||||
}
|
||||
|
||||
private RepositoryHandle requireRepository(HttpHeaders headers, String domain, String repository) {
|
||||
String token = CodeArtifactTokenExtractor.extractToken(headers);
|
||||
// No WWW-Authenticate scheme challenge: unlike Maven/pypi/NuGet (genuinely Basic, per
|
||||
// AWS's own docs) or npm (genuinely Bearer), a real cargo client's own token has no named
|
||||
// HTTP auth scheme at all (it's sent as a bare Authorization value), so naming one here
|
||||
// would misleadingly suggest a scheme real CodeArtifact doesn't actually expect for Cargo.
|
||||
AuthorizationTokenScope scope = service.resolveAuthorizationToken(token, domain)
|
||||
.orElseThrow(() -> new NotAuthorizedException(Response.status(401).build()));
|
||||
String repoId;
|
||||
try {
|
||||
repoId = service.resolveContainerIdAndBeginUse("cargo", scope.region(), domain, scope.owner(), repository,
|
||||
kellnr);
|
||||
} catch (AwsException e) {
|
||||
throw new NotFoundException();
|
||||
}
|
||||
try {
|
||||
String endpoint = service.getRepositoryEndpoint(scope.region(), domain, scope.owner(), repository,
|
||||
"cargo", null);
|
||||
String publicBaseUrl = endpoint.endsWith("/") ? endpoint.substring(0, endpoint.length() - 1) : endpoint;
|
||||
return new RepositoryHandle(repoId, scope.region(), scope.owner(), publicBaseUrl);
|
||||
} catch (RuntimeException e) {
|
||||
endUse(repoId);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
+384
@@ -0,0 +1,384 @@
|
||||
package io.floci.aws.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 io.floci.aws.services.codeartifact.model.ExternalConnection;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Retains a Cargo crate version from the real public {@code crates.io} registry a repository's
|
||||
* {@code public:crates-io} external connection names, the way real CodeArtifact does when a
|
||||
* {@code cargo} client requests a crate version that is not present locally yet (confirmed real
|
||||
* and documented from AWS's own {@code external-connection.html}: "Rust | Crates.io |
|
||||
* public:crates-io"), mirroring {@link CodeArtifactNuGetExternalConnectionImporter}'s own
|
||||
* claim/fence/retention shell exactly.
|
||||
*
|
||||
* <p><b>One thing this format genuinely needs that NuGet/Maven/pypi don't</b>: {@link
|
||||
* CodeArtifactNuGetExternalConnectionImporter}'s own javadoc deliberately does not merge the real
|
||||
* upstream version listing into any local response, since a NuGet client can fetch a known {@code
|
||||
* .nupkg} URL directly without ever consulting a version-list index first. A real {@code cargo}
|
||||
* client cannot work that way: {@code cargo build}/{@code cargo add} always resolve against the
|
||||
* sparse index first, and the index for one crate name is a single file covering every version,
|
||||
* not a per-version URL. Skipping a listing merge the way NuGet does would make an upstream-only
|
||||
* crate invisible to Cargo's own resolver even though the download route alone could serve it.
|
||||
* {@link #mergeExternalVersions} is that merge: a pure, read-only proxy of the real upstream
|
||||
* index's own version lines not already known locally, never a retention write (Kellnr has no
|
||||
* "write an index entry without the crate bytes" capability, so there is nothing to write here
|
||||
* anyway). It takes no package fence snapshot the way {@code CodeArtifactService
|
||||
* #mergeMavenMetadataUnderPackageFence}'s own package-level merge does: that method guards a real,
|
||||
* persistent write to Reposilite's own {@code maven-metadata.xml} against a concurrent {@code
|
||||
* DeletePackage}/{@code DeleteRepository} resurrecting deleted content; this method never
|
||||
* persists anything at all, so the same race's worst case is a single HTTP response momentarily
|
||||
* showing a version that is concurrently being deleted, self-correcting on the very next request
|
||||
* once the deletion fence moves.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CodeArtifactCargoExternalConnectionImporter {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CodeArtifactCargoExternalConnectionImporter.class);
|
||||
|
||||
private final CodeArtifactService service;
|
||||
private final KellnrSidecarClient kellnr;
|
||||
private final CargoExternalConnectionClient externalConnectionClient;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public CodeArtifactCargoExternalConnectionImporter(CodeArtifactService service, KellnrSidecarClient kellnr,
|
||||
CargoExternalConnectionClient externalConnectionClient, ObjectMapper mapper) {
|
||||
this.service = service;
|
||||
this.kellnr = kellnr;
|
||||
this.externalConnectionClient = externalConnectionClient;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to retain {@code packageName}/{@code version}'s real {@code .crate} into {@code
|
||||
* repoId} from {@code repository}'s own cargo external connection. Returns {@code true} only
|
||||
* when the crate is genuinely present under this connection's claim by the time this returns,
|
||||
* whether because this attempt imported it or a concurrent one already had, the same contract
|
||||
* {@link CodeArtifactNuGetExternalConnectionImporter#tryImport}'s own javadoc documents.
|
||||
*/
|
||||
public boolean tryImport(String region, String domain, String owner, String repository, String repoId,
|
||||
String packageName, String version) {
|
||||
String externalConnectionName = cargoExternalConnectionName(region, domain, owner, repository);
|
||||
if (externalConnectionName == null) {
|
||||
return false;
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "cargo", null, packageName,
|
||||
"EXTERNAL_UPSTREAM")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
long packageFenceSnapshot = service.currentContainerBackedPackageFence(region, domain, owner, repository,
|
||||
"cargo", null, packageName);
|
||||
long versionFenceSnapshot = service.currentContainerBackedVersionFence(region, domain, owner, repository,
|
||||
"cargo", null, packageName, version);
|
||||
CodeArtifactService.RetainedVersionOriginClaimOutcome claim = service.claimRetainedVersionOrigin(region,
|
||||
domain, owner, repository, "cargo", null, packageName, version, externalConnectionName,
|
||||
RetentionOriginKind.EXTERNAL_CONNECTION, packageFenceSnapshot);
|
||||
if (!claim.claimed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean imported = false;
|
||||
try {
|
||||
if (kellnr.packageVersionExists(repoId, domain, repository, null, packageName, version)) {
|
||||
imported = service.retainedVersionOriginConnection(region, domain, owner, repository, "cargo", null,
|
||||
packageName, version).filter(externalConnectionName::equals).isPresent();
|
||||
return imported;
|
||||
}
|
||||
Optional<byte[]> index = externalConnectionClient.fetchSparseIndex(externalConnectionName, packageName);
|
||||
if (index.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
Optional<JsonNode> indexLine = findIndexLine(index.get(), version);
|
||||
if (indexLine.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
Path crateFile;
|
||||
try {
|
||||
crateFile = Files.createTempFile("codeartifact-cargo-import-", ".crate");
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to create a staging file for a Cargo external-connection "
|
||||
+ "import", e);
|
||||
}
|
||||
try {
|
||||
Optional<CargoExternalConnectionClient.FetchedFile> fetched;
|
||||
try {
|
||||
fetched = externalConnectionClient.fetchCrate(externalConnectionName, packageName, version,
|
||||
crateFile);
|
||||
} catch (AssetDigestingInputStream.AssetTooLargeException e) {
|
||||
LOG.warnv("Skipping {0} {1}: the real registry''s own file is larger than this emulator''s "
|
||||
+ "{2}-byte asset quota.", packageName, version,
|
||||
CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES);
|
||||
return false;
|
||||
}
|
||||
if (fetched.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String expectedSha256 = indexLine.get().path("cksum").asText(null);
|
||||
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(fetched.get().sha256())) {
|
||||
LOG.warnv("Skipping {0} {1}: its real bytes do not match the real index''s own cksum.",
|
||||
packageName, version);
|
||||
return false;
|
||||
}
|
||||
long contentLength = fetched.get().size();
|
||||
Path stagedWireBody = buildStagedWireBody(metadataFromIndexLine(indexLine.get()), crateFile);
|
||||
try {
|
||||
CodeArtifactService.AssetRetentionAttemptResult result = service.retainAssetUnderVersionFence(
|
||||
region, domain, owner, repository, "cargo", null, packageName, version,
|
||||
versionFenceSnapshot, packageFenceSnapshot, claim.episodeId(), repoId, packageName
|
||||
+ "-" + version + ".crate", contentLength,
|
||||
() -> {
|
||||
KellnrSidecarClient.KellnrPublishResult publishResult = kellnr.publishRawWireBody(
|
||||
repoId, stagedWireBody, fileSize(stagedWireBody));
|
||||
if (publishResult.statusCode() != 200) {
|
||||
throw new IllegalStateException("Kellnr refused this retained crate: upstream "
|
||||
+ "returned " + publishResult.statusCode());
|
||||
}
|
||||
});
|
||||
imported = result.fenceMatched() && result.wroteNewContent();
|
||||
return imported;
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(stagedWireBody);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Could not delete a staged Cargo external-connection wire-body file at {0}",
|
||||
stagedWireBody);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(crateFile);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Could not delete a staged Cargo external-connection crate file at {0}", crateFile);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (imported) {
|
||||
service.ensureRetainedPackageOriginDefaultIfCurrentRepository(region, domain, owner, repository,
|
||||
"cargo", null, packageName, packageFenceSnapshot, repoId);
|
||||
}
|
||||
service.finishRetainedVersionOriginAttempt(region, domain, owner, repository, "cargo", null, packageName,
|
||||
version, claim.episodeId(), imported);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code localIndexBytes}'s own real version lines, plus every real upstream-only version
|
||||
* line {@code packageName}'s own real {@code crates.io} index carries that isn't already a
|
||||
* local line, each upstream line passed through close to verbatim (never re-serialized),
|
||||
* matching the "proxy real content verbatim" philosophy {@code CodeArtifactCargoController}'s
|
||||
* own local sparse-index route already uses. A {@code BLOCK}ed package, or one with no cargo
|
||||
* external connection configured, gets {@code localIndexBytes} back unchanged: "behave exactly
|
||||
* as if the external content did not exist," the same rule every other retention path in this
|
||||
* codebase already follows.
|
||||
*/
|
||||
public Optional<byte[]> mergeExternalVersions(String region, String domain, String owner, String repository,
|
||||
String packageName, Optional<byte[]> localIndexBytes) {
|
||||
String externalConnectionName = cargoExternalConnectionName(region, domain, owner, repository);
|
||||
if (externalConnectionName == null) {
|
||||
return localIndexBytes;
|
||||
}
|
||||
if (service.isUpstreamRetentionBlocked(region, domain, owner, repository, "cargo", null, packageName,
|
||||
"EXTERNAL_UPSTREAM")) {
|
||||
return localIndexBytes;
|
||||
}
|
||||
Optional<byte[]> upstream = externalConnectionClient.fetchSparseIndex(externalConnectionName, packageName);
|
||||
if (upstream.isEmpty()) {
|
||||
return localIndexBytes;
|
||||
}
|
||||
List<String> localLines = splitLines(localIndexBytes.orElse(new byte[0]));
|
||||
List<String> upstreamLines = splitLines(upstream.get());
|
||||
Map<String, String> merged = new LinkedHashMap<>();
|
||||
for (String line : localLines) {
|
||||
indexLineVersion(line).ifPresent(vers -> merged.put(vers, line));
|
||||
}
|
||||
for (String line : upstreamLines) {
|
||||
indexLineVersion(line).ifPresent(vers -> merged.putIfAbsent(vers, line));
|
||||
}
|
||||
if (merged.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(String.join("\n", merged.values()).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private Optional<String> indexLineVersion(String line) {
|
||||
try {
|
||||
return Optional.ofNullable(mapper.readTree(line).path("vers").asText(null));
|
||||
} catch (IOException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> splitLines(byte[] indexBytes) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
for (String line : new String(indexBytes, StandardCharsets.UTF_8).split("\n")) {
|
||||
if (!line.isBlank()) {
|
||||
lines.add(line);
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private Optional<JsonNode> findIndexLine(byte[] indexBytes, String version) {
|
||||
for (String line : splitLines(indexBytes)) {
|
||||
JsonNode node;
|
||||
try {
|
||||
node = mapper.readTree(line);
|
||||
} catch (IOException e) {
|
||||
continue;
|
||||
}
|
||||
if (version.equals(node.path("vers").asText(null))) {
|
||||
return Optional.of(node);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* A real {@code cargo publish} metadata object built from {@code indexLine}'s own real
|
||||
* fields, the same honest, bounded limitation {@code KellnrSidecarClient
|
||||
* #minimalPublishMetadata} already documents for {@code CopyPackageVersions}: the real
|
||||
* index never carries {@code authors}/{@code description}/etc. at all (those live in the
|
||||
* {@code .crate}'s own embedded {@code Cargo.toml}, not the index), so those fields stay
|
||||
* null/empty here too. Unlike that method, {@code deps}/{@code features} are the crate's own
|
||||
* real values, not always empty: the real index already has them, confirmed from a live
|
||||
* fetch of {@code index.crates.io}'s own per-crate index file.
|
||||
*
|
||||
* <p>A renamed dependency's alias and real crate name swap fields between the two shapes
|
||||
* (confirmed from the Cargo Book's own registry-index/registry-web-api pages): the index puts
|
||||
* the alias in its own {@code name} and the real crate in {@code package}, while publish
|
||||
* metadata puts the real crate in {@code name} and the alias in {@code
|
||||
* explicit_name_in_toml}; an unrenamed dependency has no {@code package} field at all, and
|
||||
* its index {@code name} is already the real crate name. {@code req} is renamed to {@code
|
||||
* version_req} going the same way; every other dependency field name is identical in both
|
||||
* shapes. {@code features2} (namespaced/weak-dependency feature syntax crates.io splits out
|
||||
* for pre-1.19 Cargo compatibility) is merged into {@code features} rather than dropped, the
|
||||
* same merge the Cargo Book documents a real client performing on read. Top-level {@code
|
||||
* links} is identical in both shapes; top-level {@code rust_version} is carried over even
|
||||
* though crates.io itself re-derives it from the {@code .crate}'s own {@code Cargo.toml}
|
||||
* rather than trusting the index's copy.
|
||||
*/
|
||||
private byte[] metadataFromIndexLine(JsonNode indexLine) {
|
||||
ObjectNode metadata = mapper.createObjectNode();
|
||||
metadata.put("name", indexLine.path("name").asText());
|
||||
metadata.put("vers", indexLine.path("vers").asText());
|
||||
ArrayNode deps = metadata.putArray("deps");
|
||||
for (JsonNode dep : indexLine.path("deps")) {
|
||||
ObjectNode mappedDep = deps.addObject();
|
||||
String aliasInIndex = dep.path("name").asText(null);
|
||||
String realCrateName = dep.path("package").asText(null);
|
||||
if (realCrateName != null) {
|
||||
mappedDep.put("name", realCrateName);
|
||||
mappedDep.put("explicit_name_in_toml", aliasInIndex);
|
||||
} else {
|
||||
mappedDep.put("name", aliasInIndex);
|
||||
mappedDep.put("explicit_name_in_toml", (String) null);
|
||||
}
|
||||
mappedDep.put("version_req", dep.path("req").asText(null));
|
||||
mappedDep.set("features", dep.path("features"));
|
||||
mappedDep.put("optional", dep.path("optional").asBoolean(false));
|
||||
mappedDep.put("default_features", dep.path("default_features").asBoolean(true));
|
||||
mappedDep.set("target", dep.path("target").isMissingNode() ? mapper.nullNode() : dep.path("target"));
|
||||
mappedDep.put("kind", dep.path("kind").asText("normal"));
|
||||
mappedDep.put("registry", (String) null);
|
||||
}
|
||||
ObjectNode features = indexLine.path("features").isObject()
|
||||
? indexLine.path("features").deepCopy() : mapper.createObjectNode();
|
||||
if (indexLine.path("features2").isObject()) {
|
||||
features.setAll((ObjectNode) indexLine.path("features2"));
|
||||
}
|
||||
metadata.set("features", features);
|
||||
metadata.putArray("authors");
|
||||
metadata.put("description", (String) null);
|
||||
metadata.put("documentation", (String) null);
|
||||
metadata.put("homepage", (String) null);
|
||||
metadata.put("readme", (String) null);
|
||||
metadata.put("readme_file", (String) null);
|
||||
metadata.putArray("keywords");
|
||||
metadata.putArray("categories");
|
||||
metadata.put("license", (String) null);
|
||||
metadata.put("license_file", (String) null);
|
||||
metadata.put("repository", (String) null);
|
||||
metadata.putObject("badges");
|
||||
metadata.put("links", indexLine.path("links").asText(null));
|
||||
metadata.put("rust_version", indexLine.path("rust_version").asText(null));
|
||||
return metadata.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the real Cargo publish wire body (see {@code KellnrSidecarClient
|
||||
* #publishRawWireBody}'s own javadoc for its shape) straight to a staged file rather than one
|
||||
* resident {@code byte[]} the way {@code KellnrSidecarClient#publishWireBody} does for {@code
|
||||
* CopyPackageVersions}' own always-small, synthesized-empty-deps case: a crate retained
|
||||
* through an external connection can be sized anywhere up to the same 5 GB quota any other
|
||||
* asset can, so the header is written first and {@code crateFile}'s own real bytes are then
|
||||
* streamed straight through rather than ever held alongside it in memory.
|
||||
*/
|
||||
private static Path buildStagedWireBody(byte[] metadataJson, Path crateFile) {
|
||||
Path staged;
|
||||
try {
|
||||
staged = Files.createTempFile("codeartifact-cargo-import-wire-", ".bin");
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to create a staging file for a Cargo external-connection "
|
||||
+ "publish wire body", e);
|
||||
}
|
||||
try {
|
||||
long crateLength = Files.size(crateFile);
|
||||
try (OutputStream out = Files.newOutputStream(staged)) {
|
||||
out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(metadataJson.length).array());
|
||||
out.write(metadataJson);
|
||||
out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt((int) crateLength).array());
|
||||
Files.copy(crateFile, out);
|
||||
}
|
||||
return staged;
|
||||
} catch (IOException e) {
|
||||
// This method's own temp file, not yet handed back to a caller that could clean it up
|
||||
// itself: a caller's own finally is scoped to a path it actually received, so a failure
|
||||
// here must clean up before rethrowing rather than leaving it to a cleanup block that
|
||||
// never starts.
|
||||
try {
|
||||
Files.deleteIfExists(staged);
|
||||
} catch (IOException cleanupFailure) {
|
||||
LOG.warnv(cleanupFailure, "Could not delete a staged Cargo external-connection wire-body file at "
|
||||
+ "{0} after a failed write", staged);
|
||||
}
|
||||
throw new UncheckedIOException("Failed to stage a Cargo external-connection publish wire body", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static long fileSize(Path path) {
|
||||
try {
|
||||
return Files.size(path);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private String cargoExternalConnectionName(String region, String domain, String owner, String repository) {
|
||||
return service.describeRepository(region, domain, owner, repository).getExternalConnections().stream()
|
||||
.filter(ec -> "cargo".equals(ec.getPackageFormat()))
|
||||
.map(ExternalConnection::getExternalConnectionName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ public class CodeArtifactService implements Resettable {
|
||||
* and the backfill in {@link #ensureFormatContainerId} already handle it, including for
|
||||
* repositories created before that format's proxy existed.
|
||||
*/
|
||||
private static final List<String> CONTAINER_BACKED_FORMATS = List.of("maven", "npm", "pypi", "nuget");
|
||||
private static final List<String> CONTAINER_BACKED_FORMATS = List.of("maven", "npm", "pypi", "nuget", "cargo");
|
||||
private static final Set<String> ORIGIN_RESTRICTION_VALUES = Set.of("ALLOW", "BLOCK");
|
||||
/**
|
||||
* Formats AWS documents as valid for {@code GetPackageVersionReadme} specifically: the
|
||||
@@ -3699,7 +3699,12 @@ public class CodeArtifactService implements Resettable {
|
||||
String format, String namespace, String packageName, String version, String repoId,
|
||||
long versionFenceSnapshot, long episodeId) {
|
||||
String owner = effectiveOwner(domainOwner);
|
||||
if ("nuget".equals(format)) {
|
||||
// Not a nuget-specific quirk: needed by any format whose sidecar client holds a real
|
||||
// per-request container lease (beginUse/endUse actually doing something, not the no-op
|
||||
// default) that could go stale if the repository is deleted and recreated mid-write.
|
||||
// KellnrSidecarClient (cargo) delegates beginUse/endUse to a real lease exactly like
|
||||
// BagetterSidecarClient (nuget) does, so it has the identical exposure.
|
||||
if ("nuget".equals(format) || "cargo".equals(format)) {
|
||||
if (!isCurrentRepositorySidecar(owner, region, domain, repository, format, repoId)) {
|
||||
return false;
|
||||
}
|
||||
@@ -4355,7 +4360,7 @@ public class CodeArtifactService implements Resettable {
|
||||
String namespace, String packageName, List<String> versions, Map<String, String> versionRevisions,
|
||||
boolean allowOverwrite, boolean includeFromUpstream) {
|
||||
if (!"generic".equals(format) && !CONTAINER_BACKED_FORMATS.contains(format)) {
|
||||
throw validation("format must be 'generic', 'maven', 'npm', 'pypi', or 'nuget'.");
|
||||
throw validation("format must be 'generic', 'maven', 'npm', 'pypi', 'nuget', or 'cargo'.");
|
||||
}
|
||||
boolean hasVersions = versions != null && !versions.isEmpty();
|
||||
boolean hasRevisions = versionRevisions != null && !versionRevisions.isEmpty();
|
||||
@@ -6506,7 +6511,7 @@ public class CodeArtifactService implements Resettable {
|
||||
if (("maven".equals(format) || "generic".equals(format)) && (namespace == null || namespace.isBlank())) {
|
||||
throw validation("namespace is required when " + action + " a " + format + " package.");
|
||||
}
|
||||
if (("pypi".equals(format) || "nuget".equals(format)) && namespace != null) {
|
||||
if (("pypi".equals(format) || "nuget".equals(format) || "cargo".equals(format)) && namespace != null) {
|
||||
throw validation(format + " packages do not have a namespace.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,10 +7,13 @@ import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Extracts a CodeArtifact authorization token from an incoming request's {@code Authorization}
|
||||
* header, accepting either scheme real package-manager clients use: {@code Bearer <token>}
|
||||
* directly, or HTTP Basic with the token as the password field and any username. AWS documents
|
||||
* only Basic for Maven's {@code settings.xml} and pip/twine's {@code username=aws} convention;
|
||||
* accepting Bearer too costs nothing and matches what a Bearer-only format like npm sends.
|
||||
* header, accepting every scheme a real package-manager client uses: {@code Bearer <token>}
|
||||
* directly, HTTP Basic with the token as the password field and any username, or a bare token
|
||||
* with no scheme prefix at all. AWS documents Basic for Maven's {@code settings.xml} and
|
||||
* pip/twine's {@code username=aws} convention; Bearer for npm's {@code _authToken}; and a bare
|
||||
* token for Cargo (confirmed directly from the Cargo Book's own registry-authentication page:
|
||||
* "the header value is the API token", no prefix). Accepting all three costs nothing: a real
|
||||
* client of one format never happens to send another format's own scheme.
|
||||
*
|
||||
* <p>Pulled out of {@code CodeArtifactMavenController} once {@code CodeArtifactPypiController}
|
||||
* needed the identical extraction: pip and twine authenticate exactly the way Maven's HTTP wagon
|
||||
@@ -27,9 +30,13 @@ final class CodeArtifactTokenExtractor {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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.
|
||||
* {@code null} when the header is absent, or present but malformed (a declared Basic payload
|
||||
* that doesn't decode, or with no password field); {@link
|
||||
* CodeArtifactService#resolveAuthorizationToken} treats a null token the same as any other
|
||||
* invalid one. A header that starts with neither known scheme prefix is trusted as a bare
|
||||
* token verbatim (trimmed) rather than rejected outright: a malformed value reaching this
|
||||
* fallback is still just as safely rejected downstream, by {@code resolveAuthorizationToken}
|
||||
* failing to recognize it as a real, live-issued token.
|
||||
*/
|
||||
static String extractToken(HttpHeaders headers) {
|
||||
String authorization = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
|
||||
@@ -42,7 +49,7 @@ final class CodeArtifactTokenExtractor {
|
||||
if (authorization.startsWith(BASIC_PREFIX)) {
|
||||
return passwordFromBasicCredentials(authorization.substring(BASIC_PREFIX.length()));
|
||||
}
|
||||
return null;
|
||||
return authorization.strip();
|
||||
}
|
||||
|
||||
private static String passwordFromBasicCredentials(String base64Credentials) {
|
||||
|
||||
@@ -0,0 +1,743 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.StreamingResponses;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
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.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* The HTTP wire protocol for a Kellnr sidecar: Cargo's real registry API (confirmed directly
|
||||
* against a live container, not assumed from Kellnr's own thin docs site, which did not render
|
||||
* through a page fetch): the sparse HTTP index (RFC 2789), the binary publish body the Cargo
|
||||
* Book documents, and Kellnr's own admin routes for a genuine hard delete (Cargo's own protocol
|
||||
* only has "yank," which hides a version without removing it; {@code DeletePackage}/{@code
|
||||
* DeletePackageVersions} need real removal, matching AWS's own documented behavior). Container
|
||||
* lifecycle (start, readiness, stop) is {@link KellnrSidecarManager}'s job; this class asks it for
|
||||
* a ready base URL and speaks Kellnr's own protocol against it.
|
||||
*
|
||||
* <p>Unlike every other container-backed format's sidecar, Kellnr always requires a real
|
||||
* credential for publish, confirmed live: there is no "leave it fully open" switch the way
|
||||
* BaGetter's empty {@code ApiKey} provides ({@code KELLNR_REGISTRY__AUTH_REQUIRED=false}, already
|
||||
* the image's own default, only relaxes anonymous download, never publish). This class holds
|
||||
* exactly one internal credential pair per repository, minted lazily on first need and reused for
|
||||
* that repository's whole container lifetime, entirely invisible to a real CodeArtifact client
|
||||
* (whose own authorization is, and remains, enforced once at Floci's own proxy layer: this is
|
||||
* bookkeeping this client owes Kellnr, not a second authentication scheme a CodeArtifact client
|
||||
* ever sees):
|
||||
* <ul>
|
||||
* <li>An API token (minted via {@code POST /api/v1/user/add_token} under a fresh admin login),
|
||||
* cached in {@link #publishTokensByRepoId} and reused for every {@code PUT /api/v1/crates/new}
|
||||
* publish call.</li>
|
||||
* <li>A fresh admin session login per admin-route call ({@code DELETE /api/v1/ui/delete_version}/
|
||||
* {@code delete_crate}), rather than caching the session cookie: confirmed live that the API
|
||||
* token itself does not work against these admin routes (401), only the session cookie does,
|
||||
* and that cookie expires after 8 hours, so logging in fresh for each (infrequent) admin call
|
||||
* avoids expiry bookkeeping entirely rather than risk a cached cookie going stale mid-use.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>{@code CopyPackageVersions}' own destination write ({@link #storePackageVersionAsset})
|
||||
* always publishes with an empty dependency list: extracting the real {@code [dependencies]}
|
||||
* table out of the copied {@code .crate}'s embedded {@code Cargo.toml} would need a TOML parser,
|
||||
* and this codebase has none (adding one is its own decision, not bundled into this foundational
|
||||
* sidecar work), so a copied crate's own real bytes are unaffected, but its sparse-index entry
|
||||
* under-reports its dependencies until a later pass adds that parsing. Documented here rather
|
||||
* than left silent.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class KellnrSidecarClient implements RepositorySidecarManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(KellnrSidecarClient.class);
|
||||
|
||||
private final KellnrSidecarManager manager;
|
||||
private final ObjectMapper mapper;
|
||||
private final HttpClient httpClient;
|
||||
// One minted API token per repository, reused for every publish for that repository's whole
|
||||
// container lifetime; cleared on release() so a later repository under the same id never
|
||||
// inherits a stale token pointing at a container that no longer exists. Also evicted and
|
||||
// reminted on a single 401 (see sendPublishWithRetry): PerKeyContainerPool.ensureReady can
|
||||
// silently restart an unhealthy container under the same repository id without telling this
|
||||
// client, which invalidates whatever token was minted under the previous container without
|
||||
// this client ever finding out from anything other than that 401 itself.
|
||||
private final ConcurrentHashMap<String, String> publishTokensByRepoId = new ConcurrentHashMap<>();
|
||||
// Shared with a future CodeArtifactCargoController's own push handler via lockFor(), the same
|
||||
// reason BagetterSidecarClient keeps one: without it, a native push and a
|
||||
// CopyPackageVersions/DeletePackage write for the same repository could interleave.
|
||||
private final ConcurrentHashMap<String, Object> repositoryLocks = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public KellnrSidecarClient(KellnrSidecarManager manager, ObjectMapper mapper) {
|
||||
this(manager, mapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
|
||||
}
|
||||
|
||||
KellnrSidecarClient(KellnrSidecarManager manager, ObjectMapper mapper, HttpClient httpClient) {
|
||||
this.manager = manager;
|
||||
this.mapper = mapper;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String format() {
|
||||
return "cargo";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String ensureReady(String repositoryContainerId, String publicUrl) {
|
||||
return manager.ensureReady(repositoryContainerId, publicUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release(String repositoryContainerId) {
|
||||
manager.release(repositoryContainerId);
|
||||
publishTokensByRepoId.remove(repositoryContainerId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerRepository(String repositoryContainerId) {
|
||||
manager.registerRepository(repositoryContainerId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beginUse(String repositoryContainerId) {
|
||||
manager.beginUse(repositoryContainerId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endUse(String repositoryContainerId) {
|
||||
manager.endUse(repositoryContainerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cargo packages have no namespace (AWS: "Python, NuGet, Ruby, and Cargo package versions do
|
||||
* not contain a corresponding component") and exactly one real asset per version, the
|
||||
* {@code .crate} file itself, deterministically named {@code {name}-{version}.crate} (the
|
||||
* real local-cache filename convention a real {@code cargo} client itself uses), so {@code
|
||||
* assetName} is checked against that exact value rather than fetched unconditionally, the
|
||||
* same convention {@code BagetterSidecarClient} already uses for NuGet's own one asset.
|
||||
*/
|
||||
@Override
|
||||
public Optional<byte[]> fetchPackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
Optional<String> matchedVersion = matchVersion(repositoryContainerId, packageName, version);
|
||||
if (matchedVersion.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String expectedAssetName = packageName + "-" + matchedVersion.get() + ".crate";
|
||||
if (!expectedAssetName.equals(assetName)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return getBytes(repositoryContainerId, downloadPath(packageName, matchedVersion.get()));
|
||||
}
|
||||
|
||||
/** {@link #fetchPackageVersionAsset}'s streamed sibling; see {@link RepositorySidecarManager} for why. */
|
||||
@Override
|
||||
public Optional<StreamedAsset> fetchPackageVersionAssetStreamed(String repositoryContainerId, String domain,
|
||||
String repository, String namespace, String packageName, String version, String assetName) {
|
||||
Optional<String> matchedVersion = matchVersion(repositoryContainerId, packageName, version);
|
||||
if (matchedVersion.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String expectedAssetName = packageName + "-" + matchedVersion.get() + ".crate";
|
||||
if (!expectedAssetName.equals(assetName)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return getBytesStreamed(repositoryContainerId, downloadPath(packageName, matchedVersion.get()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Every crate name this sidecar holds at least one version of, confirmed live: {@code
|
||||
* GET /api/v1/ui/crates?page=N&page_size=M} needs no credential, returns {@code {"crates":
|
||||
* [{"name":...,"version":...,...}],"page_size":M,"page":N}} with one entry per crate name
|
||||
* (its latest version only, which this bridge doesn't need), and an out-of-range page returns
|
||||
* an empty array rather than erroring, the same paginated-loop shape {@code
|
||||
* BagetterSidecarClient#listPackages} already uses for BaGetter's own search endpoint.
|
||||
*/
|
||||
@Override
|
||||
public List<PackageIdentifier> listPackages(String repositoryContainerId, String domain, String repository) {
|
||||
if (!manager.isRunning(repositoryContainerId)) {
|
||||
return List.of();
|
||||
}
|
||||
List<PackageIdentifier> result = new ArrayList<>();
|
||||
int page = 0;
|
||||
int pageSize = 100;
|
||||
while (true) {
|
||||
JsonNode response = getJson(repositoryContainerId, "/api/v1/ui/crates?page=" + page + "&page_size="
|
||||
+ pageSize).orElseThrow(() -> new IllegalStateException("Could not list packages on the Kellnr "
|
||||
+ "sidecar"));
|
||||
JsonNode crates = response.path("crates");
|
||||
if (!crates.isArray() || crates.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
for (JsonNode entry : crates) {
|
||||
String name = entry.path("name").asText(null);
|
||||
if (name != null) {
|
||||
result.add(new PackageIdentifier(null, name));
|
||||
}
|
||||
}
|
||||
page++;
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<JsonNode> getJson(String repositoryContainerId, String encodedPath) {
|
||||
return getBytes(repositoryContainerId, encodedPath).map(bytes -> {
|
||||
try {
|
||||
return mapper.readTree(bytes);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Could not parse the Kellnr sidecar's own response at "
|
||||
+ encodedPath, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean packageExists(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
return !sparseIndexEntries(repositoryContainerId, packageName).isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean packageVersionExists(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
return matchVersion(repositoryContainerId, packageName, version).isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Every version this sidecar holds for a package, with its publish timestamp, from the sparse
|
||||
* index's own {@code pubtime} field (confirmed live). Does not distinguish a yanked version
|
||||
* from a live one: Cargo's real registry protocol tracks "yanked" as a flag on an otherwise
|
||||
* still-present index entry, not a separate listing, and there is no yank-aware status-override
|
||||
* layer for cargo yet (see this class's own javadoc on scope).
|
||||
*/
|
||||
@Override
|
||||
public List<PackageVersionTimestamp> listPackageVersions(String repositoryContainerId, String domain,
|
||||
String repository, String namespace, String packageName) {
|
||||
List<JsonNode> entries = sparseIndexEntries(repositoryContainerId, packageName);
|
||||
List<PackageVersionTimestamp> result = new ArrayList<>();
|
||||
for (JsonNode entry : entries) {
|
||||
String version = entry.path("vers").asText(null);
|
||||
if (version == null) {
|
||||
continue;
|
||||
}
|
||||
Instant published = null;
|
||||
String publishedText = entry.path("pubtime").asText(null);
|
||||
if (publishedText != null) {
|
||||
try {
|
||||
published = Instant.parse(publishedText);
|
||||
} catch (DateTimeParseException e) {
|
||||
// Leave unmapped: CodeArtifactService falls back to a deterministic tie-break
|
||||
// rather than guessing a time from text that didn't parse.
|
||||
}
|
||||
}
|
||||
result.add(new PackageVersionTimestamp(version, published));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cargo's own one asset per version is deterministically named (see {@link
|
||||
* #fetchPackageVersionAsset}'s own javadoc), so enumerating it for {@code CopyPackageVersions}
|
||||
* needs only confirm the version exists and name it the same way; empty when it doesn't.
|
||||
*/
|
||||
@Override
|
||||
public List<String> listPackageVersionAssetNames(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version) {
|
||||
Optional<String> matchedVersion = matchVersion(repositoryContainerId, packageName, version);
|
||||
return matchedVersion.map(v -> List.of(packageName + "-" + v + ".crate")).orElse(List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@code content} (the whole {@code .crate}, Cargo's one asset per version) through the
|
||||
* real publish wire shape confirmed live against Kellnr: a 4-byte little-endian length +
|
||||
* minimal JSON metadata (name/version from this call's own parameters, no dependency list,
|
||||
* see this class's own javadoc), then a 4-byte little-endian length + the raw {@code .crate}
|
||||
* bytes, {@code PUT} to {@code /api/v1/crates/new} with this repository's own internally-held
|
||||
* token in a bare {@code Authorization} header (no {@code Bearer} prefix, confirmed both from
|
||||
* the Cargo Book's own spec text and live against Kellnr).
|
||||
*
|
||||
* <p>Runs inside {@link #lockFor}, the same lock a future native push handler is expected to
|
||||
* share, for the same reason {@code BagetterSidecarClient} already documents for its own
|
||||
* identical lock.
|
||||
*/
|
||||
@Override
|
||||
public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, byte[] content) {
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
publish(repositoryContainerId, packageName, version, content);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #storePackageVersionAsset(String, String, String, String, String, String, String,
|
||||
* byte[])}'s own streamed sibling, for an asset too large to comfortably hold twice over in
|
||||
* memory (once as the raw crate, once again inside the combined publish body): the header is
|
||||
* written first and {@code content}'s own real bytes are then streamed straight through via
|
||||
* {@link #publishRawWireBody}, the same shape {@code CodeArtifactCargoExternalConnectionImporter
|
||||
* #buildStagedWireBody} already uses for a crate retained through an external connection,
|
||||
* rather than ever holding the whole crate resident the way the {@code byte[]} overload above
|
||||
* does for {@code CopyPackageVersions}' own always-small case.
|
||||
*/
|
||||
@Override
|
||||
public void storePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName, Path content,
|
||||
long contentLength) {
|
||||
byte[] metadata = minimalPublishMetadata(packageName, version);
|
||||
Path staged;
|
||||
try {
|
||||
staged = Files.createTempFile("codeartifact-cargo-copy-wire-", ".bin");
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
try {
|
||||
try (OutputStream out = Files.newOutputStream(staged)) {
|
||||
out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(metadata.length).array());
|
||||
out.write(metadata);
|
||||
out.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt((int) contentLength).array());
|
||||
Files.copy(content, out);
|
||||
}
|
||||
KellnrPublishResult result;
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
result = publishRawWireBody(repositoryContainerId, staged, Files.size(staged));
|
||||
}
|
||||
if (result.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not publish " + packageName + " " + version + " to the "
|
||||
+ "Kellnr sidecar: upstream returned " + result.statusCode());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(staged);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Could not delete a staged Kellnr copy wire-body file at {0}", staged);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void publish(String repositoryContainerId, String packageName, String version, byte[] crateBytes) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
byte[] metadata = minimalPublishMetadata(packageName, version);
|
||||
byte[] body = publishWireBody(metadata, crateBytes);
|
||||
HttpResponse<String> response = sendPublishWithRetry(repositoryContainerId, baseUrl, token ->
|
||||
HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), "/api/v1/crates/new"))
|
||||
.timeout(SidecarUriUtils.transferTimeout(body.length))
|
||||
.header("Content-Type", "application/octet-stream")
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", token)
|
||||
.PUT(BodyPublishers.ofByteArray(body))
|
||||
.build());
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not publish " + packageName + " " + version + " to the Kellnr "
|
||||
+ "sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forwards a real {@code cargo publish}'s own already-correctly-shaped wire body (streamed
|
||||
* from disk, since a {@code .crate} can be large) to {@code PUT /api/v1/crates/new} verbatim,
|
||||
* using this repository's own internally-held token. Deliberately separate from {@link
|
||||
* #storePackageVersionAsset}, which builds its own minimal, dependency-free metadata for
|
||||
* {@code CopyPackageVersions}' sake (see this class's own javadoc): a native publish's own
|
||||
* metadata, built by the real client itself, already carries the package's real dependency
|
||||
* list, which must survive untouched, not be discarded and resynthesized.
|
||||
*
|
||||
* <p>Returns Kellnr's own status and body rather than throwing on a non-200: confirmed live
|
||||
* that Kellnr genuinely rejects a republish of an already-existing name/version with a 400 and
|
||||
* a body already shaped exactly like the Cargo Book's own documented error response ({@code
|
||||
* {"errors":[{"detail":"..."}]}}), matching the Cargo Book's own documented rule that "a
|
||||
* publish is generally permanent" and a version "can never be overwritten". That is a real
|
||||
* answer a real {@code cargo} client understands, not an internal failure to swallow into an
|
||||
* opaque 500; the caller forwards it to the client verbatim.
|
||||
*
|
||||
* <p>Not part of {@link RepositorySidecarManager}: this is Cargo's own native-publish bridge,
|
||||
* called directly by {@code CodeArtifactCargoController}, the same way {@code
|
||||
* BagetterSidecarClient#lockFor} is reused directly by {@code CodeArtifactNuGetController}
|
||||
* without going through the shared interface either.
|
||||
*/
|
||||
record KellnrPublishResult(int statusCode, String body) {
|
||||
}
|
||||
|
||||
KellnrPublishResult publishRawWireBody(String repositoryContainerId, Path stagedWireBody, long contentLength) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
HttpResponse<String> response = sendPublishWithRetry(repositoryContainerId, baseUrl, token -> {
|
||||
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder(SidecarUriUtils.combine(
|
||||
URI.create(baseUrl), "/api/v1/crates/new"))
|
||||
.timeout(SidecarUriUtils.transferTimeout(contentLength))
|
||||
.header("Content-Type", "application/octet-stream")
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", token);
|
||||
try {
|
||||
requestBuilder.PUT(BodyPublishers.ofFile(stagedWireBody));
|
||||
} catch (FileNotFoundException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return requestBuilder.build();
|
||||
});
|
||||
return new KellnrPublishResult(response.statusCode(), response.body());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a publish request built from whichever token is current, and, only on a {@code 401},
|
||||
* evicts that cached token, mints a fresh one, and retries exactly once: this is how a
|
||||
* container silently restarted under this repository's own id by {@code PerKeyContainerPool
|
||||
* #ensureReady} (see {@link #publishTokensByRepoId}'s own javadoc) heals on its very next
|
||||
* publish attempt instead of 401ing every one of them until Floci itself restarts. {@code
|
||||
* requestForToken} is called again for the retry, so it must build a genuinely fresh {@link
|
||||
* HttpRequest} each time rather than reuse one (an {@link HttpRequest} already carries its own
|
||||
* immutable headers, the stale {@code Authorization} included).
|
||||
*/
|
||||
private HttpResponse<String> sendPublishWithRetry(String repositoryContainerId, String baseUrl,
|
||||
Function<String, HttpRequest> requestForToken) {
|
||||
String token = publishToken(repositoryContainerId, baseUrl);
|
||||
HttpResponse<String> response = sendHttp(requestForToken.apply(token));
|
||||
if (response.statusCode() == 401) {
|
||||
publishTokensByRepoId.remove(repositoryContainerId, token);
|
||||
String freshToken = publishToken(repositoryContainerId, baseUrl);
|
||||
response = sendHttp(requestForToken.apply(freshToken));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private HttpResponse<String> sendHttp(HttpRequest request) {
|
||||
try {
|
||||
return httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar to publish this crate", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes every version of the named package via Kellnr's own admin route, confirmed live: a
|
||||
* genuine hard delete, not Cargo's own protocol-level "yank". Runs inside {@link #lockFor},
|
||||
* the same lock {@link #storePackageVersionAsset} and a future native push handler share.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackage(String repositoryContainerId, String domain, String repository, String namespace,
|
||||
String packageName) {
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
String cookie = adminLogin(repositoryContainerId, baseUrl);
|
||||
String query = "name=" + SidecarUriUtils.encodeSegment(packageName);
|
||||
adminDelete(baseUrl, "/api/v1/ui/delete_crate?" + query, cookie, packageName, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the one version this asset belongs to, via the same admin route family as {@link
|
||||
* #deletePackage}: Cargo has exactly one asset per version, so there is no finer grain to
|
||||
* delete at. Runs inside the same {@link #lockFor} lock {@link #storePackageVersionAsset} and
|
||||
* {@link #deletePackage} both take, for the same reason.
|
||||
*/
|
||||
@Override
|
||||
public void deletePackageVersionAsset(String repositoryContainerId, String domain, String repository,
|
||||
String namespace, String packageName, String version, String assetName) {
|
||||
synchronized (lockFor(repositoryContainerId)) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
String cookie = adminLogin(repositoryContainerId, baseUrl);
|
||||
String query = "name=" + SidecarUriUtils.encodeSegment(packageName) + "&version="
|
||||
+ SidecarUriUtils.encodeSegment(version);
|
||||
adminDelete(baseUrl, "/api/v1/ui/delete_version?" + query, cookie, packageName, version);
|
||||
}
|
||||
}
|
||||
|
||||
private void adminDelete(String baseUrl, String pathAndQuery, String cookie, String packageName,
|
||||
String version) {
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), pathAndQuery))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.header("Cookie", cookie)
|
||||
.DELETE()
|
||||
.build();
|
||||
HttpResponse<Void> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.discarding());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar to delete " + packageName
|
||||
+ (version == null ? "" : " " + version), e);
|
||||
}
|
||||
// 404 means this exact coordinate is already gone, the same tolerance
|
||||
// BagetterSidecarClient's own delete calls already apply.
|
||||
if (response.statusCode() != 200 && response.statusCode() != 404) {
|
||||
throw new IllegalStateException("Could not delete " + packageName + (version == null ? "" : " "
|
||||
+ version) + " from the Kellnr sidecar: upstream returned " + response.statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock a future native push handler and this client's own write/delete methods all share
|
||||
* for one repository, so neither can interleave with the other. Package-private so a future
|
||||
* {@code CodeArtifactCargoController} can synchronize its own push-or-conflict check and
|
||||
* forwarded write on the exact same lock, the only way either one closes the race against the
|
||||
* other, the same reason {@code BagetterSidecarClient#lockFor} is package-private.
|
||||
*/
|
||||
Object lockFor(String repositoryContainerId) {
|
||||
return repositoryLocks.computeIfAbsent(repositoryContainerId, k -> new Object());
|
||||
}
|
||||
|
||||
/**
|
||||
* The minimal metadata shape confirmed live to be accepted by Kellnr's real publish endpoint:
|
||||
* every optional field explicitly {@code null}/empty rather than omitted, matching the shape
|
||||
* this class's own hands-on verification used. {@code deps}/{@code features} are always empty
|
||||
* (see this class's own javadoc on why); {@code license} is a fixed placeholder since real
|
||||
* CodeArtifact has no license field of its own to source this from for a sidecar-level copy.
|
||||
*/
|
||||
private byte[] minimalPublishMetadata(String packageName, String version) {
|
||||
ObjectNode metadata = mapper.createObjectNode();
|
||||
metadata.put("name", packageName);
|
||||
metadata.put("vers", version);
|
||||
metadata.putArray("deps");
|
||||
metadata.putObject("features");
|
||||
metadata.putArray("authors");
|
||||
metadata.put("description", (String) null);
|
||||
metadata.put("documentation", (String) null);
|
||||
metadata.put("homepage", (String) null);
|
||||
metadata.put("readme", (String) null);
|
||||
metadata.put("readme_file", (String) null);
|
||||
metadata.putArray("keywords");
|
||||
metadata.putArray("categories");
|
||||
metadata.put("license", (String) null);
|
||||
metadata.put("license_file", (String) null);
|
||||
metadata.put("repository", (String) null);
|
||||
metadata.putObject("badges");
|
||||
metadata.put("links", (String) null);
|
||||
return metadata.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* The real Cargo publish wire body, confirmed directly from the Cargo Book's own spec text and
|
||||
* live against Kellnr: a 4-byte little-endian length-prefixed JSON metadata object, followed
|
||||
* by a 4-byte little-endian length-prefixed {@code .crate} tarball.
|
||||
*/
|
||||
private static byte[] publishWireBody(byte[] metadataJson, byte[] crateBytes) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(4 + metadataJson.length + 4 + crateBytes.length)
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(metadataJson.length);
|
||||
buffer.put(metadataJson);
|
||||
buffer.putInt(crateBytes.length);
|
||||
buffer.put(crateBytes);
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
private String publishToken(String repositoryContainerId, String baseUrl) {
|
||||
return publishTokensByRepoId.computeIfAbsent(repositoryContainerId,
|
||||
id -> mintPublishToken(repositoryContainerId, baseUrl));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints one fresh API token under a fresh admin login, confirmed live: {@code
|
||||
* POST /api/v1/user/add_token} with the admin session cookie returns {@code
|
||||
* {"name":...,"token":"..."}}. The token itself never expires on its own in Kellnr's own model
|
||||
* (confirmed live across repeated use within this session); the admin session cookie that
|
||||
* mints it does, which is exactly why this is minted once and cached rather than re-derived
|
||||
* from a cached cookie later.
|
||||
*/
|
||||
private String mintPublishToken(String repositoryContainerId, String baseUrl) {
|
||||
String cookie = adminLogin(repositoryContainerId, baseUrl);
|
||||
byte[] body = "{\"name\":\"floci\"}".getBytes(StandardCharsets.UTF_8);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl),
|
||||
"/api/v1/user/add_token"))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Cookie", cookie)
|
||||
.POST(BodyPublishers.ofByteArray(body))
|
||||
.build();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar to mint a publish token", e);
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not mint a Kellnr publish token: upstream returned "
|
||||
+ response.statusCode());
|
||||
}
|
||||
try {
|
||||
return mapper.readTree(response.body()).path("token").asText();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not parse Kellnr's token-mint response", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs in as Kellnr's own {@code admin} account, confirmed live: {@code POST
|
||||
* /api/v1/user/login} with {@code {"user":"admin","pwd":"<this repository's own random
|
||||
* password>"}} returns a {@code kellnr_session_id} session cookie. The password itself comes
|
||||
* from {@link KellnrSidecarManager#adminPassword}, read fresh on every call rather than
|
||||
* cached, not Kellnr's own shipped {@code admin}/{@code admin} default (see that manager's
|
||||
* own javadoc for why). This admin account is purely internal to this sidecar container
|
||||
* (loopback-bound, never reachable except through Floci itself), the same trust boundary
|
||||
* every other container-backed format's own sidecar already relies on.
|
||||
*/
|
||||
private String adminLogin(String repositoryContainerId, String baseUrl) {
|
||||
ObjectNode credentials = mapper.createObjectNode();
|
||||
credentials.put("user", "admin");
|
||||
credentials.put("pwd", manager.adminPassword(repositoryContainerId));
|
||||
byte[] body = credentials.toString().getBytes(StandardCharsets.UTF_8);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl),
|
||||
"/api/v1/user/login"))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(BodyPublishers.ofByteArray(body))
|
||||
.build();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar to log in as its admin", e);
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not log in to the Kellnr sidecar as its admin: "
|
||||
+ "upstream returned " + response.statusCode());
|
||||
}
|
||||
return response.headers().firstValue("set-cookie")
|
||||
.map(raw -> raw.split(";", 2)[0])
|
||||
.orElseThrow(() -> new IllegalStateException("Kellnr sidecar login did not return a session "
|
||||
+ "cookie"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code empty()} when {@code version} doesn't match any version Kellnr actually holds for
|
||||
* this package, the matching sparse-index entry's own {@code vers} text otherwise. Cargo
|
||||
* version strings have no leading/trailing-zero aliasing the way NuGet's do (AWS documents no
|
||||
* such normalization for Cargo), so this is a plain exact-string match against the index,
|
||||
* unlike {@code BagetterSidecarClient#matchVersion}'s own normalized comparison.
|
||||
*/
|
||||
private Optional<String> matchVersion(String repositoryContainerId, String packageName, String version) {
|
||||
for (JsonNode entry : sparseIndexEntries(repositoryContainerId, packageName)) {
|
||||
String candidate = entry.path("vers").asText(null);
|
||||
if (version.equals(candidate)) {
|
||||
return Optional.of(candidate);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The real, complete sparse-index bytes for one crate, verbatim (confirmed live:
|
||||
* newline-delimited JSON, one object per version, each carrying its own real {@code deps}/
|
||||
* {@code cksum}/{@code features}, not just what {@link #listPackageVersions}' own abstracted
|
||||
* {@code PackageVersionTimestamp} carries). For {@code CodeArtifactCargoController} to serve
|
||||
* close to verbatim: a real {@code cargo} client needs those fields to resolve dependencies
|
||||
* and verify a download's integrity, information none of this interface's own generic bridge
|
||||
* methods carry. Empty, not an error, when the package was never published or this
|
||||
* repository's sidecar was never started.
|
||||
*/
|
||||
Optional<byte[]> fetchSparseIndexRaw(String repositoryContainerId, String domain, String repository,
|
||||
String packageName) {
|
||||
return getBytes(repositoryContainerId, sparseIndexPath(packageName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Every line of this package's own sparse-index file, each one JSON describing one published
|
||||
* version (confirmed live: newline-delimited JSON, one object per version). Empty, not an
|
||||
* error, when the package was never published or this repository's sidecar was never started.
|
||||
*/
|
||||
private List<JsonNode> sparseIndexEntries(String repositoryContainerId, String packageName) {
|
||||
Optional<byte[]> raw = getBytes(repositoryContainerId, sparseIndexPath(packageName));
|
||||
if (raw.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<JsonNode> entries = new ArrayList<>();
|
||||
for (String line : new String(raw.get(), StandardCharsets.UTF_8).split("\n")) {
|
||||
String trimmed = line.strip();
|
||||
if (trimmed.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
entries.add(mapper.readTree(trimmed));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not parse the Kellnr sidecar's sparse-index entry for "
|
||||
+ packageName, e);
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kellnr's own bucketed index path, the real crates.io bucketing rule (see {@link
|
||||
* SidecarUriUtils#cratesIoBucketPath}, shared with {@code CargoExternalConnectionClient} so
|
||||
* the rule is written once) under Kellnr's own {@code /api/v1/crates/} prefix.
|
||||
*/
|
||||
private static String sparseIndexPath(String packageName) {
|
||||
return "/api/v1/crates/" + SidecarUriUtils.cratesIoBucketPath(packageName);
|
||||
}
|
||||
|
||||
private static String downloadPath(String packageName, String version) {
|
||||
return "/api/v1/crates/dl/" + SidecarUriUtils.encodeSegment(packageName) + "/"
|
||||
+ SidecarUriUtils.encodeSegment(version) + "/download";
|
||||
}
|
||||
|
||||
private Optional<byte[]> getBytes(String repositoryContainerId, String encodedPath) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), encodedPath))
|
||||
.timeout(Duration.ofSeconds(10)).GET().build();
|
||||
HttpResponse<byte[]> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofByteArray());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar at " + encodedPath, e);
|
||||
}
|
||||
if (response.statusCode() == 404) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IllegalStateException("Could not fetch " + encodedPath + " from the Kellnr sidecar: upstream "
|
||||
+ "returned " + response.statusCode());
|
||||
}
|
||||
return Optional.of(response.body());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #getBytes}'s streamed sibling, for the one asset download that can be large: a flat
|
||||
* 10-second timeout, fine for {@link #getBytes}'s own small-metadata callers, would cancel a
|
||||
* legitimately large, still-in-progress download here, the same gap every other container-
|
||||
* backed sidecar client's own streamed fetch already closes.
|
||||
*/
|
||||
private Optional<StreamedAsset> getBytesStreamed(String repositoryContainerId, String encodedPath) {
|
||||
String baseUrl = ensureReady(repositoryContainerId, null);
|
||||
HttpRequest request = HttpRequest.newBuilder(SidecarUriUtils.combine(URI.create(baseUrl), encodedPath))
|
||||
.timeout(SidecarUriUtils.maxTransferTimeout()).GET().build();
|
||||
HttpResponse<InputStream> response;
|
||||
try {
|
||||
response = httpClient.send(request, BodyHandlers.ofInputStream());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Could not reach the Kellnr sidecar at " + encodedPath, e);
|
||||
}
|
||||
if (response.statusCode() == 404) {
|
||||
StreamingResponses.closeQuietly(response.body());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
StreamingResponses.closeQuietly(response.body());
|
||||
throw new IllegalStateException("Could not fetch " + encodedPath + " from the Kellnr sidecar: upstream "
|
||||
+ "returned " + response.statusCode());
|
||||
}
|
||||
long contentLength = response.headers().firstValueAsLong("Content-Length").orElse(-1);
|
||||
return Optional.of(new StreamedAsset(response.body(), contentLength));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.ContainerTeardown;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.PerKeyContainerPool;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Starts and stops one Kellnr container per CodeArtifact repository backing the {@code cargo}
|
||||
* format, the same per-repository shape as Verdaccio (npm), pypiserver (pypi), and BaGetter
|
||||
* (nuget) rather than Reposilite's one shared instance. The HTTP protocol lives in {@link
|
||||
* KellnrSidecarClient}. Implements {@link ContainerTeardown} so reset, nuke, and shutdown stop
|
||||
* every container this manager started.
|
||||
*
|
||||
* <p>Unlike BaGetter, Kellnr has no "leave it fully open" configuration: confirmed directly
|
||||
* against a live container, {@code KELLNR_REGISTRY__AUTH_REQUIRED=false} (already the image's own
|
||||
* documented default) only relaxes anonymous download, never publish, which 401s without a valid
|
||||
* token regardless of that setting. So this container is left at its real default auth posture,
|
||||
* and {@link KellnrSidecarClient} itself holds the one internal admin credential every publish
|
||||
* needs (see its own javadoc); real CodeArtifact authorization still happens exactly once, at
|
||||
* Floci's own proxy layer, before a request ever reaches this container, the same reasoning every
|
||||
* other container-backed format's own manager already documents.
|
||||
*
|
||||
* <p>The admin account's own password is a fresh, random value minted per container at creation
|
||||
* (via {@code KELLNR_SETUP__ADMIN_PWD}, confirmed live to override Kellnr's own shipped
|
||||
* {@code admin}/{@code admin} default), not the shipped default itself: every Kellnr image shares
|
||||
* that same default, so anything else already able to reach this container on the configured
|
||||
* Docker network (the same cross-container reachability every sidecar-backed format's own manager
|
||||
* documents, see {@code docs/services/codeartifact.md}) could otherwise log in as this container's
|
||||
* own admin using nothing but public knowledge of Kellnr's defaults, without ever needing the
|
||||
* internal token {@link KellnrSidecarClient} mints under it.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class KellnrSidecarManager implements ContainerTeardown {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(KellnrSidecarManager.class);
|
||||
// Kellnr's own shipped default (confirmed directly against a live container: it listens on
|
||||
// 8000 with no port configuration set at all).
|
||||
private static final int KELLNR_PORT = 8000;
|
||||
// Kellnr's static SPA shell answers 200 on "/" even before its backend API is actually ready
|
||||
// to serve requests, so it is not a safe readiness signal; this config endpoint only answers
|
||||
// once the real API is up, confirmed live.
|
||||
private static final String HEALTH_PATH = "/api/v1/crates/config.json";
|
||||
private static final SecureRandom ADMIN_PASSWORD_RANDOM = new SecureRandom();
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final EmulatorConfig config;
|
||||
private final PerKeyContainerPool pool;
|
||||
private final SidecarRepositoryLease lease;
|
||||
// One random admin password per repository's own container, regenerated every time
|
||||
// startContainer() runs for that key (including an internal pool restart of an unhealthy
|
||||
// container under the same key): KellnrSidecarClient reads this fresh on every admin login
|
||||
// rather than caching it, so it always matches whichever container is actually running now.
|
||||
private final ConcurrentHashMap<String, String> adminPasswords = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public KellnrSidecarManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
|
||||
EmulatorConfig config) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.pool = new PerKeyContainerPool(lifecycleManager, HEALTH_PATH);
|
||||
this.lease = new SidecarRepositoryLease("Kellnr", pool);
|
||||
}
|
||||
|
||||
/**
|
||||
* Base URL of a ready Kellnr instance for this cargo repository, starting its container if
|
||||
* this is the first use. {@code publicUrl} is unused: Kellnr's own self-reported {@code
|
||||
* config.json} (and anything else that could embed a self-referential URL) is never proxied
|
||||
* verbatim by a future controller, which is expected to author that response itself, the same
|
||||
* way {@code CodeArtifactNuGetController} already authors its own service index rather than
|
||||
* proxying BaGetter's.
|
||||
*/
|
||||
public String ensureReady(String cargoRepositoryId, String publicUrl) {
|
||||
return pool.ensureReady(cargoRepositoryId, () -> startContainer(cargoRepositoryId));
|
||||
}
|
||||
|
||||
/** Stops and removes the container for one cargo repository, if one was ever started. */
|
||||
public void release(String cargoRepositoryId) {
|
||||
lease.release(cargoRepositoryId);
|
||||
adminPasswords.remove(cargoRepositoryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* This cargo repository's own container's current admin password, read fresh on every call
|
||||
* (never cached by the caller) so it always matches whichever container is actually running,
|
||||
* including one silently restarted under the same key by {@link PerKeyContainerPool
|
||||
* #ensureReady}. Only meaningful after {@link #ensureReady} has started this repository's
|
||||
* container at least once.
|
||||
*/
|
||||
String adminPassword(String cargoRepositoryId) {
|
||||
String password = adminPasswords.get(cargoRepositoryId);
|
||||
if (password == null) {
|
||||
throw new IllegalStateException("No Kellnr admin password minted yet for cargo repository "
|
||||
+ cargoRepositoryId);
|
||||
}
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* For a test that seeds a container directly into the pool without going through this class's
|
||||
* own {@link #ensureReady}/{@link #startContainer}: those real paths always mint and store a
|
||||
* password themselves, so a test standing in for them needs its own way to make one visible to
|
||||
* {@link #adminPassword} too, without reaching for reflection the way its own seeding of
|
||||
* {@code pool}'s containers map already does for that unrelated, pre-existing convention.
|
||||
*/
|
||||
void seedAdminPasswordForTest(String cargoRepositoryId, String password) {
|
||||
adminPasswords.put(cargoRepositoryId, password);
|
||||
}
|
||||
|
||||
public void registerRepository(String cargoRepositoryId) {
|
||||
lease.registerRepository(cargoRepositoryId);
|
||||
}
|
||||
|
||||
public void beginUse(String cargoRepositoryId) {
|
||||
lease.beginUse(cargoRepositoryId);
|
||||
}
|
||||
|
||||
public void endUse(String cargoRepositoryId) {
|
||||
lease.endUse(cargoRepositoryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this cargo repository's own Kellnr container is already running, without starting
|
||||
* one for a repository that has never used cargo at all. Every CodeArtifact repository gets a
|
||||
* cargo sidecar id at creation regardless of whether it is ever actually used through cargo,
|
||||
* so a caller that only wants to ask an already-running container what it holds must check
|
||||
* this first rather than provision a brand-new container just to find it has nothing, the same
|
||||
* reasoning {@code BagetterSidecarManager#isRunning} already documents.
|
||||
*/
|
||||
public boolean isRunning(String cargoRepositoryId) {
|
||||
return pool.isTracked(cargoRepositoryId);
|
||||
}
|
||||
|
||||
private PerKeyContainerPool.StartedContainer startContainer(String cargoRepositoryId) {
|
||||
String image = config.services().codeartifact().cargoImage();
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-kellnr-" + cargoRepositoryId);
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
|
||||
// Set before the container is created, not after: KellnrSidecarClient's own adminLogin
|
||||
// reads this map directly, so the new password must already be visible to it the moment
|
||||
// this container could first be reached, never a window where the map still holds a
|
||||
// previous container's own now-wrong password.
|
||||
String adminPassword = generateAdminPassword();
|
||||
adminPasswords.put(cargoRepositoryId, adminPassword);
|
||||
|
||||
// Loopback-only: nothing inside this container should ever be reachable except through
|
||||
// Floci's own proxy layer, the same reasoning Verdaccio/pypiserver/BaGetter's own managers
|
||||
// already document. KELLNR_ORIGIN__HOSTNAME is required for Kellnr's own self-reported
|
||||
// base URLs (confirmed live); storage is left at the image's own SQLite/local-filesystem
|
||||
// default, matching every other sidecar's own "keep it simple, ephemeral" choice.
|
||||
// KELLNR_SETUP__ADMIN_PWD overrides Kellnr's own shipped admin/admin default (confirmed
|
||||
// live), see this class's own javadoc for why that default is never left in place.
|
||||
ContainerSpec spec = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withEnv("KELLNR_ORIGIN__HOSTNAME", "localhost")
|
||||
.withEnv("KELLNR_SETUP__ADMIN_PWD", adminPassword)
|
||||
.withLoopbackPortBinding(KELLNR_PORT, 0)
|
||||
.withDockerNetwork(config.services().dockerNetwork())
|
||||
.withEmbeddedDns()
|
||||
.withLogRotation()
|
||||
.build();
|
||||
String containerId = lifecycleManager.create(spec);
|
||||
try {
|
||||
ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
|
||||
EndpointInfo endpoint = info.getEndpoint(KELLNR_PORT);
|
||||
String url = "http://" + endpoint;
|
||||
LOG.infov("Kellnr sidecar for cargo repository {0} is ready at {1}", cargoRepositoryId, url);
|
||||
return new PerKeyContainerPool.StartedContainer(containerId, url);
|
||||
} catch (RuntimeException e) {
|
||||
lifecycleManager.stopAndRemove(containerId, null);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** A fresh 256-bit random value, hex-encoded so it is always safe as a Kellnr config env var
|
||||
* and a JSON login body's own string value with no escaping concerns either way. */
|
||||
private static String generateAdminPassword() {
|
||||
byte[] bytes = new byte[32];
|
||||
ADMIN_PASSWORD_RANDOM.nextBytes(bytes);
|
||||
StringBuilder hex = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
hex.append(String.format("%02x", b));
|
||||
}
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopManagedContainers() {
|
||||
lease.stopManagedContainers();
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,17 @@ import io.floci.aws.core.common.auth.SigV4Canonicalization;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Shared helpers for the Maven, npm, pypi, and NuGet sidecar clients: URI construction out of
|
||||
* each one's own {@code baseUrl} plus one or more caller-supplied path segments (a repository
|
||||
* id, package coordinates, an asset filename), and a request timeout sized for forwarding a
|
||||
* large asset's real bytes rather than a small metadata-only request. Package-private: every
|
||||
* caller lives in this package, and {@link #combine} in particular requires its {@code
|
||||
* encodedPath} argument to already be fully percent-encoded, a precondition not worth exposing
|
||||
* to unrelated callers outside the four clients that know to uphold it.
|
||||
* Shared helpers for the Maven, npm, pypi, NuGet, and Kellnr (Cargo) sidecar clients, and their
|
||||
* external-connection siblings: URI construction out of each one's own {@code baseUrl} plus one
|
||||
* or more caller-supplied path segments (a repository id, package coordinates, an asset
|
||||
* filename), and a request timeout sized for forwarding a large asset's real bytes rather than a
|
||||
* small metadata-only request. Package-private: every caller lives in this package, and {@link
|
||||
* #combine} in particular requires its {@code encodedPath} argument to already be fully
|
||||
* percent-encoded, a precondition not worth exposing to unrelated callers outside the clients
|
||||
* that know to uphold it.
|
||||
*/
|
||||
final class SidecarUriUtils {
|
||||
|
||||
@@ -93,4 +95,33 @@ final class SidecarUriUtils {
|
||||
static Duration maxTransferTimeout() {
|
||||
return transferTimeout(CodeArtifactService.MAX_ASSET_FILE_SIZE_BYTES);
|
||||
}
|
||||
|
||||
/**
|
||||
* The real crates.io sparse-index bucketing rule (RFC 2789), confirmed live against both
|
||||
* Kellnr and the real {@code index.crates.io} (a 1 or 2 character name sits directly under a
|
||||
* {@code 1}/{@code 2} directory, a 3 character name adds one more level keyed by its own
|
||||
* first character, and a 4+ character name buckets by its own first two, then next two,
|
||||
* characters), with no leading slash and no host-specific prefix: {@link KellnrSidecarClient}
|
||||
* prepends its own {@code /api/v1/crates/}, {@code CargoExternalConnectionClient} prepends
|
||||
* nothing (the real {@code index.crates.io} serves bucket paths straight off its own root).
|
||||
* Lowercased: the Cargo Book's own registry-index page is explicit that both the bucket
|
||||
* directory names and the index filename itself are the package name "converted to
|
||||
* lowercase," confirmed live against the real production index (a mixed-case crate like
|
||||
* {@code Inflector} 404s at {@code In/fl/Inflector} and only resolves at {@code in/fl/
|
||||
* inflector}; the returned index line's own {@code name} field still preserves the original
|
||||
* case). The {@code packageName} value itself, as used for anything other than this one path,
|
||||
* keeps its original casing.
|
||||
*/
|
||||
static String cratesIoBucketPath(String packageName) {
|
||||
String lower = packageName.toLowerCase(Locale.ROOT);
|
||||
String encoded = encodeSegment(lower);
|
||||
int length = lower.length();
|
||||
if (length <= 2) {
|
||||
return length + "/" + encoded;
|
||||
}
|
||||
if (length == 3) {
|
||||
return "3/" + encodeSegment(lower.substring(0, 1)) + "/" + encoded;
|
||||
}
|
||||
return encodeSegment(lower.substring(0, 2)) + "/" + encodeSegment(lower.substring(2, 4)) + "/" + encoded;
|
||||
}
|
||||
}
|
||||
@@ -163,6 +163,7 @@ quarkus:
|
||||
- --initialize-at-run-time=io.floci.aws.services.dms.DmsService
|
||||
- --initialize-at-run-time=io.floci.aws.services.lambda.launcher.LambdaExecutionRoleCredentials
|
||||
- --initialize-at-run-time=io.floci.aws.services.ecs.container.EcsTaskRoleCredentials
|
||||
- --initialize-at-run-time=io.floci.aws.services.codeartifact.KellnrSidecarManager
|
||||
- --initialize-at-run-time=io.floci.aws.services.ssoportal.SsoPortalService
|
||||
- --initialize-at-run-time=io.floci.aws.services.redshift.proxy.RedshiftRoleAccess
|
||||
- --initialize-at-run-time=io.floci.aws.services.redshift.spectrum.SpectrumMaterializer
|
||||
@@ -1149,6 +1150,7 @@ floci:
|
||||
npm-image: "verdaccio/verdaccio:6.10.4"
|
||||
pypi-image: "pypiserver/pypiserver:v2.4.2"
|
||||
nuget-image: "bagetter/bagetter:1.6.5"
|
||||
cargo-image: "ghcr.io/kellnr/kellnr:5.14.1"
|
||||
quicksight:
|
||||
enabled: true
|
||||
embed-base-url: ${floci.base-url}
|
||||
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
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.net.InetSocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The wire contract towards the real public {@code crates.io} registry, exercised against a
|
||||
* local {@code HttpServer} fake standing in for it, named {@code fake} in these tests rather than
|
||||
* the real {@code public:crates-io} connection name, mirroring {@link
|
||||
* NuGetExternalConnectionClientTest}'s own shape.
|
||||
*/
|
||||
class CargoExternalConnectionClientTest {
|
||||
|
||||
private HttpServer server;
|
||||
private CargoExternalConnectionClient client;
|
||||
|
||||
@BeforeEach
|
||||
void startServer() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.start();
|
||||
String baseUrl = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
client = new CargoExternalConnectionClient(
|
||||
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL).build(),
|
||||
Map.of("fake", baseUrl), Map.of("fake", baseUrl));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopServer() {
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchSparseIndexReturnsTheRealBytesOnA200() throws IOException {
|
||||
byte[] content = "{\"name\":\"widget\",\"vers\":\"1.0.0\"}\n".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/wi/dg/widget", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<byte[]> result = client.fetchSparseIndex("fake", "widget");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertArrayEquals(content, result.get());
|
||||
}
|
||||
|
||||
/** Confirms the real RFC 2789 bucketing rule for each name-length case, not just the 4+
|
||||
* character case the one example above covers. */
|
||||
@Test
|
||||
void fetchSparseIndexUsesTheRealBucketingPathForEveryNameLength() throws IOException {
|
||||
server.createContext("/1/a", exchange -> respond(exchange, 200, "one"));
|
||||
server.createContext("/2/ab", exchange -> respond(exchange, 200, "two"));
|
||||
server.createContext("/3/a/abc", exchange -> respond(exchange, 200, "three"));
|
||||
server.createContext("/wi/dg/widget", exchange -> respond(exchange, 200, "four-plus"));
|
||||
|
||||
assertEquals("one", new String(client.fetchSparseIndex("fake", "a").orElseThrow(), StandardCharsets.UTF_8));
|
||||
assertEquals("two", new String(client.fetchSparseIndex("fake", "ab").orElseThrow(), StandardCharsets.UTF_8));
|
||||
assertEquals("three",
|
||||
new String(client.fetchSparseIndex("fake", "abc").orElseThrow(), StandardCharsets.UTF_8));
|
||||
assertEquals("four-plus",
|
||||
new String(client.fetchSparseIndex("fake", "widget").orElseThrow(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchSparseIndexReturnsEmptyOnA404() throws IOException {
|
||||
server.createContext("/wi/dg/widget", exchange -> respondEmpty(exchange, 404));
|
||||
|
||||
assertFalse(client.fetchSparseIndex("fake", "widget").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchSparseIndexReturnsEmptyForAnUnknownConnectionName() {
|
||||
assertFalse(client.fetchSparseIndex("public:crates-io", "widget").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchCrateWritesTheRealBytesAndReportsTheirRealSizeAndSha256() throws IOException, NoSuchAlgorithmException {
|
||||
byte[] content = "crate-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/widget/1.0.0/download", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
Path destination = Files.createTempFile("cargo-external-connection-test-", ".crate");
|
||||
|
||||
try {
|
||||
Optional<CargoExternalConnectionClient.FetchedFile> result =
|
||||
client.fetchCrate("fake", "widget", "1.0.0", destination);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(content.length, result.get().size());
|
||||
assertArrayEquals(content, Files.readAllBytes(destination));
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
String expectedSha256 = HexFormat.of().formatHex(digest.digest(content));
|
||||
assertEquals(expectedSha256, result.get().sha256());
|
||||
} finally {
|
||||
Files.deleteIfExists(destination);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchCrateReturnsEmptyOnA404() throws IOException {
|
||||
server.createContext("/widget/1.0.0/download", exchange -> respondEmpty(exchange, 404));
|
||||
Path destination = Files.createTempFile("cargo-external-connection-test-", ".crate");
|
||||
|
||||
try {
|
||||
assertFalse(client.fetchCrate("fake", "widget", "1.0.0", destination).isPresent());
|
||||
} finally {
|
||||
Files.deleteIfExists(destination);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchCrateReturnsEmptyForAnUnknownConnectionName() throws IOException {
|
||||
Path destination = Files.createTempFile("cargo-external-connection-test-", ".crate");
|
||||
|
||||
try {
|
||||
assertFalse(client.fetchCrate("public:crates-io", "widget", "1.0.0", destination).isPresent());
|
||||
} finally {
|
||||
Files.deleteIfExists(destination);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchCrateFollowsARealRedirectInsteadOfTreatingItAsMissing() throws IOException {
|
||||
byte[] content = "redirected-crate-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
server.createContext("/widget/1.0.0/download", exchange -> {
|
||||
exchange.getResponseHeaders().add("Location", "/moved/widget-1.0.0.crate");
|
||||
exchange.sendResponseHeaders(301, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.createContext("/moved/widget-1.0.0.crate", exchange -> {
|
||||
exchange.sendResponseHeaders(200, content.length);
|
||||
exchange.getResponseBody().write(content);
|
||||
exchange.close();
|
||||
});
|
||||
Path destination = Files.createTempFile("cargo-external-connection-test-", ".crate");
|
||||
|
||||
try {
|
||||
Optional<CargoExternalConnectionClient.FetchedFile> result =
|
||||
client.fetchCrate("fake", "widget", "1.0.0", destination);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertArrayEquals(content, Files.readAllBytes(destination));
|
||||
} finally {
|
||||
Files.deleteIfExists(destination);
|
||||
}
|
||||
}
|
||||
|
||||
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.close();
|
||||
}
|
||||
|
||||
private static void respondEmpty(HttpExchange exchange, int status) throws IOException {
|
||||
exchange.sendResponseHeaders(status, -1);
|
||||
exchange.close();
|
||||
}
|
||||
}
|
||||
+326
@@ -0,0 +1,326 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.codeartifact.CodeArtifactService.AuthorizationTokenScope;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.StreamingOutput;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Lease and dispatch correctness for {@link CodeArtifactCargoController}, mirroring {@link
|
||||
* CodeArtifactNuGetControllerLeaseTest}'s own shape. {@link KellnrSidecarClient} is mocked, so no
|
||||
* real Kellnr call ever happens here; its own wire contract has its own tests.
|
||||
*/
|
||||
class CodeArtifactCargoControllerLeaseTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String OWNER = "123456789012";
|
||||
private static final String DOMAIN = "dom";
|
||||
private static final String REPOSITORY = "repo";
|
||||
private static final String REPO_ID = "cargo-repo-id";
|
||||
|
||||
private CodeArtifactService service;
|
||||
private KellnrSidecarClient kellnr;
|
||||
private CodeArtifactCargoExternalConnectionImporter externalConnectionImporter;
|
||||
private CodeArtifactCargoController controller;
|
||||
private HttpHeaders headers;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = mock(CodeArtifactService.class);
|
||||
kellnr = mock(KellnrSidecarClient.class);
|
||||
externalConnectionImporter = mock(CodeArtifactCargoExternalConnectionImporter.class);
|
||||
controller = new CodeArtifactCargoController(service, kellnr, externalConnectionImporter, new ObjectMapper());
|
||||
// Default: no external connection configured, so the merge is a pure pass-through of
|
||||
// whatever Kellnr's own local lookup returned, exactly what the real importer itself does
|
||||
// when cargoExternalConnectionName resolves to null. Individual tests override this to
|
||||
// exercise the merge itself.
|
||||
when(externalConnectionImporter.mergeExternalVersions(any(), any(), any(), any(), any(), any()))
|
||||
.thenAnswer(invocation -> invocation.getArgument(5));
|
||||
headers = mock(HttpHeaders.class);
|
||||
// A bare token, no scheme prefix: the real shape a cargo client sends (confirmed from the
|
||||
// Cargo Book's own registry-authentication page).
|
||||
when(headers.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("token");
|
||||
when(service.resolveAuthorizationToken("token", DOMAIN))
|
||||
.thenReturn(Optional.of(new AuthorizationTokenScope(OWNER, REGION)));
|
||||
when(service.resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, REPOSITORY, kellnr))
|
||||
.thenReturn(REPO_ID);
|
||||
when(service.getRepositoryEndpoint(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null))
|
||||
.thenReturn("http://localhost:4566/codeartifact/cargo/dom/repo/");
|
||||
when(service.stageAssetBody(any())).thenAnswer(invocation -> {
|
||||
InputStream in = invocation.getArgument(0);
|
||||
Path staged = Files.createTempFile("cargo-controller-test-", ".bin");
|
||||
Files.copy(in, staged, StandardCopyOption.REPLACE_EXISTING);
|
||||
return staged;
|
||||
});
|
||||
doAnswer(invocation -> {
|
||||
Files.deleteIfExists(invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(service).deleteStagedAssetBody(any());
|
||||
when(kellnr.lockFor(any())).thenReturn(new Object());
|
||||
when(kellnr.publishRawWireBody(any(), any(), anyLong()))
|
||||
.thenReturn(new KellnrSidecarClient.KellnrPublishResult(200, "{\"warnings\":null}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void configJsonReleasesItsLeaseWithoutEverStartingTheSidecar() {
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "config.json");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("\"dl\": "
|
||||
+ "\"http://localhost:4566/codeartifact/cargo/dom/repo/api/v1/crates\""));
|
||||
verify(service).resolveContainerIdAndBeginUse("cargo", REGION, DOMAIN, OWNER, REPOSITORY, kellnr);
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
// config.json is authored directly from GetRepositoryEndpoint, never from the sidecar
|
||||
// itself, so there is no reason to ever start a container just to answer it.
|
||||
verify(kellnr, never()).ensureReady(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sparseIndexLookupReleasesItsLeaseOnAMiss() {
|
||||
when(kellnr.fetchSparseIndexRaw(REPO_ID, DOMAIN, REPOSITORY, "democrate")).thenReturn(Optional.empty());
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "de/mo/democrate");
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sparseIndexLookupProxiesTheRealBytesVerbatim() {
|
||||
byte[] indexBytes = "{\"name\":\"democrate\",\"vers\":\"1.0.0\"}".getBytes(StandardCharsets.UTF_8);
|
||||
when(kellnr.fetchSparseIndexRaw(REPO_ID, DOMAIN, REPOSITORY, "democrate"))
|
||||
.thenReturn(Optional.of(indexBytes));
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "de/mo/democrate");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(new String(indexBytes, StandardCharsets.UTF_8),
|
||||
new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sparseIndexLookupServesTheMergedResultFromTheExternalConnectionImporter() {
|
||||
Optional<byte[]> local = Optional.empty();
|
||||
when(kellnr.fetchSparseIndexRaw(REPO_ID, DOMAIN, REPOSITORY, "democrate")).thenReturn(local);
|
||||
byte[] merged = "{\"name\":\"democrate\",\"vers\":\"2.0.0\"}".getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionImporter.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, "democrate", local))
|
||||
.thenReturn(Optional.of(merged));
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "de/mo/democrate");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(new String(merged, StandardCharsets.UTF_8),
|
||||
new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadReleasesItsLeaseOnAnEarlyNotFound() {
|
||||
doThrow(mock(AwsException.class)).when(service).requireContainerBackedVersionDownloadable(
|
||||
OWNER, REGION, DOMAIN, REPOSITORY, "cargo", null, "democrate", "1.0.0", REPO_ID);
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadAttemptsAnExternalConnectionImportOnlyOnALocalMiss() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0"))
|
||||
.thenReturn(true);
|
||||
|
||||
controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
verify(externalConnectionImporter, never()).tryImport(any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadAttemptsAnExternalConnectionImportOnALocalMissThenStreamsWhatItImported() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0"))
|
||||
.thenReturn(false);
|
||||
byte[] crateBytes = "imported-crate-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
when(kellnr.fetchPackageVersionAssetStreamed(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate")).thenReturn(Optional.of(new RepositorySidecarManager.StreamedAsset(
|
||||
new ByteArrayInputStream(crateBytes), crateBytes.length)));
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
verify(externalConnectionImporter).tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, "democrate",
|
||||
"1.0.0");
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* The one real asset download in this controller: proves it streams the sidecar's response
|
||||
* straight through rather than buffering it first, and still releases its lease afterward.
|
||||
*/
|
||||
@Test
|
||||
void downloadStreamsTheCrateAndReleasesItsLease() throws Exception {
|
||||
byte[] crateBytes = "crate-bytes".getBytes(StandardCharsets.UTF_8);
|
||||
when(kellnr.fetchPackageVersionAssetStreamed(REPO_ID, DOMAIN, REPOSITORY, null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate")).thenReturn(Optional.of(new RepositorySidecarManager.StreamedAsset(
|
||||
new ByteArrayInputStream(crateBytes), crateBytes.length)));
|
||||
|
||||
Response response = controller.get(headers, DOMAIN, REPOSITORY, "api/v1/crates/democrate/1.0.0/download");
|
||||
|
||||
// The lease must still be held once the method itself has returned: a concurrent
|
||||
// DeleteRepository must not be able to tear down the Kellnr container before the entity
|
||||
// stream below is actually drained.
|
||||
verify(kellnr, never()).endUse(REPO_ID);
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("crate-bytes", new String(readEntity(response), StandardCharsets.UTF_8));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
private static byte[] readEntity(Response response) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try {
|
||||
((StreamingOutput) response.getEntity()).write(out);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishParsesTheMetadataPrefixAndForwardsTheWholeBodyVerbatim() throws Exception {
|
||||
byte[] body = publishBody("democrate", "1.0.0", "crate-bytes");
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(body));
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(service).requireContainerBackedPackagePublishAllowed(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
"democrate");
|
||||
verify(service).requireContainerBackedVersionNotArchivedOrDisposed(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
"cargo", null, "democrate", "1.0.0");
|
||||
verify(kellnr).publishRawWireBody(eq(REPO_ID), any(Path.class), eq((long) body.length));
|
||||
verify(service).completeContainerBackedPublishIfCurrentRepository(eq(REGION), eq(DOMAIN), eq(OWNER),
|
||||
eq(REPOSITORY), eq(REPO_ID), eq("cargo"), eq("democrate"), eq("1.0.0"),
|
||||
eq((long) "crate-bytes".getBytes(StandardCharsets.UTF_8).length), any(Long.class), isNull(),
|
||||
isNull(), eq(0L));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishRefusesAPublishBlockedByOriginConfiguration() throws Exception {
|
||||
doThrow(new AwsException("ConflictException", "blocked", 409)).when(service)
|
||||
.requireContainerBackedPackagePublishAllowed(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
"democrate");
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(publishBody("democrate", "1.0.0", "crate-bytes")));
|
||||
|
||||
assertEquals(409, response.getStatus());
|
||||
verify(kellnr, never()).publishRawWireBody(any(), any(), anyLong());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishForwardsKellnrsOwnRejectionVerbatimWithoutCompletingTheBookkeeping() throws Exception {
|
||||
when(kellnr.publishRawWireBody(eq(REPO_ID), any(Path.class), anyLong()))
|
||||
.thenReturn(new KellnrSidecarClient.KellnrPublishResult(400,
|
||||
"{\"errors\":[{\"detail\":\"ERROR: Crate with version already exists: democrate-1.0.0\"}]}"));
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(publishBody("democrate", "1.0.0", "crate-bytes")));
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals("{\"errors\":[{\"detail\":\"ERROR: Crate with version already exists: democrate-1.0.0\"}]}",
|
||||
response.getEntity());
|
||||
verify(service, never()).completeContainerBackedPublishIfCurrentRepository(any(), any(), any(), any(),
|
||||
any(), any(), any(), any(), anyLong(), anyLong(), any(), any(), anyLong());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishReleasesItsLeaseOnATruncatedMetadataPrefix() {
|
||||
byte[] truncated = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(100).array();
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(truncated));
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishDeletesItsStagedFileEvenOnFailure() {
|
||||
byte[] truncated = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(100).array();
|
||||
|
||||
Response response = controller.publish(headers, DOMAIN, REPOSITORY, "api/v1/crates/new",
|
||||
new ByteArrayInputStream(truncated));
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
// The shared setUp() stub for deleteStagedAssetBody actually deletes the real temp file
|
||||
// it's handed, so a real leaked file (not just a missed call) would survive to fail a
|
||||
// later assertion that reads it; verifying the call happened is the meaningful check here.
|
||||
verify(service).deleteStagedAssetBody(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedSidecarStartupReleasesTheLease() {
|
||||
when(kellnr.fetchSparseIndexRaw(REPO_ID, DOMAIN, REPOSITORY, "democrate"))
|
||||
.thenThrow(new IllegalStateException("Docker unavailable"));
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> controller.get(headers, DOMAIN, REPOSITORY, "de/mo/democrate"));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidLeaseCompletionIsNotHidden() {
|
||||
IllegalStateException invalidLease = new IllegalStateException("No active Kellnr sidecar use");
|
||||
doThrow(invalidLease).when(kellnr).endUse(REPO_ID);
|
||||
|
||||
assertSame(invalidLease,
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> controller.get(headers, DOMAIN, REPOSITORY, "config.json")));
|
||||
verify(kellnr).endUse(REPO_ID);
|
||||
}
|
||||
|
||||
private static byte[] publishBody(String name, String version, String crateContent) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
byte[] metadata = mapper.writeValueAsBytes(Map.of("name", name, "vers", version));
|
||||
byte[] crate = crateContent.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(4 + metadata.length + 4 + crate.length).order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(metadata.length);
|
||||
buffer.put(metadata);
|
||||
buffer.putInt(crate.length);
|
||||
buffer.put(crate);
|
||||
return buffer.array();
|
||||
}
|
||||
}
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
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.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static io.floci.aws.testing.CodeArtifactRequests.putPackageOriginConfiguration;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Runs a real Cargo publish/install round trip against a live, per-repository Kellnr container,
|
||||
* started by {@link KellnrSidecarManager} exactly as in production. The published {@code .crate}
|
||||
* files are hand-built with the JDK's own {@code java.util.zip} plus the already-present {@code
|
||||
* commons-compress} (a real {@code Cargo.toml} inside a real gzipped tarball), not a captured
|
||||
* fixture: what this class needs to prove is the real container's behavior, not a client
|
||||
* library's fidelity to the wire format, the same reasoning {@link
|
||||
* CodeArtifactNuGetDockerIntegrationTest}'s own class-level documentation gives for NuGet.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CodeArtifactCargoDockerIntegrationTest {
|
||||
|
||||
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
|
||||
private static final String DOMAIN = "cargo-sidecar-domain";
|
||||
private static final String REPO = "cargo-sidecar-repo";
|
||||
private static final String CRATE_NAME = "democrate";
|
||||
private static final String VERSION = "1.0.0";
|
||||
|
||||
private static String bearerToken;
|
||||
private static byte[] originalPublishBody;
|
||||
private static byte[] originalCrateBytes;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.cargo-image");
|
||||
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");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code config.json} must be rooted at the exact endpoint {@code GetRepositoryEndpoint}
|
||||
* itself returns, the same requirement {@link CodeArtifactNuGetDockerIntegrationTest}'s own
|
||||
* service-index test proves for NuGet: a real {@code cargo} client's own sparse-registry
|
||||
* resolver only trusts an absolute {@code dl}/{@code api} rooted at the address it already
|
||||
* reached this response through.
|
||||
*/
|
||||
@Test
|
||||
@Order(1)
|
||||
void configJsonIsRootedAtTheRealRepositoryEndpoint() {
|
||||
String repositoryEndpoint = given().header("Authorization", AUTH)
|
||||
.get("/v1/repository/endpoint?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("repositoryEndpoint");
|
||||
String endpointNoTrailingSlash = repositoryEndpoint.substring(0, repositoryEndpoint.length() - 1);
|
||||
|
||||
given().header("Authorization", "Bearer " + bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/config.json")
|
||||
.then().statusCode(200)
|
||||
.body("dl", equalTo(endpointNoTrailingSlash + "/api/v1/crates"))
|
||||
.body("api", equalTo(endpointNoTrailingSlash))
|
||||
.body("auth-required", equalTo(true));
|
||||
}
|
||||
|
||||
/**
|
||||
* The full round trip: publish with a real, non-empty dependency list, then confirm the
|
||||
* sparse index and the download both genuinely reflect what was published, dependency list
|
||||
* included, not a reconstructed or truncated version of it.
|
||||
*/
|
||||
@Test
|
||||
@Order(2)
|
||||
void publishThenInstallRoundTripsTheExactBytesAndRealDependencies() throws IOException {
|
||||
originalCrateBytes = buildCrate(CRATE_NAME, VERSION);
|
||||
originalPublishBody = publishBody(CRATE_NAME, VERSION, originalCrateBytes);
|
||||
long assetSizeBytesBeforePublish = describeDomainAssetSizeBytes();
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(originalPublishBody)
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200)
|
||||
.body("warnings", equalTo(null));
|
||||
|
||||
assertEquals(assetSizeBytesBeforePublish + originalCrateBytes.length, describeDomainAssetSizeBytes());
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/de/mo/" + CRATE_NAME)
|
||||
.then().statusCode(200)
|
||||
.body(containsString("\"name\":\"" + CRATE_NAME + "\""))
|
||||
.body(containsString("\"vers\":\"" + VERSION + "\""))
|
||||
.body(containsString("\"name\":\"real-dependency\""));
|
||||
|
||||
byte[] fetchedCrate = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + CRATE_NAME + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertArrayEquals(originalCrateBytes, fetchedCrate);
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo&package=" + CRATE_NAME)
|
||||
.then().statusCode(200).body("package.name", equalTo(CRATE_NAME))
|
||||
.body("package.originConfiguration.restrictions.publish", equalTo("ALLOW"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void getPackageVersionAssetBridgesToTheRealKellnrSidecar() throws IOException {
|
||||
String assetName = CRATE_NAME + "-" + VERSION + ".crate";
|
||||
byte[] fetched = given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version/asset?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo"
|
||||
+ "&package=" + CRATE_NAME + "&version=" + VERSION + "&asset=" + assetName)
|
||||
.then().statusCode(200)
|
||||
.header("X-AssetName", equalTo(assetName))
|
||||
.extract().asByteArray();
|
||||
assertArrayEquals(originalCrateBytes, fetched);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void describePackageVersionBridgesToTheRealKellnrSidecar() {
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package/version?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo&package="
|
||||
+ CRATE_NAME + "&version=" + VERSION)
|
||||
.then().statusCode(200)
|
||||
.body("packageVersion.version", equalTo(VERSION))
|
||||
.body("packageVersion.status", equalTo("Published"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A republish of an already-existing name/version is rejected, matching the Cargo Book's own
|
||||
* documented rule that "a publish is generally permanent" and a version "can never be
|
||||
* overwritten", confirmed live against Kellnr: it answers 400 with a body already shaped
|
||||
* exactly like the Cargo Book's own documented error response, which this test confirms is
|
||||
* forwarded to the client verbatim rather than swallowed into an opaque 500.
|
||||
*/
|
||||
@Test
|
||||
@Order(5)
|
||||
void repeatingTheExactSamePublishIsRejectedAsAnAlreadyExistingVersion() {
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(originalPublishBody)
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(400)
|
||||
.body("errors[0].detail", containsString("already exists"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void repositoriesAreIsolatedFromEachOther() {
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=other-cargo-repo")
|
||||
.then().statusCode(200);
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/other-cargo-repo/de/mo/" + CRATE_NAME)
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void missingOrWrongDomainTokensAreUnauthorized() {
|
||||
given().get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/config.json")
|
||||
.then().statusCode(401);
|
||||
|
||||
given().header("Authorization", "not-a-real-token")
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/config.json")
|
||||
.then().statusCode(401);
|
||||
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/domain?domain=other-cargo-token-domain")
|
||||
.then().statusCode(200);
|
||||
String otherDomainToken = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=other-cargo-token-domain")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
|
||||
given().header("Authorization", otherDomainToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/config.json")
|
||||
.then().statusCode(401);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes 10-NATIVE-STATUS for cargo: a plain {@code cargo add}/{@code cargo build} download of
|
||||
* an Archived version's real {@code .crate} must 404 against the live Kellnr sidecar, even
|
||||
* though the file itself is still sitting there untouched. Its own crate, not {@link
|
||||
* #CRATE_NAME}, so archiving it can't disturb any other ordered test in this class.
|
||||
*/
|
||||
@Test
|
||||
@Order(8)
|
||||
void archivingAVersionBlocksItsRealKellnrContentDownloadWhileLeavingTheBytesInPlace() throws IOException {
|
||||
String crateName = "archivecrate";
|
||||
byte[] crateBytes = buildCrate(crateName, VERSION);
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, VERSION, crateBytes))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
|
||||
given().contentType("application/json").header("Authorization", AUTH)
|
||||
.body("{\"versions\":[\"" + VERSION + "\"],\"targetStatus\":\"Archived\"}")
|
||||
.post("/v1/package/versions/update_status?domain=" + DOMAIN + "&repository=" + REPO
|
||||
+ "&format=cargo&package=" + crateName)
|
||||
.then().statusCode(200)
|
||||
.body("successfulVersions['" + VERSION + "'].status", equalTo("Archived"));
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + crateName + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(404);
|
||||
|
||||
// Proves the block above is this check's own override, not Kellnr having genuinely lost
|
||||
// the file: un-archiving must make the exact same bytes fetchable again, with nothing
|
||||
// re-published in between.
|
||||
given().contentType("application/json").header("Authorization", AUTH)
|
||||
.body("{\"versions\":[\"" + VERSION + "\"],\"targetStatus\":\"Published\"}")
|
||||
.post("/v1/package/versions/update_status?domain=" + DOMAIN + "&repository=" + REPO
|
||||
+ "&format=cargo&package=" + crateName)
|
||||
.then().statusCode(200)
|
||||
.body("successfulVersions['" + VERSION + "'].status", equalTo("Published"));
|
||||
byte[] fetchedAfterUnarchive = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + crateName + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertArrayEquals(crateBytes, fetchedAfterUnarchive);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code publish:BLOCK} set through the real {@code PutPackageOriginConfiguration} route must
|
||||
* refuse a real {@code cargo publish}, the same real-world gap this already closed for every
|
||||
* other native format. Its own crate, so no other ordered test is disturbed.
|
||||
*/
|
||||
@Test
|
||||
@Order(9)
|
||||
void publishBlockedByOriginConfigurationRefusesARealPublishUntilItIsLifted() throws IOException {
|
||||
String crateName = "originblockedcrate";
|
||||
byte[] published = buildCrate(crateName, VERSION);
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, VERSION, published))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
|
||||
putPackageOriginConfiguration(AUTH, DOMAIN, REPO, "cargo", null, crateName, "BLOCK", "BLOCK");
|
||||
|
||||
byte[] nextVersionCrate = buildCrate(crateName, "2.0.0");
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, "2.0.0", nextVersionCrate))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(409);
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/" + sparseIndexPath(crateName))
|
||||
.then().statusCode(200)
|
||||
.body(containsString("\"vers\":\"" + VERSION + "\""));
|
||||
|
||||
putPackageOriginConfiguration(AUTH, DOMAIN, REPO, "cargo", null, crateName, "ALLOW", "BLOCK");
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.contentType("application/octet-stream")
|
||||
.body(publishBody(crateName, "2.0.0", nextVersionCrate))
|
||||
.put("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/new")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code ListPackages} against a repository that has actually published through cargo, against
|
||||
* the real Kellnr container this whole class already shares: {@code KellnrSidecarClient} had
|
||||
* no {@code listPackages} override at all until this was added, so adding {@code cargo} to
|
||||
* {@code CONTAINER_BACKED_FORMATS} alone made every unfiltered or cargo-filtered {@code
|
||||
* ListPackages} request on any repository 500 before this fix, confirmed only by calling the
|
||||
* real action here rather than the sidecar client directly.
|
||||
*/
|
||||
@Test
|
||||
@Order(10)
|
||||
void listPackagesListsEveryRealCrateThisRepositoryHasPublished() {
|
||||
given().header("Authorization", AUTH)
|
||||
.post("/v1/packages?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo")
|
||||
.then().statusCode(200)
|
||||
.body("packages.package", hasItem(CRATE_NAME));
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases this class's own Kellnr container (via a real ordered {@code @Test}, not {@code
|
||||
* @AfterAll}: Quarkus's own test extension can already be tearing down the HTTP listener by
|
||||
* the time a {@code @AfterAll} static method runs if this happens to be the last class in the
|
||||
* fork, so the request itself would fail with a connection reset) rather than leaving it for a
|
||||
* later, unrelated {@code /state/reset} call to stop as part of {@code ContainerTeardowns
|
||||
* #stopAll}'s own sequential sweep over every registered {@code ContainerTeardown}, cargo's
|
||||
* included: that sweep blocks whichever single HTTP request happens to trigger it on every
|
||||
* one of them, so a container left running here only extends some later, unrelated test's own
|
||||
* reset call rather than this class's own.
|
||||
*/
|
||||
@Test
|
||||
@Order(11)
|
||||
void releasesItsOwnKellnrContainerSoALaterUnrelatedResetDoesNotHaveToStopIt() {
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static long describeDomainAssetSizeBytes() {
|
||||
return given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
}
|
||||
|
||||
/** The real crates.io sparse-index bucketing rule for a name 9 characters long (4+ case). */
|
||||
private static String sparseIndexPath(String crateName) {
|
||||
return crateName.substring(0, 2) + "/" + crateName.substring(2, 4) + "/" + crateName;
|
||||
}
|
||||
|
||||
/**
|
||||
* The real binary wire body confirmed directly from the Cargo Book's own spec text, and live
|
||||
* against a real Kellnr container in part 1: a 4-byte little-endian metadata length, the JSON
|
||||
* metadata itself (here with one real, non-empty dependency, to prove a native publish's own
|
||||
* dependency list survives the round trip untouched, unlike {@code CopyPackageVersions}'s own
|
||||
* always-empty-deps path), then a 4-byte little-endian crate length and the crate itself.
|
||||
*/
|
||||
private static byte[] publishBody(String name, String version, byte[] crateBytes) {
|
||||
String metadataJson = "{\"name\":\"" + name + "\",\"vers\":\"" + version + "\",\"deps\":["
|
||||
+ "{\"name\":\"real-dependency\",\"version_req\":\"^1.0\",\"features\":[],\"optional\":false,"
|
||||
+ "\"default_features\":true,\"target\":null,\"kind\":\"normal\",\"registry\":null}],"
|
||||
+ "\"features\":{},\"authors\":[],\"description\":\"a test crate\",\"documentation\":null,"
|
||||
+ "\"homepage\":null,\"readme\":null,\"readme_file\":null,\"keywords\":[],\"categories\":[],"
|
||||
+ "\"license\":\"MIT\",\"license_file\":null,\"repository\":null,\"badges\":{},\"links\":null}";
|
||||
byte[] metadata = metadataJson.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(4 + metadata.length + 4 + crateBytes.length)
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(metadata.length);
|
||||
buffer.put(metadata);
|
||||
buffer.putInt(crateBytes.length);
|
||||
buffer.put(crateBytes);
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
/** A real, minimal, valid {@code .crate}: a gzipped tarball with one real {@code Cargo.toml}. */
|
||||
private static byte[] buildCrate(String name, String version) throws IOException {
|
||||
String cargoToml = "[package]\nname = \"" + name + "\"\nversion = \"" + version + "\"\nedition = \"2021\"\n";
|
||||
byte[] cargoTomlBytes = cargoToml.getBytes(StandardCharsets.UTF_8);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(out);
|
||||
TarArchiveOutputStream tar = new TarArchiveOutputStream(gzip)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry(name + "-" + version + "/Cargo.toml");
|
||||
entry.setSize(cargoTomlBytes.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(cargoTomlBytes);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
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 static io.floci.aws.testing.CodeArtifactRequests.putPackageOriginConfiguration;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Retains a real crate version from the real, live {@code public:crates-io} repository (not a
|
||||
* local fake), through the native per-format route, the way a real {@code cargo build}/{@code
|
||||
* cargo add} would. {@code libc} 0.2.169 is picked because it is small, stable, and confirmed
|
||||
* live against the real {@code index.crates.io}/{@code static.crates.io} production endpoints
|
||||
* (the index's own {@code cksum} for this exact version was confirmed to match the real
|
||||
* downloaded bytes' own SHA-256 before writing this test, not assumed). A genuine network
|
||||
* dependency, unlike every other sidecar-backed test here, which only ever talks to a container
|
||||
* Floci itself started; see {@code CodeArtifactCargoExternalConnectionImporterTest} for the
|
||||
* mocked, deterministic coverage of the claim/fence/mixed-origin/checksum logic this test does
|
||||
* not re-exercise, mirroring {@code CodeArtifactNuGetExternalConnectionDockerIntegrationTest}'s
|
||||
* own shape and reasoning.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CodeArtifactCargoExternalConnectionDockerIntegrationTest {
|
||||
|
||||
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/codeartifact/aws4_request";
|
||||
private static final String DOMAIN = "cargo-external-connection-domain";
|
||||
private static final String REPO = "cargo-external-connection-repo";
|
||||
private static final String BLOCKED_REPO = "cargo-external-connection-blocked-repo";
|
||||
private static final String CRATE_NAME = "libc";
|
||||
private static final String VERSION = "0.2.169";
|
||||
|
||||
private static String bearerToken;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.codeartifact.cargo-image");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(0)
|
||||
void createDomainRepositoriesConnectionAndToken() {
|
||||
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);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + REPO
|
||||
+ "&external-connection=public:crates-io")
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository/external-connection?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO
|
||||
+ "&external-connection=public:crates-io")
|
||||
.then().statusCode(200);
|
||||
|
||||
bearerToken = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
}
|
||||
|
||||
/**
|
||||
* Proves {@link CodeArtifactCargoExternalConnectionImporter#mergeExternalVersions}'s own
|
||||
* reason for existing: the real upstream version line is visible here even though nothing
|
||||
* has ever been downloaded (so nothing is retained yet), which a real {@code cargo} client's
|
||||
* dependency resolver needs in order to ever choose this version at all. Run before the
|
||||
* download test below, so this genuinely proves the merge, not a locally-cached line.
|
||||
*/
|
||||
@Test
|
||||
@Order(1)
|
||||
void fetchingTheSparseIndexMergesInTheRealUpstreamVersionBeforeAnythingIsRetained() {
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/" + sparseIndexPath(CRATE_NAME))
|
||||
.then().statusCode(200)
|
||||
.body(containsString("\"name\":\"" + CRATE_NAME + "\""))
|
||||
.body(containsString("\"vers\":\"" + VERSION + "\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void fetchingAMissingCrateRetainsItFromTheRealCratesIoConnectionAndCountsItsBytes() {
|
||||
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
|
||||
assertEquals(0L, assetSizeBytesBefore);
|
||||
|
||||
byte[] fetched = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + CRATE_NAME + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
|
||||
// A real .crate is a real gzip file: 0x1f 0x8b magic bytes, not asserting exact content
|
||||
// since the real artifact is out of this test's control.
|
||||
assertEquals((byte) 0x1f, fetched[0]);
|
||||
assertEquals((byte) 0x8b, fetched[1]);
|
||||
assertThat(fetched.length, greaterThan(1000));
|
||||
|
||||
assertEquals(assetSizeBytesBefore + fetched.length, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void refetchingTheSameVersionServesItWithoutRetainingItAgain() {
|
||||
long assetSizeBytesBefore = describeDomainAssetSizeBytes();
|
||||
|
||||
byte[] fetched = given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + CRATE_NAME + "/" + VERSION
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertEquals((byte) 0x1f, fetched[0]);
|
||||
assertEquals((byte) 0x8b, fetched[1]);
|
||||
|
||||
assertEquals(assetSizeBytesBefore, describeDomainAssetSizeBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code BLOCK}ed package shows no upstream-only version either, matching every other
|
||||
* retention path's own "behave exactly as if the external content did not exist" rule, not
|
||||
* just refusing the download: a real {@code cargo} client's own resolver must not even see a
|
||||
* version this repository is configured never to retain.
|
||||
*/
|
||||
@Test
|
||||
@Order(4)
|
||||
void upstreamBlockPreventsBothRetentionAndTheIndexMerge() {
|
||||
putPackageOriginConfiguration(AUTH, DOMAIN, BLOCKED_REPO, "cargo", null, CRATE_NAME, "ALLOW", "BLOCK");
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + BLOCKED_REPO + "/api/v1/crates/" + CRATE_NAME + "/"
|
||||
+ VERSION + "/download")
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + BLOCKED_REPO + "/" + sparseIndexPath(CRATE_NAME))
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", AUTH)
|
||||
.get("/v1/package?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO + "&format=cargo&package="
|
||||
+ CRATE_NAME)
|
||||
.then().statusCode(200)
|
||||
.body("package.originConfiguration.restrictions.upstream", equalTo("BLOCK"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void aVersionTheRealRepositoryDoesNotHaveIsNeverRetained() {
|
||||
given().header("Authorization", bearerToken)
|
||||
.get("/codeartifact/cargo/" + DOMAIN + "/" + REPO + "/api/v1/crates/" + CRATE_NAME
|
||||
+ "/999.999.999/download")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms the fix every other format's own importer already needed (a successfully retained
|
||||
* version reporting an external, not internal, origin) holds for cargo too, against the real
|
||||
* sidecar's own retained version from {@link
|
||||
* #fetchingAMissingCrateRetainsItFromTheRealCratesIoConnectionAndCountsItsBytes}, not a mock.
|
||||
*/
|
||||
@Test
|
||||
@Order(6)
|
||||
void aRetainedVersionReportsAnExternalOriginNotInternal() {
|
||||
given().header("Authorization", AUTH)
|
||||
.post("/v1/package/versions?domain=" + DOMAIN + "&repository=" + REPO + "&format=cargo&package="
|
||||
+ CRATE_NAME)
|
||||
.then().statusCode(200)
|
||||
.body("versions[0].version", equalTo(VERSION))
|
||||
.body("versions[0].origin.originType", equalTo("EXTERNAL"))
|
||||
.body("versions[0].origin.domainEntryPoint.externalConnectionName", equalTo("public:crates-io"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A mixed-case real crate name, confirmed live against production before writing this test
|
||||
* (its real {@code cksum} matches its real downloaded bytes' own SHA-256): the Cargo Book
|
||||
* requires the sparse-index bucket path and filename to be lowercased, confirmed live too
|
||||
* (the real {@code index.crates.io} 404s at {@code In/fl/Inflector} and only resolves at
|
||||
* {@code in/fl/inflector}), while the download route needs the crate's own original case.
|
||||
* Its own repository, separate from {@link #REPO}, so this doesn't interleave with the
|
||||
* ordered sequence above.
|
||||
*/
|
||||
@Test
|
||||
@Order(7)
|
||||
void aMixedCaseCrateNameResolvesAndRetainsCorrectly() {
|
||||
String domain = "cargo-external-connection-mixed-case-domain";
|
||||
String repo = "cargo-external-connection-mixed-case-repo";
|
||||
String crateName = "Inflector";
|
||||
String version = "0.11.4";
|
||||
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);
|
||||
given().contentType("application/json").header("Authorization", AUTH).body("{}")
|
||||
.post("/v1/repository/external-connection?domain=" + domain + "&repository=" + repo
|
||||
+ "&external-connection=public:crates-io")
|
||||
.then().statusCode(200);
|
||||
String token = given().header("Authorization", AUTH)
|
||||
.post("/v1/authorization-token?domain=" + domain)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("authorizationToken");
|
||||
|
||||
given().header("Authorization", token)
|
||||
.get("/codeartifact/cargo/" + domain + "/" + repo + "/" + sparseIndexPath(crateName))
|
||||
.then().statusCode(200)
|
||||
.body(containsString("\"name\":\"" + crateName + "\""))
|
||||
.body(containsString("\"vers\":\"" + version + "\""));
|
||||
|
||||
byte[] fetched = given().header("Authorization", token)
|
||||
.get("/codeartifact/cargo/" + domain + "/" + repo + "/api/v1/crates/" + crateName + "/" + version
|
||||
+ "/download")
|
||||
.then().statusCode(200)
|
||||
.extract().asByteArray();
|
||||
assertEquals((byte) 0x1f, fetched[0]);
|
||||
assertEquals((byte) 0x8b, fetched[1]);
|
||||
assertThat(fetched.length, greaterThan(100));
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases every Kellnr container this class started (see {@code
|
||||
* CodeArtifactCargoDockerIntegrationTest#releasesItsOwnKellnrContainerSoALaterUnrelatedResetDoesNotHaveToStopIt}'s
|
||||
* own javadoc for why this is a real ordered {@code @Test} and not {@code @AfterAll}),
|
||||
* including the mixed-case test's own separate repository.
|
||||
*/
|
||||
@Test
|
||||
@Order(8)
|
||||
void releasesEveryKellnrContainerThisClassStarted() {
|
||||
given().header("Authorization", AUTH).delete("/v1/repository?domain=" + DOMAIN + "&repository=" + REPO)
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/repository?domain=" + DOMAIN + "&repository=" + BLOCKED_REPO)
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", AUTH)
|
||||
.delete("/v1/repository?domain=cargo-external-connection-mixed-case-domain&repository="
|
||||
+ "cargo-external-connection-mixed-case-repo")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static long describeDomainAssetSizeBytes() {
|
||||
return given().header("Authorization", AUTH)
|
||||
.get("/v1/domain?domain=" + DOMAIN)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getLong("domain.assetSizeBytes");
|
||||
}
|
||||
|
||||
/** The real crates.io sparse-index bucketing rule for {@link #CRATE_NAME} (a 4+-character
|
||||
* name): first two, then next two, characters. */
|
||||
private static String sparseIndexPath(String crateName) {
|
||||
return crateName.substring(0, 2) + "/" + crateName.substring(2, 4) + "/" + crateName;
|
||||
}
|
||||
}
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.services.codeartifact.model.CodeArtifactRepository;
|
||||
import io.floci.aws.services.codeartifact.model.ExternalConnection;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.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.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link CodeArtifactCargoExternalConnectionImporter}'s own decision logic: when it attempts a
|
||||
* real external-connection fetch at all, and what it writes back, mirroring {@link
|
||||
* CodeArtifactNuGetExternalConnectionImporterTest}'s own shape for {@code tryImport}, plus
|
||||
* dedicated cases for {@code mergeExternalVersions}, the one genuinely new piece this format
|
||||
* needs (see this importer's own javadoc for why). {@link KellnrSidecarClient} and {@link
|
||||
* CargoExternalConnectionClient} are both mocked, so no real network or Kellnr call ever happens
|
||||
* here; their own wire contracts have their own tests.
|
||||
*/
|
||||
class CodeArtifactCargoExternalConnectionImporterTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String DOMAIN = "dom";
|
||||
private static final String OWNER = "123456789012";
|
||||
private static final String REPOSITORY = "repo";
|
||||
private static final String REPO_ID = "repo-id";
|
||||
private static final String PACKAGE_NAME = "democrate";
|
||||
private static final String VERSION = "1.0.0";
|
||||
private static final byte[] CRATE_CONTENT = "crate-content".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static final long EPISODE_ID = 7L;
|
||||
|
||||
private CodeArtifactService service;
|
||||
private KellnrSidecarClient kellnr;
|
||||
private CargoExternalConnectionClient externalConnectionClient;
|
||||
private CodeArtifactCargoExternalConnectionImporter importer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = mock(CodeArtifactService.class);
|
||||
kellnr = mock(KellnrSidecarClient.class);
|
||||
externalConnectionClient = mock(CargoExternalConnectionClient.class);
|
||||
importer = new CodeArtifactCargoExternalConnectionImporter(service, kellnr, externalConnectionClient,
|
||||
new ObjectMapper());
|
||||
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setExternalConnections(
|
||||
List.of(new ExternalConnection("public:crates-io", "cargo", "AVAILABLE")));
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
when(service.isUpstreamRetentionBlocked(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), eq("EXTERNAL_UPSTREAM"))).thenReturn(false);
|
||||
when(service.currentContainerBackedPackageFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString())).thenReturn(42L);
|
||||
when(service.currentContainerBackedVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString())).thenReturn(99L);
|
||||
when(service.claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION), anyLong()))
|
||||
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(true, EPISODE_ID));
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(false);
|
||||
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
|
||||
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(true, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importsFromExternalConnectionWhenNotFoundLocally() {
|
||||
stubRealIndexAndCrate(VERSION, CRATE_CONTENT);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(service).retainAssetUnderVersionFence(eq(REGION), eq(DOMAIN), eq(OWNER), eq(REPOSITORY), eq("cargo"),
|
||||
isNull(), eq(PACKAGE_NAME), eq(VERSION), eq(99L), eq(42L), eq(EPISODE_ID), eq(REPO_ID),
|
||||
eq(PACKAGE_NAME + "-" + VERSION + ".crate"), eq((long) CRATE_CONTENT.length), any());
|
||||
verify(service).ensureRetainedPackageOriginDefaultIfCurrentRepository(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
"cargo", null, PACKAGE_NAME, 42L, REPO_ID);
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenNoCargoExternalConnectionIsConfigured() {
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setExternalConnections(List.of());
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION),
|
||||
anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenUpstreamRetentionIsBlocked() {
|
||||
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
"EXTERNAL_UPSTREAM")).thenReturn(true);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).claimRetainedVersionOrigin(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyString(), eq(RetentionOriginKind.EXTERNAL_CONNECTION),
|
||||
anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWithoutFinishingWhenTheClaimIsRefused() {
|
||||
when(service.claimRetainedVersionOrigin(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION, "public:crates-io", RetentionOriginKind.EXTERNAL_CONNECTION, 42L))
|
||||
.thenReturn(new CodeArtifactService.RetainedVersionOriginClaimOutcome(false, 0L));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(kellnr, never()).packageVersionExists(anyString(), anyString(), anyString(), any(), anyString(),
|
||||
anyString());
|
||||
verify(service, never()).finishRetainedVersionOriginAttempt(anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), any(), anyString(), anyString(), anyLong(), anyBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsTrueWithoutFetchingWhenAConcurrentAttemptAlreadyRetainedIt() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(true);
|
||||
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION)).thenReturn(Optional.of("public:crates-io"));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertTrue(imported);
|
||||
verify(externalConnectionClient, never()).fetchSparseIndex(anyString(), anyString());
|
||||
verify(externalConnectionClient, never()).fetchCrate(anyString(), anyString(), anyString(), any());
|
||||
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
|
||||
anyString(), anyLong(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotMislabelAVersionADirectPushWroteDuringTheRaceAsExternallyRetained() {
|
||||
when(kellnr.packageVersionExists(REPO_ID, DOMAIN, REPOSITORY, null, PACKAGE_NAME, VERSION))
|
||||
.thenReturn(true);
|
||||
when(service.retainedVersionOriginConnection(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
VERSION)).thenReturn(Optional.empty());
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(externalConnectionClient, never()).fetchSparseIndex(anyString(), anyString());
|
||||
verify(service, never()).ensureRetainedPackageOriginDefaultIfCurrentRepository(anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), any(), anyString(), anyLong(), anyString());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseAndFinishesWhenTheRealIndexIsUnreachable() {
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
|
||||
anyString(), anyLong(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseWhenTheRealIndexNamesNoMatchingVersion() {
|
||||
byte[] index = indexLine("2.0.0", sha256Hex(CRATE_CONTENT)).getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(index));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(externalConnectionClient, never()).fetchCrate(anyString(), anyString(), anyString(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFetchThatThrowsPropagatesRatherThanBeingTreatedLikeAMissingCrate() {
|
||||
byte[] index = indexLine(VERSION, sha256Hex(CRATE_CONTENT)).getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(index));
|
||||
when(externalConnectionClient.fetchCrate(eq("public:crates-io"), eq(PACKAGE_NAME), eq(VERSION),
|
||||
any(Path.class))).thenThrow(new IllegalStateException("public registry unreachable"));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY,
|
||||
REPO_ID, PACKAGE_NAME, VERSION));
|
||||
|
||||
// Still runs its own bookkeeping on the way out, via the outer finally, rather than ever
|
||||
// leaving a claimed-but-never-finished retention attempt behind.
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsAnImportWhoseRealBytesDoNotMatchTheIndexsOwnCksum() {
|
||||
byte[] index = indexLine(VERSION, "0".repeat(64)).getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(index));
|
||||
stubFetchCrate(VERSION, CRATE_CONTENT);
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(),
|
||||
anyString(), anyLong(), any());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsFalseAndDoesNotRecordADefaultWhenTheFenceMovedDuringTheWrite() {
|
||||
stubRealIndexAndCrate(VERSION, CRATE_CONTENT);
|
||||
when(service.retainAssetUnderVersionFence(anyString(), anyString(), anyString(), anyString(), anyString(),
|
||||
any(), anyString(), anyString(), anyLong(), anyLong(), anyLong(), anyString(), anyString(), anyLong(),
|
||||
any())).thenReturn(new CodeArtifactService.AssetRetentionAttemptResult(false, false));
|
||||
|
||||
boolean imported = importer.tryImport(REGION, DOMAIN, OWNER, REPOSITORY, REPO_ID, PACKAGE_NAME, VERSION);
|
||||
|
||||
assertFalse(imported);
|
||||
verify(service, never()).ensureRetainedPackageOriginDefaultIfCurrentRepository(anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), any(), anyString(), anyLong(), anyString());
|
||||
verify(service).finishRetainedVersionOriginAttempt(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null,
|
||||
PACKAGE_NAME, VERSION, EPISODE_ID, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsReturnsLocalBytesUnchangedWhenNoConnectionConfigured() {
|
||||
CodeArtifactRepository repository = new CodeArtifactRepository();
|
||||
repository.setExternalConnections(List.of());
|
||||
when(service.describeRepository(REGION, DOMAIN, OWNER, REPOSITORY)).thenReturn(repository);
|
||||
Optional<byte[]> local = Optional.of("local-bytes".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
local);
|
||||
|
||||
assertEquals(local, merged);
|
||||
verify(externalConnectionClient, never()).fetchSparseIndex(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsReturnsLocalBytesUnchangedWhenUpstreamRetentionIsBlocked() {
|
||||
when(service.isUpstreamRetentionBlocked(REGION, DOMAIN, OWNER, REPOSITORY, "cargo", null, PACKAGE_NAME,
|
||||
"EXTERNAL_UPSTREAM")).thenReturn(true);
|
||||
Optional<byte[]> local = Optional.of("local-bytes".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
local);
|
||||
|
||||
assertEquals(local, merged);
|
||||
verify(externalConnectionClient, never()).fetchSparseIndex(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsAddsUpstreamOnlyVersionLinesNotAlreadyLocal() {
|
||||
String localLine = indexLine("1.0.0", "a".repeat(64));
|
||||
String upstreamOnlyLine = indexLine("2.0.0", "b".repeat(64));
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of((localLine + "\n" + upstreamOnlyLine).getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
Optional.of((localLine + "\n").getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
assertTrue(merged.isPresent());
|
||||
String mergedText = new String(merged.get(), StandardCharsets.UTF_8);
|
||||
assertTrue(mergedText.contains("\"1.0.0\""));
|
||||
assertTrue(mergedText.contains("\"2.0.0\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsKeepsTheLocalLineForAVersionPresentInBoth() {
|
||||
String localLine = indexLine("1.0.0", "a".repeat(64));
|
||||
String upstreamLineSameVersion = indexLine("1.0.0", "different-cksum-should-never-win".repeat(2));
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(upstreamLineSameVersion.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
Optional.of(localLine.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
assertTrue(merged.isPresent());
|
||||
assertEquals(localLine, new String(merged.get(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeExternalVersionsReturnsEmptyWhenBothLocalAndUpstreamAreEmpty() {
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(new byte[0]));
|
||||
|
||||
Optional<byte[]> merged = importer.mergeExternalVersions(REGION, DOMAIN, OWNER, REPOSITORY, PACKAGE_NAME,
|
||||
Optional.empty());
|
||||
|
||||
assertEquals(Optional.empty(), merged);
|
||||
}
|
||||
|
||||
private static String indexLine(String version, String cksum) {
|
||||
return "{\"name\":\"" + PACKAGE_NAME + "\",\"vers\":\"" + version + "\",\"deps\":[],\"cksum\":\"" + cksum
|
||||
+ "\",\"features\":{},\"yanked\":false}";
|
||||
}
|
||||
|
||||
private void stubRealIndexAndCrate(String version, byte[] content) {
|
||||
byte[] index = indexLine(version, sha256Hex(content)).getBytes(StandardCharsets.UTF_8);
|
||||
when(externalConnectionClient.fetchSparseIndex("public:crates-io", PACKAGE_NAME))
|
||||
.thenReturn(Optional.of(index));
|
||||
stubFetchCrate(version, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code fetchCrate}'s real, streamed signature takes the destination {@link Path} to write
|
||||
* to, generated fresh by the importer itself for every real call, so a test fixture can't
|
||||
* name it in advance the way it could a plain {@code byte[]}-returning method: this answers
|
||||
* whatever path the importer actually passes by writing {@code content} straight to it, the
|
||||
* same real effect the real method has.
|
||||
*/
|
||||
private void stubFetchCrate(String version, byte[] content) {
|
||||
when(externalConnectionClient.fetchCrate(eq("public:crates-io"), eq(PACKAGE_NAME), eq(version),
|
||||
any(Path.class))).thenAnswer(invocation -> {
|
||||
Path destination = invocation.getArgument(3);
|
||||
Files.write(destination, content);
|
||||
return Optional.of(new CargoExternalConnectionClient.FetchedFile(content.length,
|
||||
sha256Hex(content)));
|
||||
});
|
||||
}
|
||||
|
||||
private static String sha256Hex(byte[] content) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(digest.digest(content));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1065,7 +1065,7 @@ class CodeArtifactServiceTest {
|
||||
service.createDomain(REGION, "dom", null, Map.of());
|
||||
CodeArtifactRepository created = service.createRepository(REGION, "dom", null, "repo", null, null, Map.of());
|
||||
|
||||
assertEquals(Set.of("maven", "npm", "pypi", "nuget"), created.getSidecarContainerIds().keySet());
|
||||
assertEquals(Set.of("maven", "npm", "pypi", "nuget", "cargo"), created.getSidecarContainerIds().keySet());
|
||||
created.getSidecarContainerIds().values()
|
||||
.forEach(id -> assertTrue(id != null && !id.isBlank()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,508 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.PerKeyContainerPool;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* Wire-contract tests for {@link KellnrSidecarClient} against a JDK {@code HttpServer} standing
|
||||
* in for a running Kellnr container, shaped exactly like the real responses captured live against
|
||||
* a real Kellnr container earlier in this project. The container is registered in the manager's
|
||||
* pool directly, so readiness resolves to the fake server without any Docker daemon.
|
||||
*/
|
||||
class KellnrSidecarClientTest {
|
||||
|
||||
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
|
||||
private HttpServer backend;
|
||||
private String backendUrl;
|
||||
|
||||
@BeforeEach
|
||||
void setUpBackend() throws Exception {
|
||||
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
backend.createContext("/api/v1/crates/config.json", exchange -> {
|
||||
byte[] body = "{\"dl\":\"/api/v1/crates/dl\",\"api\":\"\",\"auth-required\":false}"
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
backend.start();
|
||||
backendUrl = "http://127.0.0.1:" + backend.getAddress().getPort();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDownBackend() {
|
||||
backend.stop(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageVersionExistsTrueForAPublishedVersion() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
|
||||
assertTrue(client(manager).packageVersionExists("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageVersionExistsFalseForAVersionThatWasNeverPublished() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
|
||||
assertFalse(client(manager).packageVersionExists("cargo-repo-1", "dom", "repo", null, "democrate", "9.9.9"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packageExistsFalseWhenTheSparseIndexHasNeverBeenPublished() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
backend.createContext("/api/v1/crates/de/mo/democrate", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
assertFalse(client(manager).packageExists("cargo-repo-1", "dom", "repo", null, "democrate"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPackagesIsEmptyWhenTheRepositoryHasNoRunningContainerYet() {
|
||||
KellnrSidecarManager manager = manager();
|
||||
|
||||
assertTrue(client(manager).listPackages("cargo-repo-1", "dom", "repo").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPackagesNamesEveryCrateAcrossAPaginatedReadOfTheRealListingRoute() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
List<String> requestedQueries = new CopyOnWriteArrayList<>();
|
||||
backend.createContext("/api/v1/ui/crates", exchange -> {
|
||||
requestedQueries.add(exchange.getRequestURI().getQuery());
|
||||
byte[] body;
|
||||
if (exchange.getRequestURI().getQuery().contains("page=0")) {
|
||||
body = ("{\"crates\":[{\"name\":\"democrate\",\"version\":\"1.0.0\"},"
|
||||
+ "{\"name\":\"othercrate\",\"version\":\"2.0.0\"}],\"page_size\":100,\"page\":0}")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
} else {
|
||||
body = "{\"crates\":[],\"page_size\":100,\"page\":1}".getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
List<RepositorySidecarManager.PackageIdentifier> packages = client(manager).listPackages("cargo-repo-1",
|
||||
"dom", "repo");
|
||||
|
||||
assertEquals(List.of(new RepositorySidecarManager.PackageIdentifier(null, "democrate"),
|
||||
new RepositorySidecarManager.PackageIdentifier(null, "othercrate")), packages);
|
||||
assertEquals(2, requestedQueries.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionAssetGetsTheRealDownloadPath() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
backend.createContext("/api/v1/crates/dl/democrate/1.0.0/download", exchange -> {
|
||||
byte[] body = "crate bytes".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<byte[]> result = client(manager).fetchPackageVersionAsset("cargo-repo-1", "dom", "repo", null,
|
||||
"democrate", "1.0.0", "democrate-1.0.0.crate");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("crate bytes", new String(result.get(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchPackageVersionAssetEmptyWhenTheAssetNameIsNotTheDeterministicForm() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
|
||||
Optional<byte[]> result = client(manager).fetchPackageVersionAsset("cargo-repo-1", "dom", "repo", null,
|
||||
"democrate", "1.0.0", "wrong-name.crate");
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #fetchPackageVersionAssetGetsTheRealDownloadPath}'s own streamed sibling: same wire
|
||||
* behavior, but the caller gets an open {@link InputStream} plus the real {@code
|
||||
* Content-Length} instead of an already-resident {@code byte[]}.
|
||||
*/
|
||||
@Test
|
||||
void fetchPackageVersionAssetStreamedGetsTheRealDownloadPath() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
backend.createContext("/api/v1/crates/dl/democrate/1.0.0/download", exchange -> {
|
||||
byte[] body = "crate bytes".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
Optional<RepositorySidecarManager.StreamedAsset> result = client(manager).fetchPackageVersionAssetStreamed(
|
||||
"cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0", "democrate-1.0.0.crate");
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
try (InputStream in = result.get().content()) {
|
||||
assertEquals("crate bytes", new String(in.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
assertEquals(11, result.get().contentLength());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPackageVersionAssetNamesNamesTheOneDeterministicAsset() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndex("democrate", "1.0.0");
|
||||
|
||||
List<String> result = client(manager).listPackageVersionAssetNames("cargo-repo-1", "dom", "repo", null,
|
||||
"democrate", "1.0.0");
|
||||
|
||||
assertEquals(List.of("democrate-1.0.0.crate"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPackageVersionsReadsEachEntrysPubtime() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondWithSparseIndexLines("democrate",
|
||||
sparseIndexLine("democrate", "1.0.0", "2026-01-15T10:00:00Z"),
|
||||
sparseIndexLine("democrate", "2.0.0", "2026-02-20T10:00:00Z"));
|
||||
|
||||
List<RepositorySidecarManager.PackageVersionTimestamp> result = client(manager)
|
||||
.listPackageVersions("cargo-repo-1", "dom", "repo", null, "democrate");
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertEquals("1.0.0", result.get(0).version());
|
||||
assertEquals(Instant.parse("2026-01-15T10:00:00Z"), result.get(0).publishedTime());
|
||||
assertEquals("2.0.0", result.get(1).version());
|
||||
assertEquals(Instant.parse("2026-02-20T10:00:00Z"), result.get(1).publishedTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* The real crates.io sparse-index bucketing rule for a 4+ character name: first two
|
||||
* characters, then next two, then the name itself, confirmed live against a real Kellnr
|
||||
* container earlier in this project.
|
||||
*/
|
||||
@Test
|
||||
void sparseIndexPathBucketsAFourCharacterOrLongerNameByItsFirstFourCharacters() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
backend.createContext("/api/v1/crates/se/rd/serde", exchange -> {
|
||||
byte[] body = sparseIndexLine("serde", "1.0.0", "2026-01-15T10:00:00Z").getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
assertTrue(client(manager).packageVersionExists("cargo-repo-1", "dom", "repo", null, "serde", "1.0.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storePackageVersionAssetPublishesTheRealBinaryWireBody() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
AtomicReference<String> receivedCookie = new AtomicReference<>();
|
||||
AtomicReference<byte[]> receivedBody = new AtomicReference<>();
|
||||
AtomicReference<String> receivedAuthorization = new AtomicReference<>();
|
||||
respondToLogin();
|
||||
respondToAddToken(cookie -> receivedCookie.set(cookie));
|
||||
backend.createContext("/api/v1/crates/new", exchange -> {
|
||||
receivedAuthorization.set(exchange.getRequestHeaders().getFirst("Authorization"));
|
||||
receivedBody.set(exchange.getRequestBody().readAllBytes());
|
||||
byte[] body = "{\"warnings\":null}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
client(manager).storePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate", "crate bytes".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// The token-mint call used the admin session cookie, and the real publish call used the
|
||||
// minted token (no "Bearer" prefix, confirmed live against a real Kellnr container) rather
|
||||
// than the cookie itself.
|
||||
assertEquals("kellnr_session_id=test-session", receivedCookie.get());
|
||||
assertEquals("tok-1", receivedAuthorization.get());
|
||||
byte[] body = receivedBody.get();
|
||||
ByteBuffer buffer = ByteBuffer.wrap(body).order(ByteOrder.LITTLE_ENDIAN);
|
||||
int metadataLength = buffer.getInt();
|
||||
byte[] metadata = new byte[metadataLength];
|
||||
buffer.get(metadata);
|
||||
assertTrue(new String(metadata, StandardCharsets.UTF_8).contains("\"name\":\"democrate\""));
|
||||
assertTrue(new String(metadata, StandardCharsets.UTF_8).contains("\"vers\":\"1.0.0\""));
|
||||
int crateLength = buffer.getInt();
|
||||
byte[] crate = new byte[crateLength];
|
||||
buffer.get(crate);
|
||||
assertEquals("crate bytes", new String(crate, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link KellnrSidecarClient#storePackageVersionAsset(String, String, String, String, String,
|
||||
* String, String, byte[])}'s own streamed sibling: the staged file's real content ends up in
|
||||
* the same binary wire body.
|
||||
*/
|
||||
@Test
|
||||
void storePackageVersionAssetStreamedSendsTheStagedFilesRealContent() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
Path staged = Files.createTempFile("kellnr-client-test-", ".tmp");
|
||||
Files.writeString(staged, "staged crate bytes");
|
||||
respondToLogin();
|
||||
respondToAddToken(cookie -> { });
|
||||
AtomicReference<byte[]> receivedBody = new AtomicReference<>();
|
||||
backend.createContext("/api/v1/crates/new", exchange -> {
|
||||
receivedBody.set(exchange.getRequestBody().readAllBytes());
|
||||
byte[] body = "{\"warnings\":null}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
client(manager).storePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate", staged, Files.size(staged));
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.wrap(receivedBody.get()).order(ByteOrder.LITTLE_ENDIAN);
|
||||
int metadataLength = buffer.getInt();
|
||||
buffer.position(buffer.position() + metadataLength);
|
||||
int crateLength = buffer.getInt();
|
||||
byte[] crate = new byte[crateLength];
|
||||
buffer.get(crate);
|
||||
assertEquals("staged crate bytes", new String(crate, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storePackageVersionAssetMintsOnlyOneTokenAcrossSeveralPublishes() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondToLogin();
|
||||
List<String> mintedTokenNames = new CopyOnWriteArrayList<>();
|
||||
backend.createContext("/api/v1/user/add_token", exchange -> {
|
||||
mintedTokenNames.add("minted");
|
||||
byte[] body = "{\"name\":\"floci\",\"token\":\"tok-1\"}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
backend.createContext("/api/v1/crates/new", exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
byte[] body = "{\"warnings\":null}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
KellnrSidecarClient client = client(manager);
|
||||
|
||||
client.storePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate", "a".getBytes(StandardCharsets.UTF_8));
|
||||
client.storePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "2.0.0",
|
||||
"democrate-2.0.0.crate", "b".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertEquals(1, mintedTokenNames.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePackageDeletesViaTheAdminRouteWithTheSessionCookie() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondToLogin();
|
||||
AtomicReference<String> receivedQuery = new AtomicReference<>();
|
||||
AtomicReference<String> receivedCookie = new AtomicReference<>();
|
||||
backend.createContext("/api/v1/ui/delete_crate", exchange -> {
|
||||
receivedQuery.set(exchange.getRequestURI().getQuery());
|
||||
receivedCookie.set(exchange.getRequestHeaders().getFirst("Cookie"));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
client(manager).deletePackage("cargo-repo-1", "dom", "repo", null, "democrate");
|
||||
|
||||
assertEquals("name=democrate", receivedQuery.get());
|
||||
assertEquals("kellnr_session_id=test-session", receivedCookie.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePackageVersionAssetDeletesViaTheAdminRouteWithBothNameAndVersion() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondToLogin();
|
||||
AtomicReference<String> receivedQuery = new AtomicReference<>();
|
||||
backend.createContext("/api/v1/ui/delete_version", exchange -> {
|
||||
receivedQuery.set(exchange.getRequestURI().getQuery());
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
client(manager).deletePackageVersionAsset("cargo-repo-1", "dom", "repo", null, "democrate", "1.0.0",
|
||||
"democrate-1.0.0.crate");
|
||||
|
||||
assertEquals("name=democrate&version=1.0.0", receivedQuery.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePackageToleratesAnAlreadyGoneCoordinate() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", backendUrl);
|
||||
respondToLogin();
|
||||
backend.createContext("/api/v1/ui/delete_crate", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
exchange.close();
|
||||
});
|
||||
|
||||
assertFalse(catches(() -> client(manager).deletePackage("cargo-repo-1", "dom", "repo", null, "democrate")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A future {@code CodeArtifactCargoController}'s own push handler is expected to synchronize
|
||||
* on this exact object for a repository, the same one {@link KellnrSidecarClient
|
||||
* #storePackageVersionAsset} and {@link KellnrSidecarClient#deletePackage} themselves take, so
|
||||
* a push and a delete for the same repository can never interleave; a different repository
|
||||
* must still get its own lock rather than blocking behind an unrelated one.
|
||||
*/
|
||||
@Test
|
||||
void lockForReturnsTheSameObjectForOneRepositoryAndDifferentObjectsForDifferentOnes() {
|
||||
KellnrSidecarClient client = client(manager());
|
||||
|
||||
Object repo1Again = client.lockFor("cargo-repo-1");
|
||||
|
||||
assertSame(client.lockFor("cargo-repo-1"), repo1Again);
|
||||
assertNotSame(client.lockFor("cargo-repo-1"), client.lockFor("cargo-repo-2"));
|
||||
}
|
||||
|
||||
private static boolean catches(ThrowingRunnable runnable) {
|
||||
try {
|
||||
runnable.run();
|
||||
return false;
|
||||
} catch (RuntimeException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ThrowingRunnable {
|
||||
void run();
|
||||
}
|
||||
|
||||
private void respondToLogin() {
|
||||
backend.createContext("/api/v1/user/login", exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
exchange.getResponseHeaders().add("Set-Cookie", "kellnr_session_id=test-session; Path=/");
|
||||
byte[] body = "{\"user\":\"admin\",\"is_admin\":true,\"is_logged_in\":true}"
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
}
|
||||
|
||||
private void respondToAddToken(Consumer<String> receivedCookie) {
|
||||
backend.createContext("/api/v1/user/add_token", exchange -> {
|
||||
receivedCookie.accept(exchange.getRequestHeaders().getFirst("Cookie"));
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
byte[] body = "{\"name\":\"floci\",\"token\":\"tok-1\"}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
}
|
||||
|
||||
private void respondWithSparseIndex(String packageName, String version) {
|
||||
respondWithSparseIndexLines(packageName, sparseIndexLine(packageName, version, "2026-01-15T10:00:00Z"));
|
||||
}
|
||||
|
||||
private void respondWithSparseIndexLines(String packageName, String... lines) {
|
||||
String body = String.join("\n", lines);
|
||||
backend.createContext(sparseIndexContextPath(packageName), exchange -> {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.close();
|
||||
});
|
||||
}
|
||||
|
||||
private static String sparseIndexContextPath(String packageName) {
|
||||
String first2 = packageName.substring(0, 2);
|
||||
String next2 = packageName.substring(2, 4);
|
||||
return "/api/v1/crates/" + first2 + "/" + next2 + "/" + packageName;
|
||||
}
|
||||
|
||||
private static String sparseIndexLine(String packageName, String version, String pubtime) {
|
||||
return "{\"name\":\"" + packageName + "\",\"vers\":\"" + version + "\",\"deps\":[],\"cksum\":\"abc\","
|
||||
+ "\"features\":{},\"yanked\":false,\"pubtime\":\"" + pubtime + "\",\"v\":1}";
|
||||
}
|
||||
|
||||
private KellnrSidecarClient client(KellnrSidecarManager manager) {
|
||||
return new KellnrSidecarClient(manager, new ObjectMapper(), HttpClient.newHttpClient());
|
||||
}
|
||||
|
||||
private KellnrSidecarManager manager() {
|
||||
return new KellnrSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void seedPooledContainer(KellnrSidecarManager manager, String key, String containerId,
|
||||
String url) throws Exception {
|
||||
Field poolField = KellnrSidecarManager.class.getDeclaredField("pool");
|
||||
poolField.setAccessible(true);
|
||||
PerKeyContainerPool pool = (PerKeyContainerPool) poolField.get(manager);
|
||||
|
||||
Field containersField = PerKeyContainerPool.class.getDeclaredField("containers");
|
||||
containersField.setAccessible(true);
|
||||
ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer> containers =
|
||||
(ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer>) containersField.get(pool);
|
||||
containers.put(key, new PerKeyContainerPool.StartedContainer(containerId, url));
|
||||
// The real startContainer() always mints and stores a password together with starting the
|
||||
// container; this fake seeding stands in for both at once via the manager's own
|
||||
// package-private test seam, not reflection, since that one is new to this class.
|
||||
manager.seedAdminPasswordForTest(key, "test-admin-password");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package io.floci.aws.services.codeartifact;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.ContainerTeardown;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.PerKeyContainerPool;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.http.HttpClient;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
/**
|
||||
* Checks teardown wiring and use leases without a Docker daemon. Containers are seeded directly
|
||||
* into the pool; the manager must defer deletion while a request is active and retain failed
|
||||
* removal for a later teardown retry. Mirrors {@link BagetterSidecarManagerTest} exactly: same
|
||||
* per-repository container lease shape, different sidecar.
|
||||
*/
|
||||
class KellnrSidecarManagerTest {
|
||||
|
||||
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
|
||||
@Test
|
||||
void implementsContainerTeardownSoStateResetAndNukeCanFindIt() {
|
||||
assertInstanceOf(ContainerTeardown.class, manager());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopManagedContainersStopsEveryContainerThePoolIsTracking() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", "http://127.0.0.1:1");
|
||||
seedPooledContainer(manager, "cargo-repo-2", "tracked-kellnr-2", "http://127.0.0.1:1");
|
||||
|
||||
manager.stopManagedContainers();
|
||||
|
||||
verify(lifecycleManager).stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
verify(lifecycleManager).stopAndRemoveStrict("tracked-kellnr-2", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopManagedContainersIsANoOpWhenNothingWasEverStarted() {
|
||||
KellnrSidecarManager manager = manager();
|
||||
|
||||
manager.stopManagedContainers();
|
||||
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void releaseWaitsForTheLastCargoRequestBeforeStoppingItsContainer() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", "http://127.0.0.1:1");
|
||||
RepositorySidecarManager client = new KellnrSidecarClient(manager, new ObjectMapper(),
|
||||
HttpClient.newHttpClient());
|
||||
client.registerRepository("cargo-repo-1");
|
||||
client.beginUse("cargo-repo-1");
|
||||
|
||||
client.release("cargo-repo-1");
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
assertThrows(IllegalStateException.class, () -> client.beginUse("cargo-repo-1"));
|
||||
|
||||
client.endUse("cargo-repo-1");
|
||||
verify(lifecycleManager).stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRemovalRemainsRetryableAfterTheLastUse() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", "http://127.0.0.1:1");
|
||||
manager.registerRepository("cargo-repo-1");
|
||||
manager.beginUse("cargo-repo-1");
|
||||
manager.release("cargo-repo-1");
|
||||
doThrow(new IllegalStateException("Docker unavailable")).doNothing().when(lifecycleManager)
|
||||
.stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
|
||||
assertDoesNotThrow(() -> manager.endUse("cargo-repo-1"));
|
||||
assertTrue(manager.isRunning("cargo-repo-1"));
|
||||
assertThrows(IllegalStateException.class, () -> manager.beginUse("cargo-repo-1"));
|
||||
assertThrows(IllegalStateException.class, () -> manager.endUse("cargo-repo-1"));
|
||||
|
||||
manager.stopManagedContainers();
|
||||
assertFalse(manager.isRunning("cargo-repo-1"));
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void teardownKeepsAnActiveUseUntilTheRequestFinishes() throws Exception {
|
||||
KellnrSidecarManager manager = manager();
|
||||
seedPooledContainer(manager, "cargo-repo-1", "tracked-kellnr-1", "http://127.0.0.1:1");
|
||||
manager.registerRepository("cargo-repo-1");
|
||||
manager.beginUse("cargo-repo-1");
|
||||
|
||||
manager.stopManagedContainers();
|
||||
verifyNoInteractions(lifecycleManager);
|
||||
assertThrows(IllegalStateException.class, () -> manager.beginUse("cargo-repo-1"));
|
||||
|
||||
manager.endUse("cargo-repo-1");
|
||||
verify(lifecycleManager).stopAndRemoveStrict("tracked-kellnr-1", null);
|
||||
}
|
||||
|
||||
private KellnrSidecarManager manager() {
|
||||
return new KellnrSidecarManager(containerBuilder, lifecycleManager, config);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void seedPooledContainer(KellnrSidecarManager manager, String key, String containerId,
|
||||
String url) throws Exception {
|
||||
Field poolField = KellnrSidecarManager.class.getDeclaredField("pool");
|
||||
poolField.setAccessible(true);
|
||||
PerKeyContainerPool pool = (PerKeyContainerPool) poolField.get(manager);
|
||||
|
||||
Field containersField = PerKeyContainerPool.class.getDeclaredField("containers");
|
||||
containersField.setAccessible(true);
|
||||
ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer> containers =
|
||||
(ConcurrentHashMap<String, PerKeyContainerPool.StartedContainer>) containersField.get(pool);
|
||||
containers.put(key, new PerKeyContainerPool.StartedContainer(containerId, url));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user