gunk-dev/the-valley

record_test.go

source53fb2c06ff1amain's published tip history
19.4 KiB
1package main
2
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "strings"
10 "testing"
11
12 "the-valley/change"
13)
14
15const changeID = "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz"
16
17var recordRef = change.Ref("main", changeID)
18
19// records is a bare repository to push change records into, read the way
20// the hook reads one: through gitRepository, with real git objects.
21type records struct {
22 t *testing.T
23 dir string
24 p policy
25}
26
27func newRecords(t *testing.T) *records {
28 dir := t.TempDir()
29 gitIn(t, dir, "", "init", "--quiet", "--bare", dir)
30 t.Setenv("GIT_DIR", dir)
31 return &records{t: t, dir: dir, p: policy{
32 project: "project",
33 grants: grants{"operator": {grantRequest: true}},
34 repo: gitRepository{},
35 }}
36}
37
38func (r *records) git(stdin string, args ...string) string {
39 r.t.Helper()
40 return gitIn(r.t, r.dir, stdin, args...)
41}
42
43// source is a commit standing for a head a change is marked ready at.
44func (r *records) source(subject string) string {
45 empty := r.git("", "mktree")
46 return r.commit(empty, nil, subject)
47}
48
49// commit writes a commit object exactly as given, parents and all, which
50// git's own porcelain would not always write.
51func (r *records) commit(tree string, parents []string, message string) string {
52 r.t.Helper()
53 var b strings.Builder
54 fmt.Fprintf(&b, "tree %s\n", tree)
55 for _, p := range parents {
56 fmt.Fprintf(&b, "parent %s\n", p)
57 }
58 b.WriteString("author a <a@localhost> 1700000000 +0000\ncommitter a <a@localhost> 1700000000 +0000\n\n")
59 b.WriteString(message + "\n")
60 return r.git(b.String(), "hash-object", "-t", "commit", "-w", "--literally", "--stdin")
61}
62
63func (r *records) blob(content string) string {
64 return r.git(content, "hash-object", "-w", "--stdin")
65}
66
67// recordTree is a record commit's tree, holding the text as record.json.
68func (r *records) recordTree(text string) string {
69 return r.git(fmt.Sprintf("100644 blob %s\trecord.json\n", r.blob(text)), "mktree")
70}
71
72// write writes a record commit holding text, with the parents given.
73func (r *records) write(text string, parents ...string) string {
74 return r.commit(r.recordTree(text), parents, "a change record")
75}
76
77func encode(t *testing.T, rec change.Record) string {
78 t.Helper()
79 out, err := change.Encode(&rec)
80 if err != nil {
81 t.Fatal(err)
82 }
83 return string(out)
84}
85
86// first is the record that creates the change at head h, pushed by owner.
87func first(owner, h string) change.Record {
88 return change.Record{
89 Schema: change.Schema, ChangeID: changeID, Target: "main", Owner: owner,
90 State: change.Ready, Seq: 1, Active: 1,
91 Versions: []change.Version{
92 {N: 1, Head: change.HeadPrefix + h, Title: "the first", Branch: "topic", Uploader: owner},
93 },
94 }
95}
96
97// next is rec with a new version at head h, uploaded by who.
98func next(rec change.Record, who, h string) change.Record {
99 rec.Versions = append(append([]change.Version(nil), rec.Versions...), change.Version{
100 N: len(rec.Versions) + 1, Head: change.HeadPrefix + h, Title: "the next", Branch: "topic", Uploader: who,
101 })
102 rec.Active = len(rec.Versions)
103 rec.State = change.Ready
104 rec.Seq++
105 return rec
106}
107
108// withdrawn is rec, withdrawn.
109func withdrawn(rec change.Record) change.Record {
110 rec.State = change.Withdrawn
111 rec.Seq++
112 return rec
113}
114
115// expect decides one write and holds the answer to what is wanted: "" for
116// an allowed write, and otherwise a phrase the refusal has to hold.
117func (r *records) expect(what, who, ref, old, new, says string) {
118 r.t.Helper()
119 got := r.p.decide(who, update{old: old, new: new, ref: ref})
120 switch {
121 case says == "" && got != "":
122 r.t.Errorf("%s: refused: %s", what, got)
123 case says != "" && !strings.Contains(got, says):
124 r.t.Errorf("%s: got %q, want a refusal saying %q", what, got, says)
125 }
126}
127
128const zeroID = "0000000000000000000000000000000000000000"
129
130func TestCreatingAChangeRecord(t *testing.T) {
131 r := newRecords(t)
132 h := r.source("the head")
133 h2 := r.source("another head")
134 good := encode(t, first("alice", h))
135 create := func(what, who, text string, says string, parents ...string) {
136 t.Helper()
137 r.expect(what, who, recordRef, zeroID, r.write(text, parents...), says)
138 }
139 mutate := func(f func(*change.Record)) string {
140 rec := first("alice", h)
141 f(&rec)
142 return encode(t, rec)
143 }
144
145 create("the create row", "alice", good, "", h)
146
147 // Who.
148 create("an untagged key", "", good, "a key that names no principal", h)
149
150 // Parent structure.
151 create("no parent", "alice", good, "has 0 parents")
152 create("an extra parent", "alice", good, "has 2 parents", h, h2)
153 tree := r.git("", "mktree")
154 create("a tree as the head", "alice",
155 strings.Replace(good, h, tree, 1), "is a tree, and a head is a commit", tree)
156 create("a head the repository lacks", "alice",
157 strings.Replace(good, h, strings.Repeat("9", 40), 1), "does not hold", strings.Repeat("9", 40))
158
159 // Record content.
160 create("a head other than the parent", "alice", good, "the record commit's parent is "+h2, h2)
161 create("another uploader", "alice", mutate(func(c *change.Record) { c.Versions[0].Uploader = "bob" }),
162 "names bob as its uploader", h)
163 create("another owner", "alice", mutate(func(c *change.Record) { c.Owner = "bob" }),
164 "names bob as the owner", h)
165 create("a seq other than 1", "alice", mutate(func(c *change.Record) { c.Seq = 2 }), "seq is 2", h)
166 create("a withdrawn change", "alice", mutate(func(c *change.Record) { c.State = change.Withdrawn }),
167 "state is withdrawn", h)
168 create("two versions", "alice", encode(t, next(first("alice", h2), "alice", h)), "holds 2", h)
169 create("another target", "alice", mutate(func(c *change.Record) { c.Target = "release" }),
170 "names the target release", h)
171 create("another change", "alice", mutate(func(c *change.Record) { c.ChangeID = strings.Repeat("k", 32) }),
172 "names the change kkkk", h)
173 r.expect("a ref for another target", "alice", change.Ref("release", changeID), zeroID, r.write(good, h),
174 "refs/the-valley/changes/main/<change ID>")
175 r.expect("a ref that names no change", "alice", change.RefPrefix+"main/topic", zeroID, r.write(good, h),
176 "32 letters from k to z")
177
178 // Parsing.
179 create("a duplicate key", "alice", strings.Replace(good, `"seq": 1,`, `"seq": 1, "seq": 1,`, 1),
180 `names the key "seq" twice`, h)
181 create("a duplicate key in a version", "alice", strings.Replace(good, `"n": 1,`, `"n": 1, "n": 1,`, 1),
182 `names the key "n" twice`, h)
183 create("an unknown field", "alice", strings.Replace(good, `"seq": 1,`, `"seq": 1, "extra": 1,`, 1),
184 `"extra"`, h)
185 create("trailing data", "alice", good+"{}", "more after the value", h)
186 create("bytes that are not UTF-8", "alice", strings.Replace(good, "the first", "the \xff", 1),
187 "not valid UTF-8", h)
188
189 // Tree shape.
190 shaped := func(what, entries, says string) {
191 t.Helper()
192 commit := r.commit(r.git(entries, "mktree"), []string{h}, "a change record")
193 r.expect(what, "alice", recordRef, zeroID, commit, says)
194 }
195 blob := r.blob(good)
196 shaped("an empty tree", "", "its tree is empty")
197 shaped("a second entry", fmt.Sprintf("100644 blob %s\trecord.json\n100644 blob %s\tz\n", blob, blob),
198 "more than one entry")
199 shaped("another name", fmt.Sprintf("100644 blob %s\trecord.jsonx\n", blob), `"record.jsonx"`)
200 shaped("an executable", fmt.Sprintf("100755 blob %s\trecord.json\n", blob), "mode 100755")
201 shaped("a subtree", fmt.Sprintf("040000 tree %s\trecord.json\n", tree), "mode 40000")
202 r.expect("a tree as the record", "alice", recordRef, zeroID, r.recordTree(good),
203 "points at a tree, where a change record holds a commit")
204
205 // Bounds. Each object past its bound is refused on its type and size
206 // alone, before its content is asked for.
207 big := r.commit(r.recordTree(good), []string{h}, strings.Repeat("x", maxRecordCommit))
208 r.expect("an oversized commit", "alice", recordRef, zeroID, big, "more than the 4096")
209 long := r.commit(r.git(fmt.Sprintf("100644 blob %s\t%s\n", blob, strings.Repeat("r", maxRecordTree)), "mktree"),
210 []string{h}, "a change record")
211 r.expect("an oversized tree", "alice", recordRef, zeroID, long, "more than the 1024")
212 create("an oversized record.json", "alice", good+strings.Repeat(" ", maxRecordBlob), "more than the 65536", h)
213 objects, err := openObjects()
214 if err != nil {
215 t.Fatal(err)
216 }
217 objects.subject = "a change record"
218 _, err = readRecord(objects, big)
219 objects.close()
220 if err == nil || strings.Join(objects.requests, "; ") != "info "+big {
221 t.Errorf("an oversized commit: requests = %v, error = %v; want its info alone", objects.requests, err)
222 }
223
224 // A record commit naming a parent after its other headers names one
225 // git does not read, so it is refused rather than read two ways.
226 sneaky := r.git(fmt.Sprintf("tree %s\nparent %s\nauthor a <a@localhost> 1700000000 +0000\nparent %s\n\nx\n",
227 r.recordTree(good), h, h2), "hash-object", "-t", "commit", "-w", "--literally", "--stdin")
228 r.expect("a parent among the later headers", "alice", recordRef, zeroID, sneaky, "does not read as a parent")
229}
230
231func TestAddingAVersion(t *testing.T) {
232 r := newRecords(t)
233 h1, h2, h3 := r.source("one"), r.source("two"), r.source("three")
234 v1 := first("alice", h1)
235 old := r.write(encode(t, v1), h1)
236 update := func(what, who, text, says string, parents ...string) {
237 t.Helper()
238 r.expect(what, who, recordRef, old, r.write(text, parents...), says)
239 }
240 mutate := func(f func(*change.Record)) string {
241 rec := next(v1, "alice", h2)
242 f(&rec)
243 return encode(t, rec)
244 }
245 good := encode(t, next(v1, "alice", h2))
246
247 update("the new version row", "alice", good, "", old, h2)
248 update("the new version row, by the operator", "operator", encode(t, next(v1, "operator", h2)), "", old, h2)
249
250 // Who.
251 update("a principal that is neither owner nor operator", "mallory", encode(t, next(v1, "mallory", h2)),
252 "only the change's owner, alice, or a principal holding the request grant", old, h2)
253 update("an untagged key", "", good, "a key that names no principal", old, h2)
254
255 // Parent structure.
256 update("the parents in the wrong order", "alice", good, "has the record it replaces as its first parent", h2, old)
257 update("an extra parent", "alice", good, "has the record it replaces as its first parent", old, h2, h3)
258 update("a first parent that is not the old record", "alice", good, "as its first parent", h1, h2)
259 tree := r.git("", "mktree")
260 update("a tree as the head", "alice", strings.Replace(good, h2, tree, 1), "is a tree, and a head is a commit", old, tree)
261
262 // Record content.
263 update("a changed historical entry", "alice", mutate(func(c *change.Record) { c.Versions[0].Title = "rewritten" }),
264 "changes version 1", old, h2)
265 update("a historical entry with another uploader", "alice",
266 mutate(func(c *change.Record) { c.Versions[0].Uploader = "bob" }), "changes version 1", old, h2)
267 update("a skipped n", "alice", strings.Replace(good, `"n": 2`, `"n": 3`, 1), "no gap", old, h2)
268 update("seq not incremented", "alice", mutate(func(c *change.Record) { c.Seq = 1 }), "seq is 1", old, h2)
269 update("seq incremented twice", "alice", mutate(func(c *change.Record) { c.Seq = 3 }), "seq is 3", old, h2)
270 update("the owner changed", "alice", mutate(func(c *change.Record) { c.Owner = "bob" }),
271 "changes the owner from alice to bob", old, h2)
272 update("the target changed", "alice", mutate(func(c *change.Record) { c.Target = "release" }),
273 "names the target release", old, h2)
274 update("the change ID changed", "alice", mutate(func(c *change.Record) { c.ChangeID = strings.Repeat("k", 32) }),
275 "names the change kkkk", old, h2)
276 update("the active head again", "alice", encode(t, next(v1, "alice", h1)), "needs a new head", old, h1)
277 update("a head other than the second parent", "alice", good, "second parent is "+h3, old, h3)
278 update("another uploader", "alice", encode(t, next(v1, "bob", h2)), "names bob as its uploader", old, h2)
279 update("active left on the old version", "alice", mutate(func(c *change.Record) { c.Active = 1 }),
280 "active is 1", old, h2)
281 update("a new version that withdraws", "alice", mutate(func(c *change.Record) { c.State = change.Withdrawn }),
282 "state is withdrawn", old, h2)
283 update("two new versions", "alice", encode(t, next(next(v1, "alice", h3), "alice", h2)), "holds 3", old, h2)
284 update("no new version", "alice", encode(t, withdrawn(withdrawn(v1))), "adds one version", old, h2)
285}
286
287func TestWithdrawingAndComingBack(t *testing.T) {
288 r := newRecords(t)
289 h1, h2 := r.source("one"), r.source("two")
290 v1 := first("alice", h1)
291 ready := r.write(encode(t, v1), h1)
292 withdraw := func(what, who, text, says string, parents ...string) {
293 t.Helper()
294 r.expect(what, who, recordRef, ready, r.write(text, parents...), says)
295 }
296 mutate := func(f func(*change.Record)) string {
297 rec := withdrawn(v1)
298 f(&rec)
299 return encode(t, rec)
300 }
301 good := encode(t, withdrawn(v1))
302
303 withdraw("the withdraw row", "alice", good, "", ready)
304 withdraw("the withdraw row, by the operator", "operator", good, "", ready)
305
306 withdraw("a principal that is neither owner nor operator", "mallory", good, "only the change's owner", ready)
307 withdraw("an untagged key", "", good, "a key that names no principal", ready)
308 withdraw("an extra parent", "alice", good, "first parent", ready, h1, h2)
309 withdraw("the old record as a second parent", "alice", good, "a new version adds one version", ready, ready)
310 withdraw("no parent", "alice", good, "first parent")
311 withdraw("ready to ready without a new version", "alice", mutate(func(c *change.Record) { c.State = change.Ready }),
312 "withdraws the change, and this one's state is ready", ready)
313 withdraw("seq not incremented", "alice", mutate(func(c *change.Record) { c.Seq = 1 }), "seq is 1", ready)
314 withdraw("the owner changed", "alice", mutate(func(c *change.Record) { c.Owner = "bob" }), "changes the owner", ready)
315 withdraw("a version changed", "alice", mutate(func(c *change.Record) { c.Versions[0].Title = "x" }),
316 "changes the versions", ready)
317 withdraw("the target changed", "alice", mutate(func(c *change.Record) { c.Target = "release" }),
318 "names the target release", ready)
319
320 // From withdrawn, the change comes back only with a new version.
321 gone := withdrawn(v1)
322 old := r.write(encode(t, gone), ready)
323 again := func(what, who, text, says string, parents ...string) {
324 t.Helper()
325 r.expect(what, who, recordRef, old, r.write(text, parents...), says)
326 }
327 again("the re-ready row", "alice", encode(t, next(gone, "alice", h2)), "", old, h2)
328 again("the re-ready row, by the operator", "operator", encode(t, next(gone, "operator", h2)), "", old, h2)
329 again("back as it was", "alice", encode(t, func() change.Record { c := gone; c.State = change.Ready; c.Seq++; return c }()),
330 "only a new version brings it back", old)
331 again("back at the same head", "alice", encode(t, next(gone, "alice", h1)), "needs a new head", old, h1)
332 again("withdrawn twice", "alice", encode(t, withdrawn(gone)), "withdrawn already", old)
333 again("a new version left withdrawn", "alice",
334 encode(t, func() change.Record { c := next(gone, "alice", h2); c.State = change.Withdrawn; return c }()),
335 "state is withdrawn", old, h2)
336 again("re-ready by another principal", "mallory", encode(t, next(gone, "mallory", h2)), "only the change's owner", old, h2)
337}
338
339func TestOnlyTheOperatorDeletesARecord(t *testing.T) {
340 r := newRecords(t)
341 h := r.source("one")
342 old := r.write(encode(t, first("alice", h)), h)
343 r.expect("the delete row", "operator", recordRef, old, zeroID, "")
344 r.expect("a delete by the owner", "alice", recordRef, old, zeroID, "only a principal holding the request grant may delete")
345 r.expect("a delete by an untagged key", "", recordRef, old, zeroID, "a key that names no principal")
346}
347
348// The bounds about a push as a whole are checked by preReceive, before
349// any record is read.
350func TestAPushIsBoundInTheRecordsItWrites(t *testing.T) {
351 r := newRecords(t)
352 h := r.source("one")
353 dir := t.TempDir()
354 policyFile := filepath.Join(dir, "policy.json")
355 grantsFile := filepath.Join(dir, "grants")
356 if err := os.WriteFile(policyFile, []byte(`{"refs": [], "writers": [], "grants": {}}`), 0o644); err != nil {
357 t.Fatal(err)
358 }
359 if err := os.WriteFile(grantsFile, []byte("request operator\n"), 0o644); err != nil {
360 t.Fatal(err)
361 }
362 push := func(repo repository, who string, lines []string) (int, string) {
363 var stderr bytes.Buffer
364 code := preReceive([]string{"--project", "project", "--policy", policyFile, "--grants", grantsFile,
365 "--principal", who}, strings.NewReader(strings.Join(lines, "\n")+"\n"), &stderr, repo)
366 return code, stderr.String()
367 }
368 // ids makes n distinct change IDs, from an offset.
369 ids := func(from, n int) []string {
370 var out []string
371 for i := from; i < from+n; i++ {
372 id := []byte(strings.Repeat("k", 32))
373 for j, x := 31, i; x > 0; j, x = j-1, x/16 {
374 id[j] = byte('z' - x%16)
375 }
376 out = append(out, string(id))
377 }
378 return out
379 }
380
381 // 33 record updates are refused before any is read, or any ref looked
382 // up: this repository fails the test if one is.
383 var many []string
384 for _, id := range ids(0, maxRecordUpdates+1) {
385 many = append(many, zeroID+" "+h+" "+change.Ref("main", id))
386 }
387 code, says := push(unreadable{t}, "alice", many)
388 if code == 0 || !strings.Contains(says, "it updates 33 change records, and a push may update at most 32") {
389 t.Errorf("33 record updates: exit %d, %q", code, says)
390 }
391
392 // 32 are within the bound, and each is then read and decided.
393 var creates []string
394 for _, id := range ids(0, maxRecordUpdates) {
395 rec := first("alice", h)
396 rec.ChangeID = id
397 creates = append(creates, zeroID+" "+r.write(encode(t, rec), h)+" "+change.Ref("main", id))
398 }
399 if code, says := push(gitRepository{}, "alice", creates); code != 0 {
400 t.Errorf("32 record creates: exit %d, %q", code, says)
401 }
402
403 // Those were decided and never written. With 1999 records in place,
404 // one more fits and two more do not. Once the repository is full, a
405 // delete still goes through.
406 var refs strings.Builder
407 for _, id := range ids(maxRecordUpdates, maxRecords-1) {
408 fmt.Fprintf(&refs, "create %s %s\n", change.Ref("main", id), h)
409 }
410 r.git(refs.String(), "update-ref", "--stdin")
411 line := func(id string) string {
412 rec := first("alice", h)
413 rec.ChangeID = id
414 return zeroID + " " + r.write(encode(t, rec), h) + " " + change.Ref("main", id)
415 }
416 more := ids(maxRecordUpdates+maxRecords, 2)
417 code, says = push(gitRepository{}, "alice", []string{line(more[0]), line(more[1])})
418 if code == 0 || !strings.Contains(says, "holds 1999 change records, and this push would create 2 more, past the 2000") {
419 t.Errorf("two records past the bound: exit %d, %q", code, says)
420 }
421 if code, says := push(gitRepository{}, "alice", []string{line(more[0])}); code != 0 {
422 t.Errorf("the last record within the bound: exit %d, %q", code, says)
423 }
424 r.git("", "update-ref", change.Ref("main", more[0]), h)
425 code, says = push(gitRepository{}, "alice", []string{line(more[1])})
426 if code == 0 || !strings.Contains(says, "holds 2000 change records") {
427 t.Errorf("a record past a full repository: exit %d, %q", code, says)
428 }
429 if code, says := push(gitRepository{}, "operator", []string{h + " " + zeroID + " " + change.Ref("main", more[0])}); code != 0 {
430 t.Errorf("a delete from a full repository: exit %d, %q", code, says)
431 }
432}
433
434// unreadable is a repository whose objects must not be read.
435type unreadable struct{ t *testing.T }
436
437func (u unreadable) symbolic([]string) (map[string]bool, error) {
438 u.t.Error("the refs were read")
439 return nil, errors.New("unread")
440}
441func (u unreadable) notes(string) (map[string][]byte, error) {
442 u.t.Error("an object was read")
443 return nil, errors.New("unread")
444}
445func (u unreadable) record(string) (recordCommit, error) {
446 u.t.Error("a record was read")
447 return recordCommit{}, errors.New("unread")
448}
449func (u unreadable) kind(string) (string, error) {
450 u.t.Error("an object was read")
451 return "", errors.New("unread")
452}
453func (u unreadable) records() (int, error) {
454 u.t.Error("the records were counted")
455 return 0, errors.New("unread")
456}