From 4415127c3d17383fc41b3d2ce9c60968c300ddcf Mon Sep 17 00:00:00 2001 From: oglassdev <23040613+oglassdev@users.noreply.github.com> Date: Mon, 21 Sep 2026 01:15:47 -0400 Subject: [PATCH] perf: compute artifact checksums in the publishing CLI --- README.md | 10 +-- apps/worker/src/coordinator.ts | 10 ++- apps/worker/src/publications.ts | 34 +++++----- apps/worker/src/storage.ts | 36 +++------- apps/worker/test/publication.test.ts | 82 +++++++++++++++++++---- internal/api/generated.go | 14 +++- internal/client/client.go | 4 +- internal/client/client_test.go | 2 +- internal/proxy/proxy.go | 16 ++++- internal/proxy/proxy_test.go | 48 +++++++++++++ packages/contracts/generated/openapi.json | 32 ++++++++- packages/contracts/src/index.ts | 3 +- packages/contracts/src/schemas.ts | 7 ++ 13 files changed, 221 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 8d9b618..c846c8d 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 @@ -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: @@ -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. diff --git a/apps/worker/src/coordinator.ts b/apps/worker/src/coordinator.ts index a981814..3a2e494 100644 --- a/apps/worker/src/coordinator.ts +++ b/apps/worker/src/coordinator.ts @@ -175,7 +175,11 @@ export class RepositoryCoordinator extends DurableObject { 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 && @@ -185,7 +189,7 @@ export class RepositoryCoordinator extends DurableObject { 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, @@ -219,7 +223,7 @@ export class RepositoryCoordinator extends DurableObject { .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( diff --git a/apps/worker/src/publications.ts b/apps/worker/src/publications.ts index a4d3e8a..fd16ac5 100644 --- a/apps/worker/src/publications.ts +++ b/apps/worker/src/publications.ts @@ -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"; @@ -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( @@ -248,12 +249,12 @@ export function registerPublications(app: OpenAPIHono) { ); } } - 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); }); @@ -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"); @@ -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(); - 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"); @@ -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) { @@ -445,10 +447,10 @@ 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( @@ -456,8 +458,8 @@ export async function initiateUpload( 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); diff --git a/apps/worker/src/storage.ts b/apps/worker/src/storage.ts index 8a4bf40..84556df 100644 --- a/apps/worker/src/storage.ts +++ b/apps/worker/src/storage.ts @@ -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, 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) diff --git a/apps/worker/test/publication.test.ts b/apps/worker/test/publication.test.ts index f20cb01..a97f900 100644 --- a/apps/worker/test/publication.test.ts +++ b/apps/worker/test/publication.test.ts @@ -1,4 +1,4 @@ -import { createHmac } from "node:crypto"; +import { createHash, createHmac } from "node:crypto"; import { auth } from "../src/auth"; import { cleanup } from "../src/cleanup"; import { env } from "cloudflare:workers"; @@ -33,16 +33,21 @@ async function begin(repository = "releases") { 201, ); } +function checksums(content: string | Uint8Array) { + return { + md5: createHash("md5").update(content).digest("hex"), + sha1: createHash("sha1").update(content).digest("hex"), + sha256: createHash("sha256").update(content).digest("hex"), + sha512: createHash("sha512").update(content).digest("hex"), + }; +} async function stage(session: string, path: string, content: string | Uint8Array) { const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content; - const sha256 = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (b) => - b.toString(16).padStart(2, "0"), - ).join(""); const upload = await json( await request(`/api/publications/${session}/uploads`, "POST", { path, size: bytes.length, - sha256, + checksums: checksums(bytes), }), ); for ( @@ -105,6 +110,14 @@ describe("publication and Maven protocol", () => { expect(await file.text()).toBe("artifact"); expect((await request(path, "GET", undefined, "")).status).toBe(401); expect(await (await request(path + ".sha256")).text()).toBe(await hash("artifact")); + for (const [algorithm, value] of Object.entries(checksums("artifact"))) { + expect(await (await request(path + "." + algorithm)).text()).toBe(value); + } + const metadataPath = "/maven/test/releases/com/acme/demo/maven-metadata.xml"; + const metadataText = await (await request(metadataPath)).text(); + expect(await (await request(metadataPath + ".sha256")).text()).toBe( + await hash(metadataText), + ); const metadata = parseMetadata( await (await request("/maven/test/releases/com/acme/demo/maven-metadata.xml")).text(), ); @@ -172,7 +185,7 @@ describe("publication and Maven protocol", () => { const conflict = await request(`/api/publications/${session.id}/uploads`, "POST", { path: "com/acme/demo/1.0/demo-1.0.jar", size: 9, - sha256: "0".repeat(64), + checksums: checksums("different"), }); expect(conflict.status).toBe(409); await json(await request(`/api/publications/${session.id}/commit`, "POST")); @@ -205,14 +218,17 @@ describe("publication and Maven protocol", () => { )?.value, ).toBe("1.0-20260920.120000-1"); }); - it("uploads and verifies multipart artifacts", async () => { + it("uploads multipart artifacts with publisher-provided checksums", async () => { const session = await begin(); await stage(session.id, "com/acme/demo/1.0/demo-1.0.pom", pom("1.0")); - await stage( - session.id, - "com/acme/demo/1.0/demo-1.0.jar", - new Uint8Array(PART_SIZE + 8).fill(7), - ); + const bytes = new Uint8Array(PART_SIZE + 8).fill(7); + const read = vi.spyOn(env.BUCKET, "get"); + try { + await stage(session.id, "com/acme/demo/1.0/demo-1.0.jar", bytes); + expect(read).not.toHaveBeenCalled(); + } finally { + read.mockRestore(); + } await json(await request(`/api/publications/${session.id}/commit`, "POST")); expect( ( @@ -220,6 +236,44 @@ describe("publication and Maven protocol", () => { ).headers.get("content-length"), ).toBe(String(PART_SIZE + 8)); }); + it("requires complete checksum declarations and preserves them across retries", async () => { + const session = await begin(); + const endpoint = `/api/publications/${session.id}/uploads`; + const input = { + path: "com/acme/demo/1.0/demo-1.0.jar", + size: 8, + checksums: checksums("artifact"), + }; + expect((await request(endpoint, "POST", { ...input, checksums: undefined })).status).toBe( + 400, + ); + expect( + ( + await request(endpoint, "POST", { + ...input, + checksums: { ...input.checksums, md5: "invalid" }, + }) + ).status, + ).toBe(400); + const upload = await json(await request(endpoint, "POST", input)); + expect((await json(await request(endpoint, "POST", input))).id).toBe(upload.id); + expect( + ( + await request(endpoint, "POST", { + ...input, + checksums: { ...input.checksums, sha1: "0".repeat(40) }, + }) + ).status, + ).toBe(409); + expect((await request(endpoint, "POST", { ...input, size: 9 })).status).toBe(409); + await env.BUCKET.put( + (await env.DB.prepare("SELECT object_key FROM uploads WHERE id=?") + .bind(upload.id) + .first<{ object_key: string }>())!.object_key, + "short", + ); + expect((await request(`${endpoint}/${upload.id}/complete`, "POST")).status).toBe(400); + }); it("enforces namespace boundaries, expiry and service account revocation", async () => { const row = await env.DB.prepare("SELECT * FROM tokens").first<{ id: string; @@ -241,7 +295,7 @@ describe("publication and Maven protocol", () => { const denied = await request(`/api/publications/${session.id}/uploads`, "POST", { path: "com/acmeevil/demo/1.0/demo-1.0.jar", size: 1, - sha256: await hash("x"), + checksums: checksums("x"), }); expect(denied.status).toBe(403); await env.DB.prepare("UPDATE service_accounts SET disabled=1 WHERE id=?") @@ -783,7 +837,7 @@ describe("workspace policies", () => { await request(`/api/publications/${session.id}/uploads`, "POST", { path: "com/acme/demo/1.0/demo-1.0.pom", size: 11, - sha256: await hash("x".repeat(11)), + checksums: checksums("x".repeat(11)), }) ).status, ).toBe(413); diff --git a/internal/api/generated.go b/internal/api/generated.go index bf805aa..f69702d 100644 --- a/internal/api/generated.go +++ b/internal/api/generated.go @@ -55,6 +55,14 @@ func (e UploadStatus) Valid() bool { } } +// Checksums defines model for Checksums. +type Checksums struct { + Md5 string `json:"md5"` + Sha1 string `json:"sha1"` + Sha256 string `json:"sha256"` + Sha512 string `json:"sha512"` +} + // CreatePublication defines model for CreatePublication. type CreatePublication struct { Account string `json:"account"` @@ -64,9 +72,9 @@ type CreatePublication struct { // CreateUpload defines model for CreateUpload. type CreateUpload struct { - Path string `json:"path"` - Sha256 string `json:"sha256"` - Size int `json:"size"` + Checksums Checksums `json:"checksums"` + Path string `json:"path"` + Size int `json:"size"` } // Error defines model for Error. diff --git a/internal/client/client.go b/internal/client/client.go index a1893dd..c3e9af2 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -102,9 +102,9 @@ func (c *Client) Abort(ctx context.Context, id string) error { return err } -func (c *Client) Upload(ctx context.Context, session, path string, file *os.File, size int64, digest string) error { +func (c *Client) Upload(ctx context.Context, session, path string, file *os.File, size int64, checksums api.Checksums) error { upload, err := retry(ctx, func() (api.Upload, error) { - response, err := c.API.CreateUpload(ctx, session, api.CreateUpload{Path: path, Size: int(size), Sha256: digest}) + response, err := c.API.CreateUpload(ctx, session, api.CreateUpload{Path: path, Size: int(size), Checksums: checksums}) return decode[api.Upload](response, err) }) if err != nil { diff --git a/internal/client/client_test.go b/internal/client/client_test.go index 98da48d..aa8d6b9 100644 --- a/internal/client/client_test.go +++ b/internal/client/client_test.go @@ -54,7 +54,7 @@ func TestUploadResumesPartsAndRetriesTransientFailures(t *testing.T) { } defer file.Close() file.WriteString("123456789") - if err = c.Upload(context.Background(), "session", "x", file, 9, "digest"); err != nil { + if err = c.Upload(context.Background(), "session", "x", file, 9, api.Checksums{Sha256: "digest"}); err != nil { t.Fatal(err) } if attempts["/api/publications/session/uploads/upload/parts/1"] != 0 { diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go index 7d09e01..a589fc1 100644 --- a/internal/proxy/proxy.go +++ b/internal/proxy/proxy.go @@ -2,8 +2,11 @@ package proxy import ( "context" + "crypto/md5" "crypto/rand" + "crypto/sha1" "crypto/sha256" + "crypto/sha512" "crypto/subtle" "encoding/hex" "errors" @@ -18,6 +21,7 @@ import ( "sync" "time" + "github.com/chunkzero/maven-r2/internal/api" "github.com/chunkzero/maven-r2/internal/client" ) @@ -172,8 +176,8 @@ func (s *Server) upload(ctx context.Context, path string, body io.Reader, length } defer os.Remove(file.Name()) defer file.Close() - digest := sha256.New() - size, err := io.Copy(io.MultiWriter(file, digest), io.LimitReader(body, s.MaxFileBytes+1)) + md5Hash, sha1Hash, sha256Hash, sha512Hash := md5.New(), sha1.New(), sha256.New(), sha512.New() + size, err := io.Copy(io.MultiWriter(file, md5Hash, sha1Hash, sha256Hash, sha512Hash), io.LimitReader(body, s.MaxFileBytes+1)) if err != nil { return err } @@ -183,7 +187,13 @@ func (s *Server) upload(ctx context.Context, path string, body io.Reader, length if length >= 0 && size != length { return fmt.Errorf("incomplete upload body") } - if err = s.Client.Upload(ctx, s.Session, path, file, size, hex.EncodeToString(digest.Sum(nil))); err != nil { + checksums := api.Checksums{ + Md5: hex.EncodeToString(md5Hash.Sum(nil)), + Sha1: hex.EncodeToString(sha1Hash.Sum(nil)), + Sha256: hex.EncodeToString(sha256Hash.Sum(nil)), + Sha512: hex.EncodeToString(sha512Hash.Sum(nil)), + } + if err = s.Client.Upload(ctx, s.Session, path, file, size, checksums); err != nil { return err } if s.Log != nil { diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go index c02e38e..3c3e971 100644 --- a/internal/proxy/proxy_test.go +++ b/internal/proxy/proxy_test.go @@ -1,8 +1,14 @@ package proxy import ( + "context" + "encoding/json" + "github.com/chunkzero/maven-r2/internal/api" + "github.com/chunkzero/maven-r2/internal/client" + "io" "net/http" "net/http/httptest" + "strings" "testing" ) @@ -34,3 +40,45 @@ func TestLocalProxyRejectsUntrustedRequests(t *testing.T) { }) } } + +func TestUploadComputesAllChecksumsWhileSpooling(t *testing.T) { + expected := api.Checksums{ + Md5: "900150983cd24fb0d6963f7d28e17f72", + Sha1: "a9993e364706816aba3e25717850c26c9cd0d89d", + Sha256: "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + Sha512: "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", + } + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/uploads"): + var input api.CreateUpload + if err := json.NewDecoder(r.Body).Decode(&input); err != nil { + t.Error(err) + } + if input.Checksums != expected || input.Size != 3 { + t.Errorf("unexpected declaration: %+v", input) + } + json.NewEncoder(w).Encode(api.Upload{Id: "upload", PartSize: 16, Status: api.Pending}) + case strings.HasSuffix(r.URL.Path, "/parts/1"): + body, _ := io.ReadAll(r.Body) + if string(body) != "abc" { + t.Errorf("unexpected body: %q", body) + } + io.WriteString(w, "{}") + case strings.HasSuffix(r.URL.Path, "/complete"): + json.NewEncoder(w).Encode(api.Upload{Id: "upload", Status: api.Complete}) + default: + t.Errorf("unexpected request: %s", r.URL.Path) + w.WriteHeader(404) + } + })) + defer upstream.Close() + c, err := client.New(upstream.URL, "mr2_test") + if err != nil { + t.Fatal(err) + } + server := Server{Client: c, Session: "session", MaxFileBytes: 1024} + if err := server.upload(context.Background(), "g/a/1/a-1.jar", strings.NewReader("abc"), 3); err != nil { + t.Fatal(err) + } +} diff --git a/packages/contracts/generated/openapi.json b/packages/contracts/generated/openapi.json index df72a47..c75d7c0 100644 --- a/packages/contracts/generated/openapi.json +++ b/packages/contracts/generated/openapi.json @@ -155,15 +155,41 @@ "type": "integer", "minimum": 0 }, + "checksums": { + "$ref": "#/components/schemas/Checksums" + } + }, + "required": [ + "path", + "size", + "checksums" + ] + }, + "Checksums": { + "type": "object", + "properties": { + "md5": { + "type": "string", + "pattern": "^[a-f0-9]{32}$" + }, + "sha1": { + "type": "string", + "pattern": "^[a-f0-9]{40}$" + }, "sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" + }, + "sha512": { + "type": "string", + "pattern": "^[a-f0-9]{128}$" } }, "required": [ - "path", - "size", - "sha256" + "md5", + "sha1", + "sha256", + "sha512" ] } }, diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 72ad50a..69a0325 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -1,6 +1,7 @@ import { createRoute, z } from "@hono/zod-openapi"; import { slug, + checksumsSchema, publicationSchema as publication, uploadSchema as upload, errorSchema as error, @@ -71,7 +72,7 @@ export const initUploadRoute = createRoute({ .object({ path: z.string().min(1).max(1024), size: z.number().int().min(0), - sha256: z.string().regex(/^[a-f0-9]{64}$/), + checksums: checksumsSchema.openapi("Checksums"), }) .openapi("CreateUpload"), }, diff --git a/packages/contracts/src/schemas.ts b/packages/contracts/src/schemas.ts index 9aaf35f..79198b3 100644 --- a/packages/contracts/src/schemas.ts +++ b/packages/contracts/src/schemas.ts @@ -1,6 +1,13 @@ import { z } from "zod"; export const slug = z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/); +export const checksumsSchema = z.object({ + md5: z.string().regex(/^[a-f0-9]{32}$/), + sha1: z.string().regex(/^[a-f0-9]{40}$/), + sha256: z.string().regex(/^[a-f0-9]{64}$/), + sha512: z.string().regex(/^[a-f0-9]{128}$/), +}); +export type Checksums = z.infer; export const role = z.enum(["owner", "admin", "publisher", "reader"]); export const action = z.enum(["read", "publish:release", "publish:snapshot", "delete"]); export const scope = z.object({