Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ A Maven repository backed by Cloudflare R2, with a standalone Go publishing clie

- Release, snapshot, and mixed repositories; public or private visibility.
- Atomic publication sessions, immutable releases and timestamped snapshots, concurrent metadata merging, resumable multipart uploads, and failed-build rollback.
- Maven POMs, parent POMs, Gradle module metadata, classifiers, detached signatures, and MD5/SHA-1/SHA-256/SHA-512 sidecars. The server verifies supplied checksums and generates checksums for its own metadata.
- Maven POMs, parent POMs, Gradle module metadata, classifiers, detached signatures, and MD5/SHA-1/SHA-256/SHA-512 sidecars. The Go CLI computes artifact checksums; the server checks supplied sidecars against those declarations and generates checksums for its own metadata.
- Direct downloads with Basic or Bearer token authentication, conditional GET, HEAD, and byte ranges. Public repositories need no credentials.
- Configurable repository URLs, including a release repository at the domain root and snapshots at `/snapshots`, in single- or multiple-workspace instances.
- Single-workspace or multiple-workspace instances, GitHub login, optional OIDC, configurable signups, invitation links, and owner/admin/publisher/reader roles.
Expand All @@ -30,9 +30,9 @@ A Maven repository backed by Cloudflare R2, with a standalone Go publishing clie
| Approach | Advantages | Costs |
| ----------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Presigned R2 uploads | Artifact bytes bypass Worker execution; useful for very large transfers | Requires S3 signing credentials, grants remain usable until expiry, multipart coordination and final validation are still needed |
| Worker streaming, implemented | Binding-based R2 access, immediate authorization checks, one protocol and deployment surface | More Worker requests; full-file checksum validation reads uploaded bytes again; CPU and D1 limits need capacity planning |
| Worker streaming, implemented | Binding-based R2 access, immediate authorization checks, one protocol and deployment surface | More Worker requests; publisher-provided multipart checksums; CPU and D1 limits need capacity planning |

