// Prefix closure: for a valid encoding, every strict prefix throws a typed error, or — when the cut lands on an // entry boundary — parses to a prefix of the entries. A new `export function parse*` (or the other decoder names) // without an `@decoder name prefix=` annotation fails the registry test at the bottom of this file. import { test } from 'vitest'; import assert from 'node:assert/strict'; import { readdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import zlib from 'node:zlib'; import { te, td, concat, take } from '../src/bytes.js'; import { assertBytes } from './bytes-assert.js'; import { fromHex } from '../src/sha1.js'; import { plyError as fail } from '../src/errors.js'; import { validateIdent } from '../src/validate.js'; import { parseTree, parseCommit, parseTag, parseIdent, encodeCommit, encodeTag, encodeTree, assertFetched, ident, hashObject, TYPE, } from '../src/objects.js'; import { pkt, FLUSH, DELIM, pktInit, pktStep, pktFinish } from '../src/pktline.js'; import { encodeObjHeader, encodeVarint, buildPack, spliceDelta } from '../src/pack.js'; import { readObjHeader, readOfsDelta, parsePack, applyDelta, parseDelta } from '../src/packresolve.js'; import { readVarint } from '../src/packstream.js'; import { inflate } from '../src/inflate.js'; import { parseSideband as parseSidebandR, spInit, spStep as spStepR, spFinish as spFinishR, v2Init, v2Step as v2StepR } from '../src/fetch.js'; import { parseLsRefLine as parseLsRefLineR, parseUnbornLine } from '../src/lsrefs.js'; import { parseCapabilitiesV2 as parseCapabilitiesV2R } from '../src/discover.js'; import { classifyReport, reportInit, reportStep, streamInit, streamStep, streamFinish, parseCommand, parseCommands } from '../src/push.js'; import { parseReceiveAdvert } from '../src/receivecaps.js'; import { parseUploadPackRequest } from '../src/uprequest.js'; import { fetchBody as fetchBodyR } from '../src/fetch.js'; import { lsRefsBody as lsRefsBodyR } from '../src/lsrefs.js'; import { parseLine, parseFile } from '../src/attributes.js'; import { OID_BYTES, OID_HEX_CHARS, OBJ_CONTINUE, OBJ_SIZE_NEXT_MASK } from '../src/format.js'; import { parseOid, parseCommitId } from '../src/oid.js'; import { parsePath } from '../src/path.js'; import { parseHttpOptions } from '../src/http.js'; import { parseRefname, parseBranchName, parseTagName } from '../src/refname.js'; import { DEFAULT_LIMITS, parseLimits } from '../src/limits.js'; import { unwrap } from './unwrap.js'; // Throwing adapters over the Result API (0.2.0): the assertions below are about the throw. const parseSideband = (...a) => unwrap(parseSidebandR(...a)); const spStep = (...a) => unwrap(spStepR(...a)); const spFinish = (...a) => unwrap(spFinishR(...a)); const v2Step = (...a) => unwrap(v2StepR(...a)); const parseLsRefLine = (...a) => unwrap(parseLsRefLineR(...a)); const parseCapabilitiesV2 = (...a) => unwrap(parseCapabilitiesV2R(...a)); const covered = new Set(); const property = (id, name, fn) => { covered.add(id); test(name, fn); }; const oid = n => n.toString(16).padStart(OID_HEX_CHARS, '0'); const oidBytes = n => fromHex(oid(n)); const CODES = new Set(['pack_corrupt', 'protocol', 'bad_request', 'remote_error', 'unsupported']); function sampleTree() { const entries = [ { mode: '100644', name: 'ab', oid: oid(1) }, { mode: '100644', name: 'c', oid: oid(2) }, { mode: '100755', name: 'de', oid: oid(3) }, ]; return { entries, bytes: unwrap(encodeTree(entries)) }; } // The guard Ivar's review caught: `nul + OID_BYTES > length` plus a clamping subarray. Kept here so the property's // failure mode stays visible — prefix 29 of the 89-byte tree is one byte short of the first object id. function parseTreePreFix(data) { const entries = []; let p = 0; while (p < data.length) { const sp = data.indexOf(0x20, p); const nul = data.indexOf(0, sp); if (sp < 0 || nul < 0 || nul + OID_BYTES > data.length) throw fail('pack_corrupt', 'tree: malformed entry'); entries.push({ mode: td.decode(data.subarray(p, sp)), name: td.decode(data.subarray(sp + 1, nul)), oid: toHexClamp(data.subarray(nul + 1, nul + 1 + OID_BYTES)), oidOffset: nul + 1, }); p = nul + 1 + OID_BYTES; } return entries; } const toHexClamp = b => [...b].map(x => x.toString(16).padStart(2, '0')).join(''); function assertTree(parse, bytes) { const full = parse(bytes); const ends = []; { let p = 0; for (const e of full) { const head = te.encode(`${e.mode} ${e.name}\0`); p += head.length + OID_BYTES; ends.push(p); } } for (let i = 1; i < bytes.length; i++) { let got; try { got = parse(bytes.subarray(0, i)); } catch (e) { assert.equal(e.code, 'pack_corrupt', `prefix ${i} threw ${e.code}: ${e.message}`); continue; } if (!ends.includes(i)) { const last = got.at(-1); throw new Error(`prefix ${i}/${bytes.length} parsed with a ${last ? last.oid.length : 0}-byte last oid`); } const n = ends.indexOf(i) + 1; assert.deepEqual(got.slice(0, n).map(e => [e.mode, e.name, e.oid]), full.slice(0, n).map(e => [e.mode, e.name, e.oid])); for (const e of got) assert.equal(e.oid.length, OID_HEX_CHARS); } } property('tree', 'tree prefix-closure fails on the pre-fix parser at 29/89', () => { const { bytes } = sampleTree(); assert.equal(bytes.length, 89); let message = null; try { assertTree(parseTreePreFix, bytes); } catch (e) { message = e.message; } assert.equal(message, 'prefix 29/89 parsed with a 38-byte last oid'); console.log(` pre-fix tree property: ${message}`); }); property('tree', 'tree prefix-closure holds, including the 29/89 cut', () => { const { bytes, entries } = sampleTree(); assert.equal(bytes.length, 89); assert.throws(() => unwrap(parseTree(bytes.subarray(0, 29))), e => e.code === 'pack_corrupt' && /short read:/.test(e.message)); assertTree(b => unwrap(parseTree(b)), bytes); assert.deepEqual(unwrap(parseTree(bytes)).map(e => e.name), entries.map(e => e.name)); }); test('tree: fsck-hard malformations are rejected; a bad filemode warning still parses', () => { const id = oid(4); const raw = (text, extra = oidBytes(4)) => concat([te.encode(text), extra]); const bad = [ ['empty mode', raw(' a\0')], ['empty name', raw('100644 \0')], ['truncated oid', raw('100644 a\0', oidBytes(4).subarray(0, OID_BYTES - 1))], ['zero-padded mode', raw('0100644 a\0')], ['bare zero mode', raw('0 a\0')], ['non-octal mode', raw('10064g a\0')], ['full pathname', raw('100644 a/b\0')], ['dot', raw('100644 .\0')], ['dotdot', raw('100644 ..\0')], ['dotgit', raw('100644 .git\0')], ['unsorted', concat([raw('100644 b\0'), raw('100644 a\0')])], ['duplicate', concat([raw('100644 a\0'), raw('100644 a\0', oidBytes(5))])], ]; for (const [label, bytes] of bad) assert.throws(() => unwrap(parseTree(bytes)), e => e.code === 'pack_corrupt', label); assert.equal(unwrap(parseTree(raw('100664 a\0')))[0].mode, '100644'); // canon_mode, as git ls-tree prints it assert.equal(unwrap(parseTree(new Uint8Array(0))).length, 0); assert.equal(id.length, OID_HEX_CHARS); }); function linesOf(c) { const lines = []; if (c.tree != null) lines.push(`tree ${c.tree}`); for (const p of c.parents ?? []) lines.push(`parent ${p}`); if (c.object != null) lines.push(`object ${c.object}`); if (c.type != null) lines.push(`type ${c.type}`); if (c.tag != null) lines.push(`tag ${c.tag}`); if (c.author != null) lines.push(`author ${c.author}`); if (c.committer != null) lines.push(`committer ${c.committer}`); if (c.tagger != null) lines.push(`tagger ${c.tagger}`); if (c.encoding != null) lines.push(`encoding ${c.encoding}`); lines.push(...(c.extra ?? [])); return lines; } function headerBounds(bytes) { const text = td.decode(bytes); const bounds = new Set(); const blank = text.indexOf('\n\n'); // The first newline of the blank line is also the last header line's terminator. const headEnd = blank < 0 ? text.length : blank + 1; for (let p = 0; p < headEnd;) { const n = text.indexOf('\n', p); if (n < 0 || n >= headEnd) break; bounds.add(n + 1); p = n + 1; } if (blank >= 0) for (let i = blank + 2; i <= text.length; i++) bounds.add(i); return bounds; } function assertHeaderObject(parse, bytes) { const full = parse(bytes); const bounds = headerBounds(bytes); for (let i = 1; i < bytes.length; i++) { let got; try { got = parse(bytes.subarray(0, i)); } catch (e) { assert.equal(e.code, 'pack_corrupt'); continue; } if (!bounds.has(i)) throw new Error(`prefix ${i}/${bytes.length} parsed off an entry boundary`); const g = linesOf(got), f = linesOf(full); if (got.message === null) assert.deepEqual(g, f.slice(0, g.length)); else { assert.deepEqual(g, f); assert.equal(typeof got.message, 'string'); assert.ok((full.message ?? '').startsWith(got.message)); } } } // Built on first use inside a test, never while the file loads (#307): Stryker counts a src line reached during // module load as a static mutant and runs each mutant on it against the whole mutation suite instead of the tests // that cover it. let fixtureMemo = null; const fixture = () => (fixtureMemo ??= (() => { const author = unwrap(ident(unwrap(validateIdent({ name: 'Ada', email: 'ada@x', time: 1700000000 })))); const commitBytes = unwrap(encodeCommit({ tree: oid(9), parents: [oid(8)], author, message: 'subject\n\nbody\n', extra: ['gpgsig -----BEGIN', ' signature'], })); const tagBytes = unwrap(encodeTag({ object: oid(9), type: 'commit', tag: 'v1', tagger: author, message: 'release\n' })); return { author, commitBytes, tagBytes }; })()); property('commit', 'commit prefix-closure: header lines are entries, the message is an opaque tail', () => { const { author, commitBytes } = fixture(); assertHeaderObject(b => unwrap(parseCommit(b)), commitBytes); assertHeaderObject(b => unwrap(parseCommit(b)), unwrap(encodeCommit({ tree: oid(1), author, message: null }))); assertHeaderObject(b => unwrap(parseCommit(b)), unwrap(encodeCommit({ tree: oid(9), author, encoding: 'UTF-8', message: 'm\n', extra: ['gpgsig -----BEGIN', ' signature'] }))); }); property('tag', 'tag prefix-closure matches the commit header framing', () => { const { tagBytes } = fixture(); assertHeaderObject(b => unwrap(parseTag(b)), tagBytes); }); property('ident', 'ident prefixes are field prefixes and never throw', () => { const line = 'Ada Lovelace 1700000000 +0000'; const full = parseIdent(line); for (let i = 0; i < line.length; i++) { const pre = line.slice(0, i); const got = parseIdent(pre); assert.ok(got); // No closing '>' yet: split_ident_line has not found an email, so the whole line is the name. if (pre.includes('<') && !pre.includes('>')) continue; assert.ok(full.name.startsWith(got.name), JSON.stringify(pre)); assert.ok(full.email.startsWith(got.email)); assert.ok(full.tz.startsWith(got.tz)); if (got.time !== null) assert.ok(full.time.startsWith(got.time)); } }); test('assertFetched and parseCommit apply fsck to a complete object; a header prefix is refused', () => { const { author, tagBytes } = fixture(); const tree = unwrap(encodeTree([{ mode: '100644', name: 'a', oid: oid(1) }])); unwrap(assertFetched('tree', tree)); assert.throws(() => unwrap(assertFetched('tree', tree.subarray(0, tree.length - 1))), e => e.code === 'pack_corrupt'); const good = unwrap(encodeCommit({ tree: oid(1), author, message: 'm\n' })); unwrap(assertFetched('commit', good)); assert.throws(() => unwrap(assertFetched('commit', te.encode(`tree ${oid(1)}\ncommitter ${author}\n\nm\n`))), /missingAuthor/); assert.throws(() => unwrap(assertFetched('commit', te.encode(`tree ${oid(1)}\n\nm\n`))), /missingAuthor/); assert.throws(() => unwrap(assertFetched('commit', te.encode(`tree ${oid(1)}\nauthor Ada 1700000000 +0000\ncommitter ${author}\n\nm\n`))), /missingEmail/); assert.throws(() => unwrap(assertFetched('commit', te.encode(`tree ${oid(1)}\nauthor Ada soon +0000\ncommitter ${author}\n\nm\n`))), /badDate/); assert.throws(() => unwrap(assertFetched('commit', te.encode(`tree short\nauthor ${author}\ncommitter ${author}\n\nm\n`))), /badTreeSha1/); unwrap(assertFetched('tag', tagBytes)); assert.throws(() => unwrap(assertFetched('tag', te.encode(`object ${oid(1)}\ntype commit\ntagger ${author}\n\nm\n`))), /missingTagEntry/); assert.throws(() => unwrap(assertFetched('tag', te.encode(`object ${oid(1)}\ntype commit\n\nm\n`))), /missingTagEntry/); assert.equal(hashObject('blob', te.encode('x')).length, OID_HEX_CHARS); // parseCommit is the fsck check itself (#59): a header prefix that stops before the committer is not a commit assert.throws(() => unwrap(parseCommit(te.encode(`tree ${oid(1)}\n`))), /missingAuthor/); }); function stepPkt(bytes) { let st = pktInit(); const r = unwrap(pktStep(st, bytes)); st = r.state; unwrap(pktFinish(st)); return r.frames; } property('pkt', 'pkt-line prefix-closure, finished so a partial frame cannot hide in the carry', () => { const frames = [unwrap(pkt('hello')), unwrap(pkt('')), FLUSH, DELIM, te.encode('0002'), unwrap(pkt('z'))]; const bytes = concat(frames); const full = stepPkt(bytes); const ends = []; let n = 0; for (const f of frames) { n += f.length; ends.push(n); } for (let i = 1; i < bytes.length; i++) { let got; try { got = stepPkt(bytes.subarray(0, i)); } catch (e) { assert.ok(CODES.has(e.code), e.message); continue; } assert.ok(ends.includes(i), `prefix ${i}/${bytes.length} parsed off a frame boundary`); const k = ends.indexOf(i) + 1; assert.equal(got.length, k); got.forEach((g, j) => { assert.equal(g.kind, full[j].kind); if (g.kind === 'data') assertBytes(g.payload, full[j].payload); }); } }); property('obj-header', 'object-header prefixes are short reads until the continuation bit clears', () => { for (const [type, size] of [[1, 0], [3, 15], [2, 16], [7, 2 ** 20 + 3]]) { const h = encodeObjHeader(type, size); for (let i = 1; i < h.length; i++) assert.throws(() => unwrap(readObjHeader(h.subarray(0, i), 0)), e => e.code === 'pack_corrupt'); const got = unwrap(readObjHeader(h, 0)); assert.equal(got.type, type); assert.equal(got.size, size); assert.equal(got.next, h.length); } }); property('ofs-delta', 'ofs-delta prefixes are short reads until the offset is complete', () => { // off = (1 + 1) * 128 + 2 = 258, two bytes, continuation on the first. const enc = Uint8Array.of(OBJ_CONTINUE | 1, 2); assert.throws(() => unwrap(readOfsDelta(enc.subarray(0, 1), 0)), e => e.code === 'pack_corrupt'); assert.deepEqual(unwrap(readOfsDelta(enc, 0)), { off: (1 + 1) * (OBJ_SIZE_NEXT_MASK + 1) + 2, next: 2 }); }); property('varint', 'size-varint prefixes are short reads until the continuation bit clears', () => { for (const n of [0, 1, 127, 128, 300, 2 ** 20 + 3, 2 ** 40]) { const v = encodeVarint(n); for (let i = 0; i < v.length; i++) { const r = readVarint(v.subarray(0, i), 0, 'delta'); assert.equal(r.ok, false); assert.equal(r.error.reason, 'short_read'); } assert.deepEqual(unwrap(readVarint(v, 0, 'delta')), [n, v.length]); } }); property('pack', 'every strict prefix of a pack throws', async () => { const { pack } = await buildPack([{ type: TYPE.BLOB, data: te.encode('hello') }]); unwrap(parsePack(pack)); for (let i = 1; i < pack.length; i++) assert.throws(() => unwrap(parsePack(pack.subarray(0, i))), e => e.code === 'pack_corrupt'); }); property('delta', 'every strict prefix of a delta throws', () => { const base = te.encode('hello world, hello'); const { delta } = spliceDelta({ baseLen: base.length, off: 6, oldLen: 5, insert: te.encode('there') }); assert.ok(delta.length >= 4); unwrap(applyDelta(base, delta)); unwrap(parseDelta(delta)); for (let i = 1; i < delta.length; i++) { assert.throws(() => unwrap(applyDelta(base, delta.subarray(0, i))), e => e.code === 'pack_corrupt'); assert.throws(() => unwrap(parseDelta(delta.subarray(0, i))), e => e.code === 'pack_corrupt'); } }); property('sideband', 'a sideband frame is a channel byte plus an opaque body prefix', () => { const body = te.encode('pack-bytes'); const payload = concat([Uint8Array.of(1), body]); assert.throws(() => parseSideband(payload.subarray(0, 0)), e => e.code === 'protocol'); for (let i = 1; i < payload.length; i++) { const got = parseSideband(payload.subarray(0, i)); assert.equal(got.band, 1); assertBytes(got.body, body.subarray(0, i - 1)); } }); property('sp-header', 'a strict prefix of a single-object pack does not finish', async () => { const { pack } = await buildPack([{ type: TYPE.BLOB, data: te.encode('xyz') }]); let st = spInit(); for (const chunk of [pack]) { const r = spStep(st, chunk); st = r.state; } spFinish(st); for (let i = 0; i < pack.length; i++) { let s = spInit(); try { s = spStep(s, pack.subarray(0, i)).state; } catch (e) { assert.equal(e.code, 'pack_corrupt'); continue; } assert.throws(() => spFinish(s), e => e.code === 'pack_corrupt'); } }); property('inflate', 'every strict prefix of a zlib stream throws', () => { const z = zlib.deflateSync(Buffer.from('hello prefix')); unwrap(inflate(z)); for (let i = 1; i < z.length; i++) assert.throws(() => unwrap(inflate(z.subarray(0, i))), e => e.code === 'pack_corrupt'); }); property('v2', 'a prefix of a v2 fetch response is a prefix of its sections and pack bytes', () => { const frames = [ { kind: 'data', payload: te.encode('acknowledgments\n') }, { kind: 'data', payload: te.encode('ACK abc common\n') }, { kind: 'delim' }, { kind: 'data', payload: te.encode('packfile\n') }, { kind: 'data', payload: concat([Uint8Array.of(1), te.encode('PACK')]) }, { kind: 'data', payload: concat([Uint8Array.of(2), te.encode('counting')]) }, { kind: 'flush' }, ]; const run = list => { let st = v2Init(); const packs = []; for (const f of list) { const r = v2Step(st, f); st = r.state; if (r.pack) packs.push(r.pack); } return { sections: st.sections, pack: packs.length ? concat(packs) : new Uint8Array(0), done: st.done }; }; const full = run(frames); for (let i = 0; i < frames.length; i++) { const got = run(frames.slice(0, i)); assert.deepEqual(got.sections, full.sections.slice(0, got.sections.length)); assert.ok(full.pack.length >= got.pack.length); assertBytes(got.pack, full.pack.subarray(0, got.pack.length)); } }); property('ls-ref', 'an ls-refs line prefix is a typed error or a field prefix', () => { const line = `${oid(7)} refs/heads/main symref-target:refs/heads/main peeled:${oid(6)}`; const full = parseLsRefLine(line); for (let i = 1; i < line.length; i++) { let got; try { got = parseLsRefLine(line.slice(0, i)); } catch (e) { assert.ok(CODES.has(e.code), e.message); continue; } assert.equal(got.oid, full.oid); assert.ok(full.name.startsWith(got.name)); } }); property('upload-pack-request', 'an upload-pack request cut anywhere is a typed error: its flush comes last', () => { const bodies = [unwrap(fetchBodyR({ wants: [oid(1), oid(2)], haves: [oid(3)], filter: 'tree:0', deepen: 3, deepenNot: ['refs/heads/x'] })), unwrap(lsRefsBodyR(['refs/heads/', 'HEAD'], { unborn: true }))]; for (const body of bodies) { assert.equal(parseUploadPackRequest(body).ok, true); for (let i = 0; i < body.length; i++) { const r = parseUploadPackRequest(body.subarray(0, i)); assert.equal(r.ok, false, `${i} of ${body.length} bytes`); assert.ok(CODES.has(r.error.code), r.error.message); } } }); property('ls-unborn', 'an unborn line prefix records nothing or a prefix of the target', () => { const line = 'unborn HEAD peeled:x symref-target:refs/heads/main symref-target:refs/heads/other'; assert.deepEqual(parseUnbornLine(line), { name: 'HEAD', target: 'refs/heads/main' }); for (let i = 1; i < line.length; i++) { const got = parseUnbornLine(line.slice(0, i)); if (got !== null) assert.ok('refs/heads/main'.startsWith(got.target), got.target); } }); property('caps', 'a v2 capability advertisement cut anywhere is a typed error: its flush comes last', () => { const data = l => ({ kind: 'data', payload: te.encode(l) }); const frames = [data('# service=git-upload-pack\n'), { kind: 'flush' }, data('version 2\n'), data('agent=git/2.50.0\n'), data('ls-refs=unborn\n'), data('fetch=shallow wait-for-done filter\n'), data('object-format=sha1\n'), { kind: 'flush' }]; assert.deepEqual(parseCapabilitiesV2(frames), ['agent=git/2.50.0', 'ls-refs=unborn', 'fetch=shallow wait-for-done filter', 'object-format=sha1']); for (let i = 0; i < frames.length; i++) assert.throws(() => parseCapabilitiesV2(frames.slice(0, i)), e => CODES.has(e.code), `${i} frames`); }); test('caps: a v0/v1 answer is unsupported and a pkt after the flush is refused, each by its own check', () => { const data = l => ({ kind: 'data', payload: te.encode(l) }); // a v0 ref advertisement ends in a flush too: only the version check refuses it const v0 = [data(`${'a'.repeat(40)} HEAD\0multi_ack\n`), data(`${'a'.repeat(40)} refs/heads/main\n`), { kind: 'flush' }]; assert.throws(() => parseCapabilitiesV2(v0), e => e.code === 'unsupported' && e.message === `server did not answer protocol v2 (first line ${JSON.stringify(`${'a'.repeat(40)} HEAD\0multi_ack`)})` && e.lines.length === 1); const trailing = [data('version 2\n'), data('agent=git/2.50.0\n'), { kind: 'flush' }, { kind: 'delim' }]; assert.throws(() => parseCapabilitiesV2(trailing), e => e.code === 'protocol' && e.message === "advertisement: delim after the capabilities' flush"); }); property('advertisement', 'a receive-pack advertisement cut anywhere is a typed Err: its flush comes last', () => { const data = l => ({ kind: 'data', payload: te.encode(l) }); const frames = [data('# service=git-receive-pack\n'), { kind: 'flush' }, data(`${oid(1)} refs/heads/main\0report-status atomic\n`), data(`${oid(2)} refs/heads/x\n`), data(`shallow ${oid(3)}\n`), { kind: 'flush' }]; assert.deepEqual(parseReceiveAdvert(frames), { ok: true, value: new Set(['report-status', 'atomic']) }); for (let i = 0; i < frames.length; i++) { const r = parseReceiveAdvert(frames.slice(0, i)); assert.equal(r.ok, false, `${i} frames`); assert.ok(CODES.has(r.error.code), `${i} frames`); } }); property('report', 'the report machine steps line by line: a prefix that is malformed stays malformed, and a statuses prefix only grows', () => { const commands = [{ ref: 'refs/heads/main' }, { ref: 'refs/heads/other' }]; const lines = ['unpack ok\n', 'ok refs/heads/main\n', 'ng refs/heads/other hook declined\n', 'option old-oid abcdef\n'].map(l => te.encode(l)); let st = reportInit(commands); const seen = []; for (const l of lines) { st = reportStep(st, l); seen.push(st.tag === 'refs' ? st.seen.size : st.tag); } // option lines are not git's plain report (proc-receive only): the machine becomes malformed there and stays so assert.deepEqual(seen, [0, 1, 2, 'malformed']); assert.equal(reportStep(st, lines[0]), st); assert.deepEqual(classifyReport([te.encode('unpack o\n')], commands), { tag: 'malformed', why: 'no git unpack line first' }); }); property('report', 'a proper prefix of a git report never classifies as definite', () => { const commands = [{ ref: 'refs/heads/main' }, { ref: 'refs/heads/other' }]; const lines = ['unpack ok\n', 'ok refs/heads/main\n', 'ng refs/heads/other hook declined\n'].map(l => te.encode(l)); assert.equal(classifyReport(lines, commands).tag, 'statuses'); for (let i = 0; i < lines.length; i++) assert.equal(classifyReport(lines.slice(0, i), commands).tag, 'malformed', `${i} lines`); const last = lines.at(-1); for (let j = 0; j < last.length; j++) assert.equal(classifyReport([...lines.slice(0, -1), last.subarray(0, j)], commands).tag, 'malformed', `last line cut at ${j}`); }); property('stream', 'a proper prefix of a git response stream is never a report', () => { const inner = concat([unwrap(pkt('unpack ok\n')), unwrap(pkt('ok refs/heads/main\n')), FLUSH]); const shapes = { plain: { sideband: false, frames: [{ kind: 'data', payload: te.encode('unpack ok\n') }, { kind: 'data', payload: te.encode('ok refs/heads/main\n') }, { kind: 'flush' }] }, sideband: { sideband: true, frames: [{ kind: 'data', payload: concat([Uint8Array.of(2), te.encode('hook\n')]) }, { kind: 'data', payload: concat([Uint8Array.of(1), inner]) }, { kind: 'data', payload: Uint8Array.of(1) }, { kind: 'flush' }] }, }; for (const [name, { sideband, frames }] of Object.entries(shapes)) { const run = fs => { let st = streamInit(sideband); for (const f of fs) st = unwrap(streamStep(st, f)); return streamFinish(st); }; assert.equal(run(frames).tag, 'report', name); assert.equal(run(frames).lines.length, 2, name); for (let i = 0; i < frames.length; i++) assert.equal(run(frames.slice(0, i)).tag, 'broken', `${name}: ${i} frames`); if (sideband) for (let j = 1; j < inner.length; j++) assert.equal(run([frames[0], { kind: 'data', payload: concat([Uint8Array.of(1), inner.subarray(0, j)]) }, { kind: 'flush' }]).tag, 'broken', `band 1 cut at ${j}`); } }); property('attr-line', 'a gitattributes line prefix parses as a pattern prefix or not at all', () => { const line = '*.txt text ident'; const full = parseLine(line, { macrosOk: false }); for (let i = 1; i < line.length; i++) { const got = parseLine(line.slice(0, i), { macrosOk: false }); if (!got?.pat) continue; assert.ok(full.pat.pattern.startsWith(got.pat.pattern)); } }); property('attr-file', 'a gitattributes file prefix is a prefix of its patterns', () => { const text = '*.txt text\n*.c diff=cpp\n'; const pats = rows => rows.map(l => l.pat?.pattern).filter(Boolean); const full = pats(parseFile(text)); for (let i = 1; i < text.length; i++) { const got = pats(parseFile(text.slice(0, i))); assert.ok(got.length <= full.length); got.forEach((p, j) => { if (j < got.length - 1 || text[i - 1] === '\n') assert.equal(p, full[j]); else assert.ok(full[j].startsWith(p)); }); } }); property('oid', 'a prefix of an object id is not an object id', () => { const full = 'a'.repeat(OID_HEX_CHARS); assert.equal(parseOid(full).ok, true); for (let i = 0; i < full.length; i++) { const r = parseOid(full.slice(0, i)); assert.equal(r.ok, false); if (!r.ok) assert.equal(r.error.code, 'bad_request'); } }); // A validator has no framing: a prefix of a valid name may itself be valid ("refs/heads/m" of "refs/heads/main"). // Closure here is that every prefix is a value equal to that prefix or a typed bad_request, never a throw or another value. const closedUnderPrefix = (full, parse, valueOf) => { const whole = parse(full); assert.equal(whole.ok, true, full); assert.equal(valueOf(whole.value), full); for (let i = 0; i < full.length; i++) { const cut = full.slice(0, i); const r = parse(cut); if (r.ok) assert.equal(valueOf(r.value), cut, `prefix ${JSON.stringify(cut)} parsed to another value`); else assert.equal(r.error.code, 'bad_request', `prefix ${JSON.stringify(cut)}`); } }; // A push command: every prefix of its ref is that ref or a bad_request; a prefix of an oid is never an oid. A prefix of // the list is that list, and the empty one is 'protocol' (nothing to push), never a throw. property('push-command', 'a prefix of a command field is that value or a bad_request; the empty list is protocol', () => { const a = 'a'.repeat(OID_HEX_CHARS), b = 'b'.repeat(OID_HEX_CHARS); closedUnderPrefix('refs/heads/main', v => parseCommand({ ref: v, oldOid: a, newOid: b }), v => v.ref); for (const key of ['oldOid', 'newOid']) { for (let i = 0; i < OID_HEX_CHARS; i++) { const r = parseCommand({ ref: 'refs/heads/main', oldOid: a, newOid: b, [key]: a.slice(0, i) }); assert.deepEqual([r.ok, r.error?.code, r.error?.message], [false, 'bad_request', 'push: oids must be 40-hex'], `${key} ${i}`); } } const list = ['refs/heads/x', 'refs/heads/y', 'refs/tags/z'].map(ref => ({ ref, oldOid: a, newOid: b })); for (let i = 0; i <= list.length; i++) { const r = parseCommands(list.slice(0, i)); if (i === 0) assert.deepEqual([r.ok, r.error.code, r.error.message], [false, 'protocol', 'push: no commands']); else assert.deepEqual(unwrap(r).map(c => c.ref), list.slice(0, i).map(c => c.ref)); } }); // The transport's options: every prefix of a remote URL (with userinfo, a port, a path) is settings for that URL or a // bad_request, never a throw. An absolute URL's prefix that still parses is that prefix, without its userinfo. property('http-options', 'a prefix of a remote URL is settings for that URL or a bad_request', () => { for (const full of ['https://user:tok@example.com:8443/org/repo.git', 'http://127.0.0.1/r', 'https://h/a%20b']) { for (let i = 0; i <= full.length; i++) { const r = parseHttpOptions(full.slice(0, i)); if (r.ok) assert.equal(r.value.url.username + r.value.url.password, '', full.slice(0, i)); else assert.equal(r.error.code, 'bad_request', full.slice(0, i)); } } }); // A limits record's prefix is its first keys (in DEFAULT_LIMITS order): every key it gives is taken, every key it leaves // out is the default. A bad key is refused from the first prefix that holds it on, and never before. property('limits', 'a prefix of a limits record is that record with the defaults for the rest, or the first bad key', () => { const keys = Object.keys(DEFAULT_LIMITS); const full = Object.fromEntries(keys.map((k, i) => [k, i + 1])); // no bad key (badAt past the end), or one at the first, a middle or the last key for (const [badAt, value] of [[keys.length, 0], [0, Infinity], [3, -1], [keys.length - 1, NaN]]) { const record = badAt < keys.length ? { ...full, [keys[badAt]]: value } : full; for (let i = 0; i <= keys.length; i++) { const prefix = Object.fromEntries(keys.slice(0, i).map(k => [k, record[k]])); const r = parseLimits(prefix); if (i > badAt) { assert.deepEqual([r.ok, r.error?.code, r.error?.what], [false, 'bad_request', keys[badAt]], String(i)); continue; } assert.equal(r.ok, true, String(i)); // a key left out is the default, but maxResolveWork left out is derived: 8 x the maxInflatedTotal of the same record const inflated = keys.indexOf('maxInflatedTotal') < i ? record.maxInflatedTotal : DEFAULT_LIMITS.maxInflatedTotal; for (const [j, k] of keys.entries()) assert.equal(r.value[k], j < i ? record[k] : k === 'maxResolveWork' ? 8 * inflated : DEFAULT_LIMITS[k], `${i} ${k}`); } } }); property('path', 'a prefix of a path is that path or a bad_request', () => { for (const full of ['a', 'src/index.ts', 'a/b/c/d.e', 'dir with space/f\u00e9.txt', '.github/workflows/ci.yml']) { closedUnderPrefix(full, v => parsePath(v, DEFAULT_LIMITS), v => v.path); } }); property('refname', 'a prefix of a refname is that refname or a bad_request', () => { for (const full of ['refs/heads/main', 'refs/heads/feature/x-1', 'refs/tags/v1.2.3', 'refs/notes/commits']) closedUnderPrefix(full, parseRefname, v => v); for (const full of ['refs/heads/main', 'refs/heads/a/b']) closedUnderPrefix(full, parseBranchName, v => v); for (const full of ['refs/tags/v1.2.3', 'refs/tags/release/2026']) closedUnderPrefix(full, parseTagName, v => v); // a valid ref of the other kind is refused by name, not by syntax const tagAsBranch = parseBranchName('refs/tags/v1.2.3'); assert.equal(tagAsBranch.ok, false); if (!tagAsBranch.ok) assert.equal(tagAsBranch.error.code, 'bad_request'); assert.equal(parseTagName('refs/heads/main').ok, false); }); property('commit-id', 'a prefix of a commit id is not a commit id', () => { const full = 'b'.repeat(OID_HEX_CHARS); assert.equal(parseCommitId(full).ok, true); for (let i = 0; i < full.length; i++) { const r = parseCommitId(full.slice(0, i)); assert.equal(r.ok, false); if (!r.ok) assert.equal(r.error.code, 'bad_request'); } }); test('take() throws a typed short read and does not clamp', () => { const buf = new Uint8Array([1, 2, 3, 4]); assert.throws(() => unwrap(take(buf, 2, 3)), e => e.code === 'pack_corrupt' && e.message.startsWith('short read:')); assert.throws(() => unwrap(take(buf, 3, 2, 'protocol')), e => e.code === 'protocol' && e.message.startsWith('short read:')); assert.deepEqual([...unwrap(take(buf, 1, 2))], [2, 3]); assert.equal(unwrap(take(buf, 4, 0)).length, 0); }); const DECODER_EXPORT = /^(parse[A-Z]\w*|readObjHeader|readOfsDelta|readVarint|applyDelta|inflate|pktStep|pktFinish|spStep|v2Step)(Result)?$/; test('every exported decoder has a prefix-closure property', () => { const missing = []; const annotated = []; for (const file of readdirSync('src').filter(f => /\.[jt]s$/.test(f))) { const text = readFileSync(join('src', file), 'utf8'); const anns = [...text.matchAll(/@decoder\s+(\w+)\s+prefix=([\w-]+)/g)].map(m => ({ name: m[1], prefix: m[2] })); for (const a of anns) annotated.push({ file, ...a }); for (const m of text.matchAll(/export (?:async )?function (\w+)/g)) { if (DECODER_EXPORT.test(m[1]) && !anns.some(a => a.name === m[1])) missing.push(`${file}: ${m[1]}`); } } assert.deepEqual(missing, [], `decoder exports without @decoder:\n${missing.join('\n')}`); const uncovered = annotated.filter(a => !covered.has(a.prefix)); assert.deepEqual(uncovered.map(a => `${a.file} ${a.name} prefix=${a.prefix}`), []); console.log(` decoders: ${annotated.map(a => a.name).sort().join(', ')}`); });