gunk-dev/the-valley

bundle_test.go

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