forked from go-rod/rod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hijack_test.go
384 lines (283 loc) · 8.28 KB
/
hijack_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package rod_test
import (
"context"
"errors"
"io"
"mime"
"net/http"
"sync"
"testing"
"time"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/proto"
"github.com/go-rod/rod/lib/utils"
"github.com/ysmood/gson"
)
func TestHijack(t *testing.T) {
g := setup(t)
s := g.Serve()
// to simulate a backend server
s.Route("/", slash("fixtures/fetch.html"))
s.Mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
panic("wrong http method")
}
g.Eq("header", r.Header.Get("Test"))
b, err := io.ReadAll(r.Body)
g.E(err)
g.Eq("a", string(b))
g.HandleHTTP(".html", "test")(w, r)
})
s.Route("/b", "", "b")
router := g.page.HijackRequests()
defer router.MustStop()
router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {
r := ctx.Request.SetContext(g.Context())
r.Req().Header.Set("Test", "header") // override request header
r.SetBody([]byte("test")) // override request body
r.SetBody(123) // override request body
r.SetBody(r.Body()) // override request body
type MyState struct {
Val int
}
ctx.CustomState = &MyState{10}
g.Eq(http.MethodPost, r.Method())
g.Eq(s.URL("/a"), r.URL().String())
g.Eq(proto.NetworkResourceTypeXHR, ctx.Request.Type())
g.Is(ctx.Request.IsNavigation(), false)
g.Has(s.URL(), ctx.Request.Header("Origin"))
g.Len(ctx.Request.Headers(), 6)
g.True(ctx.Request.JSONBody().Nil())
// send request load response from real destination as the default value to hijack
ctx.MustLoadResponse()
g.Eq(200, ctx.Response.Payload().ResponseCode)
// override status code
ctx.Response.Payload().ResponseCode = http.StatusCreated
g.Eq("4", ctx.Response.Headers().Get("Content-Length"))
g.Has(ctx.Response.Headers().Get("Content-Type"), "text/html; charset=utf-8")
// override response header
ctx.Response.AddHeader("Set-Cookie", "key=val1")
// This should override the previous one
ctx.Response.SetHeader("Set-Cookie", "key=val")
// override response body
ctx.Response.SetBody([]byte("test"))
ctx.Response.SetBody("test")
ctx.Response.SetBody(map[string]string{
"text": "test",
})
g.Eq("{\"text\":\"test\"}", ctx.Response.Body())
})
router.MustAdd(s.URL("/b"), func(_ *rod.Hijack) {
panic("should not come to here")
})
router.MustRemove(s.URL("/b"))
router.MustAdd(s.URL("/b"), func(ctx *rod.Hijack) {
// transparent proxy
ctx.MustLoadResponse()
})
go router.Run()
g.page.MustNavigate(s.URL())
g.Eq("201 test key=val", g.page.MustElement("#a").MustText())
g.Eq("b", g.page.MustElement("#b").MustText())
}
func TestHijackContinue(t *testing.T) {
g := setup(t)
s := g.Serve().Route("/", ".html", `<body>ok</body>`)
router := g.page.HijackRequests()
defer router.MustStop()
wg := &sync.WaitGroup{}
wg.Add(1)
router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {
ctx.ContinueRequest(&proto.FetchContinueRequest{})
wg.Done()
})
go router.Run()
g.page.MustNavigate(s.URL("/a"))
g.Eq("ok", g.page.MustElement("body").MustText())
wg.Wait()
}
func TestHijackMockWholeResponseEmptyBody(t *testing.T) {
g := setup(t)
router := g.page.HijackRequests()
defer router.MustStop()
router.MustAdd("*", func(ctx *rod.Hijack) {
ctx.Response.SetBody("")
})
go router.Run()
// needs to timeout or will hang when "omitempty" does not get removed from body in fulfillRequest
timed := g.page.Timeout(time.Second)
timed.MustNavigate(g.Serve().Route("/", ".txt", "OK").URL())
g.Eq("", g.page.MustElement("body").MustText())
}
func TestHijackMockWholeResponseNoBody(t *testing.T) {
// TODO: remove the skip
t.Skip("Because of flaky test result")
g := setup(t)
router := g.page.HijackRequests()
defer router.MustStop()
// intercept and reply without setting a body
router.MustAdd("*", func(_ *rod.Hijack) {
// we don't set any body here
})
go router.Run()
// has to timeout as it will lock up the browser reading the reply.
err := g.page.Timeout(time.Second).Navigate(g.Serve().Route("/", "").URL())
g.Is(err, context.DeadlineExceeded)
}
func TestHijackMockWholeResponse(t *testing.T) {
g := setup(t)
router := g.page.HijackRequests()
defer router.MustStop()
router.MustAdd("*", func(ctx *rod.Hijack) {
ctx.Response.SetHeader("Content-Type", mime.TypeByExtension(".html"))
ctx.Response.SetBody("<body>ok</body>")
})
go router.Run()
g.page.MustNavigate("http://localhost")
g.Eq("ok", g.page.MustElement("body").MustText())
}
func TestHijackSkip(t *testing.T) {
g := setup(t)
s := g.Serve()
router := g.page.HijackRequests()
defer router.MustStop()
wg := &sync.WaitGroup{}
wg.Add(2)
router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {
ctx.Skip = true
wg.Done()
})
router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {
ctx.ContinueRequest(&proto.FetchContinueRequest{})
wg.Done()
})
go router.Run()
g.page.MustNavigate(s.URL("/a"))
wg.Wait()
}
func TestHijackOnErrorLog(t *testing.T) {
g := setup(t)
s := g.Serve().Route("/", ".html", `<body>ok</body>`)
router := g.page.HijackRequests()
defer router.MustStop()
wg := &sync.WaitGroup{}
wg.Add(1)
var err error
router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {
ctx.OnError = func(e error) {
err = e
wg.Done()
}
ctx.ContinueRequest(&proto.FetchContinueRequest{})
})
go router.Run()
g.mc.stub(1, proto.FetchContinueRequest{}, func(_ StubSend) (gson.JSON, error) {
return gson.New(nil), errors.New("err")
})
go func() {
_ = g.page.Context(g.Context()).Navigate(s.URL("/a"))
}()
wg.Wait()
g.Eq(err.Error(), "err")
}
func TestHijackFailRequest(t *testing.T) {
g := setup(t)
s := g.Serve().Route("/page", ".html", `<html>
<body></body>
<script>
fetch('/a').catch(async (err) => {
document.title = err.message
})
</script></html>`)
router := g.browser.HijackRequests()
defer router.MustStop()
router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {
ctx.Response.Fail(proto.NetworkErrorReasonAborted)
})
go router.Run()
g.page.MustNavigate(s.URL("/page")).MustWaitLoad()
g.page.MustWait(`() => document.title === 'Failed to fetch'`)
{ // test error log
g.mc.stub(1, proto.FetchFailRequest{}, func(send StubSend) (gson.JSON, error) {
_, _ = send()
return gson.JSON{}, errors.New("err")
})
_ = g.page.Navigate(s.URL("/a"))
}
}
func TestHijackLoadResponseErr(t *testing.T) {
g := setup(t)
p := g.newPage().Context(g.Context())
router := p.HijackRequests()
defer router.MustStop()
wg := &sync.WaitGroup{}
wg.Add(1)
router.MustAdd("http://localhost/a", func(ctx *rod.Hijack) {
g.Err(ctx.LoadResponse(&http.Client{
Transport: &MockRoundTripper{err: errors.New("err")},
}, true))
g.Err(ctx.LoadResponse(&http.Client{
Transport: &MockRoundTripper{res: &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(&MockReader{err: errors.New("err")}),
}},
}, true))
wg.Done()
ctx.Response.Fail(proto.NetworkErrorReasonAborted)
})
go router.Run()
_ = p.Navigate("http://localhost/a")
wg.Wait()
}
func TestHijackResponseErr(t *testing.T) {
g := setup(t)
s := g.Serve().Route("/", ".html", `ok`)
p := g.newPage().Context(g.Context())
router := p.HijackRequests()
defer router.MustStop()
wg := &sync.WaitGroup{}
wg.Add(1)
router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) { // to ignore favicon
ctx.OnError = func(err error) {
g.Err(err)
wg.Done()
}
ctx.MustLoadResponse()
g.mc.stub(1, proto.FetchFulfillRequest{}, func(send StubSend) (gson.JSON, error) {
res, _ := send()
return res, errors.New("err")
})
})
go router.Run()
p.MustNavigate(s.URL("/a"))
wg.Wait()
}
func TestHandleAuth(t *testing.T) {
g := setup(t)
s := g.Serve()
// mock the server
s.Mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {
u, p, ok := r.BasicAuth()
if !ok {
w.Header().Add("WWW-Authenticate", `Basic realm="web"`)
w.WriteHeader(http.StatusUnauthorized)
return
}
g.Eq("a", u)
g.Eq("b", p)
g.HandleHTTP(".html", `<p>ok</p>`)(w, r)
})
s.Route("/err", ".html", "err page")
go g.browser.MustHandleAuth("a", "b")()
page := g.newPage(s.URL("/a"))
page.MustElementR("p", "ok")
wait := g.browser.HandleAuth("a", "b")
var page2 *rod.Page
wait2 := utils.All(func() {
page2, _ = g.browser.Page(proto.TargetCreateTarget{URL: s.URL("/err")})
})
g.mc.stubErr(1, proto.FetchContinueRequest{})
g.Err(wait())
wait2()
page2.MustClose()
}