gunk-dev/the-valley

project_test.go

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