package bridge import ( "context" "encoding/base64" "encoding/json" "errors" "fmt" "io" "net/http" "strings" "sync" "testing" "testing/fstest" "time" "yetano.dev/yetano/core/gui/assets" ) // fakeUI runs dispatched functions serially on one goroutine (like a UI // thread) and decodes every Eval into a message. type fakeUI struct { q chan func() msgs chan map[string]any once sync.Once } func newFakeUI() *fakeUI { u := &fakeUI{q: make(chan func(), 256), msgs: make(chan map[string]any, 256)} go func() { for f := range u.q { f() } }() return u } func (u *fakeUI) Dispatch(f func()) { u.q <- f } func (u *fakeUI) Eval(js string) { const p = "window.__yetano_recv&&window.__yetano_recv(" var m map[string]any if err := json.Unmarshal([]byte(strings.TrimSuffix(strings.TrimPrefix(js, p), ")")), &m); err != nil { panic(err) } u.msgs <- m } func (u *fakeUI) next(t *testing.T) map[string]any { t.Helper() select { case m := <-u.msgs: return m case <-time.After(3 * time.Second): t.Fatal("no message") return nil } } func (u *fakeUI) none(t *testing.T, d time.Duration) { t.Helper() select { case m := <-u.msgs: t.Fatalf("unexpected message %v", m) case <-time.After(d): } } type harness struct { s *Session ui *fakeUI started chan string causes chan error } func newHarness(t *testing.T) *harness { res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{"a.wasm": {Data: []byte("\x00asm\x01\x00\x00\x00")}})) r := NewRouter(res) h := &harness{ui: newFakeUI(), started: make(chan string, 16), causes: make(chan error, 16)} must := func(err error) { if err != nil { t.Fatal(err) } } must(r.Handle("POST", "/rpc/add", func(_ context.Context, req *Request) (*Response, error) { var in struct{ A, B int } json.Unmarshal(req.Body, &in) return JSONBytes(200, []byte(fmt.Sprintf(`{"result":%d}`, in.A+in.B))), nil })) must(r.Handle("POST", "/rpc/block", func(ctx context.Context, req *Request) (*Response, error) { h.started <- string(req.Body) <-ctx.Done() h.causes <- context.Cause(ctx) return nil, ctx.Err() })) must(r.Handle("GET", "/rpc/panic", func(context.Context, *Request) (*Response, error) { panic("boom") })) if err := r.Handle("POST", "/rpc/add", nil); err == nil { t.Fatal("nil/duplicate handler accepted") } if err := r.Handle("POST", "/rpc/add", func(context.Context, *Request) (*Response, error) { return nil, nil }); err == nil { t.Fatal("duplicate route accepted") } h.s = NewSession(r, Options{CloseWait: time.Second}) if err := r.Handle("GET", "/late", func(context.Context, *Request) (*Response, error) { return nil, nil }); err == nil { t.Fatal("route after session start accepted") } h.s.Attach(h.ui) t.Cleanup(func() { h.s.Close() }) return h } func (h *harness) post(v any) { b, _ := json.Marshal(v) h.s.Post(b) } func (h *harness) hello(t *testing.T) uint64 { h.post(map[string]any{"t": "hello", "v": ProtocolVersion, "nonce": "n"}) m := h.ui.next(t) if m["t"] != "ready" || m["nonce"] != "n" { t.Fatalf("ready: %v", m) } return uint64(m["gen"].(float64)) } func (h *harness) req(gen uint64, id, method, url, body string) { var b *string if body != "" { e := base64.StdEncoding.EncodeToString([]byte(body)) b = &e } h.post(map[string]any{"t": "req", "id": id, "gen": gen, "method": method, "url": url, "body": b}) } func body(t *testing.T, m map[string]any) string { b, err := base64.StdEncoding.DecodeString(m["body"].(string)) if err != nil { t.Fatal(err) } return string(b) } func TestRoundtripAndResponses(t *testing.T) { h := newHarness(t) g := h.hello(t) h.req(g, "1", "POST", "/rpc/add", `{"a":3,"b":4}`) m := h.ui.next(t) if m["t"] != "res" || m["id"] != "1" || m["status"].(float64) != 200 || body(t, m) != `{"result":7}` { t.Fatalf("%v", m) } cases := map[string]float64{"/rpc/nope": 404, "/rpc/panic": 500, "/assets/../x": 400, "/assets/a.wasm": 200, "assets:a.wasm": 200, "//evil/x": 400, "/assets/missing": 404} i := 10 for u, want := range cases { i++ h.req(g, fmt.Sprint(i), "GET", u, "") m := h.ui.next(t) if m["status"].(float64) != want { t.Errorf("%s: %v", u, m["status"]) } if u == "/assets/a.wasm" && m["headers"].(map[string]any)["content-type"] != "application/wasm" { t.Errorf("wasm mime: %v", m["headers"]) } } h.req(g, "h", "HEAD", "/assets/a.wasm", "") if m := h.ui.next(t); body(t, m) != "" || m["headers"].(map[string]any)["content-length"] != "8" { t.Errorf("HEAD: %v", m) } h.req(g, "m", "PUT", "/rpc/add", "") if m := h.ui.next(t); m["status"].(float64) != 405 { t.Errorf("405: %v", m) } } func TestProtocolVersionMismatch(t *testing.T) { h := newHarness(t) h.post(map[string]any{"t": "hello", "v": 99, "nonce": "x"}) m := h.ui.next(t) if m["t"] != "ready" || !strings.Contains(fmt.Sprint(m["error"]), "unsupported bridge protocol 99") { t.Fatalf("%v", m) } if h.s.Stats().Generation != 0 { t.Error("generation advanced on refused hello") } } func TestAbortReachesHandler(t *testing.T) { h := newHarness(t) g := h.hello(t) h.req(g, "1", "POST", "/rpc/block", "x") <-h.started h.post(map[string]any{"t": "abort", "id": "1", "gen": g}) if c := <-h.causes; !errors.Is(c, ErrAborted) { t.Fatalf("cause %v", c) } h.ui.none(t, 100*time.Millisecond) // the page already settled the call } func TestStaleGenerationCancelledAndDropped(t *testing.T) { h := newHarness(t) g1 := h.hello(t) h.req(g1, "1", "POST", "/rpc/block", "old") <-h.started g2 := h.hello(t) // reload if g2 != g1+1 { t.Fatalf("gen %d -> %d", g1, g2) } if c := <-h.causes; !errors.Is(c, ErrStale) { t.Fatalf("cause %v", c) } h.ui.none(t, 100*time.Millisecond) // A request still tagged with the old generation is dropped. h.req(g1, "2", "POST", "/rpc/add", `{"a":1,"b":1}`) h.ui.none(t, 100*time.Millisecond) if h.s.Stats().DroppedStale == 0 { t.Error("stale request not counted") } } func TestCloseCancelsAndBlocksDelivery(t *testing.T) { h := newHarness(t) g := h.hello(t) h.req(g, "1", "POST", "/rpc/block", "x") <-h.started if err := h.s.Close(); err != nil { t.Fatal(err) } if c := <-h.causes; !errors.Is(c, ErrClosed) { t.Fatalf("cause %v", c) } if err := h.s.Close(); err != nil { t.Fatal("second close", err) } h.req(g, "2", "POST", "/rpc/add", `{"a":1,"b":1}`) h.ui.none(t, 100*time.Millisecond) if st := h.s.Stats(); st.Pending != 0 || st.DroppedClosed == 0 { t.Errorf("%+v", st) } } func TestDuplicateIDAndBadMessages(t *testing.T) { h := newHarness(t) g := h.hello(t) h.req(g, "1", "POST", "/rpc/block", "x") <-h.started h.req(g, "1", "POST", "/rpc/add", `{}`) if m := h.ui.next(t); m["code"] != "protocol" { t.Fatalf("%v", m) } h.s.Post(json.RawMessage(`"string"`)) h.s.Post(json.RawMessage(`{"t":"bogus","id":"z","gen":1}`)) if m := h.ui.next(t); m["code"] != "protocol" { t.Fatalf("%v", m) } if h.s.Stats().ProtocolErrors < 3 { t.Errorf("%+v", h.s.Stats()) } } func TestHostTimeout(t *testing.T) { res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{})) r := NewRouter(res) r.Handle("GET", "/slow", func(ctx context.Context, _ *Request) (*Response, error) { <-ctx.Done(); return nil, ctx.Err() }) s := NewSession(r, Options{MaxTimeout: 50 * time.Millisecond}) ui := newFakeUI() s.Attach(ui) defer s.Close() s.Post(json.RawMessage(`{"t":"hello","v":1,"nonce":"n"}`)) ui.next(t) s.Post(json.RawMessage(`{"t":"req","id":"1","gen":1,"method":"GET","url":"/slow"}`)) if m := ui.next(t); m["t"] != "err" || m["code"] != "timeout" { t.Fatalf("%v", m) } } func TestParseLocalURL(t *testing.T) { p, q, err := ParseLocalURL("assets:img/a.png?x=1#f") if err != nil || p != "/assets/img/a.png" || q.Get("x") != "1" { t.Fatal(p, q, err) } if p, _, _ := ParseLocalURL("/assets/%252e"); p != "/assets/%2e" { t.Errorf("decoded more than once: %q", p) } for _, bad := range []string{"https://x/y", "//x/y", "rel/path", "/a%zz"} { if _, _, err := ParseLocalURL(bad); err == nil { t.Errorf("%q accepted", bad) } } } func TestInitScript(t *testing.T) { js := InitScript(PageConfig{Selftest: true}) if !strings.HasPrefix(js, `window.__yetano_config={"external":"reject"`) || !strings.Contains(js, "__yetano_post") { t.Fatal(js[:120]) } _ = http.StatusOK } func TestStreamChunksAndAbort(t *testing.T) { res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{})) r := NewRouter(res) causes := make(chan error, 1) r.Handle("GET", "/s", func(context.Context, *Request) (*Response, error) { return &Response{Status: 200, Stream: func(ctx context.Context, w io.Writer) error { for i := 0; ; i++ { if _, err := fmt.Fprintf(w, "c%d", i); err != nil { causes <- err return err } if i == 2 { // after three chunks wait for the page to abort <-ctx.Done() causes <- context.Cause(ctx) return ctx.Err() } } }}, nil }) r.Handle("GET", "/done", func(context.Context, *Request) (*Response, error) { return &Response{Status: 201, Stream: func(_ context.Context, w io.Writer) error { w.Write(make([]byte, 400<<10)) // split into 192 KiB chunks return nil }}, nil }) s := NewSession(r, Options{}) ui := newFakeUI() s.Attach(ui) defer s.Close() s.Post(json.RawMessage(`{"t":"hello","v":1,"nonce":"n"}`)) ui.next(t) s.Post(json.RawMessage(`{"t":"req","id":"1","gen":1,"method":"GET","url":"/s"}`)) if m := ui.next(t); m["t"] != "res" || m["stream"] != true { t.Fatalf("head: %v", m) } for i := 0; i < 3; i++ { if m := ui.next(t); m["t"] != "chunk" { t.Fatalf("chunk %d: %v", i, m) } } s.Post(json.RawMessage(`{"t":"abort","id":"1","gen":1}`)) if c := <-causes; !errors.Is(c, ErrAborted) { t.Fatalf("cause %v", c) } ui.none(t, 100*time.Millisecond) // page already ended the stream: no end/err s.Post(json.RawMessage(`{"t":"req","id":"2","gen":1,"method":"GET","url":"/done"}`)) if m := ui.next(t); m["status"].(float64) != 201 { t.Fatalf("%v", m) } total := 0 for { m := ui.next(t) if m["t"] == "end" { break } b, _ := base64.StdEncoding.DecodeString(m["data"].(string)) total += len(b) } if total != 400<<10 { t.Fatalf("streamed %d bytes", total) } }