| 1 | package render |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "os" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "testing" |
| 14 | "testing/iotest" |
| 15 | "time" |
| 16 | ) |
| 17 | |
| 18 | // Frames are NUL-ended, may arrive in any pieces, and one over the cap |
| 19 | // is refused however it arrives. |
| 20 | func TestReadFrame(t *testing.T) { |
| 21 | const max = 32 |
| 22 | for _, c := range []struct { |
| 23 | name string |
| 24 | input string |
| 25 | want []string |
| 26 | err error |
| 27 | }{ |
| 28 | {"one", "{\"id\":1}\x00", []string{`{"id":1}`}, io.EOF}, |
| 29 | {"two in one read", "a\x00b\x00", []string{"a", "b"}, io.EOF}, |
| 30 | {"empty frame", "\x00x\x00", []string{"", "x"}, io.EOF}, |
| 31 | {"exactly the cap", strings.Repeat("x", max) + "\x00", []string{strings.Repeat("x", max)}, io.EOF}, |
| 32 | {"one over the cap", strings.Repeat("x", max+1) + "\x00", nil, errFrameTooLarge}, |
| 33 | {"over the cap, no NUL", strings.Repeat("x", 10*max), nil, errFrameTooLarge}, |
| 34 | {"ends mid-frame", "a\x00bc", []string{"a"}, io.ErrUnexpectedEOF}, |
| 35 | } { |
| 36 | t.Run(c.name, func(t *testing.T) { |
| 37 | // A small buffer and one byte a read: every frame arrives |
| 38 | // in pieces and crosses the buffer's end. |
| 39 | r := bufio.NewReaderSize(iotest.OneByteReader(strings.NewReader(c.input)), 16) |
| 40 | var got []string |
| 41 | for { |
| 42 | msg, err := readFrame(r, max) |
| 43 | if err != nil { |
| 44 | if !errors.Is(err, c.err) { |
| 45 | t.Fatalf("err %v, want %v", err, c.err) |
| 46 | } |
| 47 | break |
| 48 | } |
| 49 | got = append(got, string(msg)) |
| 50 | } |
| 51 | if strings.Join(got, "|") != strings.Join(c.want, "|") { |
| 52 | t.Fatalf("frames %q, want %q", got, c.want) |
| 53 | } |
| 54 | }) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // peer is a fake browser on the far side of two pipes: it reads this |
| 59 | // side's calls and answers with whatever handle writes. |
| 60 | type peer struct { |
| 61 | t *testing.T |
| 62 | toBrowser *os.File // this side writes |
| 63 | fromPeer *os.File // this side reads |
| 64 | in *os.File // the peer reads |
| 65 | out *os.File // the peer writes |
| 66 | mu sync.Mutex |
| 67 | calls []peerCall |
| 68 | handle func(p *peer, c peerCall) |
| 69 | done chan struct{} |
| 70 | } |
| 71 | |
| 72 | type peerCall struct { |
| 73 | ID int64 `json:"id"` |
| 74 | Method string `json:"method"` |
| 75 | SessionID string `json:"sessionId"` |
| 76 | Params json.RawMessage `json:"params"` |
| 77 | } |
| 78 | |
| 79 | func newPeer(t *testing.T, handle func(p *peer, c peerCall)) *peer { |
| 80 | t.Helper() |
| 81 | in, toBrowser, err := os.Pipe() |
| 82 | if err != nil { |
| 83 | t.Fatal(err) |
| 84 | } |
| 85 | fromPeer, out, err := os.Pipe() |
| 86 | if err != nil { |
| 87 | t.Fatal(err) |
| 88 | } |
| 89 | p := &peer{t: t, toBrowser: toBrowser, fromPeer: fromPeer, in: in, out: out, handle: handle, done: make(chan struct{})} |
| 90 | go func() { |
| 91 | defer close(p.done) |
| 92 | r := bufio.NewReader(in) |
| 93 | for { |
| 94 | raw, err := readFrame(r, maxFrame) |
| 95 | if err != nil { |
| 96 | return |
| 97 | } |
| 98 | var c peerCall |
| 99 | if json.Unmarshal(raw, &c) != nil { |
| 100 | return |
| 101 | } |
| 102 | p.mu.Lock() |
| 103 | p.calls = append(p.calls, c) |
| 104 | p.mu.Unlock() |
| 105 | p.handle(p, c) |
| 106 | } |
| 107 | }() |
| 108 | t.Cleanup(func() { |
| 109 | toBrowser.Close() |
| 110 | fromPeer.Close() |
| 111 | in.Close() |
| 112 | out.Close() |
| 113 | <-p.done |
| 114 | }) |
| 115 | return p |
| 116 | } |
| 117 | |
| 118 | // send writes one raw frame, NUL added. |
| 119 | func (p *peer) send(raw string) { |
| 120 | p.out.Write(append([]byte(raw), 0)) |
| 121 | } |
| 122 | |
| 123 | func (p *peer) reply(c peerCall, result any) { |
| 124 | raw, _ := json.Marshal(map[string]any{"id": c.ID, "result": result}) |
| 125 | p.send(string(raw)) |
| 126 | } |
| 127 | |
| 128 | func (p *peer) event(session, method string, params any) { |
| 129 | m := map[string]any{"method": method, "params": params} |
| 130 | if session != "" { |
| 131 | m["sessionId"] = session |
| 132 | } |
| 133 | raw, _ := json.Marshal(m) |
| 134 | p.send(string(raw)) |
| 135 | } |
| 136 | |
| 137 | func (p *peer) methods() []string { |
| 138 | p.mu.Lock() |
| 139 | defer p.mu.Unlock() |
| 140 | var m []string |
| 141 | for _, c := range p.calls { |
| 142 | m = append(m, c.Method) |
| 143 | } |
| 144 | return m |
| 145 | } |
| 146 | |
| 147 | // Replies are matched to the call that asked, in any order; an error |
| 148 | // reply is the call's error; events between them reach the handler. |
| 149 | func TestConnMatchesReplies(t *testing.T) { |
| 150 | var pending []peerCall |
| 151 | var mu sync.Mutex |
| 152 | p := newPeer(t, func(p *peer, c peerCall) { |
| 153 | mu.Lock() |
| 154 | defer mu.Unlock() |
| 155 | pending = append(pending, c) |
| 156 | if len(pending) < 2 { |
| 157 | return |
| 158 | } |
| 159 | // Both calls are in: a reply to no call, an event, then the |
| 160 | // replies the other way round. |
| 161 | p.send(`{"id":999,"result":{}}`) |
| 162 | p.event("S", "Page.loadEventFired", map[string]any{"timestamp": 1}) |
| 163 | p.send(`{"id":` + itoa(pending[1].ID) + `,"error":{"code":-32000,"message":"no\u0007 such thing"}}`) |
| 164 | p.reply(pending[0], map[string]any{"value": "first"}) |
| 165 | }) |
| 166 | var events []string |
| 167 | var emu sync.Mutex |
| 168 | c := newConn(p.fromPeer, p.toBrowser, maxFrame, func(session, method string, _ json.RawMessage) { |
| 169 | emu.Lock() |
| 170 | events = append(events, session+" "+method) |
| 171 | emu.Unlock() |
| 172 | }) |
| 173 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 174 | defer cancel() |
| 175 | var wg sync.WaitGroup |
| 176 | var first struct { |
| 177 | Value string `json:"value"` |
| 178 | } |
| 179 | var errFirst, errSecond error |
| 180 | wg.Add(2) |
| 181 | go func() { defer wg.Done(); errFirst = c.call(ctx, "", "A.first", nil, &first) }() |
| 182 | time.Sleep(50 * time.Millisecond) |
| 183 | go func() { defer wg.Done(); errSecond = c.call(ctx, "S", "B.second", map[string]any{"x": 1}, nil) }() |
| 184 | wg.Wait() |
| 185 | if errFirst != nil || first.Value != "first" { |
| 186 | t.Fatalf("first: %v %+v", errFirst, first) |
| 187 | } |
| 188 | var ce *cdpError |
| 189 | if !errors.As(errSecond, &ce) || ce.Method != "B.second" || ce.Code != -32000 || ce.Message != "no such thing" { |
| 190 | t.Fatalf("second: %v", errSecond) |
| 191 | } |
| 192 | emu.Lock() |
| 193 | defer emu.Unlock() |
| 194 | if len(events) != 1 || events[0] != "S Page.loadEventFired" { |
| 195 | t.Fatalf("events %q", events) |
| 196 | } |
| 197 | if c.Err() != nil { |
| 198 | t.Fatalf("the connection ended: %v", c.Err()) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | // A browser that never answers, or never reads, does not hold a call |
| 203 | // past its deadline. |
| 204 | func TestConnCallHasADeadline(t *testing.T) { |
| 205 | t.Run("no reply", func(t *testing.T) { |
| 206 | p := newPeer(t, func(*peer, peerCall) {}) |
| 207 | c := newConn(p.fromPeer, p.toBrowser, maxFrame, nil) |
| 208 | ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) |
| 209 | defer cancel() |
| 210 | began := time.Now() |
| 211 | if err := c.call(ctx, "", "Never.answered", nil, nil); !errors.Is(err, context.DeadlineExceeded) { |
| 212 | t.Fatalf("err %v", err) |
| 213 | } |
| 214 | if time.Since(began) > 2*time.Second { |
| 215 | t.Fatal("the call outlived its deadline") |
| 216 | } |
| 217 | c.mu.Lock() |
| 218 | defer c.mu.Unlock() |
| 219 | if len(c.calls) != 0 { |
| 220 | t.Fatalf("%d calls still waiting", len(c.calls)) |
| 221 | } |
| 222 | }) |
| 223 | t.Run("never reads", func(t *testing.T) { |
| 224 | in, toBrowser, err := os.Pipe() |
| 225 | if err != nil { |
| 226 | t.Fatal(err) |
| 227 | } |
| 228 | defer in.Close() |
| 229 | defer toBrowser.Close() |
| 230 | from, out, err := os.Pipe() |
| 231 | if err != nil { |
| 232 | t.Fatal(err) |
| 233 | } |
| 234 | defer from.Close() |
| 235 | defer out.Close() |
| 236 | c := newConn(from, toBrowser, maxFrame, nil) |
| 237 | ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) |
| 238 | defer cancel() |
| 239 | // More than a pipe holds, to a browser that reads nothing. |
| 240 | big := strings.Repeat("x", 4<<20) |
| 241 | began := time.Now() |
| 242 | if err := c.call(ctx, "", "Big.call", map[string]any{"x": big}, nil); err == nil { |
| 243 | t.Fatal("the write finished") |
| 244 | } |
| 245 | if time.Since(began) > 2*time.Second { |
| 246 | t.Fatal("the write outlived its deadline") |
| 247 | } |
| 248 | if c.Err() == nil { |
| 249 | t.Fatal("a half-written message left the connection open") |
| 250 | } |
| 251 | }) |
| 252 | } |
| 253 | |
| 254 | // What the browser sends cannot grow without bound or confuse the |
| 255 | // client: an oversize frame or a frame that is not JSON ends the |
| 256 | // connection, and every waiting call fails with it. |
| 257 | func TestConnEndsOnABadFrame(t *testing.T) { |
| 258 | for _, c := range []struct { |
| 259 | name string |
| 260 | send func(p *peer) |
| 261 | want error |
| 262 | }{ |
| 263 | {"oversize", func(p *peer) { p.send(`{"id":1,"result":{"data":"` + strings.Repeat("A", 2048) + `"}}`) }, errFrameTooLarge}, |
| 264 | {"not JSON", func(p *peer) { p.send(`{"id":1,`) }, nil}, |
| 265 | {"pipe closed", func(p *peer) { p.out.Close() }, errConnClosed}, |
| 266 | } { |
| 267 | t.Run(c.name, func(t *testing.T) { |
| 268 | p := newPeer(t, func(p *peer, _ peerCall) { c.send(p) }) |
| 269 | conn := newConn(p.fromPeer, p.toBrowser, 1024, nil) |
| 270 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 271 | defer cancel() |
| 272 | err := conn.call(ctx, "", "Any.thing", nil, nil) |
| 273 | if err == nil || errors.Is(err, context.DeadlineExceeded) { |
| 274 | t.Fatalf("err %v", err) |
| 275 | } |
| 276 | if c.want != nil && !errors.Is(err, c.want) { |
| 277 | t.Fatalf("err %v, want %v", err, c.want) |
| 278 | } |
| 279 | if conn.Err() == nil { |
| 280 | t.Fatal("the connection is still open") |
| 281 | } |
| 282 | if err := conn.call(ctx, "", "After.end", nil, nil); err == nil { |
| 283 | t.Fatal("a call after the end was sent") |
| 284 | } |
| 285 | }) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | // A message this side sends is one JSON object and one NUL, with the |
| 290 | // session when there is one. |
| 291 | func TestConnWritesOneFramePerCall(t *testing.T) { |
| 292 | p := newPeer(t, func(p *peer, c peerCall) { p.reply(c, map[string]any{}) }) |
| 293 | c := newConn(p.fromPeer, p.toBrowser, maxFrame, nil) |
| 294 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 295 | defer cancel() |
| 296 | if err := c.call(ctx, "S1", "Page.navigate", map[string]any{"url": "http://127.0.0.1:1/"}, nil); err != nil { |
| 297 | t.Fatal(err) |
| 298 | } |
| 299 | if err := c.call(ctx, "", "Browser.getVersion", nil, nil); err != nil { |
| 300 | t.Fatal(err) |
| 301 | } |
| 302 | p.mu.Lock() |
| 303 | defer p.mu.Unlock() |
| 304 | if len(p.calls) != 2 || p.calls[0].SessionID != "S1" || p.calls[1].SessionID != "" || !bytes.Contains(p.calls[0].Params, []byte(`"url"`)) || p.calls[0].ID == p.calls[1].ID { |
| 305 | t.Fatalf("calls %+v", p.calls) |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | func itoa(n int64) string { |
| 310 | raw, _ := json.Marshal(n) |
| 311 | return string(raw) |
| 312 | } |
| 313 | |