Public: anyone can read this; the crew can change it.
Revert "LFS door: batch API and locks on the BlobStore" #16754
Check · Review · Land · Live done — Landed and live in production.
revert-16708 → main 0 commits
13 files
changed +2
−912
- docs/features/lfs.md
- src/blob/large.ts
- src/blob/lfs.ts
- src/http/lfs_routes.ts
- src/http/server.ts
- src/kernel/body_caps.ts
- src/tui/screens/lfslocks.ts
- src/tui/screens/workspace.ts
- test/lfs-locks-tui.test.ts
- test/lfs.test.ts
- test/no-polling.test.ts
- test/openapi-covers-routes.test.ts
- test/pages-budget.test.ts
docs/features/lfs.md deleted −20
| @@ -1,20 +0,0 @@ | ||
| 1 | --- | |
| 2 | topic: Your apps | |
| 3 | row: Git LFS: the batch API and file locks, on the same BlobStore as large files | |
| 4 | --- | |
| 5 | # Git LFS | |
| 6 | ||
| 7 | `git lfs` works against a repository's clone address, with no setup beyond `git lfs track`: it finds `/<owner>/<name>.git/info/lfs`. Objects are kept in the BlobStore (the bucket when `S3_*` is set, else a directory under the forge's data) under `lfs/<owner>/<name>/<sha256>`, so CAD files and other binaries stay out of git history. | |
| 8 | ||
| 9 | ## What is there | |
| 10 | ||
| 11 | - Batch API (`POST …/info/lfs/objects/batch`), basic transfer: at most 100 objects a call. On a bucket, each object's address is presigned straight to the bucket (an hour); on a directory store it is the forge's own `…/info/lfs/objects/<oid>` (GET to read, PUT to write, up to 512 MiB; the bytes are kept only if their sha256 is the object id). | |
| 12 | - Locks: `git lfs lock`, `unlock`, `locks` and the verify call a push makes. One lock per path, 1000 a repository; `unlock --force` is for anyone who may write. Locks are a file in the repository's directory, `forge-locks.json`. | |
| 13 | - Who: whoever may read the repository downloads and lists; uploading and locking take write access and a token that may write, as a push does. Anyone else gets the challenge (signed out) or a 404. | |
| 14 | - Terminal: open a repository, then the palette's "LFS locks" (`src/tui/screens/lfslocks.ts`); `u` releases the lock under the cursor after a confirm; `g` reads again. | |
| 15 | ||
| 16 | ## Not done | |
| 17 | ||
| 18 | The `verify` action after an upload, the `tus` and `ssh` transfers, and lock `ref` scoping are not here. An LFS object is not counted against a storage limit. Deleting a repository removes its objects; renaming it leaves them under the old name. | |
| 19 | ||
| 20 | Code: `src/blob/lfs.ts`, `src/http/lfs_routes.ts`. |
src/blob/large.ts −2
| @@ -25,7 +25,6 @@ import { gitEnv, runGit } from "../git/env.ts"; | ||
| 25 | 25 | import { isSafeOid } from "../git/guard.ts"; |
| 26 | 26 | import { repoDir } from "../git/repos.ts"; |
| 27 | 27 | import { createLog } from "../kernel/log.ts"; |
| 28 | import { lfsPrefix } from "./lfs.ts"; | |
| 29 | 28 | import { dirStore, s3FromEnv, s3Store, type BlobStore } from "./store.ts"; |
| 30 | 29 | |
| 31 | 30 | /** What this module needs of a forge. */ |
| @@ -216,7 +215,6 @@ export async function retractLarge( | ||
| 216 | 215 | const store = largeStore(app.config.dataDir); |
| 217 | 216 | const prefix = `large/${encodeURIComponent(repo.ownerName)}/${encodeURIComponent(repo.name)}/`; |
| 218 | 217 | for (const key of await store.list(prefix).catch(() => [])) await store.delete(key).catch(() => {}); |
| 219 | for (const key of await store.list(lfsPrefix(repo.ownerName, repo.name)).catch(() => [])) await store.delete(key).catch(() => {}); | |
| 220 | 218 | } |
| 221 | 219 | |
| 222 | 220 | /** |
src/blob/lfs.ts deleted −225
| @@ -1,225 +0,0 @@ | ||
| 1 | /** | |
| 2 | * Git LFS on the BlobStore (#4493, step 6 of #4481): what a CAD tool's `git lfs` needs, the batch | |
| 3 | * API and file locks, kept in the same store (and so the same bucket and presigned URLs) as large | |
| 4 | * blobs (`large.ts`). Objects are `lfs/<owner>/<name>/<sha256>`. The basic transfer only: a batch | |
| 5 | * answers each object with an address to PUT or GET, presigned when the store is a bucket, else | |
| 6 | * this forge's own (`/<owner>/<name>.git/info/lfs/objects/<oid>`, served by `http/lfs_routes.ts`). | |
| 7 | * | |
| 8 | * State: locks are one small file per repository, `<repo>/forge-locks.json`, read and written | |
| 9 | * synchronously so two requests in this one process never interleave. | |
| 10 | */ | |
| 11 | ||
| 12 | import { createHash, randomBytes } from "node:crypto"; | |
| 13 | import { readFileSync, renameSync, writeFileSync } from "node:fs"; | |
| 14 | import { join } from "node:path"; | |
| 15 | import type { BlobStore } from "./store.ts"; | |
| 16 | ||
| 17 | export const LFS_TYPE = "application/vnd.git-lfs+json"; | |
| 18 | /** The most objects one batch may name (git-lfs asks for 100). */ | |
| 19 | export const MAX_BATCH = 100; | |
| 20 | /** The largest object accepted: 512 MiB through this forge, as a push; a bucket sets its own. */ | |
| 21 | export const MAX_OBJECT = 512 * 1024 * 1024; | |
| 22 | /** How long an object's address lives. */ | |
| 23 | export const LFS_PRESIGN_S = 3600; | |
| 24 | export const MAX_LOCKS = 1000; | |
| 25 | export const MAX_LOCK_PATH = 1024; | |
| 26 | const LOCKS = "forge-locks.json"; | |
| 27 | ||
| 28 | export const isLfsOid = (oid: unknown): oid is string => typeof oid === "string" && /^[0-9a-f]{64}$/.test(oid); | |
| 29 | ||
| 30 | export const lfsKey = (owner: string, name: string, oid: string): string => | |
| 31 | `lfs/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/${oid}`; | |
| 32 | export const lfsPrefix = (owner: string, name: string): string => | |
| 33 | `lfs/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/`; | |
| 34 | ||
| 35 | // ---- batch ---- | |
| 36 | ||
| 37 | export interface BatchObject { | |
| 38 | readonly oid: string; | |
| 39 | readonly size: number; | |
| 40 | } | |
| 41 | export interface BatchInput { | |
| 42 | readonly operation: "download" | "upload"; | |
| 43 | readonly objects: BatchObject[]; | |
| 44 | } | |
| 45 | ||
| 46 | /** The request body read as a batch, or the sentence that refuses it. */ | |
| 47 | export function readBatch(raw: Record<string, unknown>): BatchInput | string { | |
| 48 | const { operation, objects, transfers } = raw; | |
| 49 | if (operation !== "download" && operation !== "upload") return "operation must be download or upload"; | |
| 50 | if (transfers !== undefined && (!Array.isArray(transfers) || !transfers.includes("basic"))) | |
| 51 | return "only the basic transfer is offered"; | |
| 52 | if (!Array.isArray(objects) || objects.length === 0) return "objects must be a list"; | |
| 53 | if (objects.length > MAX_BATCH) return `at most ${MAX_BATCH} objects in a batch`; | |
| 54 | const out: BatchObject[] = []; | |
| 55 | for (const o of objects as unknown[]) { | |
| 56 | const { oid, size } = (typeof o === "object" && o !== null ? o : {}) as { oid?: unknown; size?: unknown }; | |
| 57 | if (!isLfsOid(oid)) return "an object id is a lowercase sha256"; | |
| 58 | if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) return "an object size is a whole number of bytes"; | |
| 59 | out.push({ oid, size }); | |
| 60 | } | |
| 61 | return { operation, objects: out }; | |
| 62 | } | |
| 63 | ||
| 64 | /** One object's answer in a batch: what the client does next, or why it cannot. */ | |
| 65 | export async function answerObject(input: { | |
| 66 | readonly store: BlobStore; | |
| 67 | readonly owner: string; | |
| 68 | readonly name: string; | |
| 69 | readonly operation: "download" | "upload"; | |
| 70 | readonly object: BatchObject; | |
| 71 | /** The forge's own address for an object, used when the store cannot presign. */ | |
| 72 | readonly own: (oid: string) => string; | |
| 73 | }): Promise<Record<string, unknown>> { | |
| 74 | const { store, operation, object } = input; | |
| 75 | const { oid, size } = object; | |
| 76 | const key = lfsKey(input.owner, input.name, oid); | |
| 77 | const held = await store.size(key); | |
| 78 | const href = (method: "GET" | "PUT"): string => | |
| 79 | store.presign?.(key, { method, expiresInS: LFS_PRESIGN_S }) ?? input.own(oid); | |
| 80 | if (operation === "download") { | |
| 81 | if (held === undefined) return { oid, size, error: { code: 404, message: "object not found" } }; | |
| 82 | return { oid, size: held, authenticated: true, actions: { download: { href: href("GET"), expires_in: LFS_PRESIGN_S } } }; | |
| 83 | } | |
| 84 | if (size > MAX_OBJECT && store.presign === undefined) | |
| 85 | return { oid, size, error: { code: 413, message: `at most ${MAX_OBJECT} bytes through this forge` } }; | |
| 86 | if (held === size) return { oid, size, authenticated: true }; // already here: nothing to do | |
| 87 | return { oid, size, authenticated: true, actions: { upload: { href: href("PUT"), expires_in: LFS_PRESIGN_S } } }; | |
| 88 | } | |
| 89 | ||
| 90 | // ---- upload ---- | |
| 91 | ||
| 92 | export type Stored = "stored" | "held" | "too_large" | "mismatch" | "failed"; | |
| 93 | ||
| 94 | /** | |
| 95 | * Keep an uploaded object under its oid, only if its bytes are the object named. An object already | |
| 96 | * held at that length is never written again: a wrong upload cannot spoil it. Otherwise the bytes | |
| 97 | * are staged under a key of their own, checked (length and sha256), and only then copied to the | |
| 98 | * oid's key (the store has no move), so a bad upload leaves nothing at the final key. At most | |
| 99 | * `declared` bytes are read, whatever the body holds. | |
| 100 | */ | |
| 101 | export async function storeObject(input: { | |
| 102 | readonly store: BlobStore; | |
| 103 | readonly owner: string; | |
| 104 | readonly name: string; | |
| 105 | readonly oid: string; | |
| 106 | readonly declared: number; | |
| 107 | readonly source: ReadableStream<Uint8Array>; | |
| 108 | }): Promise<Stored> { | |
| 109 | const { store, declared } = input; | |
| 110 | if (declared > MAX_OBJECT) return "too_large"; | |
| 111 | const key = lfsKey(input.owner, input.name, input.oid); | |
| 112 | if ((await store.size(key)) === declared) { | |
| 113 | await input.source.cancel().catch(() => {}); | |
| 114 | return "held"; | |
| 115 | } | |
| 116 | const stage = `${lfsPrefix(input.owner, input.name)}tmp-${randomBytes(8).toString("hex")}`; | |
| 117 | const hash = createHash("sha256"); | |
| 118 | let seen = 0; | |
| 119 | const measured = input.source.pipeThrough( | |
| 120 | new TransformStream<Uint8Array, Uint8Array>({ | |
| 121 | transform(chunk, controller) { | |
| 122 | seen += chunk.byteLength; | |
| 123 | if (seen > declared) { | |
| 124 | controller.error(new Error("longer than declared")); | |
| 125 | return; | |
| 126 | } | |
| 127 | hash.update(chunk); | |
| 128 | controller.enqueue(chunk); | |
| 129 | }, | |
| 130 | }), | |
| 131 | ); | |
| 132 | try { | |
| 133 | await store.putStream(stage, measured); | |
| 134 | if (seen !== declared || hash.digest("hex") !== input.oid) return "mismatch"; | |
| 135 | const staged = await store.getStream(stage); | |
| 136 | if (staged === undefined) return "failed"; | |
| 137 | try { | |
| 138 | await store.putStream(key, staged); | |
| 139 | } catch { | |
| 140 | await store.delete(key).catch(() => {}); | |
| 141 | return "failed"; | |
| 142 | } | |
| 143 | return "stored"; | |
| 144 | } catch { | |
| 145 | return seen > declared ? "mismatch" : "failed"; | |
| 146 | } finally { | |
| 147 | await store.delete(stage).catch(() => {}); | |
| 148 | } | |
| 149 | } | |
| 150 | ||
| 151 | // ---- locks ---- | |
| 152 | ||
| 153 | export interface Lock { | |
| 154 | readonly id: string; | |
| 155 | readonly path: string; | |
| 156 | readonly locked_at: string; | |
| 157 | readonly owner: { readonly name: string; readonly id: string }; | |
| 158 | } | |
| 159 | ||
| 160 | /** | |
| 161 | * A lock's path as stored: relative, no `..`, no control characters, at most 1 KiB; else undefined. | |
| 162 | */ | |
| 163 | export function lockPath(raw: unknown): string | undefined { | |
| 164 | if (typeof raw !== "string" || raw === "" || raw.length > MAX_LOCK_PATH) return undefined; | |
| 165 | if (/[\x00-\x1f\x7f\\]/.test(raw) || raw.startsWith("/")) return undefined; | |
| 166 | const parts = raw.split("/"); | |
| 167 | if (parts.some((p) => p === "" || p === "." || p === "..")) return undefined; | |
| 168 | return raw; | |
| 169 | } | |
| 170 | ||
| 171 | export function readLocks(dir: string): Lock[] { | |
| 172 | try { | |
| 173 | const v: unknown = JSON.parse(readFileSync(join(dir, LOCKS), "utf8")); | |
| 174 | if (!Array.isArray(v)) return []; | |
| 175 | return (v as unknown[]).filter((l): l is Lock => { | |
| 176 | const x = (l ?? {}) as Partial<Lock>; | |
| 177 | return typeof x.id === "string" && typeof x.path === "string" && typeof x.locked_at === "string" && | |
| 178 | typeof x.owner?.name === "string" && typeof x.owner.id === "string"; | |
| 179 | }); | |
| 180 | } catch { | |
| 181 | return []; | |
| 182 | } | |
| 183 | } | |
| 184 | ||
| 185 | function writeLocks(dir: string, locks: Lock[]): void { | |
| 186 | const tmp = join(dir, `${LOCKS}.tmp`); | |
| 187 | writeFileSync(tmp, JSON.stringify(locks)); | |
| 188 | renameSync(tmp, join(dir, LOCKS)); | |
| 189 | } | |
| 190 | ||
| 191 | export type Took = { ok: true; lock: Lock } | { ok: false; why: "held"; lock: Lock } | { ok: false; why: "full" }; | |
| 192 | ||
| 193 | /** | |
| 194 | * Lock `path` for `who`, unless someone holds it (the same person asking again gets theirs back as | |
| 195 | * held). | |
| 196 | */ | |
| 197 | export function takeLock(dir: string, path: string, who: { id: string; name: string }, now = new Date()): Took { | |
| 198 | const locks = readLocks(dir); | |
| 199 | const held = locks.find((l) => l.path === path); | |
| 200 | if (held) return { ok: false, why: "held", lock: held }; | |
| 201 | if (locks.length >= MAX_LOCKS) return { ok: false, why: "full" }; | |
| 202 | const lock: Lock = { id: randomBytes(8).toString("hex"), path, locked_at: now.toISOString(), owner: { name: who.name, id: who.id } }; | |
| 203 | writeLocks(dir, [...locks, lock]); | |
| 204 | return { ok: true, lock }; | |
| 205 | } | |
| 206 | ||
| 207 | export type Released = { ok: true; lock: Lock } | { ok: false; why: "missing" | "not_yours" }; | |
| 208 | ||
| 209 | /** Release a lock: its holder's, or anyone who may write when `force`. */ | |
| 210 | export function releaseLock(dir: string, id: string, who: { id: string }, force: boolean): Released { | |
| 211 | const locks = readLocks(dir); | |
| 212 | const lock = locks.find((l) => l.id === id); | |
| 213 | if (!lock) return { ok: false, why: "missing" }; | |
| 214 | if (lock.owner.id !== who.id && !force) return { ok: false, why: "not_yours" }; | |
| 215 | writeLocks(dir, locks.filter((l) => l.id !== id)); | |
| 216 | return { ok: true, lock }; | |
| 217 | } | |
| 218 | ||
| 219 | /** A page of locks by cursor (an offset) and limit, 1 to 100, default 100. */ | |
| 220 | export function pageLocks(locks: Lock[], cursor: unknown, limit: unknown): { locks: Lock[]; next_cursor?: string } { | |
| 221 | const start = typeof cursor === "string" && /^\d{1,6}$/.test(cursor) ? Number(cursor) : 0; | |
| 222 | const n = Math.min(100, Math.max(1, Number.isSafeInteger(Number(limit)) && Number(limit) > 0 ? Number(limit) : 100)); | |
| 223 | const page = locks.slice(start, start + n); | |
| 224 | return start + n < locks.length ? { locks: page, next_cursor: String(start + n) } : { locks: page }; | |
| 225 | } |
src/http/lfs_routes.ts deleted −179
| @@ -1,179 +0,0 @@ | ||
| 1 | /** | |
| 2 | * Git LFS over HTTP (#4493): `/<owner>/<name>.git/info/lfs/…`, where `git lfs` looks for it. The | |
| 3 | * batch API, the forge's own object door (for a store that cannot presign) and file locks; the | |
| 4 | * logic is `blob/lfs.ts`. Reading takes whoever may read the repository, writing whoever may | |
| 5 | * write it with a token that may (as a push does); a caller who may not is answered as git does | |
| 6 | * (a challenge for no one, a 404 that hides the repository for someone). The same-origin gate | |
| 7 | * covers every POST and PUT before they get here. | |
| 8 | */ | |
| 9 | ||
| 10 | import { answerObject, isLfsOid, lfsKey, LFS_TYPE, MAX_OBJECT, lockPath, pageLocks, readBatch, readLocks, releaseLock, storeObject, takeLock } from "../blob/lfs.ts"; | |
| 11 | import { largeStore } from "../blob/large.ts"; | |
| 12 | import { canRead, canWrite, getRepo, type Repo } from "../core/repos.ts"; | |
| 13 | import { scopeAllows } from "../core/tokens.ts"; | |
| 14 | import { repoDir } from "../git/repos.ts"; | |
| 15 | import { isPacksMirror } from "../packs/owner.ts"; | |
| 16 | import type { Ctx, Handler } from "./context.ts"; | |
| 17 | import { publicUrl } from "./context.ts"; | |
| 18 | import { BODY_CAPS, closeAfter } from "./limits.ts"; | |
| 19 | import { boundedBody } from "./respond.ts"; | |
| 20 | import type { Router } from "./router.ts"; | |
| 21 | ||
| 22 | const answer = (status: number, value: unknown): Response => | |
| 23 | new Response(JSON.stringify(value), { | |
| 24 | status, | |
| 25 | headers: { "content-type": LFS_TYPE, "cache-control": "private, no-store" }, | |
| 26 | }); | |
| 27 | const refuse = (status: number, message: string): Response => answer(status, { message }); | |
| 28 | ||
| 29 | type Access = { repo: Repo; dir: string; write: boolean } | Response; | |
| 30 | ||
| 31 | /** | |
| 32 | * The repository, if this caller may read it (or write it, when `write`); else the answer to give. | |
| 33 | */ | |
| 34 | function access(ctx: Ctx, write: boolean): Access { | |
| 35 | const repo = getRepo(ctx.app.db, ctx.params.owner ?? "", ctx.params.name ?? ""); | |
| 36 | const hidden = (): Response => | |
| 37 | ctx.auth.user | |
| 38 | ? refuse(404, "not found") | |
| 39 | : new Response(JSON.stringify({ message: "credentials needed" }), { | |
| 40 | status: 401, | |
| 41 | headers: { "content-type": LFS_TYPE, "www-authenticate": 'Basic realm="forge"' }, | |
| 42 | }); | |
| 43 | if (!repo) return hidden(); | |
| 44 | if (write) { | |
| 45 | if (!ctx.auth.user) return hidden(); | |
| 46 | if (isPacksMirror(repo) || !canWrite(ctx.app.db, repo, ctx.auth.user) || !scopeAllows(ctx.auth.scope ?? "ro", "rw")) | |
| 47 | return refuse(404, "not found"); | |
| 48 | } else if (!canRead(ctx.app.db, repo, ctx.auth.user)) return hidden(); | |
| 49 | return { repo, dir: repoDir(ctx.app.reposRoot, repo.ownerName, repo.name), write }; | |
| 50 | } | |
| 51 | ||
| 52 | const asked = async (ctx: Ctx, max: number): Promise<Record<string, unknown> | Response> => { | |
| 53 | try { | |
| 54 | const got = await boundedBody(ctx.request, max); | |
| 55 | return got === "too_large" ? refuse(413, "request too large") : got; | |
| 56 | } catch { | |
| 57 | return refuse(422, "a JSON object is expected"); | |
| 58 | } | |
| 59 | }; | |
| 60 | ||
| 61 | /** POST …/info/lfs/objects/batch */ | |
| 62 | async function batch(ctx: Ctx): Promise<Response> { | |
| 63 | const raw = await asked(ctx, BODY_CAPS.lfsJson.bytes); | |
| 64 | if (raw instanceof Response) return raw; | |
| 65 | const input = readBatch(raw); | |
| 66 | if (typeof input === "string") return refuse(422, input); | |
| 67 | const got = access(ctx, input.operation === "upload"); | |
| 68 | if (got instanceof Response) return got; | |
| 69 | const { repo } = got; | |
| 70 | const base = publicUrl(ctx.request, ctx.app.config.url).origin; | |
| 71 | const own = (oid: string): string => `${base}/${encodeURIComponent(repo.ownerName)}/${encodeURIComponent(repo.name)}.git/info/lfs/objects/${oid}`; | |
| 72 | const store = largeStore(ctx.app.config.dataDir); | |
| 73 | const objects = await Promise.all( | |
| 74 | input.objects.map((object) => answerObject({ store, owner: repo.ownerName, name: repo.name, operation: input.operation, object, own })), | |
| 75 | ); | |
| 76 | return answer(200, { transfer: "basic", objects, hash_algo: "sha256" }); | |
| 77 | } | |
| 78 | ||
| 79 | /** GET …/info/lfs/objects/:oid: the bytes, for a store with no presigned addresses. */ | |
| 80 | async function download(ctx: Ctx): Promise<Response> { | |
| 81 | const got = access(ctx, false); | |
| 82 | if (got instanceof Response) return got; | |
| 83 | const oid = ctx.params.oid ?? ""; | |
| 84 | if (!isLfsOid(oid)) return refuse(404, "not found"); | |
| 85 | const store = largeStore(ctx.app.config.dataDir); | |
| 86 | const key = lfsKey(got.repo.ownerName, got.repo.name, oid); | |
| 87 | const size = await store.size(key); | |
| 88 | const stream = size === undefined ? undefined : await store.getStream(key); | |
| 89 | if (size === undefined || stream === undefined) return refuse(404, "object not found"); | |
| 90 | return new Response(stream, { headers: { "content-type": "application/octet-stream", "content-length": String(size), "cache-control": "private, no-store" } }); | |
| 91 | } | |
| 92 | ||
| 93 | /** PUT …/info/lfs/objects/:oid: streamed to the store, kept only if its sha256 is the oid. */ | |
| 94 | async function upload(ctx: Ctx): Promise<Response> { | |
| 95 | const got = access(ctx, true); | |
| 96 | if (got instanceof Response) return got; | |
| 97 | const oid = ctx.params.oid ?? ""; | |
| 98 | if (!isLfsOid(oid)) return refuse(422, "an object id is a lowercase sha256"); | |
| 99 | const declared = Number(ctx.request.headers.get("content-length") ?? NaN); | |
| 100 | if (!Number.isSafeInteger(declared) || declared < 0) return refuse(411, "a content-length is needed"); | |
| 101 | if (declared > MAX_OBJECT) { | |
| 102 | closeAfter(ctx.request); | |
| 103 | return refuse(413, `at most ${MAX_OBJECT} bytes through this forge`); | |
| 104 | } | |
| 105 | const stored = await storeObject({ | |
| 106 | store: largeStore(ctx.app.config.dataDir), | |
| 107 | owner: got.repo.ownerName, | |
| 108 | name: got.repo.name, | |
| 109 | oid, | |
| 110 | declared, | |
| 111 | source: ctx.request.body ?? new Blob([]).stream(), | |
| 112 | }); | |
| 113 | if (stored === "mismatch") return refuse(422, "the bytes are not the object named"); | |
| 114 | if (stored === "failed") return refuse(400, "the upload did not finish"); | |
| 115 | if (stored === "too_large") return refuse(413, `at most ${MAX_OBJECT} bytes through this forge`); | |
| 116 | return new Response(null, { status: 200, headers: { "cache-control": "no-store" } }); | |
| 117 | } | |
| 118 | ||
| 119 | /** POST …/info/lfs/locks */ | |
| 120 | async function lockCreate(ctx: Ctx): Promise<Response> { | |
| 121 | const got = access(ctx, true); | |
| 122 | if (got instanceof Response) return got; | |
| 123 | const raw = await asked(ctx, BODY_CAPS.lfsJson.bytes); | |
| 124 | if (raw instanceof Response) return raw; | |
| 125 | const path = lockPath(raw["path"]); | |
| 126 | if (path === undefined) return refuse(422, "path must be a relative path of at most 1024 characters"); | |
| 127 | const user = ctx.auth.user!; | |
| 128 | const took = takeLock(got.dir, path, { id: user.id, name: user.username }); | |
| 129 | if (took.ok) return answer(201, { lock: took.lock }); | |
| 130 | if (took.why === "held") return answer(409, { lock: took.lock, message: "already created lock" }); | |
| 131 | return refuse(422, "too many locks in this repository"); | |
| 132 | } | |
| 133 | ||
| 134 | /** GET …/info/lfs/locks?path=&id=&cursor=&limit= */ | |
| 135 | function lockList(ctx: Ctx): Response { | |
| 136 | const got = access(ctx, false); | |
| 137 | if (got instanceof Response) return got; | |
| 138 | const q = ctx.url.searchParams; | |
| 139 | const path = q.get("path"); | |
| 140 | const id = q.get("id"); | |
| 141 | const all = readLocks(got.dir).filter((l) => (path === null || l.path === path) && (id === null || l.id === id)); | |
| 142 | return answer(200, pageLocks(all, q.get("cursor"), q.get("limit"))); | |
| 143 | } | |
| 144 | ||
| 145 | /** POST …/info/lfs/locks/verify: the locks split into mine and others', for a push to check. */ | |
| 146 | async function lockVerify(ctx: Ctx): Promise<Response> { | |
| 147 | const got = access(ctx, true); | |
| 148 | if (got instanceof Response) return got; | |
| 149 | const raw = await asked(ctx, BODY_CAPS.lfsJson.bytes); | |
| 150 | if (raw instanceof Response) return raw; | |
| 151 | const mine = ctx.auth.user!.id; | |
| 152 | const page = pageLocks(readLocks(got.dir), raw["cursor"], raw["limit"]); | |
| 153 | return answer(200, { | |
| 154 | ours: page.locks.filter((l) => l.owner.id === mine), | |
| 155 | theirs: page.locks.filter((l) => l.owner.id !== mine), | |
| 156 | ...(page.next_cursor === undefined ? {} : { next_cursor: page.next_cursor }), | |
| 157 | }); | |
| 158 | } | |
| 159 | ||
| 160 | /** POST …/info/lfs/locks/:id/unlock; `force` releases another's (a writer may). */ | |
| 161 | async function lockRelease(ctx: Ctx): Promise<Response> { | |
| 162 | const got = access(ctx, true); | |
| 163 | if (got instanceof Response) return got; | |
| 164 | const raw = await asked(ctx, BODY_CAPS.lfsJson.bytes); | |
| 165 | if (raw instanceof Response) return raw; | |
| 166 | const released = releaseLock(got.dir, ctx.params.id ?? "", ctx.auth.user!, raw["force"] === true); | |
| 167 | if (released.ok) return answer(200, { lock: released.lock }); | |
| 168 | return released.why === "missing" ? refuse(404, "no such lock") : refuse(403, "the lock is another's; force to release it"); | |
| 169 | } | |
| 170 | ||
| 171 | export function lfsRoutes(router: Router<Handler>): void { | |
| 172 | router.add("POST", "/:owner/:name.git/info/lfs/objects/batch", batch); | |
| 173 | router.add("GET", "/:owner/:name.git/info/lfs/objects/:oid", download); | |
| 174 | router.add("PUT", "/:owner/:name.git/info/lfs/objects/:oid", upload); | |
| 175 | router.add("POST", "/:owner/:name.git/info/lfs/locks", lockCreate); | |
| 176 | router.add("GET", "/:owner/:name.git/info/lfs/locks", lockList); | |
| 177 | router.add("POST", "/:owner/:name.git/info/lfs/locks/verify", lockVerify); | |
| 178 | router.add("POST", "/:owner/:name.git/info/lfs/locks/:id/unlock", lockRelease); | |
| 179 | } |
src/http/server.ts +1 −3
| @@ -67,7 +67,6 @@ import { cspReportSubmit } from "./csp_report.ts"; | ||
| 67 | 67 | import { scriptErrorSubmit } from "./script_errors.ts"; |
| 68 | 68 | import { stripeHook } from "./stripe_hook.ts"; |
| 69 | 69 | import { settingsRoutes } from "./settings_routes.ts"; |
| 70 | import { lfsRoutes } from "./lfs_routes.ts"; | |
| 71 | 70 | import { pluginRoutes } from "./plugin_routes.ts"; |
| 72 | 71 | import { atomRoutes } from "./atom_routes.ts"; |
| 73 | 72 | import { pinnedRoutes } from "./pinned_routes.ts"; |
| @@ -1413,8 +1412,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1413 | 1412 | browseContributeSubmit, |
| 1414 | 1413 | ); |
| 1415 | 1414 | |
| 1416 | // git smart HTTP, and Git LFS beside it (`lfs_routes.ts`) | |
| 1417 | lfsRoutes(router); | |
| 1415 | // git smart HTTP | |
| 1418 | 1416 | router.add("GET", "/:owner/:name.git/info/refs", (ctx) => { |
| 1419 | 1417 | const service = ctx.url.searchParams.get("service"); |
| 1420 | 1418 | if (!isGitService(service)) |
src/kernel/body_caps.ts −4
| @@ -26,10 +26,6 @@ export const BODY_CAPS = { | ||
| 26 | 26 | bytes: 16 * MIB, |
| 27 | 27 | reason: "a git fetch's negotiation (wants and haves), decompressed: a huge history's haves fit", |
| 28 | 28 | }, |
| 29 | lfsJson: { | |
| 30 | bytes: 256 * KIB, | |
| 31 | reason: "a Git LFS batch (at most 100 objects, each a sha256 and a size) or a lock call: a few hundred bytes to some tens of KiB", | |
| 32 | }, | |
| 33 | 29 | gzip: { |
| 34 | 30 | bytes: 1 * MIB, |
| 35 | 31 | reason: "that negotiation as sent, when the client compressed it: a sixteenth of what it may grow to", |
src/tui/screens/lfslocks.ts deleted −79
| @@ -1,79 +0,0 @@ | ||
| 1 | /** | |
| 2 | * A repository's Git LFS file locks in the terminal (#4493): the locks `git lfs lock` took | |
| 3 | * (`blob/lfs.ts`, `readLocks`), who holds each and since when. Whoever may read the repository | |
| 4 | * sees them; a writer presses `u` to release the one under the cursor, after a confirm, whoever | |
| 5 | * holds it (the same as `git lfs unlock --force`). | |
| 6 | */ | |
| 7 | import { readLocks, releaseLock, type Lock } from "../../blob/lfs.ts"; | |
| 8 | import { canRead, canWrite, type Repo } from "../../core/repos.ts"; | |
| 9 | import { repoDir } from "../../git/repos.ts"; | |
| 10 | import { binding } from "../app/keys.ts"; | |
| 11 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 12 | import type { Command } from "../app/palette.ts"; | |
| 13 | import type { Session } from "../session.ts"; | |
| 14 | import { ListState, confirmScreen, drawList, later, type ListRow } from "./common.ts"; | |
| 15 | ||
| 16 | export const lockRow = (l: Lock): ListRow => ({ | |
| 17 | title: l.path, | |
| 18 | meta: `${l.owner.name} · ${l.locked_at.slice(0, 16).replace("T", " ")}`, | |
| 19 | }); | |
| 20 | ||
| 21 | /** The locks someone who may read the repository sees, else none. */ | |
| 22 | export function lockRows(f: Session, repo: Repo): Lock[] { | |
| 23 | return canRead(f.app.db, repo, f.user) ? readLocks(repoDir(f.app.reposRoot, repo.ownerName, repo.name)) : []; | |
| 24 | } | |
| 25 | ||
| 26 | export function lfsLocksScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | |
| 27 | const state = new ListState(); | |
| 28 | let locks = lockRows(f, repo); | |
| 29 | const screen: Screen = { | |
| 30 | title: `${repo.ownerName}/${repo.name} — LFS locks`, | |
| 31 | keys: [binding(["j", "k"], "move cursor"), binding(["u"], "release"), binding(["g"], "read again")], | |
| 32 | render(area, s) { | |
| 33 | drawList(s, area, ctx.theme.c, state, locks.map(lockRow)); | |
| 34 | }, | |
| 35 | key(e) { | |
| 36 | if (e.key === "g") { | |
| 37 | locks = lockRows(f, repo); | |
| 38 | return true; | |
| 39 | } | |
| 40 | if (e.key !== "u") return state.key(e, locks.length); | |
| 41 | const at = locks[state.index]; | |
| 42 | if (at === undefined) return true; | |
| 43 | if (!canWrite(f.app.db, repo, f.user)) { | |
| 44 | ctx.toast("Only someone who may write can release a lock.", "danger"); | |
| 45 | return true; | |
| 46 | } | |
| 47 | void later(ctx, () => | |
| 48 | confirmScreen(ctx, screen, { | |
| 49 | title: "Release lock", | |
| 50 | body: [`${at.path} is held by ${at.owner.name}. Release it now?`], | |
| 51 | actions: [{ label: "Cancel", variant: "ghost" }, { label: "Release" }], | |
| 52 | selected: 0, | |
| 53 | onChoose: (i) => { | |
| 54 | if (i !== 1) return; | |
| 55 | const done = releaseLock(repoDir(f.app.reposRoot, repo.ownerName, repo.name), at.id, { id: f.user?.id ?? "" }, true); | |
| 56 | locks = lockRows(f, repo); | |
| 57 | ctx.toast(done.ok ? "Lock released." : "No such lock.", done.ok ? undefined : "danger"); | |
| 58 | ctx.invalidate(); | |
| 59 | }, | |
| 60 | }), | |
| 61 | ); | |
| 62 | return true; | |
| 63 | }, | |
| 64 | }; | |
| 65 | return screen; | |
| 66 | } | |
| 67 | ||
| 68 | /** The palette's command while a repository is open. */ | |
| 69 | export function lfsLocksCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] { | |
| 70 | if (repo === undefined) return []; | |
| 71 | return [ | |
| 72 | { | |
| 73 | id: "lfs-locks", | |
| 74 | title: `${repo.ownerName}/${repo.name} — LFS locks`, | |
| 75 | hint: "files locked by git lfs, and who holds them", | |
| 76 | run: () => ctx.push(lfsLocksScreen(f, ctx, repo)), | |
| 77 | }, | |
| 78 | ]; | |
| 79 | } |
src/tui/screens/workspace.ts −2
| @@ -227,7 +227,6 @@ import { buildCacheCommands } from "./buildcache.ts"; | ||
| 227 | 227 | import { schedulesCommands } from "./schedules.ts"; |
| 228 | 228 | import { appReleasesCommands } from "./appreleases.ts"; |
| 229 | 229 | import { largeFilesCommands } from "./largefiles.ts"; |
| 230 | import { lfsLocksCommands } from "./lfslocks.ts"; | |
| 231 | 230 | import { migrationCommands } from "./migration.ts"; |
| 232 | 231 | import { dropCommands } from "./drop.ts"; |
| 233 | 232 | import { recheckWindowCommands } from "./recheckwindow.ts"; |
| @@ -2451,7 +2450,6 @@ export function workspaceScreen( | ||
| 2451 | 2450 | ...schedulesCommands(f, ctx, repo), |
| 2452 | 2451 | ...appReleasesCommands(f, ctx, repo), |
| 2453 | 2452 | ...largeFilesCommands(f, ctx, repo), |
| 2454 | ...lfsLocksCommands(f, ctx, repo), | |
| 2455 | 2453 | ...dropCommands(f, ctx, repo), |
| 2456 | 2454 | ...migrationCommands(f, ctx, repo), |
| 2457 | 2455 | ...recheckWindowCommands(f, ctx, repo, () => screen), |
test/lfs-locks-tui.test.ts deleted −101
| @@ -1,101 +0,0 @@ | ||
| 1 | /** | |
| 2 | * The LFS locks screen (#4493): whoever may read a repository sees its locks, a person who may not | |
| 3 | * write is refused the release key, and a writer's release happens only after a confirm. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { readLocks, takeLock } from "../src/blob/lfs.ts"; | |
| 11 | import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | |
| 12 | import { createRepo, type Repo } from "../src/core/repos.ts"; | |
| 13 | import { createUser, type User } from "../src/core/users.ts"; | |
| 14 | import { repoDir } from "../src/git/repos.ts"; | |
| 15 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 16 | import { lfsLocksScreen } from "../src/tui/screens/lfslocks.ts"; | |
| 17 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | import { settleApp } from "./helpers/tui.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | let dir: string; | |
| 24 | let app: App; | |
| 25 | let repo: Repo; | |
| 26 | let writer: User; | |
| 27 | let reader: User; | |
| 28 | let guest: User; | |
| 29 | let locks: string; | |
| 30 | ||
| 31 | const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => { | |
| 32 | if (!r.ok) throw new Error(String(r.error)); | |
| 33 | return r.value; | |
| 34 | }; | |
| 35 | ||
| 36 | beforeAll(async () => { | |
| 37 | dir = await mkdtemp(join(tmpdir(), "forge-lfs-tui-")); | |
| 38 | app = createApp({ dataDir: dir, port: 0 }); | |
| 39 | const make = async (username: string, adminIfFirst = false) => | |
| 40 | ok(await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst })); | |
| 41 | await make("founding", true); | |
| 42 | const founder = await make("founder"); | |
| 43 | writer = await make("writer"); | |
| 44 | reader = await make("reader"); | |
| 45 | guest = await make("guest"); | |
| 46 | const org = ok(createOrg(app.db, "acme", founder.id)); | |
| 47 | repo = ok(await createRepo(app.db, app.reposRoot, { ownerId: org.id, name: "cad", visibility: "private" })); | |
| 48 | addTeamMember(app.db, ok(createTeam(app.db, org.id, "Writers", "write")), writer.id); | |
| 49 | addTeamMember(app.db, ok(createTeam(app.db, org.id, "Readers", "read")), reader.id); | |
| 50 | locks = repoDir(app.reposRoot, "acme", "cad"); | |
| 51 | takeLock(locks, "part.step", { id: founder.id, name: "founder" }); | |
| 52 | }); | |
| 53 | afterAll(async () => { | |
| 54 | app.close(); | |
| 55 | await rm(dir, { recursive: true, force: true }); | |
| 56 | }); | |
| 57 | ||
| 58 | const key = (k: string) => ({ type: "key" as const, key: k, ctrl: false, alt: false, shift: false }); | |
| 59 | async function open(user: User) { | |
| 60 | const { app: tui, session } = createForgeApp( | |
| 61 | app, | |
| 62 | { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, | |
| 63 | { terminal: headlessTerminal(120, 30), exitHooks: false }, | |
| 64 | ); | |
| 65 | tui.start(); | |
| 66 | tui.ctx.push(lfsLocksScreen(session, tui.ctx, repo)); | |
| 67 | await settleApp(tui); | |
| 68 | return tui; | |
| 69 | } | |
| 70 | ||
| 71 | test("a reader of a private repository sees its locks; a guest sees none", async () => { | |
| 72 | const seen = await open(reader); | |
| 73 | expect(seen.screen.toText()).toContain("part.step"); | |
| 74 | const none = await open(guest); | |
| 75 | expect(none.screen.toText()).not.toContain("part.step"); | |
| 76 | }); | |
| 77 | ||
| 78 | test("u is refused to someone who may not write, and nothing is released", async () => { | |
| 79 | const tui = await open(reader); | |
| 80 | tui.dispatch(key("u")); | |
| 81 | await settleApp(tui); | |
| 82 | expect(tui.screen.toText()).toContain("Only someone who may write can release a lock."); | |
| 83 | expect(readLocks(locks).length).toBe(1); | |
| 84 | }); | |
| 85 | ||
| 86 | test("a writer's u asks first: cancel keeps the lock, release takes it", async () => { | |
| 87 | const tui = await open(writer); | |
| 88 | tui.dispatch(key("u")); | |
| 89 | await settleApp(tui); | |
| 90 | expect(tui.screen.toText()).toContain("Release it now?"); | |
| 91 | tui.dispatch(key("esc")); | |
| 92 | await settleApp(tui); | |
| 93 | expect(readLocks(locks).length).toBe(1); | |
| 94 | tui.dispatch(key("u")); | |
| 95 | await settleApp(tui); | |
| 96 | tui.dispatch(key("right")); | |
| 97 | tui.dispatch(key("enter")); | |
| 98 | await settleApp(tui); | |
| 99 | expect(readLocks(locks).length).toBe(0); | |
| 100 | expect(tui.screen.toText()).toContain("Lock released."); | |
| 101 | }); |
test/lfs.test.ts deleted −285
| @@ -1,285 +0,0 @@ | ||
| 1 | /** | |
| 2 | * Git LFS on the BlobStore (#4493): the batch API answers an address per object (the forge's own | |
| 3 | * for a directory store), an upload is kept only if its sha256 is the oid, a reader may download | |
| 4 | * and not upload, and locks are taken, refused to the second taker, verified and released. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { createHash } from "node:crypto"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { mkdirSync, writeFileSync } from "node:fs"; | |
| 14 | import { largeStore, retractLarge } from "../src/blob/large.ts"; | |
| 15 | import { lfsKey, lfsPrefix, lockPath, MAX_LOCKS, MAX_OBJECT, pageLocks, readBatch, storeObject, takeLock } from "../src/blob/lfs.ts"; | |
| 16 | import { createRepo as initRepo } from "../src/core/repos.ts"; | |
| 17 | import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | |
| 18 | import { createToken } from "../src/core/tokens.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | const sha = (s: string): string => createHash("sha256").update(s).digest("hex"); | |
| 27 | const TYPE = "application/vnd.git-lfs+json"; | |
| 28 | ||
| 29 | describe("what is read", () => { | |
| 30 | test("a batch is a known operation and at most 100 well-formed objects", () => { | |
| 31 | const ok = { operation: "upload", objects: [{ oid: sha("a"), size: 1 }] }; | |
| 32 | expect(readBatch(ok)).toEqual({ operation: "upload", objects: [{ oid: sha("a"), size: 1 }] }); | |
| 33 | for (const bad of [ | |
| 34 | { ...ok, operation: "delete" }, | |
| 35 | { ...ok, transfers: ["tus"] }, | |
| 36 | { ...ok, objects: [] }, | |
| 37 | { ...ok, objects: [{ oid: "ABC", size: 1 }] }, | |
| 38 | { ...ok, objects: [{ oid: sha("a"), size: -1 }] }, | |
| 39 | { ...ok, objects: [{ oid: sha("a"), size: 1.5 }] }, | |
| 40 | { ...ok, objects: Array.from({ length: 101 }, () => ({ oid: sha("a"), size: 1 })) }, | |
| 41 | ]) | |
| 42 | expect(typeof readBatch(bad)).toBe("string"); | |
| 43 | }); | |
| 44 | test("a lock path is relative and clean", () => { | |
| 45 | expect(lockPath("cad/part.step")).toBe("cad/part.step"); | |
| 46 | for (const bad of ["", "/abs", "a/../b", "a//b", "a\\b", "a\0b", "x".repeat(1025), 5]) expect(lockPath(bad)).toBeUndefined(); | |
| 47 | }); | |
| 48 | test("locks page by cursor", () => { | |
| 49 | const l = (n: number) => ({ id: `${n}`, path: `p${n}`, locked_at: "", owner: { id: "u", name: "u" } }); | |
| 50 | const p = pageLocks([l(1), l(2), l(3)], undefined, 2); | |
| 51 | expect(p.locks.length).toBe(2); | |
| 52 | expect(pageLocks([l(1), l(2), l(3)], p.next_cursor, 2)).toEqual({ locks: [l(3)] }); | |
| 53 | }); | |
| 54 | }); | |
| 55 | ||
| 56 | describe("through the real router", () => { | |
| 57 | let dataDir: string; | |
| 58 | let app: App; | |
| 59 | let servers: Servers; | |
| 60 | let ada: User; | |
| 61 | let bob: User; | |
| 62 | let adaAuth: Record<string, string>; | |
| 63 | let bobAuth: Record<string, string>; | |
| 64 | const base = () => `${servers.url}/ada/pub.git/info/lfs`; | |
| 65 | const body = "hello lfs"; | |
| 66 | const oid = sha(body); | |
| 67 | ||
| 68 | const basic = (u: User, scope: "ro" | "rw") => | |
| 69 | ({ authorization: `Basic ${btoa(`${u.username}:${createToken(app.db, u.id, "t", scope).token}`)}` }); | |
| 70 | const json = (auth: Record<string, string>, value: unknown) => ({ | |
| 71 | method: "POST", | |
| 72 | headers: { ...auth, "content-type": TYPE }, | |
| 73 | body: JSON.stringify(value), | |
| 74 | }); | |
| 75 | ||
| 76 | beforeAll(async () => { | |
| 77 | dataDir = await mkdtemp(join(tmpdir(), "forge-lfs-")); | |
| 78 | app = createApp({ dataDir, port: 0, host: "forge.example", url: "https://forge.example" }); | |
| 79 | servers = await serve(app); | |
| 80 | const a = await seedAdmin(app, { username: "ada", email: "[email protected]" }); | |
| 81 | if (!a.ok) throw new Error(a.error); | |
| 82 | ada = a.value; | |
| 83 | const b = await createUser(app.db, { username: "bob", email: "[email protected]", password: "correct horse battery", origin: "seed", trusted: true }); | |
| 84 | if (!b.ok) throw new Error(b.error); | |
| 85 | bob = b.value; | |
| 86 | const r = await createRepo(app, ada, { name: "pub", visibility: "public" }); | |
| 87 | if (!r.ok) throw new Error(String(r.error)); | |
| 88 | adaAuth = basic(ada, "rw"); | |
| 89 | bobAuth = basic(bob, "rw"); | |
| 90 | }); | |
| 91 | afterAll(async () => { | |
| 92 | servers.stop(); | |
| 93 | app.close(); | |
| 94 | await rm(dataDir, { recursive: true, force: true }); | |
| 95 | }); | |
| 96 | ||
| 97 | test("an upload is offered, sent, verified, then a download serves the same bytes", async () => { | |
| 98 | const asked = await fetch(`${base()}/objects/batch`, json(adaAuth, { operation: "upload", objects: [{ oid, size: body.length }] })); | |
| 99 | expect(asked.status).toBe(200); | |
| 100 | expect(asked.headers.get("content-type")).toBe(TYPE); | |
| 101 | const { objects } = (await asked.json()) as { objects: { actions?: { upload?: { href: string } } }[] }; | |
| 102 | const href = objects[0]!.actions!.upload!.href; | |
| 103 | expect(href).toBe(`https://forge.example/ada/pub.git/info/lfs/objects/${oid}`); | |
| 104 | ||
| 105 | // wrong bytes under the oid are refused and not kept | |
| 106 | const bad = await fetch(`${base()}/objects/${oid}`, { method: "PUT", headers: adaAuth, body: "other bytes" }); | |
| 107 | expect(bad.status).toBe(422); | |
| 108 | const none = await fetch(`${base()}/objects/batch`, json(adaAuth, { operation: "download", objects: [{ oid, size: body.length }] })); | |
| 109 | expect(((await none.json()) as { objects: { error?: { code: number } }[] }).objects[0]!.error!.code).toBe(404); | |
| 110 | ||
| 111 | const put = await fetch(`${base()}/objects/${oid}`, { method: "PUT", headers: adaAuth, body }); | |
| 112 | expect(put.status).toBe(200); | |
| 113 | ||
| 114 | // already held: an upload batch has nothing to do | |
| 115 | const again = await fetch(`${base()}/objects/batch`, json(adaAuth, { operation: "upload", objects: [{ oid, size: body.length }] })); | |
| 116 | expect(((await again.json()) as { objects: { actions?: unknown }[] }).objects[0]!.actions).toBeUndefined(); | |
| 117 | ||
| 118 | // a stranger may read a public repository's object, not write | |
| 119 | const dl = await fetch(`${base()}/objects/batch`, json({}, { operation: "download", objects: [{ oid, size: body.length }] })); | |
| 120 | expect(dl.status).toBe(200); | |
| 121 | expect(await (await fetch(`${base()}/objects/${oid}`)).text()).toBe(body); | |
| 122 | const up = await fetch(`${base()}/objects/batch`, json({}, { operation: "upload", objects: [{ oid, size: body.length }] })); | |
| 123 | expect(up.status).toBe(401); | |
| 124 | expect(up.headers.get("www-authenticate")).toContain("Basic"); | |
| 125 | const bobUp = await fetch(`${base()}/objects/${oid}`, { method: "PUT", headers: bobAuth, body }); | |
| 126 | expect(bobUp.status).toBe(404); | |
| 127 | const roUp = await fetch(`${base()}/objects/batch`, json(basic(ada, "ro"), { operation: "upload", objects: [{ oid, size: 1 }] })); | |
| 128 | expect(roUp.status).toBe(404); | |
| 129 | }); | |
| 130 | ||
| 131 | test("a bad batch is 422, an unknown repository 404 for someone signed in", async () => { | |
| 132 | expect((await fetch(`${base()}/objects/batch`, json(adaAuth, { operation: "x" }))).status).toBe(422); | |
| 133 | expect((await fetch(`${servers.url}/ada/nope.git/info/lfs/objects/batch`, json(adaAuth, { operation: "download", objects: [{ oid, size: 1 }] }))).status).toBe(404); | |
| 134 | expect((await fetch(`${base()}/objects/${"z".repeat(64)}`)).status).toBe(404); | |
| 135 | }); | |
| 136 | ||
| 137 | test("a private repository's objects are hidden from others", async () => { | |
| 138 | const r = await createRepo(app, ada, { name: "priv", visibility: "private" }); | |
| 139 | if (!r.ok) throw new Error(String(r.error)); | |
| 140 | const url = `${servers.url}/ada/priv.git/info/lfs/objects/batch`; | |
| 141 | const ask = { operation: "download", objects: [{ oid, size: 1 }] }; | |
| 142 | expect((await fetch(url, json(bobAuth, ask))).status).toBe(404); | |
| 143 | expect((await fetch(url, json({}, ask))).status).toBe(401); | |
| 144 | }); | |
| 145 | ||
| 146 | test("locks: taken, refused to a second taker, listed, verified, released", async () => { | |
| 147 | const made = await fetch(`${base()}/locks`, json(adaAuth, { path: "cad/part.step" })); | |
| 148 | expect(made.status).toBe(201); | |
| 149 | const { lock } = (await made.json()) as { lock: { id: string; path: string; owner: { name: string } } }; | |
| 150 | expect(lock.path).toBe("cad/part.step"); | |
| 151 | expect(lock.owner.name).toBe("ada"); | |
| 152 | ||
| 153 | expect((await fetch(`${base()}/locks`, json(adaAuth, { path: "../x" }))).status).toBe(422); | |
| 154 | const bobs = await fetch(`${base()}/locks`, json(bobAuth, { path: "cad/part.step" })); | |
| 155 | expect(bobs.status).toBe(404); // bob cannot write ada's repository | |
| 156 | ||
| 157 | const list = await fetch(`${base()}/locks?path=cad/part.step`); | |
| 158 | expect(((await list.json()) as { locks: unknown[] }).locks.length).toBe(1); | |
| 159 | expect(((await (await fetch(`${base()}/locks?path=other`)).json()) as { locks: unknown[] }).locks.length).toBe(0); | |
| 160 | ||
| 161 | const verify = await fetch(`${base()}/locks/verify`, json(adaAuth, {})); | |
| 162 | const v = (await verify.json()) as { ours: unknown[]; theirs: unknown[] }; | |
| 163 | expect([v.ours.length, v.theirs.length]).toEqual([1, 0]); | |
| 164 | ||
| 165 | const again = await fetch(`${base()}/locks`, json(adaAuth, { path: "cad/part.step" })); | |
| 166 | expect(again.status).toBe(409); | |
| 167 | ||
| 168 | const gone = await fetch(`${base()}/locks/${lock.id}/unlock`, json(adaAuth, {})); | |
| 169 | expect(gone.status).toBe(200); | |
| 170 | expect(((await (await fetch(`${base()}/locks`)).json()) as { locks: unknown[] }).locks.length).toBe(0); | |
| 171 | expect((await fetch(`${base()}/locks/${lock.id}/unlock`, json(adaAuth, {}))).status).toBe(404); | |
| 172 | }); | |
| 173 | ||
| 174 | test("another writer's lock needs force", async () => { | |
| 175 | // a real collaborator: cy is on the Writers team of an organisation that owns the repository | |
| 176 | const org = createOrg(app.db, "acme", ada.id); | |
| 177 | if (!org.ok) throw new Error(String(org.error)); | |
| 178 | const repo = await initRepo(app.db, app.reposRoot, { ownerId: org.value.id, name: "site", visibility: "public" }); | |
| 179 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 180 | const second = await createUser(app.db, { username: "cy", email: "[email protected]", password: "correct horse battery", origin: "seed", trusted: true }); | |
| 181 | if (!second.ok) throw new Error(second.error); | |
| 182 | const team = createTeam(app.db, org.value.id, "Writers", "write"); | |
| 183 | if (!team.ok) throw new Error(String(team.error)); | |
| 184 | addTeamMember(app.db, team.value, second.value.id); | |
| 185 | const url = `${servers.url}/acme/site.git/info/lfs`; | |
| 186 | const cy = basic(second.value, "rw"); | |
| 187 | const made = await fetch(`${url}/locks`, json(adaAuth, { path: "a.step" })); | |
| 188 | const { lock } = (await made.json()) as { lock: { id: string } }; | |
| 189 | expect((await fetch(`${url}/locks/${lock.id}/unlock`, json(cy, {}))).status).toBe(403); | |
| 190 | const v = (await (await fetch(`${url}/locks/verify`, json(cy, {}))).json()) as { ours: unknown[]; theirs: unknown[] }; | |
| 191 | expect([v.ours.length, v.theirs.length]).toEqual([0, 1]); | |
| 192 | expect((await fetch(`${url}/locks/${lock.id}/unlock`, json(cy, { force: true }))).status).toBe(200); | |
| 193 | }); | |
| 194 | ||
| 195 | test("an anonymous caller is challenged before any body is read", async () => { | |
| 196 | // a body far over the cap: a reader would answer 413, an access check first answers 401 | |
| 197 | const big = JSON.stringify({ path: "x".repeat(300 * 1024) }); | |
| 198 | for (const path of ["/locks", "/locks/verify", "/locks/abc/unlock"]) { | |
| 199 | const r = await fetch(`${base()}${path}`, { method: "POST", headers: { "content-type": TYPE }, body: big }); | |
| 200 | expect([path, r.status]).toEqual([path, 401]); | |
| 201 | } | |
| 202 | }); | |
| 203 | ||
| 204 | test("a wrong upload under a stored oid leaves the good object intact", async () => { | |
| 205 | const good = "a good object"; | |
| 206 | const goodOid = sha(good); | |
| 207 | expect((await fetch(`${base()}/objects/${goodOid}`, { method: "PUT", headers: adaAuth, body: good })).status).toBe(200); | |
| 208 | // same length, wrong bytes, and a different length | |
| 209 | for (const wrong of ["a bad object!", "short"]) { | |
| 210 | const r = await fetch(`${base()}/objects/${goodOid}`, { method: "PUT", headers: adaAuth, body: wrong }); | |
| 211 | expect(r.status).toBe(wrong.length === good.length ? 200 : 422); | |
| 212 | expect(await (await fetch(`${base()}/objects/${goodOid}`)).text()).toBe(good); | |
| 213 | } | |
| 214 | // nothing is left staged beside it | |
| 215 | const keys = await largeStore(dataDir).list(lfsPrefix("ada", "pub")); | |
| 216 | expect(keys.filter((k) => k.includes("tmp-"))).toEqual([]); | |
| 217 | }); | |
| 218 | ||
| 219 | test("an object over the limit is refused by the batch and by the PUT, before any bytes", async () => { | |
| 220 | const huge = MAX_OBJECT + 1; | |
| 221 | const asked = await fetch(`${base()}/objects/batch`, json(adaAuth, { operation: "upload", objects: [{ oid: sha("huge"), size: huge }] })); | |
| 222 | const { objects } = (await asked.json()) as { objects: { error?: { code: number } }[] }; | |
| 223 | expect(objects[0]!.error!.code).toBe(413); | |
| 224 | // a content-length over the limit and no body: answered 413 without waiting for one | |
| 225 | const url = new URL(base()); | |
| 226 | const reply = await new Promise<string>((resolve) => { | |
| 227 | let text = ""; | |
| 228 | void Bun.connect({ | |
| 229 | hostname: url.hostname, | |
| 230 | port: Number(url.port), | |
| 231 | socket: { | |
| 232 | open(sock) { | |
| 233 | sock.write(`PUT /ada/pub.git/info/lfs/objects/${sha("huge")} HTTP/1.1\r\nhost: ${url.host}\r\nauthorization: ${adaAuth["authorization"]}\r\ncontent-length: ${huge}\r\n\r\n`); | |
| 234 | }, | |
| 235 | data(sock, d) { | |
| 236 | text += d.toString(); | |
| 237 | if (text.includes("\r\n\r\n")) { | |
| 238 | sock.end(); | |
| 239 | resolve(text); | |
| 240 | } | |
| 241 | }, | |
| 242 | close() { | |
| 243 | resolve(text); | |
| 244 | }, | |
| 245 | }, | |
| 246 | }); | |
| 247 | }); | |
| 248 | expect(reply.split("\r\n")[0]).toContain("413"); | |
| 249 | }); | |
| 250 | ||
| 251 | test("a stream longer than declared is cut at the declared length and keeps nothing", async () => { | |
| 252 | const store = largeStore(dataDir); | |
| 253 | const stream = (parts: string[]) => new ReadableStream<Uint8Array>({ start(c) { for (const p of parts) c.enqueue(new TextEncoder().encode(p)); c.close(); } }); | |
| 254 | const o = sha("abc"); | |
| 255 | const input = { store, owner: "ada", name: "pub", oid: o, declared: 3 }; | |
| 256 | expect(await storeObject({ ...input, source: stream(["abc", "defgh"]) })).toBe("mismatch"); | |
| 257 | expect(await store.size(lfsKey("ada", "pub", o))).toBeUndefined(); | |
| 258 | expect(await storeObject({ ...input, source: stream(["ab"]) })).toBe("mismatch"); // shorter | |
| 259 | expect(await storeObject({ ...input, source: stream(["abc"]) })).toBe("stored"); | |
| 260 | expect(await storeObject({ ...input, declared: MAX_OBJECT + 1, source: stream(["x"]) })).toBe("too_large"); | |
| 261 | }); | |
| 262 | ||
| 263 | test("retracting a repository's large blobs takes its LFS objects too", async () => { | |
| 264 | const store = largeStore(dataDir); | |
| 265 | const o = sha("to retract"); | |
| 266 | await store.put(lfsKey("ada", "gone", o), "to retract"); | |
| 267 | await store.put(lfsKey("ada", "kept", o), "to retract"); | |
| 268 | await retractLarge(app, { ownerName: "ada", name: "gone" }); | |
| 269 | expect(await store.size(lfsKey("ada", "gone", o))).toBeUndefined(); | |
| 270 | expect(await store.size(lfsKey("ada", "kept", o))).toBe(10); | |
| 271 | }); | |
| 272 | ||
| 273 | test("a repository holds at most MAX_LOCKS locks", () => { | |
| 274 | const dir = join(dataDir, "locks-full"); | |
| 275 | mkdirSync(dir, { recursive: true }); | |
| 276 | writeFileSync(join(dir, "forge-locks.json"), JSON.stringify(Array.from({ length: MAX_LOCKS }, (_, i) => ({ id: `${i}`, path: `p${i}`, locked_at: "t", owner: { id: "u", name: "u" } })))); | |
| 277 | expect(takeLock(dir, "one-more", { id: "u", name: "u" })).toEqual({ ok: false, why: "full" }); | |
| 278 | expect(takeLock(dir, "p0", { id: "u", name: "u" }).ok).toBe(false); // held, not full | |
| 279 | }); | |
| 280 | ||
| 281 | test("a cross-origin browser POST is refused before it acts", async () => { | |
| 282 | const r = await fetch(`${base()}/locks`, { method: "POST", headers: { origin: "https://evil.example", "content-type": TYPE, cookie: "forge_session=x" }, body: "{}" }); | |
| 283 | expect([401, 403]).toContain(r.status); | |
| 284 | }); | |
| 285 | }); |
test/no-polling.test.ts −1
| @@ -353,7 +353,6 @@ const NOT_WALKED: Record<string, string> = { | ||
| 353 | 353 | "/settings/origins/flows/:id/stream": ORIGIN, |
| 354 | 354 | "/settings/teams/:slug": "needs a team", |
| 355 | 355 | "/talk/:id": "needs a conversation of the signed-in person", |
| 356 | "/:owner/:name.git/info/lfs/objects/:oid": "an LFS object download: needs a stored object, and answers bytes", | |
| 357 | 356 | "/talk/:id/download": "needs a conversation of the signed-in person", |
| 358 | 357 | }; |
| 359 | 358 | /** The whole browse-an-origin family is one reason. */ |
test/openapi-covers-routes.test.ts +1 −10
| @@ -34,16 +34,7 @@ const JSON_EXTRA: readonly string[] = [ | ||
| 34 | 34 | ]; |
| 35 | 35 | |
| 36 | 36 | /** Answers a JSON type that is not an API: an image's miss. Never counted as JSON. */ |
| 37 | const NOT_JSON: readonly string[] = [ | |
| 38 | "GET /icons/{}.png", | |
| 39 | // Git LFS wire protocol (application/vnd.git-lfs+json), spoken by git-lfs like info/refs, not an | |
| 40 | // API. | |
| 41 | "POST /{}/{}.git/info/lfs/locks", | |
| 42 | "POST /{}/{}.git/info/lfs/locks/verify", | |
| 43 | "POST /{}/{}.git/info/lfs/locks/{}/unlock", | |
| 44 | "POST /{}/{}.git/info/lfs/objects/batch", | |
| 45 | "PUT /{}/{}.git/info/lfs/objects/{}", | |
| 46 | ]; | |
| 37 | const NOT_JSON: readonly string[] = ["GET /icons/{}.png"]; | |
| 47 | 38 | |
| 48 | 39 | /** The most routes `NOT_YET_DESCRIBED` may hold. Lower it with every deletion; never raise it. */ |
| 49 | 40 | const CEILING = 41; |
test/pages-budget.test.ts −1
| @@ -94,7 +94,6 @@ const FIXTURE: Record<string, string> = { | ||
| 94 | 94 | "/:owner/:name/pulls/:number.diff": "/alice/forge/pulls/2.diff", |
| 95 | 95 | "/:owner/:name/display": "/alice/forge/display", |
| 96 | 96 | "/api/v1/admin/machines/:machine/disks": "/api/v1/admin/machines/rack1/disks", |
| 97 | "/:owner/:name.git/info/lfs/objects/:oid": `/alice/forge.git/info/lfs/objects/${"0".repeat(64)}`, // an object nobody stored: the 404 is the common answer | |
| 98 | 97 | "/claim/start/:token": "/claim/start/claim_fixture", |
| 99 | 98 | "/templates/:owner/:name": "/templates/alice/forge", // marked a template in the setup below |
| 100 | 99 | "/og/template/:ref.svg": "/og/template/alice~forge.svg", |
new above
offline