gunk-dev/the-valley

bundle_test.go

source8ea96b8e18d0main's published tip history
15.8 KiB
1package export_test
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "syscall"
14 "testing"
15 "time"
16
17 "the-valley/web/export"
18 "the-valley/web/export/exporttest"
19)
20
21// git runs git for a test, with none of the caller's GIT_ variables and no
22// system or global configuration, and returns its trimmed output.
23func git(t *testing.T, dir string, stdin []byte, args ...string) string {
24 t.Helper()
25 if dir != "" {
26 args = append([]string{"-C", dir}, args...)
27 }
28 cmd := exec.Command("git", args...)
29 for _, kv := range os.Environ() {
30 if !strings.HasPrefix(kv, "GIT_") {
31 cmd.Env = append(cmd.Env, kv)
32 }
33 }
34 cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
35 "GIT_AUTHOR_NAME=Example Author", "GIT_AUTHOR_EMAIL=author@example.org",
36 "GIT_COMMITTER_NAME=Example Author", "GIT_COMMITTER_EMAIL=author@example.org",
37 "GIT_AUTHOR_DATE=2026-10-01T09:00:00Z", "GIT_COMMITTER_DATE=2026-10-01T09:00:00Z")
38 if stdin != nil {
39 cmd.Stdin = bytes.NewReader(stdin)
40 }
41 var out, stderr bytes.Buffer
42 cmd.Stdout, cmd.Stderr = &out, &stderr
43 if err := exporttest.Run(t, cmd, gitTimeout); err != nil {
44 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String())
45 }
46 return strings.TrimSpace(out.String())
47}
48
49// gitTimeout is how long a test waits for one git command.
50const gitTimeout = 2 * time.Minute
51
52// source is a bare repository whose main has two commits, first and tip,
53// and whose side branch has a commit main does not reach.
54type source struct {
55 repo, first, tip, side string
56}
57
58func newSource(t *testing.T, format string) source {
59 t.Helper()
60 repo := filepath.Join(t.TempDir(), "source.git")
61 git(t, "", nil, "init", "--quiet", "--bare", "--initial-branch=main", "--object-format="+format, repo)
62 commit := func(parent, file, content string) string {
63 blob := git(t, repo, []byte(content), "hash-object", "-w", "--stdin")
64 tree := git(t, repo, []byte(fmt.Sprintf("100644 blob %s\t%s\n", blob, file)), "mktree")
65 args := []string{"commit-tree", tree, "-m", file}
66 if parent != "" {
67 args = append(args, "-p", parent)
68 }
69 return git(t, repo, nil, args...)
70 }
71 s := source{repo: repo}
72 s.first = commit("", "README.md", "# source\n")
73 s.tip = commit(s.first, "main.go", "package main\n")
74 s.side = commit(s.first, "side.txt", "not on main\n")
75 git(t, repo, nil, "update-ref", "refs/heads/main", s.tip)
76 git(t, repo, nil, "update-ref", "refs/heads/side", s.side)
77 return s
78}
79
80func (s source) bundle(t *testing.T, args ...string) string {
81 t.Helper()
82 path := filepath.Join(t.TempDir(), "b.bundle")
83 git(t, s.repo, nil, append([]string{"bundle", "create", "--quiet", path}, args...)...)
84 return path
85}
86
87// A full bundle of main at the declared tip is accepted into a fresh bare
88// repository holding main alone, with a commit-graph of main's history
89// that git verifies.
90func TestAcceptBundle(t *testing.T) {
91 ctx := context.Background()
92 for _, format := range []string{"sha1", "sha256"} {
93 t.Run(format, func(t *testing.T) {
94 s := newSource(t, format)
95 repo := filepath.Join(t.TempDir(), "app.git")
96 if err := export.AcceptBundle(ctx, s.bundle(t, "main"), repo, s.tip); err != nil {
97 t.Fatal(err)
98 }
99 if refs := git(t, repo, nil, "for-each-ref", "--format=%(refname) %(objectname)"); refs != "refs/heads/main "+s.tip {
100 t.Errorf("the repository holds %q", refs)
101 }
102 if got := git(t, repo, nil, "rev-parse", "--show-object-format"); got != format {
103 t.Errorf("the repository is %s", got)
104 }
105 hasCommitGraph(t, repo)
106 })
107 }
108}
109
110// hasCommitGraph checks that repo has a commit-graph git verifies.
111func hasCommitGraph(t *testing.T, repo string) {
112 t.Helper()
113 if _, err := os.Stat(filepath.Join(repo, "objects", "info", "commit-graph")); err != nil {
114 t.Errorf("the repository has no commit-graph: %v", err)
115 }
116 git(t, repo, nil, "commit-graph", "verify")
117}
118
119// A bundle and a repository named relative to the working directory are
120// read and written there.
121func TestAcceptBundleTakesRelativePaths(t *testing.T) {
122 s := newSource(t, "sha1")
123 bundle := s.bundle(t, "main")
124 t.Chdir(filepath.Dir(bundle))
125 if err := export.AcceptBundle(context.Background(), filepath.Base(bundle), "app.git", s.tip); err != nil {
126 t.Fatal(err)
127 }
128 if _, err := os.Stat(filepath.Join(filepath.Dir(bundle), "app.git", "HEAD")); err != nil {
129 t.Error(err)
130 }
131}
132
133// What the acceptance procedure refuses, each leaving no repository.
134func TestAcceptBundleRefuses(t *testing.T) {
135 ctx := context.Background()
136 s := newSource(t, "sha1")
137 good := s.bundle(t, "main")
138 corrupt := func() string {
139 data, err := os.ReadFile(good)
140 if err != nil {
141 t.Fatal(err)
142 }
143 // Past the header, in the pack: flip one byte of the last object.
144 data[len(data)-30] ^= 0xff
145 path := filepath.Join(t.TempDir(), "corrupt.bundle")
146 if err := os.WriteFile(path, data, 0o644); err != nil {
147 t.Fatal(err)
148 }
149 return path
150 }
151 cases := []struct {
152 name, bundle, tip, says string
153 }{
154 {"a wrong tip", good, s.first, "the manifest declares"},
155 {"prerequisites", s.bundle(t, "main~1..main"), s.tip, "prerequisite"},
156 {"an extra ref", s.bundle(t, "main", "side"), s.tip, "2 refs"},
157 {"another ref than main", s.bundle(t, "side"), s.side, "refs/heads/side"},
158 {"a corrupt pack", corrupt(), s.tip, "git fetch"},
159 {"a malformed commit", malformedBundle(t), "", "fsck"},
160 {"no bundle", filepath.Join(t.TempDir(), "missing.bundle"), s.tip, "no such file"},
161 }
162 for _, c := range cases {
163 t.Run(c.name, func(t *testing.T) {
164 tip := c.tip
165 if tip == "" {
166 tip = bundleTip(t, c.bundle)
167 }
168 repo := filepath.Join(t.TempDir(), "app.git")
169 err := export.AcceptBundle(ctx, c.bundle, repo, tip)
170 if err == nil || !strings.Contains(err.Error(), c.says) {
171 t.Fatalf("AcceptBundle gave %v, want an error saying %q", err, c.says)
172 }
173 if c.name != "no bundle" {
174 wantCode(t, err, export.CodeBadBundle)
175 }
176 if _, err := os.Lstat(repo); !os.IsNotExist(err) {
177 t.Errorf("the refusal left %s behind", repo)
178 }
179 })
180 }
181 t.Run("a repository that exists", func(t *testing.T) {
182 repo := t.TempDir()
183 if err := export.AcceptBundle(ctx, good, repo, s.tip); err == nil {
184 t.Fatal("AcceptBundle fetched into a directory that existed")
185 }
186 if _, err := os.Lstat(repo); err != nil {
187 t.Errorf("the refusal removed the directory that was there: %v", err)
188 }
189 })
190}
191
192// A bundle's header is read through a 64 KiB bound on the file. A header
193// with no line end, a thousand times longer, is refused once the bound
194// is reached: the receiver reads about 64 KiB of it, not the whole of it.
195// The bundle is a named pipe, so the test counts what was read.
196func TestAcceptBundleBoundsTheHeader(t *testing.T) {
197 path := filepath.Join(t.TempDir(), "endless.bundle")
198 if err := syscall.Mkfifo(path, 0o600); err != nil {
199 t.Fatal(err)
200 }
201 const offered = 64 << 20
202 taken := make(chan int64, 1)
203 go func() {
204 w, err := os.OpenFile(path, os.O_WRONLY, 0)
205 if err != nil {
206 taken <- -1
207 return
208 }
209 defer w.Close()
210 n, _ := w.Write([]byte("# v2 git bundle\n"))
211 total := int64(n)
212 chunk := bytes.Repeat([]byte("a"), 32<<10)
213 for total < offered {
214 n, err := w.Write(chunk)
215 total += int64(n)
216 if err != nil {
217 break // the receiver closed the bundle
218 }
219 }
220 taken <- total
221 }()
222 repo := filepath.Join(t.TempDir(), "app.git")
223 err := export.AcceptBundle(context.Background(), path, repo, strings.Repeat("1", 40))
224 if err == nil || !strings.Contains(err.Error(), "longer than") {
225 t.Fatalf("AcceptBundle gave %v, want a refusal of the header's length", err)
226 }
227 wantCode(t, err, export.CodeBadBundle)
228 // What the pipe holds unread comes on top of what was read.
229 if n := <-taken; n < 0 || n > 4<<20 {
230 t.Errorf("the receiver took %d bytes of a header with no end, want about 64 KiB", n)
231 }
232 if _, err := os.Lstat(repo); !os.IsNotExist(err) {
233 t.Errorf("the refusal left %s behind", repo)
234 }
235}
236
237// bundleTip is the one ref a bundle's header names.
238func bundleTip(t *testing.T, path string) string {
239 t.Helper()
240 return strings.Fields(git(t, "", nil, "bundle", "list-heads", path))[0]
241}
242
243// malformedBundle is a bundle of a main whose tip is a commit fsck
244// refuses: its author has no email and no date.
245func malformedBundle(t *testing.T) string {
246 t.Helper()
247 repo := filepath.Join(t.TempDir(), "bad.git")
248 git(t, "", nil, "init", "--quiet", "--bare", "--initial-branch=main", repo)
249 tree := git(t, repo, nil, "mktree")
250 bad := git(t, repo, []byte("tree "+tree+"\nauthor nobody\ncommitter nobody\n\nmalformed\n"),
251 "hash-object", "-t", "commit", "--literally", "-w", "--stdin")
252 git(t, repo, nil, "update-ref", "refs/heads/main", bad)
253 path := filepath.Join(t.TempDir(), "bad.bundle")
254 git(t, repo, nil, "bundle", "create", "--quiet", path, "main")
255 return path
256}
257
258// unreachableBundle is a bundle of main whose pack also carries a commit
259// main does not reach, as a hostile publisher could write one.
260func unreachableBundle(t *testing.T, s source) string {
261 t.Helper()
262 objects := git(t, s.repo, nil, "rev-list", "--objects", "main", "side")
263 pack := packObjects(t, s.repo, objects)
264 header := "# v2 git bundle\n" + s.tip + " refs/heads/main\n\n"
265 if len(s.tip) == 64 {
266 header = "# v3 git bundle\n@object-format=sha256\n" + s.tip + " refs/heads/main\n\n"
267 }
268 path := filepath.Join(t.TempDir(), "unreachable.bundle")
269 if err := os.WriteFile(path, append([]byte(header), pack...), 0o644); err != nil {
270 t.Fatal(err)
271 }
272 return path
273}
274
275func packObjects(t *testing.T, repo, objects string) []byte {
276 t.Helper()
277 cmd := exec.Command("git", "-C", repo, "pack-objects", "--stdout", "--quiet")
278 cmd.Env = append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null")
279 cmd.Stdin = strings.NewReader(objects + "\n")
280 var out bytes.Buffer
281 cmd.Stdout = &out
282 if err := exporttest.Run(t, cmd, gitTimeout); err != nil {
283 t.Fatal(err)
284 }
285 return out.Bytes()
286}
287
288// Reachable admits only commits main's tip reaches, each named by its
289// full ID in the repository's object format. A bundle can carry other
290// objects; they are in the repository and never reachable. In a SHA-256
291// repository, the first 40 hex digits of a commit are refused, though git
292// would read them as an abbreviation of it.
293func TestReachable(t *testing.T) {
294 ctx := context.Background()
295 for _, format := range []string{"sha1", "sha256"} {
296 t.Run(format, func(t *testing.T) {
297 s := newSource(t, format)
298 repo := filepath.Join(t.TempDir(), "app.git")
299 if err := export.AcceptBundle(ctx, unreachableBundle(t, s), repo, s.tip); err != nil {
300 t.Fatal(err)
301 }
302 if got := git(t, repo, nil, "cat-file", "-t", s.side); got != "commit" {
303 t.Fatalf("the unreachable commit is not in the repository: %q", got)
304 }
305 tree := git(t, repo, nil, "rev-parse", s.tip+"^{tree}")
306 cases := []struct {
307 name, commit string
308 want bool
309 }{
310 {"the tip", s.tip, true},
311 {"its parent", s.first, true},
312 {"a commit in the bundle that main does not reach", s.side, false},
313 {"a tree", tree, false},
314 {"an object the repository does not hold", strings.Repeat("1", len(s.tip)), false},
315 {"an abbreviated ID", s.tip[:12], false},
316 {"a revision expression", s.tip + "~1", false},
317 {"an option", "--all", false},
318 }
319 if format == "sha256" {
320 if got := git(t, repo, nil, "rev-parse", "--verify", s.tip[:40]+"^{commit}"); got != s.tip {
321 t.Fatalf("git does not read the tip's first 40 hex digits as the tip: %q", got)
322 }
323 cases = append(cases, struct {
324 name, commit string
325 want bool
326 }{"the tip's first 40 hex digits", s.tip[:40], false})
327 } else {
328 cases = append(cases, struct {
329 name, commit string
330 want bool
331 }{"64 hex digits", s.tip + strings.Repeat("0", 24), false})
332 }
333 for _, c := range cases {
334 t.Run(c.name, func(t *testing.T) {
335 got, err := export.Reachable(ctx, repo, s.tip, c.commit)
336 if err != nil || got != c.want {
337 t.Errorf("Reachable gave %v, %v; want %v", got, err, c.want)
338 }
339 })
340 }
341 if _, err := export.Reachable(ctx, repo, "main", s.tip); err == nil {
342 t.Error("Reachable took a tip that is no object ID")
343 }
344 // Several commits are reachable only when each of them is.
345 for _, c := range []struct {
346 commits []string
347 want bool
348 }{
349 {[]string{s.first, s.tip}, true},
350 {[]string{s.first, s.side}, false},
351 {[]string{s.first, tree}, false},
352 {[]string{s.side, s.tip}, false},
353 } {
354 if got, err := export.Reachable(ctx, repo, s.tip, c.commits...); err != nil || got != c.want {
355 t.Errorf("Reachable of %d commits gave %v, %v; want %v", len(c.commits), got, err, c.want)
356 }
357 }
358 if _, err := export.Reachable(ctx, repo, s.tip); err == nil {
359 t.Error("Reachable of no commit did not fail")
360 }
361 })
362 }
363}
364
365// A carried repository is fetched and checked as a bundle is, and holds
366// main alone.
367func TestCarryRepo(t *testing.T) {
368 ctx := context.Background()
369 s := newSource(t, "sha1")
370 held := filepath.Join(t.TempDir(), "held.git")
371 if err := export.AcceptBundle(ctx, s.bundle(t, "main"), held, s.tip); err != nil {
372 t.Fatal(err)
373 }
374 carried := filepath.Join(t.TempDir(), "carried.git")
375 if err := export.CarryRepo(ctx, held, carried, s.tip); err != nil {
376 t.Fatal(err)
377 }
378 if refs := git(t, carried, nil, "for-each-ref", "--format=%(refname) %(objectname)"); refs != "refs/heads/main "+s.tip {
379 t.Errorf("the carried repository holds %q", refs)
380 }
381 hasCommitGraph(t, carried)
382 wrong := filepath.Join(t.TempDir(), "wrong.git")
383 if err := export.CarryRepo(ctx, held, wrong, s.first); err == nil {
384 t.Error("CarryRepo carried a repository at another tip")
385 }
386 if _, err := os.Lstat(wrong); !os.IsNotExist(err) {
387 t.Error("the refusal left a repository behind")
388 }
389}
390
391// Git reads the repository it is given and no other: a directory that is
392// not a repository fails, even when a repository holds it.
393func TestGit(t *testing.T) {
394 ctx := context.Background()
395 s := newSource(t, "sha1")
396 repo := filepath.Join(t.TempDir(), "app.git")
397 if err := export.AcceptBundle(ctx, s.bundle(t, "main"), repo, s.tip); err != nil {
398 t.Fatal(err)
399 }
400 out, err := export.Git(ctx, repo, 1<<10, "rev-parse", export.MainRef)
401 if err != nil || strings.TrimSpace(string(out)) != s.tip {
402 t.Errorf("Git read main as %q, %v; want %s", out, err, s.tip)
403 }
404 if out, err := export.Git(ctx, filepath.Join(repo, "refs"), 1<<10, "rev-parse", export.MainRef); err == nil {
405 t.Errorf("Git read %q from a directory inside the repository", out)
406 }
407}
408
409// Git reads no more output than its limit: git printing more is stopped
410// and waited for, and the read fails. Output of exactly the limit is
411// read whole. A reader that returns before the output ends stops git too,
412// and is not failed for it. A git left writing to a pipe nobody reads
413// would never exit, so each call returning shows git was stopped.
414func TestGitOutputLimit(t *testing.T) {
415 ctx := context.Background()
416 repo := filepath.Join(t.TempDir(), "big.git")
417 git(t, "", nil, "init", "--quiet", "--bare", repo)
418 big := strings.Repeat("eight MiB of output\n", (8<<20)/20)
419 blob := git(t, repo, []byte(big), "hash-object", "-w", "--stdin")
420
421 if out, err := export.Git(ctx, repo, 1<<20, "cat-file", "blob", blob); !errors.Is(err, export.ErrOutputLimit) {
422 t.Errorf("Git read %d bytes of an 8 MiB blob with a 1 MiB limit, and returned %v", len(out), err)
423 }
424 if out, err := export.Git(ctx, repo, int64(len(big)), "cat-file", "blob", blob); err != nil || string(out) != big {
425 t.Errorf("Git read %d bytes of a blob exactly its limit long: %v", len(out), err)
426 }
427
428 var first []byte
429 err := export.GitStream(ctx, repo, 64<<20, func(r io.Reader) error {
430 first = make([]byte, 5)
431 _, err := io.ReadFull(r, first)
432 return err
433 }, "cat-file", "blob", blob)
434 if err != nil || string(first) != "eight" {
435 t.Errorf("a reader that stopped early read %q and got %v", first, err)
436 }
437
438 // A git that fails is reported once its output is read to the end.
439 if err := export.GitStream(ctx, repo, 1<<10, func(r io.Reader) error {
440 _, err := io.ReadAll(r)
441 return err
442 }, "cat-file", "blob", strings.Repeat("0", 40)); err == nil {
443 t.Error("GitStream did not report git's failure")
444 }
445}