gunk-dev/the-valley

project_test.go

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