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