diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ec98ee74f5..9fb61430c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -137,19 +137,8 @@ jobs: - 'scripts/deploy/durable-object-migrations.ts' - 'scripts/deploy/types.ts' - 'scripts/deploy/vapid-keys.ts' - # Self-host build tests import the celld generator, presign vars, SMTP settings and - # account SQL: these modules plus the scripts/selfhost modules they import. The - # transitive ones are listed by hand: ci-suite-selection.test.ts checks the direct - # imports but does not follow `./x.js` specifiers to `x.ts`. - - 'scripts/selfhost/account-sql.ts' - - 'scripts/selfhost/box-settings.ts' - - 'scripts/selfhost/celld-config.ts' - - 'scripts/selfhost/celld-project.ts' - - 'scripts/selfhost/mail-settings.ts' - - 'scripts/selfhost/observability-migrations.ts' - - 'scripts/selfhost/reverse-tunnel-migrations.ts' - - 'scripts/selfhost/secret-files.ts' - - 'scripts/selfhost/selfhost-migrations.ts' + # API build/conformance tests import the celld generator and its helpers. + - 'scripts/selfhost/**' # selfhost-inbound-email.test.ts builds this receiver (Self-host Email job only). - 'deploy/selfhost/sam-mx/**' # The self-host access-log redaction guard scans the API routes against this filter. @@ -589,6 +578,11 @@ jobs: --coverage.thresholds.statements=0 --coverage.thresholds.branches=0 --coverage.thresholds.functions=0 --coverage.thresholds.lines=0 + # One shard owns the real-git suite; the dedicated config launches its own runtime. + - name: Hosted git conformance and celld bundle + if: matrix.shard == 1 + run: pnpm --filter @simple-agent-manager/api test:hosted-git + - name: Upload API blob report uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: diff --git a/apps/api/package.json b/apps/api/package.json index 062be113ae..fabf53589d 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -18,7 +18,8 @@ "openapi:generate": "tsx scripts/generate-openapi.ts", "openapi:check": "tsx scripts/generate-openapi.ts --check", "deploy": "wrangler deploy", - "deploy:staging": "wrangler deploy --env staging" + "deploy:staging": "wrangler deploy --env staging", + "test:hosted-git": "vitest run --config vitest.hosted-git.config.ts" }, "dependencies": { "@ai-sdk/openai-compatible": "2.0.87", @@ -51,6 +52,7 @@ "drizzle-orm": "catalog:", "hono": "4.13.4", "jose": "catalog:", + "pako": "^2.1.0", "tsx": "catalog:", "valibot": "catalog:", "workers-ai-provider": "4.0.1", @@ -62,6 +64,7 @@ "@modelcontextprotocol/client": "2.4.0", "@types/better-sqlite3": "^7.6.13", "@types/diff": "^8.0.0", + "@types/pako": "^2.0.3", "@typescript-eslint/eslint-plugin": "catalog:", "@typescript-eslint/parser": "catalog:", "@vitest/coverage-v8": "catalog:", diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 760e30a8f0..650b30e954 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -191,7 +191,7 @@ import { agentEmailConfig } from './services/agent-email/setup-state'; import { isAgentSignInEnabled } from './services/agent-sign-in/config'; import { isInstantRuntimeAvailable } from './services/vm-agent-container'; -const app = new Hono<{ Bindings: Env }>(); +export const app = new Hono<{ Bindings: Env }>(); // Global error handler — catches errors from all routes including subrouters. // Must use app.onError() instead of middleware try/catch because Hono's diff --git a/apps/api/src/lib/git-ref-name.ts b/apps/api/src/lib/git-ref-name.ts new file mode 100644 index 0000000000..2a2f844c5e --- /dev/null +++ b/apps/api/src/lib/git-ref-name.ts @@ -0,0 +1,32 @@ +/** + * Git ref-name admission shared by hosted-git push validation (`validatePush` in the vendored + * dgit protocol) and project creation, which names the branch the seed push writes. One + * predicate, so a branch SAM accepts can always be pushed. + * + * Rules follow `git check-ref-format` (https://git-scm.com/docs/git-check-ref-format) plus SAM's + * conservative bounds: no whitespace, control, quote or HTML characters and at most 255 + * characters in total. This module has no dependencies, so the Worker graph may import it. + */ +// eslint-disable-next-line no-control-regex -- git check-ref-format rejects ASCII control bytes +const BAD_REF_CHARS = /[\s~^:?*[\\'"<>&`\x00-\x1f\x7f]/; +const MAX_REF_NAME_LENGTH = 255; + +/** True when `ref` (a full name such as `refs/heads/main`) is a ref name git and SAM accept. */ +export function isValidGitRefName(ref: string): boolean { + return ( + ref.startsWith('refs/') && + ref.length <= MAX_REF_NAME_LENGTH && + !ref.includes('..') && + !BAD_REF_CHARS.test(ref) && + !ref.includes('@{') && + !ref.includes('//') && + !ref.endsWith('/') && + !ref.endsWith('.') && + !ref.split('/').some((c) => c.startsWith('.') || c.endsWith('.lock')) + ); +} + +/** True when `branch` (a short name such as `main`) names a valid `refs/heads/` ref. */ +export function isValidGitBranchName(branch: string): boolean { + return branch.length > 0 && isValidGitRefName(`refs/heads/${branch}`); +} diff --git a/apps/api/src/repo-hosting-ports/artifacts.ts b/apps/api/src/repo-hosting-ports/artifacts.ts index e4a6673306..d7d068a3d1 100644 --- a/apps/api/src/repo-hosting-ports/artifacts.ts +++ b/apps/api/src/repo-hosting-ports/artifacts.ts @@ -1,7 +1,7 @@ import type { ArtifactsBackendPort } from '@simple-agent-manager/repo-hosting/ports'; import type { Env } from '../env'; -import { resolveArtifactsBackend } from '../services/hosted-git/backend'; +import { resolveArtifactsBackend } from '../services/artifacts/backend'; /** * Repo hosting resolves the SAM-native repository backend through the worker's hosted-git seam: diff --git a/apps/api/src/routes/artifacts-config.ts b/apps/api/src/routes/artifacts-config.ts index 8674a45f8b..0bbf138712 100644 --- a/apps/api/src/routes/artifacts-config.ts +++ b/apps/api/src/routes/artifacts-config.ts @@ -2,7 +2,7 @@ import { Hono } from 'hono'; import type { Env } from '../env'; import { applyCacheHeaders } from '../lib/cache-headers'; -import { isArtifactsAvailable } from '../services/hosted-git/backend'; +import { isArtifactsAvailable } from '../services/artifacts/backend'; /** * Public config: whether this install can create SAM-native (Artifacts) repositories. True only diff --git a/apps/api/src/routes/projects/crud.ts b/apps/api/src/routes/projects/crud.ts index 588ab9dc21..8cc77f5a3e 100644 --- a/apps/api/src/routes/projects/crud.ts +++ b/apps/api/src/routes/projects/crud.ts @@ -11,6 +11,7 @@ import { toProjectSummaryResponse } from '../../lib/mappers'; import { parsePositiveInt } from '../../lib/route-helpers'; import { getUserId } from '../../middleware/auth'; import { requireProjectCapability } from '../../middleware/project-auth'; +import { resolveArtifactsBackendForCleanup } from '../../services/artifacts/backend'; import { buildProjectLibraryDeleteStatements, buildProjectLibraryR2Prefix, @@ -18,7 +19,6 @@ import { getProjectDeleteCleanupBatchSize, } from '../../services/file-library'; import { reconcileGcpWifPoolIndex } from '../../services/gcp-wif-pool-ownership'; -import { resolveArtifactsBackendForCleanup } from '../../services/hosted-git/backend'; import { getRuntimeLimits } from '../../services/limits'; import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history'; import { registerProjectCreateRoute } from './project-create'; diff --git a/apps/api/src/routes/projects/project-create.ts b/apps/api/src/routes/projects/project-create.ts index 663f60ad13..400f06226a 100644 --- a/apps/api/src/routes/projects/project-create.ts +++ b/apps/api/src/routes/projects/project-create.ts @@ -6,13 +6,15 @@ import { type Hono } from 'hono'; import * as schema from '../../db/schema'; import type { Env } from '../../env'; +import { isValidGitBranchName } from '../../lib/git-ref-name'; import { log } from '../../lib/logger'; import { toProjectResponse } from '../../lib/mappers'; import { ulid } from '../../lib/ulid'; import { getUserId } from '../../middleware/auth'; -import { errors } from '../../middleware/error'; +import { AppError, errors } from '../../middleware/error'; import { createOwnerProjectMembership } from '../../middleware/project-auth'; import { CreateProjectSchema, jsonValidator } from '../../schemas'; +import { artifactsBackendExtensions, resolveArtifactsBackend } from '../../services/artifacts/backend'; import { seedArtifactsReadme } from '../../services/artifacts/seed-readme'; import { getExternalInstallationId } from '../../services/github-installation-ids'; import { @@ -20,7 +22,6 @@ import { requireGitLabUserAccessToken, verifyGitLabProjectAccess, } from '../../services/gitlab'; -import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; import { getRuntimeLimits } from '../../services/limits'; import { assertRepositoryAccess, @@ -103,7 +104,18 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): throw errors.badRequest(`Maximum ${maxRepos} Artifacts-backed projects allowed`); } + const importUrl = body.importUrl?.trim() || null; + const extensions = artifactsBackendExtensions(c.env, artifacts); + const importer = extensions.importSource; + if (importUrl && !importer) { + throw errors.badRequest('This repository backend does not support importUrl'); + } + const importBranch = importUrl && importer ? await importer.defaultBranch(importUrl) : null; + if (importUrl && !importBranch) { + throw errors.badRequest('Could not read the default branch of the repository at importUrl'); + } const defaultBranch = + importBranch || body.defaultBranch?.trim() || c.env.ARTIFACTS_DEFAULT_BRANCH || ARTIFACTS_DEFAULTS.DEFAULT_BRANCH; @@ -116,6 +128,13 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): 'defaultBranch contains invalid characters. Only alphanumeric, hyphens, underscores, slashes, and dots are allowed (max 255 chars).' ); } + // The repository's first push writes this branch; refuse names git itself rejects + // (`foo.lock`, `.hidden`, `a..b`, `trailing.`) here rather than fail the seed push. + if (!isValidGitBranchName(defaultBranch)) { + throw errors.badRequest( + 'defaultBranch is not a valid git branch name (see git check-ref-format).' + ); + } // Create Artifacts repo — name includes projectId for uniqueness. // Must be sanitized: Artifacts rejects uppercase/spaces (the ULID projectId @@ -133,13 +152,23 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): // also orients agents (project name, description, SAM MCP tools). If seeding // fails the repo is unusable, so we abort creation and log the orphan. try { - await seedArtifactsReadme({ - remote: created.remote, - token: created.token, - branch: defaultBranch, - projectName: name, - description, - }); + if (importUrl && importer) { + await importer.populate({ + sourceUrl: importUrl, + branch: defaultBranch, + remote: created.remote, + token: created.token, + }); + } else { + await seedArtifactsReadme({ + remote: created.remote, + token: created.token, + branch: defaultBranch, + projectName: name, + description, + fetchImpl: extensions.remoteFetch, + }); + } } catch (seedError) { log.error('project_create.artifacts_seed_failed', { projectId, @@ -159,6 +188,7 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): action: 'orphaned_artifacts_repo_cleanup_failed', }); } + if (importUrl && seedError instanceof AppError) throw seedError; throw errors.internal('Failed to initialize Artifacts repository'); } diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts index f8ee409d8f..2ee1d2563a 100644 --- a/apps/api/src/routes/workspaces/runtime-git-token.ts +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -6,6 +6,10 @@ import * as schema from '../../db/schema'; import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { errors } from '../../middleware/error'; +import { + createArtifactsRuntimeToken, + resolveArtifactsBackend, +} from '../../services/artifacts/backend'; import { getInstallationToken, getUserInstallationRepositories } from '../../services/github-app'; import { GitHubCliPolicyError, @@ -19,7 +23,6 @@ import { requireGitLabUserAccessTokenResultForOwner, verifyGitLabProjectAccess, } from '../../services/gitlab'; -import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; import { boundArtifactsRepositoryHost } from '../../services/workspace-git-source'; import { assertRepositoryAccess } from '../projects/_helpers'; import { @@ -237,7 +240,11 @@ runtimeRoutes.post('/:id/git-token', async (c) => { const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const); const repo = await artifacts.get(artifactsRepoId); await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); - const tokenResult = await repo.createToken(requestedScope, ttl); + const tokenResult = await createArtifactsRuntimeToken(c.env, repo, requestedScope, ttl, { + userId: workspace.userId, + workspaceId: workspace.workspaceId, + callbackGeneration: workspace.callbackGeneration ?? null, + }); // Strip ?expires= suffix from token for git credential use const tokenSecret = tokenResult.plaintext.split('?expires=')[0] || tokenResult.plaintext; diff --git a/apps/api/src/schemas/projects.ts b/apps/api/src/schemas/projects.ts index fadc782d9d..3741a0009d 100644 --- a/apps/api/src/schemas/projects.ts +++ b/apps/api/src/schemas/projects.ts @@ -16,6 +16,7 @@ const AgentDefaultEntrySchema = v.object({ const AgentDefaultsSchema = v.record(v.string(), AgentDefaultEntrySchema); export const CreateProjectSchema = v.object({ + importUrl: v.optional(v.string()), name: v.string(), description: v.optional(v.string()), installationId: v.optional(v.string()), diff --git a/apps/api/src/selfhost/build.ts b/apps/api/src/selfhost/build.ts index 9333894c4b..e10b4c0656 100644 --- a/apps/api/src/selfhost/build.ts +++ b/apps/api/src/selfhost/build.ts @@ -11,12 +11,29 @@ * with the shared cloud-init generator as the frpc boot renderer. */ import { generateCloudInit } from '@simple-agent-manager/cloud-init'; +import type { Hono } from 'hono'; + +import type { Env } from '../env'; +import { mountHostedGitRoute } from './hosted-git'; +import { hostedGitTokenRoutes } from './hosted-git/token-route'; + +export { HostedGitRepo } from './hosted-git'; import { installAnalyticsD1Sink } from './analytics'; import { type SharedWorkerEntry, withReverseTunnel } from './reverse-tunnel/entry'; import { installSpeechEndpoints } from './speech'; -export function withSelfHostBuild(worker: T): T { +const mounted = new WeakSet(); + +export function withSelfHostBuild( + worker: T, + app: Hono<{ Bindings: Env }> +): T { + if (!mounted.has(app)) { + mountHostedGitRoute(app); + app.route('/api/projects', hostedGitTokenRoutes); + mounted.add(app); + } installSpeechEndpoints(); installAnalyticsD1Sink(); return withReverseTunnel(worker, generateCloudInit); diff --git a/apps/api/src/selfhost/hosted-git.ts b/apps/api/src/selfhost/hosted-git.ts new file mode 100644 index 0000000000..7a6e3ac825 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git.ts @@ -0,0 +1,52 @@ +/** + * SAM-hosted git for the self-host build only: the `HostedGitRepo` Durable Object class (vendored + * dgit core and pako) and the git smart-HTTP route. + * + * Only the celld entry generated by scripts/selfhost/celld-project.ts imports this module. The + * Cloudflare build's entry is `src/index.ts`, which does not, so the Cloudflare bundle carries + * neither the class nor the vendored git code (tests/unit/selfhost/selfhost-only-modules.test.ts + * fails if the shared entry reaches them again). The celld config declares the `HOSTED_GIT` + * binding and the class's migration (`SELFHOST_DURABLE_OBJECTS` in + * scripts/selfhost/selfhost-durable-objects.ts); `apps/api/wrangler.toml` does not. + * + * Loading this module also registers SAM's own git server as the Artifacts fallback in the shared + * seam (`registerArtifactsBackendFallback` in `services/artifacts/backend.ts`), so project + * creation, browsing, git tokens and deletion use it when no Cloudflare Artifacts binding exists. + * The backend (`selfhost/hosted-git/local-backend.ts`) reaches the Durable Object only through the + * `HOSTED_GIT` namespace binding, which exists only on a self-host deployment. + */ +import type { Hono } from 'hono'; + +import { registerArtifactsBackendFallback } from '../services/artifacts/backend'; +import type { HostedGitEnv as Env } from './hosted-git/env'; +import { handleHostedGitRequest, HOSTED_GIT_PATH_PREFIX } from './hosted-git/http'; +import { isLocalHostedGitActive, localHostedGitBackendFallback } from './hosted-git/local-backend'; + +export { HostedGitRepo } from './hosted-git/hosted-git-repo'; + +// Once, at module load: the celld entry imports this module before any request is served. +registerArtifactsBackendFallback(localHostedGitBackendFallback); + +/** + * Mounts git smart HTTP for SAM-hosted repositories (`/git/.git/...`). Authenticated per + * request with a repository token, not a session cookie. Inactive (falls through to the 404 + * handler) unless this install uses the local hosted git backend. + * + * Call it once, after `src/index.ts` has registered the shared routes. Hono runs every matching + * handler in registration order, and nothing `index.ts` registers after its global middleware + * matches `/git/*`, so the route runs after exactly the middleware every request gets (preview, + * pages proxy, workspace proxy, request logging, analytics, CORS), inside the request-scoped D1 + * session of the default `fetch`. tests/unit/selfhost/hosted-git-route-order.test.ts pins that. + */ +export function mountHostedGitRoute(app: Hono<{ Bindings: Env }>): void { + // An empty app means this is not the instance index.ts registered on (for example a bundle that + // loaded app.ts twice); the route would then serve nothing and every clone would 404 silently. + if (app.routes.length === 0) { + throw new Error('mountHostedGitRoute: the app has no routes; mount after src/index.ts'); + } + app.all(`${HOSTED_GIT_PATH_PREFIX}*`, async (c, next) => { + if (!isLocalHostedGitActive(c.env)) return next(); + const response = await handleHostedGitRequest(c.req.raw, c.env); + return response ?? next(); + }); +} diff --git a/apps/api/src/selfhost/hosted-git/env.ts b/apps/api/src/selfhost/hosted-git/env.ts new file mode 100644 index 0000000000..cd23a56edc --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/env.ts @@ -0,0 +1,7 @@ +import type { Env } from '../../env'; + +/** celld-only bindings; Cloudflare never configures these. */ +export interface HostedGitEnv extends Env { + HOSTED_GIT?: DurableObjectNamespace; + HOSTED_GIT_BACKEND?: string; +} diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-body.ts b/apps/api/src/selfhost/hosted-git/hosted-git-body.ts new file mode 100644 index 0000000000..a9305081d3 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/hosted-git-body.ts @@ -0,0 +1,99 @@ +/** + * Bounded request-body reading for the hosted git Durable Object: pkt-line lengths, whole-body + * reads with a byte cap, and draining a refused upload so the client sees the refusal reason. + */ +import { readGitChunk } from '../../vendor/dgit/git/budget'; +import { concat, td } from '../../vendor/dgit/git/util'; + +const PKT_LENGTH = /^[0-9a-f]{4}$/i; + +export class RequestTooLargeError extends Error { + constructor() { + super('request body exceeds maximum size'); + } +} + +/** + * A pkt-line length: exactly four hex digits. 0 is a flush packet; 1-3 are invalid. `parseInt` + * alone would accept "-004" and walk the parser backwards forever (security review, HIGH). + */ +export function pktLength(bytes: Uint8Array): number { + const text = td.decode(bytes); + if (!PKT_LENGTH.test(text)) throw new Error('bad pkt-line in push request'); + const len = parseInt(text, 16); + if (len !== 0 && len < 4) throw new Error('bad pkt-line in push request'); + return len; +} + +/** Read a whole request body, refusing (without buffering further) past `maxBytes`. */ +export async function readBodyBounded(req: Request, maxBytes: number): Promise { + if (!req.body) return new Uint8Array(0); + const reader = req.body.getReader(); + const parts: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await readGitChunk(reader); + if (done) break; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => undefined); + throw new RequestTooLargeError(); + } + parts.push(value); + } + return concat(parts); +} + +/** Discard up to `maxBytes` of a request body, then cancel whatever is left. */ +export async function drainBounded( + reader: ReadableStreamDefaultReader | null, + maxBytes: number +): Promise { + if (!reader) return; + let drained = 0; + try { + while (drained <= maxBytes) { + const { done, value } = await readGitChunk(reader); + if (done) return; + drained += value?.byteLength ?? 0; + } + await reader.cancel(); + } catch { + // The client may already be gone. + } +} + +/** + * A byte buffer that grows geometrically as chunks arrive, so reading a body in many small chunks + * copies O(total) bytes rather than re-copying everything read so far on every chunk. + */ +export class ChunkBuffer { + private bytes: Uint8Array; + length: number; + /** Bytes copied so far, for tests that bound the work. */ + copied = 0; + + constructor(initial: Uint8Array = new Uint8Array(0)) { + this.bytes = initial; + this.length = initial.length; + } + + append(chunk: Uint8Array): void { + if (this.length + chunk.length > this.bytes.length) { + const grown = new Uint8Array( + Math.max(this.bytes.length * 2, this.length + chunk.length, 4096) + ); + grown.set(this.bytes.subarray(0, this.length)); + this.copied += this.length; + this.bytes = grown; + } + this.bytes.set(chunk, this.length); + this.length += chunk.length; + this.copied += chunk.length; + } + + /** The bytes in [start, end), clamped to what has been read. */ + view(start = 0, end = this.length): Uint8Array { + return this.bytes.subarray(start, Math.min(end, this.length)); + } +} diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts new file mode 100644 index 0000000000..bba810a73e --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/hosted-git-gc.ts @@ -0,0 +1,126 @@ +/** + * Garbage collection for a SAM-hosted repository, adapted from dgit's `RepoCell.runGc` + * (https://github.com/littledivy/durable-git, MIT, commit d5eba04; see src/vendor/dgit/UPSTREAM.md). + * + * After a force push or a branch deletion, objects no longer reachable from any ref still occupy + * storage and count toward the repository's caps. This walks the graph from every ref and HEAD, + * keeps thin-pack delta bases, moves reachable pack objects to loose storage, drops the packs, and + * deletes unreachable loose objects. Huge repositories (beyond SAM's own object cap anyway) skip. + */ +import { isGitlinkMode, parseCommit, parseTag, parseTree } from '../../vendor/dgit/git/objects'; +import { OidSet } from '../../vendor/dgit/git/oidset'; +import type { GitStore } from '../../vendor/dgit/git/store'; + +const GC_MAX_OBJECTS = 300_000; +/** The Durable Object SQLite ceiling a migration must not cross while duplicating objects. */ +const DO_STORAGE_CAP = 10 * 1024 * 1024 * 1024; + +/** Delay before the GC alarm runs after a push queues work, coalescing bursts of pushes. */ +export const GC_DELAY_MS = 5 * 60 * 1000; + +type AlarmStorage = { + getAlarm(): Promise; + setAlarm(scheduledTime: number): Promise; +}; + +/** + * Arm the GC alarm GC_DELAY_MS from now unless one is already due sooner. Keeping an earlier + * alarm means a steady trickle of pushes cannot postpone cleanup indefinitely. + */ +export async function armHostedGitGcAlarm(storage: AlarmStorage): Promise { + const due = Date.now() + GC_DELAY_MS; + const armed = await storage.getAlarm(); + if (armed !== null && armed <= due) return; + await storage.setAlarm(due); +} + +/** + * Queue a GC episode for what a push left behind: history stranded by a force push or delete, + * or an ingested pack whose refs were rejected or never decided. Resets the retry budget. + */ +export async function queueHostedGitGc(store: GitStore, storage: AlarmStorage): Promise { + store.setMeta('gc-pending', '1'); + store.setMeta('gc-attempts', '0'); + await armHostedGitGcAlarm(storage).catch(() => undefined); +} + +export interface HostedGitGcResult { + removed: number; + kept: number; + skipped?: boolean; +} + +export async function runHostedGitGc(store: GitStore): Promise { + if (store.objectCount() > GC_MAX_OBJECTS) { + return { removed: 0, kept: store.objectCount(), skipped: true }; + } + const reachable = new OidSet(Math.max(store.objectCount(), 4096)); + const stack: string[] = store.refs().map((r: { target: string }) => r.target); + const head = store.resolveHead(); + if (head) stack.push(head); + for (let oid = stack.pop(); oid !== undefined; oid = stack.pop()) { + if (!reachable.addHex(oid)) continue; + const meta = store.typeAndSize(oid); + if (!meta || meta.type === 'blob') continue; + const obj = await store.get(oid); + if (!obj) continue; + if (obj.type === 'commit') { + const c = parseCommit(obj.data); + stack.push(c.tree, ...c.parents); + } else if (obj.type === 'tag') { + const t = parseTag(obj.data); + if (t.object) stack.push(t.object); + } else if (obj.type === 'tree') { + for (const e of parseTree(obj.data)) { + if (!isGitlinkMode(e.mode)) stack.push(e.oid); + } + } + } + // Thin-pack delta bases are a second reference edge, often unreachable from any ref. They + // matter only while packs are kept: migration stores every reachable object whole. + const bases = new Set(store.packs.baseOids()); + let removed = 0; + + // Reclaim whole packs that hold nothing reachable and no delta base before inflating + // anything. A rejected push's pack is reclaimed this way even when migrating the rest + // would exceed the work budget. + for (const packId of store.packs.packIds()) { + const oids = store.packs.packObjectOids(packId); + if (oids.some((oid) => reachable.hasHex(oid) || bases.has(oid))) continue; + await store.packs.dropPack(packId); + removed += oids.length; + } + + const packCount = store.packs.countObjects(); + const noHeadroom = + packCount > 0 && store.dbSize() + store.packs.totalPackBytes() > DO_STORAGE_CAP; + const migrate = packCount > 0 && !noHeadroom; + if (migrate) { + // Migrate reachable pack objects to loose storage first, then drop the packs. + let migrated = 0; + for (let i = 0; i < reachable.size; i++) { + const oid = reachable.atHex(i); + if (store.packs.lookup(oid)) { + const obj = await store.get(oid); + if (obj) { + store.put(oid, obj.type, obj.data); + migrated++; + } + } + } + removed += packCount - migrated; + store.packs.reset(); + } + for (const oid of store.allOids()) { + // While packs stay (no headroom to migrate), a loose delta base they use must stay too. + if (!reachable.hasHex(oid) && (migrate || !bases.has(oid))) { + store.deleteObject(oid); + removed++; + } + } + // A reachable cache must never list a deleted object: the next full clone rebuilds it. + if (removed > 0) store.invalidateReachable(); + return noHeadroom + ? { removed, kept: reachable.size, skipped: true } + : { removed, kept: reachable.size }; +} diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts b/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts new file mode 100644 index 0000000000..3891a53409 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/hosted-git-ls-refs.ts @@ -0,0 +1,63 @@ +/** + * `ref-prefix` for protocol v2 `ls-refs` on SAM-hosted repositories. + * + * The vendored dgit server (`vendor/dgit/git/protocol.ts`, `lsRefs`) ignores `ref-prefix` and + * always answers HEAD plus every ref. Git's protocol v2 says a server given `ref-prefix` arguments + * shows only refs that start with one of them (gitprotocol-v2, "ls-refs"). Clients that rely on it, + * such as isomorphic-git's `listServerRefs({ prefix: 'refs/heads/' })` behind the project's branch + * list, then saw "HEAD" as a branch (box round R13 D11). The SAM adaptation is recorded in UPSTREAM.md; this filter is applied by the Durable Object. + */ +import { FLUSH, pkt, PktParser } from '../../vendor/dgit/git/pktline'; +import { concat } from '../../vendor/dgit/git/util'; + +/** Upper bound on one ls-refs answer the filter buffers (refs only, no objects). */ +const MAX_LS_REFS_RESPONSE_BYTES = 16 * 1024 * 1024; +/** + * Most `ref-prefix` arguments honored. Past this the request is answered unfiltered, as git does + * past its own limit (upload-pack TOO_MANY_PREFIXES), which bounds the filter at this many prefix + * checks per ref instead of one per packet a 16 MiB request can carry. Clients send a handful. + */ +export const MAX_LS_REFS_PREFIXES = 256; + +/** + * The `ref-prefix` arguments of a protocol v2 `ls-refs` request, or null when the request is not + * `ls-refs` or names no prefix (then every ref is shown, as the protocol says). + */ +export function lsRefsPrefixes(body: Uint8Array): string[] | null { + const parser = new PktParser(body); + let lsRefs = false; + const prefixes: string[] = []; + for (let p = parser.read(); p !== null; p = parser.read()) { + if (p.kind !== 'line') continue; + if (p.text === 'command=ls-refs') lsRefs = true; + else if (p.text.startsWith('ref-prefix ')) { + if (prefixes.length === MAX_LS_REFS_PREFIXES) return null; // too many: show every ref + prefixes.push(p.text.slice('ref-prefix '.length)); + } + } + return lsRefs && prefixes.length > 0 ? prefixes : null; +} + +/** + * Keeps the lines of an `ls-refs` answer (` [ ]`) whose ref name starts + * with one of the prefixes; the flush packet that ends the answer is kept. + */ +export async function filterLsRefsResponse( + response: Response, + prefixes: readonly string[] +): Promise { + const body = new Uint8Array(await response.arrayBuffer()); + if (body.length > MAX_LS_REFS_RESPONSE_BYTES) + return new Response('error: ref advertisement exceeds maximum size\n', { status: 413 }); + const parser = new PktParser(body); + const kept: Uint8Array[] = []; + for (let p = parser.read(); p !== null; p = parser.read()) { + if (p.kind !== 'line') continue; + const name = p.text.split(' ')[1] ?? ''; + if (prefixes.some((prefix) => name.startsWith(prefix))) kept.push(pkt(p.raw)); + } + return new Response(concat([...kept, FLUSH]), { + status: response.status, + headers: response.headers, + }); +} diff --git a/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts new file mode 100644 index 0000000000..2c593be723 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/hosted-git-repo.ts @@ -0,0 +1,476 @@ +/** + * One SAM-hosted git repository: a Durable Object speaking git smart HTTP. + * + * Adapted from dgit's `RepoCell` (https://github.com/littledivy/durable-git, MIT, commit + * d5eba04, see `src/vendor/dgit/UPSTREAM.md`): the git protocol paths, delete and the GC alarm. + * Dropped: the web UI, R2 pack offload and the content API. GC lives in `hosted-git-gc.ts`. Added: SAM's push and repository caps + * (`selfhost/hosted-git/limits.ts`), checked before a pack is stored. + * + * Authentication is NOT done here. The only caller is `selfhost/hosted-git/http.ts`, which checks + * SAM's repository token on every request before forwarding to this object. The object is + * addressed by `idFromName()`, so one repository is one object. + */ +import { DurableObject } from 'cloudflare:workers'; + +import { log } from '../../lib/logger'; +import { maybeJsonRecord } from '../../lib/runtime-validation'; +import { bindGitResponse, readGitChunk, withGitWorkBudget } from '../../vendor/dgit/git/budget'; +import { ObjCache } from '../../vendor/dgit/git/packstore'; +import { + advertisement, + commitPush, + parsePushCommands, + renderStatus, + type Service, + sidebandFrames, + uploadPack, + validatePush, +} from '../../vendor/dgit/git/protocol'; +import { GitStore } from '../../vendor/dgit/git/store'; +import { concat, te } from '../../vendor/dgit/git/util'; +import { gunzipLimited } from '../../vendor/dgit/git/zlib'; +import type { HostedGitEnv } from './env'; +import { + ChunkBuffer, + drainBounded, + pktLength, + readBodyBounded, + RequestTooLargeError, +} from './hosted-git-body'; +import { + armHostedGitGcAlarm, + GC_DELAY_MS, + type HostedGitGcResult, + queueHostedGitGc, + runHostedGitGc, +} from './hosted-git-gc'; +import { filterLsRefsResponse, lsRefsPrefixes } from './hosted-git-ls-refs'; +import { + type HostedGitLimits, + hostedGitNewRefBytes, + hostedGitPushByteBudget, + hostedGitPushRefusal, + hostedGitPushTooLargeMessage, + hostedGitRefRefusal, + hostedGitStoredOverCapMessage, +} from './limits'; +import { resolveHostedGitLimits } from './policy'; +import { HostedGitUploads } from './uploads'; + +/** An upload-pack request is wants/haves/caps only. */ +const MAX_UPLOAD_PACK_BYTES = 16 * 1024 * 1024; +/** Concurrent clone/fetch walks contend on one event loop. */ +const MAX_ACTIVE_UPLOADS = 4; +/** Decompressed objects held for delta-base resolution during one push. */ +const INGEST_CACHE_BYTES = 32 * 1024 * 1024; +const PACK_HEADER_BYTES = 12; +/** The pkt-line command section of a push (ref updates + capabilities) before the pack. */ +const MAX_COMMAND_SECTION_BYTES = 1024 * 1024; +export class HostedGitRepo extends DurableObject { + private store: GitStore; + private readonly settingsEnv: HostedGitEnv; + /** Pushes are serialized: concurrent ingests would race pack-id allocation. */ + private receiveChain: Promise = Promise.resolve(); + private activeUploads = 0; + private readonly uploads = new HostedGitUploads(); + private deletion: Promise | undefined; + private deleting = false; + + constructor(ctx: DurableObjectState, env: unknown) { + super(ctx, env as never); + // celld supplies the same installation bindings to this class as its Worker. + this.settingsEnv = env as HostedGitEnv; + this.store = new GitStore(ctx.storage.sql); + } + + async fetch(req: Request): Promise { + const limits = await resolveHostedGitLimits(this.settingsEnv); + return withGitWorkBudget(limits, async () => bindGitResponse(await this.handleFetch(req))); + } + + private async handleFetch(req: Request): Promise { + const url = new URL(req.url); + const path = url.pathname; + try { + if (path === '/' && req.method === 'DELETE') { + this.deleting = true; + this.deletion ??= this.receiveChain + .then(async () => { + await this.uploads.close(); + await this.ctx.blockConcurrencyWhile(async () => { + // Preserve celld replication control tables; deleteAll would remove them. + this.store.setMeta('deleted', '1'); + this.ctx.storage.transactionSync(() => { + this.store.wipe(); + this.store = new GitStore(this.ctx.storage.sql); + this.store.setMeta('deleted', '1'); + }); + await this.ctx.storage.deleteAlarm(); + }); + }) + .catch((error) => { + this.deletion = undefined; + throw error; + }); + this.receiveChain = this.deletion.catch(() => undefined); + await this.deletion; + return new Response('deleted\n'); + } + if (this.deleting || this.store.getMeta('deleted') === '1') + return new Response('repository deleted\n', { status: 410 }); + if (path === '/info/refs' && req.method === 'GET') { + const service = url.searchParams.get('service'); + if (service !== 'git-upload-pack' && service !== 'git-receive-pack') { + return new Response('smart HTTP only\n', { status: 400 }); + } + const v2 = req.headers + .get('git-protocol') + ?.split(':') + .some((value) => value.trim() === 'version=2'); + return new Response(advertisement(this.store, service as Service, v2), { + headers: { + 'content-type': `application/x-${service}-advertisement`, + 'cache-control': 'no-cache', + }, + }); + } + if (path === '/git-upload-pack' && req.method === 'POST') { + return await this.upload(req); + } + if (path === '/git-receive-pack' && req.method === 'POST') { + return await this.receive(req); + } + if (path === '/init' && req.method === 'PUT') { + const body = maybeJsonRecord(await req.json().catch(() => null)); + const branch = typeof body?.defaultBranch === 'string' ? body.defaultBranch : 'main'; + this.store.setHead(`refs/heads/${branch}`); + this.store.setMeta('created', '1'); + return Response.json({ ok: true }); + } + if (path === '/info' && req.method === 'GET') { + return Response.json({ + exists: this.store.getMeta('created') === '1', + head: this.store.head(), + objects: this.store.objectCount(), + bytes: this.store.dbSize(), + reachableCache: this.store.reachableCacheValid(), + }); + } + return new Response('not found\n', { status: 404 }); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + log.error('hosted_git.request_failed', { path, method: req.method, error: msg }); + return new Response('error: the repository could not process this request\n', { + status: 500, + }); + } + } + + async alarm(): Promise { + const limits = await resolveHostedGitLimits(this.settingsEnv); + return withGitWorkBudget(limits, () => this.runAlarm(limits)); + } + + private async runAlarm(limits: HostedGitLimits): Promise { + if (this.deleting || this.store.getMeta('gc-pending') !== '1') return; + // GC drops packs: never while a clone is streaming. Leave gc-pending set and retry. + if (this.activeUploads > 0) { + await this.ctx.storage.setAlarm(Date.now() + 30_000).catch(() => undefined); + return; + } + try { + const result = await this.gc(limits); + log.info('hosted_git.gc', { ...result }); + } catch (err) { + log.error('hosted_git.gc_failed', { + error: err instanceof Error ? err.message : String(err), + }); + } + } + + /** GC serialized behind pushes and with no other request interleaving (it resets packs). */ + private gc(limits: HostedGitLimits): Promise { + let result: HostedGitGcResult = { removed: 0, kept: 0 }; + let failure: unknown; + let failed = false; + const run = this.receiveChain.then(() => + this.ctx.blockConcurrencyWhile(async () => { + try { + // Recheck after acquiring the push slot: a clone may have started while GC queued. + if (this.activeUploads > 0) { + this.store.setMeta('gc-pending', '1'); + await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS); + return; + } + await this.store.packs.cleanupOrphans(); + result = await runHostedGitGc(this.store); + this.store.setMeta('gc-pending', '0'); + this.store.setMeta('gc-attempts', '0'); + } catch (err) { + // Rejecting blockConcurrencyWhile resets a DO before the outer alarm can retain retry + // intent. Carry the failure out after the input gate completes successfully instead. + const attempts = Number(this.store.getMeta('gc-attempts') ?? '0') + 1; + this.store.setMeta('gc-attempts', String(attempts)); + // Keep repairable work pending, but stop automatic retries at the configured budget. + this.store.setMeta('gc-pending', attempts < limits.maxGcAttempts ? '1' : 'failed'); + if (attempts < limits.maxGcAttempts) { + await this.ctx.storage.setAlarm(Date.now() + GC_DELAY_MS).catch(() => { + log.error('hosted_git.gc_retry_schedule_failed'); + }); + } + failure = err; + failed = true; + } + }) + ); + this.receiveChain = run.then( + () => undefined, + () => undefined + ); + return run.then(() => { + if (failed) throw failure; + return result; + }); + } + + private async upload(req: Request): Promise { + const declared = parseInt(req.headers.get('content-length') ?? '', 10); + if (Number.isFinite(declared) && declared > MAX_UPLOAD_PACK_BYTES) { + return new Response('error: fetch request too large\n', { status: 413 }); + } + if (this.activeUploads >= MAX_ACTIVE_UPLOADS) { + return new Response('busy: too many concurrent fetches, retry shortly\n', { + status: 503, + headers: { 'retry-after': '15' }, + }); + } + // The slot spans the whole response stream; release() fires once from close/cancel. + this.activeUploads++; + const slot = this.uploads.start(); + let released = false; + const release = () => { + if (released) return; + released = true; + this.activeUploads--; + slot.release(); + }; + try { + let body = await readBodyBounded(req, MAX_UPLOAD_PACK_BYTES); + if (this.deleting) { + release(); + return new Response('repository deleted\n', { status: 410 }); + } + if (req.headers.get('content-encoding')?.includes('gzip')) { + body = gunzipLimited(body, MAX_UPLOAD_PACK_BYTES); + } + // dgit answers ls-refs with every ref whatever `ref-prefix` asks; filter the answer here. + const prefixes = lsRefsPrefixes(body); + const response = await uploadPack(this.store, body, release); + const filtered = prefixes ? await filterLsRefsResponse(response, prefixes) : response; + if (this.deleting) { + await filtered.body?.cancel(); + release(); + return new Response('repository deleted\n', { status: 410 }); + } + return slot.response(filtered); + } catch (err) { + release(); + if ( + err instanceof RequestTooLargeError || + (err instanceof Error && err.message.includes('exceeds maximum size')) + ) { + return new Response('error: fetch request too large\n', { status: 413 }); + } + throw err; + } + } + + /** + * The response is returned only after processing completes: returning a stream early lets + * celld treat the request as finished and evict the cell mid-ingest (upstream note). + */ + private async receive(req: Request): Promise { + const limits = await resolveHostedGitLimits(this.settingsEnv); + const declared = parseInt(req.headers.get('content-length') ?? '', 10); + // The command section has its own cap (MAX_COMMAND_SECTION_BYTES) and ingest budgets the pack, + // so a lowered push limit still admits a packless deletion that frees space. + if (Number.isFinite(declared) && declared > limits.maxPushBytes + MAX_COMMAND_SECTION_BYTES) { + return new Response(`error: ${hostedGitPushTooLargeMessage(limits.maxPushBytes)}\n`, { + status: 413, + headers: { 'content-type': 'text/plain; charset=utf-8' }, + }); + } + if (this.deleting) return new Response('repository deleted\n', { status: 410 }); + const chunks: Uint8Array[] = []; + const run = this.receiveChain.then(() => this.processReceive(req, (c) => chunks.push(c))); + this.receiveChain = run.then( + () => undefined, + () => undefined + ); + try { + await run; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + log.error('hosted_git.receive_failed', { error: msg }); + if (err instanceof RequestTooLargeError || msg.includes('exceeds maximum size')) { + return new Response(`error: ${hostedGitPushTooLargeMessage(limits.maxPushBytes)}\n`, { + status: 413, + }); + } + // Malformed requests are the client's fault; keep the detail out of the response. + const status = /pkt-line|push request|command section|git work|inflated size/.test(msg) + ? 400 + : 500; + return new Response( + status === 400 + ? 'error: malformed push request\n' + : 'error: the push could not be processed\n', + { status } + ); + } + return new Response(concat(chunks), { + headers: { + 'content-type': 'application/x-git-receive-pack-result', + 'cache-control': 'no-cache', + }, + }); + } + + private async processReceive(req: Request, emit: (chunk: Uint8Array) => void): Promise { + const limits = await resolveHostedGitLimits(this.settingsEnv); + const currentBytes = this.store.dbSize(); + const maxBytes = hostedGitPushByteBudget(currentBytes, limits); + let reader: ReadableStreamDefaultReader | null = null; + let body: ChunkBuffer; + if (req.headers.get('content-encoding')?.includes('gzip')) { + body = new ChunkBuffer( + gunzipLimited( + await readBodyBounded(req, limits.maxPushBytes + MAX_COMMAND_SECTION_BYTES), + limits.maxPushBytes + MAX_COMMAND_SECTION_BYTES + ) + ); + } else { + reader = req.body?.getReader() ?? null; + body = new ChunkBuffer(); + } + + // The pkt-line command section is small; everything after it is the pack. + let pos = 0; + const need = async (n: number): Promise => { + while (body.length - pos < n) { + if (!reader) return false; + const { done, value } = await readGitChunk(reader); + if (done) return false; + if (value?.length) body.append(value); + } + return true; + }; + for (;;) { + if (!(await need(4))) break; + const len = pktLength(body.view(pos, pos + 4)); + if (len === 0) { + pos += 4; + break; + } + if (pos + len > MAX_COMMAND_SECTION_BYTES) throw new Error('push command section too large'); + if (!(await need(len))) throw new Error('truncated push request'); + pos += len; + } + const { commands, caps } = parsePushCommands(body.view(0, pos)); + const sideband = caps.includes('side-band-64k'); + const progress = (msg: string) => { + if (!sideband) return; + for (const f of sidebandFrames(2, te.encode(msg))) emit(f); + }; + + // Read up to the pack header so the declared object count can be checked before storing. + const packStart = pos; + const hasPack = (await need(PACK_HEADER_BYTES)) || body.length > packStart; + let unpackError = hostedGitRefRefusal(this.store.refs(), commands, currentBytes, limits); + let packId: number | null = null; + if (hasPack) { + const header = body.view(packStart, packStart + PACK_HEADER_BYTES); + const incomingObjects = + header.length === PACK_HEADER_BYTES + ? new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8) + : 0; + const refusal = + unpackError ?? + hostedGitPushRefusal( + { objects: this.store.objectCount(), bytes: currentBytes }, + incomingObjects, + limits + ); + if (refusal) { + unpackError = refusal; + } else { + try { + const ingested = await this.store.packs.ingest(body.view(packStart), reader, { + maxBytes, + sizeHint: Number.isFinite(parseInt(req.headers.get('content-length') ?? '', 10)) + ? parseInt(req.headers.get('content-length') ?? '', 10) + : undefined, + cache: new ObjCache(INGEST_CACHE_BYTES), + onProgress: progress, + flush: () => this.ctx.storage.sync(), + // Pushes are untrusted: screen every object with SHA-1DC as git does, so an object + // carrying a collision-attack block is refused before any ref can point at it. The + // JS hasher runs at about 130 MiB/s; inflated bytes per push are already capped by + // maxInflatedBytes (128 MiB default), so this adds about 1 s at the cap. + collisionDetect: true, + }); + // Final reservation: the byte budget covered the raw pack, not its index rows and + // page overhead. Refuse the push and drop its pack if the stored total crossed the cap. + // The ref rows this push adds are written after this check, so reserve them here too. + const stored = this.store.dbSize() + hostedGitNewRefBytes(this.store.refs(), commands); + if (stored > limits.maxRepoBytes) { + await this.store.packs.dropPack(ingested.packId); + unpackError = hostedGitStoredOverCapMessage(stored, limits); + } else { + packId = ingested.packId; + } + } catch (err) { + // Ingest writes chunks before checksum/index validation. Reclaim those rows now, + // before the next push's quota check; retain an alarm if storage cleanup itself fails. + this.store.setMeta('gc-pending', '1'); + this.store.setMeta('gc-attempts', '0'); + await this.store.packs.cleanupOrphans().catch((cleanupError: unknown) => { + log.error('hosted_git.ingest_cleanup_failed', { + error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), + }); + }); + await armHostedGitGcAlarm(this.ctx.storage); + const msg = err instanceof Error ? err.message : String(err); + unpackError = msg.includes('exceeds maximum push size') + ? hostedGitPushTooLargeMessage(maxBytes) + : msg; + } + } + if (unpackError) { + log.warn('hosted_git.push_refused', { reason: unpackError }); + progress(`${unpackError}\n`); + // Read (and discard) the rest of the upload before answering: a response sent while the + // client is still uploading resets the connection, and git then shows "remote end hung up" + // instead of the reason. Bounded, so a refused client cannot keep the cell busy forever. + await drainBounded(reader, limits.maxPushBytes * 2); + } + } + + let outcome: ReturnType; + try { + const plan = await validatePush(this.store, commands, unpackError); + outcome = this.ctx.storage.transactionSync(() => commitPush(this.store, plan)); + } catch (err) { + // Reclaim a pack that never reached a ref decision, or it holds quota with no cleanup queued. + if (packId !== null) await queueHostedGitGc(this.store, this.ctx.storage); + throw err; + } + const { results, changed, needsGc } = outcome; + if (changed) { + this.store.setMeta('created', '1'); + this.store.setMeta('last-push', String(Date.now())); + } + if (needsGc || packId !== null) await queueHostedGitGc(this.store, this.ctx.storage); + if (caps.includes('report-status')) emit(renderStatus(results, unpackError, sideband)); + } +} diff --git a/apps/api/src/selfhost/hosted-git/http.ts b/apps/api/src/selfhost/hosted-git/http.ts new file mode 100644 index 0000000000..7d952c9df5 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/http.ts @@ -0,0 +1,196 @@ +/** + * Git smart HTTP for SAM-hosted repositories: `https://api./git/.git/...`. + * + * Every request is authenticated here before it reaches the repository's Durable Object: + * 1. HTTP Basic, password = a SAM hosted-git token (`tokens.ts`); the username is ignored. + * 2. The token names exactly this repository, and a push (receive-pack, including its + * `info/refs?service=git-receive-pack` discovery) needs the `write` scope. + * 3. D1: the repository still belongs to an `artifacts` project and the token's user is still an + * active member of it. A token minted for a workspace additionally needs that workspace to be + * active, owned by that user, in that project, on its current runtime (callback generation) + * and on a live node. + * Any failure answers 401 with a Basic challenge (git then reports "Authentication failed"), + * without saying which check failed. + */ +import { log } from '../../lib/logger'; +import { projectRoleHasCapability } from '../../middleware/project-auth'; +import { nodeStatusTerminatesCallbacks } from '../../services/node-callback-auth'; +import { WORKSPACE_CALLBACK_ACTIVE_STATUSES } from '../../services/workspace-callback-identity'; +import type { HostedGitEnv as Env } from './env'; +import { type HostedGitTokenClaims, isHostedGitRepoName, verifyHostedGitToken } from './tokens'; + +export const HOSTED_GIT_PATH_PREFIX = '/git/'; + +/** Durable Object sub-paths a client may reach, with the scope each needs. */ +type GitOperation = { doPath: string; write: boolean }; + +function classify(subPath: string, method: string, url: URL): GitOperation | null { + if (subPath === '/info/refs' && method === 'GET') { + const service = url.searchParams.get('service'); + if (service === 'git-upload-pack') return { doPath: '/info/refs', write: false }; + if (service === 'git-receive-pack') return { doPath: '/info/refs', write: true }; + return null; + } + if (subPath === '/git-upload-pack' && method === 'POST') { + return { doPath: '/git-upload-pack', write: false }; + } + if (subPath === '/git-receive-pack' && method === 'POST') { + return { doPath: '/git-receive-pack', write: true }; + } + return null; +} + +/** Parse `/git/.git/`; the `.git` suffix is optional. */ +export function parseHostedGitPath(pathname: string): { repo: string; subPath: string } | null { + if (!pathname.startsWith(HOSTED_GIT_PATH_PREFIX)) return null; + const rest = pathname.slice(HOSTED_GIT_PATH_PREFIX.length); + const slash = rest.indexOf('/'); + if (slash <= 0) return null; + const repo = rest.slice(0, slash).replace(/\.git$/, ''); + if (!isHostedGitRepoName(repo)) return null; + return { repo, subPath: rest.slice(slash) }; +} + +function unauthorized(): Response { + return new Response('Authentication required for this SAM-hosted repository\n', { + status: 401, + headers: { 'www-authenticate': 'Basic realm="SAM"', 'content-type': 'text/plain' }, + }); +} + +function basicPassword(request: Request): string | null { + const header = request.headers.get('authorization') ?? ''; + if (!header.startsWith('Basic ')) return null; + try { + const decoded = atob(header.slice(6).trim()); + const colon = decoded.indexOf(':'); + return colon === -1 ? null : decoded.slice(colon + 1); + } catch { + return null; + } +} + +interface BindingRow { + project_id: string; + /** The token user's role when they are an active member, else null. */ + member_role: string | null; + workspace_status: string | null; + workspace_project_id: string | null; + workspace_user_id: string | null; + workspace_generation: string | null; + node_id: string | null; + node_status: string | null; +} + +/** + * One D1 round trip: the repository's project, whether the token's user is an active member of + * it, and, for a workspace-bound token, that workspace and its node. + */ +async function loadBinding( + env: Pick, + repo: string, + claims: HostedGitTokenClaims +): Promise { + return env.DATABASE.prepare( + `SELECT p.id AS project_id, + (SELECT pm.role FROM project_members pm + WHERE pm.project_id = p.id AND pm.user_id = ?3 AND pm.status = 'active' + LIMIT 1) AS member_role, + w.status AS workspace_status, w.project_id AS workspace_project_id, + w.user_id AS workspace_user_id, w.callback_generation AS workspace_generation, + w.node_id AS node_id, n.status AS node_status + FROM projects p + LEFT JOIN workspaces w ON w.id = ?2 + LEFT JOIN nodes n ON n.id = w.node_id + WHERE p.artifacts_repo_id = ?1 AND p.repo_provider = 'artifacts' + LIMIT 1` + ) + .bind(repo, claims.workspaceId ?? null, claims.userId ?? null) + .first(); +} + +/** Why a token's binding is no longer valid, or null when it is. */ +function bindingRefusal( + row: BindingRow, + claims: HostedGitTokenClaims, + write: boolean +): string | null { + if (!claims.userId) return 'no_principal'; + if (!row.member_role) return 'not_a_member'; + // Scope is fixed at mint time; the role is current, so a downgrade takes effect at once. + if (write && !projectRoleHasCapability(row.member_role, 'workspace:write')) { + return 'role_cannot_write'; + } + if (!claims.workspaceId) return null; + if (!row.workspace_status || !WORKSPACE_CALLBACK_ACTIVE_STATUSES.has(row.workspace_status)) { + return 'workspace_inactive'; + } + if (row.workspace_project_id !== row.project_id) return 'workspace_project_mismatch'; + if (row.workspace_user_id !== claims.userId) return 'workspace_user_mismatch'; + if ((row.workspace_generation ?? null) !== (claims.callbackGeneration ?? null)) { + return 'workspace_generation_retired'; + } + if (!row.node_id || !row.node_status || nodeStatusTerminatesCallbacks(row.node_status)) { + return 'workspace_node_gone'; + } + return null; +} + +export interface HostedGitHttpEnv { + DATABASE: D1Database; + ENCRYPTION_KEY: string; + HOSTED_GIT?: DurableObjectNamespace; +} + +/** Handle one git request. Returns null when the path is not a hosted git path. */ +export async function handleHostedGitRequest( + request: Request, + env: HostedGitHttpEnv, + options: { + /** + * Set only by SAM's own in-process calls (`artifactsRemoteFetch`): README seeding runs + * before the project row exists, and browsing callers have already checked project access. + * The token's signature, repository, scope and expiry are still checked. + */ + trustedInternalCaller?: boolean; + } = {} +): Promise { + const url = new URL(request.url); + const parsed = parseHostedGitPath(url.pathname); + if (!parsed) return null; + if (!env.HOSTED_GIT) return new Response('not found\n', { status: 404 }); + const operation = classify(parsed.subPath, request.method, url); + if (!operation) return new Response('not found\n', { status: 404 }); + + const password = basicPassword(request); + if (!password) return unauthorized(); + const claims = await verifyHostedGitToken(env, password); + const reject = (reason: string) => { + log.info('hosted_git.auth_rejected', { repo: parsed.repo, reason, write: operation.write }); + return unauthorized(); + }; + if (!claims) return reject('invalid_token'); + if (claims.repo !== parsed.repo) return reject('repo_mismatch'); + if (operation.write && claims.scope !== 'write') return reject('scope'); + + // External requests always need a person behind the token (a member, or a workspace owner). + // Tokens with neither are minted only for SAM's own in-process seeding and browsing. + if (!options.trustedInternalCaller || claims.userId || claims.workspaceId) { + const binding = await loadBinding(env, parsed.repo, claims); + if (!binding) return reject('repo_not_bound'); + const refusal = bindingRefusal(binding, claims, operation.write); + if (refusal) return reject(refusal); + } + + const doUrl = new URL(request.url); + doUrl.pathname = operation.doPath; + const headers = new Headers(request.headers); + headers.delete('authorization'); + const forwarded = new Request(doUrl.toString(), { + method: request.method, + headers, + body: request.method === 'GET' ? null : request.body, + }); + const stub = env.HOSTED_GIT.get(env.HOSTED_GIT.idFromName(parsed.repo)); + return stub.fetch(forwarded); +} diff --git a/apps/api/src/selfhost/hosted-git/limits.ts b/apps/api/src/selfhost/hosted-git/limits.ts new file mode 100644 index 0000000000..4370af6cfb --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/limits.ts @@ -0,0 +1,126 @@ +/** + * Caps for SAM-hosted repositories (the self-host Durable Object git server). + * + * Why these numbers (measured on celld 0.6.3 with the self-host box's settings, idea + * 01M75V57RG8GR4NA0KC91TM1J7, "HOSTED REPOS ON DURABLE OBJECTS" part 6): every request to a + * repository runs inside celld's node-wide 300 s handler budget, and one repository is one + * single-threaded cell. A 24.8k-object repository (32 MiB pack) pushed in 29.5 s and cold-cloned + * in 67 s; a 97k-object repository (448 MiB) could not cold-clone within 300 s at all, and the + * cost grows faster than the object count. Ingest ran at about 5.5 MB/s. + * + * - Push: 64 MiB at ~5.5 MB/s is ~12 s of receive plus indexing and the connectivity check, well + * inside 300 s even for a fresh repository. + * - Objects: 30,000 keeps a cold full clone near the measured 25k-object point (~70-90 s). + * - Storage: 256 MiB of SQLite per repository (packs are stored about 1-2.5x their wire size). + * + * Administrators can lower these bounds through repositories.* settings. Maximums remain at + * the measured safe envelope; increasing that envelope requires a new measurement. + */ +import { + REPOSITORY_POLICY_DEFAULTS, + type RepositoryPolicyKey, +} from '../../services/artifacts/settings'; + +export const DEFAULT_HOSTED_GIT_MAX_PUSH_BYTES = REPOSITORY_POLICY_DEFAULTS.maxPushBytes; +export const DEFAULT_HOSTED_GIT_MAX_REPO_OBJECTS = REPOSITORY_POLICY_DEFAULTS.maxRepoObjects; +export const DEFAULT_HOSTED_GIT_MAX_REPO_BYTES = REPOSITORY_POLICY_DEFAULTS.maxRepoBytes; +export type HostedGitLimits = { [K in RepositoryPolicyKey]: number }; +export const DEFAULT_HOSTED_GIT_LIMITS: HostedGitLimits = REPOSITORY_POLICY_DEFAULTS; + +function mib(bytes: number): string { + return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MiB`; +} + +/** + * Decide whether a push may start, from the repository's current size and the object count the + * pushed pack declares in its header. Returns the refusal message shown to the git client, or + * null when the push may proceed. + */ +export function hostedGitPushRefusal( + current: { objects: number; bytes: number }, + incomingObjects: number, + limits: HostedGitLimits +): string | null { + if (current.bytes >= limits.maxRepoBytes) { + return ( + `SAM: push refused: this repository already uses ${mib(current.bytes)} of its ` + + `${mib(limits.maxRepoBytes)} storage limit` + ); + } + if (current.objects + incomingObjects > limits.maxRepoObjects) { + return ( + `SAM: push refused: it would bring this repository to ${current.objects + incomingObjects} ` + + `objects, over the ${limits.maxRepoObjects}-object limit for SAM-hosted repositories` + ); + } + return null; +} + +/** The most bytes this push may stream: the push cap, or less when the repository is nearly full. */ +/** + * The refusal when a pack that fit the raw byte budget pushed stored size over the cap once its + * index rows and page overhead were written (enforced at the final write, after ingest). + */ +export function hostedGitStoredOverCapMessage( + storedBytes: number, + limits: HostedGitLimits +): string { + return ( + `SAM: push refused: storing this pack would bring this repository to ${mib(storedBytes)}, ` + + `over its ${mib(limits.maxRepoBytes)} storage limit` + ); +} + +export function hostedGitPushByteBudget(currentBytes: number, limits: HostedGitLimits): number { + return Math.max(0, Math.min(limits.maxPushBytes, limits.maxRepoBytes - currentBytes)); +} + +export function hostedGitPushTooLargeMessage(maxBytes: number): string { + return `SAM: push refused: the pack is larger than the ${mib(maxBytes)} limit for one push to a SAM-hosted repository; push in smaller pieces`; +} + +/** SQLite page reserved for each new ref, including index overhead. */ +const REF_RESERVATION_BYTES = 4096; + +/** Bytes to reserve for the refs a push would create (deletions earn nothing). */ +export function hostedGitNewRefBytes( + existing: readonly { name: string }[], + commands: readonly { ref: string; next: string }[] +): number { + const refs = new Set(existing.map((ref) => ref.name)); + let additions = 0; + for (const command of commands) { + if (command.next !== '0'.repeat(40) && !refs.has(command.ref)) { + additions++; + refs.add(command.ref); + } + } + return additions * REF_RESERVATION_BYTES; +} + +/** Check ref-only pushes too. Reserve a SQLite page per new ref, including index overhead. */ +export function hostedGitRefRefusal( + existing: readonly { name: string }[], + commands: readonly { ref: string; next: string }[], + currentBytes: number, + limits: HostedGitLimits +): string | null { + const refs = new Set(existing.map((ref) => ref.name)); + let additions = 0; + let writes = false; + for (const command of commands) { + // Do not credit deletions: their old-OID check may fail while an addition succeeds. + if (command.next !== '0'.repeat(40)) { + writes = true; + if (!refs.has(command.ref)) additions++; + refs.add(command.ref); + } + } + // Deletions remain available when an administrator lowers a limit below current usage. + if (!writes) return null; + if (refs.size > limits.maxRepoRefs) + return `SAM: push refused: repository exceeds its ${limits.maxRepoRefs}-ref limit`; + if (currentBytes + additions * REF_RESERVATION_BYTES >= limits.maxRepoBytes) + return 'SAM: push refused: repository storage limit leaves no room for ref updates'; + return null; +} diff --git a/apps/api/src/selfhost/hosted-git/local-backend.ts b/apps/api/src/selfhost/hosted-git/local-backend.ts new file mode 100644 index 0000000000..d6fd41f161 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/local-backend.ts @@ -0,0 +1,149 @@ +/** + * SAM's own git server as an Artifacts backend (self-host only). + * + * `backend.ts` is the seam: it selects the Cloudflare Artifacts binding, else the fallback a + * self-host build registered. This module is that fallback: the four `Env.ARTIFACTS` methods SAM + * calls, implemented against the `HostedGitRepo` Durable Object (`selfhost/hosted-git/hosted-git-repo.ts`) + * through the `HOSTED_GIT` namespace binding only. It never imports the class. The self-host build + * registers it (`selfhost/hosted-git.ts`); only that build sets `HOSTED_GIT_BACKEND` and binds the + * class (`scripts/selfhost/celld-config.ts`, `selfhost-durable-objects.ts`), so on Cloudflare + * `isLocalHostedGitActive` is always false. + */ +import type { ArtifactsBackend } from '../../services/artifacts/backend'; +import type { HostedGitEnv as Env } from './env'; +import { handleHostedGitRequest, HOSTED_GIT_PATH_PREFIX } from './http'; +import { clampHostedGitTokenTtl, mintHostedGitToken } from './tokens'; + +type BackendEnv = Pick< + Env, + 'ARTIFACTS' | 'ARTIFACTS_ENABLED' | 'HOSTED_GIT' | 'HOSTED_GIT_BACKEND' | 'BASE_DOMAIN' +> & + Partial>; + +export function isHostedGitBackendConfigured( + env: Pick +): boolean { + return env.HOSTED_GIT_BACKEND?.trim() === 'durable-object' && !!env.HOSTED_GIT; +} + +/** Base URL of hosted repositories; a repository's remote is `.git`. */ +export function hostedGitBaseUrl(env: Pick): string { + return `https://api.${env.BASE_DOMAIN}${HOSTED_GIT_PATH_PREFIX}`; +} + +export function hostedGitRemote(env: Pick, repo: string): string { + return `${hostedGitBaseUrl(env)}${repo}.git`; +} + +/** Host git clients use for hosted repositories (`api.`). */ +export function hostedGitHost(env: Pick): string { + return `api.${env.BASE_DOMAIN}`; +} + +function repoStub(env: BackendEnv, name: string): DurableObjectStub { + if (!env.HOSTED_GIT) throw new Error('HOSTED_GIT binding is missing'); + return env.HOSTED_GIT.get(env.HOSTED_GIT.idFromName(name)); +} + +function requireEncryptionKey(env: BackendEnv): Pick { + if (!env.ENCRYPTION_KEY) + throw new Error('ENCRYPTION_KEY is required for SAM-hosted repositories'); + return { ENCRYPTION_KEY: env.ENCRYPTION_KEY }; +} + +/** The local implementation of the four `Env.ARTIFACTS` methods SAM calls. */ +export function createDurableObjectArtifactsBackend(env: BackendEnv): ArtifactsBackend { + const keyEnv = () => requireEncryptionKey(env); + return { + remoteFetch: artifactsRemoteFetch(env), + // Import stays unregistered until tasks/backlog/2026-11-19-bounded-selfhost-git-import.md + // bounds decompression before the importer materializes untrusted objects. + async create(name, opts) { + const defaultBranch = opts?.setDefaultBranch || 'main'; + const res = await repoStub(env, name).fetch('https://hosted-git/init', { + method: 'PUT', + body: JSON.stringify({ defaultBranch }), + }); + if (!res.ok) throw new Error(`Hosted repository init failed: HTTP ${res.status}`); + const { token } = await mintHostedGitToken(keyEnv(), { repo: name, scope: 'write' }); + return { + id: name, + name, + remote: hostedGitRemote(env, name), + token, + default_branch: defaultBranch, + }; + }, + async delete(name) { + const res = await repoStub(env, name).fetch('https://hosted-git/', { method: 'DELETE' }); + return res.ok; + }, + async get(name) { + const res = await repoStub(env, name).fetch('https://hosted-git/info'); + const info = res.ok ? ((await res.json()) as { head?: string }) : {}; + const defaultBranch = (info.head ?? 'refs/heads/main').replace(/^refs\/heads\//, ''); + return { + id: name, + name, + remote: hostedGitRemote(env, name), + defaultBranch, + async createToken(scope, ttl, context) { + const minted = await mintHostedGitToken(keyEnv(), { + repo: name, + scope: scope ?? 'read', + ...context, + ttlSeconds: clampHostedGitTokenTtl(ttl), + }); + return { + id: name, + plaintext: minted.token, + scope: scope ?? 'read', + expiresAt: minted.expiresAt, + }; + }, + }; + }, + }; +} + +/** + * The fallback the self-host build registers with `registerArtifactsBackendFallback`: SAM's own git + * server when this install configured it, else none. + */ +export function localHostedGitBackendFallback(env: Env): ArtifactsBackend | null { + return isHostedGitBackendConfigured(env) ? createDurableObjectArtifactsBackend(env) : null; +} + +/** Whether this install serves SAM-native repositories from its own Durable Object git server. */ +export function isLocalHostedGitActive(env: BackendEnv): boolean { + return env.ARTIFACTS_ENABLED === 'true' && !env.ARTIFACTS && isHostedGitBackendConfigured(env); +} + +/** Whether `remote` is a repository on this install's own git server. */ +export function isHostedGitRemote(env: Pick, remote: string): boolean { + return !!env.BASE_DOMAIN && remote.startsWith(hostedGitBaseUrl(env)); +} + +/** + * A fetch for SAM's own calls to a repository remote (README seeding, browsing). Requests to the + * hosted git server are served in-process through the same authenticated handler external git + * clients reach, instead of leaving the Worker and coming back through the ingress (no hairpin + * through Caddy, no egress-fence exception). Anything else uses the global fetch. + */ +export function artifactsRemoteFetch(env: BackendEnv): typeof fetch { + // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- SAM creates the repository remote URLs supplied by its Artifacts backend + if (!isLocalHostedGitActive(env)) return fetch; + return async (input, init) => { + const request = new Request(input, init); + if (!isHostedGitRemote(env, request.url) || !env.DATABASE || !env.ENCRYPTION_KEY) { + // eslint-disable-next-line sam/no-unguarded-outbound-fetch -- SAM creates the repository remote URLs supplied by its Artifacts backend + return fetch(request); + } + const response = await handleHostedGitRequest( + request, + { DATABASE: env.DATABASE, ENCRYPTION_KEY: env.ENCRYPTION_KEY, HOSTED_GIT: env.HOSTED_GIT }, + { trustedInternalCaller: true } + ); + return response ?? new Response('not found\n', { status: 404 }); + }; +} diff --git a/apps/api/src/selfhost/hosted-git/policy.ts b/apps/api/src/selfhost/hosted-git/policy.ts new file mode 100644 index 0000000000..98cc644833 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/policy.ts @@ -0,0 +1,24 @@ +import { resolveAdminSettingDetailsMany } from '../../services/admin-settings-resolution'; +import { + REPOSITORY_POLICY_DEFAULTS, + type RepositoryPolicyKey, + type RepositorySettingName, +} from '../../services/artifacts/settings'; +import type { HostedGitEnv } from './env'; +import { DEFAULT_HOSTED_GIT_LIMITS, type HostedGitLimits } from './limits'; + +export async function resolveHostedGitLimits(env: HostedGitEnv): Promise { + const keys = Object.keys(REPOSITORY_POLICY_DEFAULTS) as RepositoryPolicyKey[]; + const settings = await resolveAdminSettingDetailsMany( + env, + keys.map((key) => `repositories.${key}` as RepositorySettingName) + ); + const result = { ...DEFAULT_HOSTED_GIT_LIMITS }; + for (const [index, key] of keys.entries()) { + const setting = settings[index]; + if (!setting || typeof setting.value !== 'number') + throw new Error('Repository policy is unavailable'); + result[key] = setting.value; + } + return result; +} diff --git a/apps/api/src/selfhost/hosted-git/token-route.ts b/apps/api/src/selfhost/hosted-git/token-route.ts new file mode 100644 index 0000000000..b63e045621 --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/token-route.ts @@ -0,0 +1,62 @@ +/** + * POST /api/projects/:id/hosted-git/token — a short-lived clone/push credential for a person + * using a SAM-hosted repository from their own machine (self-host only). + * + * Session-authenticated (mounted inside projectsRoutes). Read needs `project:read`; write needs + * `workspace:write`, the capability that lets a member change the project's work. Returns 404 + * for any project that is not on this install's own git server, so Cloudflare installs and + * GitHub/GitLab projects are unaffected. + */ +import { drizzle } from 'drizzle-orm/d1'; +import { Hono } from 'hono'; + +import * as schema from '../../db/schema'; +import { assertNotAgentSignInSession, getUserId } from '../../middleware/auth'; +import { errors } from '../../middleware/error'; +import { requireProjectCapability } from '../../middleware/project-auth'; +import type { HostedGitEnv as Env } from './env'; +import { hostedGitHost, isLocalHostedGitActive } from './local-backend'; +import { mintHostedGitToken } from './tokens'; + +const hostedGitTokenRoutes = new Hono<{ Bindings: Env }>(); + +hostedGitTokenRoutes.post('/:id/hosted-git/token', async (c) => { + // A personal clone/push credential outlives the session that mints it, so an agent sign-in + // session (hard-expiring, workload identity) may not create one. + assertNotAgentSignInSession(c); + const userId = getUserId(c); + const projectId = c.req.param('id'); + const scope = c.req.query('scope') === 'write' ? 'write' : 'read'; + const db = drizzle(c.env.DATABASE, { schema }); + const project = await requireProjectCapability( + db, + projectId, + userId, + scope === 'write' ? 'workspace:write' : 'project:read' + ); + if ( + !isLocalHostedGitActive(c.env) || + project.repoProvider !== 'artifacts' || + !project.artifactsRepoId + ) { + throw errors.notFound('SAM-hosted repository'); + } + const minted = await mintHostedGitToken(c.env, { + repo: project.artifactsRepoId, + scope, + userId, + // The same operator setting that bounds workspace and browsing credentials; an absent or + // invalid value falls back to the default inside clampHostedGitTokenTtl. + ttlSeconds: Number.parseInt(c.env.ARTIFACTS_TOKEN_TTL_SECONDS ?? '', 10), + }); + return c.json({ + cloneUrl: project.repository, + host: hostedGitHost(c.env), + username: 'x', + token: minted.token, + scope, + expiresAt: minted.expiresAt, + }); +}); + +export { hostedGitTokenRoutes }; diff --git a/apps/api/src/selfhost/hosted-git/tokens.ts b/apps/api/src/selfhost/hosted-git/tokens.ts new file mode 100644 index 0000000000..cfd36fae7c --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/tokens.ts @@ -0,0 +1,178 @@ +/** + * Access tokens for SAM-hosted repositories. + * + * A token is `samgit1..`: a base64url JSON payload naming one repository, + * one scope, an expiry and who it acts for (a user, and for workspaces the workspace and its + * callback generation), signed with HMAC-SHA256. git sends it as the HTTP Basic password (any + * username). The key is derived from the Worker's ENCRYPTION_KEY with HKDF under a fixed label, so + * it is separate from every other use of that secret and needs no new secret or table. + * + * Tokens cannot be revoked individually; they are short-lived (TTL clamped to 1 s..24 h) and + * the git route re-checks in D1, on every request, that the repository still belongs to a + * project, that the user is still an active member, and that a workspace-bound token's workspace + * is still active on its current runtime (callback generation). + */ +import type { HostedGitEnv as Env } from './env'; + +export type HostedGitScope = 'read' | 'write'; + +export interface HostedGitTokenClaims { + /** Repository name (projects.artifacts_repo_id). */ + repo: string; + scope: HostedGitScope; + /** Expiry, unix seconds. */ + exp: number; + /** Workspace the token was minted for, when a workspace asked for it. */ + workspaceId?: string; + /** + * The workspace's callback credential generation at mint time (`workspaces.callback_generation`, + * null when unset). A restart or wake rotates it, retiring tokens of the previous runtime. + */ + callbackGeneration?: string | null; + /** The person the token acts for: a member, or the owner of the workspace. */ + userId?: string; +} + +const TOKEN_PREFIX = 'samgit1'; +const KEY_LABEL = 'sam-hosted-git-token/v1'; +export const DEFAULT_HOSTED_GIT_TOKEN_TTL_SECONDS = 3600; +export const MAX_HOSTED_GIT_TOKEN_TTL_SECONDS = 86_400; +/** Repository names SAM generates (toArtifactsRepoName): lowercase, digits, dashes. */ +const REPO_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,127}$/; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +export function isHostedGitRepoName(name: string): boolean { + return REPO_NAME_PATTERN.test(name); +} + +function base64UrlEncode(bytes: Uint8Array): string { + let binary = ''; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); +} + +function base64UrlDecode(value: string): Uint8Array | null { + if (!/^[A-Za-z0-9_-]+$/.test(value)) return null; + try { + const padded = + value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - (value.length % 4)) % 4); + return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0)); + } catch { + return null; + } +} + +/** + * The derived key, cached once derived. Only a finished key is shared: a request never waits on a + * derivation another request started, which on the self-hosted celld runtime could be dropped + * with that request (lib/shared-flight.ts). Concurrent cold callers each derive once (one HKDF). + */ +let cachedKey: { secret: string; key: CryptoKey } | null = null; + +/** HKDF-SHA256 from ENCRYPTION_KEY with a purpose label; no other use shares this key. */ +async function signingKey(env: Pick): Promise { + const secret = env.ENCRYPTION_KEY; + if (!secret) throw new Error('ENCRYPTION_KEY is required for SAM-hosted repositories'); + if (cachedKey?.secret === secret) return cachedKey.key; + const root = await crypto.subtle.importKey('raw', encoder.encode(secret), 'HKDF', false, [ + 'deriveKey', + ]); + const key = await crypto.subtle.deriveKey( + { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: encoder.encode(KEY_LABEL) }, + root, + { name: 'HMAC', hash: 'SHA-256', length: 256 }, + false, + ['sign', 'verify'] + ); + cachedKey = { secret, key }; + return key; +} + +export function clampHostedGitTokenTtl(ttlSeconds: number | undefined): number { + if (ttlSeconds === undefined || !Number.isFinite(ttlSeconds) || ttlSeconds <= 0) { + return DEFAULT_HOSTED_GIT_TOKEN_TTL_SECONDS; + } + return Math.min(Math.floor(ttlSeconds), MAX_HOSTED_GIT_TOKEN_TTL_SECONDS) || 1; +} + +export async function mintHostedGitToken( + env: Pick, + input: { + repo: string; + scope: HostedGitScope; + ttlSeconds?: number; + workspaceId?: string; + callbackGeneration?: string | null; + userId?: string; + }, + now: number = Date.now() +): Promise<{ token: string; expiresAt: string }> { + if (!isHostedGitRepoName(input.repo)) throw new Error('Invalid hosted repository name'); + const exp = Math.floor(now / 1000) + clampHostedGitTokenTtl(input.ttlSeconds); + const claims: HostedGitTokenClaims = { repo: input.repo, scope: input.scope, exp }; + if (input.workspaceId) { + claims.workspaceId = input.workspaceId; + claims.callbackGeneration = input.callbackGeneration ?? null; + } + if (input.userId) claims.userId = input.userId; + const payload = base64UrlEncode(encoder.encode(JSON.stringify(claims))); + const unsigned = `${TOKEN_PREFIX}.${payload}`; + const signature = await crypto.subtle.sign( + 'HMAC', + await signingKey(env), + encoder.encode(unsigned) + ); + return { + token: `${unsigned}.${base64UrlEncode(new Uint8Array(signature))}`, + expiresAt: new Date(exp * 1000).toISOString(), + }; +} + +/** Verify signature, shape and expiry. Returns null for any token that is not valid now. */ +export async function verifyHostedGitToken( + env: Pick, + token: string, + now: number = Date.now() +): Promise { + if (token.length > 2048) return null; + const parts = token.split('.'); + if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null; + const [prefix, payload, signaturePart] = parts as [string, string, string]; + const signature = base64UrlDecode(signaturePart); + const payloadBytes = base64UrlDecode(payload); + if (!signature || !payloadBytes) return null; + const valid = await crypto.subtle.verify( + 'HMAC', + await signingKey(env), + signature, + encoder.encode(`${prefix}.${payload}`) + ); + if (!valid) return null; + let parsed: unknown; + try { + parsed = JSON.parse(decoder.decode(payloadBytes)); + } catch { + return null; + } + if (!parsed || typeof parsed !== 'object') return null; + const claims = parsed as Record; + if (typeof claims.repo !== 'string' || !isHostedGitRepoName(claims.repo)) return null; + if (claims.scope !== 'read' && claims.scope !== 'write') return null; + if (typeof claims.exp !== 'number' || claims.exp * 1000 <= now) return null; + if (claims.workspaceId !== undefined && typeof claims.workspaceId !== 'string') return null; + if (claims.userId !== undefined && typeof claims.userId !== 'string') return null; + const generation = claims.callbackGeneration; + if (generation !== undefined && generation !== null && typeof generation !== 'string') + return null; + return { + repo: claims.repo, + scope: claims.scope, + exp: claims.exp, + ...(typeof claims.workspaceId === 'string' + ? { workspaceId: claims.workspaceId, callbackGeneration: generation ?? null } + : {}), + ...(typeof claims.userId === 'string' ? { userId: claims.userId } : {}), + }; +} diff --git a/apps/api/src/selfhost/hosted-git/uploads.ts b/apps/api/src/selfhost/hosted-git/uploads.ts new file mode 100644 index 0000000000..7031eea6ed --- /dev/null +++ b/apps/api/src/selfhost/hosted-git/uploads.ts @@ -0,0 +1,52 @@ +/** Tracks fetch readers so deletion can close streams before dropping their backing packs. */ +export class HostedGitUploads { + private slots = new Set<{ done: Promise; cancel?: () => Promise }>(); + start() { + let finish = () => {}; + const slot: { done: Promise; cancel?: () => Promise } = { + done: new Promise((resolve) => { + finish = resolve; + }), + }; + this.slots.add(slot); + const release = () => { + this.slots.delete(slot); + finish(); + }; + return { + release, + response: (response: Response): Response => { + if (!response.body || !this.slots.has(slot)) return response; + const reader = response.body.getReader(); + slot.cancel = async () => { + await reader.cancel().catch(() => undefined); + release(); + }; + return new Response( + new ReadableStream({ + async pull(controller) { + try { + const { done, value } = await reader.read(); + if (done) { + release(); + controller.close(); + } else controller.enqueue(value); + } catch (error) { + release(); + controller.error(error); + } + }, + cancel: slot.cancel, + }), + { status: response.status, headers: response.headers } + ); + }, + }; + } + async close(): Promise { + const slots = [...this.slots]; + await Promise.all(slots.map((slot) => slot.cancel?.())); + // Request bodies have a work deadline; their handlers release after seeing the delete fence. + await Promise.all(slots.map((slot) => slot.done)); + } +} diff --git a/apps/api/src/services/admin-setting-definitions.ts b/apps/api/src/services/admin-setting-definitions.ts index 122490496f..42cdb32abf 100644 --- a/apps/api/src/services/admin-setting-definitions.ts +++ b/apps/api/src/services/admin-setting-definitions.ts @@ -19,6 +19,7 @@ import { type OutboundSettingName } from './admin-settings-outbound-definitions' import { type AgentEmailSettingName } from './agent-email/setting-definitions'; import { type AgentModelSettingKey } from './agent-models/settings-definition'; import type { AiProxySettingName } from './ai-proxy-settings'; +import type { RepositorySettingName } from './artifacts/settings'; import { type ConnectorReadSettingName } from './connector-read-settings-definition'; import { CONNECTOR_DEFAULTS, @@ -73,6 +74,7 @@ export type AdminSettingName = | InfomaniakSettingName | InstructionBudgetSettingName | OperationsTelemetrySettingName + | RepositorySettingName | OutboundSettingName | 'operations.projectDataRowUsageIntervalMs' | 'chat.profileUsageWindowDays' diff --git a/apps/api/src/services/admin-settings-registry.ts b/apps/api/src/services/admin-settings-registry.ts index 7eab89d3ce..438633da6f 100644 --- a/apps/api/src/services/admin-settings-registry.ts +++ b/apps/api/src/services/admin-settings-registry.ts @@ -18,6 +18,7 @@ import { OUTBOUND_SETTINGS } from './admin-settings-outbound-definitions'; import { OVERVIEW_BRIEF_SETTINGS } from './admin-settings-overview-brief-definitions'; import { PROJECT_EVENT_SETTINGS } from './admin-settings-project-event-definitions'; import { AI_PROXY_SETTINGS } from './ai-proxy-settings'; +import { REPOSITORY_SETTINGS } from './artifacts/settings'; import { llmEndpointSettingDefinitions } from './llm-endpoint-settings'; export { type AdminSettingDefinition, @@ -35,6 +36,7 @@ export { OPERATOR_DEFAULTS, } from './admin-setting-definitions'; const definitions = [ + ...REPOSITORY_SETTINGS, ...LIBRARY_MULTIPART_SETTINGS, ...ACCOUNT_LINKING_SETTINGS, ...llmEndpointSettingDefinitions(), diff --git a/apps/api/src/services/hosted-git/backend.ts b/apps/api/src/services/artifacts/backend.ts similarity index 74% rename from apps/api/src/services/hosted-git/backend.ts rename to apps/api/src/services/artifacts/backend.ts index 40aa4feb0a..8db5426b28 100644 --- a/apps/api/src/services/hosted-git/backend.ts +++ b/apps/api/src/services/artifacts/backend.ts @@ -17,6 +17,18 @@ import type { Env } from '../../env'; export type ArtifactsBackend = NonNullable; +type ArtifactsRepo = Awaited>; + +/** Preserve the native binding's RPC contract; fallback tokens can bind runtime identity. */ +export function createArtifactsRuntimeToken( + env: Env, + repo: ArtifactsRepo, + scope: 'read' | 'write', + ttl: number, + context: NonNullable[2]> +): ReturnType { + return env.ARTIFACTS ? repo.createToken(scope, ttl) : repo.createToken(scope, ttl, context); +} /** Builds the fallback backend for an install with no Artifacts binding, or returns null. */ export type ArtifactsBackendFallback = (env: Env) => ArtifactsBackend | null; @@ -46,3 +58,11 @@ export function resolveArtifactsBackendForCleanup(env: Env): ArtifactsBackend | export function isArtifactsAvailable(env: Env): boolean { return resolveArtifactsBackend(env) !== null; } + +/** Native RPC stubs synthesize properties for unknown methods; never probe optional extensions. */ +export function artifactsBackendExtensions( + env: Env, + backend: ArtifactsBackend +): Pick { + return env.ARTIFACTS ? {} : backend; +} diff --git a/apps/api/src/services/artifacts/settings.ts b/apps/api/src/services/artifacts/settings.ts new file mode 100644 index 0000000000..93b26a4534 --- /dev/null +++ b/apps/api/src/services/artifacts/settings.ts @@ -0,0 +1,30 @@ +/** Resource policy metadata for an optional repository backend; contains no git implementation. */ +import { type AdminSettingDefinition, integerDefinition } from '../admin-setting-definitions'; + +export const REPOSITORY_POLICY_DEFAULTS = { + maxPushBytes: 64 * 1024 * 1024, + maxRepoObjects: 30_000, + // At 255 characters per ref, even UTF-8 advertisements stay below 12 MiB. + maxRepoRefs: 10_000, + maxRepoBytes: 256 * 1024 * 1024, + maxObjectBytes: 16 * 1024 * 1024, + maxInflatedBytes: 128 * 1024 * 1024, + maxDeltaDepth: 100, + workTimeoutMs: 120_000, + maxGcAttempts: 3, +} as const; + +export type RepositoryPolicyKey = keyof typeof REPOSITORY_POLICY_DEFAULTS; +export type RepositorySettingName = `repositories.${RepositoryPolicyKey}`; + +export const REPOSITORY_SETTINGS: readonly AdminSettingDefinition[] = ( + Object.entries(REPOSITORY_POLICY_DEFAULTS) as [RepositoryPolicyKey, number][] +).map(([key, value]) => + integerDefinition( + `repositories.${key}`, + value, + 'Operations', + `Resource bound ${key} for the installation's optional local repository backend.`, + { min: 1, max: value } + ) +); diff --git a/apps/api/src/vendor/dgit/LICENSE b/apps/api/src/vendor/dgit/LICENSE new file mode 100644 index 0000000000..57474920ff --- /dev/null +++ b/apps/api/src/vendor/dgit/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Divy Srivastava + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apps/api/src/vendor/dgit/UPSTREAM.md b/apps/api/src/vendor/dgit/UPSTREAM.md new file mode 100644 index 0000000000..ef544b9276 --- /dev/null +++ b/apps/api/src/vendor/dgit/UPSTREAM.md @@ -0,0 +1,46 @@ +# Vendored dgit git core + +- Upstream: https://github.com/littledivy/durable-git (npm `durable-git` 0.0.8) +- Commit: `d5eba04eda584b855a1bde1f86a836b751c378c0` (tag v0.0.8, 2026-08-21) +- Licence: MIT, see `LICENSE` in this directory (copyright Divy Srivastava). + +## What is here + +Vendored files carry `/* eslint-disable */` and `// @ts-nocheck` headers. Upstream typechecks under `strict` but not SAM's +`noUncheckedIndexedAccess`, and follows its own lint style. `protocol.ts` and `packstore.ts` also +carry a `// FILE SIZE EXCEPTION` line. SAM security adaptations are listed below. + +`git/` is adapted from upstream `src/git/`, minus the three modules only the web UI +used (`blame.ts`, `diff.ts`, `snapshot.ts`). Upstream's Worker router (`mod.ts`), registry +Durable Object (`registry.ts`), cgit-style UI (`ui/`) and its `RepoCell` class are not vendored. + +Only the self-host build contains this code; the Cloudflare Worker's entry never imports it (see +`apps/api/src/selfhost/hosted-git.ts`). + +SAM's Durable Object, `apps/api/src/selfhost/hosted-git/hosted-git-repo.ts`, is adapted from +upstream `src/repo.ts` (`RepoCell`): it keeps the smart-HTTP protocol paths (`info/refs`, +`git-upload-pack`, `git-receive-pack`), delete and the GC alarm, and adds SAM's push and +repository caps. Authentication is SAM's (`apps/api/src/selfhost/hosted-git/`), not upstream's. + +## Updating + +Copy the same files from a newer upstream commit, update the commit above, and run the hosted git +conformance suite (`pnpm --filter @simple-agent-manager/api test:hosted-git`). Preserve and reapply the SAM resource policy and SQL safety changes below; an upstream copy alone would remove these protections. Keep repository authentication and lifecycle policy in the self-host adapter. + +## H2 resource policy + +SAM adds `git/budget.ts` around pack ingest, reads and delta application. Every request and GC invocation carries a separate cumulative decompression and deadline budget, including streamed responses. Object size is checked before allocation and while inflating, delta targets before allocation, and delta depth before traversal. Policy values come from the optional repository backend's typed admin settings. These are deliberate security changes to the vendored code; this directory is not byte-for-byte upstream. + +SQL identifiers use static allowlisted statements, and variable-sized bind lists are split below the runtime parameter ceiling. The additional GC admission and response accounting checks are covered by the hosted git suite. + +- PackStore exposes its existing incomplete-pack sweep as `cleanupOrphans`, so failed uploads can reclaim quota immediately and GC can retry storage cleanup independently of another admitted push. + +- Ref admission rejects `.lock` suffixes on every path component and a final dot, matching Git check-ref-format; the full rule matrix also retains SAM conservative character and length bounds. The predicate lives in `apps/api/src/lib/git-ref-name.ts` (`isValidGitRefName`), which project creation also uses, so a default branch SAM accepts can always be pushed. + +- Push connectivity is proven per command by walking from the new tip until it reaches an existing ref tip, with or without a reachable cache. Each walk collects into a scratch set and joins the trusted set only when its closure is complete, so a failed command cannot vouch for a later one. Upstream's cache-less SQL check (`packComplete`, `push_edges`) is removed: it trusted every object outside the new pack, and SAM keeps a rejected pack's objects until GC. + +- Push admission reads no objects to seed the validated set (upstream peeled every ref tip on every push, so a few large tips exhausted the decompression budget for every later push, deletions included), checks the type git requires at every walked edge, refuses non-commits on `refs/heads/*` and directory/file ref conflicts (a ref named by more than one command is refused for all of them, so a deletion that would lose its CAS cannot free a nested name), rejects an unparseable object for its own command only, and memoizes failed walks within a push. Deleting a ref that does not exist succeeds without queueing GC. Pushed commits, tags and trees must have the shape git itself reads, checked on raw bytes (a first line that is exactly `tree ` or `object `, header order, newline-terminated headers, tag headers, tree modes, and unique names of at most 255 bytes other than `.`, `..`, `.git` and its NTFS forms, with no `.gitmodules` symlink in any of its NTFS forms); an ancestry check that exhausts the work budget counts the update as forced instead of failing the push. Admission never trusts the reachable cache. + +- The reachable cache is stamped only with the ref version its clone walk started from, unstamps the cache before rewriting it, and lets only the latest of overlapping saves write or stamp; `commitPush` extends the cache only if it is still stamped current at commit time. A push during a clone walk, a second clone's rewrite, or a push during a rewrite therefore cannot leave a stale or partial set marked current; GC invalidates the cache whenever it deletes objects. + +- PackStore adds `packIds`, `packObjectOids` and `dropPack`. Hosted git GC drops whole packs that hold no reachable object and no delta base before it inflates anything, and keeps delta bases only while packs are kept (migration stores reachable objects whole). diff --git a/apps/api/src/vendor/dgit/git/budget.ts b/apps/api/src/vendor/dgit/git/budget.ts new file mode 100644 index 0000000000..93227d2718 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/budget.ts @@ -0,0 +1,92 @@ +/** SAM resource policy around the vendored git engine; never imported by Cloudflare. */ +import { AsyncLocalStorage } from 'node:async_hooks'; + +export interface GitWorkLimits { + maxObjectBytes: number; + maxInflatedBytes: number; + maxDeltaDepth: number; + workTimeoutMs: number; +} + +const budgets = new AsyncLocalStorage<{ + limits: GitWorkLimits; + remaining: number; + deadline: number; +}>(); + +export function withGitWorkBudget(limits: GitWorkLimits, action: () => T): T { + return budgets.run( + { limits, remaining: limits.maxInflatedBytes, deadline: Date.now() + limits.workTimeoutMs }, + action + ); +} + +export function gitWorkLimits(): GitWorkLimits { + const budget = budgets.getStore(); + if (!budget) throw new Error('git resource budget is missing'); + if (Date.now() >= budget.deadline) throw new Error('git work exceeds time budget'); + return budget.limits; +} + +/** Charge output before storing/allocating it, including repeated reads and delta outputs. */ +export function chargeGitWork(bytes: number): void { + const limits = gitWorkLimits(); + if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > limits.maxObjectBytes) { + throw new Error('git object exceeds inflated size limit'); + } + const budget = budgets.getStore(); + if (!budget) throw new Error('git resource budget is missing'); + if (bytes > budget.remaining) throw new Error('git work exceeds decompression budget'); + budget.remaining -= bytes; +} + +/** A stalled client cannot hold a repository's receive lock past its request budget. */ +export async function readGitChunk( + reader: ReadableStreamDefaultReader +): Promise> { + gitWorkLimits(); + const budget = budgets.getStore(); + if (!budget) throw new Error('git resource budget is missing'); + const remaining = budget.deadline - Date.now(); + let timer: ReturnType | undefined; + try { + return await Promise.race([ + reader.read(), + new Promise((_, reject) => { + timer = setTimeout(() => { + reject(new Error('git work exceeds time budget')); + void reader.cancel().catch(() => undefined); + }, remaining); + }), + ]); + } finally { + if (timer) clearTimeout(timer); + } +} + +/** Keep resource accounting attached when the runtime pulls a response after fetch returns. */ +export function bindGitResponse(response: Response): Response { + if (!response.body) return response; + const budget = budgets.getStore(); + if (!budget) throw new Error('git resource budget is missing'); + const reader = response.body.getReader(); + const body = new ReadableStream({ + pull: (controller) => + budgets.run(budget, async () => { + try { + const { done, value } = await readGitChunk(reader); + if (done) controller.close(); + else controller.enqueue(value); + } catch (error) { + void reader.cancel().catch(() => undefined); + controller.error(error); + } + }), + cancel: (reason) => reader.cancel(reason), + }); + return new Response(body, { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); +} diff --git a/apps/api/src/vendor/dgit/git/multipart.ts b/apps/api/src/vendor/dgit/git/multipart.ts new file mode 100644 index 0000000000..8200b69948 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/multipart.ts @@ -0,0 +1,108 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +import { concat } from "./util"; + +/** In-progress R2 multipart upload for one pack object (clone cache or raw store). */ +export interface MultipartPackUpload { + uploadPart(data: Uint8Array): Promise; + complete(): Promise; + abort(): Promise; +} + +/** Uniform multipart part size. R2 requires every part but the last to be the + * same size and >= 5 MiB; 16 MiB parts cap a pack at 16 MiB * 10,000 = 160 GiB + * while holding at most one part in isolate memory at a time. */ +export const R2_PART_SIZE = 16 * 1024 * 1024; + +/** + * Buffers a streamed pack into fixed-size R2 multipart parts. Chunks are copied + * on push (callers hand out views into buffers that later reads evict). `drain` + * uploads every whole 16 MiB part and keeps the sub-part remainder, so isolate + * memory never holds more than ~one part; `finish` flushes the final (short) + * part and completes; any failure aborts so R2 is left with no partial object. + * Uniform part size (exactly R2_PART_SIZE, last excepted) is what satisfies R2's + * equal-size-parts rule. + */ +export class MultipartCapture { + private chunks: Uint8Array[] = []; + private len = 0; + private failed = false; + private completed = false; + constructor(private mp: MultipartPackUpload) {} + + /** True once a part upload or complete/abort has failed (no R2 object exists). */ + get aborted(): boolean { + return this.failed; + } + + push(chunk: Uint8Array): void { + if (this.failed) return; + this.chunks.push(chunk.slice()); + this.len += chunk.length; + } + + async drain(): Promise { + while (!this.failed && this.len >= R2_PART_SIZE) { + const merged = concat(this.chunks); + try { + await this.mp.uploadPart(merged.subarray(0, R2_PART_SIZE)); + } catch { + await this.abort(); + return; + } + const rest = merged.slice(R2_PART_SIZE); + this.chunks = rest.length ? [rest] : []; + this.len = rest.length; + } + } + + async finish(): Promise { + if (this.failed) return; + try { + if (this.len) await this.mp.uploadPart(concat(this.chunks)); + await this.mp.complete(); + this.completed = true; + } catch { + await this.abort(); + } + this.chunks = []; + this.len = 0; + } + + async abort(): Promise { + if (this.failed || this.completed) return; + this.failed = true; + this.chunks = []; + this.len = 0; + try { + await this.mp.abort(); + } catch { + // best effort: an un-aborted multipart auto-expires + } + } +} + +/** Begin a raw R2 multipart upload under `key`. Returns null (caller falls back) + * if R2 refuses — celld deliberately makes createMultipartUpload throw. */ +export async function beginRawMultipart( + bucket: R2Bucket, + key: string +): Promise { + try { + const mp = await bucket.createMultipartUpload(key); + const parts: R2UploadedPart[] = []; + return { + uploadPart: async (data) => { + parts.push(await mp.uploadPart(parts.length + 1, data)); + }, + complete: async () => { + await mp.complete(parts); + }, + abort: async () => { + await mp.abort(); + }, + }; + } catch { + return null; + } +} diff --git a/apps/api/src/vendor/dgit/git/objects.ts b/apps/api/src/vendor/dgit/git/objects.ts new file mode 100644 index 0000000000..02445715cd --- /dev/null +++ b/apps/api/src/vendor/dgit/git/objects.ts @@ -0,0 +1,182 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +import { te, td, toHex, concat, sha1hex, isOid } from "./util"; + +export type ObjType = "commit" | "tree" | "blob" | "tag"; + +/** Thrown for any malformed/attacker-crafted object body. */ +export class GitParseError extends Error { + constructor(msg: string) { + super(msg); + this.name = "GitParseError"; + } +} + +export const TYPE_NUM: Record = { commit: 1, tree: 2, blob: 3, tag: 4 }; +export const NUM_TYPE: Record = { 1: "commit", 2: "tree", 3: "blob", 4: "tag" }; + +export function objectHeader(type: ObjType, size: number): Uint8Array { + return te.encode(`${type} ${size}\0`); +} + +export function hashObject(type: ObjType, data: Uint8Array): string { + return sha1hex(concat([objectHeader(type, data.length), data])); +} + +export interface Person { + name: string; + email: string; + /** unix seconds */ + time: number; + tz: string; +} + +export interface Commit { + tree: string; + parents: string[]; + author: Person; + committer: Person; + message: string; + /** first line of the message */ + subject: string; +} + +export interface Tag { + object: string; + type: string; + tag: string; + tagger: Person | null; + message: string; +} + +export interface TreeEntry { + mode: string; // e.g. "100644", "40000", "120000", "160000" + name: string; + oid: string; +} + +function parsePerson(line: string): Person { + // "Name 1234567890 +0100". Parsed with linear scans, not a + // backtracking regex: an attacker controls this line and can make it + // megabytes long, so `/(.*?) <(.*?)>/` would be a quadratic-scan DoS. + const lt = line.indexOf(" <"); + const gt = lt < 0 ? -1 : line.indexOf(">", lt + 2); + if (lt < 0 || gt < 0) return { name: line, email: "", time: 0, tz: "+0000" }; + const name = line.slice(0, lt); + const email = line.slice(lt + 2, gt); + const rest = line.slice(gt + 1).trim().split(" "); + const time = rest.length ? parseInt(rest[0], 10) : 0; + const tz = rest.length > 1 && /^[+-]\d{4}$/.test(rest[1]) ? rest[1] : "+0000"; + return { name, email, time: Number.isFinite(time) ? time : 0, tz }; +} + +function splitHeaders(text: string): { headers: [string, string][]; message: string } { + const nn = text.indexOf("\n\n"); + const head = nn === -1 ? text : text.slice(0, nn); + const message = nn === -1 ? "" : text.slice(nn + 2); + const headers: [string, string][] = []; + // continuation pieces are collected per-header and joined once at the end: + // appending with `+=` in the loop is O(n^2) on a crafted object with a huge + // multi-line header value (e.g. a giant gpgsig). + const cont: string[][] = []; + for (const line of head.split("\n")) { + // continuation lines (gpgsig etc.) start with a space; append to previous + if (line.startsWith(" ") && headers.length) { + cont[cont.length - 1].push(line.slice(1)); + continue; + } + const sp = line.indexOf(" "); + if (sp > 0) { + headers.push([line.slice(0, sp), line.slice(sp + 1)]); + cont.push([]); + } + } + for (let i = 0; i < headers.length; i++) { + if (cont[i].length) headers[i][1] += "\n" + cont[i].join("\n"); + } + return { headers, message }; +} + +export function parseCommit(data: Uint8Array): Commit { + const { headers, message } = splitHeaders(td.decode(data)); + const c: Commit = { + tree: "", + parents: [], + author: { name: "", email: "", time: 0, tz: "+0000" }, + committer: { name: "", email: "", time: 0, tz: "+0000" }, + message, + subject: message.split("\n", 1)[0] ?? "", + }; + let sawTree = false; + for (const [k, v] of headers) { + if (k === "tree") { + // tree/parent oids feed the connectivity walk verbatim: reject anything + // not a real oid so a crafted value can never be treated as an object id. + if (sawTree) throw new GitParseError("commit has duplicate tree header"); + if (!isOid(v)) throw new GitParseError("commit has malformed tree oid"); + c.tree = v; + sawTree = true; + } else if (k === "parent") { + if (!isOid(v)) throw new GitParseError("commit has malformed parent oid"); + c.parents.push(v); + } else if (k === "author") c.author = parsePerson(v); + else if (k === "committer") c.committer = parsePerson(v); + } + if (!sawTree) throw new GitParseError("commit missing tree header"); + return c; +} + +export function parseTag(data: Uint8Array): Tag { + const { headers, message } = splitHeaders(td.decode(data)); + const t: Tag = { object: "", type: "", tag: "", tagger: null, message }; + let sawObject = false; + for (const [k, v] of headers) { + if (k === "object") { + if (sawObject) throw new GitParseError("tag has duplicate object header"); + if (!isOid(v)) throw new GitParseError("tag has malformed object oid"); + t.object = v; + sawObject = true; + } else if (k === "type") t.type = v; + else if (k === "tag") t.tag = v; + else if (k === "tagger") t.tagger = parsePerson(v); + } + if (!sawObject) throw new GitParseError("tag missing object header"); + return t; +} + +export function parseTree(data: Uint8Array): TreeEntry[] { + const entries: TreeEntry[] = []; + let pos = 0; + while (pos < data.length) { + let sp = pos; + while (sp < data.length && data[sp] !== 0x20) sp++; + if (sp >= data.length) throw new GitParseError("malformed tree"); + const mode = td.decode(data.subarray(pos, sp)); + let nul = sp + 1; + while (nul < data.length && data[nul] !== 0) nul++; + if (nul >= data.length || nul + 21 > data.length) throw new GitParseError("malformed tree"); + const name = td.decode(data.subarray(sp + 1, nul)); + const oid = toHex(data.subarray(nul + 1, nul + 21)); + entries.push({ mode, name, oid }); + pos = nul + 21; + } + return entries; +} + +export function isTreeMode(mode: string): boolean { + return mode === "40000" || mode === "040000"; +} + +export function isGitlinkMode(mode: string): boolean { + return mode === "160000"; +} + +/** Render a tree-entry mode the way cgit/ls-tree does: d rwx r-x r-x etc. */ +export function modeString(mode: string): string { + const m = parseInt(mode, 8); + if (isTreeMode(mode)) return "d---------"; + if (isGitlinkMode(mode)) return "m---------"; + if ((m & 0o170000) === 0o120000) return "lrwxrwxrwx"; + const bits = (n: number) => `${n & 4 ? "r" : "-"}${n & 2 ? "w" : "-"}${n & 1 ? "x" : "-"}`; + return `-${bits((m >> 6) & 7)}${bits((m >> 3) & 7)}${bits(m & 7)}`; +} diff --git a/apps/api/src/vendor/dgit/git/oidset.ts b/apps/api/src/vendor/dgit/git/oidset.ts new file mode 100644 index 0000000000..0af9c7d6ab --- /dev/null +++ b/apps/api/src/vendor/dgit/git/oidset.ts @@ -0,0 +1,167 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +import { fromHex, toHex } from "./util"; + +/** + * Memory-compact set + insertion-ordered list of object ids. A JS + * Set of 40-char hex strings costs ~100 bytes per entry — at + * Linux scale (10M objects) that is gigabytes. This stores raw 20-byte + * digests in typed arrays: ~20B per entry plus a u32 open-addressing table. + * + * A set can also carry a *tagged sub-set* (mark/isMarked/markedAt): one bit + * per entry plus a u32 index list. Two nested roles — e.g. the object walk's + * "visited" and its strict subset "send" — then cost ~28B/object in one set + * instead of ~56B in two. + */ +export class OidSet { + private table: Uint32Array; // 1-based indices into the entry list; 0 = empty + private mask: number; + private data: Uint8Array; // 20 bytes per entry, insertion order + private count = 0; + // tagged sub-set, allocated lazily on first mark() + private marks: Uint8Array | null = null; // one bit per entry index + private markedIdx: Uint32Array | null = null; // tagged entry indices, insertion order + private markedCount = 0; + + constructor(expected = 1024) { + let cap = 2048; + while (cap < expected * 2) cap *= 2; + this.table = new Uint32Array(cap); + this.mask = cap - 1; + this.data = new Uint8Array(Math.max(expected, 1024) * 20); + } + + get size(): number { + return this.count; + } + + /** Number of entries in the tagged sub-set. */ + get markedSize(): number { + return this.markedCount; + } + + private hashAt(bytes: Uint8Array, off: number): number { + // oids are uniformly random; the first 4 bytes are a fine hash + return ((bytes[off] << 24) | (bytes[off + 1] << 16) | (bytes[off + 2] << 8) | bytes[off + 3]) >>> 0; + } + + private equalsEntry(idx: number, bytes: Uint8Array, off: number): boolean { + const base = idx * 20; + for (let i = 0; i < 20; i++) { + if (this.data[base + i] !== bytes[off + i]) return false; + } + return true; + } + + private grow(): void { + const newTable = new Uint32Array(this.table.length * 2); + const newMask = newTable.length - 1; + for (let i = 0; i < this.count; i++) { + let slot = this.hashAt(this.data, i * 20) & newMask; + while (newTable[slot] !== 0) slot = (slot + 1) & newMask; + newTable[slot] = i + 1; + } + this.table = newTable; + this.mask = newMask; + } + + /** Make room for the entry about to be written at index `this.count`. */ + private growData(): void { + if ((this.count + 1) * 20 > this.data.length) { + const bigger = new Uint8Array(this.data.length * 2); + bigger.set(this.data); + this.data = bigger; + } + if (this.marks && (this.count >> 3) >= this.marks.length) { + const bigger = new Uint8Array(this.marks.length * 2); + bigger.set(this.marks); + this.marks = bigger; + } + } + + /** Entry index of `bytes`, inserting it when absent. */ + private indexOrInsert(bytes: Uint8Array, off: number): number { + if ((this.count + 1) * 2 > this.table.length) this.grow(); + let slot = this.hashAt(bytes, off) & this.mask; + while (this.table[slot] !== 0) { + if (this.equalsEntry(this.table[slot] - 1, bytes, off)) return this.table[slot] - 1; + slot = (slot + 1) & this.mask; + } + this.growData(); + this.data.set(bytes.subarray(off, off + 20), this.count * 20); + this.table[slot] = ++this.count; + return this.count - 1; + } + + /** Adds a hex oid; returns false if it was already present. */ + addHex(hex: string): boolean { + return this.addBytes(fromHex(hex), 0); + } + + addBytes(bytes: Uint8Array, off: number): boolean { + const before = this.count; + // a freshly inserted entry always lands at index `before` + return this.indexOrInsert(bytes, off) === before; + } + + hasHex(hex: string): boolean { + return this.hasBytes(fromHex(hex), 0); + } + + /** Insertion-order entry index of `hex`, or -1 if absent. */ + indexOfHex(hex: string): number { + return this.indexOf(fromHex(hex), 0); + } + + hasBytes(bytes: Uint8Array, off: number): boolean { + return this.indexOf(bytes, off) >= 0; + } + + /** Entry index of `bytes`, or -1. */ + private indexOf(bytes: Uint8Array, off: number): number { + let slot = this.hashAt(bytes, off) & this.mask; + while (this.table[slot] !== 0) { + if (this.equalsEntry(this.table[slot] - 1, bytes, off)) return this.table[slot] - 1; + slot = (slot + 1) & this.mask; + } + return -1; + } + + /** Hex oid of the i-th inserted entry. */ + atHex(i: number): string { + return toHex(this.data.subarray(i * 20, i * 20 + 20)); + } + + /** + * Adds `hex` if needed and puts it in the tagged sub-set. + * Returns false if it was already tagged. + */ + markHex(hex: string): boolean { + const idx = this.indexOrInsert(fromHex(hex), 0); + if (!this.marks) this.marks = new Uint8Array(((this.data.length / 20) >> 3) + 1); + const byte = idx >> 3; + const bit = 1 << (idx & 7); + if (this.marks[byte] & bit) return false; + this.marks[byte] |= bit; + if (!this.markedIdx) this.markedIdx = new Uint32Array(1024); + if (this.markedCount === this.markedIdx.length) { + const bigger = new Uint32Array(this.markedIdx.length * 2); + bigger.set(this.markedIdx); + this.markedIdx = bigger; + } + this.markedIdx[this.markedCount++] = idx; + return true; + } + + isMarkedHex(hex: string): boolean { + if (!this.marks) return false; + const idx = this.indexOf(fromHex(hex), 0); + return idx >= 0 && (this.marks[idx >> 3] & (1 << (idx & 7))) !== 0; + } + + /** Hex oid of the i-th entry of the tagged sub-set. */ + markedAtHex(i: number): string { + const idx = this.markedIdx![i]; + return toHex(this.data.subarray(idx * 20, idx * 20 + 20)); + } +} diff --git a/apps/api/src/vendor/dgit/git/pack.ts b/apps/api/src/vendor/dgit/git/pack.ts new file mode 100644 index 0000000000..f2099646ca --- /dev/null +++ b/apps/api/src/vendor/dgit/git/pack.ts @@ -0,0 +1,127 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +import { chargeGitWork } from "./budget"; +import { te, fromHex, Sha1 } from "./util"; +import { deflate } from "./zlib"; +import { ObjType, TYPE_NUM } from "./objects"; + +export function applyDelta(base: Uint8Array, delta: Uint8Array): Uint8Array { + let pos = 0; + // bounded read: a truncated/crafted delta must throw, never read past the end + // (which would fold `undefined` into offsets/sizes and corrupt the result). + const next = (): number => { + if (pos >= delta.length) throw new Error("delta truncated"); + return delta[pos++]; + }; + const varint = () => { + let r = 0, shift = 0, b: number; + do { + b = next(); + r += (b & 0x7f) * 2 ** shift; + shift += 7; + } while (b & 0x80); + return r; + }; + const srcSize = varint(); + const tgtSize = varint(); + if (srcSize !== base.length) throw new Error("delta base size mismatch"); + chargeGitWork(tgtSize); + const out = new Uint8Array(tgtSize); + let op = 0; + while (pos < delta.length) { + const cmd = next(); + if (cmd & 0x80) { + // copy from base + let off = 0, size = 0; + if (cmd & 0x01) off = next(); + if (cmd & 0x02) off |= next() << 8; + if (cmd & 0x04) off |= next() << 16; + if (cmd & 0x08) off += next() * 0x1000000; + if (cmd & 0x10) size = next(); + if (cmd & 0x20) size |= next() << 8; + if (cmd & 0x40) size |= next() << 16; + if (size === 0) size = 0x10000; + if (off + size > base.length) throw new Error("delta copy out of range"); + if (op + size > tgtSize) throw new Error("delta copy overflows target"); + out.set(base.subarray(off, off + size), op); + op += size; + } else if (cmd) { + // insert literal + if (pos + cmd > delta.length) throw new Error("delta literal truncated"); + if (op + cmd > tgtSize) throw new Error("delta literal overflows target"); + out.set(delta.subarray(pos, pos + cmd), op); + op += cmd; + pos += cmd; + } else { + throw new Error("invalid delta opcode 0"); + } + } + if (op !== tgtSize) throw new Error("delta target size mismatch"); + return out; +} + +const REF_DELTA_NUM = 7; + +function encodeTypeSizeNum(typeNum: number, size: number): Uint8Array { + const bytes: number[] = []; + let first = (typeNum << 4) | (size & 0x0f); + size = Math.floor(size / 16); + while (size > 0) { + bytes.push(first | 0x80); + first = size & 0x7f; + size = Math.floor(size / 128); + } + bytes.push(first); + return new Uint8Array(bytes); +} + +function encodeTypeSize(type: ObjType, size: number): Uint8Array { + return encodeTypeSizeNum(TYPE_NUM[type], size); +} + +/** + * Incremental packfile writer: emits raw pack bytes through `emit` while + * keeping the running SHA-1 for the trailer, so packs can be streamed + * without ever materializing the whole file. + */ +export class PackWriter { + private sha = new Sha1(); + + constructor(private emit: (chunk: Uint8Array) => void) {} + + private out(chunk: Uint8Array): void { + this.sha.update(chunk); + this.emit(chunk); + } + + header(count: number): void { + const h = new Uint8Array(12); + h.set(te.encode("PACK"), 0); + const dv = new DataView(h.buffer); + dv.setUint32(4, 2); + dv.setUint32(8, count); + this.out(h); + } + + object(type: ObjType, data: Uint8Array): void { + this.out(encodeTypeSize(type, data.length)); + this.out(deflate(data)); + } + + /** Copy a stored full entry verbatim (already zlib-compressed). */ + rawFull(type: ObjType, entrySize: number, compressed: Uint8Array): void { + this.out(encodeTypeSize(type, entrySize)); + this.out(compressed); + } + + /** Copy a stored delta entry verbatim, addressed as a ref-delta. */ + rawDelta(entrySize: number, baseOid: string, compressed: Uint8Array): void { + this.out(encodeTypeSizeNum(REF_DELTA_NUM, entrySize)); + this.out(fromHex(baseOid)); + this.out(compressed); + } + + finish(): void { + this.emit(this.sha.digest()); // trailer is not part of the hashed content + } +} diff --git a/apps/api/src/vendor/dgit/git/packstore.ts b/apps/api/src/vendor/dgit/git/packstore.ts new file mode 100644 index 0000000000..5fa50c8e84 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/packstore.ts @@ -0,0 +1,936 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +// FILE SIZE EXCEPTION: vendored dgit core with SAM resource bounds and static SQL identifiers (see ../UPSTREAM.md) +import pako from "pako"; +import { inflate as inflateAll } from "./zlib"; +import { chargeGitWork, gitWorkLimits, readGitChunk } from "./budget"; +import { td, concat, toHex, Sha1 } from "./util"; +import { Sha1Dc, Sha1CollisionError } from "./sha1"; +import { ObjType, NUM_TYPE, objectHeader } from "./objects"; +import { applyDelta } from "./pack"; +import { MultipartCapture, beginRawMultipart } from "./multipart"; + +export const PACK_CHUNK = 1024 * 1024; +/** a pushed pack goes to R2 only when the binding is present AND the pack is at + * least this large; smaller packs stay in SQLite (local ~ms writes/reads). R2's + * purpose is escaping the 10 GB per-DO SQLite cap, which only large repos hit. */ +export const R2_PACK_MIN_BYTES = 16 * 1024 * 1024; +/** real Workers isolates have a hard 128MB total; self-hosted celld nodes run multi-GB heaps */ +const TIGHT_MEMORY = typeof caches !== "undefined"; +const MAX_BUFFERED_ENTRY = (TIGHT_MEMORY ? 8 : 32) * 1024 * 1024; +/** full entries up to this size are kept in cache — they are likely delta bases */ +const CACHE_ENTRY_LIMIT = (TIGHT_MEMORY ? 2 : 4) * 1024 * 1024; +/** recent entry offsets kept in memory for ofs-delta base resolution */ +const OFFSET_WINDOW = 150_000; +/** + * Decoded pack chunks kept hot for readRaw. The clone loop reads one object + * per call in walk order, so without this every object re-SELECTs and + * re-decodes a whole 1MB row. A handful of 1MB chunks covers any delta chain + * and the locality of the walk. + */ +const RAW_CHUNK_CACHE = TIGHT_MEMORY ? 4 : 8; +/** + * Hard cap on delta base-chain length when resolving an object. git's default + * pack depth is 50; 50000 leaves enormous headroom for legitimately deep packs + * while a crafted unbounded chain is rejected instead of looping forever. The + * base walk is iterative (not recursive) and separately cycle-checked via a + * seen-set, so this bounds chain length rather than guarding stack depth. + */ + +/** + * pako output-chunk size. The default (64 KiB) is large enough that V8 keeps + * every inflate's backing store in its array-buffer arena, so streaming a pack + * one Inflate per object commits arena proportional to the object count — a + * 53MB pack peaked near 250MB of buffers this way. 16 KiB chunks are collected + * promptly, holding inflate memory to a bounded working set regardless of pack + * size. + */ +const INFLATE_CHUNK = 16 * 1024; + +export interface ObjRec { + type: ObjType; + data: Uint8Array; +} + +export interface PackedEntry { + oid: string; + packId: number; + offset: number; + dataOff: number; + dataLen: number; + type: ObjType; + size: number; + entrySize: number; + baseOid: string | null; +} + +export type ExternalResolver = (oid: string) => ObjRec | null; + +/** Byte-budgeted LRU cache of inflated objects (delta-chain bases, hot commits/trees). */ +export class ObjCache { + private map = new Map(); + private bytes = 0; + + constructor(private budget: number) {} + + get(oid: string): ObjRec | undefined { + const hit = this.map.get(oid); + if (hit) { + this.map.delete(oid); + this.map.set(oid, hit); + } + return hit; + } + + put(oid: string, obj: ObjRec): void { + if (obj.data.length > this.budget / 4) return; + if (this.map.has(oid)) return; + this.map.set(oid, obj); + this.bytes += obj.data.length; + while (this.bytes > this.budget) { + const oldest = this.map.keys().next().value as string; + this.bytes -= this.map.get(oldest)!.data.length; + this.map.delete(oldest); + } + } +} + +// ingest is strictly sequential, so scratch hashers serve every object. The +// SHA-1DC pair is used only when collision detection is enabled; the plain +// streaming hasher covers the flag-off huge-object path. +const scratchSha = new Sha1Dc(); +const streamSha = new Sha1Dc(); +const streamShaPlain = new Sha1(); + +/** + * Finish a SHA-1DC hash, refusing anything carrying a SHA-1 collision-attack + * block. This is git's post-SHAttered rule: the id is still plain SHA-1, but + * an object built to collide never enters the database. + */ +function finishOid(h: Sha1Dc): string { + const oid = toHex(h.digest()); + if (h.collision) throw new Sha1CollisionError(oid); + return oid; +} + +/** + * Hash a fully-materialized object. With collision detection off (default) the + * id comes from native crypto.subtle — byte-identical to plain SHA-1 but ~24x + * faster than the JS hasher; with it on, SHA-1DC screens every block. The + * object is already in memory here, so the one-shot header+data buffer adds no + * unbounded allocation. + */ +async function hashObjectAsync(type: ObjType, data: Uint8Array, cd: boolean): Promise { + if (cd) return finishOid(scratchSha.reset().update(objectHeader(type, data.length)).update(data)); + const header = objectHeader(type, data.length); + const buf = new Uint8Array(header.length + data.length); + buf.set(header); + buf.set(data, header.length); + return toHex(new Uint8Array(await crypto.subtle.digest("SHA-1", buf))); +} + +/** + * Buffered sequential reader over a pack stored as SQLite chunk rows or an R2 + * object. Chunks are loaded through the owning PackStore's chunk cache (async + * because an R2-backed chunk is a range GET), so byte()/window() await; the SQL + * backend resolves without I/O. + */ +class PackReader { + pos = 0; + private seq = -1; + private chunk: Uint8Array = new Uint8Array(0); + + constructor(private load: (seq: number) => Promise, readonly size: number) {} + + private async ensure(): Promise { + gitWorkLimits(); + if (this.pos >= this.size) throw new Error("truncated pack entry"); + const want = Math.floor(this.pos / PACK_CHUNK); + if (want !== this.seq) { + this.chunk = await this.load(want); + this.seq = want; + } + } + + async byte(): Promise { + await this.ensure(); + return this.chunk[this.pos++ - this.seq * PACK_CHUNK]; + } + + /** Remaining bytes of the chunk containing pos (never empty while pos < size). */ + async window(): Promise { + await this.ensure(); + return this.chunk.subarray(this.pos - this.seq * PACK_CHUNK); + } +} + +/** + * Pack-native object database: received packfiles are stored verbatim — in R2 + * under `raw//` when a bucket is bound (PACK_CACHE), else in + * SQLite chunk rows (the fallback / celld path) — and indexed (oid -> + * pack/offset/base), preserving the client's delta compression. Only the index + * ever lives in SQLite for an R2-backed pack, so pack data escapes the per-DO + * storage ceiling. This is what lets large repos fit and stream. + */ +export class PackStore { + /** LRU of decoded pack chunks, keyed "packId:seq" (SQLite row or R2 range). */ + private chunks = new Map(); + /** + * R2 raw-pack backend for this repo, or null when no bucket is bound (celld / + * Workers without the binding). When set, newly ingested packs store their + * bytes in R2 under `raw//` and keep only the index in SQLite; + * pre-existing SQLite packs keep working (backend is recorded per pack). + */ + private r2: { bucket: R2Bucket; repo: string } | null = null; + /** Cached backend ('sql' | 'r2') per pack id, from pack_meta.store. */ + private backend = new Map(); + + constructor(private sql: SqlStorage, private extern: ExternalResolver) { + this.init(); + } + + /** Bind (or clear) the R2 backend. Idempotent; the DO is per-repo so this is + * set on each request from the repo name. */ + setR2(bucket: R2Bucket | undefined, repo: string): void { + this.r2 = bucket ? { bucket, repo } : null; + } + + private rawKey(packId: number): string { + return `raw/${this.r2!.repo}/${packId}`; + } + + /** Storage backend of a pack. Cached; falls back to a pack_meta lookup. The + * cache is primed at ingest start (before pack_meta exists) so phase B/C read + * the right source. */ + private backendOf(packId: number): "sql" | "r2" { + const hit = this.backend.get(packId); + if (hit) return hit; + const rows = this.sql + .exec<{ store: string }>("SELECT store FROM pack_meta WHERE pack_id = ?", packId) + .toArray(); + const b = rows[0]?.store === "r2" ? "r2" : "sql"; + this.backend.set(packId, b); + return b; + } + + private init(): void { + this.sql.exec(` + CREATE TABLE IF NOT EXISTS pack_meta ( + pack_id INTEGER PRIMARY KEY, + size INTEGER NOT NULL, + count INTEGER NOT NULL, + created INTEGER NOT NULL, + store TEXT NOT NULL DEFAULT 'sql' + ); + CREATE TABLE IF NOT EXISTS pack_data ( + pack_id INTEGER NOT NULL, + seq INTEGER NOT NULL, + data BLOB NOT NULL, + PRIMARY KEY (pack_id, seq) + ); + CREATE TABLE IF NOT EXISTS pack_objects ( + oid TEXT PRIMARY KEY, + pack_id INTEGER NOT NULL, + offset INTEGER NOT NULL, + data_off INTEGER NOT NULL, + data_len INTEGER NOT NULL, + type TEXT NOT NULL, + size INTEGER NOT NULL, + entry_size INTEGER NOT NULL, + base_oid TEXT + ); + CREATE INDEX IF NOT EXISTS idx_pack_objects_loc ON pack_objects(pack_id, offset); + CREATE TABLE IF NOT EXISTS pack_pending ( + pack_id INTEGER NOT NULL, + offset INTEGER NOT NULL, + data_off INTEGER NOT NULL, + data_len INTEGER NOT NULL, + entry_size INTEGER NOT NULL, + base_oid TEXT, + base_offset INTEGER, + PRIMARY KEY (pack_id, offset) + ); + `); + // back-fill the store column on repos whose pack_meta predates the R2 backend: + // every such pack is SQLite-backed, which the 'sql' default records + const cols = this.sql.exec<{ name: string }>("PRAGMA table_info(pack_meta)").toArray(); + if (!cols.some((c) => c.name === "store")) { + this.sql.exec("ALTER TABLE pack_meta ADD COLUMN store TEXT NOT NULL DEFAULT 'sql'"); + } + } + + wipe(): void { + this.sql.exec("DROP TABLE IF EXISTS pack_meta"); + this.sql.exec("DROP TABLE IF EXISTS pack_data"); + this.sql.exec("DROP TABLE IF EXISTS pack_objects"); + this.sql.exec("DROP TABLE IF EXISTS pack_pending"); + this.chunks.clear(); // pack ids restart from 1: cached rows would be stale + this.backend.clear(); + } + + /** Drop all packs and start empty (small-repo gc migrates objects out first). */ + reset(): void { + this.wipe(); + this.init(); + } + + /** Pack ids of the currently R2-backed packs (for GC to delete their R2 bytes). */ + r2PackIds(): number[] { + return this.sql + .exec<{ pack_id: number }>("SELECT pack_id FROM pack_meta WHERE store = 'r2'") + .toArray() + .map((r) => r.pack_id); + } + + /** Delete the R2 raw objects for the given pack ids (no-op without a binding). */ + async deleteR2Packs(packIds: number[]): Promise { + if (!this.r2 || !packIds.length) return; + const keys = packIds.map((id) => this.rawKey(id)); + for (let i = 0; i < keys.length; i += 100) { + try { + await this.r2.bucket.delete(keys.slice(i, i + 100)); + } catch { + // best effort: an undeleted raw object is unreferenced garbage + } + } + } + + /** SAM: ids of the stored packs. */ + packIds(): number[] { + return this.sql + .exec<{ pack_id: number }>("SELECT pack_id FROM pack_meta ORDER BY pack_id") + .toArray() + .map((r) => r.pack_id); + } + + /** SAM: the oids one pack stores. */ + packObjectOids(packId: number): string[] { + return this.sql + .exec<{ oid: string }>("SELECT oid FROM pack_objects WHERE pack_id = ?", packId) + .toArray() + .map((r) => r.oid); + } + + /** + * SAM: drop one whole pack. GC calls this only for a pack it proved holds no reachable + * object and no delta base, so no object is inflated to reclaim it. + */ + async dropPack(packId: number): Promise { + const r2 = this.backendOf(packId) === "r2"; + this.sql.exec("DELETE FROM pack_meta WHERE pack_id = ?", packId); + this.sql.exec("DELETE FROM pack_data WHERE pack_id = ?", packId); + this.sql.exec("DELETE FROM pack_objects WHERE pack_id = ?", packId); + this.sql.exec("DELETE FROM pack_pending WHERE pack_id = ?", packId); + // the pack id can be handed out again by the next ingest: drop cached rows for it + this.chunks.clear(); + this.backend.clear(); + if (r2) await this.deleteR2Packs([packId]); + } + + countObjects(): number { + return this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM pack_objects").one().n; + } + + /** Total stored bytes across all indexed packs (0 when pack-empty). */ + totalPackBytes(): number { + return this.sql.exec<{ n: number }>("SELECT COALESCE(SUM(size), 0) AS n FROM pack_meta").one().n; + } + + /** + * Bytes of pack storage the raw-chunk LRU keeps hot. A pack no larger than + * this fits entirely in cache, so readRaw never re-decodes a chunk no matter + * what order objects are emitted in — sorting for read locality is pure + * overhead below this threshold. + */ + rawCacheWindow(): number { + return RAW_CHUNK_CACHE * PACK_CHUNK; + } + + lookup(oid: string): PackedEntry | null { + gitWorkLimits(); + const rows = this.sql + .exec<{ + pack_id: number; offset: number; data_off: number; data_len: number; + type: ObjType; size: number; entry_size: number; base_oid: string | null; + }>( + "SELECT pack_id, offset, data_off, data_len, type, size, entry_size, base_oid FROM pack_objects WHERE oid = ?", + oid + ) + .toArray(); + const r = rows[0]; + if (!r) return null; + return { + oid, packId: r.pack_id, offset: r.offset, dataOff: r.data_off, dataLen: r.data_len, + type: r.type, size: r.size, entrySize: r.entry_size, baseOid: r.base_oid, + }; + } + + typeAndSize(oid: string): { type: ObjType; size: number } | null { + const rows = this.sql + .exec<{ type: ObjType; size: number }>("SELECT type, size FROM pack_objects WHERE oid = ?", oid) + .toArray(); + return rows[0] ?? null; + } + + /** Distinct delta-base oids: a second reference edge gc must not sever. */ + baseOids(): string[] { + return this.sql + .exec<{ base_oid: string }>("SELECT DISTINCT base_oid FROM pack_objects WHERE base_oid IS NOT NULL") + .toArray() + .map((r) => r.base_oid); + } + + findOidPrefix(prefix: string): string[] { + return this.sql + .exec<{ oid: string }>("SELECT oid FROM pack_objects WHERE oid LIKE ? LIMIT 2", prefix + "%") + .toArray() + .map((r) => r.oid); + } + + /** + * Raw stored (still-compressed) bytes of a pack region. Chunk rows are + * fetched one at a time: a wide range in a single SELECT can exceed the + * runtime's result-set size cap (celld materializes blob rows as JSON). + */ + async readRaw(packId: number, off: number, len: number): Promise { + gitWorkLimits(); + const first = Math.floor(off / PACK_CHUNK); + const last = Math.floor((off + len - 1) / PACK_CHUNK); + const out = new Uint8Array(len); + for (let seq = first; seq <= last; seq++) { + const chunk = await this.chunk(packId, seq); + const chunkStart = seq * PACK_CHUNK; + const from = Math.max(off, chunkStart); + const to = Math.min(off + len, chunkStart + chunk.length); + if (to > from) out.set(chunk.subarray(from - chunkStart, to - chunkStart), from - off); + } + return out; + } + + /** + * One decoded pack chunk, through the LRU. For a SQLite-backed pack this is a + * `pack_data` row; for an R2-backed pack it is an aligned ~1 MiB range GET + * against `raw//`, so sorted sequential reads (a clone) issue + * ~one GET per chunk instead of one per object. Chunks are immutable once + * written — a pack is inserted once and only ever removed wholesale (wipe/ + * reset, or the orphan sweep at the top of ingest, both of which clear the + * cache), so a hit can never be stale. + */ + private async chunk(packId: number, seq: number): Promise { + const key = `${packId}:${seq}`; + const hit = this.chunks.get(key); + if (hit) { + this.chunks.delete(key); // reinsert: most-recently-used goes last + this.chunks.set(key, hit); + return hit; + } + let chunk: Uint8Array; + if (this.backendOf(packId) === "r2") { + if (!this.r2) throw new Error(`pack ${packId}: R2 backend not bound`); + const obj = await this.r2.bucket.get(this.rawKey(packId), { + range: { offset: seq * PACK_CHUNK, length: PACK_CHUNK }, + }); + if (!obj) throw new Error(`pack ${packId}: missing R2 object ${this.rawKey(packId)}`); + chunk = new Uint8Array(await obj.arrayBuffer()); + } else { + const rows = this.sql + .exec<{ data: ArrayBuffer }>( + "SELECT data FROM pack_data WHERE pack_id = ? AND seq = ?", + packId, + seq + ) + .toArray(); + if (!rows.length) throw new Error(`pack ${packId}: missing chunk ${seq}`); + chunk = new Uint8Array(rows[0].data); + } + this.chunks.set(key, chunk); + while (this.chunks.size > RAW_CHUNK_CACHE) { + this.chunks.delete(this.chunks.keys().next().value as string); + } + return chunk; + } + + /** + * Inflate + delta-resolve an object out of pack storage. A crafted pack can + * chain deltas arbitrarily deep or in a cycle, so the base chain is walked + * ITERATIVELY (not recursively) through cheap index lookups first — bounding + * the chain length and detecting cycles before a single delta is inflated — + * then applied from the base upward, holding at most two inflated buffers at + * a time. This caps both stack depth and peak memory regardless of input. + */ + async getObject(oid: string, cache: ObjCache): Promise { + gitWorkLimits(); + const cached = cache.get(oid); + if (cached) return cached; + const first = this.lookup(oid); + if (!first) return null; + + // walk to the base via lookups only: collect the delta entries, resolve + // where the chain bottoms out (a full entry, a cached object, or a thin + // base from another pack / loose storage). + const chain: PackedEntry[] = []; + const seen = new Set(); + let base: ObjRec | null = null; + let cur: PackedEntry = first; + for (;;) { + if (seen.has(cur.oid)) throw new Error(`cyclic delta chain at ${cur.oid}`); + seen.add(cur.oid); + if (!cur.baseOid) { + base = { type: cur.type, data: inflateAll(await this.readRaw(cur.packId, cur.dataOff, cur.dataLen)) }; + break; + } + if (chain.length >= gitWorkLimits().maxDeltaDepth) throw new Error(`delta chain exceeds depth ${gitWorkLimits().maxDeltaDepth} at ${oid}`); + chain.push(cur); + const cachedBase = cache.get(cur.baseOid); + if (cachedBase) { base = cachedBase; break; } + const next = this.lookup(cur.baseOid); + if (!next) { + const ext = this.extern(cur.baseOid); + if (!ext) throw new Error(`missing delta base ${cur.baseOid} for ${cur.oid}`); + base = ext; + break; + } + cur = next; + } + + // apply deltas from the base upward (chain is target..base order) + let obj = base; + for (let i = chain.length - 1; i >= 0; i--) { + const d = chain[i]; + const delta = inflateAll(await this.readRaw(d.packId, d.dataOff, d.dataLen)); + obj = { type: base.type, data: applyDelta(obj.data, delta) }; + cache.put(d.oid, obj); + } + if (!chain.length) cache.put(oid, obj); + return obj; + } + + /** + * Ingest a packfile arriving as a byte stream: store the bytes verbatim + * (to R2 when a bucket is bound, else SQLite chunk rows) while verifying the + * SHA-1 trailer on the fly, then index sequentially. + * Deltas resolve eagerly against the LRU cache — pack ordering keeps + * bases hot — so the straggler pass afterwards is nearly empty. Memory + * stays bounded regardless of pack size. + */ + /** Reclaim incomplete packs without requiring another admitted upload. Caller owns the write slot. */ + async cleanupOrphans(): Promise { + // a failed or interrupted ingest leaves rows (or an R2 raw object) without a + // pack_meta entry; reclaim that space before starting (pack_meta is only + // written on success). Union across every per-pack table so an R2 ingest that + // died mid-index — whose bytes are in R2, not pack_data — is caught too. + const orphans = this.sql + .exec<{ pack_id: number }>( + `SELECT pack_id FROM ( + SELECT DISTINCT pack_id FROM pack_data + UNION SELECT DISTINCT pack_id FROM pack_objects + UNION SELECT DISTINCT pack_id FROM pack_pending + ) WHERE pack_id NOT IN (SELECT pack_id FROM pack_meta)` + ) + .toArray(); + for (const o of orphans) { + this.sql.exec("DELETE FROM pack_data WHERE pack_id = ?", o.pack_id); + this.sql.exec("DELETE FROM pack_objects WHERE pack_id = ?", o.pack_id); + this.sql.exec("DELETE FROM pack_pending WHERE pack_id = ?", o.pack_id); + // an interrupted R2 ingest may have left a completed raw object; delete it + if (this.r2) { + try { + await this.r2.bucket.delete(this.rawKey(o.pack_id)); + } catch { + // best effort: the packId is reused next and its raw key overwritten + } + } + } + // the reclaimed pack id is about to be handed out again: drop anything the + // chunk LRU still holds for it (and for anything else — it is only a cache) + if (orphans.length) this.chunks.clear(); + } + + async ingest( + firstBytes: Uint8Array, + reader: ReadableStreamDefaultReader | null, + opts: { + maxBytes: number; + /** push body size (content-length ~= pack size); packs this size are + * stored in R2 when a bucket is bound, else in SQLite. Absent means the + * client went chunked, which git only does above ~1MB (http.postBuffer) + * — so unknown size picks R2, the safe side for the 10GB SQLite cap. */ + sizeHint?: number; + cache: ObjCache; + onProgress?: (msg: string) => void; + /** called periodically so the runtime can flush its write buffer — + * workerd holds a request's dirty pages in the 128MB isolate heap */ + flush?: () => Promise; + /** screen every block with SHA-1DC (git-parity collision detection); + * default hashes with native crypto.subtle, which yields the identical + * oid without the collision check */ + collisionDetect?: boolean; + } + ): Promise<{ packId: number; count: number }> { + const cd = opts.collisionDetect ?? false; + await this.cleanupOrphans(); + const packId = + (this.sql.exec<{ m: number | null }>("SELECT MAX(pack_id) AS m FROM pack_meta").one().m ?? 0) + 1; + const started = Date.now(); + const say = (msg: string) => { + opts.onProgress?.(msg); + console.log(`[ingest pack ${packId} +${Math.round((Date.now() - started) / 1000)}s] ${msg.trim()}`); + }; + + // storage backend: with an R2 binding, a large (sizeHint >= R2_PACK_MIN_BYTES) + // or unknown-length (chunked, so >1MB) pack streams its bytes to + // raw// via multipart and only the index stays in SQLite; small + // declared-length packs go to pack_data. Prime the backend cache now — before + // pack_meta exists — so phase B/C readRaw hits the right source. A refused + // multipart begin (celld makes createMultipartUpload throw) degrades to SQLite. + let capture: MultipartCapture | null = null; + const wantR2 = this.r2 !== null && (opts.sizeHint === undefined || opts.sizeHint >= R2_PACK_MIN_BYTES); + if (this.r2 && wantR2) { + const mp = await beginRawMultipart(this.r2.bucket, this.rawKey(packId)); + if (mp) capture = new MultipartCapture(mp); + } + const r2Backed = capture !== null; + this.backend.set(packId, r2Backed ? "r2" : "sql"); + + // phase A: stream bytes into R2 (or chunk rows), hashing all but the trailing 20. + // Strictly linear: a cursor fills a fixed 1MB buffer — the source may + // arrive as one multi-GB chunk (celld buffers request bodies), so any + // re-concatenation of the remainder would go quadratic. + const sha = new Sha1(); + let tail = new Uint8Array(0); // rolling 20-byte lookbehind (the trailer) + let total = 0; + let seq = 0; + const chunkBuf = new Uint8Array(PACK_CHUNK); + let chunkLen = 0; + let lastLogged = 0; + const feed = (data: Uint8Array) => { + total += data.length; + if (total > opts.maxBytes) throw new Error("pack exceeds maximum push size"); + if (total - lastLogged >= 64 * 1024 * 1024) { + lastLogged = total; + say(`Receiving pack: ${Math.round(total / 1048576)}MB\n`); + } + const joined = tail.length ? concat([tail, data]) : data; + if (joined.length > 20) { + sha.update(joined.subarray(0, joined.length - 20)); + tail = joined.slice(joined.length - 20); + } else { + tail = joined.slice(); + } + if (capture) { + capture.push(data); // copied into a 16 MiB multipart part buffer + return; + } + let off = 0; + while (off < data.length) { + const take = Math.min(PACK_CHUNK - chunkLen, data.length - off); + chunkBuf.set(data.subarray(off, off + take), chunkLen); + chunkLen += take; + off += take; + if (chunkLen === PACK_CHUNK) { + this.sql.exec( + "INSERT INTO pack_data (pack_id, seq, data) VALUES (?, ?, ?)", + packId, + seq++, + chunkBuf.slice().buffer + ); + chunkLen = 0; + } + } + }; + // feed in bounded slices with yields, so one giant buffered body doesn't + // monopolize the event loop for a minutes-long synchronous stretch + const FEED_SLICE = 8 * 1024 * 1024; + const feedSliced = async (data: Uint8Array) => { + for (let off = 0; off < data.length; off += FEED_SLICE) { + feed(data.subarray(off, off + FEED_SLICE)); + if (capture) { + await capture.drain(); // upload whole 16 MiB parts, keep only the remainder + if (capture.aborted) throw new Error("pack upload to R2 failed"); + } + if (data.length > FEED_SLICE) await new Promise((res) => setTimeout(res, 0)); + await opts.flush?.(); + } + }; + if (firstBytes.length) await feedSliced(firstBytes); + if (reader) { + for (;;) { + const { done, value } = await readGitChunk(reader); + if (done) break; + if (value?.length) await feedSliced(value); + } + } + if (!capture && chunkLen > 0) { + this.sql.exec( + "INSERT INTO pack_data (pack_id, seq, data) VALUES (?, ?, ?)", + packId, + seq++, + chunkBuf.slice(0, chunkLen).buffer + ); + } + // validate the trailer before completing the R2 upload, so a corrupt push + // never leaves a finished raw object (abort leaves R2 with nothing). + if (total < 32) { + if (capture) await capture.abort(); + throw new Error("pack too small"); + } + if (toHex(tail) !== toHex(sha.digest())) { + if (capture) await capture.abort(); + throw new Error("pack checksum mismatch"); + } + if (capture) { + // complete the multipart BEFORE phase B/C: both readRaw the finished raw + // object (phase B for eager delta bases, phase C for deferred deltas). + await capture.finish(); + if (capture.aborted) throw new Error("pack upload to R2 failed"); + } + say(`Received pack: ${Math.round(total / 1048576)}MB\n`); + + // phase B: sequential scan with eager delta resolution + const r = new PackReader((s) => this.chunk(packId, s), total); + const magic = new Uint8Array(4); + for (let i = 0; i < 4; i++) magic[i] = await r.byte(); + if (td.decode(magic) !== "PACK") throw new Error("bad pack signature"); + let version = 0, count = 0; + for (let i = 0; i < 4; i++) version = (version << 8) | (await r.byte()); + for (let i = 0; i < 4; i++) count = (count << 8) | (await r.byte()); + if (version !== 2 && version !== 3) throw new Error(`unsupported pack version ${version}`); + + // batched index inserts: one exec per object made pack_objects a top SQL + // cost, and deferring rows is safe because delta bases resolve from the + // in-memory offset window and object cache — the flush points below cover + // the rare pack_objects SELECT fallbacks (oidByOffset miss, getObject). + // OR IGNORE keeps a duplicate oid's FIRST location — including within one + // batch — so a failed ingest's orphan sweep can't strand a stored object. + // workerd caps a DO SQL statement at ~100 bound variables (celld's stock + // SQLite allows more); 10 rows x 9 cols = 90 stays under that on both. + const OBJ_BATCH = 10; + let objBatch: (string | number | null)[] = []; + let objBatchRows = 0; + const flushObjects = () => { + if (!objBatchRows) return; + const placeholders = Array(objBatchRows).fill("(?,?,?,?,?,?,?,?,?)").join(","); + this.sql.exec( + `INSERT OR IGNORE INTO pack_objects (oid, pack_id, offset, data_off, data_len, type, size, entry_size, base_oid) VALUES ${placeholders}`, + ...objBatch + ); + objBatch = []; + objBatchRows = 0; + }; + const insertObject = (row: (string | number | null)[]) => { + for (const v of row) objBatch.push(v); + if (++objBatchRows >= OBJ_BATCH) flushObjects(); + }; + const insertPending = (row: (string | number | null)[]) => { + this.sql.exec( + "INSERT INTO pack_pending (pack_id, offset, data_off, data_len, entry_size, base_oid, base_offset) VALUES (?,?,?,?,?,?,?)", + ...row + ); + }; + + // rotating offset -> oid window: ofs-delta bases are nearly always recent + let winCur = new Map(); + let winPrev = new Map(); + const winPut = (off: number, oid: string) => { + winCur.set(off, oid); + if (winCur.size >= OFFSET_WINDOW) { + winPrev = winCur; + winCur = new Map(); + } + }; + const oidByOffset = (off: number): string | null => { + const hit = winCur.get(off) ?? winPrev.get(off); + if (hit) return hit; + flushObjects(); // a windowed miss falls back to SELECT: deferred rows must be visible + const rows = this.sql + .exec<{ oid: string }>("SELECT oid FROM pack_objects WHERE pack_id = ? AND offset = ?", packId, off) + .toArray(); + return rows[0]?.oid ?? null; + }; + + let pendingCount = 0; + for (let i = 0; i < count; i++) { + gitWorkLimits(); + const offset = r.pos; + let byte = await r.byte(); + const type = (byte >> 4) & 7; + let entrySize = byte & 15; + let shift = 4; + while (byte & 0x80) { + byte = await r.byte(); + entrySize += (byte & 0x7f) * 2 ** shift; + shift += 7; + } + if (!Number.isSafeInteger(entrySize) || entrySize < 0 || entrySize > gitWorkLimits().maxObjectBytes) { + throw new Error("git object exceeds inflated size limit"); + } + let baseOid: string | null = null; + let baseOffset: number | null = null; + if (type === 6) { + byte = await r.byte(); + let off = byte & 0x7f; + while (byte & 0x80) { + byte = await r.byte(); + off = (off + 1) * 128 + (byte & 0x7f); + } + baseOffset = offset - off; + } else if (type === 7) { + const b = new Uint8Array(20); + for (let j = 0; j < 20; j++) b[j] = await r.byte(); + baseOid = toHex(b); + } else if (!NUM_TYPE[type]) { + throw new Error(`bad object type ${type} at ${offset}`); + } + + const dataOff = r.pos; + const isFull = type >= 1 && type <= 4; + const objType = isFull ? NUM_TYPE[type] : null; + const buffered = entrySize <= MAX_BUFFERED_ENTRY; + // buffered entries inflate straight into one exact-size buffer (no piece + // array + concat, which would hold the object twice at once) + const content = buffered ? new Uint8Array(entrySize) : null; + if (isFull && !buffered) { + if (cd) streamSha.reset().update(objectHeader(objType!, entrySize)); + else streamShaPlain.reset().update(objectHeader(objType!, entrySize)); + } + let inflated = 0; + const inf = new pako.Inflate({ chunkSize: INFLATE_CHUNK }); + (inf as unknown as { onData: (c: Uint8Array) => void }).onData = (c: Uint8Array) => { + if (inflated + c.length > entrySize) throw new Error("entry size mismatch"); + chargeGitWork(c.length); + if (content) content.set(c, inflated); + else if (isFull) (cd ? streamSha : streamShaPlain).update(c); + inflated += c.length; + }; + const anyInf = inf as unknown as { err: number; msg: string; ended: boolean; strm: { avail_in: number } }; + while (!anyInf.ended) { + if (r.pos >= total) throw new Error(`truncated pack entry at ${offset}`); + const win = await r.window(); + inf.push(win, false); + if (anyInf.err) throw new Error(`inflate failed at ${dataOff}: ${anyInf.msg}`); + r.pos += anyInf.ended ? win.length - anyInf.strm.avail_in : win.length; + } + if (inflated !== entrySize) throw new Error(`entry size mismatch at ${offset}`); + const dataLen = r.pos - dataOff; + + if (isFull) { + const oid = buffered + ? await hashObjectAsync(objType!, content!, cd) + : cd + ? finishOid(streamSha) + : toHex(streamShaPlain.digest()); + insertObject([oid, packId, offset, dataOff, dataLen, objType!, entrySize, entrySize, null]); + winPut(offset, oid); + if (content && content.length <= CACHE_ENTRY_LIMIT) { + opts.cache.put(oid, { type: objType!, data: content }); + } + } else { + const resolvedBase = baseOid ?? (baseOffset !== null ? oidByOffset(baseOffset) : null); + let resolved = false; + if (buffered && resolvedBase) { + let base: ObjRec | null = opts.cache.get(resolvedBase) ?? null; + if (!base) { + flushObjects(); // getObject SELECTs pack_objects: deferred rows must be visible + try { + base = await this.getObject(resolvedBase, opts.cache); + } catch { + base = null; + } + } + if (!base) base = this.extern(resolvedBase); + if (base) { + const data = applyDelta(base.data, content!); + const oid = await hashObjectAsync(base.type, data, cd); + insertObject([oid, packId, offset, dataOff, dataLen, base.type, data.length, entrySize, resolvedBase]); + winPut(offset, oid); + if (data.length <= CACHE_ENTRY_LIMIT) { + opts.cache.put(oid, { type: base.type, data }); + } + resolved = true; + } + } + if (!resolved) { + insertPending([packId, offset, dataOff, dataLen, entrySize, baseOid, baseOffset]); + pendingCount++; + } + } + + if (i % 2000 === 1999) { + await new Promise((res) => setTimeout(res, 0)); + await opts.flush?.(); + if (i % 100000 === 99999) say(`Indexing objects: ${i + 1}/${count}\n`); + } + } + // the header count must account for every byte up to the 20-byte trailer; + // otherwise objects were silently dropped (or junk trails the pack) + if (r.pos !== total - 20) throw new Error("pack has trailing data or bad object count"); + await opts.flush?.(); + say(`Indexed ${count} objects (${pendingCount} deferred)\n`); + + // phase C: stragglers — deltas whose base appeared later in the pack, + // or thin-pack bases that live in another pack / loose storage + let pendingTotal = this.sql + .exec<{ n: number }>("SELECT COUNT(*) AS n FROM pack_pending WHERE pack_id = ?", packId) + .one().n; + let resolvedTotal = 0; + while (pendingTotal > 0) { + let resolvedThisPass = 0; + let lastOffset = -1; + for (;;) { + const page = this.sql + .exec<{ + offset: number; data_off: number; data_len: number; entry_size: number; + base_oid: string | null; base_offset: number | null; + }>( + "SELECT offset, data_off, data_len, entry_size, base_oid, base_offset FROM pack_pending WHERE pack_id = ? AND offset > ? ORDER BY offset LIMIT 500", + packId, + lastOffset + ) + .toArray(); + if (!page.length) break; + for (const row of page) { + lastOffset = row.offset; + let baseOid = row.base_oid; + if (!baseOid && row.base_offset !== null) { + baseOid = oidByOffset(row.base_offset); + if (!baseOid) continue; // base itself still pending + } + if (!baseOid) continue; + let base: ObjRec | null = null; + flushObjects(); // getObject SELECTs pack_objects: deferred rows must be visible + try { + base = (await this.getObject(baseOid, opts.cache)) ?? this.extern(baseOid); + } catch { + base = null; + } + if (!base) continue; // thin base not available (yet) + const delta = inflateAll(await this.readRaw(packId, row.data_off, row.data_len)); + const data = applyDelta(base.data, delta); + const oid = await hashObjectAsync(base.type, data, cd); + insertObject([oid, packId, row.offset, row.data_off, row.data_len, base.type, data.length, row.entry_size, baseOid]); + this.sql.exec("DELETE FROM pack_pending WHERE pack_id = ? AND offset = ?", packId, row.offset); + winPut(row.offset, oid); + if (data.length <= CACHE_ENTRY_LIMIT) opts.cache.put(oid, { type: base.type, data }); + resolvedTotal++; + resolvedThisPass++; + if (resolvedTotal % 2000 === 0) { + await new Promise((res) => setTimeout(res, 0)); + if (resolvedTotal % 100000 === 0) say(`Resolving deltas: ${resolvedTotal}\n`); + } + } + } + pendingTotal -= resolvedThisPass; + if (resolvedThisPass === 0 && pendingTotal > 0) { + throw new Error(`cannot resolve ${pendingTotal} delta object(s): missing base`); + } + } + if (resolvedTotal) say(`Resolved ${resolvedTotal} deferred delta(s)\n`); + flushObjects(); // commit the final partial batch before pack_meta marks the pack complete + + this.sql.exec( + "INSERT INTO pack_meta (pack_id, size, count, created, store) VALUES (?, ?, ?, ?, ?)", + packId, total, count, Date.now(), r2Backed ? "r2" : "sql" + ); + return { packId, count }; + } +} diff --git a/apps/api/src/vendor/dgit/git/pktline.ts b/apps/api/src/vendor/dgit/git/pktline.ts new file mode 100644 index 0000000000..553b7b6e3e --- /dev/null +++ b/apps/api/src/vendor/dgit/git/pktline.ts @@ -0,0 +1,69 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +import { te, td, concat } from "./util"; + +export const FLUSH = te.encode("0000"); + +/** Encode one pkt-line (length prefix includes the 4 prefix bytes). */ +export function pkt(payload: string | Uint8Array): Uint8Array { + const body = typeof payload === "string" ? te.encode(payload) : payload; + if (body.length > 65516) throw new Error("pkt-line too long"); + return concat([te.encode((body.length + 4).toString(16).padStart(4, "0")), body]); +} + +export function pktLines(...payloads: (string | Uint8Array)[]): Uint8Array { + return concat(payloads.map(pkt)); +} + +export type Pkt = { kind: "flush" | "delim" | "line"; raw: Uint8Array; text: string }; + +/** Iterates pkt-lines from a buffer; `rest()` returns unparsed bytes (e.g. a packfile). */ +export class PktParser { + pos = 0; + constructor(private buf: Uint8Array) {} + + /** + * Strict 4-byte hex length. `parseInt` is too lenient for attacker-framed + * input — it accepts leading whitespace and stops at the first non-digit, so + * " 12" or "001g" would parse to a bogus length and desync the stream. Every + * one of the four bytes must be a hex digit or the packet is rejected. + */ + private len4(): number { + let n = 0; + for (let i = 0; i < 4; i++) { + const c = this.buf[this.pos + i]; + let d: number; + if (c >= 0x30 && c <= 0x39) d = c - 0x30; + else if (c >= 0x61 && c <= 0x66) d = c - 0x57; + else if (c >= 0x41 && c <= 0x46) d = c - 0x37; + else throw new Error("bad pkt-line length"); + n = (n << 4) | d; + } + return n; + } + + read(): Pkt | null { + if (this.pos + 4 > this.buf.length) return null; + const len = this.len4(); + // 0000 flush and 0001 delim are the only special lengths; 0002/0003 are + // undefined and rejected, as is any declared length that overruns the buffer. + if (len === 0) { + this.pos += 4; + return { kind: "flush", raw: new Uint8Array(0), text: "" }; + } + if (len === 1) { + this.pos += 4; + return { kind: "delim", raw: new Uint8Array(0), text: "" }; + } + if (len < 4 || this.pos + len > this.buf.length) throw new Error("bad pkt-line"); + const raw = this.buf.subarray(this.pos + 4, this.pos + len); + this.pos += len; + let text = td.decode(raw); + if (text.endsWith("\n")) text = text.slice(0, -1); + return { kind: "line", raw, text }; + } + + rest(): Uint8Array { + return this.buf.subarray(this.pos); + } +} diff --git a/apps/api/src/vendor/dgit/git/protocol.ts b/apps/api/src/vendor/dgit/git/protocol.ts new file mode 100644 index 0000000000..809b314f73 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/protocol.ts @@ -0,0 +1,1627 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +// FILE SIZE EXCEPTION: vendored third-party code kept identical to upstream dgit (see ../UPSTREAM.md) +import { concat, isOid, ZERO_OID, te } from "./util"; +import { pkt, FLUSH, PktParser } from "./pktline"; +import { GitStore } from "./store"; +import { PackWriter } from "./pack"; +import { isValidGitRefName } from "../../../lib/git-ref-name"; +import { OidSet } from "./oidset"; +import { MultipartCapture, MultipartPackUpload } from "./multipart"; +import { GitParseError, parseCommit, parseTag, parseTree, isGitlinkMode, isTreeMode, TYPE_NUM, NUM_TYPE, ObjType } from "./objects"; + +const AGENT = "agent=dgit/0.3"; +const INFINITE_DEPTH = 0x7fffffff; +const SIDEBAND_CHUNK = 32 * 1024; +const WALK_YIELD = 5000; +/** + * Committer-date skew tolerated before the uninteresting (have) commit walk + * stops descending. Cutting the walk short can only ever shrink the "client + * already has it" set, i.e. send a few redundant objects — never omit one — + * so a day of slack is a safe way to keep an incremental fetch off the full + * commit graph. + */ +const WALK_DATE_SLOP = 24 * 60 * 60; + +export type Service = "git-upload-pack" | "git-receive-pack"; + +/** + * Optional R2-backed full-clone offload, write side only: on a full-clone MISS + * the DO tees the generated pack into a multipart upload so it never buffers the + * whole pack in isolate memory (no size cap). Absent on celld and on Workers + * without the binding, in which case every clone is served from the DO exactly + * as before. HITs are served by the Worker streaming R2 directly, not the DO. + */ +export interface PackCache { + repo: string; + /** Begin a multipart pack build under `key`, stamping the object count as + * customMetadata; null when R2 is unavailable (the clone still streams). */ + beginMultipart(key: string, objects: number): Promise; +} + +/** GET /info/refs?service=... — smart ref advertisement. */ +export function advertisement(store: GitStore, service: Service, v2 = false): Uint8Array { + if (v2 && service === "git-upload-pack") { + return concat([pkt("version 2\n"), pkt(`${AGENT}\n`), pkt("ls-refs\n"), pkt("fetch=shallow\n"), FLUSH]); + } + const caps = + service === "git-upload-pack" + ? [ + "multi_ack_detailed", + "no-done", + "shallow", + "side-band-64k", + `symref=HEAD:${store.head()}`, + AGENT, + ].join(" ") + : ["report-status", "delete-refs", "ofs-delta", "side-band-64k", AGENT].join(" "); + + const lines: Uint8Array[] = [pkt(`# service=${service}\n`), FLUSH]; + const refs: { name: string; target: string }[] = []; + if (service === "git-upload-pack") { + const head = store.resolveHead(); + if (head) refs.push({ name: "HEAD", target: head }); + } + refs.push(...store.refs()); + + if (refs.length === 0) { + lines.push(pkt(`${ZERO_OID} capabilities^{}\0${caps}\n`)); + } else { + refs.forEach((r, i) => { + lines.push(pkt(i === 0 ? `${r.target} ${r.name}\0${caps}\n` : `${r.target} ${r.name}\n`)); + }); + } + lines.push(FLUSH); + return concat(lines); +} + +/** + * The oids a fetch is allowed to `want`: exactly what the advertisement above + * exposes — HEAD, every current ref tip, and the peeled commit target of each + * annotated tag (git advertises those as `^{}`). + * + * This is git's default (`uploadpack.allowAnySHA1InWant=false`): serving any + * oid the database merely *has* leaks objects that are no longer reachable + * from any ref — a commit orphaned by a force-push stays readable to anyone + * who learned its sha. Membership in a set of ref tips, so a normal fetch + * (which only ever wants advertised tips) pays a few hash lookups, not a walk. + */ +export async function advertisedOids(store: GitStore): Promise> { + const oids = new Set(); + const head = store.resolveHead(); + if (head) oids.add(head); + for (const r of store.refs()) { + oids.add(r.target); + // peel annotated tags; lightweight tags already point at the commit + if (!r.name.startsWith("refs/tags/")) continue; + if (store.typeAndSize(r.target)?.type !== "tag") continue; + const peeled = await peelToCommitOid(store, r.target); + if (peeled) oids.add(peeled); + } + return oids; +} + +/** + * True when `wants` is exactly the set of current ref tips — a true full clone, + * not a single-branch or partial fetch. Only then does the whole-repo reachable + * cache describe precisely what the client asked for; a subset of the tips would + * pull unrelated branches' objects in and leave the client with danglers. + */ +export function wantsAreAllTips(store: GitStore, wants: string[]): boolean { + const tips = new Set(); + for (const r of store.refs()) tips.add(r.target); + if (tips.size === 0) return false; + const wantSet = new Set(wants); + if (wantSet.size !== tips.size) return false; + for (const t of tips) if (!wantSet.has(t)) return false; + return true; +} + +export function sidebandFrames(band: number, payload: Uint8Array): Uint8Array[] { + const frames: Uint8Array[] = []; + for (let off = 0; off < payload.length; off += SIDEBAND_CHUNK) { + const chunk = payload.subarray(off, off + SIDEBAND_CHUNK); + const framed = new Uint8Array(chunk.length + 1); + framed[0] = band; + framed.set(chunk, 1); + frames.push(pkt(framed)); + } + return frames; +} + +/** + * Serve a full clone by streaming the R2-cached raw pack straight from the + * Worker: the protocol's pack preamble, the + * optional band-2 progress line, then the pack re-chunked into band-1 side-band + * frames as R2 hands it over, then flush. Framing is identical to the DO path + * and the pack bytes are the stored bytes, so the client receives a + * byte-for-byte-equal pack. Memory is one R2 read chunk at a time — never + * proportional to pack size — and the DO is never contacted for bytes. + */ +export function streamingCloneResponse( + body: ReadableStream, + objects: number, + noProgress: boolean, v2 = false +): Response { + const headers = { + "content-type": "application/x-git-upload-pack-result", + "cache-control": "no-cache", + "x-pack-cache": "hit", + }; + const reader = body.getReader(); + let started = false; + let done = false; + const stream = new ReadableStream({ + pull: async (ctrl) => { + try { + if (!started) { + started = true; + ctrl.enqueue(pkt(v2 ? "packfile\n" : "NAK\n")); + if (!noProgress) { + for (const f of sidebandFrames(2, te.encode(`Enumerating objects: ${objects}, done.\n`))) ctrl.enqueue(f); + } + } + const { done: rdone, value } = await reader.read(); + if (rdone) { + if (!done) { + done = true; + ctrl.enqueue(FLUSH); + ctrl.close(); + } + return; + } + for (const f of sidebandFrames(1, value)) ctrl.enqueue(f); + } catch (err) { + ctrl.error(err); + } + }, + cancel: () => reader.cancel(), + }); + return new Response(stream, { headers }); +} + +interface UploadRequest { + command: "fetch" | "ls-refs" | null; + wants: string[]; + haves: string[]; + done: boolean; + clientShallows: string[]; + deepen: number; // 0 = no depth limit requested + caps: Set; +} + +/** + * SAM: most distinct wants, haves or shallow lines one upload request may list. Above SAM's + * 30,000-object and 10,000-ref repository caps, so no legitimate request reaches it. + */ +export const MAX_UPLOAD_OIDS = 32768; + +export function parseUploadRequest(body: Uint8Array): UploadRequest { + const parser = new PktParser(body); + const req: UploadRequest = { + command: null, + wants: [], + haves: [], + done: false, + clientShallows: [], + deepen: 0, + caps: new Set(), + }; + // SAM: each listed oid later costs a synchronous store lookup, so duplicates are dropped + // and each list is capped while parsing; a 16 MiB request could otherwise queue ~335k + // lookups. Past the cap extra haves/shallows are ignored (negotiation stays correct, the + // pack is just larger) and extra wants cannot be advertised refs anyway. + const seenWants = new Set(); + const seenHaves = new Set(); + const seenShallows = new Set(); + const addUnique = (list: string[], seen: Set, oid: string) => { + if (list.length >= MAX_UPLOAD_OIDS || seen.has(oid)) return; + seen.add(oid); + list.push(oid); + }; + for (let p = parser.read(); p !== null; p = parser.read()) { + if (p.kind !== "line") continue; + const line = p.text; + if (line === "command=fetch" || line === "command=ls-refs") { + req.command = line === "command=fetch" ? "fetch" : "ls-refs"; + } else if (line === "no-progress" || line === "symrefs" || line === "peel") { + req.caps.add(line); + } else if (line.startsWith("want ")) { + addUnique(req.wants, seenWants, line.slice(5, 45)); + // capabilities ride on the first want line + for (const cap of line.slice(45).trim().split(" ")) if (cap) req.caps.add(cap); + } else if (line.startsWith("have ")) { + addUnique(req.haves, seenHaves, line.slice(5, 45)); + } else if (line.startsWith("shallow ")) { + addUnique(req.clientShallows, seenShallows, line.slice(8, 48)); + } else if (line.startsWith("deepen ")) { + req.deepen = parseInt(line.slice(7), 10) || 0; + } else if (line === "done") { + req.done = true; + } + } + return req; +} + +async function lsRefs(store: GitStore, req: UploadRequest): Promise { + const lines: Uint8Array[] = []; + const head = store.resolveHead(); + if (head) lines.push(pkt(`${head} HEAD${req.caps.has("symrefs") ? ` symref-target:${store.head()}` : ""}\n`)); + for (const ref of store.refs()) { + let peeled = ""; + if (req.caps.has("peel") && ref.name.startsWith("refs/tags/") && store.typeAndSize(ref.target)?.type === "tag") { + const oid = await peelToCommitOid(store, ref.target); + if (oid) peeled = ` peeled:${oid}`; + } + lines.push(pkt(`${ref.target} ${ref.name}${peeled}\n`)); + } + return concat([...lines, FLUSH]); +} + +/** Follow tag objects down to the underlying commit oid (or null). */ +async function peelToCommitOid(store: GitStore, oid: string): Promise { + for (let i = 0; i < 10; i++) { + const obj = await store.get(oid); + if (!obj) return null; + if (obj.type === "commit") return oid; + if (obj.type === "tag") { + oid = parseTag(obj.data).object; + continue; + } + return null; + } + return null; +} + +/** + * Newest committer time (ms) across every current ref tip and HEAD: each tip is + * peeled through annotated tags to its commit and its committer time taken; + * non-commit tips are ignored, parse errors skipped. Falls back to Date.now() + * when the repo holds no commits. Committer time is unix seconds, so ×1000. + */ +export async function latestCommitTime(store: GitStore): Promise { + const tips = new Set(); + const head = store.resolveHead(); + if (head) tips.add(head); + for (const r of store.refs()) tips.add(r.target); + let max = 0; + for (const tip of tips) { + try { + const oid = await peelToCommitOid(store, tip); + if (!oid) continue; + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + const t = parseCommit(obj.data).committer.time; + if (t > max) max = t; + } catch { + // broken/unparseable tip: skip it, never fail the push/config + } + } + return max > 0 ? max * 1000 : Date.now(); +} + +/** + * Depth-limited commit set from the wants (BFS, min depth wins; the tip is + * depth 1, like git). Boundary commits are included but their parents cut. + */ +async function computeDepthSet( + store: GitStore, + wants: string[], + depth: number +): Promise<{ commits: Set; boundary: Set }> { + const commits = new Set(); + const boundary = new Set(); + const queue: { oid: string; depth: number }[] = []; + for (const w of wants) { + const c = await peelToCommitOid(store, w); + if (c && !commits.has(c)) { + commits.add(c); + queue.push({ oid: c, depth: 1 }); + } + } + while (queue.length) { + const { oid, depth: d } = queue.shift()!; + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + const parents = parseCommit(obj.data).parents; + if (d >= depth) { + // every commit reached at the depth limit is a graft point, root commits + // included — git's get_shallow_commits() marks them unconditionally, and + // the client compares the advertised list against its own .git/shallow + boundary.add(oid); + continue; + } + boundary.delete(oid); // reachable within depth via this (shorter) path + for (const p of parents) { + if (!commits.has(p) && store.has(p)) { + commits.add(p); + queue.push({ oid: p, depth: d + 1 }); + } + } + } + return { commits, boundary }; +} + +/** + * Commits reachable from the wants without passing through one of the + * client's haves — the "interesting" side of the walk — plus the oldest + * committer date among them. Commit objects only; no trees are touched. + * + * The date is what bounds the uninteresting side: nothing older than the + * oldest thing the client is asking for can be needed as a boundary, so the + * have walk may stop there instead of marching down the whole commit graph. + */ +async function interestingCommits( + store: GitStore, + wants: string[], + haveCommits: Set, + yieldMaybe: () => Promise +): Promise<{ set: OidSet; minTime: number }> { + const set = new OidSet(4096); + const stack: string[] = []; + for (const w of wants) { + const c = await peelToCommitOid(store, w); + if (c && !haveCommits.has(c) && set.addHex(c)) stack.push(c); + } + let minTime = Infinity; + while (stack.length) { + const oid = stack.pop()!; + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + await yieldMaybe(); + const c = parseCommit(obj.data); + if (c.committer.time < minTime) minTime = c.committer.time; + for (const p of c.parents) { + if (haveCommits.has(p)) continue; // the client's side of the boundary + if (store.has(p) && set.addHex(p)) stack.push(p); + } + } + return { set, minTime }; +} + +/** + * Objects the client demonstrably already has, marked the way git marks + * UNINTERESTING: commits reachable from the haves (cut at the client's + * shallow boundaries), plus the *tree closure of the boundary commits only* + * — the client's own tips and the uninteresting parents of the commits it is + * asking for. Boundary tree descent halts the moment it reaches an object + * already known present, so shared subtrees are walked once, and history the + * fetch never touches is never inflated at all. + * + * The set is deliberately allowed to be an under-approximation: leaving an + * object out only means re-sending something the client had (a bigger pack), + * while putting one in wrongly would produce a broken pack. Every bound here + * therefore errs towards sending. + */ +async function excludedObjects( + store: GitStore, + haves: string[], + clientShallows: string[], + wants: string[] +): Promise { + const excluded = new OidSet(Math.max(haves.length * 64, 4096)); + if (!haves.length) return excluded; // full clone: nothing is excluded + + let ops = 0; + const yieldMaybe = async () => { + if (++ops % WALK_YIELD === 0) await new Promise((r) => setTimeout(r, 0)); + }; + + // the client's tips, peeled through any annotated tags + const haveCommits = new Set(); + for (const h of haves) { + if (!store.has(h)) continue; + const c = await peelToCommitOid(store, h); + if (c) haveCommits.add(c); + } + + const { set: interesting, minTime } = await interestingCommits(store, wants, haveCommits, yieldMaybe); + // minTime stays Infinity when the client wants nothing new: then no ancestor + // of a have can be a boundary and the walk stops at the haves themselves. + const cutoff = minTime === Infinity ? Infinity : minTime - WALK_DATE_SLOP; + + // uninteresting commit walk — commits and tags only, no trees + const shallowStops = new Set(clientShallows); + const commitStack: string[] = []; + for (const h of haves) { + if (store.has(h) && excluded.addHex(h)) commitStack.push(h); + } + while (commitStack.length) { + const oid = commitStack.pop()!; + const obj = await store.get(oid); + if (!obj) continue; + await yieldMaybe(); + if (obj.type === "tag") { + const t = parseTag(obj.data).object; + if (t && store.has(t) && excluded.addHex(t)) commitStack.push(t); + continue; + } + if (obj.type !== "commit") continue; + const c = parseCommit(obj.data); + if (shallowStops.has(oid)) continue; // client's history stops here + if (c.committer.time < cutoff) continue; // older than anything wanted + for (const p of c.parents) { + if (store.has(p) && excluded.addHex(p)) commitStack.push(p); + } + } + + // boundary commits whose trees are worth marking: the client's own tips + // (it has those trees in full) and the uninteresting parents of interesting + // commits (git's mark_edges_uninteresting). + const boundary: string[] = []; + for (const c of haveCommits) boundary.push(c); + for (let i = 0; i < interesting.size; i++) { + const oid = interesting.atHex(i); + if (excluded.hasHex(oid)) continue; // contested: reachable from a have too + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + await yieldMaybe(); + for (const p of parseCommit(obj.data).parents) { + if (excluded.hasHex(p)) boundary.push(p); + } + } + + const trees: string[] = []; + for (const oid of boundary) { + const obj = await store.get(oid); + if (obj?.type !== "commit") continue; + const tree = parseCommit(obj.data).tree; + if (tree && excluded.addHex(tree)) trees.push(tree); + } + while (trees.length) { + const oid = trees.pop()!; + const obj = await store.get(oid); + if (obj?.type !== "tree") continue; + await yieldMaybe(); + for (const e of parseTree(obj.data)) { + if (isGitlinkMode(e.mode)) continue; + // already present => the whole subtree below it is too; stop descending + if (excluded.addHex(e.oid) && isTreeMode(e.mode)) trees.push(e.oid); + } + } + return excluded; +} + +/** + * Objects to pack: closure of wants, minus excluded, cut at commitLimit. + * Returned as one OidSet whose tagged sub-set is the pack contents — the + * untagged remainder is the walk's visited bookkeeping, which is a strict + * superset, so one set carries both roles at half the per-object cost. + * + * `descendThroughExcluded` is set only when the client is deepening: with a + * shallow client, commits BELOW its boundary are not excluded and must be + * reachable even when the walk enters via commits it already has (deepen and + * unshallow fetches). On an ordinary fetch the walk must stop dead at an + * excluded commit — descending anyway re-sends the history the client + * deliberately does not have, and strands it below its own shallow graft. + * Blobs are added by type lookup alone — never inflated during the walk. + */ +async function collectPackOids( + store: GitStore, + wants: string[], + excluded: OidSet, + commitLimit: Set | null, + descendThroughExcluded: boolean, + expected: number +): Promise { + // The frontier is the visited set itself, walked in insertion order by a + // cursor: a child is appended with addHex (deduped in place) and reached + // when the cursor gets to it, so there is no separate stack of hex oids to + // hold alongside the OidSet. The result set is decided by membership, so + // this BFS and the old DFS produce the identical walk and marked sub-set. + const walk = new OidSet(expected); + for (const w of wants) walk.addHex(w); + let ops = 0; + for (let i = 0; i < walk.size; i++) { + const oid = walk.atHex(i); + if (++ops % WALK_YIELD === 0) await new Promise((r) => setTimeout(r, 0)); + const meta = store.typeAndSize(oid); + if (!meta) throw new Error(`missing object ${oid}`); + if (meta.type === "commit" && commitLimit && !commitLimit.has(oid)) continue; + if (excluded.hasHex(oid)) { + if (descendThroughExcluded && meta.type === "commit") { + const full = (await store.get(oid))!; + for (const p of parseCommit(full.data).parents) walk.addHex(p); + } + continue; + } + walk.markHex(oid); + if (meta.type === "blob") continue; // leaf: membership only + for (const child of childOids((await store.get(oid))!)) walk.addHex(child); + } + return walk; +} + +/** + * POST /git-upload-pack — stateless protocol v0 with single-ack negotiation, + * shallow (--depth) support, side-band-64k, and a streamed pack response. + * Stored pack entries are copied verbatim (deltas preserved) whenever their + * base ships in the same pack; everything else is inflated and re-deflated. + */ +export async function uploadPack( + store: GitStore, + body: Uint8Array, + release: () => void = () => {}, + packCache?: PackCache +): Promise { + const headers = { + "content-type": "application/x-git-upload-pack-result", + "cache-control": "no-cache", + }; + const req = parseUploadRequest(body); + if (req.command === "ls-refs") { + release(); + return new Response(await lsRefs(store, req) as unknown as BodyInit, { headers }); + } + const v2 = req.command === "fetch"; + if (!req.wants.length || req.wants.some((w) => !isOid(w))) { + release(); + return new Response(pkt("ERR no valid wants\n") as unknown as BodyInit, { headers }); + } + // a want must be an object we currently advertise, not merely one we store + const allowed = await advertisedOids(store); + for (const w of req.wants) { + if (!allowed.has(w) || !store.has(w)) { + release(); + return new Response(pkt(`ERR upload-pack: not our ref ${w}\n`) as unknown as BodyInit, { headers }); + } + } + + const preamble: Uint8Array[] = []; + + // shallow section (only when the client asked to deepen) + let commitLimit: Set | null = null; + if (req.deepen > 0) { + if (v2) preamble.push(pkt("shallow-info\n")); + const clientShallowSet = new Set(req.clientShallows); + if (req.deepen >= INFINITE_DEPTH) { + // --unshallow: full history, everything the client thought was shallow opens up + for (const s of req.clientShallows) { + if (store.has(s)) preamble.push(pkt(`unshallow ${s}\n`)); + } + } else { + const { commits, boundary } = await computeDepthSet(store, req.wants, req.deepen); + commitLimit = commits; + for (const b of boundary) { + if (!clientShallowSet.has(b)) preamble.push(pkt(`shallow ${b}\n`)); + } + for (const s of req.clientShallows) { + if (commits.has(s) && !boundary.has(s)) preamble.push(pkt(`unshallow ${s}\n`)); + } + } + preamble.push(v2 ? te.encode("0001") : FLUSH); + } + if (v2 && !req.done) preamble.length = 0; + + // Negotiation. A round with neither haves nor done (shallow discovery) gets + // no ack line at all — a stray NAK would desync the client's stateless + // response stream. + // + // Single-ack cannot carry a stateless fetch on its own: `ACK ` means + // "negotiation over, pack follows", so a client that receives one mid-round + // stops negotiating and reads the response as a pack — but git only batches + // 16 haves per round, and the follow-up request it sends carries no haves at + // all. The pack therefore has to be produced by the same request that + // carried the haves, which is exactly what multi_ack_detailed's `ready` plus + // `no-done` is for. This mirrors upload-pack's wire shape line for line; + // clients that negotiate neither capability keep the single-ack path. + const common = req.haves.filter((h) => isOid(h) && store.has(h)); + const lastCommon = common.length ? common[common.length - 1] : null; + let sendPack = req.done; + if (v2) { + if (req.done) preamble.push(pkt("packfile\n")); + else { + const acknowledgments = common.length ? common.map((oid) => pkt(`ACK ${oid}\n`)) : [pkt("NAK\n")]; + preamble.push(pkt("acknowledgments\n"), ...acknowledgments, FLUSH); + } + } else if (!req.caps.has("multi_ack_detailed")) { + if (req.done || req.haves.length) { + preamble.push(pkt(common.length ? `ACK ${common[0]}\n` : "NAK\n")); + } + } else if (req.done) { + for (const c of common) preamble.push(pkt(`ACK ${c} common\n`)); + preamble.push(pkt(lastCommon ? `ACK ${lastCommon}\n` : "NAK\n")); + } else if (req.haves.length) { + for (const c of common) preamble.push(pkt(`ACK ${c} common\n`)); + if (lastCommon && req.caps.has("no-done")) { + // enough common ground to build the pack, and the client agreed it can + // be answered without a `done` round trip: reply with it right here, + // while the haves are still in hand + preamble.push(pkt(`ACK ${lastCommon} ready\n`)); + preamble.push(pkt("NAK\n")); + preamble.push(pkt(`ACK ${lastCommon}\n`)); + sendPack = true; + } else { + preamble.push(pkt("NAK\n")); // keep negotiating + } + } + + if (!sendPack) { + // negotiation round only — client will POST again + release(); + return new Response(concat(preamble) as unknown as BodyInit, { headers }); + } + + const sideband = v2 || req.caps.has("side-band-64k"); + const noProgress = req.caps.has("no-progress"); + + // Full-clone fast path: no haves, not shallow/deepen, and the wants are + // exactly the current ref tips. The reachable object set is then identical to + // what the graph walk would rediscover, so serve it from the versioned cache + // and skip the walk (and every commit/tree inflation it drives) entirely. A + // missing or stale cache (version mismatch, or any failure) falls straight + // through to the walk, which then repopulates it — so a wrong pack is never + // served, and existing repos become fast on their next full clone. + const fullClone = !req.haves.length && req.deepen === 0 && wantsAreAllTips(store, req.wants); + + // R2 full-clone offload (write side). Only a standard side-band-64k full clone + // is eligible, and it is reached only after the advertised-oids gate above — so + // the versioned key can never warm an unreachable/force-pushed object. The key + // is the ref version, so a push/force-push/delete lands on a fresh key and + // stale packs are simply never referenced. HITs are served by the Worker + // streaming R2 directly; the DO only reaches here on a MISS, where it serves + // the client and self-warms the cache via multipart while it streams (see + // `capture` below). Absent R2 (celld / no binding) this is a plain DO clone. + const r2Key = + fullClone && sideband && packCache ? `pack/${packCache.repo}/${store.reachableVersion()}` : null; + + // Warm full-clone fast path: the reachable set is persisted and current, so + // stream the pack straight out of storage in (pack_id, offset) order without + // ever loading the object set into the isolate. This is the O(1)-memory clone + // — no OidSet, no parallel typed arrays — bounded by one keyset page instead + // of the object count. A cold or stale cache falls through to the walk below, + // which rebuilds and persists the set (one in-RAM walk, then warm forever). + if (fullClone && store.reachableCacheValid()) { + return warmFullClone(store, { + preamble, + sideband, + noProgress, + r2Key, + packCache, + release, + headers, + }); + } + + let send = fullClone ? store.loadReachable() : null; + if (!send) { + const walkVersion = store.reachableVersion(); + const excluded = await excludedObjects(store, req.haves, req.clientShallows, req.wants); + // a plain clone enumerates the whole database: size the walk's set up front + // so it never doubles (a doubling keeps the old and new arrays live at once) + const expected = + !req.haves.length && !commitLimit && !req.deepen ? Math.max(store.objectCount(), 4096) : 4096; + send = await collectPackOids( + store, + req.wants, + excluded, + commitLimit, + req.deepen > 0, // descendThroughExcluded: only while deepening/unshallowing + expected + ); + if (fullClone) { + try { + await store.saveReachable(send, walkVersion); + } catch { + // the cache is best-effort: a failed persist just means the next full + // clone walks again, never a wrong pack + } + } + } + // Emit objects in pack storage order — (packId, offset) — rather than the + // DFS walk order they were collected in. Reused entries are copied straight + // out of stored packs via readRaw, and the raw-chunk LRU only pays off when + // consecutive reads stay inside the same 1MB pack chunk; walk order jumps + // all over the pack, so it rarely does. Marching sequentially through each + // pack lifts that hit rate to ~100% and cuts per-object decode cost. + // + // Order-safe: the SET of emitted entries and every entry's bytes are decided + // by set membership alone (isMarkedHex on the delta base), never by position, + // so only the ordering changes. Delta entries are re-addressed as REF-deltas + // (see PackWriter.rawDelta) and git's index-pack resolves ref-deltas in any + // order via a second pass; no ofs-deltas are ever emitted. Loose objects + // (no pack entry) sort last, ordered by oid, for a stable total order. + // + // Only worth it once the packs outgrow the raw-chunk LRU: below that every + // chunk stays cached regardless of order, so the sort would be pure overhead. + // The arrays stay null then and emission falls back to walk order with a + // per-object lookup, exactly as before. + // + // The lookups done to build the sort key are *retained* — in LEAN parallel + // typed arrays, not an array of PackedEntry objects — and reused by the + // stream, so sorting adds an in-memory sort but not a second round of SQL + // lookups. Storing the reused fields as five typed arrays (~28 B/obj) rather + // than live objects (~204 B/obj) is what keeps a one-shot full clone inside + // the 128MB isolate at multi-million-object scale. + // + // ePack Int32 pack id (1-based), or LOOSE_PACK for objects with no + // pack entry (loose / unindexed) — those sort last, by oid. + // eDataOff Float64 start of the stored (compressed) region. Offsets on a + // pack past 4GB exceed 2^32, so this must NOT be a Uint32. The + // (packId, dataOff) pair is also the sort key: dataOff rises + // monotonically with entry offset within a pack, so ordering by + // it reproduces pack storage order exactly. + // eDataLen Uint32 length of that region (a single entry never reaches + // the 4GB a Uint32 caps, and readRaw could not allocate one). + // eSize Float64 uncompressed entry size for the pack object header. + // A blob copied verbatim on a big-heap celld node can exceed 4GB + // uncompressed, so this is not a Uint32 either. + // eCode Int32 how to emit the object, folding type and delta base + // into one slot (they are mutually exclusive per entry): + // >= 0 ref-delta whose base ships in this pack; the value is + // the base's insertion index in `send` (base oid = + // send.atHex(code)). + // <= -3 full entry copied verbatim; NUM_TYPE[-2 - code] is its + // type (commit=-3, tree=-4, blob=-5, tag=-6). + // -1 inflate via store.get: a loose object, or a delta whose + // base is not being sent (so it cannot be a ref-delta). + const total = send.markedSize; + let order: Int32Array | null = null; + let ePack: Int32Array | null = null; + let eDataOff: Float64Array | null = null; + let eDataLen: Uint32Array | null = null; + let eSize: Float64Array | null = null; + let eCode: Int32Array | null = null; + const LOOSE_PACK = 0x7fffffff; // sorts after every real (1-based) pack id + if (store.packs.totalPackBytes() > store.packs.rawCacheWindow()) { + ePack = new Int32Array(total); + eDataOff = new Float64Array(total); + eDataLen = new Uint32Array(total); + eSize = new Float64Array(total); + eCode = new Int32Array(total); + for (let i = 0; i < total; i++) { + const entry = store.packs.lookup(send.markedAtHex(i)); + if (!entry) { + ePack[i] = LOOSE_PACK; + eCode[i] = -1; + } else { + ePack[i] = entry.packId; + eDataOff[i] = entry.dataOff; + eDataLen[i] = entry.dataLen; + eSize[i] = entry.entrySize; + if (entry.baseOid) { + // ref-delta only when the base also ships here; else inflate it + eCode[i] = send.isMarkedHex(entry.baseOid) ? send.indexOfHex(entry.baseOid) : -1; + } else { + eCode[i] = -2 - TYPE_NUM[entry.type]; + } + } + if ((i & 8191) === 8191) await new Promise((r) => setTimeout(r, 0)); + } + order = new Int32Array(total); + for (let i = 0; i < total; i++) order[i] = i; + order.sort((a, b) => { + if (ePack![a] !== ePack![b]) return ePack![a] - ePack![b]; + if (ePack![a] === LOOSE_PACK) { + const oa = send.markedAtHex(a); + const ob = send.markedAtHex(b); + return oa < ob ? -1 : oa > ob ? 1 : 0; + } + return eDataOff![a] - eDataOff![b]; + }); + } + + // stream the pack: preamble, then pack bytes (side-band framed if negotiated) + const pending: Uint8Array[] = [concat(preamble)]; + let buffered: Uint8Array[] = []; + let bufferedLen = 0; + const flushBuffered = () => { + if (!bufferedLen) return; + const payload = concat(buffered); + buffered = []; + bufferedLen = 0; + if (sideband) pending.push(...sidebandFrames(1, payload)); + else pending.push(payload); + }; + // Self-warm R2 on a full-clone MISS: tee the raw pack (writer output, verbatim + // — same bytes a later HIT re-frames) into a multipart upload alongside the + // live stream. The pack streams into R2 in 16 MiB parts as it is generated, so + // isolate memory is never proportional to pack size and there is no size cap. + // A failed begin just streams the clone without caching. + let capture: MultipartCapture | null = null; + if (r2Key && packCache) { + const mp = await packCache.beginMultipart(r2Key, total); + if (mp) capture = new MultipartCapture(mp); + } + const writer = new PackWriter((chunk) => { + if (capture) capture.push(chunk); + buffered.push(chunk); + bufferedLen += chunk.length; + if (bufferedLen >= SIDEBAND_CHUNK) flushBuffered(); + }); + + let i = 0; + let finished = false; + const stream = new ReadableStream({ + start: (ctrl) => { + if (sideband && !noProgress) { + pending.push(...sidebandFrames(2, te.encode(`Enumerating objects: ${total}, done.\n`))); + } + writer.header(total); + for (const c of pending) ctrl.enqueue(c); + pending.length = 0; + }, + pull: async (ctrl) => { + try { + for (let n = 0; n < 64 && i < total; n++, i++) { + const idx = order ? order[i] : i; + if (!eCode) { + // unsorted (small-pack) path: no sort pass ran, so do a fresh + // per-object lookup in walk order, exactly as before OPT 2. + const oid = send.markedAtHex(idx); + const entry = store.packs.lookup(oid); + if (entry && !entry.baseOid) { + writer.rawFull(entry.type, entry.entrySize, await store.packs.readRaw(entry.packId, entry.dataOff, entry.dataLen)); + } else if (entry && entry.baseOid && send.isMarkedHex(entry.baseOid)) { + writer.rawDelta(entry.entrySize, entry.baseOid, await store.packs.readRaw(entry.packId, entry.dataOff, entry.dataLen)); + } else { + const obj = await store.get(oid); + if (!obj) throw new Error(`missing object ${oid}`); + writer.object(obj.type, obj.data); + } + continue; + } + // sorted path: everything needed to emit the object was captured in + // the lean typed arrays, so no SQL lookup happens here. + const code = eCode[idx]; + if (code <= -3) { + writer.rawFull(NUM_TYPE[-2 - code], eSize![idx], await store.packs.readRaw(ePack![idx], eDataOff![idx], eDataLen![idx])); + } else if (code >= 0) { + writer.rawDelta(eSize![idx], send.atHex(code), await store.packs.readRaw(ePack![idx], eDataOff![idx], eDataLen![idx])); + } else { + const oid = send.markedAtHex(idx); + const obj = await store.get(oid); + if (!obj) throw new Error(`missing object ${oid}`); + writer.object(obj.type, obj.data); + } + } + if (i >= total && !finished) { + finished = true; + writer.finish(); + flushBuffered(); + if (sideband) pending.push(FLUSH); + } else { + flushBuffered(); + } + for (const c of pending) ctrl.enqueue(c); + pending.length = 0; + // Warm R2 in lock-step with generation: the client already has this + // batch's bytes, and awaiting the part upload here is what bounds isolate + // memory to one part regardless of pack size. finish() flushes the final + // part and completes; a failure aborts, leaving no partial R2 object. + if (capture) { + if (finished) await capture.finish(); + else await capture.drain(); + } + if (finished) { + ctrl.close(); + release(); // stream fully drained: this upload no longer holds a slot + } + } catch (err) { + if (capture) await capture.abort(); + release(); + ctrl.error(err); + } + }, + cancel: async () => { + // client went away mid-transfer (e.g. negotiation round abort): abort the + // half-built multipart upload so R2 keeps no partial object + if (capture) await capture.abort(); + release(); + }, + }); + return new Response(stream, { headers }); +} + +/** + * Stream a full clone straight from the persisted reachable set, holding no + * object set in the isolate. The reachable cache is current (the caller checked + * `reachableCacheValid`), so the objects to send are exactly its rows: emit the + * packed ones in (pack_id, offset) storage order a keyset page at a time, then + * the loose ones by oid. Peak memory is one page plus one object, independent + * of repo size — the walk path's OidSet and parallel typed arrays are gone. + * + * Emission is byte-identical to the walk path: a stored delta ships as a + * ref-delta when its base is also reachable (so also sent), else it is inflated + * whole; index-pack resolves ref-deltas by oid in any order. `total` is the + * reachable count, declared in the header; if the set drifts mid-stream (a push + * landing during the clone) the count guard aborts rather than ship a pack that + * disagrees with its header — the client simply retries. + */ +async function warmFullClone( + store: GitStore, + opts: { + preamble: Uint8Array[]; + sideband: boolean; + noProgress: boolean; + r2Key: string | null; + packCache: PackCache | undefined; + release: () => void; + headers: Record; + }, +): Promise { + const { preamble, sideband, noProgress, r2Key, packCache, release, headers } = opts; + const total = store.reachableCount(); + const PAGE = 1000; + + // One emit-thunk per object, in storage order: every packed reachable object + // (marching packs sequentially), then every loose reachable object by oid. + async function* objects(): AsyncGenerator<(w: PackWriter) => Promise> { + let curPack = 0; + let curOff = -1; + for (;;) { + const rows = store.reachablePackedAfter(curPack, curOff, PAGE); + for (const e of rows) { + curPack = e.packId; + curOff = e.offset; + if (e.baseOid !== null && store.reachableHas(e.baseOid)) { + const base = e.baseOid; + yield async (w) => + w.rawDelta(e.entrySize, base, await store.packs.readRaw(e.packId, e.dataOff, e.dataLen)); + } else if (e.baseOid !== null) { + // base is not itself being sent: it cannot be a ref-delta, inflate it + yield async (w) => { + const obj = await store.get(e.oid); + if (!obj) throw new Error(`missing object ${e.oid}`); + w.object(obj.type, obj.data); + }; + } else { + yield async (w) => + w.rawFull(e.type, e.entrySize, await store.packs.readRaw(e.packId, e.dataOff, e.dataLen)); + } + } + if (rows.length < PAGE) break; + } + let afterOid = ""; + for (;;) { + const loose = store.reachableLooseAfter(afterOid, PAGE); + for (const oid of loose) { + afterOid = oid; + yield async (w) => { + const obj = await store.get(oid); + if (!obj) throw new Error(`missing object ${oid}`); + w.object(obj.type, obj.data); + }; + } + if (loose.length < PAGE) break; + } + } + const it = objects(); + + const pending: Uint8Array[] = [concat(preamble)]; + let buffered: Uint8Array[] = []; + let bufferedLen = 0; + const flushBuffered = () => { + if (!bufferedLen) return; + const payload = concat(buffered); + buffered = []; + bufferedLen = 0; + if (sideband) pending.push(...sidebandFrames(1, payload)); + else pending.push(payload); + }; + let capture: MultipartCapture | null = null; + if (r2Key && packCache) { + const mp = await packCache.beginMultipart(r2Key, total); + if (mp) capture = new MultipartCapture(mp); + } + const writer = new PackWriter((chunk) => { + if (capture) capture.push(chunk); + buffered.push(chunk); + bufferedLen += chunk.length; + if (bufferedLen >= SIDEBAND_CHUNK) flushBuffered(); + }); + + let emitted = 0; + let finished = false; + const stream = new ReadableStream({ + start: (ctrl) => { + if (sideband && !noProgress) { + pending.push(...sidebandFrames(2, te.encode(`Enumerating objects: ${total}, done.\n`))); + } + writer.header(total); + for (const c of pending) ctrl.enqueue(c); + pending.length = 0; + }, + pull: async (ctrl) => { + try { + let drained = false; + for (let n = 0; n < 64; n++) { + const next = await it.next(); + if (next.done) { + drained = true; + break; + } + await next.value(writer); + emitted++; + } + if (drained && !finished) { + // A count check, not a full set-consistency check: it catches a push + // that grew or shrank the reachable set mid-stream (the pack would + // disagree with its declared header), so the client retries rather + // than resolve a malformed pack. The cold path snapshots the set into + // an OidSet and has no such window; this is the warm path's tradeoff. + if (emitted !== total) { + throw new Error(`reachable set drifted mid-clone: emitted ${emitted}, declared ${total}`); + } + finished = true; + writer.finish(); + flushBuffered(); + if (sideband) pending.push(FLUSH); + } else { + flushBuffered(); + } + for (const c of pending) ctrl.enqueue(c); + pending.length = 0; + if (capture) { + if (finished) await capture.finish(); + else await capture.drain(); + } + if (finished) { + ctrl.close(); + release(); + } + } catch (err) { + if (capture) await capture.abort(); + release(); + ctrl.error(err); + } + }, + cancel: async () => { + if (capture) await capture.abort(); + release(); + }, + }); + return new Response(stream, { headers }); +} + +/** Is `anc` an ancestor of (or equal to) `desc`? Bounded walk. */ +export async function isAncestor(store: GitStore, anc: string, desc: string): Promise { + if (anc === desc) return true; + const seen = new Set([desc]); + const stack = [desc]; + let visited = 0; + while (stack.length && visited++ < 10000) { + const obj = await store.get(stack.pop()!); + if (obj?.type !== "commit") continue; + for (const p of parseCommit(obj.data).parents) { + if (p === anc) return true; + if (!seen.has(p)) { + seen.add(p); + stack.push(p); + } + } + } + return false; +} + +export interface PushCommand { + old: string; + next: string; + ref: string; +} + +export interface CommandResult { + ref: string; + ok: boolean; + msg?: string; +} + +/** Parse the command section of a receive-pack request (already buffered). */ +export function parsePushCommands(section: Uint8Array): { commands: PushCommand[]; caps: string[] } { + const parser = new PktParser(section); + const commands: PushCommand[] = []; + let caps: string[] = []; + for (let p = parser.read(); p !== null; p = parser.read()) { + if (p.kind === "flush") break; + if (p.kind !== "line") continue; + let line = p.text; + const nul = line.indexOf("\0"); + if (nul !== -1) { + caps = line.slice(nul + 1).trim().split(" "); + line = line.slice(0, nul); + } + const m = line.match(/^([0-9a-f]{40}) ([0-9a-f]{40}) (.+)$/); + if (m) commands.push({ old: m[1], next: m[2], ref: m[3] }); + } + return { commands, caps }; +} + +/** + * Every object in the closure of `tip` is present, so setting a ref to it + * cannot brick the repo. A thin/broken pack that fails to close over its new + * ref leaves a referenced object absent; walking commit->tree->subtrees+blobs + * (and tag->target) with a presence probe at each node catches it before the + * ref moves. `known` is pre-seeded with the pre-existing ref tips, whose + * closure was validated at their own push, so descent stops there — the walk + * touches only objects this push introduced (or older objects no ref holds). + * + * SAM: the walk is transactional per command. Newly reached oids go into a + * scratch set and are merged into `known` only once the whole closure is + * proven present. Upstream walked straight into `known`, so a command whose + * walk failed left its unproven frontier there and a later command in the + * same push stopped at it: a ref could then name an object that does not + * exist (Codex r4633317762). `known` therefore only ever holds validated + * closures, which is also what commitPush folds into the reachable cache. + */ +async function reachableComplete( + store: GitStore, + tip: string, + known: OidSet, + failed: OidSet +): Promise { + if (known.hasHex(tip)) return true; // tip already in a validated closure + if (failed.hasHex(tip)) return false; // an earlier command in this push proved it incomplete + // Cursor BFS over the scratch set itself: newly reached oids append past the + // cursor, so no separate hex-oid stack is needed to walk it. Parallel arrays + // hold each entry's BFS parent and the type its referencing edge requires. + const fresh = new OidSet(1024); + let parent = new Uint32Array(1024); + let expect: (ObjType | null)[] = [null]; // the tip may be any type + fresh.addHex(tip); + // SAM: every oid on the BFS path from the tip to a failing entry has that + // entry in its closure, so it is incomplete for the rest of this push. + // Recording the path means repeated or overlapping failing commands stop + // at the first known-bad oid instead of re-walking the same objects. + const fail = (i: number): false => { + for (let j = i; ; j = parent[j]) { + failed.addHex(fresh.atHex(j)); + if (j === 0) return false; + } + }; + for (let i = 0; i < fresh.size; i++) { + const oid = fresh.atHex(i); + if (i > 0 && failed.hasHex(oid)) return fail(i); + const meta = store.typeAndSize(oid); + if (!meta) return fail(i); + // A type mismatch is the referencing object's fault, not this object's: blame the + // parent (and its ancestors) so a valid object shared elsewhere stays usable. + if (expect[i] !== null && meta.type !== expect[i]) return fail(parent[i]); + if (meta.type === "blob") continue; + const obj = await store.get(oid); + if (!obj) return fail(i); + let children: ChildRef[]; + try { + assertGitObjectShape(obj); + children = childRefs(obj); + } catch (err) { + // SAM: a commit, tag or tree that does not parse cannot have a proven + // closure; reject this command rather than failing the whole push. + if (err instanceof GitParseError) return fail(i); + throw err; + } + for (const child of children) { + if (known.hasHex(child.oid) || fresh.hasHex(child.oid)) { + // Already validated or queued under another edge: this edge still has to name + // an object of the type it requires (absent ones fail when their entry is walked). + const type = store.typeAndSize(child.oid)?.type; + if (type !== undefined && type !== child.type) return fail(i); + continue; + } + fresh.addHex(child.oid); + if (fresh.size > parent.length) { + const bigger = new Uint32Array(parent.length * 2); + bigger.set(parent); + parent = bigger; + } + parent[fresh.size - 1] = i; + expect[fresh.size - 1] = child.type; + } + } + for (let i = 0; i < fresh.size; i++) known.addHex(fresh.atHex(i)); + return true; +} + +/** Per-command outcome decided by the object-reading validation pass. */ +interface PushDecision { + ref: string; + expectedOld: string; // CAS value re-checked atomically at commit + reject?: string; // ng message; the command does not apply + del?: boolean; // delete the ref + set?: string; // move the ref to this oid + forced?: boolean; // a set that strands old history (non-fast-forward) +} + +/** Result of the async push validation, consumed by the sync commit under a savepoint. */ +export interface PushPlan { + decisions: PushDecision[]; + known: OidSet; + hadCache: boolean; +} + +/** + * Validate push commands against the (already ingested) object database. This + * is the object-reading half — connectivity + ancestry walks — and is async + * because an R2-backed pack's bytes are fetched over the network. It performs no + * writes; the ref mutations happen in commitPush under a savepoint. Splitting + * the read pass out is what lets the writes stay inside transactionSync (which + * cannot await) while still reading R2-backed objects. Pushes are serialized + * (receiveChain) and only pushes write refs, so ref state read here is stable + * through to commit; commitPush re-checks each CAS atomically regardless. + */ +/** The child oids a non-blob object references (blobs are leaves). */ +function childOids(obj: { type: ObjType; data: Uint8Array }): string[] { + if (obj.type === "commit") { + const c = parseCommit(obj.data); + return [c.tree, ...c.parents]; + } + if (obj.type === "tag") { + const t = parseTag(obj.data); + return t.object ? [t.object] : []; + } + if (obj.type === "tree") { + const out: string[] = []; + for (const e of parseTree(obj.data)) if (!isGitlinkMode(e.mode)) out.push(e.oid); + return out; + } + return []; +} + +/** Git's file modes (any 100xxx permission set), plus symlink, tree and gitlink. */ +const TREE_MODE = /^(100[0-7]{3}|120000|40000|160000)$/; + +/** Bytes as a one-char-per-byte string: lossless, unlike a UTF-8 decode (BOMs, invalid bytes). */ +function byteString(data: Uint8Array, start: number, end: number): string { + let out = ""; + for (let i = start; i < end; i += 8192) { + out += String.fromCharCode(...data.subarray(i, Math.min(end, i + 8192))); + } + return out; +} + +/** + * Header lines of a commit or tag, as raw byte strings, or null when the header + * section is not newline-terminated (git cannot parse a tag whose last header + * lacks its newline). The section ends at the first blank line or at the end. + */ +function rawHeaderLines(data: Uint8Array): string[] | null { + let stop = data.length; + for (let i = 0; i + 1 < data.length; i++) { + if (data[i] === 10 && data[i + 1] === 10) { + stop = i + 1; + break; + } + } + if (stop === 0 || data[stop - 1] !== 10) return null; + const lines: string[] = []; + for (let i = 0, start = 0; i < stop; i++) { + if (data[i] === 10) { + lines.push(byteString(data, start, i)); + start = i + 1; + } + } + return lines; +} + +function headerKeyList(lines: string[]): string[] { + return lines.filter((l) => !l.startsWith(" ")).map((l) => (l.includes(" ") ? l.slice(0, l.indexOf(" ")) : l)); +} + +/** `.git` as git's own path checks see it: case, trailing dots/spaces, NTFS short name and streams. */ +function isDotGitName(name: string): boolean { + const n = name.toLowerCase().replace(/[ .]+$/, ""); + return n === ".git" || n === "git~1" || n.startsWith(".git:"); +} + +/** `.gitmodules` in the same forms git checks: case, trailing dots/spaces, NTFS short name and streams. */ +function isDotGitmodulesName(name: string): boolean { + const n = name.toLowerCase().replace(/[ .]+$/, ""); + return n === ".gitmodules" || n === "gitmod~1" || n.startsWith(".gitmodules:"); +} + +const OID_LINE = /^[0-9a-f]{40}$/; +/** Longest single path component git checks out (NAME_MAX). */ +const MAX_TREE_NAME_BYTES = 255; + +/** + * SAM: refuse objects git itself cannot read, so a pushed object can never make the + * repository uncloneable. The parsers above are lenient (any header order, lossy + * UTF-8 decoding); git requires a commit to start with `tree` and its parents, a tag + * to start with `object`, `type`, `tag`, newline-terminated headers, and tree entries + * with a known mode and a plain, unique name. Checked on raw bytes, so a BOM or an + * invalid UTF-8 byte is neither hidden nor mistaken for another name. + */ +function assertGitObjectShape(obj: { type: ObjType; data: Uint8Array }): void { + if (obj.type === "commit" || obj.type === "tag") { + const lines = rawHeaderLines(obj.data); + if (!lines) throw new GitParseError(`${obj.type} headers are not newline-terminated`); + if (lines.some((l) => l.includes("\0"))) throw new GitParseError(`${obj.type} header contains NUL`); + // Git reads the first line by position: it must be the object's own first header, never a + // continuation line that the key list below would skip. + const first = obj.type === "commit" ? "tree " : "object "; + if (!lines[0]?.startsWith(first) || !OID_LINE.test(lines[0].slice(first.length))) { + throw new GitParseError(`${obj.type} must start with a ${first.trim()} line`); + } + const keys = headerKeyList(lines); + if (obj.type === "commit") { + let i = 0; + if (keys[i++] !== "tree") throw new GitParseError("commit must start with a tree header"); + while (keys[i] === "parent") i++; + if (keys[i] !== "author" || keys[i + 1] !== "committer") { + throw new GitParseError("commit must have author then committer after its parents"); + } + for (const k of keys.slice(i + 2)) { + if (k === "tree" || k === "parent" || k === "author" || k === "committer") { + throw new GitParseError(`commit has a misplaced ${k} header`); + } + } + } else { + if (keys[0] !== "object" || keys[1] !== "type" || keys[2] !== "tag") { + throw new GitParseError("tag must start with object, type and tag headers"); + } + const name = lines.filter((l) => !l.startsWith(" "))[2]!.slice(4); + if (!name) throw new GitParseError("tag has an empty name"); + } + } else if (obj.type === "tree") { + const data = obj.data; + const names = new Set(); + for (let pos = 0; pos < data.length; ) { + const sp = data.indexOf(32, pos); + const nul = sp === -1 ? -1 : data.indexOf(0, sp + 1); + if (sp === -1 || nul === -1 || nul + 21 > data.length) throw new GitParseError("malformed tree"); + const mode = byteString(data, pos, sp); + const name = byteString(data, sp + 1, nul); + pos = nul + 21; + if (!TREE_MODE.test(mode)) throw new GitParseError("tree entry has an invalid mode"); + if ( + !name || + name.length > MAX_TREE_NAME_BYTES || + name.includes("/") || + name === "." || + name === ".." || + isDotGitName(name) || + names.has(name) + ) { + throw new GitParseError("tree entry has an invalid or duplicate name"); + } + if (mode === "120000" && isDotGitmodulesName(name)) { + throw new GitParseError("tree has a .gitmodules symlink"); + } + names.add(name); + } + } +} + +/** An object a parent references, with the type the reference requires. */ +interface ChildRef { + oid: string; + type: ObjType; +} + +const TAG_TARGET_TYPES: ReadonlySet = new Set(["commit", "tree", "blob", "tag"]); + +/** + * The objects a non-blob object references (blobs are leaves), each with the type + * git requires at that edge. SAM: upstream returned bare oids, so a commit whose + * "tree" was a blob, or whose parent was a tree, passed the presence-only walk and + * then broke every clone ("bad tree pointer"); the walk now checks each edge's type. + */ +function childRefs(obj: { type: ObjType; data: Uint8Array }): ChildRef[] { + if (obj.type === "commit") { + const c = parseCommit(obj.data); + return [{ oid: c.tree, type: "tree" }, ...c.parents.map((oid) => ({ oid, type: "commit" as ObjType }))]; + } + if (obj.type === "tag") { + const t = parseTag(obj.data); + if (!TAG_TARGET_TYPES.has(t.type)) throw new GitParseError("tag has invalid type header"); + return [{ oid: t.object, type: t.type as ObjType }]; + } + if (obj.type === "tree") { + const out: ChildRef[] = []; + for (const e of parseTree(obj.data)) { + if (isGitlinkMode(e.mode)) continue; + out.push({ oid: e.oid, type: isTreeMode(e.mode) ? "tree" : "blob" }); + } + return out; + } + return []; +} + +/** + * SAM: the ancestry check only decides whether an update strands history (GC and + * cache invalidation). When a heavy history exhausts the push's work budget, treat + * the update as forced, the conservative answer, rather than failing the push. + */ +async function isAncestorOrForced(store: GitStore, old: string, next: string): Promise { + try { + return await isAncestor(store, old, next); + } catch (err) { + const msg = err instanceof Error ? err.message : ""; + if (msg.includes("exceeds decompression budget") || msg.includes("exceeds time budget")) return false; + throw err; + } +} + +export async function validatePush( + store: GitStore, + commands: PushCommand[], + unpackError: string | null +): Promise { + // whether the reachable cache is valid for the pre-push refs: only then can + // it be extended in place (union with the connectivity walk) instead of + // rebuilt from scratch on the next full clone + const hadCache = store.getMeta("reachable-version") === store.reachableVersion(); + // SAM: every command proves its closure by walking, with or without a cache. + // Upstream checked a cache-less push in SQL ("every child of the new pack is + // in pack_objects ∪ objects"), which is sound only if every object outside + // the new pack is itself closure-complete. Here a pack whose refs were all + // rejected stays ingested until GC reclaims it, so an earlier broken pack + // could vouch for a later command. Repository caps bound the walk. + // pre-existing ref tips bound the connectivity walk: their closure is + // already validated, so a normal fast-forward only re-checks new objects + // SAM: seeding reads no objects. Upstream peeled every ref tip here, which + // inflated each tip under the push's decompression budget on every push, so + // a handful of large tips made every later push, including the deletion + // that would remove them, exceed the budget. A walk that reaches a tagged + // commit descends through it instead (or stops at the reachable cache). + const known = new OidSet(4096); + const existing = store.refs(); + for (const r of existing) known.addHex(r.target); + const knownHead = store.resolveHead(); + if (knownHead) known.addHex(knownHead); + // oids proven to have an incomplete closure earlier in this push + const failed = new OidSet(1024); + // SAM: directory/file conflicts. Git cannot store both refs/heads/a and + // refs/heads/a/b (clients fail to fetch them), so a new ref must not be a path + // prefix of a ref, nor have one as a prefix. Deletions in this push with a + // matching old value apply first, as in git's ref transaction. + const refNames = new Set(); + const dirCounts = new Map(); + const trackRef = (name: string, delta: 1 | -1) => { + if (delta === 1) refNames.add(name); + else refNames.delete(name); + for (let k = name.indexOf("/"); k !== -1; k = name.indexOf("/", k + 1)) { + const dir = name.slice(0, k); + dirCounts.set(dir, (dirCounts.get(dir) ?? 0) + delta); + } + }; + const refConflict = (name: string) => { + if ((dirCounts.get(name) ?? 0) > 0) return true; + for (let k = name.indexOf("/"); k !== -1; k = name.indexOf("/", k + 1)) { + if (refNames.has(name.slice(0, k))) return true; + } + return false; + }; + // SAM: a ref named by more than one command is refused for all of them, as git + // refuses multiple updates of one ref in a transaction. Otherwise a deletion that + // loses its CAS to an earlier update of the same ref would still have freed the + // name for a nested ref here, leaving both stored. + const seen = new Set(); + const duplicated = new Set(); + for (const cmd of commands) { + if (seen.has(cmd.ref)) duplicated.add(cmd.ref); + seen.add(cmd.ref); + } + for (const r of existing) trackRef(r.name, 1); + for (const cmd of commands) { + if ( + cmd.next === ZERO_OID && !duplicated.has(cmd.ref) && refNames.has(cmd.ref) + && store.getRef(cmd.ref) === cmd.old + ) { + trackRef(cmd.ref, -1); + } + } + + const decisions: PushDecision[] = []; + for (const cmd of commands) { + if (unpackError) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "unpacker error" }); + continue; + } + if (!isValidGitRefName(cmd.ref)) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "funny refname" }); + continue; + } + if (duplicated.has(cmd.ref)) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "multiple updates for ref not allowed" }); + continue; + } + const current = store.getRef(cmd.ref) ?? ZERO_OID; + if (current !== cmd.old) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "fetch first" }); + continue; + } + if (cmd.next === ZERO_OID) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, del: true }); + continue; + } + if (current === ZERO_OID && refConflict(cmd.ref)) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "ref name conflicts with an existing ref" }); + continue; + } + // SAM: git refuses to write a non-commit to a branch; a clone of such a + // repository fails while updating HEAD. + if (cmd.ref.startsWith("refs/heads/") && store.typeAndSize(cmd.next)?.type !== "commit") { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "trying to write non-commit object to branch" }); + continue; + } + const connected = await reachableComplete(store, cmd.next, known, failed); + if (!connected) { + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, reject: "missing necessary objects" }); + continue; + } + const forced = cmd.old !== ZERO_OID && !(await isAncestorOrForced(store, cmd.old, cmd.next)); + decisions.push({ ref: cmd.ref, expectedOld: cmd.old, set: cmd.next, forced }); + if (current === ZERO_OID) trackRef(cmd.ref, 1); + } + return { decisions, known, hadCache }; +} + +/** + * Apply a validated PushPlan under a savepoint (transactionSync): a multi-ref + * push must not leave half its branches moved if a later update throws. Each CAS + * is re-checked here against live ref state so the write is atomic with its + * guard; a mismatch (a ref moved between validation and commit, which the push + * serialization normally prevents) both rejects that command and forces the + * reachable cache to be rebuilt rather than extended from a now-stale walk. + */ +export function commitPush(store: GitStore, plan: PushPlan): { results: CommandResult[]; changed: boolean; needsGc: boolean } { + const results: CommandResult[] = []; + let changed = false; + let needsGc = false; + let casMismatch = false; + // SAM: re-check the cache stamp now, before any ref moves. `plan.hadCache` was read + // before validation awaited; a clone's save may have unstamped and be rewriting the + // table since, and extending that partial table would stamp it current. + const cacheValid = plan.hadCache && store.reachableCacheValid(); + for (const d of plan.decisions) { + if (d.reject) { + results.push({ ref: d.ref, ok: false, msg: d.reject }); + continue; + } + const current = store.getRef(d.ref) ?? ZERO_OID; + if (current !== d.expectedOld) { + results.push({ ref: d.ref, ok: false, msg: "fetch first" }); + casMismatch = true; + continue; + } + if (d.del) { + // SAM: deleting a ref that does not exist succeeds without changing + // anything (as in git), so it must not queue a GC episode either. + if (current === ZERO_OID) { + results.push({ ref: d.ref, ok: true }); + continue; + } + store.delRef(d.ref); + needsGc = true; + } else { + store.setRef(d.ref, d.set!); + if (d.forced) needsGc = true; // forced update strands old history + } + changed = true; + results.push({ ref: d.ref, ok: true }); + } + + // keep HEAD pointing at a branch that exists (first push wins, prefer main/master) + if (changed && store.getRef(store.head()) === null) { + const branches = store.refs().filter((r) => r.name.startsWith("refs/heads/")); + const preferred = + branches.find((b) => b.name === "refs/heads/main") ?? + branches.find((b) => b.name === "refs/heads/master") ?? + branches[0]; + if (preferred) store.setHead(preferred.name); + } + + // maintain the full-clone reachable cache. `known` holds the connectivity + // walk: the pre-existing tips plus every object this push newly connected. On + // a pure fast-forward with a valid prior cache, union closes over exactly the + // new reachable set. Anything else (a force-push/delete that strands history, + // no prior cache to extend, or a commit-time CAS mismatch that leaves `known` + // describing a command that did not apply) invalidates it, so the next full + // clone rebuilds by walking rather than risk serving unreachable objects. + if (changed) { + if (cacheValid && !needsGc && !casMismatch) store.extendReachable(plan.known); + else store.invalidateReachable(); + } + return { results, changed, needsGc }; +} + +/** report-status payload; ends with its own flush (nested inside band 1 when sidebanded). */ +export function renderStatus(results: CommandResult[], unpackError: string | null, sideband: boolean): Uint8Array { + const lines: Uint8Array[] = [pkt(unpackError ? `unpack ${unpackError}\n` : "unpack ok\n")]; + for (const r of results) { + lines.push(pkt(r.ok ? `ok ${r.ref}\n` : `ng ${r.ref} ${r.msg}\n`)); + } + lines.push(FLUSH); + if (!sideband) return concat(lines); + return concat([...sidebandFrames(1, concat(lines)), FLUSH]); +} diff --git a/apps/api/src/vendor/dgit/git/sha1.ts b/apps/api/src/vendor/dgit/git/sha1.ts new file mode 100644 index 0000000000..2f9cd07fec --- /dev/null +++ b/apps/api/src/vendor/dgit/git/sha1.ts @@ -0,0 +1,369 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +import { SHA1_DVS, ubcCheck } from "./sha1dc-tables"; + +/** + * Incremental SHA-1. Workers' crypto.subtle is one-shot and async; pack + * streaming needs a running digest and the object database wants sync + * hashing, so we carry our own (git still speaks SHA-1 for object ids). + */ +export class Sha1 { + private h0 = 0x67452301 | 0; + private h1 = 0xefcdab89 | 0; + private h2 = 0x98badcfe | 0; + private h3 = 0x10325476 | 0; + private h4 = 0xc3d2e1f0 | 0; + private block = new Uint8Array(64); + private blockLen = 0; + private bytes = 0; + private w = new Int32Array(80); + + /** Reinitialize so one instance can hash many inputs without reallocating. */ + reset(): this { + this.h0 = 0x67452301 | 0; + this.h1 = 0xefcdab89 | 0; + this.h2 = 0x98badcfe | 0; + this.h3 = 0x10325476 | 0; + this.h4 = 0xc3d2e1f0 | 0; + this.blockLen = 0; + this.bytes = 0; + return this; + } + + update(data: Uint8Array): this { + this.bytes += data.length; + let off = 0; + if (this.blockLen > 0) { + const need = 64 - this.blockLen; + const take = Math.min(need, data.length); + this.block.set(data.subarray(0, take), this.blockLen); + this.blockLen += take; + off = take; + if (this.blockLen === 64) { + this.compress(this.block, 0); + this.blockLen = 0; + } + } + while (off + 64 <= data.length) { + this.compress(data, off); + off += 64; + } + if (off < data.length) { + this.block.set(data.subarray(off), 0); + this.blockLen = data.length - off; + } + return this; + } + + digest(): Uint8Array { + const bitLenHi = Math.floor((this.bytes * 8) / 0x100000000); + const bitLenLo = (this.bytes * 8) >>> 0; + const pad = new Uint8Array(((this.blockLen < 56 ? 56 : 120) - this.blockLen) + 8); + pad[0] = 0x80; + const dv = new DataView(pad.buffer); + dv.setUint32(pad.length - 8, bitLenHi); + dv.setUint32(pad.length - 4, bitLenLo); + this.update(pad); + const out = new Uint8Array(20); + const ov = new DataView(out.buffer); + ov.setInt32(0, this.h0); + ov.setInt32(4, this.h1); + ov.setInt32(8, this.h2); + ov.setInt32(12, this.h3); + ov.setInt32(16, this.h4); + return out; + } + + private compress(buf: Uint8Array, off: number): void { + const w = this.w; + for (let i = 0; i < 16; i++) { + const j = off + i * 4; + w[i] = (buf[j] << 24) | (buf[j + 1] << 16) | (buf[j + 2] << 8) | buf[j + 3]; + } + for (let i = 16; i < 80; i++) { + const n = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + w[i] = (n << 1) | (n >>> 31); + } + let a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4; + for (let i = 0; i < 80; i++) { + let f: number, k: number; + if (i < 20) { + f = (b & c) | (~b & d); + k = 0x5a827999; + } else if (i < 40) { + f = b ^ c ^ d; + k = 0x6ed9eba1; + } else if (i < 60) { + f = (b & c) | (b & d) | (c & d); + k = 0x8f1bbcdc | 0; + } else { + f = b ^ c ^ d; + k = 0xca62c1d6 | 0; + } + const t = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) | 0; + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + this.h0 = (this.h0 + a) | 0; + this.h1 = (this.h1 + b) | 0; + this.h2 = (this.h2 + c) | 0; + this.h3 = (this.h3 + d) | 0; + this.h4 = (this.h4 + e) | 0; + } +} + +export function sha1(data: Uint8Array): Uint8Array { + return new Sha1().update(data).digest(); +} + +/* + * SHA-1 collision detection (SHA-1DC) + * + * A port of Stevens & Shumow's sha1collisiondetection, the same defence + * git adopted after SHAttered. Every compressed block is screened by + * ubcCheck against 32 known disturbance vectors; a flagged DV is then + * confirmed by recompressing the block from the DV's test step with the + * perturbed message. If the reconstructed chaining value reproduces the + * real one, the block is half of a collision attack. + * + * Like git, safe-hash mangling stays off: the digest is always plain + * SHA-1, so object ids never move. Detection is reported out-of-band and + * the caller refuses the object. + */ + +const DVS = SHA1_DVS.map((dv) => ({ + testt: dv.testt, + maskb: dv.maskb, + dm: Int32Array.from(dv.dm), +})); + +const K0 = 0x5a827999 | 0; +const K1 = 0x6ed9eba1 | 0; +const K2 = 0x8f1bbcdc | 0; +const K3 = 0xca62c1d6 | 0; + +/** + * One step of the compression function, run over a rotating register file + * so a single loop can serve any step index. At step `i` the roles + * (a,b,c,d,e) live at v[(role - i) mod 5]. + */ +function stepForward(v: Int32Array, i: number, m: Int32Array): void { + const ia = (5 - (i % 5)) % 5; + const ib = (ia + 1) % 5; + const ic = (ia + 2) % 5; + const id = (ia + 3) % 5; + const ie = (ia + 4) % 5; + const a = v[ia], b = v[ib], c = v[ic], d = v[id], e = v[ie]; + let f: number, k: number; + if (i < 20) { f = d ^ (b & (c ^ d)); k = K0; } + else if (i < 40) { f = b ^ c ^ d; k = K1; } + else if (i < 60) { f = (b & c) | (d & (b ^ c)); k = K2; } + else { f = b ^ c ^ d; k = K3; } + v[ie] = (e + (((a << 5) | (a >>> 27)) + f + k + m[i])) | 0; + v[ib] = (b << 30) | (b >>> 2); +} + +/** Inverse of stepForward: undoes step `i`. */ +function stepBackward(v: Int32Array, i: number, m: Int32Array): void { + const ia = (5 - (i % 5)) % 5; + const ib = (ia + 1) % 5; + const ic = (ia + 2) % 5; + const id = (ia + 3) % 5; + const ie = (ia + 4) % 5; + const a = v[ia]; + const b = ((v[ib] >>> 30) | (v[ib] << 2)) | 0; + v[ib] = b; + const c = v[ic], d = v[id], e = v[ie]; + let f: number, k: number; + if (i < 20) { f = d ^ (b & (c ^ d)); k = K0; } + else if (i < 40) { f = b ^ c ^ d; k = K1; } + else if (i < 60) { f = (b & c) | (d & (b ^ c)); k = K2; } + else { f = b ^ c ^ d; k = K3; } + v[ie] = (e - (((a << 5) | (a >>> 27)) + f + k + m[i])) | 0; +} + +/** + * Reconstruct the chaining values a block would have had, had it been + * compressed with the perturbed message `me2`. Runs backwards from step + * `t` to recover the input chaining value, then forwards to step 79 for + * the output. `state` is the real block's register file entering step t. + */ +function recompress( + t: number, + ihvin: Int32Array, + ihvout: Int32Array, + me2: Int32Array, + state: Int32Array, + scratch: Int32Array +): void { + scratch.set(state); + for (let i = t - 1; i >= 0; i--) stepBackward(scratch, i, me2); + ihvin.set(scratch); + scratch.set(state); + for (let i = t; i < 80; i++) stepForward(scratch, i, me2); + for (let j = 0; j < 5; j++) ihvout[j] = (ihvin[j] + scratch[j]) | 0; +} + +/** + * Collision-detecting SHA-1. Drop-in for {@link Sha1}: `digest()` returns + * the identical bytes for every input. After digesting, {@link collision} + * reports whether any block looked like a collision-attack near-collision + * block. + */ +export class Sha1Dc { + private ihv = new Int32Array(5); + private block = new Uint8Array(64); + private blockLen = 0; + private bytes = 0; + /** expanded message of the block being compressed */ + private m1 = new Int32Array(80); + private m2 = new Int32Array(80); + /** register file entering steps 58 and 65 — the only DV test steps */ + private state58 = new Int32Array(5); + private state65 = new Int32Array(5); + private ihvin = new Int32Array(5); + private ihvout = new Int32Array(5); + private scratch = new Int32Array(5); + private found = false; + + constructor() { + this.reset(); + } + + /** True when a near-collision block was seen since the last reset. */ + get collision(): boolean { + return this.found; + } + + reset(): this { + this.ihv[0] = 0x67452301 | 0; + this.ihv[1] = 0xefcdab89 | 0; + this.ihv[2] = 0x98badcfe | 0; + this.ihv[3] = 0x10325476 | 0; + this.ihv[4] = 0xc3d2e1f0 | 0; + this.blockLen = 0; + this.bytes = 0; + this.found = false; + return this; + } + + update(data: Uint8Array): this { + this.bytes += data.length; + let off = 0; + if (this.blockLen > 0) { + const need = 64 - this.blockLen; + const take = Math.min(need, data.length); + this.block.set(data.subarray(0, take), this.blockLen); + this.blockLen += take; + off = take; + if (this.blockLen === 64) { + this.process(this.block, 0); + this.blockLen = 0; + } + } + while (off + 64 <= data.length) { + this.process(data, off); + off += 64; + } + if (off < data.length) { + this.block.set(data.subarray(off), 0); + this.blockLen = data.length - off; + } + return this; + } + + digest(): Uint8Array { + const bitLenHi = Math.floor((this.bytes * 8) / 0x100000000); + const bitLenLo = (this.bytes * 8) >>> 0; + const pad = new Uint8Array(((this.blockLen < 56 ? 56 : 120) - this.blockLen) + 8); + pad[0] = 0x80; + const dv = new DataView(pad.buffer); + dv.setUint32(pad.length - 8, bitLenHi); + dv.setUint32(pad.length - 4, bitLenLo); + this.update(pad); + const out = new Uint8Array(20); + const ov = new DataView(out.buffer); + for (let i = 0; i < 5; i++) ov.setInt32(i * 4, this.ihv[i]); + return out; + } + + /** Compress one block, retaining what the collision check needs. */ + private process(buf: Uint8Array, off: number): void { + const w = this.m1; + for (let i = 0; i < 16; i++) { + const j = off + i * 4; + w[i] = (buf[j] << 24) | (buf[j + 1] << 16) | (buf[j + 2] << 8) | buf[j + 3]; + } + for (let i = 16; i < 80; i++) { + const n = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; + w[i] = (n << 1) | (n >>> 31); + } + const ihv = this.ihv; + let a = ihv[0], b = ihv[1], c = ihv[2], d = ihv[3], e = ihv[4]; + for (let i = 0; i < 80; i++) { + // The unrolled reference names registers canonically while this loop + // shifts them, so a snapshot at step i must be rotated back by i mod 5. + if (i === 58) { + // 58 mod 5 == 3 + this.state58[0] = d; this.state58[1] = e; this.state58[2] = a; + this.state58[3] = b; this.state58[4] = c; + } else if (i === 65) { + // 65 mod 5 == 0 + this.state65[0] = a; this.state65[1] = b; this.state65[2] = c; + this.state65[3] = d; this.state65[4] = e; + } + let f: number, k: number; + if (i < 20) { f = (b & c) | (~b & d); k = K0; } + else if (i < 40) { f = b ^ c ^ d; k = K1; } + else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = K2; } + else { f = b ^ c ^ d; k = K3; } + const t = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) | 0; + e = d; + d = c; + c = (b << 30) | (b >>> 2); + b = a; + a = t; + } + ihv[0] = (ihv[0] + a) | 0; + ihv[1] = (ihv[1] + b) | 0; + ihv[2] = (ihv[2] + c) | 0; + ihv[3] = (ihv[3] + d) | 0; + ihv[4] = (ihv[4] + e) | 0; + + if (this.found) return; // already refused; skip the rest of the work + const mask = ubcCheck(w); + if (mask === 0) return; + const m2 = this.m2; + for (const dv of DVS) { + if ((mask & (1 << dv.maskb)) === 0) continue; + const dm = dv.dm; + for (let j = 0; j < 80; j++) m2[j] = w[j] ^ dm[j]; + recompress( + dv.testt, + this.ihvin, + this.ihvout, + m2, + dv.testt === 58 ? this.state58 : this.state65, + this.scratch + ); + const o = this.ihvout; + if (((o[0] ^ ihv[0]) | (o[1] ^ ihv[1]) | (o[2] ^ ihv[2]) | (o[3] ^ ihv[3]) | (o[4] ^ ihv[4])) === 0) { + this.found = true; + return; + } + } + } +} + +/** Thrown when a hashed object carries a SHA-1 collision-attack block. */ +export class Sha1CollisionError extends Error { + readonly oid: string; + constructor(oid: string) { + super(`object ${oid.slice(0, 12)} triggered SHA-1 collision detection; refused`); + this.name = "Sha1CollisionError"; + this.oid = oid; + } +} diff --git a/apps/api/src/vendor/dgit/git/sha1dc-tables.ts b/apps/api/src/vendor/dgit/git/sha1dc-tables.ts new file mode 100644 index 0000000000..65a1bfd5b8 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/sha1dc-tables.ts @@ -0,0 +1,324 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +// GENERATED — do not edit by hand. +// Transcribed from sha1collisiondetection/lib/ubc_check.c (Marc Stevens, Dan +// Shumow; MIT). Regenerate with scripts/gen-sha1dc-tables.mjs. +// +// C uint32 arithmetic maps onto JS int32 bit-for-bit: '>>' becomes '>>>' and +// wrapping subtraction is left to two's-complement, since every result feeds a +// bitwise operator. + +/** One disturbance vector: the step to recompress from, its bit in the UBC + * mask, and the expanded-message XOR difference. */ +export interface Sha1Dv { + readonly testt: number; + readonly maskb: number; + readonly dm: readonly number[]; +} + +/** The 32 disturbance vectors checked by SHA-1DC. */ +export const SHA1_DVS: readonly Sha1Dv[] = [ + { testt: 58, maskb: 0, dm: [0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161,0x80000599] }, // I(43,0) + { testt: 58, maskb: 1, dm: [0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803,0x80000161] }, // I(44,0) + { testt: 58, maskb: 2, dm: [0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c,0x00000803] }, // I(45,0) + { testt: 58, maskb: 3, dm: [0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6,0x8000004c] }, // I(46,0) + { testt: 58, maskb: 4, dm: [0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a,0x00000132] }, // I(46,2) + { testt: 58, maskb: 5, dm: [0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408,0x800000e6] }, // I(47,0) + { testt: 58, maskb: 6, dm: [0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020,0x0000039a] }, // I(47,2) + { testt: 58, maskb: 7, dm: [0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164,0x00000408] }, // I(48,0) + { testt: 58, maskb: 8, dm: [0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590,0x00001020] }, // I(48,2) + { testt: 58, maskb: 9, dm: [0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018,0x00000164] }, // I(49,0) + { testt: 58, maskb: 10, dm: [0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060,0x00000590] }, // I(49,2) + { testt: 65, maskb: 11, dm: [0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202,0x00000018] }, // I(50,0) + { testt: 65, maskb: 12, dm: [0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a,0x00000060] }, // I(50,2) + { testt: 65, maskb: 13, dm: [0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012,0x80000202] }, // I(51,0) + { testt: 65, maskb: 14, dm: [0xa0000003,0x20000030,0x60000000,0xe000002a,0x20000043,0xb0000040,0xd0000053,0xd0000022,0x20000000,0x60000032,0x60000043,0x20000040,0xe0000042,0x60000002,0x80000001,0x00000020,0x00000003,0x40000052,0x40000040,0xe0000052,0xa0000000,0x80000040,0x20000001,0x20000060,0x80000001,0x40000042,0xc0000043,0x40000022,0x00000003,0x40000042,0xc0000043,0xc0000022,0x00000001,0x40000002,0xc0000043,0x40000062,0x80000001,0x40000042,0x40000042,0x40000002,0x00000002,0x00000040,0x80000002,0x80000000,0x80000002,0x80000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000000,0x00000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000101,0x00000009,0x00000012,0x00000202,0x0000001a,0x00000124,0x0000040c,0x00000026,0x0000004a,0x0000080a] }, // I(51,2) + { testt: 65, maskb: 15, dm: [0x04000010,0xe8000000,0x0800000c,0x18000000,0xb800000a,0xc8000010,0x2c000010,0xf4000014,0xb4000008,0x08000000,0x9800000c,0xd8000010,0x08000010,0xb8000010,0x98000000,0x60000000,0x00000008,0xc0000000,0x90000014,0x10000010,0xb8000014,0x28000000,0x20000010,0x48000000,0x08000018,0x60000000,0x90000010,0xf0000010,0x90000008,0xc0000000,0x90000010,0xf0000010,0xb0000008,0x40000000,0x90000000,0xf0000010,0x90000018,0x60000000,0x90000010,0x90000010,0x90000000,0x80000000,0x00000010,0xa0000000,0x20000000,0xa0000000,0x20000010,0x00000000,0x20000010,0x20000000,0x00000010,0x20000000,0x00000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000040,0x40000002,0x80000004,0x80000080,0x80000006,0x00000049,0x00000103,0x80000009,0x80000012] }, // I(52,0) + { testt: 58, maskb: 16, dm: [0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054,0x00000967] }, // II(45,0) + { testt: 58, maskb: 17, dm: [0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4,0x80000054] }, // II(46,0) + { testt: 58, maskb: 18, dm: [0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6,0x0000106a,0x00000b90,0x00000152] }, // II(46,2) + { testt: 58, maskb: 19, dm: [0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a,0x000002e4] }, // II(47,0) + { testt: 58, maskb: 20, dm: [0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d,0x8000041a] }, // II(48,0) + { testt: 58, maskb: 21, dm: [0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b,0x8000016d] }, // II(49,0) + { testt: 58, maskb: 22, dm: [0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c,0x000005b6] }, // II(49,2) + { testt: 65, maskb: 23, dm: [0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b,0x0000011b] }, // II(50,0) + { testt: 65, maskb: 24, dm: [0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e,0x0000046c] }, // II(50,2) + { testt: 65, maskb: 25, dm: [0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014,0x8000024b] }, // II(51,0) + { testt: 65, maskb: 26, dm: [0x00000043,0xd0000072,0xf0000010,0xf000006a,0x80000040,0x90000070,0xb0000053,0x30000008,0x00000043,0xd0000072,0xb0000010,0xf0000062,0xc0000042,0x00000030,0xe0000042,0x20000060,0xe0000041,0x20000050,0xc0000041,0xe0000072,0xa0000003,0xc0000012,0x60000041,0xc0000032,0x20000001,0xc0000002,0xe0000042,0x60000042,0x80000002,0x00000000,0x00000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000000,0x00000040,0x80000001,0x00000060,0x80000003,0x40000002,0xc0000040,0xc0000002,0x80000000,0x80000000,0x80000002,0x00000040,0x00000002,0x80000000,0x80000000,0x80000000,0x00000002,0x00000040,0x00000000,0x80000040,0x80000002,0x00000000,0x80000000,0x80000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000004,0x00000080,0x00000004,0x00000009,0x00000105,0x00000089,0x00000016,0x0000020b,0x0000011b,0x0000012d,0x0000041e,0x00000224,0x00000050,0x0000092e] }, // II(51,2) + { testt: 65, maskb: 27, dm: [0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089,0x00000014] }, // II(52,0) + { testt: 65, maskb: 28, dm: [0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107,0x00000089] }, // II(53,0) + { testt: 65, maskb: 29, dm: [0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b,0x80000107] }, // II(54,0) + { testt: 65, maskb: 30, dm: [0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046,0x4000004b] }, // II(55,0) + { testt: 65, maskb: 31, dm: [0x2600001a,0x00000010,0x0400001c,0xcc000014,0x0c000002,0xc0000010,0xb400001c,0x3c000004,0xbc00001a,0x20000010,0x2400001c,0xec000014,0x0c000002,0xc0000010,0xb400001c,0x2c000004,0xbc000018,0xb0000010,0x0000000c,0xb8000010,0x08000018,0x78000010,0x08000014,0x70000010,0xb800001c,0xe8000000,0xb0000004,0x58000010,0xb000000c,0x48000000,0xb0000000,0xb8000010,0x98000010,0xa0000000,0x00000000,0x00000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0x20000000,0x00000010,0x60000000,0x00000018,0xe0000000,0x90000000,0x30000010,0xb0000000,0x20000000,0x20000000,0xa0000000,0x00000010,0x80000000,0x20000000,0x20000000,0x20000000,0x80000000,0x00000010,0x00000000,0x20000010,0xa0000000,0x00000000,0x20000000,0x20000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000001,0x00000020,0x00000001,0x40000002,0x40000041,0x40000022,0x80000005,0xc0000082,0xc0000046] }, // II(56,0) +]; + +/** + * Check the unavoidable bit conditions for every DV against an expanded + * message block. Returns a mask whose bit `maskb` is set when every UBC for + * that DV holds, i.e. when the DV is worth the cost of a recompression check. + */ +export function ubcCheck(W: Int32Array): number { + let mask = ~0; + + + mask &= (((((W[44]^W[45])>>>29)&1)-1) | ~((1 << 7)|(1 << 13)|(1 << 15)|(1 << 16)|(1 << 17)|(1 << 23)|(1 << 25))); + mask &= (((((W[49]^W[50])>>>29)&1)-1) | ~((1 << 3)|(1 << 16)|(1 << 23)|(1 << 25)|(1 << 30)|(1 << 31))); + mask &= (((((W[48]^W[49])>>>29)&1)-1) | ~((1 << 2)|(1 << 15)|(1 << 21)|(1 << 23)|(1 << 29)|(1 << 30))); + mask &= ((((W[47]^(W[50]>>>25))&(1<<4))-(1<<4)) | ~((1 << 5)|(1 << 9)|(1 << 13)|(1 << 16)|(1 << 25)|(1 << 31))); + mask &= (((((W[47]^W[48])>>>29)&1)-1) | ~((1 << 1)|(1 << 13)|(1 << 20)|(1 << 21)|(1 << 28)|(1 << 29))); + mask &= (((((W[46]>>>4)^(W[49]>>>29))&1)-1) | ~((1 << 3)|(1 << 7)|(1 << 11)|(1 << 15)|(1 << 23)|(1 << 30))); + mask &= (((((W[46]^W[47])>>>29)&1)-1) | ~((1 << 0)|(1 << 11)|(1 << 19)|(1 << 20)|(1 << 27)|(1 << 28))); + mask &= (((((W[45]>>>4)^(W[48]>>>29))&1)-1) | ~((1 << 2)|(1 << 5)|(1 << 9)|(1 << 13)|(1 << 21)|(1 << 29))); + mask &= (((((W[45]^W[46])>>>29)&1)-1) | ~((1 << 9)|(1 << 15)|(1 << 17)|(1 << 19)|(1 << 25)|(1 << 27))); + mask &= (((((W[44]>>>4)^(W[47]>>>29))&1)-1) | ~((1 << 1)|(1 << 3)|(1 << 7)|(1 << 11)|(1 << 20)|(1 << 28))); + mask &= (((((W[43]>>>4)^(W[46]>>>29))&1)-1) | ~((1 << 0)|(1 << 2)|(1 << 5)|(1 << 9)|(1 << 19)|(1 << 27))); + mask &= (((((W[43]^W[44])>>>29)&1)-1) | ~((1 << 5)|(1 << 11)|(1 << 13)|(1 << 16)|(1 << 21)|(1 << 23))); + mask &= (((((W[42]>>>4)^(W[45]>>>29))&1)-1) | ~((1 << 1)|(1 << 3)|(1 << 7)|(1 << 15)|(1 << 17)|(1 << 25))); + mask &= (((((W[41]>>>4)^(W[44]>>>29))&1)-1) | ~((1 << 0)|(1 << 2)|(1 << 5)|(1 << 13)|(1 << 16)|(1 << 23))); + mask &= (((((W[40]^W[41])>>>29)&1)-1) | ~((1 << 1)|(1 << 5)|(1 << 7)|(1 << 17)|(1 << 19)|(1 << 31))); + mask &= (((((W[54]^W[55])>>>29)&1)-1) | ~((1 << 13)|(1 << 19)|(1 << 23)|(1 << 30)|(1 << 31))); + mask &= (((((W[53]^W[54])>>>29)&1)-1) | ~((1 << 11)|(1 << 17)|(1 << 21)|(1 << 29)|(1 << 30))); + mask &= (((((W[52]^W[53])>>>29)&1)-1) | ~((1 << 9)|(1 << 16)|(1 << 20)|(1 << 28)|(1 << 29))); + mask &= ((((W[50]^(W[53]>>>25))&(1<<4))-(1<<4)) | ~((1 << 11)|(1 << 15)|(1 << 17)|(1 << 20)|(1 << 29))); + mask &= (((((W[50]^W[51])>>>29)&1)-1) | ~((1 << 5)|(1 << 17)|(1 << 25)|(1 << 27)|(1 << 31))); + mask &= ((((W[49]^(W[52]>>>25))&(1<<4))-(1<<4)) | ~((1 << 9)|(1 << 13)|(1 << 16)|(1 << 19)|(1 << 28))); + mask &= ((((W[48]^(W[51]>>>25))&(1<<4))-(1<<4)) | ~((1 << 7)|(1 << 11)|(1 << 15)|(1 << 17)|(1 << 27))); + mask &= (((((W[42]^W[43])>>>29)&1)-1) | ~((1 << 3)|(1 << 9)|(1 << 11)|(1 << 20)|(1 << 21))); + mask &= (((((W[41]^W[42])>>>29)&1)-1) | ~((1 << 2)|(1 << 7)|(1 << 9)|(1 << 19)|(1 << 20))); + mask &= (((((W[40]>>>4)^(W[43]>>>29))&1)-1) | ~((1 << 1)|(1 << 3)|(1 << 11)|(1 << 21)|(1 << 31))); + mask &= (((((W[39]>>>4)^(W[42]>>>29))&1)-1) | ~((1 << 0)|(1 << 2)|(1 << 9)|(1 << 20)|(1 << 30))); + if (mask & ((1 << 1)|(1 << 7)|(1 << 19)|(1 << 29)|(1 << 31))) + mask &= (((((W[38]>>>4)^(W[41]>>>29))&1)-1) | ~((1 << 1)|(1 << 7)|(1 << 19)|(1 << 29)|(1 << 31))); + mask &= (((((W[37]>>>4)^(W[40]>>>29))&1)-1) | ~((1 << 0)|(1 << 5)|(1 << 17)|(1 << 28)|(1 << 30))); + if (mask & ((1 << 15)|(1 << 20)|(1 << 25)|(1 << 31))) + mask &= (((((W[55]^W[56])>>>29)&1)-1) | ~((1 << 15)|(1 << 20)|(1 << 25)|(1 << 31))); + if (mask & ((1 << 15)|(1 << 20)|(1 << 23)|(1 << 31))) + mask &= ((((W[52]^(W[55]>>>25))&(1<<4))-(1<<4)) | ~((1 << 15)|(1 << 20)|(1 << 23)|(1 << 31))); + if (mask & ((1 << 13)|(1 << 19)|(1 << 21)|(1 << 30))) + mask &= ((((W[51]^(W[54]>>>25))&(1<<4))-(1<<4)) | ~((1 << 13)|(1 << 19)|(1 << 21)|(1 << 30))); + if (mask & ((1 << 7)|(1 << 19)|(1 << 27)|(1 << 28))) + mask &= (((((W[51]^W[52])>>>29)&1)-1) | ~((1 << 7)|(1 << 19)|(1 << 27)|(1 << 28))); + if (mask & ((1 << 3)|(1 << 9)|(1 << 16)|(1 << 20))) + mask &= (((((W[36]>>>4)^(W[40]>>>29))&1)-1) | ~((1 << 3)|(1 << 9)|(1 << 16)|(1 << 20))); + if (mask & ((1 << 15)|(1 << 20)|(1 << 21))) + mask &= ((0-(((W[53]^W[56])>>>29)&1)) | ~((1 << 15)|(1 << 20)|(1 << 21))); + if (mask & ((1 << 11)|(1 << 17)|(1 << 19))) + mask &= ((0-(((W[51]^W[54])>>>29)&1)) | ~((1 << 11)|(1 << 17)|(1 << 19))); + if (mask & ((1 << 9)|(1 << 13)|(1 << 16))) + mask &= ((0-(((W[50]^W[52])>>>29)&1)) | ~((1 << 9)|(1 << 13)|(1 << 16))); + if (mask & ((1 << 7)|(1 << 11)|(1 << 15))) + mask &= ((0-(((W[49]^W[51])>>>29)&1)) | ~((1 << 7)|(1 << 11)|(1 << 15))); + if (mask & ((1 << 5)|(1 << 9)|(1 << 13))) + mask &= ((0-(((W[48]^W[50])>>>29)&1)) | ~((1 << 5)|(1 << 9)|(1 << 13))); + if (mask & ((1 << 3)|(1 << 7)|(1 << 11))) + mask &= ((0-(((W[47]^W[49])>>>29)&1)) | ~((1 << 3)|(1 << 7)|(1 << 11))); + if (mask & ((1 << 2)|(1 << 5)|(1 << 9))) + mask &= ((0-(((W[46]^W[48])>>>29)&1)) | ~((1 << 2)|(1 << 5)|(1 << 9))); + mask &= ((((W[45]^W[47])&(1<<6))-(1<<6)) | ~((1 << 6)|(1 << 10)|(1 << 14))); + if (mask & ((1 << 1)|(1 << 3)|(1 << 7))) + mask &= ((0-(((W[45]^W[47])>>>29)&1)) | ~((1 << 1)|(1 << 3)|(1 << 7))); + mask &= (((((W[44]^W[46])>>>6)&1)-1) | ~((1 << 4)|(1 << 8)|(1 << 12))); + if (mask & ((1 << 0)|(1 << 2)|(1 << 5))) + mask &= ((0-(((W[44]^W[46])>>>29)&1)) | ~((1 << 0)|(1 << 2)|(1 << 5))); + mask &= ((0-((W[41]^(W[42]>>>5))&(1<<1))) | ~((1 << 8)|(1 << 18)|(1 << 26))); + mask &= ((0-((W[40]^(W[41]>>>5))&(1<<1))) | ~((1 << 6)|(1 << 14)|(1 << 24))); + if (mask & ((1 << 1)|(1 << 3)|(1 << 31))) + mask &= ((0-(((W[40]^W[42])>>>4)&1)) | ~((1 << 1)|(1 << 3)|(1 << 31))); + mask &= ((0-((W[39]^(W[40]>>>5))&(1<<1))) | ~((1 << 4)|(1 << 12)|(1 << 22))); + if (mask & ((1 << 0)|(1 << 2)|(1 << 30))) + mask &= ((0-(((W[39]^W[41])>>>4)&1)) | ~((1 << 0)|(1 << 2)|(1 << 30))); + if (mask & ((1 << 1)|(1 << 29)|(1 << 31))) + mask &= ((0-(((W[38]^W[40])>>>4)&1)) | ~((1 << 1)|(1 << 29)|(1 << 31))); + if (mask & ((1 << 0)|(1 << 28)|(1 << 30))) + mask &= ((0-(((W[37]^W[39])>>>4)&1)) | ~((1 << 0)|(1 << 28)|(1 << 30))); + mask &= ((0-((W[36]^(W[37]>>>5))&(1<<1))) | ~((1 << 6)|(1 << 12)|(1 << 18))); + if (mask & ((1 << 2)|(1 << 7)|(1 << 19))) + mask &= (((((W[35]>>>4)^(W[39]>>>29))&1)-1) | ~((1 << 2)|(1 << 7)|(1 << 19))); + if (mask & ((1 << 7)|(1 << 20))) + mask &= ((0-((W[63]^(W[64]>>>5))&(1<<0))) | ~((1 << 7)|(1 << 20))); + if (mask & ((1 << 2)|(1 << 16))) + mask &= ((0-((W[63]^(W[64]>>>5))&(1<<1))) | ~((1 << 2)|(1 << 16))); + if (mask & ((1 << 5)|(1 << 19))) + mask &= ((0-((W[62]^(W[63]>>>5))&(1<<0))) | ~((1 << 5)|(1 << 19))); + if (mask & ((1 << 3)|(1 << 17))) + mask &= ((0-((W[61]^(W[62]>>>5))&(1<<0))) | ~((1 << 3)|(1 << 17))); + mask &= ((0-((W[61]^(W[62]>>>5))&(1<<2))) | ~((1 << 4)|(1 << 18))); + if (mask & ((1 << 2)|(1 << 16))) + mask &= ((0-((W[60]^(W[61]>>>5))&(1<<0))) | ~((1 << 2)|(1 << 16))); + if (mask & ((1 << 25)|(1 << 29))) + mask &= (((((W[58]^W[59])>>>29)&1)-1) | ~((1 << 25)|(1 << 29))); + if (mask & ((1 << 23)|(1 << 28))) + mask &= (((((W[57]^W[58])>>>29)&1)-1) | ~((1 << 23)|(1 << 28))); + if (mask & ((1 << 27)|(1 << 29))) + mask &= ((((W[56]^(W[59]>>>25))&(1<<4))-(1<<4)) | ~((1 << 27)|(1 << 29))); + if (mask & ((1 << 25)|(1 << 27))) + mask &= ((0-(((W[56]^W[59])>>>29)&1)) | ~((1 << 25)|(1 << 27))); + if (mask & ((1 << 21)|(1 << 27))) + mask &= (((((W[56]^W[57])>>>29)&1)-1) | ~((1 << 21)|(1 << 27))); + if (mask & ((1 << 25)|(1 << 28))) + mask &= ((((W[55]^(W[58]>>>25))&(1<<4))-(1<<4)) | ~((1 << 25)|(1 << 28))); + if (mask & ((1 << 23)|(1 << 27))) + mask &= ((((W[54]^(W[57]>>>25))&(1<<4))-(1<<4)) | ~((1 << 23)|(1 << 27))); + if (mask & ((1 << 21)|(1 << 25))) + mask &= ((((W[53]^(W[56]>>>25))&(1<<4))-(1<<4)) | ~((1 << 21)|(1 << 25))); + mask &= ((((W[51]^(W[50]>>>5))&(1<<1))-(1<<1)) | ~((1 << 12)|(1 << 18))); + mask &= ((((W[48]^W[50])&(1<<6))-(1<<6)) | ~((1 << 12)|(1 << 18))); + if (mask & ((1 << 13)|(1 << 15))) + mask &= ((0-(((W[48]^W[55])>>>29)&1)) | ~((1 << 13)|(1 << 15))); + mask &= ((((W[47]^W[49])&(1<<6))-(1<<6)) | ~((1 << 10)|(1 << 14))); + mask &= ((((W[48]^(W[47]>>>5))&(1<<1))-(1<<1)) | ~((1 << 6)|(1 << 26))); + mask &= ((((W[46]^W[48])&(1<<6))-(1<<6)) | ~((1 << 8)|(1 << 12))); + mask &= ((((W[47]^(W[46]>>>5))&(1<<1))-(1<<1)) | ~((1 << 4)|(1 << 24))); + mask &= ((0-((W[44]^(W[45]>>>5))&(1<<1))) | ~((1 << 14)|(1 << 22))); + mask &= ((((W[43]^W[45])&(1<<6))-(1<<6)) | ~((1 << 6)|(1 << 10))); + mask &= (((((W[42]^W[44])>>>6)&1)-1) | ~((1 << 4)|(1 << 8))); + mask &= ((((W[43]^(W[42]>>>5))&(1<<1))-(1<<1)) | ~((1 << 18)|(1 << 26))); + mask &= ((((W[42]^(W[41]>>>5))&(1<<1))-(1<<1)) | ~((1 << 14)|(1 << 24))); + mask &= ((((W[41]^(W[40]>>>5))&(1<<1))-(1<<1)) | ~((1 << 12)|(1 << 22))); + if (mask & ((1 << 15)|(1 << 25))) + mask &= ((((W[39]^(W[43]>>>25))&(1<<4))-(1<<4)) | ~((1 << 15)|(1 << 25))); + if (mask & ((1 << 13)|(1 << 23))) + mask &= ((((W[38]^(W[42]>>>25))&(1<<4))-(1<<4)) | ~((1 << 13)|(1 << 23))); + if (mask & ((1 << 8)|(1 << 14))) + mask &= ((0-((W[37]^(W[38]>>>5))&(1<<1))) | ~((1 << 8)|(1 << 14))); + if (mask & ((1 << 11)|(1 << 21))) + mask &= ((((W[37]^(W[41]>>>25))&(1<<4))-(1<<4)) | ~((1 << 11)|(1 << 21))); + if (mask & ((1 << 27)|(1 << 29))) + mask &= ((0-((W[36]^W[38])&(1<<4))) | ~((1 << 27)|(1 << 29))); + mask &= ((0-((W[35]^(W[36]>>>5))&(1<<1))) | ~((1 << 4)|(1 << 10))); + if (mask & ((1 << 13)|(1 << 19))) + mask &= ((((W[35]^(W[39]>>>25))&(1<<3))-(1<<3)) | ~((1 << 13)|(1 << 19))); +if (mask) { + + if (mask & (1 << 0)) + if ( + !((W[61]^(W[62]>>>5)) & (1<<1)) + || !(!((W[59]^(W[63]>>>25)) & (1<<5))) + || !((W[58]^(W[63]>>>30)) & (1<<0)) + ) mask &= ~(1 << 0); + if (mask & (1 << 1)) + if ( + !((W[62]^(W[63]>>>5)) & (1<<1)) + || !(!((W[60]^(W[64]>>>25)) & (1<<5))) + || !((W[59]^(W[64]>>>30)) & (1<<0)) + ) mask &= ~(1 << 1); + if (mask & (1 << 4)) + mask &= ((~((W[40]^W[42])>>>2)) | ~(1 << 4)); + if (mask & (1 << 6)) + if ( + !((W[62]^(W[63]>>>5)) & (1<<2)) + || !(!((W[41]^W[43]) & (1<<6))) + ) mask &= ~(1 << 6); + if (mask & (1 << 8)) + if ( + !((W[63]^(W[64]>>>5)) & (1<<2)) + || !(!((W[48]^(W[49]<<5)) & (1<<6))) + ) mask &= ~(1 << 8); + if (mask & (1 << 10)) + if ( + !(!((W[49]^(W[50]<<5)) & (1<<6))) + || !((W[42]^W[50]) & (1<<1)) + || !(!((W[39]^(W[40]<<5)) & (1<<6))) + || !((W[38]^W[40]) & (1<<1)) + ) mask &= ~(1 << 10); + if (mask & (1 << 11)) + mask &= ((((W[36]^W[37])<<7)) | ~(1 << 11)); + if (mask & (1 << 12)) + mask &= ((((W[43]^W[51])<<11)) | ~(1 << 12)); + if (mask & (1 << 13)) + mask &= ((((W[37]^W[38])<<9)) | ~(1 << 13)); + if (mask & (1 << 14)) + if ( + !(!((W[51]^(W[52]<<5)) & (1<<6))) + || !(!((W[49]^W[51]) & (1<<6))) + || !(!((W[37]^(W[37]>>>5)) & (1<<1))) + || !(!((W[35]^(W[39]>>>25)) & (1<<5))) + ) mask &= ~(1 << 14); + if (mask & (1 << 15)) + mask &= ((((W[38]^W[39])<<11)) | ~(1 << 15)); + if (mask & (1 << 18)) + mask &= ((((W[47]^W[51])<<17)) | ~(1 << 18)); + if (mask & (1 << 20)) + if ( + !(!((W[36]^(W[40]>>>25)) & (1<<3))) + || !((W[35]^(W[40]<<2)) & (1<<30)) + ) mask &= ~(1 << 20); + if (mask & (1 << 21)) + if ( + !(!((W[37]^(W[41]>>>25)) & (1<<3))) + || !((W[36]^(W[41]<<2)) & (1<<30)) + ) mask &= ~(1 << 21); + if (mask & (1 << 22)) + if ( + !(!((W[53]^(W[54]<<5)) & (1<<6))) + || !(!((W[51]^W[53]) & (1<<6))) + || !((W[50]^W[54]) & (1<<1)) + || !(!((W[45]^(W[46]<<5)) & (1<<6))) + || !(!((W[37]^(W[41]>>>25)) & (1<<5))) + || !((W[36]^(W[41]>>>30)) & (1<<0)) + ) mask &= ~(1 << 22); + if (mask & (1 << 23)) + if ( + !((W[55]^W[58]) & (1<<29)) + || !(!((W[38]^(W[42]>>>25)) & (1<<3))) + || !((W[37]^(W[42]<<2)) & (1<<30)) + ) mask &= ~(1 << 23); + if (mask & (1 << 24)) + if ( + !(!((W[54]^(W[55]<<5)) & (1<<6))) + || !(!((W[52]^W[54]) & (1<<6))) + || !((W[51]^W[55]) & (1<<1)) + || !((W[45]^W[47]) & (1<<1)) + || !(!((W[38]^(W[42]>>>25)) & (1<<5))) + || !((W[37]^(W[42]>>>30)) & (1<<0)) + ) mask &= ~(1 << 24); + if (mask & (1 << 25)) + if ( + !(!((W[39]^(W[43]>>>25)) & (1<<3))) + || !((W[38]^(W[43]<<2)) & (1<<30)) + ) mask &= ~(1 << 25); + if (mask & (1 << 26)) + if ( + !(!((W[55]^(W[56]<<5)) & (1<<6))) + || !(!((W[53]^W[55]) & (1<<6))) + || !((W[52]^W[56]) & (1<<1)) + || !((W[46]^W[48]) & (1<<1)) + || !(!((W[39]^(W[43]>>>25)) & (1<<5))) + || !((W[38]^(W[43]>>>30)) & (1<<0)) + ) mask &= ~(1 << 26); + if (mask & (1 << 27)) + if ( + !(!((W[59]^W[60]) & (1<<29))) + || !(!((W[40]^(W[44]>>>25)) & (1<<3))) + || !(!((W[40]^(W[44]>>>25)) & (1<<4))) + || !((W[39]^(W[44]<<2)) & (1<<30)) + ) mask &= ~(1 << 27); + if (mask & (1 << 28)) + if ( + !((W[58]^W[61]) & (1<<29)) + || !(!((W[57]^(W[61]>>>25)) & (1<<4))) + || !(!((W[41]^(W[45]>>>25)) & (1<<3))) + || !(!((W[41]^(W[45]>>>25)) & (1<<4))) + ) mask &= ~(1 << 28); + if (mask & (1 << 29)) + if ( + !(!((W[58]^(W[62]>>>25)) & (1<<4))) + || !(!((W[42]^(W[46]>>>25)) & (1<<3))) + || !(!((W[42]^(W[46]>>>25)) & (1<<4))) + ) mask &= ~(1 << 29); + if (mask & (1 << 30)) + if ( + !(!((W[59]^(W[63]>>>25)) & (1<<4))) + || !(!((W[57]^(W[59]>>>25)) & (1<<4))) + || !(!((W[43]^(W[47]>>>25)) & (1<<3))) + || !(!((W[43]^(W[47]>>>25)) & (1<<4))) + ) mask &= ~(1 << 30); + if (mask & (1 << 31)) + if ( + !(!((W[60]^(W[64]>>>25)) & (1<<4))) + || !(!((W[44]^(W[48]>>>25)) & (1<<3))) + || !(!((W[44]^(W[48]>>>25)) & (1<<4))) + ) mask &= ~(1 << 31); +} + return mask; +} diff --git a/apps/api/src/vendor/dgit/git/store.ts b/apps/api/src/vendor/dgit/git/store.ts new file mode 100644 index 0000000000..4a36d2838d --- /dev/null +++ b/apps/api/src/vendor/dgit/git/store.ts @@ -0,0 +1,461 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +import { gitWorkLimits } from "./budget"; +import { concat, te, sha1hex } from "./util"; +import { deflate, inflate } from "./zlib"; +import { ObjType } from "./objects"; +import { OidSet } from "./oidset"; +import { PackStore, ObjCache, ObjRec } from "./packstore"; + +/** A reachable pack entry, streamed in storage order by `reachablePackedAfter`. + * The `size` field of a full PackedEntry is not needed to emit the pack, so it + * is left unselected. */ +export interface PackedReachable { + oid: string; + packId: number; + offset: number; + dataOff: number; + dataLen: number; + type: ObjType; + entrySize: number; + baseOid: string | null; +} + +const CHUNK = 1024 * 1024; // stay well under the DO SQLite per-row limit +// serving cache: Workers isolates have a hard 128MB total, so stay modest +// there; self-hosted celld nodes run with multi-GB heaps +const CACHE_BUDGET = typeof caches !== "undefined" ? 16 * 1024 * 1024 : 128 * 1024 * 1024; + +/** + * Git object database + refs, stored in a Durable Object's SQLite database. + * Small/legacy objects live loose (zlib-deflated, chunked across rows); + * pushed packs are kept verbatim and served through the PackStore index. + */ +export class GitStore { + readonly packs: PackStore; + readonly cache = new ObjCache(CACHE_BUDGET); + /** SAM: bumped by each saveReachable; only the latest save may keep writing or stamp. */ + private reachableSaveGeneration = 0; + /** + * Whether the loose `objects` table holds anything. A pushed repo is + * pack-native — loose objects only appear after a gc migration (see + * runGc) — so on the normal path this is false and every get/has/typeAndSize + * skips a guaranteed-miss loose SELECT and goes straight to the pack index. + * Cached in memory and mirrored to the `has-loose` meta row so it survives + * isolate eviction; back-filled once for repos that predate the flag. + */ + private hasLoose: boolean; + + constructor(private sql: SqlStorage) { + this.packs = new PackStore(sql, (oid) => this.getLoose(oid)); + sql.exec(` + CREATE TABLE IF NOT EXISTS objects ( + oid TEXT PRIMARY KEY, + type TEXT NOT NULL, + size INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS chunks ( + oid TEXT NOT NULL, + seq INTEGER NOT NULL, + data BLOB NOT NULL, + PRIMARY KEY (oid, seq) + ); + CREATE TABLE IF NOT EXISTS refs ( + name TEXT PRIMARY KEY, + target TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS reachable ( + oid TEXT PRIMARY KEY + ); + CREATE TABLE IF NOT EXISTS peeled ( + oid TEXT PRIMARY KEY, + target TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS stats_cache ( + tip_oid TEXT NOT NULL, + period TEXT NOT NULL, + data TEXT NOT NULL, + PRIMARY KEY (tip_oid, period) + ); + `); + const flag = this.getMeta("has-loose"); + if (flag === null) { + // back-fill: a repo migrated by an older build may already hold loose + // objects with no flag set — probe once and record the answer + const any = this.sql.exec("SELECT 1 FROM objects LIMIT 1").toArray().length > 0; + this.setMeta("has-loose", any ? "1" : "0"); + this.hasLoose = any; + } else { + this.hasLoose = flag === "1"; + } + } + + has(oid: string): boolean { + if (this.hasLoose && this.sql.exec("SELECT 1 FROM objects WHERE oid = ?", oid).toArray().length > 0) return true; + return this.packs.typeAndSize(oid) !== null; + } + + typeAndSize(oid: string): { type: ObjType; size: number } | null { + if (this.hasLoose) { + const rows = this.sql + .exec<{ type: ObjType; size: number }>("SELECT type, size FROM objects WHERE oid = ?", oid) + .toArray(); + if (rows[0]) return rows[0]; + } + return this.packs.typeAndSize(oid); + } + + private getLoose(oid: string): ObjRec | null { + if (!this.hasLoose) return null; + const rows = this.sql + .exec<{ type: ObjType; size: number }>("SELECT type, size FROM objects WHERE oid = ?", oid) + .toArray(); + if (!rows.length) return null; + const size = rows[0].size; + if (!Number.isSafeInteger(size) || size < 0 || size > gitWorkLimits().maxObjectBytes) { + throw new Error("git object exceeds inflated size limit"); + } + const chunks = this.sql + .exec<{ data: ArrayBuffer }>("SELECT data FROM chunks WHERE oid = ? ORDER BY seq", oid) + .toArray(); + const packed = concat(chunks.map((r) => new Uint8Array(r.data))); + return { type: rows[0].type, data: inflate(packed) }; + } + + async get(oid: string): Promise<{ type: ObjType; data: Uint8Array } | null> { + return this.getLoose(oid) ?? (await this.packs.getObject(oid, this.cache)); + } + + /** + * Bind (or clear) the R2 raw-pack backend for this repo. Absent binding keeps + * every pack in SQLite (celld / Workers without the binding). Idempotent and + * cheap: the DO is per-repo, so this is set on each request from the repo name. + */ + setR2(bucket: R2Bucket | undefined, repo: string): void { + this.packs.setR2(bucket, repo); + } + + put(oid: string, type: ObjType, data: Uint8Array): void { + if (this.sql.exec("SELECT 1 FROM objects WHERE oid = ?", oid).toArray().length > 0) return; + const packed = deflate(data); + this.sql.exec("INSERT INTO objects (oid, type, size) VALUES (?, ?, ?)", oid, type, data.length); + for (let seq = 0, off = 0; off < packed.length || seq === 0; seq++, off += CHUNK) { + const slice = packed.slice(off, off + CHUNK); + this.sql.exec("INSERT INTO chunks (oid, seq, data) VALUES (?, ?, ?)", oid, seq, slice.buffer); + } + // the repo now has at least one loose object (gc migration path): the + // loose probe can no longer be skipped + if (!this.hasLoose) { + this.hasLoose = true; + this.setMeta("has-loose", "1"); + } + } + + objectCount(): number { + return this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM objects").one().n + this.packs.countObjects(); + } + + /** Resolve an abbreviated oid; null if unknown or ambiguous. */ + findOid(prefix: string): string | null { + if (!/^[0-9a-f]{4,40}$/.test(prefix)) return null; + const loose = this.hasLoose + ? this.sql + .exec<{ oid: string }>("SELECT oid FROM objects WHERE oid LIKE ? LIMIT 2", prefix + "%") + .toArray() + .map((r) => r.oid) + : []; + const all = [...new Set([...loose, ...this.packs.findOidPrefix(prefix)])]; + return all.length === 1 ? all[0] : null; + } + + allOids(): string[] { + return this.sql.exec<{ oid: string }>("SELECT oid FROM objects").toArray().map((r) => r.oid); + } + + deleteObject(oid: string): void { + this.sql.exec("DELETE FROM objects WHERE oid = ?", oid); + this.sql.exec("DELETE FROM chunks WHERE oid = ?", oid); + } + + dbSize(): number { + return this.sql.databaseSize; + } + + wipe(): void { + this.sql.exec("DROP TABLE IF EXISTS objects"); + this.sql.exec("DROP TABLE IF EXISTS chunks"); + this.sql.exec("DROP TABLE IF EXISTS refs"); + this.sql.exec("DROP TABLE IF EXISTS meta"); + this.sql.exec("DROP TABLE IF EXISTS reachable"); + this.sql.exec("DROP TABLE IF EXISTS peeled"); + this.sql.exec("DROP TABLE IF EXISTS stats_cache"); + this.packs.wipe(); + // meta (with the flag) is gone; a fresh empty repo has no loose objects + this.hasLoose = false; + } + + + /** All refs except HEAD, sorted by name. */ + refs(): { name: string; target: string }[] { + return this.sql + .exec<{ name: string; target: string }>( + "SELECT name, target FROM refs WHERE name != 'HEAD' ORDER BY name" + ) + .toArray(); + } + + getRef(name: string): string | null { + const rows = this.sql + .exec<{ target: string }>("SELECT target FROM refs WHERE name = ?", name) + .toArray(); + return rows[0]?.target ?? null; + } + + setRef(name: string, target: string): void { + this.sql.exec( + "INSERT INTO refs (name, target) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET target = excluded.target", + name, + target + ); + } + + delRef(name: string): void { + this.sql.exec("DELETE FROM refs WHERE name = ?", name); + } + + /** HEAD symref target, e.g. "refs/heads/main". */ + head(): string { + const raw = this.getRef("HEAD"); + if (raw?.startsWith("ref: ")) return raw.slice(5); + return raw ?? "refs/heads/main"; + } + + setHead(refName: string): void { + this.setRef("HEAD", `ref: ${refName}`); + } + + /** Resolve HEAD to an oid, or null for an empty/unborn repo. */ + resolveHead(): string | null { + return this.getRef(this.head()); + } + + + getMeta(key: string): string | null { + const rows = this.sql + .exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", key) + .toArray(); + return rows[0]?.value ?? null; + } + + setMeta(key: string, value: string): void { + this.sql.exec( + "INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + key, + value + ); + } + + /** + * Cached peel target for an oid (tag -> ... -> commit). Tag oids are + * content-addressed and immutable, so a hit never needs a version check. + */ + getPeeled(oid: string): string | null { + const rows = this.sql.exec<{ target: string }>("SELECT target FROM peeled WHERE oid = ?", oid).toArray(); + return rows[0]?.target ?? null; + } + + setPeeled(oid: string, target: string): void { + this.sql.exec("INSERT OR IGNORE INTO peeled (oid, target) VALUES (?, ?)", oid, target); + } + + /** + * Cached commit-activity aggregation for a (tip commit oid, period) pair. + * Keyed on the tip's oid rather than a ref name: history under a fixed + * commit oid is immutable, so no version check is needed for a hit. + */ + getStatsCache(tipOid: string, period: string): string | null { + const rows = this.sql + .exec<{ data: string }>("SELECT data FROM stats_cache WHERE tip_oid = ? AND period = ?", tipOid, period) + .toArray(); + return rows[0]?.data ?? null; + } + + setStatsCache(tipOid: string, period: string, data: string): void { + this.sql.exec( + "INSERT OR REPLACE INTO stats_cache (tip_oid, period, data) VALUES (?, ?, ?)", + tipOid, + period, + data + ); + } + + /** + * A tag over the current ref state (names + tips + HEAD). The cached + * reachable object set is keyed on it: any push, ref delete, or gc changes + * a tip and so bumps the version, which is exactly when the set can change. + * A sha1 hex string never collides with the "" invalidation sentinel. + */ + reachableVersion(): string { + const parts: string[] = []; + for (const r of this.refs()) parts.push(`${r.name}\0${r.target}`); + parts.push(`HEAD\0${this.getRef("HEAD") ?? ""}`); + return sha1hex(te.encode(parts.join("\n"))); + } + + /** + * The cached reachable object set as an OidSet with every entry marked (so + * markedSize/markedAtHex/isMarkedHex feed the pack-emission path directly), + * or null when the cache is missing or its version no longer matches current + * refs. The version check is the only correctness gate — a stale set is + * never returned, so the fast path can never serve unreachable objects. + */ + loadReachable(): OidSet | null { + if (this.getMeta("reachable-version") !== this.reachableVersion()) return null; + const rows = this.sql.exec<{ oid: string }>("SELECT oid FROM reachable").toArray(); + if (!rows.length) return null; + const set = new OidSet(rows.length); + for (const r of rows) set.markHex(r.oid); + return set; + } + + /** + * Persist the marked sub-set of `set` (a full clone's reachable object set) + * and stamp it with the current ref version. Yields periodically so a large + * write never monopolizes the event loop; if refs change mid-write (a push + * landing during a cold clone) the version guard abandons the stamp, leaving + * the half-written table unversioned and thus ignored until it is rebuilt. + */ + async saveReachable(set: OidSet, version: string = this.reachableVersion()): Promise { + // SAM: `version` is the ref version the walk that built `set` started from. + // A push that moved refs during that walk (the walk yields) makes `set` + // describe old refs; stamping it with the new version would let a stranded, + // later-collected object pass for reachable. + if (this.reachableVersion() !== version) return; + // Single-flight: a later save's DELETE wipes this one's rows, so a superseded + // save must neither keep inserting nor stamp what is left. + const generation = ++this.reachableSaveGeneration; + const current = () => this.reachableSaveGeneration === generation && this.reachableVersion() === version; + // Unstamp before rewriting: while this rewrite yields, a stamp left from an earlier + // save would present the partial table as the whole reachable set, and a push in the + // window would extend that partial table and re-stamp it valid. + this.setMeta("reachable-version", ""); + this.sql.exec("DELETE FROM reachable"); + const n = set.markedSize; + for (let i = 0; i < n; i++) { + this.sql.exec("INSERT OR IGNORE INTO reachable (oid) VALUES (?)", set.markedAtHex(i)); + if ((i & 8191) === 8191) { + if (!current()) return; + await new Promise((r) => setTimeout(r, 0)); + if (!current()) return; + } + } + if (!current()) return; + this.setMeta("reachable-version", version); + } + + /** + * Fold every oid in `set` into the cached reachable set and re-stamp it with + * the current ref version. Used on a fast-forward push, where the receive + * connectivity walk already visited exactly the newly connected objects: + * union with the prior (validated) set yields the new reachable set without + * a fresh graph walk. Only sound when no object became unreachable — the + * caller must have a valid prior cache and no stranded history. + */ + extendReachable(set: OidSet): void { + for (let i = 0; i < set.size; i++) { + this.sql.exec("INSERT OR IGNORE INTO reachable (oid) VALUES (?)", set.atHex(i)); + } + this.setMeta("reachable-version", this.reachableVersion()); + } + + /** Drop the version stamp so the next full clone rebuilds the set by walking. */ + invalidateReachable(): void { + this.setMeta("reachable-version", ""); + } + + /** + * True when the persisted reachable set still matches the current refs, so a + * full clone can stream its objects straight from storage (see + * `reachablePackedAfter`) instead of loading the whole set into an OidSet and + * walking. The version check is the same correctness gate `loadReachable` + * uses — a stale set is never streamed. + */ + reachableCacheValid(): boolean { + return this.getMeta("reachable-version") === this.reachableVersion(); + } + + /** Size of the cached reachable set — the exact object count a warm full + * clone declares in its pack header. */ + reachableCount(): number { + return this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM reachable").one().n; + } + + /** Whether `oid` is in the cached reachable set. On the warm full-clone path a + * stored delta ships as a ref-delta only when its base is also being sent, + * i.e. also reachable; otherwise that object is inflated whole. */ + reachableHas(oid: string): boolean { + return this.sql.exec("SELECT 1 FROM reachable WHERE oid = ? LIMIT 1", oid).toArray().length > 0; + } + + /** + * Reachable objects that live in a pack, one keyset page at a time in + * (pack_id, offset) storage order. Marching each pack sequentially keeps the + * raw-chunk cache hitting, and the (pack_id, offset) cursor holds no + * per-object state in the isolate — so a warm full clone streams in O(page) + * memory no matter how many objects the repo has, replacing the OidSet and + * parallel typed arrays the walk path builds. + */ + reachablePackedAfter(afterPack: number, afterOffset: number, limit: number): PackedReachable[] { + return this.sql + .exec<{ + oid: string; + pack_id: number; + offset: number; + data_off: number; + data_len: number; + type: ObjType; + entry_size: number; + base_oid: string | null; + }>( + `SELECT p.oid, p.pack_id, p.offset, p.data_off, p.data_len, p.type, p.entry_size, p.base_oid + FROM reachable r JOIN pack_objects p ON p.oid = r.oid + WHERE p.pack_id > ? OR (p.pack_id = ? AND p.offset > ?) + ORDER BY p.pack_id, p.offset + LIMIT ?`, + afterPack, + afterPack, + afterOffset, + limit, + ) + .toArray() + .map((r) => ({ + oid: r.oid, + packId: r.pack_id, + offset: r.offset, + dataOff: r.data_off, + dataLen: r.data_len, + type: r.type, + entrySize: r.entry_size, + baseOid: r.base_oid, + })); + } + + /** Reachable objects with no pack entry (loose), ordered by oid — streamed + * after every packed object so a warm full clone has a stable total order. */ + reachableLooseAfter(afterOid: string, limit: number): string[] { + return this.sql + .exec<{ oid: string }>( + `SELECT r.oid FROM reachable r + WHERE NOT EXISTS (SELECT 1 FROM pack_objects p WHERE p.oid = r.oid) AND r.oid > ? + ORDER BY r.oid LIMIT ?`, + afterOid, + limit, + ) + .toArray() + .map((r) => r.oid); + } +} diff --git a/apps/api/src/vendor/dgit/git/util.ts b/apps/api/src/vendor/dgit/git/util.ts new file mode 100644 index 0000000000..29d4132377 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/util.ts @@ -0,0 +1,41 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +export const te = new TextEncoder(); +export const td = new TextDecoder(); + +export function concat(parts: Uint8Array[]): Uint8Array { + let len = 0; + for (const p of parts) len += p.length; + const out = new Uint8Array(len); + let off = 0; + for (const p of parts) { + out.set(p, off); + off += p.length; + } + return out; +} + +export function toHex(b: Uint8Array): string { + let s = ""; + for (let i = 0; i < b.length; i++) s += b[i].toString(16).padStart(2, "0"); + return s; +} + +export function fromHex(s: string): Uint8Array { + const out = new Uint8Array(s.length / 2); + for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16); + return out; +} + +export const ZERO_OID = "0".repeat(40); + +export function isOid(s: string): boolean { + return /^[0-9a-f]{40}$/.test(s); +} + +export function sha1hex(data: Uint8Array): string { + return toHex(sha1(data)); +} + +import { sha1 } from "./sha1"; +export { sha1, Sha1 } from "./sha1"; diff --git a/apps/api/src/vendor/dgit/git/zlib.ts b/apps/api/src/vendor/dgit/git/zlib.ts new file mode 100644 index 0000000000..9979abb537 --- /dev/null +++ b/apps/api/src/vendor/dgit/git/zlib.ts @@ -0,0 +1,47 @@ +/* eslint-disable */ +// @ts-nocheck -- vendored dgit core, see ../UPSTREAM.md (upstream typechecks strict, without noUncheckedIndexedAccess) +import pako from "pako"; +import { chargeGitWork, gitWorkLimits } from "./budget"; +import { concat } from "./util"; + +/** Deflate with a zlib wrapper (what git uses for loose objects and pack entries). */ +export function deflate(data: Uint8Array): Uint8Array { + return pako.deflate(data); +} + +export function inflate(data: Uint8Array): Uint8Array { + const inf = new pako.Inflate({ chunkSize: 16 * 1024 }); + const parts: Uint8Array[] = []; + let size = 0; + inf.onData = (chunk: Uint8Array) => { + size += chunk.length; + if (size > gitWorkLimits().maxObjectBytes) throw new Error("git object exceeds inflated size limit"); + chargeGitWork(chunk.length); + parts.push(chunk); + }; + inf.push(data, true); + if (inf.err) throw new Error(`inflate failed: ${inf.msg}`); + return concat(parts); +} + +/** + * gunzip with an output budget. A gzipped request body compresses ~1000:1 in + * the adversarial case, so the compressed length says nothing about what it + * inflates to: the only safe bound is on the bytes coming *out*. Inflating + * incrementally and stopping the moment the budget is passed means an + * over-inflating body costs the budget, not the bomb. + */ +export function gunzipLimited(data: Uint8Array, maxOut: number): Uint8Array { + const inf = new pako.Inflate({ windowBits: 15 + 16 }); + const parts: Uint8Array[] = []; + let out = 0; + (inf as unknown as { onData: (c: Uint8Array) => void }).onData = (c: Uint8Array) => { + out += c.length; + if (out > maxOut) throw new Error(`request body exceeds maximum size (${maxOut} bytes decompressed)`); + parts.push(c); + }; + inf.push(data, true); + const anyInf = inf as unknown as { err: number; msg: string }; + if (anyInf.err) throw new Error(`gunzip failed: ${anyInf.msg}`); + return concat(parts); +} diff --git a/apps/api/tests/helpers/selfhost-only-modules.ts b/apps/api/tests/helpers/selfhost-only-modules.ts index 1c6b4453ce..94f048421b 100644 --- a/apps/api/tests/helpers/selfhost-only-modules.ts +++ b/apps/api/tests/helpers/selfhost-only-modules.ts @@ -9,7 +9,7 @@ * * Every specifier `ts.preProcessFile` reports counts, type-only imports included: erring towards * a false alarm is cheaper than shipping the code. Workspace packages (`@simple-agent-manager/*`) - * are not descended into; none of them imports these modules or pako. + * are descended into through their declared exports, including sources behind dist/. */ import { existsSync, readFileSync, statSync } from 'node:fs'; import { dirname, relative, resolve } from 'node:path'; @@ -18,12 +18,14 @@ import ts from 'typescript'; export const REPO_ROOT = resolve(import.meta.dirname, '../../../..'); export const API_SRC = resolve(REPO_ROOT, 'apps/api/src'); +/** Walking a >1,000-file import graph takes several seconds on a loaded CI runner. */ +export const GRAPH_WALK_TIMEOUT_MS = 60_000; /** Repository-relative path prefixes only the self-host build may contain. */ export const SELFHOST_ONLY_PATHS: readonly string[] = [ 'apps/api/src/selfhost/', // hosted-git-repo.ts, hosted-git-gc.ts, hosted-git-ls-refs.ts and any file split out of them. - 'apps/api/src/durable-objects/hosted-git-', + 'apps/api/src/selfhost/hosted-git/hosted-git-', 'apps/api/src/vendor/dgit/', ]; @@ -84,6 +86,24 @@ export function collectImportGraph(entry: string): ImportGraph { } else { const name = packageName(specifier); if (!packages.has(name)) packages.set(name, relative(REPO_ROOT, file)); + if (name.startsWith('@simple-agent-manager/')) { + const packageDir = resolve(REPO_ROOT, 'packages', name.split('/')[1]!); + const manifestPath = resolve(packageDir, 'package.json'); + if (!isFile(manifestPath)) throw new Error(`missing workspace manifest: ${name}`); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')); + const subpath = specifier === name ? '.' : `.${specifier.slice(name.length)}`; + const exported = manifest.exports?.[subpath]; + const target = + typeof exported === 'string' + ? exported + : (exported?.import ?? + exported?.default ?? + (subpath === '.' ? manifest.main : undefined)); + if (!target) throw new Error(`cannot resolve workspace export: ${specifier}`); + // These TS packages publish dist/, but the guard must inspect current source edits. + const source = target.replace(/^\.\/dist\//, './src/').replace(/\.js$/, '.ts'); + pending.push(resolveRelative(manifestPath, source)); + } } } } diff --git a/apps/api/tests/hosted-git/celld-entry-bundle.test.ts b/apps/api/tests/hosted-git/celld-entry-bundle.test.ts new file mode 100644 index 0000000000..913108555e --- /dev/null +++ b/apps/api/tests/hosted-git/celld-entry-bundle.test.ts @@ -0,0 +1,65 @@ +/** + * The generated self-host project bundles on celld with hosted git in it. + * + * The celld config and entry come from scripts/selfhost (celld-config.ts, celld-project.ts) and + * the real apps/api/wrangler.toml, exactly as `pnpm selfhost:deploy` writes them. The pinned celld + * then bundles each one with `celld deploy --dry-run`, which builds the Worker with esbuild and + * prints every binding without touching a bucket. This catches what the Cloudflare-side guard + * (tests/unit/selfhost/selfhost-only-modules.test.ts) cannot: a generated entry that no longer + * resolves the self-host module, or a celld config that lost the HOSTED_GIT binding. + */ +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { mkdirSync } from 'node:fs'; +import { resolve as scratchResolve } from 'node:path'; +const tmpdir = () => { + const dir = scratchResolve(import.meta.dirname, '../../../../.tmp'); + mkdirSync(dir, { recursive: true }); + return dir; +}; +import { join, resolve } from 'node:path'; + +import * as TOML from '@iarna/toml'; +import { afterAll, describe, expect, it } from 'vitest'; + +import type { WranglerToml } from '../../../../scripts/deploy/types'; +import { ensureCelldBinary, resolveEsbuild } from '../../../../scripts/selfhost/celld-binary'; +import { buildCelldConfig } from '../../../../scripts/selfhost/celld-config'; +import { + CELLD_MAIN, + prepareCelldProject, + writeCelldConfig, +} from '../../../../scripts/selfhost/celld-project'; + +const API_DIR = resolve(import.meta.dirname, '../..'); +const scratch = mkdtempSync(join(tmpdir(), 'sam-celld-entry-')); + +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +describe('generated celld project', () => { + it('bundles with the HostedGitRepo binding', async () => { + const plan = buildCelldConfig( + TOML.parse(readFileSync(join(API_DIR, 'wrangler.toml'), 'utf8')) as unknown as WranglerToml, + { main: CELLD_MAIN, baseDomain: 'box.example.com' } + ); + const projectDir = join(scratch, 'plain'); + prepareCelldProject({ apiDir: API_DIR, projectDir, plan }); + writeCelldConfig(projectDir, plan.config); + + const celld = await ensureCelldBinary(join(tmpdir(), 'sam-celld-bin')); + const result = spawnSync( + celld, + ['deploy', projectDir, '--dry-run', '--bucket', 's3://dry-run-not-written'], + { + encoding: 'utf8', + timeout: 300_000, + env: { ...process.env, CELLD_ESBUILD: resolveEsbuild(API_DIR) }, + } + ); + const output = `${result.stdout}${result.stderr}`; + expect(result.status, output.slice(-4000)).toBe(0); + expect(output).toContain('Bundled workspaces-api'); + expect(output).toMatch(/env\.HOSTED_GIT \(HostedGitRepo\)\s+Durable Object \(SQLite\)/); + expect(output).toMatch(/env\.HOSTED_GIT_BACKEND \(Text\)/); + }, 600_000); +}); diff --git a/apps/api/tests/hosted-git/celld/README.md b/apps/api/tests/hosted-git/celld/README.md new file mode 100644 index 0000000000..4d045da921 --- /dev/null +++ b/apps/api/tests/hosted-git/celld/README.md @@ -0,0 +1,25 @@ +# Hosted git on celld (manual) + +Runs the real `HostedGitRepo` Durable Object under `celld dev` 0.6.3 with a bare router (no SAM +auth, which is plain JavaScript covered by `pnpm test:hosted-git` under workerd), then drives the +stock `git` CLI against it. Not part of CI. + +```bash +mkdir -p /tmp/celld-run/proj /tmp/celld-run/bin && cd /tmp/celld-run +curl -fsSL -o celld.gz https://github.com/denoland/celld/releases/download/v0.6.3/celld-x86_64-unknown-linux-gnu.gz +echo "5084a083472cf036551a7eac63fa24d22bb9a56323c517f63205724c12783047 celld.gz" | sha256sum -c +gunzip celld.gz && chmod +x celld +ln -s "$(find /node_modules/.pnpm -path '*@esbuild+linux-x64*/bin/esbuild' | head -1)" bin/esbuild +cp /apps/api/tests/hosted-git/celld/{entry.ts,wrangler.json} proj/ +ln -s /apps/api/src proj/src +PATH=/tmp/celld-run/bin:$PATH ./celld dev proj --port 9876 --no-watch & +bash /apps/api/tests/hosted-git/celld/conformance.sh +bash /apps/api/tests/hosted-git/celld/near-cap.sh +``` + +Result on 2026-11-12 (4 vCPU workspace, state on tmpfs, no bucket, so durability waits are not +included; the box's bucket adds latency): push, full clone + `fsck --strict`, shallow clone, fetch +into the shallow clone, and branch create and delete all pass. A 65 MiB push and a 30,071-object push +are refused with `remote: SAM: push refused: ...`. A `0004-004` pkt-line body answers 400 in 4 ms and +the repository keeps serving. Near the object cap (28,102 objects): push 3.2 s, cold clone 45 s, warm +clone 1.1 s, shallow clone 1.9 s, `fsck --strict` clean. diff --git a/apps/api/tests/hosted-git/celld/conformance.sh b/apps/api/tests/hosted-git/celld/conformance.sh new file mode 100755 index 0000000000..2094a0438c --- /dev/null +++ b/apps/api/tests/hosted-git/celld/conformance.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -u +cd /tmp/celld-run && rm -rf w && mkdir w && cd w +export GIT_TERMINAL_PROMPT=0 GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@e GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@e +G() { git -c gc.auto=0 -c protocol.version=2 "$@"; } +R=http://127.0.0.1:9876/repo/demo2.git +t() { local s=$(date +%s%N); "$@"; local rc=$?; echo " rc=$rc $(( ($(date +%s%N)-s)/1000000 )) ms: $*"; } +curl -s -X PUT -d '{"defaultBranch":"main"}' $R/init; echo +G init -q -b main src && cd src && for i in $(seq 1 50); do echo "line $i" > f$i.txt; done && G add . && G commit -qm one && for c in 2 3 4; do echo $c >> f1.txt; G commit -qam c$c; done +t G push -q $R main +cd ..; t G clone -q $R full; G -C full fsck --strict && echo " fsck ok, commits=$(G -C full rev-list --count HEAD)" +t G clone -q --depth 1 $R shallow; echo " shallow commits: $(G -C shallow rev-list --count HEAD)" +cd src && echo more >> f2.txt && G commit -qam c5 && t G push -q $R main && cd .. +t G -C shallow fetch -q origin main; echo " fetched $(G -C shallow rev-parse --short FETCH_HEAD) vs $(G -C src rev-parse --short HEAD)" +cd src && G checkout -qb gone && echo x > gone.txt && G add . && G commit -qm gone && t G push -q $R gone && t G push -q $R --delete gone && cd .. +echo "== push over the size cap (65 MiB random)" +cd src && G checkout -q main && head -c $((65*1024*1024)) /dev/urandom > big.bin && G add big.bin && G commit -qm big && t G push $R main:refs/heads/big 2>&1 | grep -E "remote:|error|rejected" | head -4; G reset -q --hard HEAD~1; cd .. +echo "== push over the object cap" +cd src && mkdir many && for i in $(seq 0 30000); do echo $i > many/f$i; done && G add many && G commit -qm many && t G push $R main:refs/heads/many 2>&1 | grep -E "remote:|error|rejected" | head -4; cd .. +echo "== repo still serves after refusals"; t G clone -q $R after; G -C after fsck --strict && echo " fsck ok" diff --git a/apps/api/tests/hosted-git/celld/entry.ts b/apps/api/tests/hosted-git/celld/entry.ts new file mode 100644 index 0000000000..976d2a12e2 --- /dev/null +++ b/apps/api/tests/hosted-git/celld/entry.ts @@ -0,0 +1,25 @@ +// celld dev harness (tests/hosted-git/celld/README.md): the real HostedGitRepo Durable Object behind a bare router (no auth). +import { HostedGitRepo } from './src/selfhost/hosted-git/hosted-git-repo'; + +export { HostedGitRepo }; + +interface Env { + HOSTED_GIT: DurableObjectNamespace; +} + +export default { + async fetch(req: Request, env: Env): Promise { + const url = new URL(req.url); + const m = /^\/repo\/([a-z0-9-]+)\.git(\/.*)$/.exec(url.pathname); + if (!m) return new Response('not found\n', { status: 404 }); + const stub = env.HOSTED_GIT.get(env.HOSTED_GIT.idFromName(m[1]!)); + url.pathname = m[2]!; + return stub.fetch( + new Request(url.toString(), { + method: req.method, + headers: req.headers, + body: req.method === 'GET' ? null : req.body, + }) + ); + }, +}; diff --git a/apps/api/tests/hosted-git/celld/near-cap.sh b/apps/api/tests/hosted-git/celld/near-cap.sh new file mode 100755 index 0000000000..c15d58415f --- /dev/null +++ b/apps/api/tests/hosted-git/celld/near-cap.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +cd /tmp/celld-run && rm -rf n && mkdir n && cd n +export GIT_TERMINAL_PROMPT=0 GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@e GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@e +G() { git -c gc.auto=0 "$@"; } +R=http://127.0.0.1:9876/repo/nearcap.git +curl -s -X PUT -d '{"defaultBranch":"main"}' $R/init >/dev/null +G init -q -b main src && cd src +for d in $(seq 0 99); do mkdir d$d; for i in $(seq 0 279); do echo "$d $i $RANDOM" > d$d/f$i; done; done +G add . && G commit -qm bulk +echo "objects: $(G count-objects -v | awk '/count|in-pack/{s+=$2} END{print s}')" +s=$(date +%s%N); G push -q $R main 2>/dev/null; echo "push rc=$? $(( ($(date +%s%N)-s)/1000000 )) ms" +cd ..; s=$(date +%s%N); G clone -q $R cold; echo "cold clone rc=$? $(( ($(date +%s%N)-s)/1000000 )) ms" +s=$(date +%s%N); G clone -q $R warm; echo "warm clone rc=$? $(( ($(date +%s%N)-s)/1000000 )) ms" +s=$(date +%s%N); G clone -q --depth 1 $R shallow; echo "shallow clone rc=$? $(( ($(date +%s%N)-s)/1000000 )) ms" +G -C cold fsck --strict && echo fsck ok diff --git a/apps/api/tests/hosted-git/celld/wrangler.json b/apps/api/tests/hosted-git/celld/wrangler.json new file mode 100644 index 0000000000..dab17175f0 --- /dev/null +++ b/apps/api/tests/hosted-git/celld/wrangler.json @@ -0,0 +1,7 @@ +{ + "name": "hosted-git-celld", + "main": "entry.ts", + "compatibility_date": "2026-01-01", + "durable_objects": { "bindings": [{ "name": "HOSTED_GIT", "class_name": "HostedGitRepo" }] }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["HostedGitRepo"] }] +} diff --git a/apps/api/tests/hosted-git/hosted-git-conformance.test.ts b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts new file mode 100644 index 0000000000..1819768d78 --- /dev/null +++ b/apps/api/tests/hosted-git/hosted-git-conformance.test.ts @@ -0,0 +1,1557 @@ +/** + * Conformance of the SAM-hosted git server with a real git client. + * + * Everything below drives the stock `git` CLI over HTTP against the HostedGitRepo Durable Object + * running in Miniflare, through the same authenticated route production mounts at + * `https://api./git/.git`. Repositories are created through the real + * project-create route (artifacts provider, an email-only user with no GitHub link), which seeds + * the README in-process; workspace credentials come from the real POST /workspaces/:id/git-token. + */ +import { execFile, spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { mkdirSync } from 'node:fs'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { resolve as scratchResolve } from 'node:path'; +const tmpdir = () => { + const dir = scratchResolve(import.meta.dirname, '../../../../.tmp'); + mkdirSync(dir, { recursive: true }); + return dir; +}; +import { join } from 'node:path'; +import { promisify } from 'node:util'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { + DEFAULT_HOSTED_GIT_MAX_PUSH_BYTES, + DEFAULT_HOSTED_GIT_MAX_REPO_OBJECTS, +} from '../../src/selfhost/hosted-git/limits'; +import { buildReceivePackRequest,buildSeedPack } from '../../src/services/artifacts/seed-readme'; +import { + HOSTED_GIT_TEST_BASE_DOMAIN, + HOSTED_GIT_TEST_TOKEN_TTL_SECONDS, + type HostedGitRuntime, + startHostedGitRuntime, +} from './support/hosted-git-runtime'; + +const execFileAsync = promisify(execFile); + +let runtime: HostedGitRuntime; +let scratch: string; +/** Fake public forge: https://github.com/sam-test/.git is served from a hosted repo. */ +const fakeForge = new Map(); + +interface GitResult { + code: number; + stdout: string; + stderr: string; +} + +/** Run git with no ambient credentials, prompts or config. */ +async function git(args: string[], cwd?: string): Promise { + try { + const { stdout, stderr } = await execFileAsync( + 'git', + [ + '-c', + 'credential.helper=', + '-c', + 'protocol.version=2', + '-c', + 'gc.auto=0', + '-c', + 'maintenance.auto=false', + ...args, + ], + { + cwd, + maxBuffer: 64 * 1024 * 1024, + env: { + PATH: process.env.PATH ?? '', + HOME: scratch, + GIT_TERMINAL_PROMPT: '0', + GIT_CONFIG_NOSYSTEM: '1', + GIT_AUTHOR_NAME: 'Test', + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com', + }, + } + ); + return { code: 0, stdout, stderr }; + } catch (error) { + const e = error as { code?: number; stdout?: string; stderr?: string }; + return { + code: typeof e.code === 'number' ? e.code : 1, + stdout: e.stdout ?? '', + stderr: e.stderr ?? '', + }; + } +} + +async function gitOk(args: string[], cwd?: string): Promise { + const result = await git(args, cwd); + if (result.code !== 0) { + throw new Error( + `git failed (${result.code}):\n${result.stderr.replace(/samgit1\.[A-Za-z0-9_.-]+/g, '[redacted]').replace(/https?:\/\/[^\s/@]+:[^\s/@]+@/g, 'https://[redacted]@')}` + ); + } + return result; +} + +/** A local URL for a repository remote, with the token as the Basic password. */ +function localRemote(remote: string, token?: string): string { + const url = new URL(remote); + const local = new URL(runtime.origin); + local.pathname = url.pathname; + if (token) { + local.username = 'x'; + local.password = token; + } + return local.toString(); +} + +async function mintToken( + project: { artifactsRepoId: string; ownerId: string }, + scope: 'read' | 'write', + extra: { ttlSeconds?: number; workspaceId?: string; userId?: string } = {} +): Promise { + const res = await runtime.fetch('/__test/hosted-git-token', { + method: 'POST', + body: JSON.stringify({ + repo: project.artifactsRepoId, + scope, + userId: project.ownerId, + ...extra, + }), + }); + expect(res.status).toBe(200); + return ((await res.json()) as { token: string }).token; +} + +let userCounter = 0; +async function createEmailOnlyUser(): Promise { + userCounter += 1; + const id = `user-hosted-git-${userCounter}`; + await runtime.DATABASE.prepare( + `INSERT INTO users (id, email, email_verified, name, role, status, created_at, updated_at) + VALUES (?, ?, 1, ?, 'user', 'active', ?, ?)` + ) + .bind(id, `${id}@example.com`, id, Date.now(), Date.now()) + .run(); + return id; +} + +interface CreatedProject { + id: string; + ownerId: string; + repository: string; + artifactsRepoId: string; + defaultBranch: string; +} + +async function createHostedProject(userId: string, name: string): Promise { + const res = await runtime.fetch('/api/projects', { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-test-user-id': userId }, + body: JSON.stringify({ name, repoProvider: 'artifacts', description: 'Hosted repo test' }), + }); + const body = (await res.json()) as Record; + expect(res.status, JSON.stringify(body)).toBe(201); + const row = await runtime.DATABASE.prepare( + `SELECT id, repository, artifacts_repo_id AS artifactsRepoId, default_branch AS defaultBranch + FROM projects WHERE id = ?` + ) + .bind(body.id) + .first(); + expect(row).not.toBeNull(); + return { ...row!, ownerId: userId }; +} + +async function freshDir(name: string): Promise { + const dir = join(scratch, `${name}-${randomBytes(4).toString('hex')}`); + await mkdir(dir, { recursive: true }); + return dir; +} + +beforeAll(async () => { + scratch = await mkdtemp(join(tmpdir(), 'sam-hosted-git-client-')); + runtime = await startHostedGitRuntime(async (request) => { + const url = new URL(request.url); + const match = /^\/sam-test\/([^/]+?)(?:\.git)?(\/.*)$/.exec(url.pathname); + const source = url.hostname === 'github.com' && match ? fakeForge.get(match[1]!) : undefined; + if (!source) return new Response('not found', { status: 404 }); + const headers = new Headers(request.headers); + headers.set('authorization', `Basic ${btoa(`x:${source.token}`)}`); + // Node's fetch sets these itself and refuses a forwarded content-length + // ("invalid content-length header") on the POST git sends for protocol v2 ls-refs. + headers.delete('content-length'); + headers.delete('host'); + return fetch(`${runtime.origin}/git/${source.repo}.git${match![2]}${url.search}`, { + method: request.method, + headers, + body: request.method === 'GET' ? undefined : await request.arrayBuffer(), + }); + }); +}); + +afterAll(async () => { + await runtime?.close(); + if (scratch) await rm(scratch, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); +}); + +describe('SAM-hosted repositories with a real git client', () => { + let owner: string; + let project: CreatedProject; + + beforeAll(async () => { + owner = await createEmailOnlyUser(); + project = await createHostedProject(owner, 'Hosted Conformance'); + }); + + it('creates the project with a hosted remote under api. and seeds a README', async () => { + expect(project.repository).toBe( + `https://api.${HOSTED_GIT_TEST_BASE_DOMAIN}/git/${project.artifactsRepoId}.git` + ); + const token = await mintToken(project, 'read'); + const dir = await freshDir('clone'); + await gitOk(['clone', localRemote(project.repository, token), dir]); + const readme = await readFile(join(dir, 'README.md'), 'utf8'); + expect(readme).toContain('Hosted Conformance'); + const branch = await gitOk(['rev-parse', '--abbrev-ref', 'HEAD'], dir); + expect(branch.stdout.trim()).toBe(project.defaultBranch); + const fsck = await git(['fsck', '--strict'], dir); + expect(fsck.code).toBe(0); + }); + + it('pushes a branch, then shallow-clones and fetches it', async () => { + const token = await mintToken(project, 'write'); + const work = await freshDir('work'); + await gitOk(['clone', localRemote(project.repository, token), work]); + await gitOk(['checkout', '-b', 'feature/one'], work); + for (let i = 0; i < 3; i++) { + await writeFile(join(work, `file-${i}.txt`), `content ${i}\n`); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', `commit ${i}`], work); + } + await gitOk(['push', 'origin', 'feature/one'], work); + const head = (await gitOk(['rev-parse', 'HEAD'], work)).stdout.trim(); + + const shallow = await freshDir('shallow'); + await gitOk( + [ + 'clone', + '--depth', + '1', + '--branch', + 'feature/one', + localRemote(project.repository, token), + shallow, + ], + undefined + ); + expect((await gitOk(['rev-parse', 'HEAD'], shallow)).stdout.trim()).toBe(head); + expect((await gitOk(['rev-list', '--count', 'HEAD'], shallow)).stdout.trim()).toBe('1'); + + // A new commit on the server, then fetch it into the shallow clone. + await writeFile(join(work, 'later.txt'), 'later\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'later'], work); + await gitOk(['push', 'origin', 'feature/one'], work); + const later = (await gitOk(['rev-parse', 'HEAD'], work)).stdout.trim(); + await gitOk(['fetch', 'origin', 'feature/one'], shallow); + expect((await gitOk(['rev-parse', 'FETCH_HEAD'], shallow)).stdout.trim()).toBe(later); + + // A full clone sees every branch and passes fsck. + const full = await freshDir('full'); + await gitOk(['clone', localRemote(project.repository, token), full]); + const branches = (await gitOk(['branch', '-r'], full)).stdout; + expect(branches).toContain('origin/feature/one'); + expect((await git(['fsck', '--strict'], full)).code).toBe(0); + }); + + it('refuses an unauthenticated clone', async () => { + const dir = await freshDir('anon'); + const result = await git(['clone', localRemote(project.repository), dir]); + expect(result.code).not.toBe(0); + expect(result.stderr).toMatch(/Authentication failed|could not read Username|401/); + }); + + it('refuses a push with a read-scoped token, and accepts the same push with write scope', async () => { + const read = await mintToken(project, 'read'); + const work = await freshDir('readonly'); + await gitOk(['clone', localRemote(project.repository, read), work]); + await writeFile(join(work, 'nope.txt'), 'nope\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'nope'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/read-only'], work); + expect(refused.code).not.toBe(0); + + const write = await mintToken(project, 'write'); + await gitOk(['remote', 'set-url', 'origin', localRemote(project.repository, write)], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/read-only'], work); + }); + + it("refuses another project's token, with an owner control", async () => { + const other = await createHostedProject(await createEmailOnlyUser(), 'Other Tenant'); + const otherToken = await mintToken(other, 'write'); + const attack = await freshDir('attack'); + const refused = await git(['clone', localRemote(project.repository, otherToken), attack]); + expect(refused.code).not.toBe(0); + + // Owner control: the same token works on its own repository. + const control = await freshDir('control'); + await gitOk(['clone', localRemote(other.repository, otherToken), control]); + expect(await readFile(join(control, 'README.md'), 'utf8')).toContain('Other Tenant'); + }); + + it('refuses an expired or tampered token', async () => { + const token = await mintToken(project, 'read'); + const [prefix, payload, signature] = token.split('.'); + const forged = JSON.parse(Buffer.from(payload!, 'base64url').toString()); + forged.repo = 'someone-else'; + const tampered = `${prefix}.${Buffer.from(JSON.stringify(forged)).toString('base64url')}.${signature}`; + const res = await runtime.fetch( + `/git/${project.artifactsRepoId}.git/info/refs?service=git-upload-pack`, + { headers: { authorization: `Basic ${btoa(`x:${tampered}`)}` } } + ); + expect(res.status).toBe(401); + const ok = await runtime.fetch( + `/git/${project.artifactsRepoId}.git/info/refs?service=git-upload-pack`, + { headers: { authorization: `Basic ${btoa(`x:${token}`)}` } } + ); + expect(ok.status).toBe(200); + }); + + it('refuses a small compressed pack with an oversized commit, then accepts a normal push', async () => { + const user = await createEmailOnlyUser(); + const target = await createHostedProject(user, 'Inflation bound'); + const token = await mintToken(target, 'write'); + const work = await freshDir('compressed-object'); + await gitOk(['clone', localRemote(target.repository, token), work]); + // A 17 MiB commit message compresses to a tiny pack, below the 64 MiB wire cap. + // Fixture stays fixed so raising/removing the 16 MiB object guard fails this test. + await writeFile(join(work, 'message'), 'a'.repeat(17 * 1024 * 1024)); + await gitOk(['commit', '--allow-empty', '-F', 'message'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/bomb'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain('inflated size limit'); + await gitOk(['reset', '--hard', 'origin/main'], work); + await gitOk(['commit', '--allow-empty', '-m', 'safe'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/safe'], work); + const refs = await gitOk(['ls-remote', 'origin'], work); + expect(refs.stdout).toContain('refs/heads/safe'); + expect(refs.stdout).not.toContain('refs/heads/bomb'); + }); + + it('refuses a push over the push-size cap with a clear message, and keeps the repository intact', async () => { + const token = await mintToken(project, 'write'); + const work = await freshDir('big'); + await gitOk(['clone', localRemote(project.repository, token), work]); + // Incompressible content just over the cap. + await writeFile( + join(work, 'big.bin'), + randomBytes(DEFAULT_HOSTED_GIT_MAX_PUSH_BYTES + 1024 * 1024) + ); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'big'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/too-big'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain('SAM: push refused'); + expect(refused.stderr).toContain('MiB limit for one push'); + + const check = await freshDir('after-big'); + await gitOk(['clone', localRemote(project.repository, token), check]); + const remoteBranches = (await gitOk(['branch', '-r'], check)).stdout; + expect(remoteBranches).not.toContain('too-big'); + }); + + it('refuses a push that would exceed the object cap, naming the limit', async () => { + const token = await mintToken(project, 'write'); + const work = await freshDir('many'); + await gitOk(['clone', localRemote(project.repository, token), work]); + const dir = join(work, 'many'); + await mkdir(dir); + // One distinct blob per file: more blobs than the cap allows in total. + for (let i = 0; i <= DEFAULT_HOSTED_GIT_MAX_REPO_OBJECTS; i++) { + await writeFile(join(dir, `f${i}`), `${i}\n`); + } + await gitOk(['add', '.'], work); + await gitOk(['commit', '-q', '-m', 'many'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/too-many'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain(`${DEFAULT_HOSTED_GIT_MAX_REPO_OBJECTS}-object limit`); + }); +}); + +describe('hosted git hardening (security review findings)', () => { + let project: CreatedProject; + + beforeAll(async () => { + project = await createHostedProject(await createEmailOnlyUser(), 'Hardening'); + }); + + function infoRefs(token: string): Promise { + return runtime.fetch(`/git/${project.artifactsRepoId}.git/info/refs?service=git-upload-pack`, { + headers: { authorization: `Basic ${btoa(`x:${token}`)}` }, + }); + } + + it('answers a negative pkt-line length promptly with 400 and keeps serving the repository', async () => { + const token = await mintToken(project, 'write'); + for (const body of ['0004-004', '-001', '0002', '00zz']) { + const started = Date.now(); + const res = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { + authorization: `Basic ${btoa(`x:${token}`)}`, + 'content-type': 'application/x-git-receive-pack-request', + }, + body, + }); + expect(res.status, body).toBe(400); + expect(Date.now() - started).toBeLessThan(5_000); + } + // Liveness: the same repository still answers. + expect((await infoRefs(token)).status).toBe(200); + }); + + it('refuses a chunked upload-pack body over the cap without buffering it', async () => { + const token = await mintToken(project, 'read'); + const chunk = new Uint8Array(1024 * 1024); + let sent = 0; + const body = new ReadableStream({ + pull(controller) { + if (sent >= 20) return controller.close(); + sent++; + controller.enqueue(chunk); + }, + }); + const res = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-upload-pack`, { + method: 'POST', + headers: { authorization: `Basic ${btoa(`x:${token}`)}` }, + body, + duplex: 'half', + } as RequestInit); + expect(res.status).toBe(413); + expect((await infoRefs(token)).status).toBe(200); + }); + + it('refuses a token with no person behind it (internal seeding tokens stay internal)', async () => { + const res = await runtime.fetch('/__test/hosted-git-token', { + method: 'POST', + body: JSON.stringify({ repo: project.artifactsRepoId, scope: 'read' }), + }); + const { token } = (await res.json()) as { token: string }; + expect((await infoRefs(token)).status).toBe(401); + expect((await infoRefs(await mintToken(project, 'read'))).status).toBe(200); + }); + + it("refuses a removed member's token, with an active-member control", async () => { + const member = await createEmailOnlyUser(); + const now = new Date().toISOString(); + await runtime.DATABASE.prepare( + `INSERT INTO project_members (project_id, user_id, role, status, created_at, updated_at) + VALUES (?, ?, 'maintainer', 'active', ?, ?)` + ) + .bind(project.id, member, now, now) + .run(); + const token = await mintToken(project, 'read', { userId: member }); + expect((await infoRefs(token)).status).toBe(200); + // A write token stops pushing as soon as the member's role loses write access. + const write = await mintToken(project, 'write', { userId: member }); + const receiveRefs = (t: string) => + runtime.fetch(`/git/${project.artifactsRepoId}.git/info/refs?service=git-receive-pack`, { + headers: { authorization: `Basic ${btoa(`x:${t}`)}` }, + }); + expect((await receiveRefs(write)).status).toBe(200); + await runtime.DATABASE.prepare( + `UPDATE project_members SET role = 'viewer' WHERE project_id = ? AND user_id = ?` + ) + .bind(project.id, member) + .run(); + expect((await receiveRefs(write)).status).toBe(401); + expect((await infoRefs(token)).status).toBe(200); + + await runtime.DATABASE.prepare( + `UPDATE project_members SET status = 'removed', removed_at = ? WHERE project_id = ? AND user_id = ?` + ) + .bind(now, project.id, member) + .run(); + expect((await infoRefs(token)).status).toBe(401); + }); +}); + +describe('browsing a hosted repository through the repo-browse API', () => { + it('lists branches, the tree and a file, and compares two branches', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Browse Me'); + const token = await mintToken(project, 'write'); + const work = await freshDir('browse'); + await gitOk(['clone', localRemote(project.repository, token), work]); + await gitOk(['checkout', '-b', 'feature/browse'], work); + await mkdir(join(work, 'src')); + await writeFile(join(work, 'src', 'app.ts'), 'export const answer = 42;\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'add app'], work); + await gitOk(['push', 'origin', 'feature/browse'], work); + + const get = async (path: string) => { + const res = await runtime.fetch(`/api/projects/${project.id}${path}`, { + headers: { 'x-test-user-id': owner }, + }); + const body = (await res.json()) as Record; + expect(res.status, `${path} ${JSON.stringify(body)}`).toBe(200); + return body; + }; + const branches = (await get('/repo/branches')) as { + branches: Array<{ name: string; isDefault: boolean }>; + }; + // Exactly the branches: the list asks the server for refs/heads/ only, so HEAD is never one + // (box round R13 D11: dgit ignored ref-prefix and "HEAD" showed up as a branch). + expect(branches.branches).toEqual([ + { name: project.defaultBranch, isDefault: true }, + { name: 'feature/browse', isDefault: false }, + ]); + + const tree = (await get('/repo/tree?ref=feature/browse')) as { + entries: Array<{ path: string }>; + }; + const paths = tree.entries.map((e) => e.path); + expect(paths).toContain('README.md'); + expect(paths).toContain('src/app.ts'); + + const file = (await get('/repo/file?ref=feature/browse&path=src/app.ts')) as { + content?: string; + }; + expect(file.content).toBe('export const answer = 42;\n'); + + const compare = (await get( + `/repo/compare?base=${project.defaultBranch}&head=feature/browse` + )) as { files: Array<{ path: string; status: string }> }; + expect(compare.files.map((f) => f.path)).toEqual(['src/app.ts']); + + const stranger = await createEmailOnlyUser(); + const denied = await runtime.fetch(`/api/projects/${project.id}/repo/branches`, { + headers: { 'x-test-user-id': stranger }, + }); + expect([403, 404]).toContain(denied.status); + }); +}); + +describe('garbage collection', () => { + it('reclaims the objects of a deleted branch and keeps the repository intact', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'GC Me'); + const token = await mintToken(project, 'write'); + const work = await freshDir('gc'); + await gitOk(['clone', localRemote(project.repository, token), work]); + await gitOk(['checkout', '-b', 'throwaway'], work); + for (let i = 0; i < 20; i++) await writeFile(join(work, `junk-${i}.bin`), randomBytes(4096)); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'junk'], work); + await gitOk(['push', 'origin', 'throwaway'], work); + type Info = { objects: number }; + const before = (await ( + await runtime.fetch(`/__test/info/${project.artifactsRepoId}`) + ).json()) as Info; + await gitOk(['push', 'origin', '--delete', 'throwaway'], work); + const after = (await ( + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }) + ).json()) as Info; + // 20 blobs + 1 tree + 1 commit were only reachable from the deleted branch. + expect(before.objects - after.objects).toBeGreaterThanOrEqual(22); + + const check = await freshDir('gc-check'); + await gitOk(['clone', localRemote(project.repository, token), check]); + expect(await readFile(join(check, 'README.md'), 'utf8')).toContain('GC Me'); + expect((await git(['fsck', '--strict'], check)).code).toBe(0); + }); +}); + +describe('public import remains unavailable in H2', () => { + it('refuses importUrl before creating a repository', async () => { + const owner = await createEmailOnlyUser(); + const res = await runtime.fetch('/api/projects', { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-test-user-id': owner }, + body: JSON.stringify({ + name: 'Import unavailable', + repoProvider: 'artifacts', + importUrl: 'https://github.com/sam-test/source.git', + }), + }); + expect(res.status).toBe(400); + expect(await res.text()).toContain('does not support importUrl'); + }); +}); + +describe('member clone credentials (POST /api/projects/:id/hosted-git/token)', () => { + it('lets the owner clone and push, and refuses a non-member', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Member Token'); + const res = await runtime.fetch(`/api/projects/${project.id}/hosted-git/token?scope=write`, { + method: 'POST', + headers: { 'x-test-user-id': owner }, + }); + const requestedAt = Date.now(); + const body = (await res.json()) as { token: string; cloneUrl: string; host: string; expiresAt: string }; + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.cloneUrl).toBe(project.repository); + // The personal credential honors the operator's ARTIFACTS_TOKEN_TTL_SECONDS (900 s here), + // like workspace and browsing credentials, rather than the one-hour default. + const lifetimeSeconds = (Date.parse(body.expiresAt) - requestedAt) / 1000; + expect(lifetimeSeconds).toBeGreaterThan(HOSTED_GIT_TEST_TOKEN_TTL_SECONDS - 60); + expect(lifetimeSeconds).toBeLessThanOrEqual(HOSTED_GIT_TEST_TOKEN_TTL_SECONDS + 1); + const work = await freshDir('member'); + await gitOk(['clone', localRemote(body.cloneUrl, body.token), work]); + await writeFile(join(work, 'human.txt'), 'from a laptop\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'human'], work); + await gitOk(['push', 'origin', 'HEAD'], work); + + // An agent sign-in session cannot mint a credential that outlives it (Codex r4637122062). + const agentSession = await runtime.fetch(`/api/projects/${project.id}/hosted-git/token?scope=read`, { + method: 'POST', + headers: { 'x-test-user-id': owner, 'x-test-agent-sign-in': '1' }, + }); + expect(agentSession.status).toBe(403); + + const stranger = await createEmailOnlyUser(); + const denied = await runtime.fetch(`/api/projects/${project.id}/hosted-git/token`, { + method: 'POST', + headers: { 'x-test-user-id': stranger }, + }); + expect([403, 404]).toContain(denied.status); + }); +}); + +describe('vertical: project creation to a workspace clone and push', () => { + it('a workspace gets a token from git-token, clones, pushes, and is refused once stopped', async () => { + const userId = await createEmailOnlyUser(); + const project = await createHostedProject(userId, 'Workspace Flow'); + const now = new Date().toISOString(); + const nodeId = 'node-hosted-git-1'; + const workspaceId = 'ws-hosted-git-1'; + await runtime.DATABASE.prepare( + `INSERT INTO nodes (id, user_id, name, status, created_at, updated_at) + VALUES (?, ?, 'node', 'running', ?, ?)` + ) + .bind(nodeId, userId, now, now) + .run(); + await runtime.DATABASE.prepare( + `INSERT INTO workspaces (id, node_id, project_id, user_id, name, repository, branch, status, vm_size, vm_location, created_at, updated_at) + VALUES (?, ?, ?, ?, 'ws', ?, ?, 'running', 'small', 'local', ?, ?)` + ) + .bind( + workspaceId, + nodeId, + project.id, + userId, + project.repository, + project.defaultBranch, + now, + now + ) + .run(); + + const callback = (await ( + await runtime.fetch('/__test/workspace-callback-token', { + method: 'POST', + body: JSON.stringify({ workspaceId }), + }) + ).json()) as { token: string }; + const res = await runtime.fetch(`/api/workspaces/${workspaceId}/git-token`, { + method: 'POST', + headers: { authorization: `Bearer ${callback.token}` }, + }); + const body = (await res.json()) as { + token: string; + cloneUrl: string; + username?: string; + }; + expect(res.status, JSON.stringify(body)).toBe(200); + // What the VM agent's credential helper needs for a host it does not know by name. + // Main's L16 response: the VM agent derives the credential host from cloneUrl. + expect(body.cloneUrl).toBe(project.repository); + expect(new URL(body.cloneUrl).host).toBe(`api.${HOSTED_GIT_TEST_BASE_DOMAIN}`); + expect(body.username).toBe('x'); + + const work = await freshDir('workspace'); + await gitOk([ + 'clone', + '--branch', + project.defaultBranch, + localRemote(body.cloneUrl, body.token), + work, + ]); + await gitOk(['checkout', '-b', 'sam/agent-work'], work); + await writeFile(join(work, 'agent.txt'), 'agent output\n'); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-m', 'agent work'], work); + await gitOk(['push', 'origin', 'sam/agent-work'], work); + + // The pushed branch is visible to a fresh reader. + const reader = await mintToken(project, 'read'); + const check = await freshDir('verify'); + await gitOk([ + 'clone', + '--branch', + 'sam/agent-work', + localRemote(project.repository, reader), + check, + ]); + expect(await readFile(join(check, 'agent.txt'), 'utf8')).toBe('agent output\n'); + + // Generation fence: a restarted runtime (rotated callback generation) retires the token. + await runtime.DATABASE.prepare( + `UPDATE workspaces SET callback_generation = 'rotated' WHERE id = ?` + ) + .bind(workspaceId) + .run(); + const retired = await git(['push', 'origin', 'sam/agent-work:refs/heads/after-rotate'], work); + expect(retired.code).not.toBe(0); + const fresh = (await ( + await runtime.fetch(`/api/workspaces/${workspaceId}/git-token`, { + method: 'POST', + headers: { + authorization: `Bearer ${ + ( + (await ( + await runtime.fetch('/__test/workspace-callback-token', { + method: 'POST', + body: JSON.stringify({ workspaceId }), + }) + ).json()) as { token: string } + ).token + }`, + }, + }) + ).json()) as { token: string }; + await gitOk(['remote', 'set-url', 'origin', localRemote(body.cloneUrl, fresh.token)], work); + await gitOk(['push', 'origin', 'sam/agent-work:refs/heads/after-rotate'], work); + + // Lifecycle fence: once the workspace stops, its token is refused. + await runtime.DATABASE.prepare(`UPDATE workspaces SET status = 'stopped' WHERE id = ?`) + .bind(workspaceId) + .run(); + const refused = await git(['push', 'origin', 'sam/agent-work:refs/heads/after-stop'], work); + expect(refused.code).not.toBe(0); + }); +}); + +describe('ref-only push admission', () => { + it('caps new refs without a pack, while permitting recovery by deleting refs', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Ref cap'); + const token = await mintToken(project, 'write'); + const work = await freshDir('ref-cap'); + await gitOk(['clone', localRemote(project.repository, token), work]); + const setting = runtime.DATABASE.prepare( + "INSERT OR REPLACE INTO platform_settings(key,value) VALUES ('repositories.maxRepoRefs',?)" + ); + try { + await setting.bind('2').run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + await gitOk(['push', 'origin', 'HEAD:refs/heads/second'], work); + // A stale deletion must not create capacity for a partially accepted mixed push. + const tip = (await gitOk(['rev-parse', 'HEAD'], work)).stdout.trim(); + const packet = (line: string) => + (Buffer.byteLength(line) + 4).toString(16).padStart(4, '0') + line; + const mixed = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}`, + 'content-type': 'application/x-git-receive-pack-request', + }, + body: + packet(`${'1'.repeat(40)} ${'0'.repeat(40)} refs/heads/second\0report-status\n`) + + packet(`${'0'.repeat(40)} ${tip} refs/heads/third\n`) + + '0000', + }); + expect(await mixed.text()).toContain('2-ref limit'); + const refs = (await gitOk(['ls-remote', 'origin'], work)).stdout; + expect(refs).toContain('refs/heads/second'); + expect(refs).not.toContain('refs/heads/third'); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/third'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain('2-ref limit'); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).not.toContain('refs/heads/third'); + await gitOk(['push', 'origin', '--delete', 'second'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/third'], work); + } finally { + await runtime.DATABASE.prepare( + "DELETE FROM platform_settings WHERE key='repositories.maxRepoRefs'" + ).run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); +}); + + +describe('Git ref-name admission through smart HTTP', () => { + it('rejects every .lock path component and accepts a similar valid ref', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Ref names'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const oid = (await gitOk(['ls-remote', remote, 'refs/heads/main'])).stdout.split(/\s+/)[0]!; + const send = async (branch: string) => (await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { method: 'POST', headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, body: buildReceivePackRequest(oid, branch, new Uint8Array()) as BodyInit })).text(); + for (const branch of ['foo.lock/bar', 'foo.lock', 'ends-dot.']) { + expect((await git(['check-ref-format', `refs/heads/${branch}`])).code).not.toBe(0); + expect(await send(branch)).toContain(`ng refs/heads/${branch} funny refname`); + } + for (const branch of ['normal', 'feature/x', 'foo.lockish/bar']) { + expect((await git(['check-ref-format', `refs/heads/${branch}`])).code).toBe(0); + expect(await send(branch)).toContain(`ok refs/heads/${branch}`); + } + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain('refs/heads/foo.lockish/bar'); + expect(refs).not.toContain('refs/heads/foo.lock/bar'); + }); +}); + +describe('repository cleanup through real SQLite', () => { + it('schedules and reclaims an ingested pack whose only ref update is rejected', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Rejected pack'); + const token = await mintToken(project, 'write'); + const info = async () => (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { objects: number }; + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + const idle = await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json(); + expect(idle).toMatchObject({ pending: '0', alarm: null }); + const before = await info(); + const { pack, commitOid } = await buildSeedPack({ projectName: 'Unreachable rejected pack' }); + const rejected = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}`, 'content-type': 'application/x-git-receive-pack-request' }, + body: buildReceivePackRequest(commitOid, 'main', pack) as BodyInit, + }); + expect(await rejected.text()).toContain('ng refs/heads/main'); + expect((await info()).objects).toBeGreaterThan(before.objects); + const queued = await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json() as { pending: string; alarm: number | null }; + expect(queued.pending).toBe('1'); expect(queued.alarm).not.toBeNull(); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect((await info()).objects).toBe(before.objects); + }); + + it('reclaims a rejected push pack even when migrating the reachable packs exceeds the budget', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'GC budget'); + const token = await mintToken(project, 'write'); + const work = await freshDir('gc-budget'); + await gitOk(['clone', localRemote(project.repository, token), work]); + // A reachable 5 MiB blob (a few KB packed) that GC would have to inflate to migrate. + await writeFile(join(work, 'big.txt'), 'b'.repeat(5 * 1024 * 1024)); + await gitOk(['add', 'big.txt'], work); + await gitOk(['commit', '-q', '-m', 'big'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/main'], work); + const info = async () => + (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { objects: number }; + const beforeRejected = await info(); + const { pack, commitOid } = await buildSeedPack({ projectName: 'Rejected under budget' }); + const rejected = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, + body: buildReceivePackRequest(commitOid, 'main', pack) as BodyInit, + }); + expect(await rejected.text()).toContain('ng refs/heads/main'); + expect((await info()).objects).toBeGreaterThan(beforeRejected.objects); + const gcStateOf = async (p: CreatedProject) => + (await (await runtime.fetch(`/__test/gc-state/${p.artifactsRepoId}`)).json()) as { pending: string }; + const setting = "INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxInflatedBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value"; + await runtime.DATABASE.prepare(setting).bind(JSON.stringify(2 * 1024 * 1024), Date.now()).run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + try { + // Migration inflates the 5 MiB blob past the 2 MiB budget and fails; the rejected pack + // was already dropped whole, without inflating anything. + const has = async (oid: string) => + ((await (await runtime.fetch(`/__test/has/${project.artifactsRepoId}/${oid}`)).json()) as { has: boolean }).has; + expect(await has(commitOid)).toBe(true); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + // GC failed on the budget (the work is retried), yet the rejected pack is gone. A failed + // migration can leave loose copies of objects it already moved, so object counts would + // not show this; the next successful GC removes those copies. + expect(await has(commitOid)).toBe(false); + expect((await gcStateOf(project)).pending).toBe('1'); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxInflatedBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + // With the default budget the rest of the cleanup completes and the repository still clones. + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect((await info()).objects).toBe(beforeRejected.objects); + const check = await freshDir('gc-budget-check'); + await gitOk(['clone', localRemote(project.repository, token), check]); + expect((await readFile(join(check, 'big.txt'), 'utf8')).length).toBe(5 * 1024 * 1024); + }); + + it('lets a packless ref deletion through a lowered push limit (Codex r4637032838)', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Delete under limit'); + const token = await mintToken(project, 'write'); + const work = await freshDir('delete-under-limit'); + await gitOk(['clone', localRemote(project.repository, token), work]); + await gitOk(['push', 'origin', 'HEAD:refs/heads/to-delete'], work); + await runtime.DATABASE.prepare( + "INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxPushBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value" + ) + .bind(JSON.stringify(1), Date.now()) + .run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + try { + await gitOk(['push', 'origin', '--delete', 'to-delete'], work); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).not.toContain('refs/heads/to-delete'); + // Control: a push that carries a pack is still held to the 1-byte limit. + await gitOk(['commit', '--allow-empty', '-q', '-m', 'blocked'], work); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/blocked'], work); + expect(refused.code).not.toBe(0); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxPushBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); + + it('refuses and drops a pack whose index overhead takes stored size past the cap (Codex r4636923076)', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Cap at final write'); + const token = await mintToken(project, 'write'); + const work = await freshDir('cap-final'); + await gitOk(['clone', localRemote(project.repository, token), work]); + // Thousands of tiny objects: the index rows dwarf the compressed pack, beyond free pages. + await mkdir(join(work, 'many'), { recursive: true }); + for (let i = 0; i < 3000; i++) await writeFile(join(work, 'many', `f${i}`), `${i} ${randomBytes(4).toString('hex')}\n`); + await gitOk(['add', 'many'], work); + await gitOk(['commit', '-q', '-m', 'noise'], work); + const commit = (await gitOk(['rev-parse', 'HEAD'], work)).stdout.trim(); + const objects = (await gitOk(['rev-list', '--objects', commit, '^HEAD~1'], work)).stdout + .split('\n') + .filter(Boolean) + .map((line) => line.split(' ')[0]!); + const pack = spawnSync('git', ['pack-objects', '--stdout'], { + cwd: work, + input: `${objects.join('\n')}\n`, + maxBuffer: 16 * 1024 * 1024, + }).stdout; + const info = async () => + (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { bytes: number }; + const send = () => + runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, + body: buildReceivePackRequest(commit, 'noise', pack) as BodyInit, + }); + const setCap = async (cap: number) => { + await runtime.DATABASE.prepare( + "INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxRepoBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value" + ) + .bind(JSON.stringify(cap), Date.now()) + .run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + }; + const before = await info(); + try { + // The raw pack fits the byte budget exactly; its index rows and pages do not. + await setCap(before.bytes + pack.length); + const refused = await (await send()).text(); + expect(refused).toContain('over its'); + expect(refused).toContain('storage limit'); + expect((await gitOk(['ls-remote', localRemote(project.repository, token)])).stdout).not.toContain( + 'refs/heads/noise' + ); + // The pack was dropped at once, not left holding bytes until GC. + expect((await info()).bytes).toBeLessThanOrEqual(before.bytes + pack.length); + // Control: with headroom for the index the same push is accepted. + await setCap(before.bytes + pack.length + 4 * 1024 * 1024); + expect(await (await send()).text()).toContain('ok refs/heads/noise'); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxRepoBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); + + it('reclaims failed-ingest pack rows before the next push quota check', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Failed ingest'); + const token = await mintToken(project, 'write'); + const work = await freshDir('failed-ingest'); + await gitOk(['clone', localRemote(project.repository, token), work]); + const before = await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json() as { bytes: number }; + // A full raw chunk is persisted before checksum validation; the remaining bytes cross quota. + const pack = randomBytes(2 * 1024 * 1024); + pack.write('PACK'); pack.writeUInt32BE(2, 4); pack.writeUInt32BE(1, 8); + const cap = before.bytes + pack.length; + await runtime.DATABASE.prepare("INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxRepoBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").bind(JSON.stringify(cap), Date.now()).run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + try { + const response = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { method: 'POST', headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, body: buildReceivePackRequest('a'.repeat(40), 'bad', pack) as BodyInit }); + expect(await response.text()).toContain('checksum mismatch'); + // No alarm or second ingest is allowed to repair the first request for this assertion. + const after = await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json() as { bytes: number }; + expect(after.bytes).toBeLessThan(cap); + await gitOk(['commit', '--allow-empty', '-m', 'safe after corrupt upload'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/recovered'], work); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).toContain('refs/heads/recovered'); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxRepoBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); + it('retains failed GC work and reclaims it on the next alarm after a transient read failure', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'GC retry'); + const token = await mintToken(project, 'write'); + const before = await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json() as { objects: number }; + const { pack, commitOid } = await buildSeedPack({ projectName: 'Unreachable retry pack' }); + await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { method: 'POST', headers: { authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}` }, body: buildReceivePackRequest(commitOid, 'main', pack) as BodyInit }); + await runtime.fetch(`/__test/alarm/${project.artifactsRepoId}/fail`, { method: 'POST' }); + const failed = await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json() as { pending: string; alarm: number | null }; + expect(failed.pending).toBe('1'); expect(failed.alarm).not.toBeNull(); + await runtime.fetch(`/__test/alarm/${project.artifactsRepoId}/run`, { method: 'POST' }); + const done = await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json(); + expect(done).toMatchObject({ pending: '0', alarm: null }); + const after = await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json() as { objects: number }; + expect(after.objects).toBe(before.objects); + await runtime.fetch(`/__test/alarm/${project.artifactsRepoId}/run`, { method: 'POST' }); + expect(await (await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`)).json()).toMatchObject({ pending: '0', alarm: null }); + }); + it('transactionally deletes a populated repository and refuses later Git requests', async () => { + const owner = await createEmailOnlyUser(); + const project = await createHostedProject(owner, 'Delete me'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + expect((await git(['ls-remote', remote])).code).toBe(0); + expect((await runtime.fetch(`/__test/repository/${project.artifactsRepoId}`, { method: 'DELETE' })).status).toBe(200); + const after = await git(['ls-remote', remote]); + expect(after.code).not.toBe(0); expect(after.stderr).toContain('410'); + expect((await runtime.fetch(`/__test/repository/${project.artifactsRepoId}`, { method: 'DELETE' })).status).toBe(200); + }); +}); + +/** + * Push connectivity admission: a ref may only move to an object whose whole closure is + * present. Each scenario builds raw packs with the git CLI, sends them through the real + * receive-pack route into the real SQLite store, and asserts on refs read back plus an + * fsck of a fresh clone. + */ +describe('push connectivity admission (closure must be complete per command)', () => { + const ZERO = '0'.repeat(40); + + function gitEnv(): NodeJS.ProcessEnv { + return { + PATH: process.env.PATH ?? '', + HOME: scratch, + GIT_CONFIG_NOSYSTEM: '1', + GIT_AUTHOR_NAME: 'Test', + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com', + }; + } + + /** A pack holding exactly `oids`, deliberately omitting anything they reference. */ + function packOf(cwd: string, oids: string[]): Buffer { + const out = spawnSync('git', ['pack-objects', '--stdout'], { + cwd, + env: gitEnv(), + input: `${oids.join('\n')}\n`, + maxBuffer: 16 * 1024 * 1024, + }); + if (out.status !== 0) throw new Error(`pack-objects failed: ${out.stderr.toString()}`); + return out.stdout; + } + + async function rev(cwd: string, spec: string): Promise { + return (await gitOk(['rev-parse', spec], cwd)).stdout.trim(); + } + + /** Commit one new uniquely named file and return the commit and its root tree. */ + async function commitFile(cwd: string, name: string): Promise<{ commit: string; tree: string }> { + await writeFile(join(cwd, name), `${name} ${randomBytes(8).toString('hex')}\n`); + await gitOk(['add', name], cwd); + await gitOk(['commit', '-m', name], cwd); + return { commit: await rev(cwd, 'HEAD'), tree: await rev(cwd, 'HEAD^{tree}') }; + } + + async function receive( + project: CreatedProject, + token: string, + commands: Array<[old: string, next: string, ref: string]>, + pack?: Uint8Array + ): Promise { + const packet = (line: string) => (Buffer.byteLength(line) + 4).toString(16).padStart(4, '0') + line; + const lines = commands.map(([old, next, ref], i) => + packet(`${old} ${next} ${ref}${i === 0 ? '\0report-status' : ''}\n`) + ); + const head = Buffer.from(lines.join('') + '0000'); + const body = pack ? Buffer.concat([head, Buffer.from(pack)]) : head; + const res = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}`, + 'content-type': 'application/x-git-receive-pack-request', + }, + body: body as unknown as BodyInit, + }); + return res.text(); + } + + async function info(project: CreatedProject): Promise<{ objects: number }> { + return (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { objects: number }; + } + + async function gcState(project: CreatedProject): Promise<{ pending: string; alarm: number | null }> { + const res = await runtime.fetch(`/__test/gc-state/${project.artifactsRepoId}`); + return (await res.json()) as { pending: string; alarm: number | null }; + } + + /** Every blob and subtree under a commit's root tree. */ + async function treeObjects(cwd: string, commit: string): Promise { + return (await gitOk(['ls-tree', '-r', '-t', commit], cwd)).stdout + .split('\n') + .filter(Boolean) + .map((line) => line.split(/\s+/)[2]!); + } + + async function reachableCache(project: CreatedProject): Promise { + const info = (await (await runtime.fetch(`/__test/info/${project.artifactsRepoId}`)).json()) as { + reachableCache: boolean; + }; + return info.reachableCache; + } + + async function assertCleanClone(remote: string): Promise { + const check = await freshDir('closure-check'); + await gitOk(['clone', remote, check]); + expect((await git(['fsck', '--strict', '--connectivity-only'], check)).code).toBe(0); + expect((await git(['fsck', '--strict'], check)).code).toBe(0); + return check; + } + + it('with a reachable cache, a failed first command does not vouch for a later command (Codex r4633317762)', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure cache attack'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-cache'); + await gitOk(['clone', remote, work]); // a full clone persists the reachable cache + expect(await reachableCache(project)).toBe(true); + + const { commit, tree } = await commitFile(work, 'attack.txt'); + // The pack carries the commit but not its tree. The first command's walk reaches the + // missing tree and fails; the second command names that same tree directly. It is a tag, + // since branches refuse non-commits before any walk, so only the walk decides it. + const out = await receive( + project, + token, + [ + [ZERO, commit, 'refs/heads/attack-commit'], + [ZERO, tree, 'refs/tags/attack-tree'], + ], + packOf(work, [commit]) + ); + expect(out).toContain('ng refs/heads/attack-commit missing necessary objects'); + expect(out).toContain('ng refs/tags/attack-tree missing necessary objects'); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain('refs/heads/main'); + expect(refs).not.toContain('attack-commit'); + expect(refs).not.toContain('attack-tree'); + expect(await reachableCache(project)).toBe(true); + await assertCleanClone(remote); + }); + + it('with a reachable cache, a valid multi-ref push whose closures overlap is accepted and extends the cache', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure cache control'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-cache-ok'); + await gitOk(['clone', remote, work]); + expect(await reachableCache(project)).toBe(true); + + const first = await commitFile(work, 'one.txt'); + const second = await commitFile(work, 'two.txt'); // child of `first` + await gitOk(['branch', 'b-one', first.commit], work); + await gitOk(['branch', 'b-two', second.commit], work); + await gitOk(['push', 'origin', 'b-one', 'b-two', 'HEAD:refs/heads/main'], work); + // A fast-forward with a valid prior cache extends it in place rather than invalidating. + expect(await reachableCache(project)).toBe(true); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain(`${first.commit}\trefs/heads/b-one`); + expect(refs).toContain(`${second.commit}\trefs/heads/b-two`); + // The next full clone is served from the extended cache, so a missing object fails fsck. + const check = await assertCleanClone(remote); + expect(await rev(check, 'origin/b-two')).toBe(second.commit); + }); + + it('without a reachable cache, a commit left by a rejected pack cannot be referenced later', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure stale pack'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-stale'); + await gitOk(['init', '-q', '-b', 'main', work]); + const orphan = await commitFile(work, 'orphan.txt'); // root commit, tree not sent + expect(await reachableCache(project)).toBe(false); + + const first = await receive(project, token, [[ZERO, orphan.commit, 'refs/heads/stale']], packOf(work, [orphan.commit])); + expect(first).toContain('ng refs/heads/stale missing necessary objects'); + // The rejected pack stays ingested until GC runs; it must not count as validated history. + const child = await commitFile(work, 'child.txt'); + const childTreeObjects = (await gitOk(['ls-tree', '-r', '-t', child.commit], work)).stdout + .split('\n') + .filter(Boolean) + .map((line) => line.split(/\s+/)[2]!) + .filter((oid) => oid !== orphan.tree); + const second = await receive( + project, + token, + [ + [ZERO, orphan.commit, 'refs/heads/reuse-orphan'], + [ZERO, child.commit, 'refs/heads/child-of-orphan'], + ], + packOf(work, [child.commit, child.tree, ...childTreeObjects]) + ); + expect(second).toContain('ng refs/heads/reuse-orphan missing necessary objects'); + expect(second).toContain('ng refs/heads/child-of-orphan missing necessary objects'); + const ref = await receive(project, token, [[ZERO, orphan.commit, 'refs/heads/ref-only']]); + expect(ref).toContain('ng refs/heads/ref-only missing necessary objects'); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain('refs/heads/main'); + expect(refs).not.toMatch(/stale|reuse-orphan|child-of-orphan|ref-only/); + expect(await reachableCache(project)).toBe(false); + await assertCleanClone(remote); + }); + + it('with a reachable cache, one failing command does not block or pollute a valid sibling', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure mixed push'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-mixed'); + await gitOk(['clone', remote, work]); + expect(await reachableCache(project)).toBe(true); + const base = await rev(work, 'HEAD'); + const valid = await commitFile(work, 'valid.txt'); + await gitOk(['checkout', '-q', '--detach', base], work); + const broken = await commitFile(work, 'broken.txt'); + const validObjects = (await gitOk(['rev-list', '--objects', valid.commit, `^${base}`], work)).stdout + .split('\n') + .filter(Boolean) + .map((line) => line.split(' ')[0]!); + const out = await receive( + project, + token, + [ + [ZERO, broken.commit, 'refs/heads/broken'], + [ZERO, valid.commit, 'refs/heads/valid'], + ], + packOf(work, [broken.commit, ...validObjects]) + ); + expect(out).toContain('ng refs/heads/broken missing necessary objects'); + expect(out).toContain('ok refs/heads/valid'); + expect(await reachableCache(project)).toBe(true); + const check = await assertCleanClone(remote); + expect(await rev(check, 'origin/valid')).toBe(valid.commit); + expect((await gitOk(['ls-remote', remote])).stdout).not.toContain('refs/heads/broken'); + }); + + it('refuses a commit that does not parse for that command only, and queues its pack for GC', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure malformed'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect(await gcState(project)).toMatchObject({ pending: '0', alarm: null }); + const work = await freshDir('closure-malformed'); + await gitOk(['init', '-q', '-b', 'main', work]); + const made = spawnSync('git', ['hash-object', '-t', 'commit', '--literally', '-w', '--stdin'], { + cwd: work, + env: gitEnv(), + input: `author ${'Test 0 +0000'}\ncommitter Test 0 +0000\n\nno tree header\n`, + }); + expect(made.status).toBe(0); + const malformed = made.stdout.toString().trim(); + const ordinary = await commitFile(work, 'ordinary.txt'); + const out = await receive( + project, + token, + [ + [ZERO, malformed, 'refs/heads/malformed'], + [ZERO, ordinary.commit, 'refs/heads/ordinary'], + ], + packOf(work, [malformed, ordinary.commit, ordinary.tree, ...(await treeObjects(work, ordinary.commit))]) + ); + expect(out).toContain('ng refs/heads/malformed missing necessary objects'); + expect(out).toContain('ok refs/heads/ordinary'); + expect((await gcState(project)).pending).toBe('1'); + await assertCleanClone(remote); + }); + + it('refuses a default branch git rejects with a 400, before any repository exists', async () => { + const userId = await createEmailOnlyUser(); + const create = (defaultBranch: string) => + runtime.fetch('/api/projects', { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-test-user-id': userId }, + body: JSON.stringify({ name: `Branch ${defaultBranch}`, repoProvider: 'artifacts', defaultBranch }), + }); + for (const branch of ['foo.lock', '.hidden', 'a..b', 'trailing.']) { + const res = await create(branch); + const body = await res.text(); + expect(res.status, `${branch}: ${body}`).toBe(400); + expect(body).toContain('not a valid git branch name'); + } + const projects = await runtime.DATABASE.prepare('SELECT count(*) AS n FROM projects WHERE user_id = ?') + .bind(userId) + .first<{ n: number }>(); + expect(projects?.n).toBe(0); + // Control: a nested branch name that passes check-ref-format creates and seeds the repository. + const ok = await create('feature/seeded'); + expect(ok.status, await ok.clone().text()).toBe(201); + const { id } = (await ok.json()) as { id: string }; + const row = await runtime.DATABASE.prepare( + 'SELECT repository, artifacts_repo_id AS repo, default_branch AS branch FROM projects WHERE id = ?' + ) + .bind(id) + .first<{ repository: string; repo: string; branch: string }>(); + expect(row?.branch).toBe('feature/seeded'); + const token = await mintToken({ artifactsRepoId: row!.repo, ownerId: userId }, 'read'); + const refs = await gitOk(['ls-remote', localRemote(row!.repository, token)]); + expect(refs.stdout).toContain('refs/heads/feature/seeded'); + }); + + it('refuses a push whose object SHA-1DC flags as a collision attack, before any ref', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Collision screen'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('collision'); + await gitOk(['clone', remote, work]); + await commitFile(work, 'collide.txt'); + const blob = await rev(work, 'HEAD:collide.txt'); + // The detector's verdict for this one object is forced (see flagCollisionOnce): a real git + // object cannot carry the published SHAttered blocks. + await runtime.fetch(`/__test/flag-collision/${project.artifactsRepoId}/${blob}`, { method: 'POST' }); + const refused = await git(['push', 'origin', 'HEAD:refs/heads/collide'], work); + expect(refused.code).not.toBe(0); + expect(refused.stderr).toContain(`object ${blob.slice(0, 12)} triggered SHA-1 collision detection`); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).not.toContain('refs/heads/collide'); + expect((await gcState(project)).pending).toBe('1'); + // Control: the same push, unflagged, is accepted, so the refusal came from the detector alone. + await gitOk(['push', 'origin', 'HEAD:refs/heads/collide'], work); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).toContain('refs/heads/collide'); + + // A delta-resolved object is screened too: git sends this edit of a large file as a thin-pack + // delta against the blob the server already has. + const big = Array.from({ length: 400 }, (_, i) => `line ${i} ${'x'.repeat(40)}`).join('\n'); + await writeFile(join(work, 'big.txt'), `${big}\n`); + await gitOk(['add', 'big.txt'], work); + await gitOk(['commit', '-m', 'big'], work); + await gitOk(['push', 'origin', 'HEAD:refs/heads/collide'], work); + await writeFile(join(work, 'big.txt'), `${big}\nappended\n`); + await gitOk(['commit', '-am', 'edit'], work); + const edited = await rev(work, 'HEAD:big.txt'); + await runtime.fetch(`/__test/flag-collision/${project.artifactsRepoId}/${edited}`, { method: 'POST' }); + const deltaRefused = await git(['push', 'origin', 'HEAD:refs/heads/collide-delta'], work); + expect(deltaRefused.code).not.toBe(0); + expect(deltaRefused.stderr).toContain(`object ${edited.slice(0, 12)} triggered SHA-1 collision detection`); + expect((await gitOk(['ls-remote', 'origin'], work)).stdout).not.toContain('refs/heads/collide-delta'); + }); + + it('queues GC for an ingested pack when validation fails before any ref decision', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure validate fault'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect(await gcState(project)).toMatchObject({ pending: '0', alarm: null }); + const before = await info(project); + const work = await freshDir('closure-fault'); + await gitOk(['init', '-q', '-b', 'main', work]); + const root = await commitFile(work, 'fault.txt'); + // The next read of this commit throws: ingest has stored the pack, the walk then faults. + await runtime.fetch(`/__test/fail-read/${project.artifactsRepoId}/${root.commit}`, { method: 'POST' }); + const res = await runtime.fetch(`/git/${project.artifactsRepoId}.git/git-receive-pack`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`x:${token}`).toString('base64')}`, + 'content-type': 'application/x-git-receive-pack-request', + }, + body: buildReceivePackRequest( + root.commit, + 'fault', + packOf(work, [root.commit, root.tree, ...(await treeObjects(work, root.commit))]) + ) as BodyInit, + }); + const text = await res.text(); + // The fault surfaced from validation, not from ingest (which would answer "unpack ..."). + expect(res.status).toBe(500); + expect(text).not.toContain('unpack'); + expect((await info(project)).objects).toBeGreaterThan(before.objects); + const queued = await gcState(project); + expect(queued.pending).toBe('1'); + expect(queued.alarm).not.toBeNull(); + expect((await gitOk(['ls-remote', remote])).stdout).not.toContain('refs/heads/fault'); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect((await info(project)).objects).toBe(before.objects); + }); + + it('keeps pushes and deletions working however large the existing ref tips are', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Large tips'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('large-tips'); + await gitOk(['clone', remote, work]); + const base = await rev(work, 'HEAD'); + // Each tip is a commit with a 5 MiB message (a few KB compressed). Objects over a quarter of + // the 16 MiB serving cache are never cached, so every read inflates it again. A push costs + // about 10 MiB of a 14 MiB decompression budget; reading the existing tips on each push + // would exceed it from the second tip on. + const message = join(work, '..', `msg-${randomBytes(4).toString('hex')}`); + await writeFile(message, 'a'.repeat(5 * 1024 * 1024)); + const setting = "INSERT INTO platform_settings (key,value,updated_at) VALUES ('repositories.maxInflatedBytes',?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value"; + await runtime.DATABASE.prepare(setting).bind(JSON.stringify(14 * 1024 * 1024), Date.now()).run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + try { + for (let i = 0; i < 4; i++) { + await gitOk(['checkout', '-q', '--detach', base], work); + await writeFile(join(work, `big-${i}.txt`), `${i}\n`); + await gitOk(['add', '.'], work); + await gitOk(['commit', '-q', '-F', message], work); + await gitOk(['push', 'origin', `HEAD:refs/heads/big-${i}`], work); + } + const small = await commitFile(work, 'small.txt'); + await gitOk(['push', 'origin', 'HEAD:refs/heads/small'], work); + await gitOk(['push', 'origin', '--delete', 'big-0'], work); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain(`${small.commit}\trefs/heads/small`); + expect(refs).toContain('refs/heads/big-3'); + expect(refs).not.toContain('refs/heads/big-0\n'); + } finally { + await runtime.DATABASE.prepare("DELETE FROM platform_settings WHERE key='repositories.maxInflatedBytes'").run(); + await runtime.fetch('/__test/invalidate-settings', { method: 'POST' }); + } + }); + + it('refuses objects of the wrong type at an edge or on a branch, and keeps clones working', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Edge types'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('edge-types'); + await gitOk(['init', '-q', '-b', 'main', work]); + const plain = await commitFile(work, 'plain.txt'); + const blob = (await gitOk(['rev-parse', `${plain.commit}:plain.txt`], work)).stdout.trim(); + const made = spawnSync('git', ['hash-object', '-t', 'commit', '--literally', '-w', '--stdin'], { + cwd: work, + env: gitEnv(), + input: `tree ${blob}\nauthor Test 0 +0000\ncommitter Test 0 +0000\n\nblob as tree\n`, + }); + expect(made.status).toBe(0); + const evil = made.stdout.toString().trim(); + const out = await receive( + project, + token, + [ + [ZERO, evil, 'refs/heads/evil'], + [ZERO, plain.tree, 'refs/heads/tree-branch'], + [ZERO, plain.tree, 'refs/tags/tree-tag'], + ], + packOf(work, [evil, blob, plain.tree]) + ); + expect(out).toContain('ng refs/heads/evil missing necessary objects'); + expect(out).toContain('ng refs/heads/tree-branch trying to write non-commit object to branch'); + expect(out).toContain('ok refs/tags/tree-tag'); + await assertCleanClone(remote); + }); + + it('refuses objects git cannot read (header order, tag headers, tree modes) and keeps clones working', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Object shapes'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('object-shapes'); + await gitOk(['init', '-q', '-b', 'main', work]); + const plain = await commitFile(work, 'plain.txt'); + const blob = (await gitOk(['rev-parse', `${plain.commit}:plain.txt`], work)).stdout.trim(); + const literal = (type: string, input: Buffer | string) => { + const out = spawnSync('git', ['hash-object', '-t', type, '--literally', '-w', '--stdin'], { cwd: work, env: gitEnv(), input }); + expect(out.status).toBe(0); + return out.stdout.toString().trim(); + }; + const sig = 'Test 0 +0000'; + const authorFirst = literal('commit', `author ${sig}\ntree ${plain.tree}\ncommitter ${sig}\n\nauthor first\n`); + const leading = literal('commit', ` junk\ntree ${plain.tree}\nauthor ${sig}\ncommitter ${sig}\n\nleading continuation\n`); + const typeFirstTag = literal('tag', `type commit\nobject ${plain.commit}\ntag odd\ntagger ${sig}\n\nodd\n`); + const badModeTree = literal('tree', Buffer.concat([Buffer.from('8 f\0'), Buffer.from(blob, 'hex')])); + const badModeCommit = literal('commit', `tree ${badModeTree}\nauthor ${sig}\ncommitter ${sig}\n\nbad mode\n`); + const out = await receive( + project, + token, + [ + [ZERO, authorFirst, 'refs/heads/author-first'], + [ZERO, leading, 'refs/heads/leading'], + [ZERO, typeFirstTag, 'refs/tags/type-first'], + [ZERO, badModeCommit, 'refs/heads/bad-mode'], + [ZERO, plain.commit, 'refs/heads/plain'], + ], + packOf(work, [authorFirst, leading, typeFirstTag, badModeTree, badModeCommit, plain.commit, plain.tree, blob]) + ); + expect(out).toContain('ng refs/heads/author-first missing necessary objects'); + expect(out).toContain('ng refs/heads/leading missing necessary objects'); + expect(out).toContain('ng refs/tags/type-first missing necessary objects'); + expect(out).toContain('ng refs/heads/bad-mode missing necessary objects'); + expect(out).toContain('ok refs/heads/plain'); + const check = await assertCleanClone(remote); + expect(await rev(check, 'origin/plain')).toBe(plain.commit); + }); + + it('treats deleting a missing ref as a no-op that queues no GC, and refuses D/F ref conflicts', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Ref no-ops'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + await runtime.fetch(`/__test/gc/${project.artifactsRepoId}`, { method: 'POST' }); + expect(await gcState(project)).toMatchObject({ pending: '0', alarm: null }); + const missing = await receive(project, token, [[ZERO, ZERO, 'refs/heads/never-existed']]); + expect(missing).toContain('ok refs/heads/never-existed'); + expect(await gcState(project)).toMatchObject({ pending: '0', alarm: null }); + + const main = (await gitOk(['ls-remote', remote, 'refs/heads/main'])).stdout.split(/\s+/)[0]!; + expect(await receive(project, token, [[ZERO, main, 'refs/heads/df']])).toContain('ok refs/heads/df'); + const nested = await receive(project, token, [ + [ZERO, main, 'refs/heads/df/x'], + [ZERO, main, 'refs/heads/dfx'], + ]); + expect(nested).toContain('ng refs/heads/df/x ref name conflicts with an existing ref'); + expect(nested).toContain('ok refs/heads/dfx'); + // A real deletion is the control: it changes refs and queues GC. + expect(await receive(project, token, [[main, ZERO, 'refs/heads/df']])).toContain('ok refs/heads/df'); + expect((await gcState(project)).pending).toBe('1'); + await assertCleanClone(remote); + }); + + it('refuses every command for a ref named twice, so a losing delete cannot free a nested name', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Duplicate ref commands'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('dup-ref'); + await gitOk(['clone', remote, work]); + const main = await rev(work, 'HEAD'); + await commitFile(work, 'next.txt'); + const next = await rev(work, 'HEAD'); + await gitOk(['push', 'origin', 'HEAD:refs/heads/next'], work); + expect(await receive(project, token, [[ZERO, main, 'refs/heads/a']])).toContain('ok refs/heads/a'); + // Update a, delete a (would lose its CAS to the update), then create a/b nested under it. + const out = await receive(project, token, [ + [main, next, 'refs/heads/a'], + [main, ZERO, 'refs/heads/a'], + [ZERO, main, 'refs/heads/a/b'], + ]); + expect(out).toContain('ng refs/heads/a multiple updates for ref not allowed'); + expect(out).toContain('ng refs/heads/a/b ref name conflicts with an existing ref'); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain(`${main}\trefs/heads/a\n`); + expect(refs).not.toContain('refs/heads/a/b'); + await assertCleanClone(remote); + }); + + it('without a reachable cache, a valid push from a shallow clone is accepted', async () => { + const project = await createHostedProject(await createEmailOnlyUser(), 'Closure shallow control'); + const token = await mintToken(project, 'write'); + const remote = localRemote(project.repository, token); + const work = await freshDir('closure-shallow'); + await gitOk(['clone', '--depth', '1', remote, work]); // not a full clone: no cache + expect(await reachableCache(project)).toBe(false); + const next = await commitFile(work, 'shallow.txt'); + await gitOk(['push', 'origin', 'HEAD:refs/heads/main', 'HEAD:refs/heads/shallow-copy'], work); + const refs = (await gitOk(['ls-remote', remote])).stdout; + expect(refs).toContain(`${next.commit}\trefs/heads/main`); + expect(refs).toContain(`${next.commit}\trefs/heads/shallow-copy`); + await assertCleanClone(remote); + }); +}); diff --git a/apps/api/tests/hosted-git/support/hosted-git-entry.ts b/apps/api/tests/hosted-git/support/hosted-git-entry.ts new file mode 100644 index 0000000000..1b51e2757c --- /dev/null +++ b/apps/api/tests/hosted-git/support/hosted-git-entry.ts @@ -0,0 +1,230 @@ +/** + * Test Worker for the hosted git conformance suite. It wires the production pieces a self-hosted + * install uses for SAM-hosted repositories: the git smart-HTTP route, the real project-create + * route (artifacts provider) and the real workspace git-token route. Only authentication of the + * browser session is replaced (an `x-test-user-id` header stands in for BetterAuth), plus two + * test-only endpoints that mint credentials the production code would mint elsewhere. + */ +// The production entry (src/index.ts, imported by the celld entry) wires repo-hosting's ports +// first; the branch list, project create and import reach them, so this entry must too. +import '../../../src/repo-hosting-wiring'; + +import { Hono } from 'hono'; + +import { handleAppError } from '../../../src/middleware/app-error-handler'; +import { registerProjectCreateRoute } from '../../../src/routes/projects/project-create'; +import { repoBrowseRoutes } from '../../../src/routes/projects/repo-browse'; +import { runtimeRoutes } from '../../../src/routes/workspaces/runtime'; +// The self-host build's own module: the class and route the generated celld entry exports and mounts. +import { HostedGitRepo, mountHostedGitRoute } from '../../../src/selfhost/hosted-git'; +import type { HostedGitEnv as Env } from '../../../src/selfhost/hosted-git/env'; +import { hostedGitTokenRoutes } from '../../../src/selfhost/hosted-git/token-route'; +import { type HostedGitScope, mintHostedGitToken } from '../../../src/selfhost/hosted-git/tokens'; +import { invalidateAdminSettings } from '../../../src/services/admin-settings-resolution'; +import { signCurrentWorkspaceCallbackToken } from '../../../src/services/jwt'; +import { Sha1Dc } from '../../../src/vendor/dgit/git/sha1'; + +/** + * Test-only: SHA-1DC reports a collision for the next object hashed to `target`. A real git + * object cannot carry a published collision (its `type size\0` header shifts the attack blocks + * off the chaining state they were built for), so this stands in for the detector's verdict; + * tests/unit/selfhost/hosted-git-sha1dc.test.ts proves the detector on the SHAttered blocks. + * The flag reaches push ingest only when it hashes through SHA-1DC: with collision detection + * off, objects hash through crypto.subtle and this hook is never consulted. + */ +function flagCollisionOnce(target: string): void { + const proto = Sha1Dc.prototype as unknown as { + digest: (this: object) => Uint8Array; + }; + const collision = Object.getOwnPropertyDescriptor(Sha1Dc.prototype, 'collision')!; + const digest = proto.digest; + const restore = () => { + proto.digest = digest; + Object.defineProperty(Sha1Dc.prototype, 'collision', collision); + }; + const flagged = new WeakSet(); + proto.digest = function (this: object) { + const out = digest.call(this); + if (Array.from(out, (b) => b.toString(16).padStart(2, '0')).join('') === target) + flagged.add(this); + return out; + }; + Object.defineProperty(Sha1Dc.prototype, 'collision', { + configurable: true, + get(this: object) { + if (!flagged.has(this)) return collision.get!.call(this) as boolean; + restore(); + return true; + }, + }); +} + +/** Test-only: run the GC alarm on demand (production schedules it 5 minutes after a push). */ +export class HostedGitRepoTest extends HostedGitRepo { + override async fetch(req: Request): Promise { + if (new URL(req.url).pathname === '/__test/gc') { + this.ctx.storage.sql.exec( + "INSERT INTO meta (key, value) VALUES ('gc-pending', '1') ON CONFLICT(key) DO UPDATE SET value = '1'" + ); + await this.alarm(); + await this.ctx.storage.deleteAlarm(); + return new Response('ok'); + } + if ( + new URL(req.url).pathname === '/__test/alarm' || + new URL(req.url).pathname === '/__test/alarm-fail' + ) { + const store = ( + this as unknown as { store: { get: (...args: unknown[]) => Promise } } + ).store; + const get = store.get; + if (new URL(req.url).pathname.endsWith('-fail')) + store.get = async () => { + throw new Error('injected transient read failure'); + }; + await this.ctx.storage.deleteAlarm(); + try { + await this.alarm(); + } finally { + store.get = get; + } + return new Response('ok'); + } + if (new URL(req.url).pathname.startsWith('/__test/fail-read/')) { + // One-shot: the next read of this object throws, as a storage fault or an exhausted work + // budget would, so a push fails after its pack was ingested but before any ref decision. + const oid = new URL(req.url).pathname.slice('/__test/fail-read/'.length); + const store = ( + this as unknown as { store: { get: (oid: string, ...rest: unknown[]) => Promise } } + ).store; + const get = store.get; + store.get = async (target: string, ...rest: unknown[]) => { + if (target !== oid) return get.call(store, target, ...rest); + store.get = get; + throw new Error('injected read failure during push validation'); + }; + return new Response('ok'); + } + if (new URL(req.url).pathname.startsWith('/__test/flag-collision/')) { + flagCollisionOnce(new URL(req.url).pathname.slice('/__test/flag-collision/'.length)); + return new Response('ok'); + } + if (new URL(req.url).pathname.startsWith('/__test/has/')) { + const oid = new URL(req.url).pathname.slice('/__test/has/'.length); + const store = (this as unknown as { store: { has: (oid: string) => boolean } }).store; + return Response.json({ has: store.has(oid) }); + } + if (new URL(req.url).pathname === '/__test/gc-state') { + return Response.json({ + pending: this.ctx.storage.sql + .exec<{ value: string }>("SELECT value FROM meta WHERE key='gc-pending'") + .toArray()[0]?.value, + alarm: await this.ctx.storage.getAlarm(), + }); + } + return super.fetch(req); + } +} + +const app = new Hono<{ Bindings: Env }>(); +app.onError(handleAppError); + +const projects = new Hono<{ Bindings: Env }>(); +projects.use('*', async (c, next) => { + const userId = c.req.header('x-test-user-id'); + if (!userId) return c.json({ error: 'UNAUTHORIZED' }, 401); + // `x-test-agent-sign-in: 1` stands in for a workload-identity agent sign-in session. + const agentSignIn = c.req.header('x-test-agent-sign-in') === '1'; + c.set( + 'auth' as never, + { + user: { id: userId, role: 'user', status: 'active' }, + session: { id: `test-session-${userId}`, agentSignIn, hardExpiresAt: null }, + } as never + ); + await next(); +}); +registerProjectCreateRoute(projects); +projects.route('/', hostedGitTokenRoutes); +projects.route('/', repoBrowseRoutes); +app.route('/api/projects', projects); +app.route('/api/workspaces', runtimeRoutes); + +// The production mount, after the other routes as in the generated celld entry. +mountHostedGitRoute(app); + +app.post('/__test/hosted-git-token', async (c) => { + const body = await c.req.json<{ + repo: string; + scope: HostedGitScope; + ttlSeconds?: number; + workspaceId?: string; + userId?: string; + callbackGeneration?: string | null; + }>(); + return c.json(await mintHostedGitToken(c.env, body)); +}); + +app.post('/__test/gc/:repo', async (c) => { + const ns = c.env.HOSTED_GIT!; + await ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/__test/gc'); + const info = await ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/info'); + return c.json(await info.json()); +}); + +app.get('/__test/info/:repo', async (c) => { + const ns = c.env.HOSTED_GIT!; + const info = await ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/info'); + return c.json(await info.json()); +}); + +app.post('/__test/workspace-callback-token', async (c) => { + const { workspaceId } = await c.req.json<{ workspaceId: string }>(); + return c.json({ token: await signCurrentWorkspaceCallbackToken(workspaceId, c.env) }); +}); + +export default app; + +app.post('/__test/invalidate-settings', (c) => { + invalidateAdminSettings(c.env); + return new Response('ok'); +}); + +app.get('/__test/gc-state/:repo', async (c) => { + const ns = c.env.HOSTED_GIT!; + return ns.get(ns.idFromName(c.req.param('repo'))).fetch('https://hosted-git/__test/gc-state'); +}); +app.delete('/__test/repository/:repo', async (c) => { + const ns = c.env.HOSTED_GIT!; + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch('https://hosted-git/', { method: 'DELETE' }); +}); + +app.get('/__test/has/:repo/:oid', (c) => { + const ns = c.env.HOSTED_GIT!; + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch(`https://hosted-git/__test/has/${c.req.param('oid')}`); +}); + +app.post('/__test/fail-read/:repo/:oid', (c) => { + const ns = c.env.HOSTED_GIT!; + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch(`https://hosted-git/__test/fail-read/${c.req.param('oid')}`); +}); + +app.post('/__test/flag-collision/:repo/:oid', (c) => { + const ns = c.env.HOSTED_GIT!; + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch(`https://hosted-git/__test/flag-collision/${c.req.param('oid')}`); +}); + +app.post('/__test/alarm/:repo/:mode', (c) => { + const ns = c.env.HOSTED_GIT!; + return ns + .get(ns.idFromName(c.req.param('repo'))) + .fetch('https://hosted-git/__test/alarm' + (c.req.param('mode') === 'fail' ? '-fail' : '')); +}); diff --git a/apps/api/tests/hosted-git/support/hosted-git-runtime.ts b/apps/api/tests/hosted-git/support/hosted-git-runtime.ts new file mode 100644 index 0000000000..a80013358d --- /dev/null +++ b/apps/api/tests/hosted-git/support/hosted-git-runtime.ts @@ -0,0 +1,122 @@ +/** + * Runs the hosted git test Worker as native workerd modules in Miniflare, listening on a local + * port, so the real `git` CLI can clone from and push to it. Real D1 (all migrations applied) + * and real Durable Object SQLite. Same approach as tests/workers/support/sam-native-runtime.ts. + */ +import { execFile } from 'node:child_process'; +import { generateKeyPairSync, randomBytes } from 'node:crypto'; +import { mkdirSync } from 'node:fs'; +import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { resolve as scratchResolve } from 'node:path'; +const tmpdir = () => { + const dir = scratchResolve(import.meta.dirname, '../../../../../.tmp'); + mkdirSync(dir, { recursive: true }); + return dir; +}; +import { dirname, resolve } from 'node:path'; +import { promisify } from 'node:util'; + +import { readD1Migrations } from '@cloudflare/vitest-pool-workers'; + +const require = createRequire(import.meta.url); +const wranglerPackage = require.resolve('wrangler/package.json'); +const wranglerBin = resolve(dirname(wranglerPackage), require(wranglerPackage).bin.wrangler); +const execute = promisify(execFile); +const { Miniflare } = createRequire(import.meta.resolve('@cloudflare/vitest-pool-workers'))( + 'miniflare' +); + +export const HOSTED_GIT_TEST_BASE_DOMAIN = 'sam.test.example'; +export const HOSTED_GIT_TEST_TOKEN_TTL_SECONDS = 900; + +export interface HostedGitRuntime { + /** e.g. http://127.0.0.1:41234 */ + origin: string; + DATABASE: D1Database; + fetch(path: string, init?: RequestInit): Promise; + close(): Promise; +} + +/** Handles the Worker's outbound fetches (e.g. an import from a fake public forge). */ +export type OutboundHandler = (request: Request) => Promise; + +export async function startHostedGitRuntime( + outbound: OutboundHandler = async () => new Response('no outbound in tests', { status: 502 }) +): Promise { + const directory = await mkdtemp(resolve(tmpdir(), 'sam-hosted-git-')); + const root = resolve(import.meta.dirname, '../../..'); + const bundleDirectory = resolve(directory, 'bundle'); + const configPath = resolve(directory, 'wrangler.json'); + await writeFile( + configPath, + JSON.stringify({ + name: 'sam-hosted-git-test', + main: resolve(root, 'tests/hosted-git/support/hosted-git-entry.ts'), + compatibility_date: '2026-01-01', + compatibility_flags: ['nodejs_compat'], + alias: { 'unicorn-magic': resolve(root, 'src/shims/unicorn-magic.ts') }, + }) + ); + await execute( + process.execPath, + [wranglerBin, 'deploy', '--dry-run', '--config', configPath, '--outdir', bundleDirectory], + { + cwd: root, + timeout: 60_000, + maxBuffer: 4_000_000, + env: { ...process.env, WRANGLER_SEND_METRICS: 'false' }, + } + ); + const files = await readdir(bundleDirectory); + const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); + const runtime = new Miniflare({ + modulesRoot: bundleDirectory, + modules: [ + { type: 'ESModule', path: resolve(bundleDirectory, 'hosted-git-entry.js') }, + ...files + .filter((name) => name.endsWith('.wasm')) + .map((name) => ({ type: 'CompiledWasm', path: resolve(bundleDirectory, name) })), + ], + compatibilityDate: '2026-01-01', + compatibilityFlags: ['nodejs_compat'], + host: '127.0.0.1', + port: 0, + durableObjects: { HOSTED_GIT: { className: 'HostedGitRepoTest', useSQLite: true } }, + d1Databases: ['DATABASE', 'OBSERVABILITY_DATABASE'], + kvNamespaces: ['KV'], + outboundService: (request: Request) => outbound(request), + bindings: { + BASE_DOMAIN: HOSTED_GIT_TEST_BASE_DOMAIN, + // Generated per runtime so no key material is checked in. + ENCRYPTION_KEY: randomBytes(32).toString('base64'), + ARTIFACTS_ENABLED: 'true', + HOSTED_GIT_BACKEND: 'durable-object', + // Non-default, so tests can see every credential route honor the operator's lifetime. + ARTIFACTS_TOKEN_TTL_SECONDS: String(HOSTED_GIT_TEST_TOKEN_TTL_SECONDS), + JWT_PRIVATE_KEY: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), + JWT_PUBLIC_KEY: publicKey.export({ type: 'spki', format: 'pem' }).toString(), + }, + }); + const cleanup = async () => { + await runtime.dispose().catch(() => undefined); + await rm(directory, { recursive: true, force: true }); + }; + try { + const url: URL = await runtime.ready; + const database = (await runtime.getD1Database('DATABASE')) as D1Database; + for (const migration of await readD1Migrations(resolve(root, 'src/db/migrations'))) { + await database.batch(migration.queries.map((query) => database.prepare(query))); + } + const origin = url.origin; + return { + origin, + DATABASE: database, + fetch: (path, init) => fetch(`${origin}${path}`, init), + close: cleanup, + }; + } catch (error) { + await cleanup(); + throw error; + } +} diff --git a/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts b/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts new file mode 100644 index 0000000000..0ba9220f6f --- /dev/null +++ b/apps/api/tests/unit/durable-objects/hosted-git-ls-refs.test.ts @@ -0,0 +1,105 @@ +/** + * `ref-prefix` for protocol v2 ls-refs on SAM-hosted repositories (hosted-git-ls-refs.ts): the + * vendored dgit server ignores it, so "HEAD" came back for `refs/heads/` (box round R13 D11). + * The conformance suite drives the same filter through the real Durable Object and git. + */ +import { describe, expect, it } from 'vitest'; + +import { + filterLsRefsResponse, + lsRefsPrefixes, +} from '../../../src/selfhost/hosted-git/hosted-git-ls-refs'; +import { FLUSH, pkt, PktParser } from '../../../src/vendor/dgit/git/pktline'; +import { concat } from '../../../src/vendor/dgit/git/util'; + +const A = 'a'.repeat(40); +const B = 'b'.repeat(40); +const DELIM = new TextEncoder().encode('0001'); + +function lsRefsRequest(...args: string[]): Uint8Array { + return concat([ + pkt('command=ls-refs\n'), + pkt('agent=git/2.45\n'), + DELIM, + ...args.map((a) => pkt(`${a}\n`)), + FLUSH, + ]); +} + +function lines(body: Uint8Array): string[] { + const parser = new PktParser(body); + const out: string[] = []; + for (let p = parser.read(); p !== null; p = parser.read()) { + out.push(p.kind === 'line' ? p.text : p.kind); + } + return out; +} + +const answer = () => + new Response( + concat([ + pkt(`${A} HEAD symref-target:refs/heads/main\n`), + pkt(`${A} refs/heads/main\n`), + pkt(`${B} refs/heads/feature/x\n`), + pkt(`${B} refs/tags/v1 peeled:${A}\n`), + FLUSH, + ]), + { headers: { 'content-type': 'application/x-git-upload-pack-result' } } + ); + +describe('ls-refs ref-prefix', () => { + it('reads the prefixes of an ls-refs request, and none from other requests', () => { + expect(lsRefsPrefixes(lsRefsRequest('symrefs', 'ref-prefix refs/heads/'))).toEqual([ + 'refs/heads/', + ]); + expect(lsRefsPrefixes(lsRefsRequest('ref-prefix HEAD', 'ref-prefix refs/tags/'))).toEqual([ + 'HEAD', + 'refs/tags/', + ]); + // No prefix: every ref, as the protocol says. + expect(lsRefsPrefixes(lsRefsRequest('symrefs'))).toBeNull(); + const fetch = concat([pkt('command=fetch\n'), DELIM, pkt(`want ${A}\n`), FLUSH]); + expect(lsRefsPrefixes(fetch)).toBeNull(); + }); + + it('refs/heads/ keeps the branches only: no HEAD, no tags', async () => { + const filtered = await filterLsRefsResponse(answer(), ['refs/heads/']); + expect(lines(new Uint8Array(await filtered.arrayBuffer()))).toEqual([ + `${A} refs/heads/main`, + `${B} refs/heads/feature/x`, + 'flush', + ]); + expect(filtered.headers.get('content-type')).toBe('application/x-git-upload-pack-result'); + }); + + it('keeps attributes and every matching prefix (HEAD with its symref, peeled tags)', async () => { + const filtered = await filterLsRefsResponse(answer(), ['HEAD', 'refs/tags/']); + expect(lines(new Uint8Array(await filtered.arrayBuffer()))).toEqual([ + `${A} HEAD symref-target:refs/heads/main`, + `${B} refs/tags/v1 peeled:${A}`, + 'flush', + ]); + }); +}); + +it('rejects an oversized advertisement with a readable response', async () => { + const response = await filterLsRefsResponse(new Response(new Uint8Array(16 * 1024 * 1024 + 1)), [ + 'refs/heads/', + ]); + expect(response.status).toBe(413); + expect(await response.text()).toContain('advertisement exceeds'); +}); + +describe('ls-refs ref-prefix count bound (Codex r4636317748)', () => { + it('honors up to the bound and answers unfiltered past it, as git does', async () => { + const { MAX_LS_REFS_PREFIXES } = + await import('../../../src/selfhost/hosted-git/hosted-git-ls-refs'); + const prefixes = (n: number) => + Array.from({ length: n }, (_, i) => `ref-prefix refs/heads/p${i}/`); + expect(lsRefsPrefixes(lsRefsRequest(...prefixes(MAX_LS_REFS_PREFIXES)))).toHaveLength( + MAX_LS_REFS_PREFIXES + ); + // One more and the filter is skipped, so its cost is bounded by the cap, not the request size. + expect(lsRefsPrefixes(lsRefsRequest(...prefixes(MAX_LS_REFS_PREFIXES + 1)))).toBeNull(); + }); +}); diff --git a/apps/api/tests/unit/lib/git-ref-name.test.ts b/apps/api/tests/unit/lib/git-ref-name.test.ts new file mode 100644 index 0000000000..9813048d2f --- /dev/null +++ b/apps/api/tests/unit/lib/git-ref-name.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; + +import { isValidGitBranchName, isValidGitRefName } from '../../../src/lib/git-ref-name'; + +describe('git ref-name admission', () => { + it.each(['main', 'feature/x', 'sam/fix-123', 'release-2026.11', 'v1.0/hotfix', 'a.b'])( + 'accepts branch %s', + (branch) => { + expect(isValidGitBranchName(branch)).toBe(true); + } + ); + + it.each([ + ['foo.lock', 'a .lock component'], + ['dir.lock/x', 'an intermediate .lock component'], + ['.hidden', 'a component starting with a dot'], + ['x/.hidden', 'a later component starting with a dot'], + ['a..b', 'two consecutive dots'], + ['trailing.', 'a trailing dot'], + ['trailing/', 'a trailing slash'], + ['a//b', 'an empty component'], + ['a@{b', 'the @{ sequence'], + ['has space', 'whitespace'], + ['a~b', 'a check-ref-format metacharacter'], + ['', 'an empty name'], + ['x'.repeat(250), 'more than 255 characters as a full ref'], + ])('rejects %j (%s)', (branch) => { + expect(isValidGitBranchName(branch)).toBe(false); + }); + + it('requires a full ref under refs/', () => { + expect(isValidGitRefName('refs/heads/main')).toBe(true); + expect(isValidGitRefName('heads/main')).toBe(false); + }); +}); diff --git a/apps/api/tests/unit/routes/artifacts-config.test.ts b/apps/api/tests/unit/routes/artifacts-config.test.ts index 1ac9911dd9..b48e703be4 100644 --- a/apps/api/tests/unit/routes/artifacts-config.test.ts +++ b/apps/api/tests/unit/routes/artifacts-config.test.ts @@ -13,7 +13,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import type { Env } from '../../../src/env'; import { artifactsConfigRoutes } from '../../../src/routes/artifacts-config'; -import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; +import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; const app = new Hono<{ Bindings: Env }>(); app.route('/api/config', artifactsConfigRoutes); diff --git a/apps/api/tests/unit/routes/project-artifacts-creation.test.ts b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts index db8dd78d23..ade1f18b52 100644 --- a/apps/api/tests/unit/routes/project-artifacts-creation.test.ts +++ b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; import { AppError } from '../../../src/middleware/error'; import { registerProjectCreateRoute } from '../../../src/routes/projects/project-create'; -import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; +import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; /** * The Artifacts branch of `POST /api/projects` resolves its backend through @@ -131,6 +131,22 @@ describe('POST /api/projects — Artifacts provider through the hosted-git seam' expect(insertedRows[0]).toMatchObject({ repoProvider: 'artifacts', repository: remote }); }); + it('does not probe optional extension methods on a native RPC binding', async () => { + const remote = 'https://acct.artifacts.cloudflare.net/git/default/hosted-project-r1.git'; + const binding = new Proxy(backend(remote), { get(target, property, receiver) { + if (!(property in target)) return vi.fn().mockRejectedValue(new Error('Unknown RPC method')); + return Reflect.get(target, property, receiver); + } }); + limitResponses.push([], [{ id: 'x', repository: remote }]); + mocks.seedArtifactsReadme.mockImplementationOnce(async (options) => { + if (options.fetchImpl) await options.fetchImpl(options.remote); + }); + const response = await createArtifactsProject({ ...mockEnv, ARTIFACTS_ENABLED: 'true', ARTIFACTS: binding } as Env); + expect(response.status).toBe(201); + expect(binding.create).toHaveBeenCalledOnce(); + expect(mocks.seedArtifactsReadme).toHaveBeenCalledWith(expect.objectContaining({ fetchImpl: undefined })); + }); + it('creates the repository with a registered self-host backend when no binding exists', async () => { const remote = 'https://api.sam.example/git/hosted-project-r1.git'; const hosted = backend(remote); diff --git a/apps/api/tests/unit/routes/project-delete.test.ts b/apps/api/tests/unit/routes/project-delete.test.ts index 4958096502..cb52d6f248 100644 --- a/apps/api/tests/unit/routes/project-delete.test.ts +++ b/apps/api/tests/unit/routes/project-delete.test.ts @@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; import { projectsRoutes } from '../../../src/routes/projects'; -import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; +import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; const mocks = vi.hoisted(() => ({ requireProjectCapability: vi.fn(), diff --git a/apps/api/tests/unit/routes/workspace-git-token.test.ts b/apps/api/tests/unit/routes/workspace-git-token.test.ts index c20c399168..f7d0f97cea 100644 --- a/apps/api/tests/unit/routes/workspace-git-token.test.ts +++ b/apps/api/tests/unit/routes/workspace-git-token.test.ts @@ -4,9 +4,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; import { runtimeRoutes } from '../../../src/routes/workspaces/runtime'; +import { registerArtifactsBackendFallback } from '../../../src/services/artifacts/backend'; import { getInstallationToken } from '../../../src/services/github-app'; import { GitHubCliPolicyError } from '../../../src/services/github-cli-policy'; -import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; const mocks = vi.hoisted(() => ({ getInstallationToken: vi.fn(), diff --git a/apps/api/tests/unit/selfhost/hosted-git-body.test.ts b/apps/api/tests/unit/selfhost/hosted-git-body.test.ts new file mode 100644 index 0000000000..014bbe964a --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-body.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; + +import { ChunkBuffer } from '../../../src/selfhost/hosted-git/hosted-git-body'; + +describe('ChunkBuffer (Codex r4636751965)', () => { + it('copies O(total) bytes when a 1 MiB command section arrives one byte at a time', () => { + const total = 1024 * 1024; + const buffer = new ChunkBuffer(); + const one = new Uint8Array([0x41]); + for (let i = 0; i < total; i++) buffer.append(one); + expect(buffer.length).toBe(total); + expect(buffer.view(total - 1)).toEqual(one); + // Re-copying everything read so far on each chunk would be ~total^2 / 2 (5.5e11) bytes. + expect(buffer.copied).toBeLessThan(4 * total); + }); + + it('keeps an initial body and clamps views to what has been read', () => { + const buffer = new ChunkBuffer(new Uint8Array([1, 2, 3])); + buffer.append(new Uint8Array([4, 5])); + expect([...buffer.view()]).toEqual([1, 2, 3, 4, 5]); + expect([...buffer.view(3, 99)]).toEqual([4, 5]); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts b/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts new file mode 100644 index 0000000000..6a9f49e34f --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-budget.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { + chargeGitWork, + readGitChunk, + withGitWorkBudget, +} from '../../../src/vendor/dgit/git/budget'; +import { applyDelta } from '../../../src/vendor/dgit/git/pack'; +import { deflate, inflate } from '../../../src/vendor/dgit/git/zlib'; + +const limits = { maxObjectBytes: 32, maxInflatedBytes: 48, maxDeltaDepth: 2, workTimeoutMs: 1000 }; + +describe('hosted git work budget', () => { + it('bounds loose-object reads after garbage collection and charges repeated inflations', () => { + const small = deflate(new Uint8Array(24)); + const large = deflate(new Uint8Array(33)); + withGitWorkBudget(limits, () => { + expect(() => inflate(large)).toThrow('inflated size limit'); + expect(inflate(small)).toHaveLength(24); + expect(inflate(small)).toHaveLength(24); + expect(() => inflate(small)).toThrow('decompression budget'); + }); + }); + + it('rejects a delta target before allocation, while a valid delta works', () => { + withGitWorkBudget(limits, () => { + expect(() => applyDelta(new Uint8Array(), new Uint8Array([0, 33]))).toThrow( + 'inflated size limit' + ); + expect(applyDelta(new Uint8Array(), new Uint8Array([0, 1, 1, 65]))).toEqual( + new Uint8Array([65]) + ); + }); + }); + + it('charges cumulative decompression and isolates concurrent requests', async () => { + await Promise.all( + [1, 2].map(() => + withGitWorkBudget(limits, async () => { + chargeGitWork(32); + await Promise.resolve(); + chargeGitWork(16); + expect(() => chargeGitWork(1)).toThrow('decompression budget'); + }) + ) + ); + }); + + it('checks the deadline during CPU work', () => { + vi.useFakeTimers(); + try { + withGitWorkBudget(limits, () => { + chargeGitWork(1); + vi.advanceTimersByTime(1000); + expect(() => chargeGitWork(1)).toThrow('time budget'); + }); + } finally { + vi.useRealTimers(); + } + }); + + it('cancels a stalled upload instead of retaining the receive lock', async () => { + vi.useFakeTimers(); + const cancel = vi.fn(); + try { + const reader = new ReadableStream({ cancel }).getReader(); + const result = withGitWorkBudget(limits, () => readGitChunk(reader)); + const rejected = expect(result).rejects.toThrow('time budget'); + await vi.advanceTimersByTimeAsync(1000); + await rejected; + expect(cancel).toHaveBeenCalledOnce(); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-closure-walk.test.ts b/apps/api/tests/unit/selfhost/hosted-git-closure-walk.test.ts new file mode 100644 index 0000000000..50d1505f6e --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-closure-walk.test.ts @@ -0,0 +1,137 @@ +import { createHash } from 'node:crypto'; + +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +import { withGitWorkBudget } from '../../../src/vendor/dgit/git/budget'; +import { validatePush } from '../../../src/vendor/dgit/git/protocol'; +import type { GitStore } from '../../../src/vendor/dgit/git/store'; + +/** + * The connectivity walk's per-push failure memo, counted at the object-store boundary. + * The real-git suite (tests/hosted-git) proves admission end to end; these tests drive + * validatePush past every count in the path (rule 81) and measure how much it reads. + */ +const ZERO = '0'.repeat(40); +const oidOf = (label: string) => createHash('sha1').update(label).digest('hex'); +const enc = new TextEncoder(); +const SIG = 'Test 0 +0000'; + +type Obj = { type: 'commit' | 'tree' | 'blob' | 'tag'; data: Uint8Array }; + +/** A fake object store over a map, counting every presence probe and object read. */ +function fakeStore(objects: Map) { + const counts = { probes: 0, reads: 0 }; + const store = { + getMeta: () => null, + reachableVersion: () => 'v', + refs: () => [], + resolveHead: () => null, + getRef: () => null, + getPeeled: () => null, + typeAndSize: (oid: string) => { + counts.probes += 1; + const obj = objects.get(oid); + return obj ? { type: obj.type, size: obj.data.length } : null; + }, + get: async (oid: string) => { + counts.reads += 1; + return objects.get(oid) ?? null; + }, + } as unknown as GitStore; + return { store, counts }; +} + +/** + * A linear history c1..cN sharing one tree. `missingTree` points the ROOT commit at an absent + * tree, so a walk from the tip must cross the whole history before it fails. + */ +function chain( + length: number, + opts: { missingTree?: boolean; brokenRoot?: boolean; label?: string } = {} +) { + const objects = new Map(); + const blob = oidOf('blob'); + objects.set(blob, { type: 'blob', data: enc.encode('hello\n') }); + const tree = oidOf('tree'); + const entry = new Uint8Array([...enc.encode('100644 a.txt\0'), ...Buffer.from(blob, 'hex')]); + objects.set(tree, { type: 'tree', data: entry }); + const commits: string[] = []; + for (let i = 1; i <= length; i++) { + const oid = oidOf(`${opts.label ?? 'commit'}-${i}`); + const parent = commits.length ? `parent ${commits[commits.length - 1]}\n` : ''; + const rootTree = i === 1 && opts.missingTree ? oidOf('absent-tree') : tree; + const header = i === 1 && opts.brokenRoot ? '' : `tree ${rootTree}\n`; + const text = `${header}${parent}author ${SIG}\ncommitter ${SIG}\n\nc${i}\n`; + objects.set(oid, { type: 'commit', data: enc.encode(text) }); + commits.push(oid); + } + return { objects, commits }; +} + +async function decide(store: GitStore, commands: { old: string; next: string; ref: string }[]) { + return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => validatePush(store, commands, null)); +} + +const N = 1201; // history longer than any internal batch, not a multiple of 2 +const K = 2001; // commands, more than the commit count + +describe('validatePush closure walk', () => { + it('rejects many commands at one broken tip after walking the history once', async () => { + const { objects, commits } = chain(N, { missingTree: true }); + const { store, counts } = fakeStore(objects); + const tip = commits[commits.length - 1]!; + const commands = Array.from({ length: K }, (_, i) => ({ + old: ZERO, + next: tip, + ref: `refs/heads/b${i}`, + })); + const plan = await decide(store, commands); + expect(plan.decisions).toHaveLength(K); + for (const d of plan.decisions) expect(d.reject).toBe('missing necessary objects'); + // One full walk (N commits, a type probe for each commit's edge to the shared tree, the + // tree and blob, the absent tree) plus one branch type probe per command; every later + // command stops at its tip, which that walk recorded as failed. Unmemoized: about K x N. + expect(counts.probes).toBeLessThanOrEqual(2 * N + 3 + K); + expect(counts.reads).toBeLessThanOrEqual(N + 1); + }); + + it('rejects commands at every commit of a broken history without re-walking it', async () => { + const { objects, commits } = chain(N, { missingTree: true }); + const { store, counts } = fakeStore(objects); + // Oldest first: each tip's walk reaches its parent, which an earlier command proved broken. + // Unmemoized, command i re-walks i commits: about N^2 / 2 reads. + const commands = commits.map((next, i) => ({ old: ZERO, next, ref: `refs/heads/c${i}` })); + const plan = await decide(store, commands); + for (const d of plan.decisions) expect(d.reject).toBe('missing necessary objects'); + expect(counts.probes).toBeLessThanOrEqual(5 * N); + expect(counts.reads).toBeLessThanOrEqual(2 * N); + }); + + it('rejects a commit that does not parse instead of failing the whole push', async () => { + const { objects, commits } = chain(3, { brokenRoot: true }); + const good = chain(2, { label: 'good' }); + for (const [oid, obj] of good.objects) objects.set(oid, obj); + const { store } = fakeStore(objects); + const plan = await decide(store, [ + { old: ZERO, next: commits[2]!, ref: 'refs/heads/broken' }, + { old: ZERO, next: good.commits[1]!, ref: 'refs/heads/good' }, + ]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + expect(plan.decisions[1]).toMatchObject({ set: good.commits[1] }); + }); + + it('accepts a complete history and every commit in it (positive control)', async () => { + const { objects, commits } = chain(N); + const { store, counts } = fakeStore(objects); + const commands = [...commits] + .reverse() + .map((next, i) => ({ old: ZERO, next, ref: `refs/heads/ok${i}` })); + const plan = await decide(store, commands); + for (const [i, d] of plan.decisions.entries()) + expect(d).toMatchObject({ set: commands[i]!.next }); + // The first command proves the whole history; later commands stop at their own tip. + expect(counts.reads).toBeLessThanOrEqual(N + 1); + expect(plan.known.hasHex(commits[0]!)).toBe(true); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts b/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts new file mode 100644 index 0000000000..eab33d8cde --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-deletion.test.ts @@ -0,0 +1,167 @@ +import { beforeEach, expect, it, vi } from 'vitest'; + +import { HostedGitRepo } from '../../../src/selfhost/hosted-git/hosted-git-repo'; +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +const state = vi.hoisted(() => ({ + meta: new Map(), + events: [] as string[], + validate: vi.fn(), + setAlarm: vi.fn(async () => undefined), + getAlarm: vi.fn(async () => null), + cancel: vi.fn(), + deleteAlarm: vi.fn(async () => undefined), +})); +vi.mock('cloudflare:workers', () => ({ + DurableObject: class { + constructor(public ctx: unknown) {} + }, +})); +vi.mock('../../../src/selfhost/hosted-git/policy', () => ({ + resolveHostedGitLimits: async () => DEFAULT_HOSTED_GIT_LIMITS, +})); +vi.mock('../../../src/vendor/dgit/git/store', () => ({ + GitStore: class { + getMeta(key: string) { + return state.meta.get(key); + } + setMeta(key: string, value: string) { + state.meta.set(key, value); + } + refs() { + return []; + } + dbSize() { + return 0; + } + objectCount() { + return 0; + } + wipe() { + state.events.push('wipe'); + state.meta.clear(); + } + packs = { ingest: async () => ({ packId: 1 }) }; + }, +})); +vi.mock('../../../src/vendor/dgit/git/protocol', () => ({ + advertisement: () => new Uint8Array(), + parsePushCommands: () => ({ commands: [], caps: [] }), + sidebandFrames: () => [], + renderStatus: () => new Uint8Array(), + validatePush: (...args: unknown[]) => state.validate(...args), + commitPush: () => { + state.events.push('commit'); + return { results: [], changed: false, needsGc: false }; + }, + uploadPack: async (_store: unknown, _body: unknown, release: () => void) => + new Response( + new ReadableStream({ + pull(controller) { + controller.enqueue(new Uint8Array(1024)); + }, + cancel() { + state.cancel(); + release(); + }, + }) + ), +})); +function repo() { + return new HostedGitRepo( + { + storage: { + sql: {}, + deleteAlarm: state.deleteAlarm, + setAlarm: state.setAlarm, + getAlarm: state.getAlarm, + transactionSync: (fn: () => unknown) => fn(), + }, + blockConcurrencyWhile: async (fn: () => Promise) => fn(), + } as unknown as DurableObjectState, + {} + ); +} +beforeEach(() => { + vi.clearAllMocks(); + state.meta.clear(); + state.events = []; + state.validate.mockResolvedValue({}); +}); +it('DELETE waits for an accepted push, then fences new writes and persists deletion', async () => { + let resume = () => {}; + state.validate.mockImplementationOnce( + () => + new Promise((resolve) => { + resume = () => resolve({}); + }) + ); + const cell = repo(); + const push = cell.fetch( + new Request('https://git/git-receive-pack', { method: 'POST', body: '0000' }) + ); + await vi.waitFor(() => expect(state.validate).toHaveBeenCalledOnce()); + const deletion = cell.fetch(new Request('https://git/', { method: 'DELETE' })); + await vi.waitFor(async () => + expect( + (await cell.fetch(new Request('https://git/init', { method: 'PUT', body: '{}' }))).status + ).toBe(410) + ); + expect(state.events).toEqual([]); + resume(); + expect((await push).status).toBe(200); + expect((await deletion).status).toBe(200); + expect(state.events).toEqual(['commit', 'wipe']); + expect( + (await repo().fetch(new Request('https://git/init', { method: 'PUT', body: '{}' }))).status + ).toBe(410); +}); +it('DELETE cancels an active clone stream before wiping its packs', async () => { + const cell = repo(); + const upload = await cell.fetch( + new Request('https://git/git-upload-pack', { method: 'POST', body: '0000' }) + ); + expect((await cell.fetch(new Request('https://git/', { method: 'DELETE' }))).status).toBe(200); + expect(state.cancel).toHaveBeenCalledOnce(); + expect(state.events).toEqual(['wipe']); + await upload.body?.cancel(); +}); +it('schedules collection for an ingested pack even when all ref updates are rejected', async () => { + const cell = repo(); + expect( + ( + await cell.fetch( + new Request('https://git/git-receive-pack', { + method: 'POST', + body: new Uint8Array([48, 48, 48, 48, 80, 65, 67, 75, 0, 0, 0, 2, 0, 0, 0, 0]), + }) + ) + ).status + ).toBe(200); + expect(state.setAlarm).toHaveBeenCalledOnce(); + expect(state.meta.get('gc-pending')).toBe('1'); +}); + +it('retries failed cleanup while keeping all writes fenced', async () => { + state.deleteAlarm.mockRejectedValueOnce(new Error('temporary storage failure')); + const cell = repo(); + expect((await cell.fetch(new Request('https://git/', { method: 'DELETE' }))).status).toBe(500); + expect( + (await cell.fetch(new Request('https://git/init', { method: 'PUT', body: '{}' }))).status + ).toBe(410); + expect((await cell.fetch(new Request('https://git/', { method: 'DELETE' }))).status).toBe(200); + expect(state.deleteAlarm).toHaveBeenCalledTimes(2); + expect(state.meta.get('deleted')).toBe('1'); +}); + +it('reclaims failed-ingest rows even when scheduling the cleanup alarm fails', async () => { + const cell = repo(); + const events: string[] = []; + const packs = (cell as unknown as { store: { packs: { ingest: () => Promise; cleanupOrphans: () => Promise } } }).store.packs; + packs.ingest = async () => { events.push('ingest'); throw new Error('pack checksum mismatch'); }; + packs.cleanupOrphans = async () => { events.push('cleanup'); }; + state.setAlarm.mockImplementationOnce(async () => { events.push('alarm'); throw new Error('alarm storage unavailable'); }); + const response = await cell.fetch(new Request('https://git/git-receive-pack', { method: 'POST', body: new Uint8Array([48, 48, 48, 48, 80, 65, 67, 75, 0, 0, 0, 2, 0, 0, 0, 0]) })); + expect(response.status).toBe(500); + expect(events).toEqual(['ingest', 'cleanup', 'alarm']); + expect(state.meta.get('gc-pending')).toBe('1'); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts new file mode 100644 index 0000000000..0cb673b9ce --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-gc-admission.test.ts @@ -0,0 +1,98 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { HostedGitRepo } from '../../../src/selfhost/hosted-git/hosted-git-repo'; +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +const mocks = vi.hoisted(() => ({ + pending: '1', + attempts: '0', + gc: vi.fn(async () => ({ removed: 1, kept: 2 })), + setAlarm: vi.fn(async () => undefined), + getAlarm: vi.fn(async () => null), +})); +vi.mock('cloudflare:workers', () => ({ + DurableObject: class { + constructor( + public ctx: unknown, + public env: unknown + ) {} + }, +})); +vi.mock('../../../src/selfhost/hosted-git/policy', () => ({ + resolveHostedGitLimits: async () => DEFAULT_HOSTED_GIT_LIMITS, +})); +vi.mock('../../../src/vendor/dgit/git/store', () => ({ + GitStore: class { + packs = { cleanupOrphans: async () => undefined }; + getMeta(key: string) { + return key === 'gc-attempts' ? mocks.attempts : mocks.pending; + } + setMeta(key: string, value: string) { + if (key === 'gc-attempts') mocks.attempts = value; + else mocks.pending = value; + } + }, +})); +vi.mock('../../../src/selfhost/hosted-git/hosted-git-gc', async (importOriginal) => ({ + ...(await importOriginal()), + runHostedGitGc: mocks.gc, +})); +beforeEach(() => { + mocks.pending = '1'; + mocks.attempts = '0'; + mocks.gc.mockReset().mockResolvedValue({ removed: 1, kept: 2 }); + vi.clearAllMocks(); +}); +describe('hosted git GC admission', () => { + it('rechecks uploads after waiting behind a push, and runs once after the upload leaves', async () => { + const ctx = { + storage: { setAlarm: mocks.setAlarm, getAlarm: mocks.getAlarm }, + blockConcurrencyWhile: async (action: () => Promise) => action(), + }; + const repo = new HostedGitRepo(ctx as unknown as DurableObjectState, {}); + // Hold the same promise-chain slot that receive-pack owns, exercising alarm's real queue. + let releasePush = () => {}; + const state = repo as unknown as { receiveChain: Promise; activeUploads: number }; + state.receiveChain = new Promise((resolve) => { + releasePush = resolve; + }); + const alarm = repo.alarm(); + await Promise.resolve(); + await Promise.resolve(); + state.activeUploads = 1; + releasePush(); + await alarm; + expect(mocks.gc).not.toHaveBeenCalled(); + expect(mocks.pending).toBe('1'); + expect(mocks.setAlarm).toHaveBeenCalledOnce(); + state.activeUploads = 0; + await repo.alarm(); + expect(mocks.gc).toHaveBeenCalledOnce(); + expect(mocks.pending).toBe('0'); + await repo.alarm(); + expect(mocks.gc).toHaveBeenCalledOnce(); + }); + it('retries a transient failed sweep and resets its attempt budget after success', async () => { + const ctx = { storage: { setAlarm: mocks.setAlarm, getAlarm: mocks.getAlarm }, blockConcurrencyWhile: async (fn: () => Promise) => fn() }; + const repo = new HostedGitRepo(ctx as unknown as DurableObjectState, {}); + for (let cycle = 0; cycle < 4; cycle++) { + mocks.pending = '1'; + mocks.gc.mockRejectedValueOnce(new Error('transient read failure')); + await repo.alarm(); + expect(mocks.pending).toBe('1'); expect(mocks.attempts).toBe('1'); + expect(mocks.setAlarm).toHaveBeenCalledTimes(cycle + 1); + await repo.alarm(); + expect(mocks.pending).toBe('0'); expect(mocks.attempts).toBe('0'); + } + const calls = mocks.gc.mock.calls.length; + await repo.alarm(); expect(mocks.gc).toHaveBeenCalledTimes(calls); + }); + it('stops automatic retries after the configured consecutive failure budget', async () => { + const repo = new HostedGitRepo({ storage: { setAlarm: mocks.setAlarm, getAlarm: mocks.getAlarm }, blockConcurrencyWhile: async (fn: () => Promise) => fn() } as unknown as DurableObjectState, {}); + mocks.gc.mockRejectedValue(new Error('permanent failure')); + for (let tick = 0; tick < 5; tick++) await repo.alarm(); + expect(mocks.gc).toHaveBeenCalledTimes(3); + expect(mocks.setAlarm).toHaveBeenCalledTimes(2); + expect(mocks.pending).toBe('failed'); + }); + +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts new file mode 100644 index 0000000000..667c6dcfa8 --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-push-admission.test.ts @@ -0,0 +1,810 @@ +import { createHash } from 'node:crypto'; + +import { describe, expect, it, vi } from 'vitest'; + +import { armHostedGitGcAlarm, GC_DELAY_MS } from '../../../src/selfhost/hosted-git/hosted-git-gc'; +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +import { withGitWorkBudget } from '../../../src/vendor/dgit/git/budget'; +import { commitPush, validatePush } from '../../../src/vendor/dgit/git/protocol'; +import type { GitStore } from '../../../src/vendor/dgit/git/store'; + +/** + * Push admission guards from the adversarial review of PR #2907, at the store boundary: + * ref seeding reads no objects, every walked edge has the type git requires, branches hold + * only commits, directory/file ref conflicts are refused, and deleting a missing ref is a + * no-op that queues no GC. tests/hosted-git covers the same guards through real git. + */ +const ZERO = '0'.repeat(40); +const enc = new TextEncoder(); +const oidOf = (label: string) => createHash('sha1').update(label).digest('hex'); +const SIG = 'Test 0 +0000'; + +type Kind = 'commit' | 'tree' | 'blob' | 'tag'; +type Obj = { type: Kind; data: Uint8Array }; + +function treeEntry(mode: string, name: string, oid: string): number[] { + return [...enc.encode(`${mode} ${name}\0`), ...Buffer.from(oid, 'hex')]; +} + +class Repo { + objects = new Map(); + refs = new Map(); + reads = 0; + + put(label: string, type: Kind, data: Uint8Array): string { + const oid = oidOf(label); + this.objects.set(oid, { type, data }); + return oid; + } + blob(label: string) { + return this.put(label, 'blob', enc.encode(`${label}\n`)); + } + tree(label: string, entries: number[][]) { + return this.put(label, 'tree', new Uint8Array(entries.flat())); + } + commit(label: string, tree: string, parents: string[] = []) { + const text = `tree ${tree}\n${parents.map((p) => `parent ${p}\n`).join('')}author ${SIG}\ncommitter ${SIG}\n\n${label}\n`; + return this.put(label, 'commit', enc.encode(text)); + } + tag(label: string, object: string, type: string) { + return this.put( + label, + 'tag', + enc.encode(`object ${object}\ntype ${type}\ntag ${label}\ntagger ${SIG}\n\n${label}\n`) + ); + } + /** A complete one-file commit. */ + simple(label: string, parents: string[] = []) { + const tree = this.tree(`${label}-tree`, [treeEntry('100644', 'f', this.blob(`${label}-blob`))]); + return this.commit(label, tree, parents); + } + + store(): GitStore { + return { + getMeta: () => null, + reachableVersion: () => 'v', + refs: () => [...this.refs].map(([name, target]) => ({ name, target })), + resolveHead: () => null, + getRef: (name: string) => this.refs.get(name) ?? null, + getPeeled: () => null, + typeAndSize: (oid: string) => { + const obj = this.objects.get(oid); + return obj ? { type: obj.type, size: obj.data.length } : null; + }, + get: async (oid: string) => { + this.reads += 1; + return this.objects.get(oid) ?? null; + }, + head: () => 'refs/heads/main', + setHead: () => undefined, + setRef: (name: string, target: string) => void this.refs.set(name, target), + delRef: (name: string) => void this.refs.delete(name), + invalidateReachable: () => undefined, + extendReachable: () => undefined, + } as unknown as GitStore; + } +} + +async function decide(repo: Repo, commands: [old: string, next: string, ref: string][]) { + return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush( + repo.store(), + commands.map(([old, next, ref]) => ({ old, next, ref })), + null + ) + ); +} + +describe('push admission: ref seeding', () => { + it('reads no existing ref tip before deciding commands', async () => { + const repo = new Repo(); + const tips: string[] = []; + for (let i = 0; i < 1201; i++) { + tips.push(repo.simple(`tip-${i}`)); + repo.refs.set(`refs/heads/t${i}`, tips[i]!); + } + const next = repo.simple('on-top', [tips[7]!]); + repo.reads = 0; + const plan = await decide(repo, [ + [tips[3]!, ZERO, 'refs/heads/t3'], + [ZERO, next, 'refs/heads/new'], + ]); + expect(plan.decisions[0]).toMatchObject({ del: true }); + expect(plan.decisions[1]).toMatchObject({ set: next }); + // The new commit and its tree: its parent is an existing tip and is never read. + expect(repo.reads).toBe(2); + }); +}); + +describe('push admission: edge types', () => { + it('refuses a commit whose tree is a blob, with a valid sibling accepted', async () => { + const repo = new Repo(); + const blob = repo.blob('loose'); + const evil = repo.commit('blob-as-tree', blob); + const good = repo.simple('good'); + const plan = await decide(repo, [ + [ZERO, evil, 'refs/heads/evil'], + [ZERO, good, 'refs/heads/good'], + ]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + expect(plan.decisions[1]).toMatchObject({ set: good }); + }); + + it('refuses a commit whose parent is a tree', async () => { + const repo = new Repo(); + const base = repo.simple('base'); + const tree = repo.tree('t', [treeEntry('100644', 'f', repo.blob('b'))]); + const evil = repo.commit('tree-as-parent', tree, [tree]); + repo.refs.set('refs/heads/main', base); + const plan = await decide(repo, [[ZERO, evil, 'refs/heads/evil']]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + }); + + it('refuses a validated object at an edge of the wrong type', async () => { + const repo = new Repo(); + const tip = repo.simple('tip'); + repo.refs.set('refs/heads/main', tip); + // The existing tip is in the validated set, but a commit's tree must be a tree. + const evil = repo.commit('commit-as-tree', tip); + const plan = await decide(repo, [[ZERO, evil, 'refs/heads/evil']]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + const ok = repo.simple('child', [tip]); + expect((await decide(repo, [[ZERO, ok, 'refs/heads/child']])).decisions[0]).toMatchObject({ + set: ok, + }); + }); + + it('refuses a tree entry whose mode disagrees with its object type', async () => { + const repo = new Repo(); + const inner = repo.tree('inner', [treeEntry('100644', 'f', repo.blob('x'))]); + const evil = repo.commit('mode', repo.tree('outer', [treeEntry('100644', 'dir', inner)])); + const fine = repo.commit('fine', repo.tree('outer-ok', [treeEntry('40000', 'dir', inner)])); + const plan = await decide(repo, [ + [ZERO, evil, 'refs/heads/evil'], + [ZERO, fine, 'refs/heads/fine'], + ]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + expect(plan.decisions[1]).toMatchObject({ set: fine }); + }); + + it('refuses an annotated tag whose type header disagrees with its object', async () => { + const repo = new Repo(); + const commit = repo.simple('tagged'); + const lying = repo.tag('lying', commit, 'tree'); + const honest = repo.tag('honest', commit, 'commit'); + const plan = await decide(repo, [ + [ZERO, lying, 'refs/tags/lying'], + [ZERO, honest, 'refs/tags/honest'], + ]); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + expect(plan.decisions[1]).toMatchObject({ set: honest }); + }); + + it('refuses a non-commit on a branch but allows it as a lightweight tag', async () => { + const repo = new Repo(); + const tree = repo.tree('bare', [treeEntry('100644', 'f', repo.blob('y'))]); + const plan = await decide(repo, [ + [ZERO, tree, 'refs/heads/tree'], + [ZERO, tree, 'refs/tags/tree'], + ]); + expect(plan.decisions[0]).toMatchObject({ + reject: 'trying to write non-commit object to branch', + }); + expect(plan.decisions[1]).toMatchObject({ set: tree }); + }); +}); + +describe('push admission: directory/file ref conflicts', () => { + it('refuses a ref nested under an existing ref, and an existing ref nested under a new one', async () => { + const repo = new Repo(); + const c = repo.simple('c'); + repo.refs.set('refs/heads/a', c); + repo.refs.set('refs/heads/x/y', c); + const plan = await decide(repo, [ + [ZERO, c, 'refs/heads/a/b'], + [ZERO, c, 'refs/heads/x'], + [ZERO, c, 'refs/heads/ab'], + [ZERO, c, 'refs/heads/x-y'], + ]); + expect(plan.decisions.map((d) => d.reject ?? 'set')).toEqual([ + 'ref name conflicts with an existing ref', + 'ref name conflicts with an existing ref', + 'set', + 'set', + ]); + }); + + it('refuses the second of two conflicting new refs in one push', async () => { + const repo = new Repo(); + const c = repo.simple('c'); + const plan = await decide(repo, [ + [ZERO, c, 'refs/heads/n'], + [ZERO, c, 'refs/heads/n/m'], + ]); + expect(plan.decisions[0]).toMatchObject({ set: c }); + expect(plan.decisions[1]).toMatchObject({ reject: 'ref name conflicts with an existing ref' }); + }); + + it('refuses every command for a ref the push names twice, so a losing delete frees no name', async () => { + const repo = new Repo(); + const a = repo.simple('a'); + const b = repo.simple('b', [a]); + repo.refs.set('refs/heads/a', a); + // Update a, delete a (loses its CAS to the update at commit), create a/b under it. + const out = commitPush( + repo.store(), + await decide(repo, [ + [a, b, 'refs/heads/a'], + [a, ZERO, 'refs/heads/a'], + [ZERO, a, 'refs/heads/a/b'], + ]) + ); + expect(out.results.map((r) => (r.ok ? 'ok' : r.msg))).toEqual([ + 'multiple updates for ref not allowed', + 'multiple updates for ref not allowed', + 'ref name conflicts with an existing ref', + ]); + expect([...repo.refs]).toEqual([['refs/heads/a', a]]); + }); + + it('allows replacing a ref with a nested one when the same push deletes it', async () => { + const repo = new Repo(); + const c = repo.simple('c'); + repo.refs.set('refs/heads/a', c); + const plan = await decide(repo, [ + [ZERO, c, 'refs/heads/a/b'], + [c, ZERO, 'refs/heads/a'], + ]); + expect(plan.decisions[0]).toMatchObject({ set: c }); + expect(plan.decisions[1]).toMatchObject({ del: true }); + }); +}); + +describe('push admission: deleting a missing ref', () => { + it('reports success without changing refs or queueing GC, with a real deletion control', async () => { + const repo = new Repo(); + const c = repo.simple('c'); + repo.refs.set('refs/heads/real', c); + const missing = commitPush(repo.store(), await decide(repo, [[ZERO, ZERO, 'refs/heads/nope']])); + expect(missing).toMatchObject({ changed: false, needsGc: false }); + expect(missing.results).toEqual([{ ref: 'refs/heads/nope', ok: true }]); + const real = commitPush(repo.store(), await decide(repo, [[c, ZERO, 'refs/heads/real']])); + expect(real).toMatchObject({ changed: true, needsGc: true }); + expect(repo.refs.has('refs/heads/real')).toBe(false); + }); +}); + +describe('armHostedGitGcAlarm', () => { + it('keeps an alarm already due sooner, and arms one when none is due or it is later', async () => { + vi.useFakeTimers({ now: 1_000_000 }); + try { + const due = Date.now() + GC_DELAY_MS; + const storage = (armed: number | null) => ({ + getAlarm: vi.fn(async () => armed), + setAlarm: vi.fn(async () => undefined), + }); + const sooner = storage(Date.now() + 1000); + await armHostedGitGcAlarm(sooner); + expect(sooner.setAlarm).not.toHaveBeenCalled(); + const none = storage(null); + await armHostedGitGcAlarm(none); + expect(none.setAlarm).toHaveBeenCalledWith(due); + const later = storage(due + 60_000); + await armHostedGitGcAlarm(later); + expect(later.setAlarm).toHaveBeenCalledWith(due); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('push admission: object shapes git can read', () => { + const header = `author ${SIG}\ncommitter ${SIG}`; + it('refuses byte-level shapes git cannot read, and accepts names that are not UTF-8', async () => { + const repo = new Repo(); + const blob = repo.blob('bytes-blob'); + const tree = repo.tree('bytes-tree', [treeEntry('100644', 'f', blob)]); + const bom = [0xef, 0xbb, 0xbf]; + const raw = (label: string, type: Kind, bytes: number[]) => + repo.put(label, type, new Uint8Array(bytes)); + const sigLines = `author ${SIG}\ncommitter ${SIG}\n`; + const bomCommit = raw('bom-commit', 'commit', [ + ...bom, + ...enc.encode(`tree ${tree}\n${sigLines}\nx\n`), + ]); + const good = repo.commit('good', tree); + const bomTag = raw('bom-tag', 'tag', [ + ...bom, + ...enc.encode(`object ${good}\ntype commit\ntag t\n\nx\n`), + ]); + const openTag = raw('open-tag', 'tag', [...enc.encode(`object ${good}\ntype commit\ntag v1`)]); + // The header section must end in a newline even when its last line is optional. + const openTagger = raw('open-tagger', 'tag', [ + ...enc.encode(`object ${good}\ntype commit\ntag v2\ntagger ${SIG}`), + ]); + const nulHeader = raw('nul', 'commit', [ + ...enc.encode(`tree ${tree}\nauthor T`), + 0, + ...enc.encode(` ${SIG}\ncommitter ${SIG}\n\nx\n`), + ]); + const entry = (mode: string, name: number[], oid: string) => [ + ...enc.encode(`${mode} `), + ...name, + 0, + ...Buffer.from(oid, 'hex'), + ]; + const latin = repo.commit( + 'latin', + repo.tree('latin-tree', [entry('100644', [0xe8], blob), entry('100644', [0xe9], blob)]) + ); + const bomName = repo.commit( + 'bom-name', + repo.tree('bom-name-tree', [entry('100644', bom, blob)]) + ); + const oddMode = repo.commit( + 'odd-mode', + repo.tree('odd-mode-tree', [entry('100600', [0x66], blob)]) + ); + const dotGit = repo.commit( + 'dot-git', + repo.tree('dot-git-tree', [entry('100644', [...enc.encode('.GIT ')], blob)]) + ); + const dotDot = repo.commit( + 'dot-dot', + repo.tree('dot-dot-tree', [entry('40000', [...enc.encode('..')], tree)]) + ); + const plan = await decide(repo, [ + [ZERO, bomCommit, 'refs/heads/bom'], + [ZERO, bomTag, 'refs/tags/bom'], + [ZERO, openTag, 'refs/tags/open'], + [ZERO, openTagger, 'refs/tags/open-tagger'], + [ZERO, nulHeader, 'refs/heads/nul'], + [ZERO, dotGit, 'refs/heads/dot-git'], + [ZERO, dotDot, 'refs/heads/dot-dot'], + [ZERO, latin, 'refs/heads/latin'], + [ZERO, bomName, 'refs/heads/bom-name'], + [ZERO, oddMode, 'refs/heads/odd-mode'], + ]); + expect(plan.decisions.map((d) => (d.reject ? 'reject' : 'set'))).toEqual([ + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'set', + 'set', + 'set', + ]); + }); + + it('refuses a leading continuation line and checkout-breaking names, with controls accepted', async () => { + const repo = new Repo(); + const blob = repo.blob('lead-blob'); + const tree = repo.tree('lead-tree', [treeEntry('100644', 'f', blob)]); + const good = repo.commit('lead-good', tree); + const sigLines = `author ${SIG}\ncommitter ${SIG}\n`; + const leadCommit = repo.put( + 'lead-commit', + 'commit', + enc.encode(` junk\ntree ${tree}\n${sigLines}\nx\n`) + ); + const leadTag = repo.put( + 'lead-tag', + 'tag', + enc.encode(` junk\nobject ${good}\ntype commit\ntag t\n\nx\n`) + ); + const named = (label: string, mode: string, name: string, oid: string) => + repo.commit(label, repo.tree(`${label}-tree`, [treeEntry(mode, name, oid)])); + const plan = await decide(repo, [ + [ZERO, leadCommit, 'refs/heads/lead'], + [ZERO, leadTag, 'refs/tags/lead'], + [ZERO, named('short', '40000', 'GIT~1', tree), 'refs/heads/short'], + [ZERO, named('stream', '100644', '.git:x', blob), 'refs/heads/stream'], + [ZERO, named('modules', '120000', '.gitmodules', blob), 'refs/heads/modules'], + [ZERO, named('modules-short', '120000', 'GITMOD~1', blob), 'refs/heads/modules-short'], + [ZERO, named('modules-stream', '120000', '.gitmodules:x', blob), 'refs/heads/modules-stream'], + [ZERO, named('long', '100644', 'n'.repeat(256), blob), 'refs/heads/long'], + [ZERO, named('limit', '100644', 'n'.repeat(255), blob), 'refs/heads/limit'], + [ZERO, named('modules-file', '100644', '.gitmodules', blob), 'refs/heads/modules-file'], + [ZERO, named('gitignore', '100644', '.gitignore', blob), 'refs/heads/gitignore'], + ]); + expect(plan.decisions.map((d) => (d.reject ? 'reject' : 'set'))).toEqual([ + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'set', + 'set', + 'set', + ]); + }); + + it('refuses commits, tags and trees git cannot parse, with git-shaped controls accepted', async () => { + const repo = new Repo(); + const tree = repo.tree('shape-tree', [treeEntry('100644', 'f', repo.blob('shape-blob'))]); + const signed = repo.put( + 'signed', + 'commit', + enc.encode( + `tree ${tree}\n${header}\nencoding UTF-8\ngpgsig -----BEGIN PGP SIGNATURE-----\n line\n -----END PGP SIGNATURE-----\n\nsigned\n` + ) + ); + const authorFirst = repo.put( + 'author-first', + 'commit', + enc.encode(`${header.split('\n')[0]}\ntree ${tree}\n${header.split('\n')[1]}\n\nx\n`) + ); + const noCommitter = repo.put( + 'no-committer', + 'commit', + enc.encode(`tree ${tree}\nauthor ${SIG}\n\nx\n`) + ); + const lateParent = repo.put( + 'late-parent', + 'commit', + enc.encode(`tree ${tree}\n${header}\nparent ${signed}\n\nx\n`) + ); + const tagTypeFirst = repo.put( + 'type-first', + 'tag', + enc.encode(`type commit\nobject ${signed}\ntag t\ntagger ${SIG}\n\nx\n`) + ); + const tagNoName = repo.put( + 'no-name', + 'tag', + enc.encode(`object ${signed}\ntype commit\ntagger ${SIG}\n\nx\n`) + ); + const badMode = repo.commit( + 'bad-mode', + repo.tree('bad-mode-tree', [treeEntry('8', 'f', repo.blob('m'))]) + ); + const dupName = repo.commit( + 'dup-name', + repo.tree('dup-tree', [ + treeEntry('100644', 'f', repo.blob('d1')), + treeEntry('100644', 'f', repo.blob('d2')), + ]) + ); + const slashName = repo.commit( + 'slash', + repo.tree('slash-tree', [treeEntry('100644', 'a/b', repo.blob('s'))]) + ); + const plan = await decide(repo, [ + [ZERO, signed, 'refs/heads/signed'], + [ZERO, authorFirst, 'refs/heads/author-first'], + [ZERO, noCommitter, 'refs/heads/no-committer'], + [ZERO, lateParent, 'refs/heads/late-parent'], + [ZERO, tagTypeFirst, 'refs/tags/type-first'], + [ZERO, tagNoName, 'refs/tags/no-name'], + [ZERO, badMode, 'refs/heads/bad-mode'], + [ZERO, dupName, 'refs/heads/dup-name'], + [ZERO, slashName, 'refs/heads/slash'], + [ZERO, repo.tag('good-tag', signed, 'commit'), 'refs/tags/good'], + ]); + const outcome = plan.decisions.map((d) => (d.reject ? 'reject' : 'set')); + expect(outcome).toEqual([ + 'set', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'reject', + 'set', + ]); + }); +}); + +describe('push admission: old history and the reachable cache', () => { + it('never trusts the reachable cache for a push: a cached but absent parent is refused', async () => { + // A clone racing a stranding push could once stamp a stale reachable set as current, + // and GC then deleted an object the cache still listed. Admission must not consult it. + const repo = new Repo(); + const base = repo.simple('base'); + repo.refs.set('refs/heads/main', base); + const gone = oidOf('collected-commit'); + const child = repo.simple('child-of-gone', [gone]); + const store = repo.store() as unknown as Record; + store.getMeta = (key: string) => (key === 'reachable-version' ? 'v' : null); + store.reachableHas = (oid: string) => oid === gone || repo.objects.has(oid); + const plan = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush( + store as unknown as GitStore, + [{ old: ZERO, next: child, ref: 'refs/heads/child' }], + null + ) + ); + expect(plan.decisions[0]).toMatchObject({ reject: 'missing necessary objects' }); + const ok = repo.simple('child-of-base', [base]); + const control = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush( + store as unknown as GitStore, + [{ old: ZERO, next: ok, ref: 'refs/heads/ok' }], + null + ) + ); + expect(control.decisions[0]).toMatchObject({ set: ok }); + }); + + it('treats an update as forced when the ancestry check exhausts the work budget', async () => { + const repo = new Repo(); + const old = repo.simple('old'); + const side = repo.simple('side'); + const next = repo.simple('next', [side]); + repo.refs.set('refs/heads/main', old); + repo.refs.set('refs/heads/side', side); + const store = repo.store() as unknown as Record; + const get = store.get as (oid: string) => Promise; + let failRead: string | null = side; + store.get = async (oid: string) => { + if (oid === failRead) throw new Error('git work exceeds decompression budget'); + return get(oid); + }; + const plan = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush(store as unknown as GitStore, [{ old, next, ref: 'refs/heads/main' }], null) + ); + expect(plan.decisions[0]).toMatchObject({ set: next, forced: true }); + // Any other failure still fails the push. + failRead = side; + store.get = async (oid: string) => { + if (oid === failRead) throw new Error('storage unavailable'); + return get(oid); + }; + await expect( + withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush(store as unknown as GitStore, [{ old, next, ref: 'refs/heads/main' }], null) + ) + ).rejects.toThrow('storage unavailable'); + }); +}); + +describe('reachable cache stamping and GC', () => { + it('stamps a clone-built reachable set only if refs did not move during the walk', async () => { + const { GitStore } = await import('../../../src/vendor/dgit/git/store'); + const { OidSet } = await import('../../../src/vendor/dgit/git/oidset'); + const set = new OidSet(16); + set.markHex(oidOf('reachable-1')); + const fakeThis = (current: string) => ({ + reachableSaveGeneration: 0, + reachableVersion: () => current, + sql: { exec: vi.fn() }, + setMeta: vi.fn(), + }); + const moved = fakeThis('after-push'); + await GitStore.prototype.saveReachable.call(moved as unknown as GitStore, set, 'before-push'); + expect(moved.setMeta).not.toHaveBeenCalled(); + expect(moved.sql.exec).not.toHaveBeenCalled(); + const steady = fakeThis('same'); + await GitStore.prototype.saveReachable.call(steady as unknown as GitStore, set, 'same'); + // Unstamped before the rewrite, restamped only after it completes. + expect(steady.setMeta.mock.calls).toEqual([ + ['reachable-version', ''], + ['reachable-version', 'same'], + ]); + }); + + it('invalidates the reachable cache when GC deletes objects, and only then', async () => { + const { runHostedGitGc } = await import('../../../src/selfhost/hosted-git/hosted-git-gc'); + const gcStore = (loose: string[]) => { + const invalidateReachable = vi.fn(); + const store = { + objectCount: () => loose.length, + refs: () => [], + resolveHead: () => null, + typeAndSize: () => null, + get: async () => null, + packs: { + baseOids: () => [], + packIds: () => [], + countObjects: () => 0, + totalPackBytes: () => 0, + lookup: () => null, + reset: () => undefined, + }, + dbSize: () => 0, + allOids: () => loose, + deleteObject: vi.fn(), + invalidateReachable, + } as unknown as GitStore; + return { store, invalidateReachable }; + }; + const withGarbage = gcStore([oidOf('garbage')]); + expect((await runHostedGitGc(withGarbage.store)).removed).toBe(1); + expect(withGarbage.invalidateReachable).toHaveBeenCalledOnce(); + const clean = gcStore([]); + expect((await runHostedGitGc(clean.store)).removed).toBe(0); + expect(clean.invalidateReachable).not.toHaveBeenCalled(); + }); +}); + +describe('reachable cache writers check validity when they write', () => { + it('lets only the latest of two overlapping clone saves keep writing and stamp', async () => { + const { GitStore } = await import('../../../src/vendor/dgit/git/store'); + const { OidSet } = await import('../../../src/vendor/dgit/git/oidset'); + const n = 8192 * 2 + 5; // more than one insert batch, so each save yields mid-rewrite + const set = new OidSet(n); + for (let i = 0; i < n; i++) set.markHex(oidOf(`row-${i}`)); + let inserts = 0; + const store = { + reachableSaveGeneration: 0, + reachableVersion: () => 'v', + sql: { exec: (q: string) => void (q.startsWith('INSERT') && inserts++) }, + setMeta: vi.fn(), + } as unknown as InstanceType; + const save = GitStore.prototype.saveReachable; + const first = save.call(store, set, 'v'); // runs one batch, then yields + const second = save.call(store, set, 'v'); // supersedes it + await Promise.all([first, second]); + const stamps = (store.setMeta as ReturnType).mock.calls.filter( + ([, v]) => v === 'v' + ); + expect(stamps).toHaveLength(1); + // The superseded save stopped after its first batch; the latest wrote every row. + expect(inserts).toBe(8192 + n); + }); + + it('extends the cache at commit only if it is still stamped current, with a control', async () => { + const run = async (stillValid: boolean) => { + const repo = new Repo(); + const base = repo.simple('base'); + repo.refs.set('refs/heads/main', base); + const next = repo.simple('next', [base]); + const store = repo.store() as unknown as Record; + store.getMeta = (key: string) => (key === 'reachable-version' ? 'v' : null); + const extendReachable = vi.fn(); + const invalidateReachable = vi.fn(); + Object.assign(store, { + extendReachable, + invalidateReachable, + reachableCacheValid: () => stillValid, + }); + const plan = await withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, () => + validatePush( + store as unknown as GitStore, + [{ old: base, next, ref: 'refs/heads/main' }], + null + ) + ); + expect(plan.hadCache).toBe(true); + commitPush(store as unknown as GitStore, plan); + return { extendReachable, invalidateReachable }; + }; + const rewritten = await run(false); // a clone's save unstamped the cache during validation + expect(rewritten.extendReachable).not.toHaveBeenCalled(); + expect(rewritten.invalidateReachable).toHaveBeenCalledOnce(); + const steady = await run(true); + expect(steady.extendReachable).toHaveBeenCalledOnce(); + expect(steady.invalidateReachable).not.toHaveBeenCalled(); + }); +}); + +describe('GC reclaims packs without inflating and drops delta-only bases', () => { + /** + * A fake object store with packs and loose objects. A ref points at commit C; C's tree T holds + * blob B2, which is stored as a delta on blob B1 (unreachable). Pack 1 holds C, T, B2 and B1; + * pack 2 is a rejected push's pack holding only unreachable X. + */ + function gcFixture(opts: { noHeadroom?: boolean } = {}) { + const repo = new Repo(); + const b1 = repo.blob('base-blob'); + const b2 = repo.blob('delta-blob'); + const tree = repo.tree('gc-tree', [treeEntry('100644', 'f', b2)]); + const commit = repo.commit('gc-commit', tree); + const x = repo.blob('rejected'); + repo.refs.set('refs/heads/main', commit); + const packs = new Map([ + [1, [commit, tree, b2, b1]], + [2, [x]], + ]); + const loose = new Map(); + const dropped: number[] = []; + const migrated: string[] = []; + const reads: string[] = []; + const store = { + ...(repo.store() as unknown as Record), + objectCount: () => [...packs.values()].flat().length + loose.size, + get: async (oid: string) => { + reads.push(oid); + return repo.objects.get(oid) ?? null; + }, + packs: { + baseOids: () => [b1], + packIds: () => [...packs.keys()], + packObjectOids: (id: number) => packs.get(id) ?? [], + dropPack: async (id: number) => { + dropped.push(id); + packs.delete(id); + }, + countObjects: () => [...packs.values()].flat().length, + totalPackBytes: () => (opts.noHeadroom ? 11 * 1024 ** 3 : 0), + lookup: (oid: string) => ([...packs.values()].some((o) => o.includes(oid)) ? {} : null), + reset: () => packs.clear(), + }, + dbSize: () => 0, + put: (oid: string) => { + migrated.push(oid); + loose.set(oid, true); + }, + allOids: () => [...loose.keys()], + deleteObject: (oid: string) => loose.delete(oid), + invalidateReachable: () => undefined, + } as unknown as GitStore; + return { store, ids: { b1, b2, tree, commit, x }, dropped, migrated, reads, loose }; + } + + it('drops a pack with nothing reachable before reading any pack object', async () => { + const { runHostedGitGc } = await import('../../../src/selfhost/hosted-git/hosted-git-gc'); + const f = gcFixture(); + let readsAtDrop = -1; + const packs = (f.store as unknown as { packs: { dropPack: (id: number) => Promise } }) + .packs; + const drop = packs.dropPack; + packs.dropPack = async (id) => { + readsAtDrop = f.reads.filter((oid) => oid === f.ids.b2).length; + await drop(id); + }; + await runHostedGitGc(f.store); + expect(f.dropped).toEqual([2]); + // The rejected pack went before migration inflated any blob. + expect(readsAtDrop).toBe(0); + }); + + it('does not keep a delta-only base after migrating, but keeps a loose base while packs stay', async () => { + const { runHostedGitGc } = await import('../../../src/selfhost/hosted-git/hosted-git-gc'); + const migrating = gcFixture(); + await runHostedGitGc(migrating.store); + expect(migrating.migrated.sort()).toEqual( + [migrating.ids.commit, migrating.ids.tree, migrating.ids.b2].sort() + ); + expect(migrating.loose.has(migrating.ids.b1)).toBe(false); + + const kept = gcFixture({ noHeadroom: true }); + kept.loose.set(kept.ids.b1, true); // a loose base that pack deltas still use + const result = await runHostedGitGc(kept.store); + expect(result.skipped).toBe(true); + expect(kept.loose.has(kept.ids.b1)).toBe(true); + }); +}); + +describe('upload request lists and ref reservations', () => { + it('deduplicates and caps wants, haves and shallow lines while parsing (Codex r4637122054, r4637332208)', async () => { + const { MAX_UPLOAD_OIDS, parseUploadRequest } = + await import('../../../src/vendor/dgit/git/protocol'); + const { pkt, FLUSH } = await import('../../../src/vendor/dgit/git/pktline'); + const { concat } = await import('../../../src/vendor/dgit/git/util'); + const a = 'a'.repeat(40); + const lines = [pkt(`want ${a} side-band-64k\n`)]; + for (let i = 0; i < 1000; i++) + lines.push(pkt(`want ${a}\n`), pkt(`have ${a}\n`), pkt(`shallow ${a}\n`)); + for (let i = 0; i < MAX_UPLOAD_OIDS + 5; i++) + lines.push(pkt(`have ${i.toString(16).padStart(40, '0')}\n`)); + const req = parseUploadRequest(concat([...lines, FLUSH])); + expect(req.wants).toEqual([a]); + expect(req.clientShallows).toEqual([a]); + expect(req.haves).toHaveLength(MAX_UPLOAD_OIDS); + expect(new Set(req.haves).size).toBe(MAX_UPLOAD_OIDS); + expect(req.caps.has('side-band-64k')).toBe(true); + }); + + it('reserves a page per new ref and nothing for updates or deletions (Codex r4637332217)', async () => { + const { hostedGitNewRefBytes } = await import('../../../src/selfhost/hosted-git/limits'); + const existing = [{ name: 'refs/heads/main' }]; + expect( + hostedGitNewRefBytes(existing, [ + { ref: 'refs/heads/main', next: 'b'.repeat(40) }, + { ref: 'refs/heads/new', next: 'c'.repeat(40) }, + { ref: 'refs/heads/new', next: 'd'.repeat(40) }, + { ref: 'refs/heads/gone', next: ZERO }, + { ref: 'refs/tags/v1', next: 'e'.repeat(40) }, + ]) + ).toBe(2 * 4096); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts new file mode 100644 index 0000000000..a9bd2811d2 --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-refname.test.ts @@ -0,0 +1,99 @@ +import { spawnSync } from 'node:child_process'; + +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_HOSTED_GIT_LIMITS } from '../../../src/selfhost/hosted-git/limits'; +import { withGitWorkBudget } from '../../../src/vendor/dgit/git/budget'; +import { validatePush } from '../../../src/vendor/dgit/git/protocol'; +import type { GitStore } from '../../../src/vendor/dgit/git/store'; + +// Audit every rule in https://git-scm.com/docs/git-check-ref-format. The real smart-HTTP +// suite separately proves the parser/DO/write path with ordinary and nested branch controls. +const invalid = [ + 'refs/heads/.hidden/x', + 'refs/heads/x/.hidden', + 'refs/heads/x.lock/y', + 'refs/heads/x.lock', + 'HEAD', + '@', + 'refs/heads/x y', + 'refs/heads/x..y', + 'refs/heads/x~y', + 'refs/heads/x^y', + 'refs/heads/x:y', + 'refs/heads/x?y', + 'refs/heads/x*y', + 'refs/heads/x[y', + '/refs/heads/x', + 'refs/heads/x/', + 'refs/heads/x//y', + 'refs/heads/x.', + 'refs/heads/x@{y', + 'refs/heads/x\\y', + ...Array.from( + { length: 33 }, + (_, i) => `refs/heads/x${String.fromCharCode(i === 32 ? 127 : i)}y` + ), +]; +const valid = [ + 'refs/heads/normal', + 'refs/heads/feature/x', + 'refs/tags/v1.0', + 'refs/heads/x.lockish/y', + 'refs/heads/a.b/c', + 'refs/heads/café', +]; +// The pushed tip is a commit with an empty tree, so valid names reach a `set` decision. +const tip = 'a'.repeat(40); +const tree = 'b'.repeat(40); +const objects: Record = { + [tip]: { + type: 'commit', + data: new TextEncoder().encode( + `tree ${tree}\nauthor T 0 +0000\ncommitter T 0 +0000\n\nmsg\n` + ), + }, + [tree]: { type: 'tree', data: new Uint8Array(0) }, +}; +const store = { + getMeta: () => null, + reachableVersion: () => '0', + refs: () => [], + resolveHead: () => null, + getRef: () => null, + getPeeled: () => null, + typeAndSize: (oid: string) => (objects[oid] ? { type: objects[oid].type, size: 1 } : null), + get: async (oid: string) => objects[oid] ?? null, +} as unknown as GitStore; +async function decision(ref: string) { + return withGitWorkBudget(DEFAULT_HOSTED_GIT_LIMITS, async () => { + const plan = await validatePush( + store, + [{ old: '0'.repeat(40), next: 'a'.repeat(40), ref }], + null + ); + return plan.decisions[0]; + }); +} +describe('validatePush Git ref-format rules', () => { + it.each(invalid)('rejects invalid ref %j', async (ref) => { + // NUL cannot cross an OS argv boundary; the protocol also uses it as the capabilities delimiter. + if (!ref.includes('\0')) expect(spawnSync('git', ['check-ref-format', ref]).status).not.toBe(0); + expect(await decision(ref)).toMatchObject({ ref, reject: 'funny refname' }); + }); + it.each(valid)('accepts valid ref %j', async (ref) => { + expect(spawnSync('git', ['check-ref-format', ref]).status).toBe(0); + expect(await decision(ref)).toMatchObject({ ref, set: 'a'.repeat(40) }); + }); + it.each([ + 'refs/heads/xy', + 'refs/heads/x&y', + 'refs/heads/x`y', + 'refs/heads/x"y', + "refs/heads/x'y", + `refs/heads/${'x'.repeat(256)}`, + ])('keeps SAM conservative safety bound for %j', async (ref) => { + expect(await decision(ref)).toMatchObject({ reject: 'funny refname' }); + }); +}); diff --git a/apps/api/tests/unit/selfhost/hosted-git-sha1dc.test.ts b/apps/api/tests/unit/selfhost/hosted-git-sha1dc.test.ts new file mode 100644 index 0000000000..44be01876e --- /dev/null +++ b/apps/api/tests/unit/selfhost/hosted-git-sha1dc.test.ts @@ -0,0 +1,55 @@ +import { createHash } from 'node:crypto'; + +import { describe, expect, it } from 'vitest'; + +import { Sha1Dc } from '../../../src/vendor/dgit/git/sha1'; + +/** + * The vendored SHA-1DC detector that hosted-git push ingest screens every object with + * (`collisionDetect: true` in hosted-git-repo.ts). The fixtures are the first 320 bytes of the + * two SHAttered PDFs (shattered.io, also git's t/t0013): a shared prefix and the two + * near-collision blocks, which hash to the same SHA-1. tests/hosted-git covers the push path. + */ +const SHATTERED_1 = + 'JVBERi0xLjMKJeLjz9MKCgoxIDAgb2JqCjw8L1dpZHRoIDIgMCBSL0hlaWdodCAzIDAgUi9UeXBlIDQgMCBSL1N1YnR5cGUgNSAwIFIvRmlsdGVyIDYgMCBSL0NvbG9yU3BhY2UgNyAwIFIvTGVuZ3RoIDggMCBSL0JpdHNQZXJDb21wb25lbnQgOD4+CnN0cmVhbQr/2P/+ACRTSEEtMSBpcyBkZWFkISEhISGFL+wJIzl1nDmxocY8TJfh//4Bc0bckWa2fhGPApq2IbJWD/nKZ8yox/hbqEx5AwwrPeIY+G2zqQkB1d9FwU8m/t+z3DjpasIv571yjw5FvOBG0jxXD+sUE5i7VS71oKgr4zH+pIA3uLXXHw4zLt+TrDUA603cDezBqGR5DHgsdiFWYN0wl5HQa9CvP5jNpLxGKbE='; +const SHATTERED_2 = + 'JVBERi0xLjMKJeLjz9MKCgoxIDAgb2JqCjw8L1dpZHRoIDIgMCBSL0hlaWdodCAzIDAgUi9UeXBlIDQgMCBSL1N1YnR5cGUgNSAwIFIvRmlsdGVyIDYgMCBSL0NvbG9yU3BhY2UgNyAwIFIvTGVuZ3RoIDggMCBSL0JpdHNQZXJDb21wb25lbnQgOD4+CnN0cmVhbQr/2P/+ACRTSEEtMSBpcyBkZWFkISEhISGFL+wJIzl1nDmxocY8TJfh//4Bf0bck6a2fgE7ApqqHbJWC0XKZ9aIx/hLjEx5H+ArPfYU+G2xaQkBxWtFwVMK/t+3YDjpcnIv561yjw5JBOBGwjBXD+nUE5ir4S71vJQr4zVCpIAtmLXXDyozLsN/rDUU503cDyzBqHTNDHgwWiFWZGEwl4lga9C/P5jNqARGKaE='; + +const bytes = (b64: string) => new Uint8Array(Buffer.from(b64, 'base64')); + +function hash(data: Uint8Array): { oid: string; collision: boolean } { + const h = new Sha1Dc().reset().update(data); + const oid = Buffer.from(h.digest()).toString('hex'); + return { oid, collision: h.collision }; +} + +describe('SHA-1DC collision detection', () => { + it('flags both halves of the SHAttered collision without changing the SHA-1', () => { + const one = bytes(SHATTERED_1); + const two = bytes(SHATTERED_2); + expect(Buffer.from(one).equals(Buffer.from(two))).toBe(false); + const a = hash(one); + const b = hash(two); + expect(a.oid).toBe(b.oid); + expect(a.oid).toBe(createHash('sha1').update(one).digest('hex')); + expect(a.collision).toBe(true); + expect(b.collision).toBe(true); + }); + + it('does not flag the same bytes with one bit changed in a collision block', () => { + const data = bytes(SHATTERED_1); + data[200]! ^= 1; + const h = hash(data); + expect(h.collision).toBe(false); + expect(h.oid).toBe(createHash('sha1').update(data).digest('hex')); + }); + + it('resets the verdict between objects', () => { + const h = new Sha1Dc().reset().update(bytes(SHATTERED_1)); + h.digest(); + expect(h.collision).toBe(true); + h.reset().update(new TextEncoder().encode('blob 6\0hello\n')); + h.digest(); + expect(h.collision).toBe(false); + }); +}); diff --git a/apps/api/tests/unit/selfhost/reverse-tunnel-placement.test.ts b/apps/api/tests/unit/selfhost/reverse-tunnel-placement.test.ts index 797c0167f1..2d5aeee61f 100644 --- a/apps/api/tests/unit/selfhost/reverse-tunnel-placement.test.ts +++ b/apps/api/tests/unit/selfhost/reverse-tunnel-placement.test.ts @@ -17,17 +17,22 @@ import { REVERSE_TUNNEL_MIGRATIONS } from '../../../src/selfhost/reverse-tunnel- import { API_SRC, collectImportGraph, + GRAPH_WALK_TIMEOUT_MS, REPO_ROOT, selfhostOnlyFindings, } from '../../helpers/selfhost-only-modules'; describe('self-host-only placement', () => { - it('keeps reverse implementation out of the real Worker import graph', () => { - const graph = collectImportGraph(resolve(API_SRC, 'index.ts')); - expect(graph.files.length).toBeGreaterThan(100); - expect(graph.files).toContain('apps/api/src/services/node-provisioning-ingress.ts'); - expect(selfhostOnlyFindings(graph)).toEqual([]); - }); + it( + 'keeps reverse implementation out of the real Worker import graph', + () => { + const graph = collectImportGraph(resolve(API_SRC, 'index.ts')); + expect(graph.files.length).toBeGreaterThan(100); + expect(graph.files).toContain('apps/api/src/services/node-provisioning-ingress.ts'); + expect(selfhostOnlyFindings(graph)).toEqual([]); + }, + GRAPH_WALK_TIMEOUT_MS + ); it('follows forbidden imports from a neutral entry and recognizes package imports', () => { const scratchRoot = join(REPO_ROOT, '.tmp'); mkdirSync(scratchRoot, { recursive: true }); diff --git a/apps/api/tests/unit/selfhost/selfhost-build.test.ts b/apps/api/tests/unit/selfhost/selfhost-build.test.ts index 04b7294314..8cc1499893 100644 --- a/apps/api/tests/unit/selfhost/selfhost-build.test.ts +++ b/apps/api/tests/unit/selfhost/selfhost-build.test.ts @@ -3,6 +3,7 @@ * the D1 analytics sink and its `analytics.d1.*` settings, or a box loses product analytics * and their retention bound. Enters through the real build function, not the sink's own installer. */ +import { Hono } from 'hono'; import { afterEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; @@ -31,7 +32,10 @@ describe('withSelfHostBuild', () => { expect(activeLocalAnalyticsSink(boxEnv)).toBeUndefined(); expect(findAdminSetting('analytics.d1.retentionDays')).toBeUndefined(); - withSelfHostBuild(shared); + withSelfHostBuild( + shared, + new Hono<{ Bindings: Env }>().get('/health', (c) => c.text('ok')) + ); expect(activeLocalAnalyticsSink(boxEnv)?.table).toBe('analytics_events'); expect(resolvePlatformCapabilities(boxEnv).analyticsQuery).toBe(true); @@ -40,7 +44,10 @@ describe('withSelfHostBuild', () => { }); it('leaves the sink inactive on an installation that does not switch it on', () => { - withSelfHostBuild(shared); + withSelfHostBuild( + shared, + new Hono<{ Bindings: Env }>().get('/health', (c) => c.text('ok')) + ); expect( activeLocalAnalyticsSink({ OBSERVABILITY_DATABASE: {} } as unknown as Env) ).toBeUndefined(); diff --git a/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts index 959cb5554a..a3b543755b 100644 --- a/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts +++ b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts @@ -11,8 +11,8 @@ * them: it imports `selfhost/build.ts`, whose graph the walker must see, so this guard cannot * pass because the walker went blind. */ -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { relative, resolve } from 'node:path'; import * as TOML from '@iarna/toml'; import { describe, expect, it } from 'vitest'; @@ -23,6 +23,7 @@ import { API_SRC, CLOUDFLARE_ENTRY_FORBIDDEN_PATHS, collectImportGraph, + GRAPH_WALK_TIMEOUT_MS, REPO_ROOT, selfhostOnlyFindings, } from '../../helpers/selfhost-only-modules'; @@ -38,10 +39,25 @@ function celldEntryImports(): string[] { .map((specifier) => resolve(API_SRC, specifier.slice(prefix.length))); } -/** Walking a >1,000-file import graph takes several seconds on a loaded CI runner. */ -const GRAPH_WALK_TIMEOUT_MS = 60_000; - describe('self-host-only code stays out of the Cloudflare Worker', () => { + it('detects real imports of the hosted DO, vendored git and pako', () => { + const scratchRoot = resolve(REPO_ROOT, '.tmp'); + mkdirSync(scratchRoot, { recursive: true }); + const scratch = mkdtempSync(resolve(scratchRoot, 'hosted-git-graph-')); + const entry = resolve(scratch, 'entry.ts'); + const doPath = 'apps/api/src/selfhost/hosted-git/hosted-git-repo.ts'; + try { + writeFileSync(entry, `import '${relative(scratch, resolve(REPO_ROOT, doPath))}';`); + const graph = collectImportGraph(entry); + const findings = selfhostOnlyFindings(graph, CLOUDFLARE_ENTRY_FORBIDDEN_PATHS); + expect(findings).toContain(doPath); + expect(findings.some((path) => path.startsWith('apps/api/src/vendor/dgit/'))).toBe(true); + expect(findings.some((path) => path.startsWith('package pako '))).toBe(true); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } + }); + it('control: the actual metadata broker graph is forbidden to the Worker', () => { const graph = collectImportGraph( resolve(REPO_ROOT, 'deploy/selfhost/metadata-proxy/server.ts') diff --git a/apps/api/tests/unit/services/hosted-git-backend.test.ts b/apps/api/tests/unit/services/hosted-git-backend.test.ts index ba87fa85e5..8aeb198998 100644 --- a/apps/api/tests/unit/services/hosted-git-backend.test.ts +++ b/apps/api/tests/unit/services/hosted-git-backend.test.ts @@ -16,7 +16,7 @@ import { isArtifactsAvailable, registerArtifactsBackendFallback, resolveArtifactsBackend, -} from '../../../src/services/hosted-git/backend'; +} from '../../../src/services/artifacts/backend'; function backend(label: string): ArtifactsBackend { return { diff --git a/apps/api/tests/unit/services/hosted-git/tokens-and-limits.test.ts b/apps/api/tests/unit/services/hosted-git/tokens-and-limits.test.ts new file mode 100644 index 0000000000..c4688a65a4 --- /dev/null +++ b/apps/api/tests/unit/services/hosted-git/tokens-and-limits.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it } from 'vitest'; + +import type { HostedGitEnv as Env } from '../../../../src/selfhost/hosted-git/env'; +import { parseHostedGitPath } from '../../../../src/selfhost/hosted-git/http'; +import { + DEFAULT_HOSTED_GIT_LIMITS, + hostedGitPushByteBudget, + hostedGitPushRefusal, +} from '../../../../src/selfhost/hosted-git/limits'; +import { + createDurableObjectArtifactsBackend, + isLocalHostedGitActive, + localHostedGitBackendFallback, +} from '../../../../src/selfhost/hosted-git/local-backend'; +import { + clampHostedGitTokenTtl, + MAX_HOSTED_GIT_TOKEN_TTL_SECONDS, + mintHostedGitToken, + verifyHostedGitToken, +} from '../../../../src/selfhost/hosted-git/tokens'; +import { + isArtifactsAvailable, + registerArtifactsBackendFallback, + resolveArtifactsBackend, +} from '../../../../src/services/artifacts/backend'; + +const env = { ENCRYPTION_KEY: 'test-encryption-key-for-hosted-git' }; +const otherEnv = { ENCRYPTION_KEY: 'a-different-installation-key' }; + +describe('hosted git tokens', () => { + it('round-trips repo, scope, expiry and workspace binding', async () => { + const now = Date.UTC(2026, 10, 12); + const { token, expiresAt } = await mintHostedGitToken( + env, + { repo: 'demo-01abc', scope: 'write', ttlSeconds: 600, workspaceId: 'ws-1' }, + now + ); + expect(token.startsWith('samgit1.')).toBe(true); + expect(expiresAt).toBe(new Date(now + 600_000).toISOString()); + await expect(verifyHostedGitToken(env, token, now)).resolves.toEqual({ + repo: 'demo-01abc', + scope: 'write', + exp: now / 1000 + 600, + workspaceId: 'ws-1', + callbackGeneration: null, + }); + }); + + it('rejects expired, tampered and foreign-key tokens', async () => { + const now = Date.UTC(2026, 10, 12); + const { token } = await mintHostedGitToken( + env, + { repo: 'demo-01abc', scope: 'read', ttlSeconds: 60 }, + now + ); + await expect(verifyHostedGitToken(env, token, now + 61_000)).resolves.toBeNull(); + await expect(verifyHostedGitToken(otherEnv, token, now)).resolves.toBeNull(); + const [prefix, payload, signature] = token.split('.') as [string, string, string]; + const claims = JSON.parse(Buffer.from(payload, 'base64url').toString()); + const forged = Buffer.from(JSON.stringify({ ...claims, scope: 'write' })).toString('base64url'); + await expect( + verifyHostedGitToken(env, `${prefix}.${forged}.${signature}`, now) + ).resolves.toBeNull(); + await expect(verifyHostedGitToken(env, 'not-a-token', now)).resolves.toBeNull(); + // Control: the untouched token verifies. + await expect(verifyHostedGitToken(env, token, now)).resolves.not.toBeNull(); + }); + + it('clamps the TTL to 1 s..24 h with a 1 h default', () => { + expect(clampHostedGitTokenTtl(undefined)).toBe(3600); + expect(clampHostedGitTokenTtl(-5)).toBe(3600); + expect(clampHostedGitTokenTtl(Number.NaN)).toBe(3600); + expect(clampHostedGitTokenTtl(10 * 86_400)).toBe(MAX_HOSTED_GIT_TOKEN_TTL_SECONDS); + expect(clampHostedGitTokenTtl(0.5)).toBe(1); + }); + + it('refuses to mint for a name SAM would never generate', async () => { + await expect(mintHostedGitToken(env, { repo: '../etc', scope: 'read' })).rejects.toThrow(); + }); +}); + +describe('hosted git path parsing', () => { + it('accepts /git/.git/ and rejects anything else', () => { + expect(parseHostedGitPath('/git/demo-01abc.git/info/refs')).toEqual({ + repo: 'demo-01abc', + subPath: '/info/refs', + }); + expect(parseHostedGitPath('/git/demo-01abc/git-upload-pack')?.repo).toBe('demo-01abc'); + expect(parseHostedGitPath('/git/Demo/info/refs')).toBeNull(); + expect(parseHostedGitPath('/git/../x/info/refs')).toBeNull(); + expect(parseHostedGitPath('/api/git/demo/info/refs')).toBeNull(); + }); +}); + +describe('hosted git caps', () => { + const limits = DEFAULT_HOSTED_GIT_LIMITS; + it('refuses a push that would cross the object cap and allows one that fits', () => { + expect( + hostedGitPushRefusal({ objects: 100, bytes: 0 }, limits.maxRepoObjects - 100, limits) + ).toBeNull(); + expect( + hostedGitPushRefusal({ objects: 100, bytes: 0 }, limits.maxRepoObjects - 99, limits) + ).toContain(`${limits.maxRepoObjects}-object limit`); + }); + + it('refuses any push to a repository already at its storage cap', () => { + expect(hostedGitPushRefusal({ objects: 1, bytes: limits.maxRepoBytes }, 1, limits)).toContain( + 'storage limit' + ); + }); + + it('shrinks the per-push byte budget as the repository fills', () => { + expect(hostedGitPushByteBudget(0, limits)).toBe(limits.maxPushBytes); + expect(hostedGitPushByteBudget(limits.maxRepoBytes - 10, limits)).toBe(10); + expect(hostedGitPushByteBudget(limits.maxRepoBytes + 10, limits)).toBe(0); + }); +}); + +describe('backend resolution', () => { + const namespace = {} as DurableObjectNamespace; + const cloudflareBinding = { create: async () => ({}) } as never; + + it('keeps Cloudflare Artifacts when the binding exists, even with the hosted backend configured', () => { + const cf = { + ARTIFACTS_ENABLED: 'true', + ARTIFACTS: cloudflareBinding, + HOSTED_GIT: namespace, + HOSTED_GIT_BACKEND: 'durable-object', + BASE_DOMAIN: 'example.com', + }; + expect(resolveArtifactsBackend(cf)).toBe(cloudflareBinding); + expect(isLocalHostedGitActive(cf)).toBe(false); + }); + + it('is unavailable on Cloudflare installs without the binding or the backend switch', () => { + // Defense in depth: even with a HOSTED_GIT namespace present (only the self-host build binds + // it), the switch and ARTIFACTS_ENABLED must both select it. + expect( + isArtifactsAvailable({ + ARTIFACTS_ENABLED: 'true', + HOSTED_GIT: namespace, + BASE_DOMAIN: 'example.com', + }) + ).toBe(false); + expect( + isArtifactsAvailable({ + ARTIFACTS_ENABLED: 'false', + HOSTED_GIT: namespace, + HOSTED_GIT_BACKEND: 'durable-object', + BASE_DOMAIN: 'example.com', + }) + ).toBe(false); + }); + + it('resolves the local backend on self-host and builds remotes under api.', async () => { + const selfhost = { + ARTIFACTS_ENABLED: 'true', + HOSTED_GIT: namespace, + HOSTED_GIT_BACKEND: 'durable-object', + BASE_DOMAIN: 'box.example', + }; + // Only the self-host build registers the local backend (selfhost/hosted-git.ts). + expect(isArtifactsAvailable(selfhost as unknown as Env)).toBe(false); + registerArtifactsBackendFallback(localHostedGitBackendFallback); + try { + expect(isArtifactsAvailable(selfhost as unknown as Env)).toBe(true); + expect(isLocalHostedGitActive(selfhost)).toBe(true); + expect(resolveArtifactsBackend(selfhost as unknown as Env)).not.toBeNull(); + expect(typeof createDurableObjectArtifactsBackend(selfhost).get).toBe('function'); + } finally { + registerArtifactsBackendFallback(null); + } + }); +}); + +describe('workspace identity through the generic backend seam', () => { + it('binds a repository credential to its user and current workspace generation', async () => { + const backend = createDurableObjectArtifactsBackend({ + ...env, + BASE_DOMAIN: 'example.test', + HOSTED_GIT_BACKEND: 'durable-object', + HOSTED_GIT: { + idFromName: (name: string) => name, + get: () => ({ fetch: async () => Response.json({ head: 'refs/heads/main' }) }), + }, + } as unknown as Env); + const repo = await backend.get('demo-01abc'); + const result = await repo.createToken('write', 60, { + userId: 'u1', + workspaceId: 'w1', + callbackGeneration: 'g2', + }); + const claims = await verifyHostedGitToken(env, result.plaintext); + expect(claims).toMatchObject({ + repo: 'demo-01abc', + scope: 'write', + userId: 'u1', + workspaceId: 'w1', + callbackGeneration: 'g2', + }); + }); +}); diff --git a/apps/api/vitest.config.ts b/apps/api/vitest.config.ts index fce3c88337..38e93faf81 100644 --- a/apps/api/vitest.config.ts +++ b/apps/api/vitest.config.ts @@ -20,7 +20,7 @@ export default defineConfig({ globals: true, setupFiles: ['./tests/setup/project-data-ports.ts', './tests/setup/repo-hosting-ports.ts'], include: ['tests/**/*.test.ts'], - exclude: ['tests/workers/**'], + exclude: ['tests/workers/**', 'tests/hosted-git/**'], coverage: coverageConfig(['src/**/*.ts'], { statements: 45, branches: 40, diff --git a/apps/api/vitest.hosted-git.config.ts b/apps/api/vitest.hosted-git.config.ts new file mode 100644 index 0000000000..5bcff41262 --- /dev/null +++ b/apps/api/vitest.hosted-git.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'vitest/config'; + +/** + * Hosted git conformance: the real git CLI against the HostedGitRepo Durable Object running in + * Miniflare (tests/hosted-git/support/hosted-git-runtime.ts). Needs `git` on PATH. + */ +export default defineConfig({ + test: { + include: ['tests/hosted-git/**/*.test.ts'], + testTimeout: 120_000, + hookTimeout: 120_000, + fileParallelism: false, + }, +}); diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 62fd63d958..afe606c491 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -199,6 +199,38 @@ headers, no query strings, and no credentials in the path on the routes listed i `caddy/log-redaction.caddy` (bootstrap, invite and AI-proxy tokens, preview signatures). `docker compose logs celld` is the Worker's output. +## SAM-hosted repositories + +The celld build enables SAM-hosted git. Create a project with the Artifacts repository option; +SAM seeds an empty repository so an agent can clone, commit and push without a GitHub App. +The repository Durable Object and its `selfhost-hosted-git-v1` migration exist only in celld. +The Cloudflare Worker never includes them. + +Public repository import is unavailable in this slice; an import URL returns a clear 400. +A bounded importer is tracked in `tasks/backlog/2026-11-19-bounded-selfhost-git-import.md`. +GitHub and GitLab integrations remain available when configured. + +Admin → Settings exposes `repositories.*` limits. Failed GC sweeps retry up to +`repositories.maxGcAttempts` (default 3), five minutes apart; success resets the budget. +Exhaustion preserves a failed marker and emits `hosted_git.gc_failed`; a later admitted push +starts a new cleanup episode. Failed pack ingestion reclaims incomplete rows before the next +push checks quota. Defaults are 64 MiB per push, 30,000 objects +10,000 refs and 256 MiB stored per repository, 16 MiB per inflated object, 128 MiB cumulative inflation +per request, delta depth 100 and 120 seconds per git operation. Operators can lower these +limits; raising them needs measured capacity review. Rejected pushes leave existing refs intact. +The storage limit is checked again after a pack and its index are stored; a push that crosses it +is refused and its pack dropped at once. +Like git, push ingest hashes every object with SHA-1 collision detection (SHA-1DC) and refuses +a push carrying a SHA-1 collision-attack block before any ref changes. +GC first drops whole packs that hold nothing reachable (for example a rejected push) without +inflating them. Known limit: moving the remaining reachable packed objects to loose storage +inflates each one under the same decompression budget, so that step cannot finish while more than +`repositories.maxInflatedBytes` of reachable pushed content waits for collection. Tracked in +`tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md`. +Clone/push credentials expire and runtime credentials also require the same active workspace +and callback generation. Deleting a project removes its hosted repository. At the ref limit, delete old refs in a separate +push before creating replacements; an unvalidated deletion does not reserve space for new refs. + ## Not included yet This version runs in plaintext mode: celld keeps every Worker secret in plaintext in the fleet @@ -206,10 +238,6 @@ bucket's deploy manifests, so the bucket credential is the install's master key. - **Sealed secrets**: no key agent or KMS-backed encryption of the Worker's secrets. - **Guided credential login** (sandboxed agent sign-in on the box). -- **Hosted git.** Every project needs a repository, so on this install users can create projects - and run agents only once a GitHub App (the `GITHUB_*` Worker secrets in `.state/secrets.env`) - or a GitLab integration is configured. - Without one, sign-in, administration and nodes work, but no agent session can start. - **Backup, restore and teardown** commands. Back up the fleet bucket and `.state/` yourself. Do not put data on this box that you could not afford to lose or leak. diff --git a/packages/repo-hosting/src/env.ts b/packages/repo-hosting/src/env.ts index fed4cd1c50..f9c99e4648 100644 --- a/packages/repo-hosting/src/env.ts +++ b/packages/repo-hosting/src/env.ts @@ -1,5 +1,24 @@ /** The Cloudflare Artifacts binding (SAM-native Git repositories). */ +/** Identity of the caller minting a repository credential. Backends may bind it to a runtime. */ +export interface ArtifactsTokenContext { + userId: string; + workspaceId?: string; + callbackGeneration?: string | null; +} + export type ArtifactsBinding = { + /** Optional in-process transport registered by a self-host backend. */ + remoteFetch?: typeof fetch; + /** Optional import capability; absent on the Cloudflare binding. */ + importSource?: { + defaultBranch(sourceUrl: string): Promise; + populate(params: { + sourceUrl: string; + branch: string; + remote: string; + token: string; + }): Promise; + }; create( name: string, opts?: { description?: string; setDefaultBranch?: string } @@ -18,7 +37,8 @@ export type ArtifactsBinding = { defaultBranch: string; createToken( scope?: 'read' | 'write', - ttl?: number + ttl?: number, + context?: ArtifactsTokenContext ): Promise<{ id: string; plaintext: string; diff --git a/packages/repo-hosting/src/index.ts b/packages/repo-hosting/src/index.ts index 2a2f62c9d1..9fce968041 100644 --- a/packages/repo-hosting/src/index.ts +++ b/packages/repo-hosting/src/index.ts @@ -64,3 +64,5 @@ export { verifyGitLabProjectAccess, } from './gitlab'; export { type RepoBrowser, resolveRepoBrowser } from './repo-browse'; +export { createFetchHttpClient } from './repo-browse/fetch-http-client'; +export { MemoryFS } from './repo-browse/memory-fs'; diff --git a/packages/repo-hosting/src/ports.ts b/packages/repo-hosting/src/ports.ts index 5cc25faf79..20dc76b25c 100644 --- a/packages/repo-hosting/src/ports.ts +++ b/packages/repo-hosting/src/ports.ts @@ -45,7 +45,7 @@ export interface AuthPort { /** * The SAM-native repository backend (`ARTIFACTS`). On Cloudflare it is the Artifacts binding; a - * self-hosted install may register its own (the worker's `services/hosted-git/backend.ts`). + * self-hosted install may register its own (the worker's `services/artifacts/backend.ts`). */ export interface ArtifactsBackendPort { /** The backend this install uses for SAM-native repositories, or null when it has none. */ diff --git a/packages/repo-hosting/src/repo-browse/artifacts.ts b/packages/repo-hosting/src/repo-browse/artifacts.ts index 1fa437ea6b..19756ed8fe 100644 --- a/packages/repo-hosting/src/repo-browse/artifacts.ts +++ b/packages/repo-hosting/src/repo-browse/artifacts.ts @@ -9,10 +9,11 @@ import type { import { errors } from '@simple-agent-manager/worker-core'; import { createPatch } from 'diff'; import git from 'isomorphic-git'; -import http from 'isomorphic-git/http/web'; +import webHttp from 'isomorphic-git/http/web'; import type { Env } from '../env'; import { repoHostingPorts } from '../ports'; +import { createFetchHttpClient } from './fetch-http-client'; import { MemoryFS } from './memory-fs'; import type { RepoBrowser } from './types'; import { basename, guessContentType, isBinaryBytes, maxCompareFiles, maxInlineBytes } from './util'; @@ -27,6 +28,7 @@ type OnAuth = Parameters[0]['onAuth']; interface ArtifactsRepoInfo { remote: string; onAuth: OnAuth; + http: Parameters[0]['http']; } function countPatchLines(patch: string): { additions: number; deletions: number } { @@ -177,7 +179,12 @@ export class ArtifactsRepoBrowser implements RepoBrowser { if (!remote) { throw errors.badRequest('Artifacts repository has no resolvable clone URL'); } - return { remote, onAuth }; + return { + remote, + onAuth, + // Native RPC bindings fabricate unknown methods; extensions belong to the fallback. + http: !this.env.ARTIFACTS && binding.remoteFetch ? createFetchHttpClient(binding.remoteFetch) : webHttp, + }; })(); } return this.infoPromise; @@ -185,7 +192,7 @@ export class ArtifactsRepoBrowser implements RepoBrowser { /** Shallow single-branch clone of `ref` into a fresh in-memory fs. */ private async cloneRef(ref: string): Promise { - const { remote, onAuth } = await this.info(); + const { remote, onAuth, http } = await this.info(); const fs = new MemoryFS() as unknown as IsoFs; // noCheckout: we read objects via walk/readBlob, never the working tree — this // avoids writing a second copy of every blob into the in-memory fs. @@ -204,7 +211,7 @@ export class ArtifactsRepoBrowser implements RepoBrowser { } async listBranches(): Promise { - const { remote, onAuth } = await this.info(); + const { remote, onAuth, http } = await this.info(); const refs = await git.listServerRefs({ http, url: remote, @@ -262,7 +269,7 @@ export class ArtifactsRepoBrowser implements RepoBrowser { } async compare(base: string, head: string): Promise { - const { remote, onAuth } = await this.info(); + const { remote, onAuth, http } = await this.info(); const fs = new MemoryFS() as unknown as IsoFs; await git.clone({ fs, diff --git a/packages/repo-hosting/src/repo-browse/fetch-http-client.ts b/packages/repo-hosting/src/repo-browse/fetch-http-client.ts new file mode 100644 index 0000000000..acdf426408 --- /dev/null +++ b/packages/repo-hosting/src/repo-browse/fetch-http-client.ts @@ -0,0 +1,69 @@ +/** + * An isomorphic-git HTTP client over an injected fetch. `isomorphic-git/http/web` always uses the + * global fetch; SAM-hosted repositories are browsed in-process (`artifactsRemoteFetch`), so the + * browser needs a client that takes the fetch as a parameter. Same request/response contract as + * `isomorphic-git/http/web`. + */ +import type { HttpClient } from 'isomorphic-git'; + +async function collect(body: AsyncIterableIterator | undefined): Promise { + if (!body) return new Uint8Array(0); + const parts: Uint8Array[] = []; + let size = 0; + for await (const part of body) { + parts.push(part); + size += part.byteLength; + } + const out = new Uint8Array(size); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.byteLength; + } + return out; +} + +async function* streamChunks( + stream: ReadableStream | null +): AsyncGenerator { + if (!stream) return; + const reader = stream.getReader(); + let finished = false; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) { + finished = true; + return; + } + if (value) yield value; + } + } finally { + // A consumer that stops early (isomorphic-git abandons the iterator when pack parsing + // throws) must cancel the response, or its producer, such as a hosted repository's + // upload slot, stays held until the stream is garbage collected. + if (!finished) await reader.cancel().catch(() => undefined); + reader.releaseLock(); + } +} + +export function createFetchHttpClient(fetchImpl: typeof fetch): HttpClient { + return { + async request({ url, method = 'GET', headers = {}, body }) { + const payload = body ? await collect(body) : undefined; + const res = await fetchImpl(url, { method, headers, body: payload }); + const responseHeaders: Record = {}; + res.headers.forEach((value, key) => { + responseHeaders[key] = value; + }); + return { + url: res.url || url, + method, + statusCode: res.status, + statusMessage: res.statusText, + body: streamChunks(res.body), + headers: responseHeaders, + }; + }, + }; +} diff --git a/packages/repo-hosting/tests/unit/fetch-http-client.test.ts b/packages/repo-hosting/tests/unit/fetch-http-client.test.ts new file mode 100644 index 0000000000..f13239b7e3 --- /dev/null +++ b/packages/repo-hosting/tests/unit/fetch-http-client.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { createFetchHttpClient } from '../../src/repo-browse/fetch-http-client'; + +/** A response whose stream records whether it was cancelled (Codex r4636466068). */ +function trackedResponse(chunks: number) { + const cancel = vi.fn(); + let sent = 0; + const body = new ReadableStream({ + pull(controller) { + if (sent++ < chunks) controller.enqueue(new Uint8Array([sent])); + else controller.close(); + }, + cancel, + }); + return { response: new Response(body), cancel }; +} + +describe('createFetchHttpClient response body', () => { + it('cancels the upstream response when the consumer abandons the iterator early', async () => { + const { response, cancel } = trackedResponse(10); + const client = createFetchHttpClient(async () => response); + const res = await client.request({ url: 'https://repo.example/info/refs', method: 'GET' }); + const body = res.body as AsyncIterableIterator; + expect((await body.next()).done).toBe(false); + await body.return?.(undefined); // what a for-await `break` or a thrown parse error does + expect(cancel).toHaveBeenCalledOnce(); + }); + + it('does not cancel a response read to the end', async () => { + const { response, cancel } = trackedResponse(3); + const client = createFetchHttpClient(async () => response); + const res = await client.request({ url: 'https://repo.example/info/refs', method: 'GET' }); + let seen = 0; + for await (const chunk of res.body as AsyncIterableIterator) seen += chunk.length; + expect(seen).toBe(3); + expect(cancel).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts b/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts index af51341062..31fbf6333a 100644 --- a/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts +++ b/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts @@ -71,11 +71,15 @@ describe('resolveRepoBrowser for Artifacts projects', () => { }); it('uses the Cloudflare binding directly when present (unchanged)', async () => { - const binding = hostedBackend(); + const binding = new Proxy(hostedBackend(), { get(target, property, receiver) { + if (!(property in target)) return vi.fn().mockRejectedValue(new Error('Unknown RPC method')); + return Reflect.get(target, property, receiver); + } }); resolve.mockImplementation((env) => env.ARTIFACTS ?? null); const env = { ARTIFACTS_ENABLED: 'true', ARTIFACTS: binding } as Env; const browser = await resolveRepoBrowser({ project, env }); await browser.listBranches(); expect(binding.get).toHaveBeenCalledWith('repo-1'); + expect(iso.listServerRefs).toHaveBeenCalledWith(expect.objectContaining({ http: {} })); }); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5421ac0063..bb0c0b0f0d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -324,6 +324,9 @@ importers: jose: specifier: 'catalog:' version: 6.2.3 + pako: + specifier: ^2.1.0 + version: 2.2.0 tsx: specifier: 'catalog:' version: 4.23.1 @@ -352,6 +355,9 @@ importers: '@types/diff': specifier: ^8.0.0 version: 8.0.0 + '@types/pako': + specifier: ^2.0.3 + version: 2.0.4 '@typescript-eslint/eslint-plugin': specifier: 'catalog:' version: 8.72.0(@typescript-eslint/parser@8.72.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) @@ -4999,6 +5005,9 @@ packages: '@types/node@26.5.0': resolution: {integrity: sha512-dVSGpriSoCgz8WnDNTuSSuSv1PC/ALXihO4ulRZt7Md8k9mlbdin3lGOcDE8SnWOgf513ByWlXd7BK4azmyg/A==} + '@types/pako@2.0.4': + resolution: {integrity: sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==} + '@types/prismjs@1.26.6': resolution: {integrity: sha512-vqlvI7qlMvcCBbVe0AKAb4f97//Hy0EBTaiW8AalRnG/xAN5zOiWWyrNqNXeq8+KAuvRewjCVY1+IPxk4RdNYw==} @@ -8331,6 +8340,9 @@ packages: pako@1.0.11: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} + pako@2.2.0: + resolution: {integrity: sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==} + parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -13526,6 +13538,8 @@ snapshots: dependencies: undici-types: 8.9.0 + '@types/pako@2.0.4': {} + '@types/prismjs@1.26.6': {} '@types/react-dom@19.3.0(@types/react@19.3.0)': @@ -17740,6 +17754,8 @@ snapshots: pako@1.0.11: {} + pako@2.2.0: {} + parent-module@1.0.1: dependencies: callsites: 3.1.0 diff --git a/scripts/quality/ci-suite-selection.test.ts b/scripts/quality/ci-suite-selection.test.ts index cce92234b4..3c0188e7de 100644 --- a/scripts/quality/ci-suite-selection.test.ts +++ b/scripts/quality/ci-suite-selection.test.ts @@ -375,7 +375,8 @@ function crossReads( const walk = (current: string) => { if (!existsSync(current)) return; for (const entry of readdirSync(current)) { - if (['node_modules', 'dist', '.astro', 'coverage', 'test-results'].includes(entry)) continue; + if (['node_modules', 'dist', '.astro', '.tmp', 'coverage', 'test-results'].includes(entry)) + continue; const full = join(current, entry); if (statSync(full).isDirectory()) walk(full); else if (CODE_FILE.test(entry)) queue.push(full); @@ -389,6 +390,8 @@ function crossReads( for (const { path, imported } of references(file)) { const repoPath = relative(REPO_ROOT, path); if (repoPath === '' || repoPath.startsWith('..')) continue; + // Generated scratch is output, never a checked-in suite input. + if (repoPath === '.tmp' || repoPath.startsWith('.tmp/')) continue; if (repoPath.startsWith(`${scanned}/`)) { if (imported && CODE_FILE.test(path) && statSync(path).isFile() && !seen.has(path)) { seen.add(path); @@ -420,6 +423,18 @@ function suiteReads(suite: (typeof SUITES)[number]): Array<{ file: string; path: } describe('every file a suite reads outside its package is in its filter', () => { + it('runs real git through its dedicated config exactly once in the selected API matrix', () => { + const job = loadWorkflow().jobs['test-api']!; + const step = job.steps!.find( + (entry) => entry.name === 'Hosted git conformance and celld bundle' + )!; + expect(job.if).toContain("needs.changes.outputs.api-unit == 'true'"); + expect(step.if).toBe('matrix.shard == 1'); + expect(step.run).toBe('pnpm --filter @simple-agent-manager/api test:hosted-git'); + const buildIndex = job.steps!.findIndex((entry) => entry.name === 'Build API dependencies'); + expect(buildIndex).toBeGreaterThanOrEqual(0); + expect(job.steps!.findIndex((entry) => entry === step)).toBeGreaterThan(buildIndex); + }); it.each(SUITES.map((suite) => [suite.output, suite] as const))( '%s', (_, suite) => { @@ -452,6 +467,8 @@ describe('every file a suite reads outside its package is in its filter', () => ); expect(apiReads.some((path) => path.startsWith('packages/vm-agent/'))).toBe(true); expect(apiReads).toContain('apps/tail-worker/src/x'); + expect(apiReads.some((path) => path === '.tmp' || path.startsWith('.tmp/'))).toBe(false); + expect(apiReads).toContain('scripts/selfhost/celld-binary.ts'); // Reached only by following a web module's own imports (lineage test -> useTaskGroups). expect(apiReads).toContain('apps/web/src/lib/api/client.ts'); // Without the vm-agent extra the API unit filter would miss them. diff --git a/scripts/quality/direct-dependency-evidence.json b/scripts/quality/direct-dependency-evidence.json index 1d2b30e6c9..b21c4957e5 100644 --- a/scripts/quality/direct-dependency-evidence.json +++ b/scripts/quality/direct-dependency-evidence.json @@ -92,6 +92,11 @@ "registryUrl": "https://www.npmjs.com/package/@types/node", "necessity": "Types for node:crypto, which project-data's archive hashing uses under the Worker's nodejs_compat; same catalog version as the root." }, + "@types/pako": { + "registryUrl": "https://www.npmjs.com/package/@types/pako", + "homepageUrl": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/pako", + "necessity": "Type declarations for the pako incremental compression API used by the self-host git engine and its resource-boundary tests." + }, "@typescript-eslint/eslint-plugin": { "registryUrl": "https://www.npmjs.com/package/@typescript-eslint/eslint-plugin", "necessity": "Hosts supported TypeScript lint rules." @@ -176,6 +181,11 @@ "registryUrl": "https://www.npmjs.com/package/oxlint", "necessity": "Measures native lint findings in shadow mode." }, + "pako": { + "registryUrl": "https://www.npmjs.com/package/pako", + "homepageUrl": "https://github.com/nodeca/pako", + "necessity": "Incremental zlib Inflate callbacks let the self-host-only git engine enforce output budgets before retaining decompressed objects; native one-shot decompression cannot apply those bounds. Excluded from the Cloudflare import graph." + }, "postal-mime": { "registryUrl": "https://www.npmjs.com/package/postal-mime", "homepageUrl": "https://github.com/postalsys/postal-mime", diff --git a/scripts/selfhost/celld-config.test.ts b/scripts/selfhost/celld-config.test.ts index 5b5b1a44a6..c645b5280d 100644 --- a/scripts/selfhost/celld-config.test.ts +++ b/scripts/selfhost/celld-config.test.ts @@ -67,10 +67,11 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { } }); - it('runs no container and leaves SAM-native git off', () => { + it('runs no container and enables the self-host git fallback', () => { expect(config).not.toHaveProperty('containers'); - // No Artifacts binding and no other backend registered: resolveArtifactsBackend is null. - expect(config.vars.ARTIFACTS_ENABLED).not.toBe('true'); + // The self-host build registers the backend; Cloudflare keeps its own configuration. + expect(config.vars.ARTIFACTS_ENABLED).toBe('true'); + expect(config.vars.HOSTED_GIT_BACKEND).toBe('durable-object'); }); it('folds every legacy new_classes create into new_sqlite_classes, keeping tag order', () => { @@ -80,8 +81,11 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { new_sqlite_classes?: string[]; }>; expect(sourceMigrations.some((m) => m.new_classes?.length)).toBe(true); - // wrangler.toml's tags, in order, and nothing else. - expect(config.migrations.map((m) => m.tag)).toEqual(sourceMigrations.map((m) => m.tag)); + // Keep shared tags in order, then append the celld-only tag. + expect(config.migrations.map((m) => m.tag)).toEqual([ + ...sourceMigrations.map((m) => m.tag), + 'selfhost-hosted-git-v1', + ]); for (const migration of config.migrations) { expect(Object.keys(migration).sort()).toEqual(['new_sqlite_classes', 'tag']); } @@ -90,13 +94,15 @@ describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { ...(m.new_sqlite_classes ?? []), ...(m.new_classes ?? []), ]); - expect(new Set(created)).toEqual(new Set(expected)); + expect(new Set(created)).toEqual(new Set([...expected, 'HostedGitRepo'])); }); - it('binds exactly the Durable Objects wrangler.toml binds', () => { - expect(config.durable_objects.bindings).toEqual( - (source.durable_objects as { bindings: Array<{ name: string; class_name: string }> }).bindings - ); + it('adds only HostedGitRepo to the shared Durable Object bindings', () => { + expect(config.durable_objects.bindings).toEqual([ + ...(source.durable_objects as { bindings: Array<{ name: string; class_name: string }> }) + .bindings, + { name: 'HOSTED_GIT', class_name: 'HostedGitRepo' }, + ]); }); it('keeps container DO bindings (the classes stay exported) but not their containers', () => { diff --git a/scripts/selfhost/celld-config.ts b/scripts/selfhost/celld-config.ts index 90ecd6d418..1fa8780e4b 100644 --- a/scripts/selfhost/celld-config.ts +++ b/scripts/selfhost/celld-config.ts @@ -14,11 +14,14 @@ import { resolveDurableObjectMigrations } from '../deploy/durable-object-migrations.js'; import type { MigrationEntry, WranglerToml } from '../deploy/types.js'; +import { appendSelfhostDurableObjects } from './selfhost-durable-objects.js'; /** Worker vars set for every celld deployment, overriding wrangler.toml [vars]. */ export const SELFHOST_VAR_OVERRIDES: Readonly> = { // Cloudflare Containers: Instant sessions and the Sandbox SDK. celld's container fence // blocks container -> host traffic on a one-box install (idea 01M72M9AEB933ZY8269D376DKC). + HOSTED_GIT_BACKEND: 'durable-object', + ARTIFACTS_ENABLED: 'true', CF_CONTAINER_ENABLED: 'false', SANDBOX_ENABLED: 'false', // Managed devcontainer cache uses the Cloudflare container registry API. @@ -425,6 +428,7 @@ export function buildCelldConfig( const ctx = translateTopLevelKeys(source, options); const out = ctx.out as CelldWranglerConfig; + appendSelfhostDurableObjects(out, ctx.plan.report); out.compatibility_flags ??= []; const r2 = out.r2_buckets.find((bucket) => bucket.binding === 'R2'); out.vars = { diff --git a/scripts/selfhost/celld-project.test.ts b/scripts/selfhost/celld-project.test.ts index d453190cea..d02726b664 100644 --- a/scripts/selfhost/celld-project.test.ts +++ b/scripts/selfhost/celld-project.test.ts @@ -53,18 +53,18 @@ describe('prepareCelldProject', () => { prepareCelldProject({ apiDir: API_DIR, projectDir, plan: plan() }); const main = readFileSync(join(projectDir, CELLD_MAIN), 'utf8'); expect(main).toBe(renderCelldMain()); - expect(main).toContain("import worker from './src/index.ts';"); + expect(main).toContain("import worker, { app } from './src/index.ts';"); expect(main).toContain('resumeSharedFlightJoinsOnOwnTimer();'); expect(main).toContain("export * from './src/index.ts';"); - expect(main).toContain('export default withSelfHostBuild(worker);'); + expect(main).toContain('export default withSelfHostBuild(worker, app);'); // Every module the entry imports exists in apps/api (the symlinked src). const specifiers = [...main.matchAll(/from '\.\/src\/([^']+)'/g)].map((m) => m[1]!); expect(specifiers.length).toBeGreaterThanOrEqual(3); for (const specifier of specifiers) { expect(existsSync(join(API_DIR, 'src', specifier)), specifier).toBe(true); } - // Nothing but the shared entry's own exports and the default. - expect(main.match(/^export /gm)).toHaveLength(2); + // Shared exports, the self-host-only DO, and the default. + expect(main.match(/^export /gm)).toHaveLength(3); expect(statSync(join(projectDir, CELLD_MAIN)).mode & 0o777).toBe(0o600); }); diff --git a/scripts/selfhost/celld-project.ts b/scripts/selfhost/celld-project.ts index 54b8122ea9..538569fbfd 100644 --- a/scripts/selfhost/celld-project.ts +++ b/scripts/selfhost/celld-project.ts @@ -24,6 +24,7 @@ import type { CelldConfigPlan, CelldWranglerConfig } from './celld-config.js'; import { appendSelfhostObservabilityMigrations } from './observability-migrations.js'; import { appendReverseTunnelMigrations } from './reverse-tunnel-migrations.js'; import { writePrivateFile } from './secret-files.js'; +import { SELFHOST_DURABLE_OBJECTS, SELFHOST_ENTRY_MODULE } from './selfhost-durable-objects.js'; export const CONFIG_FILE = 'wrangler.json'; export const SOURCE_LINK = 'src'; @@ -52,13 +53,16 @@ const OBSERVABILITY_MIGRATIONS_DIR = 'src/db/migrations/observability'; export function renderCelldMain(): string { return [ '// Generated by scripts/selfhost/celld-project.ts (renderCelldMain). Do not edit.', - `import worker from './${SOURCE_LINK}/index.ts';`, + `import worker, { app } from './${SOURCE_LINK}/index.ts';`, `import { resumeSharedFlightJoinsOnOwnTimer } from './${SOURCE_LINK}/lib/shared-flight.ts';`, - `import { withSelfHostBuild } from './${SOURCE_LINK}/selfhost/build.ts';`, + `import { withSelfHostBuild } from './${SOURCE_LINK}/${SELFHOST_ENTRY_MODULE}';`, '', 'resumeSharedFlightJoinsOnOwnTimer();', `export * from './${SOURCE_LINK}/index.ts';`, - 'export default withSelfHostBuild(worker);', + ...SELFHOST_DURABLE_OBJECTS.map( + ({ className }) => `export { ${className} } from './${SOURCE_LINK}/${SELFHOST_ENTRY_MODULE}';` + ), + 'export default withSelfHostBuild(worker, app);', '', ].join('\n'); } diff --git a/scripts/selfhost/hosted-git-smoke.sh b/scripts/selfhost/hosted-git-smoke.sh new file mode 100755 index 0000000000..c9fa5d6090 --- /dev/null +++ b/scripts/selfhost/hosted-git-smoke.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +# Smoke test for SAM-hosted repositories on a self-hosted box. +# +# SAM_DOMAIN=vmtest.sam2.party SAM_API_TOKEN=sam_... scripts/selfhost/hosted-git-smoke.sh +# +# Inputs (environment): +# SAM_DOMAIN the box's SAM_DOMAIN (api. must answer) +# SAM_API_TOKEN an API token of an email-only account (Settings -> API tokens), exchanged +# for a session cookie via POST /api/auth/token-login. Never printed. +# SAM_INSECURE=1 optional: skip TLS verification (SAM_TLS_MODE=internal boxes) +# SMOKE_RUN_TASK=1 optional: also submit an agent task that commits and pushes a branch from +# a workspace, then wait for that branch (SMOKE_TASK_TIMEOUT_S, default 1200) +# +# Steps: capability on -> create an artifacts project -> member token -> clone (README) -> +# push a branch -> fresh clone sees it -> unauthenticated clone refused -> (optional) workspace +# task pushes a branch. Exits non-zero on the first failure. +set -euo pipefail + +: "${SAM_DOMAIN:?set SAM_DOMAIN}" +: "${SAM_API_TOKEN:?set SAM_API_TOKEN}" +API="https://api.${SAM_DOMAIN}" +WORK="$(mktemp -d)" +JAR="${WORK}/cookies" +trap 'rm -rf "$WORK"' EXIT + +CURL=(curl -fsS --max-time 60 -b "$JAR" -c "$JAR") +GIT=(git -c credential.helper= -c gc.auto=0) +if [[ "${SAM_INSECURE:-}" == "1" ]]; then + CURL+=(-k) + GIT+=(-c http.sslVerify=false) +fi +export GIT_TERMINAL_PROMPT=0 GIT_AUTHOR_NAME=smoke GIT_AUTHOR_EMAIL=smoke@example.com \ + GIT_COMMITTER_NAME=smoke GIT_COMMITTER_EMAIL=smoke@example.com + +step() { printf '\n== %s\n' "$*"; } +fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; } +json() { python3 -c "import json,sys; print(json.load(sys.stdin)$1)"; } +# A remote URL with the token as the Basic password (never echoed). +authed() { python3 -c "import sys,urllib.parse as u; p=u.urlsplit(sys.argv[1]); print(u.urlunsplit((p.scheme,'x:'+u.quote(sys.argv[2],safe='')+'@'+p.netloc,p.path,'','')))" "$1" "$2"; } + +step "sign in with the API token" +# The token goes through stdin so it never appears in the process list. +python3 -c 'import json,os; print(json.dumps({"token": os.environ["SAM_API_TOKEN"]}))' | + "${CURL[@]}" -X POST -H 'content-type: application/json' --data @- \ + "${API}/api/auth/token-login" >/dev/null + +step "SAM-native repositories are enabled" +enabled="$("${CURL[@]}" "${API}/api/config/artifacts-enabled" | json "['enabled']")" +[[ "$enabled" == "True" ]] || fail "artifacts-enabled is $enabled (redeploy with this branch)" + +step "create a project with a SAM-hosted repository" +name="hosted-smoke-$(date +%s)" +project="$("${CURL[@]}" -X POST -H 'content-type: application/json' \ + -d "{\"name\":\"${name}\",\"repoProvider\":\"artifacts\",\"description\":\"hosted git smoke\"}" \ + "${API}/api/projects")" +project_id="$(json "['id']" <<<"$project")" +remote="$(json "['repository']" <<<"$project")" +echo "project ${project_id} remote ${remote}" +[[ "$remote" == "${API}/git/"* ]] || fail "unexpected remote ${remote}" + +step "member write token, clone, README present" +token="$("${CURL[@]}" -X POST "${API}/api/projects/${project_id}/hosted-git/token?scope=write" | json "['token']")" +"${GIT[@]}" clone -q "$(authed "$remote" "$token")" "${WORK}/clone" +grep -q "$name" "${WORK}/clone/README.md" || fail "seeded README missing" + +step "push a branch" +(cd "${WORK}/clone" && git checkout -q -b smoke/human && echo "pushed $(date -u)" >smoke.txt && + git add smoke.txt && git commit -qm "smoke push" && "${GIT[@]}" push -q origin smoke/human) + +step "fresh clone sees the branch" +"${GIT[@]}" clone -q --branch smoke/human "$(authed "$remote" "$token")" "${WORK}/verify" +[[ -f "${WORK}/verify/smoke.txt" ]] || fail "pushed file missing" + +step "unauthenticated clone is refused" +if "${GIT[@]}" clone -q "$remote" "${WORK}/anon" 2>/dev/null; then fail "anonymous clone succeeded"; fi +echo "refused as expected" + +if [[ "${SMOKE_RUN_TASK:-}" == "1" ]]; then + step "workspace task clones and pushes (provisions a node; minutes)" + "${CURL[@]}" -X POST -H 'content-type: application/json' \ + -d '{"message":"Create a file named agent-smoke.txt containing the word hello, commit it, and run: git push origin HEAD:refs/heads/smoke/agent . Reply done when the push succeeds."}' \ + "${API}/api/projects/${project_id}/tasks/submit" >/dev/null + deadline=$(( $(date +%s) + ${SMOKE_TASK_TIMEOUT_S:-1200} )) + until "${GIT[@]}" ls-remote "$(authed "$remote" "$token")" refs/heads/smoke/agent | grep -q smoke/agent; do + (( $(date +%s) < deadline )) || fail "workspace never pushed smoke/agent (check the task in the UI)" + sleep 20 + done + echo "workspace pushed smoke/agent" +fi + +printf '\nPASS: SAM-hosted repository smoke (project %s)\n' "$project_id" diff --git a/scripts/selfhost/selfhost-durable-objects.ts b/scripts/selfhost/selfhost-durable-objects.ts new file mode 100644 index 0000000000..396ae7b853 --- /dev/null +++ b/scripts/selfhost/selfhost-durable-objects.ts @@ -0,0 +1,72 @@ +/** + * Durable Objects only the self-host (celld) build has. + * + * `apps/api/wrangler.toml` is the Cloudflare Worker's configuration and must not name these + * classes: a Cloudflare Durable Object migration cannot be taken back, and the Cloudflare bundle + * must not carry their code. The celld config (`buildCelldConfig`) appends each one's binding + * and migration after wrangler.toml's, and the generated celld entry (`celld-project.ts`) exports + * the class from `SELFHOST_ENTRY_MODULE`, which the shared entry `apps/api/src/index.ts` never + * imports. Today that module is hosted git's; a second self-host-only class must be exported from + * the same module (tests/unit/selfhost/selfhost-only-modules.test.ts checks every class is). + * + * celld 0.6.3 validates migrations declaratively (a tag or a class may appear once; a class with + * storage must be declared in `new_sqlite_classes`). Observed with `celld dev`, which keeps state + * across restarts: an object written while this class was wrangler.toml's `v23` keeps its data + * once the class is declared under this tag. Bucket-mode `celld deploy` over an existing box is not + * yet verified (task tasks/archive/2026-11-15-hosted-git-selfhost-only-build.md). + */ + +export interface SelfhostDurableObject { + /** Worker binding name (`Env.HOSTED_GIT`). */ + binding: string; + /** Class exported by `SELFHOST_ENTRY_MODULE`. */ + className: string; + /** celld migration tag; distinct from wrangler.toml's `vN` tags so the two never collide. */ + migrationTag: string; +} + +/** The module under apps/api/src that the generated celld entry imports for these classes. */ +export const SELFHOST_ENTRY_MODULE = 'selfhost/build.ts'; + +export const SELFHOST_DURABLE_OBJECTS: readonly SelfhostDurableObject[] = [ + // SAM-hosted git repositories (one per repository); selfhost/hosted-git/local-backend.ts selects it + // with HOSTED_GIT_BACKEND=durable-object (SELFHOST_VAR_OVERRIDES). + { binding: 'HOSTED_GIT', className: 'HostedGitRepo', migrationTag: 'selfhost-hosted-git-v1' }, +]; + +interface DurableObjectConfig { + durable_objects: { bindings: Array<{ name: string; class_name: string }> }; + migrations: Array<{ tag: string; new_sqlite_classes: string[] }>; +} + +/** + * Appends every self-host-only binding and migration to a config translated from wrangler.toml. + * Throws when wrangler.toml already uses a binding name, class or tag, so the class cannot end up + * declared twice or back in the Cloudflare configuration unnoticed. + */ +export function appendSelfhostDurableObjects(config: DurableObjectConfig, report: string[]): void { + const bindings = new Set(config.durable_objects.bindings.map((b) => b.name)); + const classes = new Set([ + ...config.durable_objects.bindings.map((b) => b.class_name), + ...config.migrations.flatMap((m) => m.new_sqlite_classes), + ]); + const tags = new Set(config.migrations.map((m) => m.tag)); + for (const object of SELFHOST_DURABLE_OBJECTS) { + if ( + bindings.has(object.binding) || + classes.has(object.className) || + tags.has(object.migrationTag) + ) { + throw new Error( + `celld config: wrangler.toml declares ${object.binding}, ${object.className} or ` + + `${object.migrationTag}, which only the self-host build may declare ` + + '(scripts/selfhost/selfhost-durable-objects.ts)' + ); + } + config.durable_objects.bindings.push({ name: object.binding, class_name: object.className }); + config.migrations.push({ tag: object.migrationTag, new_sqlite_classes: [object.className] }); + report.push( + `self-host Durable Object ${object.binding} (${object.className}), migration ${object.migrationTag}` + ); + } +} diff --git a/specs/001-mvp/contracts/api.md b/specs/001-mvp/contracts/api.md index aa07325002..0685435c8b 100644 --- a/specs/001-mvp/contracts/api.md +++ b/specs/001-mvp/contracts/api.md @@ -858,3 +858,20 @@ The existing publish-job events, artifact init/complete and compose release call `POST /api/auth/unlink-account` accepts BetterAuth `{accountId}`. Only the caller's GitHub/GitLab accounts can be removed; removing the last provider requires usable verified email sign-in. The affected account owner receives a linked-provider security notification at their preserved SAM email. Explicit links may have a different provider email; future sign-ins preserve an already-verified SAM email. A lookup failure aborts sign-in rather than replacing identity. GitHub repository errors distinguish `403 GITHUB_NOT_CONNECTED`, `401 GITHUB_REAUTH_REQUIRED`, `503 GITHUB_UNAVAILABLE`, `409 GITHUB_APP_NOT_CONFIGURED` and `404 FEATURE_UNAVAILABLE`. Only actual authorization failures request reauthentication; provider outages offer retry. Unverified provider-linked accounts receive a provider-sign-in note instead of an email code, and code redemption is refused without deleting links or sessions. + +## Self-hosted repository credentials + +### POST /api/projects/{id}/hosted-git/token + +Available only on self-host installations using the local hosted Git backend. Requires an +approved, session-authenticated user. The `scope` query parameter is `write` for push access; +all other values (including omission) select `read`. Read requires `project:read`; write +requires `workspace:write` on the addressed project. No request body is required. + +Returns `200` with `{ cloneUrl, host, username: "x", token, scope, expiresAt }`. `expiresAt` +is the token's expiry timestamp in ISO 8601 format. Use `username` and `token` as Git HTTP Basic +credentials; keep the short-lived token private. This personal token is not workspace-bound. + +Returns `401` for missing authentication, `403` for insufficient capability, and `404` when +the project is absent or does not use this installation's local hosted Git backend. Cloudflare +Workers do not register this endpoint and return `404`; their Artifacts and forge behavior is unchanged. diff --git a/tasks/archive/2026-11-19-selfhost-hosted-git-h2.md b/tasks/archive/2026-11-19-selfhost-hosted-git-h2.md new file mode 100644 index 0000000000..f40e8dee0b --- /dev/null +++ b/tasks/archive/2026-11-19-selfhost-hosted-git-h2.md @@ -0,0 +1,170 @@ +# H2: SAM-hosted git on self-host only + +## Problem + +A box built from main needs a repository source before it can create a project and run an agent. Owner D7 narrowed: HostedGitRepo is celld-only, never a Cloudflare export, binding, import or migration. Main v23 is unrelated and untouched. + +## Research and preflight + +Classes: cross-component, business logic, security sensitive, infra, docs sync. Main 08abf1393 already has L16's backend fallback selection and L22b's single self-host entry. L22c #2906 remains open, held on #2905 and security review; coordinator confirmed import/trim can proceed while celld wiring and BOX wait for L22c main. Integration has hosted-git runtime and conformance fixtures, but shared routes import local implementation (M4 HIGH-4). + +Trace: project-create -> resolved Artifacts backend -> seed/import via backend remoteFetch -> authenticated self-host git HTTP -> HostedGitRepo SQLite. Runtime callback -> active workspace/current generation -> backend createToken with workspace identity -> git HTTP rechecks membership/lifecycle/generation -> push commits ref. Cloudflare keeps binding or null and global fetch, with no registered fallback. + +Use existing L16 selection, extend its optional token context and fetch/import contract. Move implementation under selfhost; preserve Cloudflare semantics. Import with git checkout paths, no cherry-pick. Tests must exercise real git over smart HTTP and prove import-graph detection by introducing a forbidden import. Relevant lessons: callback routing/auth rule 34; DO interleaving rule 45; cross-boundary/vertical tests rules 23/35; no secret readback rule 83. Docs: operator README only (experimental self-host slice). + +## Checklist + +- [x] Fresh branch from main; import selected integration paths and trim +- [x] Move DO and hosted-git services under selfhost; dgit/pako excluded from Worker graph +- [x] Extend generic fallback seam: workspace-bound token context, remoteFetch and optional import capability (unregistered per coordinator empty-repo decision); remove shared local-backend branches +- [x] Wire celld-only binding/export/tag via L22 single entry stacked on stable L22c08e2f605a per coordinator +- [x] Add conformance/auth/lifecycle/token tests and import-graph violation proof +- [x] Document self-host repository support and limits +- [x] Local lint/typecheck/tests/build; security, Cloudflare, architecture and completion reviews +- [x] Draft PR then ready; CodeRabbit requested and explicit skip recorded; CI tracked below +- [x] Primary staging lease/deploy: Artifacts and GitHub project creation unchanged, local seam off +- [x] BOX existing bucket-mode deploy adds selfhost-hosted-git-v1; create project; OpenCode free reply; agent push verified; cleanup and BOX FREE +- [x] Merge main (917077fef, then 20675016f); all gates on the current head +- [ ] Announce merging/merged SHA; production success; idea SHIPPED (tracked in the PR and on the channel) + +## Acceptance + +No HostedGitRepo/dgit/pako reachable from Cloudflare index; wrangler unchanged; no CF migration. Shared seam inert on Cloudflare. BOX upgrade succeeds with new celld tag, project creation and actual short free-model agent reply/push work. Every resource created by this task cleaned up. All required gates pass on merge head. + +## Implementation evidence + +Stacked L22c08e2f605a per coordinator to break circular BOX gate; #2906 merges before H2. Hosted suite22/22 (real git21 + celld dry-run1); selfhost unit113/113; config/project29/29; native runtime-token32/32. Worker graph negative probe importing pako through workspace package failed as intended. GC admission negative probe failed exactly the race test. Security followup inflation/GC6/6. + +BOX proof: existing795bf674f upgraded bucket-mode to a7cad then f6c65e71a healthy, celld tag confirmed. Hosted project01M7SX75X1YVADRG9Z4AB4AMV0; OpenCode big-pickle task01M7SXCMYYTAB9DNCFFAZMM0G1 replied pong; cookie-free clone verified agent commitad485ee136d4c8469b1e05e2983e086dd9e9393b and h2-proof.txt=pong. Stop/node/project delete200; nodes empty/project404/GCP no matching VM. Test credential/key/firewall/scratch removed. BOX FREE channel sequence403. + + +Review follow-up at 0f504c8dc: security PASS (independent 19 tests), Cloudflare PASS (54 tests), architecture PASS. Ref-only pushes now have an administrator-lowerable 10,000-ref cap and storage reservation; deletions do not earn admission capacity before old-OID validation (delete then add as separate pushes at the cap). Real HTTP mixed stale-delete/new-ref test fails when that protection is removed. DELETE queues behind accepted pushes, cancels clone streams, persists a tombstone and transactionally wipes/reinitializes; cleanup failures can retry while writes stay fenced. Mutex-negative probe fails the overlapping push/delete test. Ingested packs schedule GC even if every ref is rejected; oversized ls-refs returns a readable 413. Personal token endpoint is documented in API contract. + +Primary staging f6 deployment44527475370 passed deploy/smokes. Live Artifacts creation exposed a native RPC regression: optional extension property reads synthesize RPC methods. Fixed by selecting empty extensions when the native binding exists; only the registered fallback supplies import/fetch. Native browser transport similarly avoids extension probing. Proxy-shaped route and browser tests cover this; removing the guard makes the route test fail. Replacement deploy44532452799 at0f504c8dc pending. No staging project or VM persisted from failed seed (route cleans the orphan). CF settings independently confirm native ARTIFACTS present, hosted binding/DO absent. Browser project list loaded with zero page errors. Artifacts/GitHub creation gates remain pending the replacement deployment. + + +## Final candidate proof (2026-11-19) + +Candidate e7ac643b18f4ca864e403d33f7fbcf7a1a5e8fe8 has identical runtime to reviewed0f504c8dc; later changes document vendoring and add real-SQLite rejected-pack GC/tombstoned-deletion coverage. Hosted22/22, full API lint/typecheck passed. Security/Cloudflare/architecture PASS; completion validator independently A-F PASS, release completion pending CI/merge/production. Five Codex threads resolved. CodeRabbit requested at readiness12:33, trusted workflow44525031212; explicit skip12:34:24 (136files>100), ending wait per policy. + +Replacement staging44532452799 succeeded. Authenticated Playwright created Artifacts01M7T0EY1H2F03C1KK3W60DMQ9 and GitHub01M7T0F97C4V2BNV2M645TFF9M:201, branches200, selfhost token/git routes404. Both projects deleted200 and verified404. Dashboard/projects/settings and project overview navigation: zero page/console errors. No staging VM created. Runtime equivalence0f→e7 avoids another deploy for docs/tests only. + +Final BOX: existing f6→e7 ordinary bucket upgrade exit0/healthy; hosted project01M7T0482A939BRG0JFFK9VG62 created201, owner token200/unauth401. Normal fresh-node task01M7T0VJHK2381FBXA2VG6PM8Q / sessionbc1634b8-0065-43d9-835f-1d75197ec00b used OpenCode big-pickle free and replied pong. Independent cookie-free clone of sam/ping-run-one-shell-g6pm8q verified pushed commit164c22e3dc1c52de674718cc3996a31f75833c29 with h2-proof.txt=pong. Stop/node/project DELETE200, project404/nodesempty, GCP inventory no matching VM for either attempt. Test agent credential removed200, own SSHkeyabsent/firewall404, remote/local access/scratch removed; checkout clean at e7 and four original containers healthy. BOX FREE feature.selfhost-landing sequence405. + +First final BOX attempt01M7T05XSYH7ZPX5Y24DC4S4CH failed Ubuntu GCE mirror503 installing Docker before ready callback. Node01M7T062B9J4M1ZMBWT0Z2BXFP deleted through SAM; coordinator approved one normal fresh retry, which passed above. Sanitized evidence library01M7T0VM6MXVT21PMF5AJ4QMB7 and backlog01M7T0W1QW6WGMZGK1RYAXEEB1 track bounded retries/fallback mirror and failure callback. Raw debug copy deleted after analysis per policy. + +Current CI at e7:30success/8skip, only Playwright Visual Tests pending (44533748428/job135593986625). Final release checklist remains unchecked until prerequisite/main merge, current-head CI and production finish. + + +## Late review corrections (2026-11-19 18:21 UTC) + +PR Shepherd found two newer 13:32 Codex threads omitted from the earlier five-thread resolution report. Both applied: failed ingest persisted incomplete pack rows until another admitted ingest, which quota could block; failed GC cleared pending before sweeping and never retried. Runtime delta touches PackStore.cleanupOrphans/ingest (extract existing sweep), HostedGitRepo.processReceive error branch, alarm/runAlarm/gc retry bookkeeping, and repositories.maxGcAttempts metadata. Auth, deletion and happy-path git protocol are unchanged. + +Incomplete rows now clear immediately after failed ingest before alarm scheduling; GC also sweeps them independently. Successful GC clears pending/attempts under its writer slot. Failure persists retry intent and attempts under that same slot, re-arms five minutes later up to administrator-lowerable maxGcAttempts=3, then preserves a failed marker without automatic rearming. Success resets the consecutive-failure budget. Errors are carried out after blockConcurrencyWhile completes to avoid DO reset discarding retry handling. + +Full real-git/SQLite suite24/24 passed; GC/deletion units8/8 passed, including transient recovery, four success/failure cycles, attempt exhaustion, and alarm-scheduling failure ordering. Negative controls independently failed: disabling immediate cleanup left2199552bytes==cap; disabling retry handling leftpending0 instead of1. Restored tests pass. Security delta review PASS, including serialized failure metadata. No implementation omission remains; fresh CI and zero unresolved threads must still be confirmed. + +Coordinator decision720e4e43-2b39-4979-a6e1-3024553dd7c8 explicitly waives repeating BOX if delta stays confined to these failure paths, full real-git+new SQLite tests/negative controls pass, security delta passes, and fresh CI is green with zero open threads. Existing BOX proof/cleanup remains valid under those conditions. Staging native seam is unchanged. + + +## Ref-name review and complete rule audit (18:30 UTC) + +New current-head Codex r4633207972 found intermediate .lock components accepted by validatePush. Added the component suffix guard. Auditing every rule from https://git-scm.com/docs/git-check-ref-format also found missing whole-ref trailing-dot refusal; added that guard in the same fix. All other ten rules were already enforced in the refs/ namespace; conservative HTML/whitespace/255-character restrictions remain unchanged. + +Real raw smart-HTTP test refuses foo.lock/bar, foo.lock and ends-dot., and accepts normal, feature/x and foo.lockish/bar through the same validatePush/write path. Real validatePush rule matrix66/66 compares Git CLI outcomes (NUL checked directly since OS argv cannot carry it); full conformance25/25. Independent negative controls: remove component guard -> raw HTTP accepts the invalid ref; remove trailing-dot guard -> exactly1matrixfailure/65pass. Restored suite rerun. Security independently audited all ten rules and passed this delta. + +Coordinator decision5e57db22-5e40-46af-8aec-f1894395779f extends NOBOXREPEAT to this invalid-name admission tightening if ordinary+nested positive controls, negative control, full real-git, security delta, fresh CI and zero threads all pass. It rejects names the ordinary BOX branch never used; auth, happy-path valid names and deletion remain unchanged. Fresh CI remains required. + + +## Takeover by task 01M7TY7Z3HBTSDSSV85FPRHE1B (2026-11-19 ~21:00 UTC) + +Previous owner 01M7SR1B79 stopped after repeated provider content-filter refusals; its pushed head 0eda6a2bd was intact. + +- [x] Merge main 917077fef (L22c merged): conflicts only in L22c files (took main's final versions) and deploy/selfhost/README.md (kept the hosted-git section, dropped main's now-false "Hosted git: not included" bullet). Merge 553a9060f. +- [x] Codex P2 r4633317762: `reachableComplete` now walks each command into a scratch OidSet and merges into `known` only once the closure is complete. +- [x] Same class, found while fixing it: the cache-less path trusted `packComplete` + `store.has(tip)`. That is sound only if every object outside the new pack is closure-complete, but a pack whose refs were all rejected stays ingested until GC. A later push (ref-only, or a pack whose commit's parent is the stale commit) could point a ref at an incomplete closure. Every command now proves its closure with the same walk; `packComplete` and the `push_edges` helpers/table creation are removed (existing repos keep an empty, unused `push_edges` table; no DO DROP). +- [x] Real git/SQLite tests (describe "push connectivity admission"): cache-path multi-ref attack, cache-less stale-rejected-pack attack (ref-only and child-pack variants), and positive controls (overlapping multi-ref push extends the cache and a full clone fscks; shallow-clone push on the cache-less path). Both attack tests fail on 0eda6a2bd. Discrimination: A non-transactional walk -> both attack tests red; B cache-less presence-only -> stale-pack test red; C never merging into `known` -> cache control red (clone from extended cache fails fsck). Hosted suite 29/29, self-host unit 186/186, API typecheck and focused lint pass. +- Bound (rule 81): one walk is bounded by the repository caps (30,000 objects, 256 MiB stored), the 128 MiB per-request inflation budget and the 120 s git-operation deadline. Worst case is one walk over every object in the repository: at most 30,000 SQLite presence probes plus inflating the non-blob objects, completing in one attempt or failing closed with the budget error. A fresh push's walk reads the same non-blob objects `packComplete` read before. +- [x] Security delta review of d16d1538e: 0 CRITICAL/HIGH. MEDIUM-1 (failed walks not memoized, so repeated failing commands cost K x N) and MEDIUM-2 (a throw in validatePush left the ingested pack without GC; pre-existing) were fixed; LOW items were tested. +- [x] One adversarial pass over the whole push admission path (auth, parsing, limits, ingest, validatePush, commitPush, GC, status): 1 HIGH, 4 MEDIUM, 5 LOW; auth, CAS, savepoint, deletion and the earlier fixes held. Fixed in this PR: + - HIGH: seeding `known` peeled every ref tip, inflating each under the push budget, so nine large tips wedged every later push, deletions included. Seeding now reads no objects; it uses cached peel targets only. + - MEDIUM-2: the walk now checks the type git requires at every edge (commit.tree is a tree, parents are commits, tree entries match their mode, a tag's object matches its type header, including edges into already-validated objects). Branches refuse non-commits. A mismatch blames the referencing object, so a valid shared object is never poisoned. + - MEDIUM-5 (part): deleting a missing ref succeeds without queueing GC; arming the GC alarm keeps an earlier armed alarm, so pushes cannot postpone GC indefinitely. + - LOW-6: directory/file ref conflicts are refused (git transaction semantics, deletions in the same push first). + - Per-push failure memo (BFS path to the failing oid), GitParseError rejected per command, GC queued when validation/commit throws after ingest. +- Deferred with justification to `tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md`: MEDIUM-3 (GC inflates migrated objects under the same budget, so it cannot finish past 128 MiB of uncollected inflated content; needs a raw-copy GC redesign; documented as a known limit in the README), MEDIUM-4 (delta depth not checked at ingest; git defaults to 50), MEDIUM-5 rest (GC holds the input gate), LOW-7..10. Every deferred item needs a write token for that repository and is confined to it. +- Tests: unit hosted-git-closure-walk (memo at 1201 commits / 2001 commands, parse errors) and hosted-git-push-admission (seeding reads zero tips at 1201 refs, edge types, branch rule, D/F, no-op delete, alarm arming); real git: mixed failing/valid sibling with cache, malformed commit, validation fault after ingest queues GC (one-shot read-fault hook), large tips under a 14 MiB budget, edge types, no-op delete and D/F. Every guard was mutated once and the intended tests went red (memo, parse catch, GC on throw, non-transactional walk, peel seeding, child-vs-parent blame, duplicate-edge check, D/F, branch rule, no-op delete, first-edge type). +- Request-body helpers moved to `hosted-git-body.ts` so `hosted-git-repo.ts` stays under 500 lines; GC queueing is one helper (`queueHostedGitGc`, `armHostedGitGcAlarm`). +- [x] Codex reviews every push automatically; 15 findings across heads fixed or deferred with tracked follow-ups; 0 open threads +- [x] Final BOX smoke on 9d8a0802 (#2907 over main 20675016f), which closes the L22c "box from main runs an agent session" criterion Raphaël deferred to H2 + +## Independent re-verification of f9eb945ef (23:20 UTC) + +A fresh security-auditor re-verified f9eb945ef. It found 0 CRITICAL and 0 HIGH. Its 400-seed differential fuzz confirmed the failure memo, the parse-failure handling, GC-on-throw, the no-op delete, the alarm and the D/F checks. Mutating the blame-parent logic to blame the child made 74 fuzz cases red. + +MEDIUM-F2 was fixed: lenient parsers let a writer push a commit with `author` before `tree`, tags missing or reordering `object`/`type`/`tag`, or tree modes like `8`, and git then cannot clone. `assertGitObjectShape` now runs in the walk, so a malformed object rejects its own command. A real-git test reproduces each shape; a signed commit with continuation lines and extra headers stays accepted. + +MEDIUM-F1 was partly fixed: with a valid reachable cache the walk stops at cached objects (SQL lookup, no read), and an ancestry check that exhausts the work budget counts as a forced update rather than failing the push. The dead `getPeeled` seeding was dropped. The cache-less heavy-history case and F4 (alarm error handling) were deferred to the backlog task. Discrimination was checked again: removing the shape check, the cache stop or the budget tolerance each turned its intended tests red. + +## Narrow verification of 8bc9a3af4 (23:45 UTC) + +The narrow verification found a HIGH regression introduced by the cache stop in 8bc9a3af4. A clone that raced a deleting push could stamp a stale reachable set as current (`saveReachable` captured its version after the walk). After GC deleted a stranded object, the cache stop admitted a push naming it, and clones failed. The same race on f9eb945ef rejected the push. Fixes: +- The cache stop is removed: admission never trusts the reachable cache. +- `saveReachable` stamps only the version its clone walk started from. +- GC invalidates the cache whenever it deletes objects. + +The shape check moved to raw bytes. Lossy UTF-8 decoding hid BOM-prefixed commits and tags (clone-breaking) and falsely merged distinct non-UTF-8 names. Header sections must be newline-terminated, header NUL is refused, `.`, `..` and `.git` variants are refused, and every `100xxx` file mode is accepted. The budget-tolerant ancestry check was confirmed sound (verdict D: PASS). + +Unit tests cover each fix: an absent cached parent is refused, with a control; the stamp guard; GC invalidation, with a control; BOM, unterminated, NUL, `.git` and `..` cases, plus accepted Latin-1, BOM-only and `100600` names. Each fix was mutated once and its test went red. + +## Final re-verification of 77e55dbb (00:10 UTC) + +The original HIGH is closed. The race reproduced in 5 of 11 runs on 8bc9a3af4 and never on 77e55dbb. No admission path reads the reachable cache, and the shape check accepts everything git handles. + +New findings, fixed: +- HIGH: a leading continuation line before `tree`/`object` was skipped by the key list, but git rejects such an object. The first header line must now be exactly `tree ` or `object `. +- MEDIUM: a second cold clone rewriting a stamped cache left it partial during a yield, and a push in that window could stamp the partial set valid. `saveReachable` now unstamps before rewriting. +- LOW: `git~1`, `.git:` streams, a `.gitmodules` symlink and names over 255 bytes are now refused. + +Deferred to the backlog: path depth, and accepting uppercase-hex oids. Each guard was mutated once and its test went red. The real-git shape test also pushes the leading-continuation commit. + +## Scoped verification of dc8e9e4c (00:25 UTC) + +- Q1 PASS: the leading-continuation bypass is closed. 27 crafted commit and tag shapes went through the real Durable Object; none of the accepted ones broke a clone. +- Q2 PASS: nothing that git fsck accepts and a default clone checks out is refused. +- Q3 found two MEDIUM cache-concurrency races, both fixed: + - Two overlapping clone saves could stamp a partial table. `saveReachable` is now single-flight through a generation counter, checked before and after every yield and before stamping. + - A push that read `hadCache` before a save unstamped could extend the partial table. `commitPush` now re-checks `reachableCacheValid()` at commit time, before refs move. +- LOW: the `.gitmodules` symlink check now covers `gitmod~1` and `.gitmodules:` streams. + +Unit tests cover overlapping saves (only the latest stamps; the superseded save stops after one batch), the commit-time re-check with a control, and the NTFS forms. Each guard was mutated once and its test went red. The admission HIGHs were independently verified closed; these last cache fixes have discriminating tests but no further review round. + +## Codex threads on dc8e9e4c (00:40 UTC) + +Seven Codex findings were reconciled: +- **P1 r4636317748:** at most 256 `ref-prefix` arguments are honored; past that the answer is unfiltered, as git does. +- **P2 r4636466068:** an abandoned upstream fetch stream is now cancelled, so an upload slot is released. +- **P1 r4636595142 (partly addressed):** GC drops whole unreferenced packs before inflating anything, which reclaims rejected-push packs even when migration exceeds the budget. Resumable migration is in the backlog. +- **P2 r4636595147:** delta bases are kept only while packs are kept, so migration no longer preserves delta-only bases. +- **P2 r4636595152 (deferred):** delta depth at ingest is in the backlog. +- **P2 r4636751965:** `ChunkBuffer` grows geometrically, so command-section copying is linear. +- **P2 r4636751970:** the personal token route honors `ARTIFACTS_TOKEN_TTL_SECONDS`; the test runtime now sets 900 s and asserts the expiry. + +Tests: prefix cap, cancel-on-abandon with a read-to-end control, `ChunkBuffer` copy bound for 1 MiB arriving one byte at a time, GC whole-pack drop before any read, base retention in both GC modes, a real-git rejected pack reclaimed under a 2 MiB budget, and the TTL route. Every guard was mutated once and its test went red; with exact-size growth the buffer test took 95 s and failed. + +## Codex r4636923076 on 1bbf2aeb (01:00 UTC) + +The byte budget covered the raw pack, not its index rows and page overhead. Following rule 69, `processReceive` now re-checks `dbSize()` after ingest. A push that crossed the cap is refused, and its pack is dropped immediately with `dropPack`. Real-git test: 3,000 tiny objects with a cap of the current size plus the raw pack size is refused, and the ref and bytes are not kept. The control with headroom is accepted. Removing the check turns the test red. Main 20675016f, a workflow action bump, was merged. + +## Final BOX smoke (00:30-00:45 UTC, 2026-11-20) + +The run used head 9d8a08029933863020011b6f0d0e7a62f12b3804. The only later commit moves this task file, so runtime is identical. +- **Upgrade:** in-place bucket-mode `pnpm selfhost:upgrade` from e7ac643b1, EXIT=0 and healthy, with no D1 migrations. The generated celld config has HostedGitRepo and the selfhost-hosted-git-v1 tag. +- **Project:** hosted-git project 01M7V67QTF30PEZ8G8EJ4SM8KX created 201, signed in as agent-test by email OTP through the box mail collector. +- **Agent:** task 01M7V681KWFSR8N9H33N5XPB71 (OpenCode, opencode/big-pickle, free) on a fresh node replied "pong" and pushed sam/ping-reply-pong-create-5xpb71. +- **Separate clone:** a cookie-free clone from the agent workspace with a read-scoped member token shows commit e7400ab74a65a152e842a99a2ebc8203d71751ae, h2-proof.txt = pong, and `git fsck --strict` passes. Unauthenticated info/refs returns 401. +- **Cleanup:** + - Resources: session stop 200, node DELETE 200, project DELETE 200 then 404; nodes [], repository 401, and the GCP inventory shows only sam-box. + - The box's standing agent-test credential from R18 was used, not changed. + - Session signed out, box scratch removed, own metadata key absent and firewall rule 404. + - The box was left healthy at 9d8a0802 with a clean checkout. BOX FREE posted at channel sequence 424. diff --git a/tasks/backlog/2026-11-19-bounded-selfhost-git-import.md b/tasks/backlog/2026-11-19-bounded-selfhost-git-import.md new file mode 100644 index 0000000000..98f5a7e925 --- /dev/null +++ b/tasks/backlog/2026-11-19-bounded-selfhost-git-import.md @@ -0,0 +1,8 @@ +# Bound self-host git imports before enabling them + +H2 security review found that a compressed-response cap around isomorphic-git's in-memory clone does not bound inflated objects or delta allocations. A small public pack can exhaust the shared celld process before MemoryFS observes a write. Coordinator approved empty seeded repositories only for H2 on 2026-11-19 (message f52622cf-1aff-4052-9bde-67766706e15e); the generic import capability remains unregistered and importUrl is refused with 400. + +- [ ] Design an importer enforcing object, cumulative decompression, delta depth, CPU/time and transport bounds before allocation (reuse hosted DO policy or isolated bounded execution). +- [ ] Preserve public-forge HTTPS allowlisting, redirect refusal, no embedded credentials and cleanup on refusal. +- [ ] Exercise compressed-bomb and stalled-source refusals, plus successful history/default-branch import through real project creation. +- [ ] Register the fallback import capability only when those tests and live self-host verification pass; document supported limits. diff --git a/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md new file mode 100644 index 0000000000..3ddd12a25b --- /dev/null +++ b/tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md @@ -0,0 +1,53 @@ +# Hosted git: GC without inflation, delta depth at ingest, GC scheduling + +## Problem + +The adversarial review of the push admission path in PR #2907 (H2, SAM-hosted git, self-host only) left these findings open. Each needs a design change rather than a guard, so they were deferred with justification in the PR. The HIGH finding and the other MEDIUM and LOW items in that review were fixed in #2907. + +1. **GC needs to inflate every migrated pack object** (review M3). `runHostedGitGc` (`apps/api/src/selfhost/hosted-git/hosted-git-gc.ts`) moves each reachable pack object to loose storage through `store.get`, which inflates it under the GC alarm's single `repositories.maxInflatedBytes` budget (128 MiB). Two cases exceed that budget: + - highly compressible blobs (14 blobs of 15 MiB stored in about 0.4 MiB); + - more than 128 MiB of inflated pack content accumulated between collections. + + Since #2907, GC drops whole packs with nothing reachable and no delta base before inflating anything, so a rejected push's pack is always reclaimed. Migrating the reachable packed objects can still exceed the budget. GC then fails on every attempt, garbage mixed into reachable packs (after a force push) is never reclaimed, and the repository drifts towards `maxRepoBytes`, where every push is refused. The reviewer reproduced this at 268 MB of a 268.4 MB cap. Raising the budget only moves the bound, since a compression bomb can exceed any inflation or deadline cap. +2. **Delta depth is enforced on read but not at ingest** (review M4). `packstore.ts` resolves deltas eagerly at ingest without checking `maxDeltaDepth`, so a pack built with `--depth=250` is accepted. Cold reads then throw `delta chain exceeds depth`, and a shallow clone aborts with `early EOF` until GC rewrites the objects loose. The exception is thrown inside the upload response stream and is not caught. +3. **GC holds the input gate for the whole sweep** (review M5, the part not fixed in #2907). `gc()` runs under `blockConcurrencyWhile` for up to `workTimeoutMs` (120 s), blocking every other request to that repository, reads included. +4. **Pushes over heavy history without a reachable cache** (re-verification F1, the part not fixed in #2907). + - A push whose parent is not a ref tip proves that parent's closure by walking old commits and trees under the 128 MiB budget. Admission deliberately does not trust the reachable cache: a version of #2907 that did was shown to admit a parent GC had deleted, after a clone raced a deleting push (stamp race now fixed in `saveReachable`). + - A repository whose old trees inflate past the budget then cannot accept a fork-from-old-commit push. A full clone faces the same envelope. + - An ancestry check that runs out of budget is already treated as a forced update rather than failing the push. + - Fix: keep a persistent set of validated objects that only GC prunes. GC already computes the reachable set, and every accepted push adds its proven closure. Or record commit parents at ingest. + - Also: `store.setPeeled` is never called, so `getPeeled` and the `peeled` table are dead upstream code. Remove them or populate them. +5. **Alarm error handling** (re-verification F4): `armHostedGitGcAlarm` in the failed-ingest path propagates a `getAlarm`/`setAlarm` error as a 500, which is deliberate so the earlier tests keep the cleanup-before-alarm ordering. `queueHostedGitGc` swallows alarm errors, so `gc-pending=1` can wait for the next push. +6. **Lower-severity items** (review L7 to L10): + - **No rate limit.** There is no per-token or per-repository request rate limit, and a queued push is authorized before it waits on `receiveChain`. + - **Command lines dropped silently.** Unmatched command pkt-lines are skipped with no `ng`, and invalid UTF-8 ref bytes alias to U+FFFD. + - **Gzip buffering.** The gzip push path buffers about 3× `maxPushBytes`. + - **Quadratic copying.** `need()` concatenates repeatedly while reading the command section. +7. **SHA-1DC ingest notes** (security delta review of the SHA-1DC change in #2907): + - **Shared streaming hasher.** The streamed full-object path in `packstore.ts` feeds the module-level `streamSha` across awaits, so a concurrent ingest in the same isolate could reset it mid-object. This is unreachable on celld today: `maxObjectBytes` (16 MiB max) is below the 32 MiB streaming threshold. Use a per-entry `Sha1Dc` before either limit changes. + - **R2 raw object leak.** If an R2-backed ingest fails before it writes any pack rows, `cleanupOrphans` cannot find the raw object. The problem predates the SHA-1DC change, and celld stores packs in SQLite. + +## Context + +Found by the security-auditor adversarial pass on 2026-11-19 (task 01M7TY7Z3HBTSDSSV85FPRHE1B). The reproductions ran against the Durable Object in Miniflare/workerd. + +Who can trigger them: +- Every item needs a token with write access to the repository: a project member, or that project's agent workspace. +- The blast radius is that one repository. +- Item 1 is also reachable without malice, when several large pushes land between collections. +- An operator can recover by deleting and recreating the project's repository. + +## Acceptance Criteria + +- [ ] GC completes migration for a repository whose reachable packed content inflates past `maxInflatedBytes` (copy raw pack entries, or make migration resumable across alarms). A real-git test proves it. Whole unreferenced packs are already dropped without inflating. +- [ ] GC work is deadline-bounded and resumable, with throughput stated at the 30,000-object / 256 MiB envelope (`.claude/rules/81-work-bounds-must-state-throughput.md`). +- [ ] Ingest records delta depth and refuses a pack whose chains exceed `maxDeltaDepth`. A real-git test pushes `--depth=250` and is refused, and a normal pack is accepted. +- [ ] Errors raised while streaming an upload-pack response end the stream cleanly. +- [ ] GC no longer blocks reads for the whole sweep; a test shows a clone proceeding while GC runs. +- [ ] Decide on and implement per-token push rate limiting, or record why not. +- [ ] Every malformed command line is answered with `ng` or a refusal, never dropped. +- [ ] A push forking from an old, heavy commit succeeds within the budget. A real-git test proves it, and a stale or poisoned cache cannot vouch for a missing object. +- [ ] Decide whether to bound tree depth or total path length; 1,500 nested directories break checkout of the default branch. +- [ ] Optionally accept uppercase-hex oids in commit and tag headers, as git does (`isOid` is lowercase-only). +- [ ] Give the streamed ingest path its own SHA-1DC hasher, and reclaim R2 raw objects of packs that fail before any rows (item 7). +- [ ] Optionally reject the remaining fsck error-level shapes that default clients tolerate but `transfer.fsckObjects=true` clients refuse: unsorted trees, malformed idents, CR in headers.