gunk-dev/the-valley

project_test.go

sourceac8c5f17256cmain's published tip history
18.6 KiB
1package export_test
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "reflect"
11 "runtime"
12 "slices"
13 "strings"
14 "testing"
15 "time"
16
17 "the-valley/webui/export"
18 "the-valley/webui/export/exporttest"
19)
20
21// Nothing the anonymous reader may not see reaches export.json: not the
22// hidden project's knots or changes, not the plan's operator sections,
23// not drafts, branches, older versions, repository URLs or request refs,
24// not a knot's storage path, and not one principal's own name.
25func TestBuildLeavesOutWhatIsNotTheReaders(t *testing.T) {
26 f := exporttest.New(t)
27 for _, leak := range []string{
28 `"path"`, "outcomes/", "waiting_on_you", `"operator":`, "changes_error",
29 "The site deploys the app", "The site serves the docs", "Hidden.", "site-operator",
30 "lmnoplmnop", "deploy: a hidden change",
31 "zyxwvutsrq", "wip: a draft", "app-agent-draft", "scratch",
32 "plan: list milestones", "4c4c4c4c", "app-agent-session",
33 "git@", "valley-host", "integration-requests", `"record"`, `"seq"`, `"restack"`,
34 "app-operator", "app-agent", "drive-by",
35 } {
36 if bytes.Contains(f.ExportJSON, []byte(leak)) {
37 t.Errorf("export.json holds %q", leak)
38 }
39 }
40 if len(f.Export.Projects) != 1 || f.Export.Projects[0].Name != "app" {
41 t.Fatalf("exported %v, want app alone", f.Export.Projects)
42 }
43}
44
45func knotOf(t *testing.T, e *export.Export, id string) export.Knot {
46 t.Helper()
47 for _, k := range e.Projects[0].Knots {
48 if k.ID == id {
49 return k
50 }
51 }
52 t.Fatalf("the export holds no knot %s", id)
53 return export.Knot{}
54}
55
56// A reference to the hidden project's knot keeps only the reference. It
57// still holds its knot up: a knot it blocks stays blocked, and is never
58// shown as free to start.
59func TestBuildHidesForeignEdges(t *testing.T) {
60 f := exporttest.New(t)
61 k := knotOf(t, f.Export, "oc-a000003")
62 if len(k.Edges) != 1 {
63 t.Fatalf("edges %v", k.Edges)
64 }
65 e := k.Edges[0]
66 if e.State != export.EdgeHidden || e.Status != nil || e.Title != nil || e.Why != nil || e.Ref != "site:oc-b000001" {
67 t.Errorf("the hidden edge is %+v", e)
68 }
69 if slices.Contains(k.WaitingOn, "site:oc-b000001") || !slices.Contains(k.WaitingOn, "oc-a000002") {
70 t.Errorf("waiting_on is %v; it keeps the local blocker and drops the hidden one", k.WaitingOn)
71 }
72 if k.State != "blocked" || k.Ready {
73 t.Errorf("the knot is %s, ready %v; it stays blocked", k.State, k.Ready)
74 }
75 if !slices.Equal(k.BlockedBy, []string{"oc-a000002", "site:oc-b000001"}) {
76 t.Errorf("blocked_by is %v; it is the knot's own field, as written", k.BlockedBy)
77 }
78 if target := knotOf(t, f.Export, "bd-a000004").Edges; len(target) != 1 || target[0].State != export.EdgeHidden || target[0].Field != "target" {
79 t.Errorf("the target edge is %+v", target)
80 }
81}
82
83// A reference to another exported project's knot keeps what the plan
84// says of it.
85func TestBuildKeepsEdgesBetweenExportedProjects(t *testing.T) {
86 f := exporttest.New(t)
87 in := f.Inputs
88 in.Visibility = map[string]export.Visibility{"app": export.Public, "site": export.Public}
89 in.SourceTips = map[string]string{"app": in.SourceTips["app"], "site": strings.Repeat("e", 40)}
90 in.Details = append(in.Details,
91 detail("site", "8c2e4a6b0d1f3e5a7c9b1d3f5e7a9c0b2d4f6e81", "oc-b000001"),
92 detail("site", "8c2e4a6b0d1f3e5a7c9b1d3f5e7a9c0b2d4f6e81", "oc-b000002"))
93 e, err := export.Build(in)
94 if err != nil {
95 t.Fatal(err)
96 }
97 edge := knotOf(t, e, "oc-a000003").Edges[0]
98 if edge.State != export.EdgeResolved || edge.Title == nil || *edge.Title != "The site deploys the app" {
99 t.Errorf("the edge is %+v", edge)
100 }
101 if !slices.Contains(knotOf(t, e, "oc-a000003").WaitingOn, "site:oc-b000001") {
102 t.Error("waiting_on dropped an exported project's blocker")
103 }
104}
105
106func detail(project, tip, id string) []byte {
107 b, _ := json.Marshal(map[string]any{"schema": "valley-knot/v1", "project": project, "tip": tip,
108 "knot": map[string]any{"id": id, "body": "", "comments": []any{}}})
109 return b
110}
111
112// In flight is the plan's claimed knots, oldest claim first, and then the
113// knots explicitly in progress that nobody claims.
114func TestBuildInFlight(t *testing.T) {
115 f := exporttest.New(t)
116 if got := f.Export.Projects[0].InFlight; !slices.Equal(got, []string{"oc-a000002", "oc-a000006"}) {
117 t.Errorf("in_flight is %v", got)
118 }
119}
120
121// Principal names pass through the display mapping, and a name it does
122// not map shows as the generic role. An edited comment's editor is a
123// principal too, and a comment never edited names no editor.
124func TestBuildMapsPrincipals(t *testing.T) {
125 f := exporttest.New(t)
126 claimed := knotOf(t, f.Export, "oc-a000002")
127 if claimed.CreatedBy != "operator" || claimed.Claim.By != "agent" || claimed.Comments[1].Author != "agent" {
128 t.Errorf("the claimed knot shows %q, %q, %q", claimed.CreatedBy, claimed.Claim.By, claimed.Comments[1].Author)
129 }
130 if c := claimed.Comments[1]; c.Edited != "2026-10-25T10:30:00Z" || c.EditedBy != "agent" {
131 t.Errorf("the edited comment shows edited %q by %q", c.Edited, c.EditedBy)
132 }
133 if c := claimed.Comments[0]; c.Edited != "" || c.EditedBy != "" {
134 t.Errorf("a comment never edited shows edited %q by %q", c.Edited, c.EditedBy)
135 }
136 bug := knotOf(t, f.Export, "bd-a000004")
137 if bug.CreatedBy != export.Unmapped || bug.Comments[0].Author != export.Unmapped {
138 t.Errorf("an unmapped principal shows as %q and %q", bug.CreatedBy, bug.Comments[0].Author)
139 }
140 c := f.Export.Projects[0].Changes[0]
141 if c.Owner != "agent" || c.Version.Uploader != "agent" {
142 t.Errorf("the change shows %q and %q", c.Owner, c.Version.Uploader)
143 }
144}
145
146// A change keeps its active version alone, with its request and outcome,
147// and includes only changes the export carries.
148func TestBuildKeepsTheActiveVersion(t *testing.T) {
149 f := exporttest.New(t)
150 changes := f.Export.Projects[0].Changes
151 if len(changes) != 1 {
152 t.Fatalf("changes %v", changes)
153 }
154 v := changes[0].Version
155 if v.N != 2 || v.Request == nil || v.Outcome == nil || v.Outcome.Decision != "stale" {
156 t.Errorf("the version is %+v", v)
157 }
158 if len(changes[0].Includes) != 0 {
159 t.Errorf("includes %v names a draft", changes[0].Includes)
160 }
161}
162
163// A field the valley adds is not exported until the projection names it.
164func TestBuildReadsNamedFieldsAlone(t *testing.T) {
165 f := exporttest.New(t)
166 in := f.Inputs
167 in.Plan = bytes.Replace(in.Plan, []byte(`"id": "oc-a000001",`), []byte(`"id": "oc-a000001", "secret_field": "do not export",`), 1)
168 e, err := export.Build(in)
169 if err != nil {
170 t.Fatal(err)
171 }
172 data, err := e.Encode()
173 if err != nil {
174 t.Fatal(err)
175 }
176 if bytes.Contains(data, []byte("do not export")) {
177 t.Error("an unnamed field reached the export")
178 }
179}
180
181// What the projection refuses, so that a partial or inconsistent export
182// is never published.
183func TestBuildRefuses(t *testing.T) {
184 f := exporttest.New(t)
185 cases := []struct {
186 name string
187 change func(in *export.Inputs)
188 want string
189 }{
190 {"a detail read at another graph tip", func(in *export.Inputs) {
191 in.Details[0] = bytes.Replace(in.Details[0], []byte("3f6a0c1d"), []byte("3f6a0c1e"), 1)
192 }, "different graph tips"},
193 {"a knot without its detail", func(in *export.Inputs) { in.Details = in.Details[1:] }, "has no detail"},
194 {"a detail twice", func(in *export.Inputs) { in.Details = append(in.Details, in.Details[0]) }, "twice"},
195 {"a public project the plan could not read", func(in *export.Inputs) {
196 in.Plan = bytes.Replace(in.Plan, []byte(`"project": "app",
197 "error": null`), []byte(`"project": "app",
198 "error": "unreadable"`), 1)
199 }, "could not read public project app"},
200 {"a public project the pending listing could not read", func(in *export.Inputs) {
201 in.Pending = bytes.Replace(in.Pending, []byte(`"url": "git@valley-host:app.git",
202 "error": null`), []byte(`"url": "git@valley-host:app.git",
203 "error": "unreadable"`), 1)
204 }, "pending listing could not read public project app"},
205 {"a public project the plan does not list", func(in *export.Inputs) {
206 in.Visibility = map[string]export.Visibility{"app": export.Public, "other": export.Public}
207 }, "not in the plan"},
208 {"a visibility v1 does not export", func(in *export.Inputs) {
209 in.Visibility = map[string]export.Visibility{"app": "private"}
210 }, "public projects alone"},
211 {"a public project with no source tip", func(in *export.Inputs) { in.SourceTips = nil }, "no source tip"},
212 {"a display name with a control character", func(in *export.Inputs) {
213 in.Principals = export.Principals{"app-agent": "agent\x1b"}
214 }, "display mapping"},
215 {"a plan of another schema", func(in *export.Inputs) {
216 in.Plan = bytes.Replace(in.Plan, []byte("valley-plan/v1"), []byte("valley-plan/v2"), 1)
217 }, "schema"},
218 {"knot text with a control character", func(in *export.Inputs) {
219 for i, d := range in.Details {
220 in.Details[i] = bytes.Replace(d, []byte(`"body": "`), []byte(`"body": "\u0007`), 1)
221 }
222 }, "control character"},
223 }
224 for _, c := range cases {
225 t.Run(c.name, func(t *testing.T) {
226 in := f.Inputs
227 in.Details = slices.Clone(in.Details)
228 c.change(&in)
229 _, err := export.Build(in)
230 if err == nil || !strings.Contains(err.Error(), c.want) {
231 t.Fatalf("Build gave %v, want an error saying %q", err, c.want)
232 }
233 })
234 }
235 in := f.Inputs
236 in.Details = slices.Clone(in.Details)
237 in.Details[0] = bytes.Replace(in.Details[0], []byte("3f6a0c1d"), []byte("3f6a0c1e"), 1)
238 if _, err := export.Build(in); !errors.Is(err, export.ErrInconsistent) {
239 t.Errorf("a detail at another tip gave %v, want ErrInconsistent", err)
240 }
241}
242
243// With no public project, the export is empty and valid.
244func TestBuildExportsNothingWhenNothingIsPublic(t *testing.T) {
245 f := exporttest.New(t)
246 in := f.Inputs
247 in.Visibility = nil
248 e, err := export.Build(in)
249 if err != nil {
250 t.Fatal(err)
251 }
252 if len(e.Projects) != 0 {
253 t.Errorf("exported %v", e.Projects)
254 }
255}
256
257// export.json is read strictly: a field the schema does not name, or a
258// project name that is not safe as a file name, fails it.
259func TestDecodeIsStrict(t *testing.T) {
260 f := exporttest.New(t)
261 if _, err := export.Decode(f.ExportJSON); err != nil {
262 t.Fatal(err)
263 }
264 for name, data := range map[string][]byte{
265 "an unknown field": bytes.Replace(f.ExportJSON, []byte(`"collected"`), []byte(`"extra":1,"collected"`), 1),
266 "an unsafe name": bytes.Replace(f.ExportJSON, []byte(`"project":"app"`), []byte(`"project":"../app"`), 1),
267 "a second document": append(append([]byte{}, f.ExportJSON...), f.ExportJSON...),
268 "another schema": bytes.Replace(f.ExportJSON, []byte(export.Schema), []byte("valley-web-export/v0"), 1),
269 } {
270 if _, err := export.Decode(data); err == nil {
271 t.Errorf("Decode took %s", name)
272 }
273 }
274}
275
276// Nothing but white space may follow export.json's document: not a
277// closing bracket or brace, which ends a document without starting
278// another, and not a malformed suffix. A receiver refuses such an
279// export.json as bad-export even when the manifest declares its bytes.
280func TestDecodeRefusesTrailingInput(t *testing.T) {
281 f := exporttest.New(t)
282 for _, suffix := range []string{"]", "}", "]garbage", "}}", "],", "garbage", ",", "{", `"`, "nul", "\x00", "{}", "[]", "1"} {
283 data := append(append([]byte{}, f.ExportJSON...), suffix...)
284 if _, err := export.Decode(data); err == nil {
285 t.Errorf("Decode took export.json followed by %q", suffix)
286 }
287 m := *f.Manifest
288 m.File = export.BodyOf(export.ExportFile, data)
289 if _, err := m.CheckExport(data); export.CodeOf(err) != export.CodeBadExport {
290 t.Errorf("CheckExport gave %v for export.json followed by %q, want bad-export", err, suffix)
291 }
292 }
293 data := append(append([]byte{}, f.ExportJSON...), " \t\r\n\n"...)
294 if _, err := export.Decode(data); err != nil {
295 t.Errorf("Decode refused export.json followed by white space: %v", err)
296 }
297}
298
299// The content digest ignores display-time fields and nothing else.
300func TestDigest(t *testing.T) {
301 f := exporttest.New(t)
302 base, err := f.Export.Digest()
303 if err != nil {
304 t.Fatal(err)
305 }
306 reread := func() *export.Export {
307 e, err := export.Decode(f.ExportJSON)
308 if err != nil {
309 t.Fatal(err)
310 }
311 return e
312 }
313 same := map[string]func(e *export.Export){
314 "collected": func(e *export.Export) { e.Collected = "2026-10-26T00:00:00Z" },
315 "a claim's age": func(e *export.Export) {
316 for i := range e.Projects[0].Knots {
317 if c := e.Projects[0].Knots[i].Claim; c != nil {
318 c.AgeSeconds, c.Stale = 999999, true
319 }
320 }
321 },
322 }
323 for name, change := range same {
324 e := reread()
325 change(e)
326 if got, _ := e.Digest(); got != base {
327 t.Errorf("changing %s changed the digest", name)
328 }
329 }
330 differs := map[string]func(e *export.Export){
331 "a title": func(e *export.Export) { e.Projects[0].Knots[0].Title += "!" },
332 "a source tip": func(e *export.Export) { e.Projects[0].SourceTip = strings.Repeat("a", 40) },
333 "a claim's at": func(e *export.Export) { e.Projects[0].Knots[1].Claim.At = "2026-10-25T11:00:00Z" },
334 "a comment": func(e *export.Export) { e.Projects[0].Knots[1].Comments[0].Body += "." },
335 }
336 for name, change := range differs {
337 e := reread()
338 change(e)
339 if got, _ := e.Digest(); got == base {
340 t.Errorf("changing %s left the digest as it was", name)
341 }
342 }
343 // Digest copies what it clears: the export it was given is unchanged.
344 if f.Export.Collected == "" || knotOf(t, f.Export, "oc-a000002").Claim.AgeSeconds == 0 {
345 t.Error("Digest changed the export it read")
346 }
347}
348
349// Incremental decoding preserves the export's values and rejects malformed
350// fields, including nested fields and integer overflow.
351func TestDecodeContextValues(t *testing.T) {
352 f := exporttest.New(t)
353 for _, data := range [][]byte{
354 f.ExportJSON,
355 []byte(`{"schema":"valley-web-export/v1","projects":null}`),
356 []byte(`{"schema":"valley-web-export/v1","projects":[]}`),
357 } {
358 var want export.Export
359 if err := json.Unmarshal(data, &want); err != nil {
360 t.Fatal(err)
361 }
362 got, err := export.DecodeContext(context.Background(), bytes.NewReader(data))
363 if err != nil {
364 t.Fatal(err)
365 }
366 if !reflect.DeepEqual(got, &want) {
367 t.Fatal("incremental decoding changed export values")
368 }
369 }
370 for _, field := range []string{
371 `"knots":{}`, `"roots":[1]`, `"knots":[{"id":"oc-a000001","active":1}]`,
372 `"knots":[{"id":"oc-a000001","comment_count":9223372036854775808}]`,
373 `"knots":[{"id":"oc-a000001","comment_count":1.5}]`, `"knots":[{"id":"oc-a000001","unknown":true}]`,
374 } {
375 data := []byte(`{"schema":"valley-web-export/v1","projects":[{"project":"app","visibility":"public","source_tip":"` + strings.Repeat("a", 40) + `",` + field + `}]}`)
376 if _, err := export.DecodeContext(context.Background(), bytes.NewReader(data)); err == nil {
377 t.Errorf("accepted %s", field)
378 }
379 }
380}
381
382// A token that spans many reads observes cancellation before consuming its
383// remaining bytes.
384func TestDecodeContextDuringToken(t *testing.T) {
385 ctx, cancel := context.WithCancel(context.Background())
386 defer cancel()
387 r := &cancelDecodeReader{Reader: strings.NewReader(`{"schema":"` + strings.Repeat("x", 1<<20) + `"}`), cancel: cancel}
388 if _, err := export.DecodeContext(ctx, r); !errors.Is(err, context.Canceled) {
389 t.Fatalf("error = %v", err)
390 }
391 if r.n > 8192 {
392 t.Fatalf("read %d bytes after cancellation", r.n)
393 }
394}
395
396type cancelDecodeReader struct {
397 io.Reader
398 cancel context.CancelFunc
399 n int
400}
401
402func (r *cancelDecodeReader) Read(p []byte) (int, error) {
403 n, err := r.Reader.Read(p)
404 r.n += n
405 if r.n >= 4096 {
406 r.cancel()
407 }
408 return n, err
409}
410
411// The final input read arms cancellation. The string scanner must observe
412// it while decoding bytes already in its buffer, without another source read.
413func TestDecodeContextFinalStringChunk(t *testing.T) {
414 for _, key := range []bool{false, true} {
415 t.Run(fmt.Sprint(key), func(t *testing.T) {
416 base, cancel := context.WithCancel(context.Background())
417 defer cancel()
418 ctx := &finalStringContext{Context: base, cancel: cancel}
419 value := strings.Repeat(`\u0061`, 1<<17)
420 data := `{"schema":"valley-web-export/v1","collected":"` + value + `"}`
421 if key {
422 data = `{"` + value + `":null}`
423 }
424 r := &finalStringReader{Reader: strings.NewReader(data), ctx: ctx}
425 started := time.Now()
426 got, err := export.DecodeContext(ctx, r)
427 if got != nil || !errors.Is(err, context.Canceled) {
428 t.Fatalf("DecodeContext = %v, %v", got, err)
429 }
430 if !ctx.inString {
431 t.Fatal("cancellation was not observed inside string decoding")
432 }
433 if r.extraRead {
434 t.Fatal("decoder requested more input after the final chunk")
435 }
436 if time.Since(started) > 2*time.Second {
437 t.Fatal("string decoding did not stop promptly")
438 }
439 })
440 }
441}
442
443type finalStringContext struct {
444 context.Context
445 cancel context.CancelFunc
446 armed bool
447 checks int
448 inString bool
449}
450
451func (c *finalStringContext) Err() error {
452 if c.armed {
453 c.checks++
454 if c.checks == 3 {
455 var pcs [16]uintptr
456 n := runtime.Callers(2, pcs[:])
457 frames := runtime.CallersFrames(pcs[:n])
458 for {
459 f, more := frames.Next()
460 if strings.HasSuffix(f.Function, ".(*stringInput).readString") {
461 c.inString = true
462 }
463 if !more {
464 break
465 }
466 }
467 c.cancel()
468 }
469 }
470 return c.Context.Err()
471}
472
473type finalStringReader struct {
474 *strings.Reader
475 ctx *finalStringContext
476 extraRead bool
477}
478
479func (r *finalStringReader) Read(p []byte) (int, error) {
480 if r.ctx.armed {
481 r.extraRead = true
482 }
483 n, err := r.Reader.Read(p)
484 if r.Len() == 0 {
485 r.ctx.armed = true
486 }
487 return n, err
488}
489
490// String decoding matches encoding/json for escapes, invalid UTF-8 and
491// surrogate pairs, including sequences split across input chunks.
492func TestDecodeStringValues(t *testing.T) {
493 values := []string{
494 `"plain"`, `"\"\\\/\b\f\n\r\t"`, `"\uD834\uDD1E"`,
495 `"\uD834x"`, `"\uDD1E"`, `"\uD834\u0061"`, `"\uD834\uD834\uDD1E"`,
496 "\"\xff\"", `"รฉ็•Œ๐„ž"`,
497 }
498 prefixes := []string{""}
499 for offset := 0; offset < 12; offset++ {
500 prefixes = append(prefixes, strings.Repeat("a", 4096-len(`{"schema":"valley-web-export/v1","collected":"`)-offset))
501 }
502 for _, prefix := range prefixes {
503 for _, value := range values {
504 data := []byte(`{"schema":"valley-web-export/v1","collected":"` + prefix + value[1:] + `}`)
505 var want export.Export
506 if err := json.Unmarshal(data, &want); err != nil {
507 t.Fatal(err)
508 }
509 got, err := export.DecodeContext(context.Background(), bytes.NewReader(data))
510 if err != nil {
511 t.Fatal(err)
512 }
513 if !reflect.DeepEqual(got, &want) {
514 t.Errorf("string %q differs from encoding/json", value)
515 }
516 }
517 }
518 for _, value := range []string{`"\x"`, `"\uZZZZ"`, `"\u123"`, `"unterminated`, "\"\n\"", `"\uD834\uZZZZ"`} {
519 data := []byte(`{"schema":"valley-web-export/v1","collected":` + value + `}`)
520 if _, err := export.Decode(data); err == nil {
521 t.Errorf("accepted invalid string %q", value)
522 }
523 }
524}
525
526// More must not consume and hide a string error before a closing delimiter.
527func TestDecodeRetainsStringError(t *testing.T) {
528 for _, data := range []string{
529 `{"schema":"valley-web-export/v1","projects":["\x]}`,
530 `{"schema":"valley-web-export/v1","\x}`,
531 } {
532 if _, err := export.Decode([]byte(data)); err == nil {
533 t.Errorf("accepted malformed document %q", data)
534 }
535 }
536}