The part size keeps individual requests below normal Worker request-body limits. This implementation targets **Workers Paid** for finalization and checksum-validation budgets; review [Worker limits](https://developers.cloudflare.com/workers/platform/limits/) and [D1 limits](https://developers.cloudflare.com/d1/platform/limits/) for your workload. A future presigned transport can use the same staging and commit model without changing build configuration.
The part size keeps individual requests below normal Worker request-body limits. Artifact hashing runs in the Go CLI. **Workers Free** deployments must remove `limits.cpu_ms` from their deployment configuration and validate their workload against the CPU, subrequest, and database limits; review [Worker limits](https://developers.cloudflare.com/workers/platform/limits/) and [D1 limits](https://developers.cloudflare.com/d1/platform/limits/) for your workload. Free-tier suitability is not guaranteed by moving hashing off the Worker. A future presigned transport can use the same staging and commit model without changing build configuration.

## Development

Expand Down Expand Up @@ -139,7 +139,7 @@ maven-r2 --profile work publish --repository acme/releases -- ./gradlew publish
maven-r2 --profile work publish --repository acme/snapshots -- mvn -s settings.xml deploy
```

The CLI launches a loopback-only proxy with a random per-run credential, starts the build, and commits after a successful exit. Configure publishing to use the injected `MAVEN_R2_URL`, `MAVEN_R2_USERNAME`, and `MAVEN_R2_PASSWORD`. The remote token is removed from the child's environment. The proxy spools at most four files concurrently to temporary files, checks their hashes, uploads resumable parts, and cleans up the spool files.
The CLI launches a loopback-only proxy with a random per-run credential, starts the build, and commits after a successful exit. Configure publishing to use the injected `MAVEN_R2_URL`, `MAVEN_R2_USERNAME`, and `MAVEN_R2_PASSWORD`. The remote token is removed from the child's environment. The proxy spools at most four files concurrently to temporary files, computes MD5/SHA-1/SHA-256/SHA-512 in the same pass, uploads resumable parts, and cleans up the spool files.

Gradle publishing configuration:

Expand All @@ -158,6 +158,8 @@ publishing {
}
```

Artifact checksums are publisher-provided declarations. R2 verifies SHA-256 for single-part uploads; multipart uploads are checked for completeness and stored size without the Worker rereading their contents. Sidecars must match the declared hashes, and server-generated metadata is hashed on the Worker. Clients and the Worker must be upgraded together: upload requests require all four hashes. Restart pending publications created by an older client. An identical retry is identified by the declared hashes and size; it never replaces an already published release object.

The proxy answers each upload only after the file is staged remotely. Gradle's HTTP client gives up after 30 seconds by default, so set `systemProp.org.gradle.internal.http.socketTimeout` in `gradle.properties` to cover your largest artifact, as the Gradle example does. Maven's default timeout is long enough.

For Maven, point both `distributionManagement.repository` and `snapshotRepository` at `${env.MAVEN_R2_URL}`, using a server ID with credentials from those environment variables. Complete multi-module examples are in [`examples/gradle`](examples/gradle) and [`examples/maven`](examples/maven). The Maven example uses the Flatten Maven Plugin to resolve `${revision}` in published POM coordinates.
Expand Down
10 changes: 7 additions & 3 deletions apps/worker/src/coordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,11 @@ export class RepositoryCoordinator extends DurableObject<Env> {
fail(400, "Signatures on mutable repository metadata are unsupported");
const c = coordinates(base)!;
const old = originals.get(upload.path);
if ((!c.snapshot || c.timestamp) && old && old.sha256 !== upload.sha256)
if (
(!c.snapshot || c.timestamp) &&
old &&
(old.sha256 !== upload.sha256 || old.size !== upload.size)
)
fail(409, "Release artifacts and timestamped snapshots are immutable");
if (
!c.snapshot &&
Expand All @@ -185,7 +189,7 @@ export class RepositoryCoordinator extends DurableObject<Env> {
fail(409, "This release version is already published");
if (upload.path.endsWith(".pom"))
validatePom(await readSmall(this.env, upload.object_key), upload.path);
if (old?.sha256 === upload.sha256) continue;
if (old?.sha256 === upload.sha256 && old.size === upload.size) continue;
const file: FileRow = {
repository_id: repo.id,
path: upload.path,
Expand Down Expand Up @@ -219,7 +223,7 @@ export class RepositoryCoordinator extends DurableObject<Env> {
.split(/\s+/)[0]
?.toLowerCase();
if (supplied !== (JSON.parse(base.checksums) as Checksums)[checksum.algorithm])
fail(400, "Uploaded checksum does not match the artifact");
fail(400, "Uploaded checksum does not match the declared artifact checksum");
}
}
const metadataPaths = new Set(
Expand Down
34 changes: 18 additions & 16 deletions apps/worker/src/publications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
publicationSchema,
uploadSchema,
errorSchema,
type Checksums,
} from "@maven-r2/contracts";
import { HTTPException } from "hono/http-exception";
import type { ContentfulStatusCode } from "hono/utils/http-status";
Expand All @@ -32,7 +33,7 @@ import {
type Principal,
} from "./security";
import { checksumBase, coordinates, isMetadata, publicationAction } from "./metadata";
import { PART_SIZE, MAX_METADATA_SIZE, digestStream } from "./storage";
import { PART_SIZE, MAX_METADATA_SIZE } from "./storage";
import { serveFile } from "./downloads";

export async function sessionAccess(
Expand Down Expand Up @@ -248,12 +249,12 @@ export function registerPublications(app: OpenAPIHono<AppEnv>) {
);
}
}
const object = await c.env.BUCKET.get(upload.object_key);
const object = await c.env.BUCKET.head(upload.object_key);
if (!object) fail(409, "Upload has missing parts");
const { checksums } = await digestStream(object.body, upload.size);
if (checksums.sha256 !== upload.sha256) fail(400, "Artifact checksum mismatch");
await c.env.DB.prepare("UPDATE uploads SET status='complete',checksums=? WHERE id=?")
.bind(JSON.stringify(checksums), upload.id)
if (object.size !== upload.size) fail(400, "Object size mismatch");
if (!upload.checksums) fail(409, "Restart this upload with client-computed checksums");
await c.env.DB.prepare("UPDATE uploads SET status='complete' WHERE id=?")
.bind(upload.id)
.run();
return c.json(await uploadView(c.env, { ...upload, status: "complete" }), 200);
});
Expand Down Expand Up @@ -376,10 +377,11 @@ export async function initiateUpload(
env: Env,
principal: Principal,
sessionId: string,
input: { path: string; size: number; sha256: string },
input: { path: string; size: number; checksums: Checksums },
) {
const { session, repo } = await sessionAccess(env, principal, sessionId, true);
const path = canonicalPath(input.path);
const checksums = JSON.stringify(input.checksums);
await authorizeUpload(env, principal, repo, session.id, path);
if (input.size > repo.max_file_bytes || input.size > Number(env.MAX_FILE_BYTES))
fail(413, "Artifact exceeds the repository file limit");
Expand All @@ -393,7 +395,7 @@ export async function initiateUpload(
let existing = await env.DB.prepare("SELECT * FROM uploads WHERE publication_id=? AND path=?")
.bind(session.id, path)
.first<UploadRow>();
if (existing && (existing.sha256 !== input.sha256 || existing.size !== input.size)) {
if (existing && (existing.checksums !== checksums || existing.size !== input.size)) {
// Maven re-uploads group metadata as each reactor module merges its plugin prefix.
if (!isMetadata(checksumBase(path)?.path ?? path))
fail(409, "This path already has different content in the publication");
Expand All @@ -408,17 +410,17 @@ export async function initiateUpload(
).bind(existing.object_key, existing.multipart_id, Date.now() + 60_000),
env.DB.prepare("DELETE FROM upload_parts WHERE upload_id=?").bind(existing.id),
env.DB.prepare(
"UPDATE uploads SET object_key=?,size=?,sha256=?,status='pending',multipart_id=NULL,checksums=NULL WHERE id=?",
).bind(key, input.size, input.sha256, existing.id),
"UPDATE uploads SET object_key=?,size=?,sha256=?,status='pending',multipart_id=NULL,checksums=? WHERE id=?",
).bind(key, input.size, input.checksums.sha256, checksums, existing.id),
]);
existing = {
...existing,
object_key: key,
size: input.size,
sha256: input.sha256,
sha256: input.checksums.sha256,
status: "pending",
multipart_id: null,
checksums: null,
checksums,
};
}
if (existing) {
Expand All @@ -445,19 +447,19 @@ export async function initiateUpload(
path,
object_key: key,
size: input.size,
sha256: input.sha256,
sha256: input.checksums.sha256,
status: "pending",
multipart_id: null,
checksums: null,
checksums,
};
await reserve(env, [
env.DB.prepare("UPDATE accounts SET reserved_bytes=reserved_bytes+? WHERE id=?").bind(
input.size,
repo.account_id,
),
env.DB.prepare(
"INSERT INTO uploads (id,publication_id,path,object_key,size,sha256,status) VALUES (?,?,?,?,?,?,'pending')",
).bind(id, session.id, path, key, input.size, input.sha256),
"INSERT INTO uploads (id,publication_id,path,object_key,size,sha256,checksums,status) VALUES (?,?,?,?,?,?,?,'pending')",
).bind(id, session.id, path, key, input.size, input.checksums.sha256, checksums),
]);
if (input.size > PART_SIZE) {
const multipart = await env.BUCKET.createMultipartUpload(key);
Expand Down
36 changes: 9 additions & 27 deletions apps/worker/src/storage.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,20 @@
import { createHash } from "node:crypto";
import type { Checksums } from "@maven-r2/contracts";
import type { Env } from "./env";
import { fail } from "./security";

export type { Checksums } from "@maven-r2/contracts";

export const PART_SIZE = 16 * 1024 * 1024;
export const MAX_METADATA_SIZE = 1024 * 1024;
export const algorithms = ["md5", "sha1", "sha256", "sha512"] as const;
export type Checksums = Record<(typeof algorithms)[number], string>;
export async function digestStream(stream: ReadableStream<Uint8Array>, expectedSize?: number) {
const digests = algorithms.map((algorithm) => createHash(algorithm));
let size = 0;
const reader = stream.getReader();
try {
for (;;) {
const { value, done } = await reader.read();
if (done) break;
size += value.byteLength;
if (expectedSize !== undefined && size > expectedSize) {
await reader.cancel();
fail(400, "Object size mismatch");
}
for (const digest of digests) digest.update(value);
}
} finally {
reader.releaseLock();
}
if (expectedSize !== undefined && size !== expectedSize) fail(400, "Object size mismatch");
const checksums = Object.fromEntries(
algorithms.map((algorithm, index) => [algorithm, digests[index]!.digest("hex")]),
) as Checksums;
return { size, checksums };
}
export async function storeText(env: Env, accountId: string, text: string) {
const bytes = new TextEncoder().encode(text);
const { checksums } = await digestStream(new Blob([bytes]).stream());
const checksums = Object.fromEntries(
["md5", "sha1", "sha256", "sha512"].map((algorithm) => [
algorithm,
createHash(algorithm).update(bytes).digest("hex"),
]),
) as Checksums;
const key = `objects/${accountId}/${crypto.randomUUID()}`;
await env.DB.prepare("INSERT INTO garbage (object_key,not_before) VALUES (?,?)")
.bind(key, Date.now() + 24 * 60 * 60 * 1000)
Expand Down
Loading
Loading