| 1 | package export_test |
| 2 | |
| 3 | import ( |
| 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. |
| 26 | func 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 | |
| 46 | func 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. |
| 61 | func 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. |
| 103 | func 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. |
| 153 | func 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 | |
| 177 | func 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. |
| 185 | func 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. |
| 195 | func 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. |
| 219 | func 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. |
| 235 | func 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. |
| 254 | func 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", 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, and one second segment of a web URL under the group core names one project`}, |
| 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. |
| 364 | func TestBuildExportsNothingWhenNothingIsPublic(t *testing.T) { |
| 365 | f := exporttest.New(t) |
| 366 | in := f.Inputs |
| 367 | in.Visibility = 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. |
| 380 | func 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 field the schema does not name, or a |
| 410 | // project name that is not safe as a file name, fails it. Each case is |
| 411 | // refused for the reason it names. |
| 412 | func TestDecodeIsStrict(t *testing.T) { |
| 413 | f := exporttest.New(t) |
| 414 | if _, err := export.Decode(f.ExportJSON); err != nil { |
| 415 | t.Fatal(err) |
| 416 | } |
| 417 | for _, c := range []struct { |
| 418 | name string |
| 419 | data []byte |
| 420 | want string |
| 421 | }{ |
| 422 | {"an unknown field", bytes.Replace(f.ExportJSON, []byte(`"collected"`), []byte(`"extra":1,"collected"`), 1), |
| 423 | `unknown field "extra"`}, |
| 424 | {"an unsafe name", bytes.Replace(f.ExportJSON, []byte(`"project":"app"`), []byte(`"project":"../app"`), 1), |
| 425 | `names a project "../app", which is not a project name`}, |
| 426 | {"a second document", append(append([]byte{}, f.ExportJSON...), f.ExportJSON...), |
| 427 | "holds more than its one document"}, |
| 428 | {"another schema", bytes.Replace(f.ExportJSON, []byte(export.Schema), []byte("valley-web-export/v0"), 1), |
| 429 | `has schema "valley-web-export/v0"`}, |
| 430 | {"a project alias that is a group's alias", bytes.Replace(f.ExportJSON, []byte(`"aliases":["app"]`), |
| 431 | []byte(`"aliases":["T"]`), 1), |
| 432 | `alias 0 of group core and alias 0 of project app are both "T"`}, |
| 433 | {"a group name that is reserved", bytes.Replace(f.ExportJSON, []byte(`"name":"tools"`), []byte(`"name":"-"`), 1), |
| 434 | `the name of group core is "-", which is not a name`}, |
| 435 | {"a former name that is the project's web name", bytes.Replace(f.ExportJSON, []byte(`"former_names":["old-app"]`), |
| 436 | []byte(`"former_names":["App"]`), 1), |
| 437 | `the web name of project app and former name 0 of project app are both "App"`}, |
| 438 | } { |
| 439 | if _, err := export.Decode(c.data); err == nil || !strings.Contains(err.Error(), c.want) { |
| 440 | t.Errorf("Decode of %s gave %v, want an error saying %q", c.name, err, c.want) |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | // An export's groups are each some project's, in identifier order, and |
| 446 | // each group a project names is listed. Every case keeps every listed |
| 447 | // group some project's but the one that tests it, so each is refused for |
| 448 | // the reason it names alone, and a check that went missing would let its |
| 449 | // case through. |
| 450 | func TestDecodeHoldsGroupsToTheirProjects(t *testing.T) { |
| 451 | f := exporttest.New(t) |
| 452 | // two is the fixture's export with site public too, as a copy of |
| 453 | // app: groups lists core and web, app is in core, and site in web. |
| 454 | two := func(change func(e *export.Export)) []byte { |
| 455 | t.Helper() |
| 456 | e, err := export.Decode(f.ExportJSON) |
| 457 | if err != nil { |
| 458 | t.Fatal(err) |
| 459 | } |
| 460 | site := e.Projects[0] |
| 461 | site.Name, site.Group, site.WebName, site.FormerNames, site.Aliases = "site", "web", "app", nil, nil |
| 462 | e.Projects = append(e.Projects, site) |
| 463 | e.Groups = append(e.Groups, export.Group{ID: "web", Name: "docs"}) |
| 464 | change(e) |
| 465 | data, err := json.Marshal(e) |
| 466 | if err != nil { |
| 467 | t.Fatal(err) |
| 468 | } |
| 469 | return data |
| 470 | } |
| 471 | if e, err := export.Decode(two(func(*export.Export) {})); err != nil { |
| 472 | t.Fatalf("an export with app and site each named app in its own group is refused: %v", err) |
| 473 | } else if e.Projects[0].WebName != "app" || e.Projects[1].WebName != "app" { |
| 474 | t.Fatalf("the two projects decode as %q and %q", e.Projects[0].WebName, e.Projects[1].WebName) |
| 475 | } |
| 476 | for _, c := range []struct { |
| 477 | name string |
| 478 | change func(e *export.Export) |
| 479 | want string |
| 480 | }{ |
| 481 | {"groups out of order", func(e *export.Export) { |
| 482 | e.Groups[0], e.Groups[1] = e.Groups[1], e.Groups[0] |
| 483 | }, "export.json: the group core is listed out of order or twice"}, |
| 484 | {"a group listed twice", func(e *export.Export) { |
| 485 | e.Groups[1] = e.Groups[0] |
| 486 | e.Projects[1].Group = "core" |
| 487 | e.Projects[1].WebName = "site" |
| 488 | }, "export.json: the group core is listed out of order or twice"}, |
| 489 | {"a group no project belongs to", func(e *export.Export) { |
| 490 | e.Projects[1].Group = "core" |
| 491 | e.Projects[1].WebName = "site" |
| 492 | }, "export.json lists group web, which none of its projects belongs to"}, |
| 493 | {"a project in a group it does not list", func(e *export.Export) { |
| 494 | e.Groups = e.Groups[:1] |
| 495 | e.Projects[1].Group = "web" |
| 496 | }, `export.json: the project site belongs to the group "web", which is not declared`}, |
| 497 | {"two projects of one web name in one group", func(e *export.Export) { |
| 498 | e.Groups = e.Groups[:1] |
| 499 | e.Projects[1].Group = "core" |
| 500 | }, `export.json: the web name of project app and the web name of project site are both "app"`}, |
| 501 | } { |
| 502 | if _, err := export.Decode(two(c.change)); err == nil || !strings.Contains(err.Error(), c.want) { |
| 503 | t.Errorf("Decode of %s gave %v, want an error saying %q", c.name, err, c.want) |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | // A v1 export from before groups decodes: it has no groups, and its |
| 509 | // projects no group and no aliases. |
| 510 | func TestDecodeTakesAnExportWithoutGroups(t *testing.T) { |
| 511 | f := exporttest.New(t) |
| 512 | data := bytes.Replace(f.ExportJSON, []byte(`"groups":[{"group":"core","name":"tools","aliases":["t"]}],`), nil, 1) |
| 513 | data = bytes.Replace(data, []byte(`"group":"core","name":"app","former_names":["old-app"],"aliases":["app"],`), nil, 1) |
| 514 | if bytes.Contains(data, []byte(`"group"`)) { |
| 515 | t.Fatalf("the fixture's export no longer reads as the test expects:\n%s", data) |
| 516 | } |
| 517 | e, err := export.Decode(data) |
| 518 | if err != nil { |
| 519 | t.Fatal(err) |
| 520 | } |
| 521 | if p := e.Projects[0]; len(e.Groups) != 0 || p.Group != "" || p.WebName != "" || p.FormerNames != nil || p.Aliases != nil { |
| 522 | 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) |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | // Nothing but white space may follow export.json's document: not a |
| 527 | // closing bracket or brace, which ends a document without starting |
| 528 | // another, and not a malformed suffix. A receiver refuses such an |
| 529 | // export.json as bad-export even when the manifest declares its bytes. |
| 530 | func TestDecodeRefusesTrailingInput(t *testing.T) { |
| 531 | f := exporttest.New(t) |
| 532 | for _, suffix := range []string{"]", "}", "]garbage", "}}", "],", "garbage", ",", "{", `"`, "nul", "\x00", "{}", "[]", "1"} { |
| 533 | data := append(append([]byte{}, f.ExportJSON...), suffix...) |
| 534 | if _, err := export.Decode(data); err == nil { |
| 535 | t.Errorf("Decode took export.json followed by %q", suffix) |
| 536 | } |
| 537 | m := *f.Manifest |
| 538 | m.File = export.BodyOf(export.ExportFile, data) |
| 539 | if _, err := m.CheckExport(data); export.CodeOf(err) != export.CodeBadExport { |
| 540 | t.Errorf("CheckExport gave %v for export.json followed by %q, want bad-export", err, suffix) |
| 541 | } |
| 542 | } |
| 543 | data := append(append([]byte{}, f.ExportJSON...), " \t\r\n\n"...) |
| 544 | if _, err := export.Decode(data); err != nil { |
| 545 | t.Errorf("Decode refused export.json followed by white space: %v", err) |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | // The content digest ignores display-time fields and nothing else. |
| 550 | func TestDigest(t *testing.T) { |
| 551 | f := exporttest.New(t) |
| 552 | base, err := f.Export.Digest() |
| 553 | if err != nil { |
| 554 | t.Fatal(err) |
| 555 | } |
| 556 | reread := func() *export.Export { |
| 557 | e, err := export.Decode(f.ExportJSON) |
| 558 | if err != nil { |
| 559 | t.Fatal(err) |
| 560 | } |
| 561 | return e |
| 562 | } |
| 563 | same := map[string]func(e *export.Export){ |
| 564 | "collected": func(e *export.Export) { e.Collected = "2026-10-26T00:00:00Z" }, |
| 565 | "a claim's age": func(e *export.Export) { |
| 566 | for i := range e.Projects[0].Knots { |
| 567 | if c := e.Projects[0].Knots[i].Claim; c != nil { |
| 568 | c.AgeSeconds, c.Stale = 999999, true |
| 569 | } |
| 570 | } |
| 571 | }, |
| 572 | } |
| 573 | for name, change := range same { |
| 574 | e := reread() |
| 575 | change(e) |
| 576 | if got, _ := e.Digest(); got != base { |
| 577 | t.Errorf("changing %s changed the digest", name) |
| 578 | } |
| 579 | } |
| 580 | differs := map[string]func(e *export.Export){ |
| 581 | "a title": func(e *export.Export) { e.Projects[0].Knots[0].Title += "!" }, |
| 582 | "a source tip": func(e *export.Export) { e.Projects[0].SourceTip = strings.Repeat("a", 40) }, |
| 583 | "a claim's at": func(e *export.Export) { e.Projects[0].Knots[1].Claim.At = "2026-10-25T11:00:00Z" }, |
| 584 | "a comment": func(e *export.Export) { e.Projects[0].Knots[1].Comments[0].Body += "." }, |
| 585 | "waiting on a hidden knot": func(e *export.Export) { |
| 586 | e.Projects[0].Knots[0].WaitingOnHidden = !e.Projects[0].Knots[0].WaitingOnHidden |
| 587 | }, |
| 588 | } |
| 589 | for name, change := range differs { |
| 590 | e := reread() |
| 591 | change(e) |
| 592 | if got, _ := e.Digest(); got == base { |
| 593 | t.Errorf("changing %s left the digest as it was", name) |
| 594 | } |
| 595 | } |
| 596 | // Digest copies what it clears: the export it was given is unchanged. |
| 597 | if f.Export.Collected == "" || knotOf(t, f.Export, "oc-a000002").Claim.AgeSeconds == 0 { |
| 598 | t.Error("Digest changed the export it read") |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | // Incremental decoding preserves the export's values and rejects malformed |
| 603 | // fields, including nested fields and integer overflow. |
| 604 | func TestDecodeContextValues(t *testing.T) { |
| 605 | f := exporttest.New(t) |
| 606 | for _, data := range [][]byte{ |
| 607 | f.ExportJSON, |
| 608 | []byte(`{"schema":"valley-web-export/v1","projects":null}`), |
| 609 | []byte(`{"schema":"valley-web-export/v1","projects":[]}`), |
| 610 | } { |
| 611 | var want export.Export |
| 612 | if err := json.Unmarshal(data, &want); err != nil { |
| 613 | t.Fatal(err) |
| 614 | } |
| 615 | got, err := export.DecodeContext(context.Background(), bytes.NewReader(data)) |
| 616 | if err != nil { |
| 617 | t.Fatal(err) |
| 618 | } |
| 619 | if !reflect.DeepEqual(got, &want) { |
| 620 | t.Fatal("incremental decoding changed export values") |
| 621 | } |
| 622 | } |
| 623 | for _, field := range []string{ |
| 624 | `"knots":{}`, `"roots":[1]`, `"knots":[{"id":"oc-a000001","active":1}]`, |
| 625 | `"knots":[{"id":"oc-a000001","comment_count":9223372036854775808}]`, |
| 626 | `"knots":[{"id":"oc-a000001","comment_count":1.5}]`, `"knots":[{"id":"oc-a000001","unknown":true}]`, |
| 627 | } { |
| 628 | data := []byte(`{"schema":"valley-web-export/v1","projects":[{"project":"app","visibility":"public","source_tip":"` + strings.Repeat("a", 40) + `",` + field + `}]}`) |
| 629 | if _, err := export.DecodeContext(context.Background(), bytes.NewReader(data)); err == nil { |
| 630 | t.Errorf("accepted %s", field) |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | // A token that spans many reads observes cancellation before consuming its |
| 636 | // remaining bytes. |
| 637 | func TestDecodeContextDuringToken(t *testing.T) { |
| 638 | ctx, cancel := context.WithCancel(context.Background()) |
| 639 | defer cancel() |
| 640 | r := &cancelDecodeReader{Reader: strings.NewReader(`{"schema":"` + strings.Repeat("x", 1<<20) + `"}`), cancel: cancel} |
| 641 | if _, err := export.DecodeContext(ctx, r); !errors.Is(err, context.Canceled) { |
| 642 | t.Fatalf("error = %v", err) |
| 643 | } |
| 644 | if r.n > 8192 { |
| 645 | t.Fatalf("read %d bytes after cancellation", r.n) |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | type cancelDecodeReader struct { |
| 650 | io.Reader |
| 651 | cancel context.CancelFunc |
| 652 | n int |
| 653 | } |
| 654 | |
| 655 | func (r *cancelDecodeReader) Read(p []byte) (int, error) { |
| 656 | n, err := r.Reader.Read(p) |
| 657 | r.n += n |
| 658 | if r.n >= 4096 { |
| 659 | r.cancel() |
| 660 | } |
| 661 | return n, err |
| 662 | } |
| 663 | |
| 664 | // The final input read arms cancellation. The string scanner must observe |
| 665 | // it while decoding bytes already in its buffer, without another source read. |
| 666 | func TestDecodeContextFinalStringChunk(t *testing.T) { |
| 667 | for _, key := range []bool{false, true} { |
| 668 | t.Run(fmt.Sprint(key), func(t *testing.T) { |
| 669 | base, cancel := context.WithCancel(context.Background()) |
| 670 | defer cancel() |
| 671 | ctx := &finalStringContext{Context: base, cancel: cancel} |
| 672 | value := strings.Repeat(`\u0061`, 1<<17) |
| 673 | data := `{"schema":"valley-web-export/v1","collected":"` + value + `"}` |
| 674 | if key { |
| 675 | data = `{"` + value + `":null}` |
| 676 | } |
| 677 | r := &finalStringReader{Reader: strings.NewReader(data), ctx: ctx} |
| 678 | started := time.Now() |
| 679 | got, err := export.DecodeContext(ctx, r) |
| 680 | if got != nil || !errors.Is(err, context.Canceled) { |
| 681 | t.Fatalf("DecodeContext = %v, %v", got, err) |
| 682 | } |
| 683 | if !ctx.inString { |
| 684 | t.Fatal("cancellation was not observed inside string decoding") |
| 685 | } |
| 686 | if r.extraRead { |
| 687 | t.Fatal("decoder requested more input after the final chunk") |
| 688 | } |
| 689 | if time.Since(started) > 2*time.Second { |
| 690 | t.Fatal("string decoding did not stop promptly") |
| 691 | } |
| 692 | }) |
| 693 | } |
| 694 | } |
| 695 | |
| 696 | type finalStringContext struct { |
| 697 | context.Context |
| 698 | cancel context.CancelFunc |
| 699 | armed bool |
| 700 | checks int |
| 701 | inString bool |
| 702 | } |
| 703 | |
| 704 | func (c *finalStringContext) Err() error { |
| 705 | if c.armed { |
| 706 | c.checks++ |
| 707 | if c.checks == 3 { |
| 708 | var pcs [16]uintptr |
| 709 | n := runtime.Callers(2, pcs[:]) |
| 710 | frames := runtime.CallersFrames(pcs[:n]) |
| 711 | for { |
| 712 | f, more := frames.Next() |
| 713 | if strings.HasSuffix(f.Function, ".(*stringInput).readString") { |
| 714 | c.inString = true |
| 715 | } |
| 716 | if !more { |
| 717 | break |
| 718 | } |
| 719 | } |
| 720 | c.cancel() |
| 721 | } |
| 722 | } |
| 723 | return c.Context.Err() |
| 724 | } |
| 725 | |
| 726 | type finalStringReader struct { |
| 727 | *strings.Reader |
| 728 | ctx *finalStringContext |
| 729 | extraRead bool |
| 730 | } |
| 731 | |
| 732 | func (r *finalStringReader) Read(p []byte) (int, error) { |
| 733 | if r.ctx.armed { |
| 734 | r.extraRead = true |
| 735 | } |
| 736 | n, err := r.Reader.Read(p) |
| 737 | if r.Len() == 0 { |
| 738 | r.ctx.armed = true |
| 739 | } |
| 740 | return n, err |
| 741 | } |
| 742 | |
| 743 | // String decoding matches encoding/json for escapes, invalid UTF-8 and |
| 744 | // surrogate pairs, including sequences split across input chunks. |
| 745 | func TestDecodeStringValues(t *testing.T) { |
| 746 | values := []string{ |
| 747 | `"plain"`, `"\"\\\/\b\f\n\r\t"`, `"\uD834\uDD1E"`, |
| 748 | `"\uD834x"`, `"\uDD1E"`, `"\uD834\u0061"`, `"\uD834\uD834\uDD1E"`, |
| 749 | "\"\xff\"", `"รฉ็๐"`, |
| 750 | } |
| 751 | prefixes := []string{""} |
| 752 | for offset := 0; offset < 12; offset++ { |
| 753 | prefixes = append(prefixes, strings.Repeat("a", 4096-len(`{"schema":"valley-web-export/v1","collected":"`)-offset)) |
| 754 | } |
| 755 | for _, prefix := range prefixes { |
| 756 | for _, value := range values { |
| 757 | data := []byte(`{"schema":"valley-web-export/v1","collected":"` + prefix + value[1:] + `}`) |
| 758 | var want export.Export |
| 759 | if err := json.Unmarshal(data, &want); err != nil { |
| 760 | t.Fatal(err) |
| 761 | } |
| 762 | got, err := export.DecodeContext(context.Background(), bytes.NewReader(data)) |
| 763 | if err != nil { |
| 764 | t.Fatal(err) |
| 765 | } |
| 766 | if !reflect.DeepEqual(got, &want) { |
| 767 | t.Errorf("string %q differs from encoding/json", value) |
| 768 | } |
| 769 | } |
| 770 | } |
| 771 | for _, value := range []string{`"\x"`, `"\uZZZZ"`, `"\u123"`, `"unterminated`, "\"\n\"", `"\uD834\uZZZZ"`} { |
| 772 | data := []byte(`{"schema":"valley-web-export/v1","collected":` + value + `}`) |
| 773 | if _, err := export.Decode(data); err == nil { |
| 774 | t.Errorf("accepted invalid string %q", value) |
| 775 | } |
| 776 | } |
| 777 | } |
| 778 | |
| 779 | // More must not consume and hide a string error before a closing delimiter. |
| 780 | func TestDecodeRetainsStringError(t *testing.T) { |
| 781 | for _, data := range []string{ |
| 782 | `{"schema":"valley-web-export/v1","projects":["\x]}`, |
| 783 | `{"schema":"valley-web-export/v1","\x}`, |
| 784 | } { |
| 785 | if _, err := export.Decode([]byte(data)); err == nil { |
| 786 | t.Errorf("accepted malformed document %q", data) |
| 787 | } |
| 788 | } |
| 789 | } |