main
1// Signed commits: our SSH/Ed25519 signature must verify with git (which shells out to ssh-keygen -Y verify) and with
2// ssh-keygen directly over the exact bytes git signs; a tampered commit must not verify; fsck must stay clean.
3import { test, beforeAll as before, afterAll as after } from 'vitest';
4import assert from 'node:assert/strict';
5import { join } from 'node:path';
6import { mkdirSync, writeFileSync } from 'node:fs';
7import { execFileSync, spawnSync } from 'node:child_process';
8import { git, tmpRoot, makeBareRepo, startGitServer, commitFiles, fsckProblems, initRepo } from './server.js';
9import { editFile, buildCommitObjects, withCommitData } from '../src/edit.js';
10import { generateSigner, signCommit, withGpgsig, armor } from '../src/sign.js';
11import { encodeCommit, hashObject, parseCommit } from '../src/objects.js';
12import { Tracer, arrayExporter, flattenLine } from '../src/otel.js';
13import { unwrap, unwrapAsync } from './unwrap.js';
15let root, cleanup, srv, bare, work, url, signers;
16const author = { name: 'signer', email: 'signer@x' };
17before(async () => {
18 ({ root, cleanup } = tmpRoot()); srv = await startGitServer(root);
19 bare = makeBareRepo(root, 'sg'); work = join(root, 'wsg'); mkdirSync(work); initRepo(work);
20 commitFiles(work, bare, { 'f.txt': 'hello MARK\n' }, 'seed');
21 url = `${srv.url}/sg.git`;
22 signers = join(root, 'allowed_signers');
23});
24after(async () => { await srv.close(); cleanup(); });
26// the real ssh-keygen: some environments point gpg.ssh.program at a signing-only shim
27const G = () => ['-C', bare, '-c', 'gpg.format=ssh', '-c', 'gpg.ssh.program=ssh-keygen', '-c', `gpg.ssh.allowedSignersFile=${signers}`];
28const verifyCommit = oid => { const r = spawnSync('git', [...G(), 'verify-commit', '--raw', oid], { encoding: 'utf8' }); return { ok: r.status === 0, out: r.stdout + r.stderr }; }; // git prints the verdict on stderr
30test('editFile with a signer: git verify-commit accepts the commit; ssh-keygen verifies the raw signature; tampering is caught', async () => {
31 const { signer, publicKeyRaw } = await generateSigner();
32 writeFileSync(signers, `${author.email} namespaces="git" ${signer.publicKeyLine}\n`);
33 const ex = arrayExporter();
34 const r = await unwrapAsync(editFile(url, { path: 'f.txt', find: 'MARK', replace: 'SIGNED', author, message: 'signed edit' }, { tracer: new Tracer({ exporter: ex }), signer }));
35 assert.equal(git(bare, ['rev-parse', 'main']).trim(), r.newCommit);
36 const rootSpan = ex.lines.flatMap(flattenLine).find(s => s.name === 'git.edit');
37 assert.equal(rootSpan.attrs['git.edit.commit.signed'], 'ssh-ed25519'); assert.equal(rootSpan.attrs['git.edit.commit.signer'], signer.publicKeyLine);
38 // 1. git's verdict
39 const v = verifyCommit(r.newCommit);
40 assert.ok(v.ok, v.out); assert.match(v.out, /GOODSIG|Good "git" signature/);
41 assert.equal(execFileSync('git', [...G(), 'log', '-1', '--format=%G?', r.newCommit], { encoding: 'utf8' }).trim(), 'G', '%G? = G (good)');
42 // 2. header layout: gpgsig right after committer, continuation lines space-prefixed, body intact
43 const raw = execFileSync('git', ['-C', bare, 'cat-file', 'commit', r.newCommit], { encoding: 'utf8' });
44 const headers = raw.slice(0, raw.indexOf('\n\n')).split('\n');
45 const ci = headers.findIndex(l => l.startsWith('committer ')); assert.ok(headers[ci + 1].startsWith('gpgsig -----BEGIN SSH SIGNATURE-----'));
46 assert.ok(headers.slice(ci + 2).every(l => l.startsWith(' ')), 'continuation lines');
47 assert.equal(unwrap(parseCommit(new TextEncoder().encode(raw))).message, 'signed edit\n');
48 // 3. ssh-keygen over the exact payload git signs (the commit without its gpgsig header)
49 const payload = raw.split('\n').filter((l, i, a) => !(l.startsWith('gpgsig ') || (i > ci + 1 && l.startsWith(' ') && a.slice(ci + 1, i).every(x => x.startsWith('gpgsig ') || x.startsWith(' '))))).join('\n');
50 const sigText = headers.slice(ci + 1).map(l => l.replace(/^gpgsig /, '').replace(/^ /, '')).join('\n') + '\n';
51 const sigFile = join(root, 'c.sig'); writeFileSync(sigFile, sigText);
52 const sk = execFileSync('ssh-keygen', ['-Y', 'verify', '-f', signers, '-I', author.email, '-n', 'git', '-s', sigFile], { input: payload, encoding: 'utf8' });
53 assert.match(sk, /Good "git" signature/);
54 // 4. tamper: same signature over a different message must fail
55 const bad = unwrap(withGpgsig(unwrap(encodeCommit({ ...unwrap(parseCommit(new TextEncoder().encode(payload))), author: unwrap(parseCommit(new TextEncoder().encode(payload))).author, committer: unwrap(parseCommit(new TextEncoder().encode(payload))).committer, message: 'tampered\n' })), sigText));
56 const badOid = execFileSync('git', ['-C', bare, 'hash-object', '-t', 'commit', '-w', '--stdin'], { input: bad, encoding: 'utf8' }).trim();
57 const tampered = verifyCommit(badOid);
58 assert.equal(tampered.ok, false); assert.match(tampered.out, /incorrect signature/, 'rejected for the signature, not for some other reason');
59 // 5. fsck is clean with the signed commit in history
60 assert.deepEqual(fsckProblems(bare), []);
61 assert.equal(git(bare, ['cat-file', '-p', 'main:f.txt']), 'hello SIGNED\n');
62});
64test('withCommitData keeps trees/blob objects and recomputes identity; armor wraps at 70 like ssh-keygen', async () => {
65 const commit = unwrap(encodeCommit({ tree: 'a'.repeat(40), parents: [], author: 'n <e@x> 1 +0000', committer: 'n <e@x> 1 +0000', message: 'm\n' }));
66 const built = { commitData: commit, newCommit: hashObject('commit', commit), objects: [{ type: 1, data: commit }, { type: 2, data: new Uint8Array(5), base: { tag: 'ref', oid: 'b'.repeat(40) } }], trees: [], newTree: 'a'.repeat(40) };
67 const { signer } = await generateSigner();
68 const signed = await unwrapAsync(signCommit(commit, signer));
69 const w = withCommitData(built, signed);
70 assert.equal(w.newCommit, hashObject('commit', signed)); assert.notEqual(w.newCommit, built.newCommit);
71 assert.equal(w.objects.length, 2); assert.equal(w.objects[1], built.objects[1]);
72 const text = new TextDecoder().decode(signed);
73 assert.ok(text.includes('\ncommitter n <e@x> 1 +0000\ngpgsig -----BEGIN SSH SIGNATURE-----\n '));
74 const a = armor(new Uint8Array(200)); for (const l of a.split('\n').slice(1, -2)) assert.ok(l.length <= 70);
75 assert.throws(() => unwrap(withGpgsig(new TextEncoder().encode('tree x\n\nm'), 'sig')), e => e.code === 'bad_request');
76});
78// objects/signcommit-null-message-bad-signature: a commit with no body section (encodeCommit's default, message null)
79// ends after its last header line. What is signed is that commit, so the signed object with its gpgsig header taken
80// out again must be those bytes exactly, and git's own verdict on the signature (verify-commit) is the judge.
81test('signCommit on a commit with no body section: git verify-commit accepts it and the payload is the unsigned commit', async () => {
82 const { signer } = await generateSigner();
83 writeFileSync(signers, `${author.email} namespaces="git" ${signer.publicKeyLine}\n`);
84 const tree = git(bare, ['rev-parse', 'main^{tree}']).trim();
85 const who = `${author.name} <${author.email}> 1700000000 +0000`;
86 for (const [what, more] of [['no body section', {}], ['no body section, with an encoding', { encoding: 'ISO-8859-1' }], ['no body section, with an extra header', { extra: ['x-note 1'] }]]) {
87 const unsigned = unwrap(encodeCommit({ tree, author: who, ...more }));
88 const text = new TextDecoder().decode(unsigned);
89 assert.ok(text.endsWith('\n') && !text.includes('\n\n'), `${what}: the unsigned commit has no blank line`);
90 const signed = unwrap(await signCommit(unsigned, signer));
91 // the payload git verifies: the object without the gpgsig header and its continuation lines (taken out by hand)
92 const lines = new TextDecoder().decode(signed).split('\n');
93 const at = lines.findIndex(l => l.startsWith('gpgsig '));
94 let end = at + 1;
95 while (lines[end].startsWith(' ')) end++;
96 lines.splice(at, end - at);
97 assert.equal(lines.join('\n'), text, `${what}: the signed commit without its gpgsig header is the commit that was signed`);
98 const oid = execFileSync('git', ['-C', bare, 'hash-object', '-t', 'commit', '-w', '--stdin'], { input: signed, encoding: 'utf8' }).trim();
99 const v = verifyCommit(oid);
100 assert.ok(v.ok, `${what}: git verify-commit: ${v.out}`);
101 assert.match(v.out, /GOODSIG|Good "git" signature/);
102 // still no body section, as the unsigned commit had none
103 assert.equal(unwrap(parseCommit(signed)).message, null, what);
104 }
105});
Diagnostics4 git calls · 284 ms
CallStatusSizeTime0284 ms
discover200152 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200145 B4 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=1 git.response.bytes=145 git.response.cache=UPDATING git.response.duration_ms=1 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=145 git.pkt.payload.max=76 git.ls_refs.count=2 git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020038 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=38434 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=6 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=38434 git.pkt.payload.max=38339 git.sideband.band1.bytes=38338 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=63 git.pack.bytes=38338 git.pack.ofs_delta=0 git.pack.ref_delta=8 git.pack.chain.max=8 git.pack.trailer=0bc36ab7adf82d3109177f11f1ea93f1ce071f77 git.pack.full=55Open pack map
fetch2003.0 KiB277 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=277 git.response.bytes=3116 git.response.cache=MISS git.response.duration_ms=277 git.fetch.wants=8d113328910a5812d9a5a2629805b799463c66c3 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=3116 git.pkt.payload.max=3095 git.sideband.band1.bytes=3094 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply.git
- Ref
- refs/heads/main
- Commit
- 19912563f540228593df0c489082e5e2508e21e4
- cf-ray
- a5e2d47a2af1689d
- Request
- 26c97bc0…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format