gunk-dev/the-valley

project_test.go

source036a3a60154dmain's published tip history
32.5 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.Identities = map[string]string{"app": exporttest.Identities["app"], "site": "273d5668702918ea7ae079de374db96b"}
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 exported 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 exported project app"},
276 {"a public project the plan does not list", func(in *export.Inputs) {
277 in.Identities = map[string]string{"app": exporttest.Identities["app"], "other": "0123456789abcdef0123456789abcdef"}
278 }, "not in the plan"},
279 {"an identity that is not one", func(in *export.Inputs) {
280 in.Identities = map[string]string{"app": "private"}
281 }, "not 32 lowercase hex digits"},
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 }, "exported 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", Name: "site", 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", Name: "app", 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", Name: "site"}
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 a web name, former names or aliases and no group"},
315 {"former names without a group", func(in *export.Inputs) {
316 in.Placements["site"] = export.Placement{FormerNames: []string{"s"}}
317 }, "site has a web name, former names or aliases and no group"},
318 {"a group's name that is not a name", func(in *export.Inputs) {
319 in.Groups = []export.Group{{ID: "core", Name: "-"}}
320 }, `the name of group core is "-", which is not a name`},
321 {"groups out of order", func(in *export.Inputs) {
322 in.Groups = []export.Group{{ID: "web", Name: "docs"}, in.Groups[0]}
323 in.Placements["site"] = export.Placement{Group: "web", Name: "site"}
324 }, "the group core is listed out of order or twice"},
325 {"a project in a group with no web name", func(in *export.Inputs) {
326 in.Placements["app"] = export.Placement{Group: "core"}
327 }, `the web name of project app is "", which is not a name`},
328 {"two web names in one group that differ in case", func(in *export.Inputs) {
329 in.Placements["site"] = export.Placement{Group: "core", Name: "App"}
330 }, `the web name of project app and the web name of project site are both "App", ignoring case: web names and former names must be unique in group core`},
331 {"a former name that is another project's web name", func(in *export.Inputs) {
332 in.Placements["site"] = export.Placement{Group: "core", Name: "site", FormerNames: []string{"app"}}
333 }, `the web name of project app and former name 0 of project site are both "app"`},
334 {"a former name that is the project's own web name", func(in *export.Inputs) {
335 in.Placements["app"] = export.Placement{Group: "core", Name: "app", FormerNames: []string{"APP"}}
336 }, `the web name of project app and former name 0 of project app are both "APP"`},
337 {"a project's identifier that is not a name", func(in *export.Inputs) {
338 in.Placements["../app"] = export.Placement{}
339 }, `a project's identifier is "../app", which is not a name`},
340 }
341 for _, c := range cases {
342 t.Run(c.name, func(t *testing.T) {
343 in := f.Inputs
344 in.Details = slices.Clone(in.Details)
345 in.Groups = slices.Clone(in.Groups)
346 in.Placements = maps.Clone(in.Placements)
347 c.change(&in)
348 _, err := export.Build(in)
349 if err == nil || !strings.Contains(err.Error(), c.want) {
350 t.Fatalf("Build gave %v, want an error saying %q", err, c.want)
351 }
352 })
353 }
354 in := f.Inputs
355 in.Details = slices.Clone(in.Details)
356 in.Details[0] = bytes.Replace(in.Details[0], []byte("3f6a0c1d"), []byte("3f6a0c1e"), 1)
357 if _, err := export.Build(in); !errors.Is(err, export.ErrInconsistent) {
358 t.Errorf("a detail at another tip gave %v, want ErrInconsistent", err)
359 }
360}
361
362// With no public project, the export is empty and valid, and names no
363// group.
364func TestBuildExportsNothingWhenNothingIsPublic(t *testing.T) {
365 f := exporttest.New(t)
366 in := f.Inputs
367 in.Identities = nil
368 e, err := export.Build(in)
369 if err != nil {
370 t.Fatal(err)
371 }
372 if len(e.Projects) != 0 || len(e.Groups) != 0 {
373 t.Errorf("exported %v and %v", e.Groups, e.Projects)
374 }
375}
376
377// The export carries each public project's group and short aliases, and
378// the groups public projects belong to. A group that only private
379// projects belong to is not exported, nor are a private project's aliases.
380func TestBuildExportsThePublicProjectsGroups(t *testing.T) {
381 f := exporttest.New(t)
382 in := f.Inputs
383 in.Groups = append(slices.Clone(in.Groups), export.Group{ID: "web", Name: "docs", Aliases: []string{"d"}})
384 in.Placements = map[string]export.Placement{
385 "app": {Group: "core", Name: "main", FormerNames: []string{"app"}, Aliases: []string{"app"}},
386 "site": {Group: "web", Name: "pages", FormerNames: []string{"site-old"}, Aliases: []string{"site-short"}},
387 }
388 e, err := export.Build(in)
389 if err != nil {
390 t.Fatal(err)
391 }
392 if want := exporttest.Groups; !reflect.DeepEqual(e.Groups, want) {
393 t.Errorf("the export's groups are %v, want %v", e.Groups, want)
394 }
395 if p := e.Projects[0]; p.Group != "core" || p.WebName != "main" || !slices.Equal(p.FormerNames, []string{"app"}) || !slices.Equal(p.Aliases, []string{"app"}) {
396 t.Errorf("app is exported in group %q as %q, with former names %v and aliases %v", p.Group, p.WebName, p.FormerNames, p.Aliases)
397 }
398 data, err := e.Encode()
399 if err != nil {
400 t.Fatal(err)
401 }
402 for _, private := range []string{`"web"`, `"docs"`, `"d"`, `"pages"`, `"site-old"`, `"site-short"`} {
403 if bytes.Contains(data, []byte(private)) {
404 t.Errorf("export.json holds %s, which only site is named by:\n%s", private, data)
405 }
406 }
407}
408
409// export.json is read strictly: a key that is not a field's name spelled
410// exactly, in any case or Unicode case-fold variant, a key twice in one
411// object, an array where the field holds none, or a project name that is
412// not safe as a file name, fails it. Each case is refused for the reason
413// it names. Brackets nested a million deep are refused at the first one
414// the field cannot hold.
415func TestDecodeIsStrict(t *testing.T) {
416 f := exporttest.New(t)
417 if _, err := export.Decode(f.ExportJSON); err != nil {
418 t.Fatal(err)
419 }
420 const deep = 1 << 20
421 brackets := strings.Repeat("[", deep) + "null" + strings.Repeat("]", deep)
422 for _, c := range []struct {
423 name string
424 data []byte
425 want string
426 }{
427 {"an unknown field", bytes.Replace(f.ExportJSON, []byte(`"collected"`), []byte(`"extra":1,"collected"`), 1),
428 `holds the key "extra", which is none of its fields`},
429 {"an unsafe name", bytes.Replace(f.ExportJSON, []byte(`"project":"app"`), []byte(`"project":"../app"`), 1),
430 `names a project "../app", which is not a project name`},
431 {"a second document", append(append([]byte{}, f.ExportJSON...), f.ExportJSON...),
432 "holds more than its one document"},
433 {"another schema", bytes.Replace(f.ExportJSON, []byte(export.Schema), []byte("valley-web-export/v0"), 1),
434 `has schema "valley-web-export/v0"`},
435 {"a field spelled in another case beside it", bytes.Replace(f.ExportJSON, []byte(`"aliases":["app"]`),
436 []byte(`"aliases":["app"],"Aliases":["other"]`), 1),
437 `projects[0] holds the key "Aliases", which is its field "aliases" spelled another way`},
438 {"a field spelled with a Unicode case-fold variant", bytes.Replace(f.ExportJSON, []byte(`"aliases":["app"]`),
439 []byte(`"alia`+"ſ"+`es":["other"]`), 1),
440 `projects[0] holds the key "alia` + "ſ" + `es", which is its field "aliases" spelled another way`},
441 {"a field given twice", bytes.Replace(f.ExportJSON, []byte(`"aliases":["app"]`),
442 []byte(`"aliases":["app"],"aliases":["other"]`), 1),
443 `projects[0] holds the key "aliases" twice`},
444 {"a field given twice, once escaped", bytes.Replace(f.ExportJSON, []byte(`"aliases":["app"]`),
445 []byte(`"aliases":["app"],"\u0061liases":["other"]`), 1),
446 `projects[0] holds the key "aliases" twice`},
447 {"a project alias that is a group's alias", bytes.Replace(f.ExportJSON, []byte(`"aliases":["app"]`),
448 []byte(`"aliases":["T"]`), 1),
449 `alias 0 of group core and alias 0 of project app are both "T"`},
450 {"a group name that is reserved", bytes.Replace(f.ExportJSON, []byte(`"name":"tools"`), []byte(`"name":"-"`), 1),
451 `the name of group core is "-", which is not a name`},
452 {"a former name that is the project's web name", bytes.Replace(f.ExportJSON, []byte(`"former_names":["old-app"]`),
453 []byte(`"former_names":["App"]`), 1),
454 `the web name of project app and former name 0 of project app are both "App"`},
455 {"brackets in place of the document", []byte(brackets),
456 `export.json: the document is an array, and export.Export holds no array`},
457 {"brackets in place of an alias", bytes.Replace(f.ExportJSON, []byte(`"aliases":["app"]`),
458 []byte(`"aliases":[`+brackets+`]`), 1),
459 `export.json: projects[0].aliases[0] is an array, and string holds no array`},
460 } {
461 if _, err := export.Decode(c.data); err == nil || !strings.Contains(err.Error(), c.want) {
462 t.Errorf("Decode of %s gave %v, want an error saying %q", c.name, err, c.want)
463 }
464 }
465}
466
467// An export's groups are each some project's, in identifier order, and
468// each group a project names is listed. Every case keeps every listed
469// group some project's but the one that tests it, so each is refused for
470// the reason it names alone, and a check that went missing would let its
471// case through.
472func TestDecodeHoldsGroupsToTheirProjects(t *testing.T) {
473 f := exporttest.New(t)
474 // two is the fixture's export with site public too, as a copy of
475 // app: groups lists core and web, app is in core, and site in web.
476 two := func(change func(e *export.Export)) []byte {
477 t.Helper()
478 e, err := export.Decode(f.ExportJSON)
479 if err != nil {
480 t.Fatal(err)
481 }
482 site := e.Projects[0]
483 site.Name, site.Group, site.WebName, site.FormerNames, site.Aliases = "site", "web", "app", nil, nil
484 e.Projects = append(e.Projects, site)
485 e.Groups = append(e.Groups, export.Group{ID: "web", Name: "docs"})
486 change(e)
487 data, err := json.Marshal(e)
488 if err != nil {
489 t.Fatal(err)
490 }
491 return data
492 }
493 if e, err := export.Decode(two(func(*export.Export) {})); err != nil {
494 t.Fatalf("an export with app and site each named app in its own group is refused: %v", err)
495 } else if e.Projects[0].WebName != "app" || e.Projects[1].WebName != "app" {
496 t.Fatalf("the two projects decode as %q and %q", e.Projects[0].WebName, e.Projects[1].WebName)
497 }
498 for _, c := range []struct {
499 name string
500 change func(e *export.Export)
501 want string
502 }{
503 {"groups out of order", func(e *export.Export) {
504 e.Groups[0], e.Groups[1] = e.Groups[1], e.Groups[0]
505 }, "export.json: the group core is listed out of order or twice"},
506 {"a group listed twice", func(e *export.Export) {
507 e.Groups[1] = e.Groups[0]
508 e.Projects[1].Group = "core"
509 e.Projects[1].WebName = "site"
510 }, "export.json: the group core is listed out of order or twice"},
511 {"a group no project belongs to", func(e *export.Export) {
512 e.Projects[1].Group = "core"
513 e.Projects[1].WebName = "site"
514 }, "export.json lists group web, which none of its projects belongs to"},
515 {"a project in a group it does not list", func(e *export.Export) {
516 e.Groups = e.Groups[:1]
517 e.Projects[1].Group = "web"
518 }, `export.json: the project site belongs to the group "web", which is not declared`},
519 {"two projects of one web name in one group", func(e *export.Export) {
520 e.Groups = e.Groups[:1]
521 e.Projects[1].Group = "core"
522 }, `export.json: the web name of project app and the web name of project site are both "app"`},
523 } {
524 if _, err := export.Decode(two(c.change)); err == nil || !strings.Contains(err.Error(), c.want) {
525 t.Errorf("Decode of %s gave %v, want an error saying %q", c.name, err, c.want)
526 }
527 }
528}
529
530// A v1 export from before groups decodes: it has no groups, and its
531// projects no group and no aliases.
532func TestDecodeTakesAnExportWithoutGroups(t *testing.T) {
533 f := exporttest.New(t)
534 data := bytes.Replace(f.ExportJSON, []byte(`"groups":[{"group":"core","name":"tools","aliases":["t"]}],`), nil, 1)
535 data = bytes.Replace(data, []byte(`"group":"core","name":"app","former_names":["old-app"],"aliases":["app"],`), nil, 1)
536 if bytes.Contains(data, []byte(`"group"`)) {
537 t.Fatalf("the fixture's export no longer reads as the test expects:\n%s", data)
538 }
539 e, err := export.Decode(data)
540 if err != nil {
541 t.Fatal(err)
542 }
543 if p := e.Projects[0]; len(e.Groups) != 0 || p.Group != "" || p.WebName != "" || p.FormerNames != nil || p.Aliases != nil {
544 t.Errorf("an export without groups decodes with %v, and app in %q as %q with %v and %v", e.Groups, p.Group, p.WebName, p.FormerNames, p.Aliases)
545 }
546}
547
548// Nothing but white space may follow export.json's document: not a
549// closing bracket or brace, which ends a document without starting
550// another, and not a malformed suffix. A receiver refuses such an
551// export.json as bad-export even when the manifest declares its bytes.
552func TestDecodeRefusesTrailingInput(t *testing.T) {
553 f := exporttest.New(t)
554 for _, suffix := range []string{"]", "}", "]garbage", "}}", "],", "garbage", ",", "{", `"`, "nul", "\x00", "{}", "[]", "1"} {
555 data := append(append([]byte{}, f.ExportJSON...), suffix...)
556 if _, err := export.Decode(data); err == nil {
557 t.Errorf("Decode took export.json followed by %q", suffix)
558 }
559 m := *f.Manifest
560 m.File = export.BodyOf(export.ExportFile, data)
561 if _, err := m.CheckExport(data); export.CodeOf(err) != export.CodeBadExport {
562 t.Errorf("CheckExport gave %v for export.json followed by %q, want bad-export", err, suffix)
563 }
564 }
565 data := append(append([]byte{}, f.ExportJSON...), " \t\r\n\n"...)
566 if _, err := export.Decode(data); err != nil {
567 t.Errorf("Decode refused export.json followed by white space: %v", err)
568 }
569}
570
571// The content digest ignores display-time fields and nothing else.
572func TestDigest(t *testing.T) {
573 f := exporttest.New(t)
574 base, err := f.Export.Digest()
575 if err != nil {
576 t.Fatal(err)
577 }
578 reread := func() *export.Export {
579 e, err := export.Decode(f.ExportJSON)
580 if err != nil {
581 t.Fatal(err)
582 }
583 return e
584 }
585 same := map[string]func(e *export.Export){
586 "collected": func(e *export.Export) { e.Collected = "2026-10-26T00:00:00Z" },
587 "a claim's age": func(e *export.Export) {
588 for i := range e.Projects[0].Knots {
589 if c := e.Projects[0].Knots[i].Claim; c != nil {
590 c.AgeSeconds, c.Stale = 999999, true
591 }
592 }
593 },
594 }
595 for name, change := range same {
596 e := reread()
597 change(e)
598 if got, _ := e.Digest(); got != base {
599 t.Errorf("changing %s changed the digest", name)
600 }
601 }
602 differs := map[string]func(e *export.Export){
603 "a title": func(e *export.Export) { e.Projects[0].Knots[0].Title += "!" },
604 "a source tip": func(e *export.Export) { e.Projects[0].SourceTip = strings.Repeat("a", 40) },
605 "a claim's at": func(e *export.Export) { e.Projects[0].Knots[1].Claim.At = "2026-10-25T11:00:00Z" },
606 "a comment": func(e *export.Export) { e.Projects[0].Knots[1].Comments[0].Body += "." },
607 "waiting on a hidden knot": func(e *export.Export) {
608 e.Projects[0].Knots[0].WaitingOnHidden = !e.Projects[0].Knots[0].WaitingOnHidden
609 },
610 }
611 for name, change := range differs {
612 e := reread()
613 change(e)
614 if got, _ := e.Digest(); got == base {
615 t.Errorf("changing %s left the digest as it was", name)
616 }
617 }
618 // Digest copies what it clears: the export it was given is unchanged.
619 if f.Export.Collected == "" || knotOf(t, f.Export, "oc-a000002").Claim.AgeSeconds == 0 {
620 t.Error("Digest changed the export it read")
621 }
622}
623
624// Incremental decoding preserves the export's values and rejects malformed
625// fields, including nested fields and integer overflow.
626func TestDecodeContextValues(t *testing.T) {
627 f := exporttest.New(t)
628 for _, data := range [][]byte{
629 f.ExportJSON,
630 []byte(`{"schema":"valley-web-export/v2","projects":null}`),
631 []byte(`{"schema":"valley-web-export/v2","projects":[]}`),
632 } {
633 var want export.Export
634 if err := json.Unmarshal(data, &want); err != nil {
635 t.Fatal(err)
636 }
637 got, err := export.DecodeContext(context.Background(), bytes.NewReader(data))
638 if err != nil {
639 t.Fatal(err)
640 }
641 if !reflect.DeepEqual(got, &want) {
642 t.Fatal("incremental decoding changed export values")
643 }
644 }
645 for _, field := range []string{
646 `"knots":{}`, `"roots":[1]`, `"knots":[{"id":"oc-a000001","active":1}]`,
647 `"knots":[{"id":"oc-a000001","comment_count":9223372036854775808}]`,
648 `"knots":[{"id":"oc-a000001","comment_count":1.5}]`, `"knots":[{"id":"oc-a000001","unknown":true}]`,
649 } {
650 data := []byte(`{"schema":"valley-web-export/v2","projects":[{"project":"app","identity":"9da6809f038df92138c131cd16bed76d","source_tip":"` + strings.Repeat("a", 40) + `",` + field + `}]}`)
651 if _, err := export.DecodeContext(context.Background(), bytes.NewReader(data)); err == nil {
652 t.Errorf("accepted %s", field)
653 }
654 }
655}
656
657// A token that spans many reads observes cancellation before consuming its
658// remaining bytes.
659func TestDecodeContextDuringToken(t *testing.T) {
660 ctx, cancel := context.WithCancel(context.Background())
661 defer cancel()
662 r := &cancelDecodeReader{Reader: strings.NewReader(`{"schema":"` + strings.Repeat("x", 1<<20) + `"}`), cancel: cancel}
663 if _, err := export.DecodeContext(ctx, r); !errors.Is(err, context.Canceled) {
664 t.Fatalf("error = %v", err)
665 }
666 if r.n > 8192 {
667 t.Fatalf("read %d bytes after cancellation", r.n)
668 }
669}
670
671type cancelDecodeReader struct {
672 io.Reader
673 cancel context.CancelFunc
674 n int
675}
676
677func (r *cancelDecodeReader) Read(p []byte) (int, error) {
678 n, err := r.Reader.Read(p)
679 r.n += n
680 if r.n >= 4096 {
681 r.cancel()
682 }
683 return n, err
684}
685
686// The final input read arms cancellation. The string scanner must observe
687// it while decoding bytes already in its buffer, without another source read.
688func TestDecodeContextFinalStringChunk(t *testing.T) {
689 for _, key := range []bool{false, true} {
690 t.Run(fmt.Sprint(key), func(t *testing.T) {
691 base, cancel := context.WithCancel(context.Background())
692 defer cancel()
693 ctx := &finalStringContext{Context: base, cancel: cancel}
694 value := strings.Repeat(`\u0061`, 1<<17)
695 data := `{"schema":"valley-web-export/v2","collected":"` + value + `"}`
696 if key {
697 data = `{"` + value + `":null}`
698 }
699 r := &finalStringReader{Reader: strings.NewReader(data), ctx: ctx}
700 started := time.Now()
701 got, err := export.DecodeContext(ctx, r)
702 if got != nil || !errors.Is(err, context.Canceled) {
703 t.Fatalf("DecodeContext = %v, %v", got, err)
704 }
705 if !ctx.inString {
706 t.Fatal("cancellation was not observed inside string decoding")
707 }
708 if r.extraRead {
709 t.Fatal("decoder requested more input after the final chunk")
710 }
711 if time.Since(started) > 2*time.Second {
712 t.Fatal("string decoding did not stop promptly")
713 }
714 })
715 }
716}
717
718type finalStringContext struct {
719 context.Context
720 cancel context.CancelFunc
721 armed bool
722 checks int
723 inString bool
724}
725
726func (c *finalStringContext) Err() error {
727 if c.armed {
728 c.checks++
729 if c.checks == 3 {
730 var pcs [16]uintptr
731 n := runtime.Callers(2, pcs[:])
732 frames := runtime.CallersFrames(pcs[:n])
733 for {
734 f, more := frames.Next()
735 if strings.HasSuffix(f.Function, ".(*stringInput).readString") {
736 c.inString = true
737 }
738 if !more {
739 break
740 }
741 }
742 c.cancel()
743 }
744 }
745 return c.Context.Err()
746}
747
748type finalStringReader struct {
749 *strings.Reader
750 ctx *finalStringContext
751 extraRead bool
752}
753
754func (r *finalStringReader) Read(p []byte) (int, error) {
755 if r.ctx.armed {
756 r.extraRead = true
757 }
758 n, err := r.Reader.Read(p)
759 if r.Len() == 0 {
760 r.ctx.armed = true
761 }
762 return n, err
763}
764
765// String decoding matches encoding/json for escapes, invalid UTF-8 and
766// surrogate pairs, including sequences split across input chunks.
767func TestDecodeStringValues(t *testing.T) {
768 values := []string{
769 `"plain"`, `"\"\\\/\b\f\n\r\t"`, `"\uD834\uDD1E"`,
770 `"\uD834x"`, `"\uDD1E"`, `"\uD834\u0061"`, `"\uD834\uD834\uDD1E"`,
771 "\"\xff\"", `"é界𝄞"`,
772 }
773 prefixes := []string{""}
774 for offset := 0; offset < 12; offset++ {
775 prefixes = append(prefixes, strings.Repeat("a", 4096-len(`{"schema":"valley-web-export/v2","collected":"`)-offset))
776 }
777 for _, prefix := range prefixes {
778 for _, value := range values {
779 data := []byte(`{"schema":"valley-web-export/v2","collected":"` + prefix + value[1:] + `}`)
780 var want export.Export
781 if err := json.Unmarshal(data, &want); err != nil {
782 t.Fatal(err)
783 }
784 got, err := export.DecodeContext(context.Background(), bytes.NewReader(data))
785 if err != nil {
786 t.Fatal(err)
787 }
788 if !reflect.DeepEqual(got, &want) {
789 t.Errorf("string %q differs from encoding/json", value)
790 }
791 }
792 }
793 for _, value := range []string{`"\x"`, `"\uZZZZ"`, `"\u123"`, `"unterminated`, "\"\n\"", `"\uD834\uZZZZ"`} {
794 data := []byte(`{"schema":"valley-web-export/v2","collected":` + value + `}`)
795 if _, err := export.Decode(data); err == nil {
796 t.Errorf("accepted invalid string %q", value)
797 }
798 }
799}
800
801// More must not consume and hide a string error before a closing delimiter.
802func TestDecodeRetainsStringError(t *testing.T) {
803 for _, data := range []string{
804 `{"schema":"valley-web-export/v2","projects":["\x]}`,
805 `{"schema":"valley-web-export/v2","\x}`,
806 } {
807 if _, err := export.Decode([]byte(data)); err == nil {
808 t.Errorf("accepted malformed document %q", data)
809 }
810 }
811}