-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathproxy_test.go
2561 lines (2157 loc) · 63.7 KB
/
proxy_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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package proxy
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"net/http/fcgi"
"net/http/httptest"
"net/url"
"os"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
log "github.com/sirupsen/logrus"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zalando/skipper/eskip"
"github.com/zalando/skipper/filters"
"github.com/zalando/skipper/filters/builtin"
"github.com/zalando/skipper/loadbalancer"
"github.com/zalando/skipper/logging"
"github.com/zalando/skipper/logging/loggingtest"
"github.com/zalando/skipper/routing"
"github.com/zalando/skipper/routing/testdataclient"
teePredicate "github.com/zalando/skipper/predicates/tee"
)
const (
streamingDelay time.Duration = 30 * time.Millisecond
sourcePollTimeout time.Duration = 6 * time.Millisecond
)
type requestCheck func(*http.Request)
type priorityRoute struct {
route *routing.Route
params map[string]string
match func(r *http.Request) bool
}
type (
preserveOriginalSpec struct{}
preserveOriginalFilter struct{}
)
type syncResponseWriter struct {
mu sync.Mutex
statusCode int
header http.Header
body *bytes.Buffer
}
type testProxy struct {
log *loggingtest.Logger
dc *testdataclient.Client
routing *routing.Routing
proxy *Proxy
}
type listener struct {
inner net.Listener
lastConn chan net.Conn
}
type testLog struct {
mu sync.Mutex
buf bytes.Buffer
oldOut io.Writer
oldLevel log.Level
}
func NewTestLog() *testLog {
oldOut := log.StandardLogger().Out
oldLevel := log.GetLevel()
log.SetLevel(log.DebugLevel)
tl := &testLog{oldOut: oldOut, oldLevel: oldLevel}
log.SetOutput(tl)
return tl
}
func (l *testLog) Write(p []byte) (int, error) {
l.mu.Lock()
defer l.mu.Unlock()
return l.buf.Write(p)
}
func (l *testLog) String() string {
l.mu.Lock()
defer l.mu.Unlock()
return l.buf.String()
}
func (l *testLog) Reset() {
l.mu.Lock()
defer l.mu.Unlock()
l.buf.Reset()
}
func (l *testLog) Close() {
log.SetOutput(l.oldOut)
log.SetLevel(l.oldLevel)
}
func (l *testLog) WaitForN(exp string, n int, to time.Duration) error {
timeout := time.After(to)
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-timeout:
return fmt.Errorf("timeout waiting for log entry: %s", exp)
case <-ticker.C:
if l.Count(exp) >= n {
return nil
}
}
}
}
func (l *testLog) WaitFor(exp string, to time.Duration) error {
return l.WaitForN(exp, 1, to)
}
func (l *testLog) Count(exp string) int {
return strings.Count(l.String(), exp)
}
func (cors *preserveOriginalSpec) Name() string { return "preserveOriginal" }
func (cors *preserveOriginalSpec) CreateFilter(_ []interface{}) (filters.Filter, error) {
return &preserveOriginalFilter{}, nil
}
func preserveHeader(from, to http.Header) {
for key, vals := range from {
to[key+"-Preserved"] = vals
}
}
func (corf *preserveOriginalFilter) Request(ctx filters.FilterContext) {
preserveHeader(ctx.OriginalRequest().Header, ctx.Request().Header)
}
func (corf *preserveOriginalFilter) Response(ctx filters.FilterContext) {
preserveHeader(ctx.OriginalResponse().Header, ctx.Response().Header)
}
func (prt *priorityRoute) Match(r *http.Request) (*routing.Route, map[string]string) {
if prt.match(r) {
return prt.route, prt.params
}
return nil, nil
}
func newSyncResponseWriter() *syncResponseWriter {
return &syncResponseWriter{header: make(http.Header), body: bytes.NewBuffer(nil)}
}
func (srw *syncResponseWriter) Header() http.Header {
return srw.header
}
func (srw *syncResponseWriter) WriteHeader(statusCode int) {
srw.statusCode = statusCode
}
func (srw *syncResponseWriter) Write(b []byte) (int, error) {
srw.mu.Lock()
defer srw.mu.Unlock()
return srw.body.Write(b)
}
func (srw *syncResponseWriter) Read(b []byte) (int, error) {
srw.mu.Lock()
defer srw.mu.Unlock()
return srw.body.Read(b)
}
func (srw *syncResponseWriter) Flush() {}
func (srw *syncResponseWriter) Len() int {
srw.mu.Lock()
defer srw.mu.Unlock()
return srw.body.Len()
}
func newTestProxyWithFiltersAndParams(fr filters.Registry, doc string, params Params, preprocs []routing.PreProcessor) (*testProxy, error) {
dc, err := testdataclient.NewDoc(doc)
if err != nil {
return nil, err
}
if fr == nil {
fr = builtin.MakeRegistry()
}
tl := loggingtest.New()
if params.EndpointRegistry == nil {
params.EndpointRegistry = routing.NewEndpointRegistry(routing.RegistryOptions{})
}
opts := routing.Options{
FilterRegistry: fr,
PollTimeout: sourcePollTimeout,
DataClients: []routing.DataClient{dc},
PostProcessors: []routing.PostProcessor{loadbalancer.NewAlgorithmProvider(), params.EndpointRegistry},
Log: tl,
Predicates: []routing.PredicateSpec{teePredicate.New()},
}
if len(preprocs) > 0 {
opts.PreProcessors = preprocs
}
rt := routing.New(opts)
params.Routing = rt
p := WithParams(params)
p.log = tl
if err := tl.WaitFor("route settings applied", time.Second); err != nil {
return nil, err
}
return &testProxy{tl, dc, rt, p}, nil
}
func newTestProxyWithFilters(fr filters.Registry, doc string, flags Flags, pr ...PriorityRoute) (*testProxy, error) {
return newTestProxyWithFiltersAndParams(fr, doc, Params{Flags: flags, PriorityRoutes: pr}, nil)
}
func newTestProxyWithFiltersAndPreProcessors(fr filters.Registry, doc string, flags Flags, preprocs []routing.PreProcessor) (*testProxy, error) {
return newTestProxyWithFiltersAndParams(fr, doc, Params{Flags: flags}, preprocs)
}
func newTestProxyWithParams(doc string, params Params) (*testProxy, error) {
return newTestProxyWithFiltersAndParams(nil, doc, params, nil)
}
func newTestProxy(doc string, flags Flags, pr ...PriorityRoute) (*testProxy, error) {
return newTestProxyWithFiltersAndParams(nil, doc, Params{Flags: flags, PriorityRoutes: pr}, nil)
}
func (tp *testProxy) close() {
tp.log.Close()
tp.dc.Close()
tp.routing.Close()
tp.proxy.Close()
}
func hasArg(arg string) bool {
for _, a := range os.Args {
if a == arg {
return true
}
}
return false
}
func voidCheck(*http.Request) {}
func writeParts(w io.Writer, parts int, data []byte) {
partSize := len(data) / parts
i := 0
for ; i+partSize <= len(data); i += partSize {
w.Write(data[i : i+partSize])
time.Sleep(streamingDelay)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
w.Write(data[i:])
}
func startTestServer(payload []byte, parts int, check requestCheck) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
check(r)
w.Header().Set("X-Test-Response-Header", "response header value")
if len(payload) <= 0 {
return
}
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Content-Length", strconv.Itoa(len(payload)))
w.WriteHeader(http.StatusOK)
if parts > 0 {
writeParts(w, parts, payload)
return
}
w.Write(payload)
}))
}
func (l *listener) Accept() (c net.Conn, err error) {
c, err = l.inner.Accept()
if err != nil {
return
}
select {
case <-l.lastConn:
default:
}
l.lastConn <- c
return
}
func (l *listener) Close() error {
return l.inner.Close()
}
func (l *listener) Addr() net.Addr {
return l.inner.Addr()
}
func TestGetRoundtrip(t *testing.T) {
payload := []byte("Hello World!")
s := startTestServer(payload, 0, func(r *http.Request) {
if r.Method != "GET" {
t.Error("wrong request method")
}
if th, ok := r.Header["X-Test-Header"]; !ok || th[0] != "test value" {
t.Error("wrong request header")
}
})
defer s.Close()
u, _ := url.ParseRequestURI("https://www.example.org/hello")
r := &http.Request{
URL: u,
Method: "GET",
Header: http.Header{"X-Test-Header": []string{"test value"}}}
w := httptest.NewRecorder()
doc := fmt.Sprintf(`hello: Path("/hello") -> "%s"`, s.URL)
tp, err := newTestProxy(doc, FlagsNone)
if err != nil {
t.Error()
return
}
defer tp.close()
tp.proxy.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Error("wrong status", w.Code)
}
if ct, ok := w.Header()["Content-Type"]; !ok || ct[0] != "text/plain" {
t.Errorf("wrong content type. Expected 'text/plain' but got '%s'", w.Header().Get("Content-Type"))
}
if cl, ok := w.Header()["Content-Length"]; !ok || cl[0] != strconv.Itoa(len(payload)) {
t.Error("wrong content length")
}
if xpb, ok := w.Header()["Server"]; !ok || xpb[0] != "Skipper" {
t.Error("Wrong Server header value")
}
if !bytes.Equal(w.Body.Bytes(), payload) {
t.Error("wrong content", w.Body.String())
}
}
func TestRetries(t *testing.T) {
for _, tt := range []struct {
name string
method string
body func() io.Reader
want []int
}{
{
name: "GET request with nil body",
method: "GET",
body: func() io.Reader { return nil },
want: []int{200, 200},
},
{
name: "GET request with http.NoBody",
method: "GET",
body: func() io.Reader { return http.NoBody },
want: []int{200, 200},
},
{
name: "POST request without body",
method: "POST",
body: func() io.Reader { return nil },
want: []int{200, 200},
},
{
name: "POST request with body",
method: "POST",
body: func() io.Reader { return strings.NewReader("hello") },
want: []int{200, 502},
},
} {
t.Run(tt.name, func(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "backend reply")
}))
defer backend.Close()
unavailableBackend := "http://127.0.0.5:9" // refuses connections
doc := fmt.Sprintf(`hello: * -> <roundRobin, "%s", "%s">`, unavailableBackend, backend.URL)
tp, err := newTestProxy(doc, FlagsNone)
require.NoError(t, err)
ps := httptest.NewServer(tp.proxy)
defer func() {
ps.Close()
tp.close()
}()
// To avoid guessing which endpoint round robin picks first,
// make two requests and compare response codes ignoring request order
var codes []int
for i := 0; i < 2; i++ {
req, err := http.NewRequest(tt.method, ps.URL, tt.body())
require.NoError(t, err)
rsp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
rsp.Body.Close()
codes = append(codes, rsp.StatusCode)
}
assert.ElementsMatch(t, tt.want, codes)
})
}
}
func TestSetRequestUrlFromRequest(t *testing.T) {
for _, ti := range []struct {
msg string
originalURL *url.URL
expectedURL *url.URL
req *http.Request
}{{
"Scheme and Host are set when empty",
&url.URL{Scheme: "", Host: ""},
&url.URL{Scheme: "http", Host: "example.com"},
&http.Request{TLS: nil, Host: "example.com"},
}, {
"Scheme and Host are not modified when already set",
&url.URL{Scheme: "http", Host: "example.com"},
&url.URL{Scheme: "http", Host: "example.com"},
&http.Request{TLS: &tls.ConnectionState{}, Host: "example2.com"},
}, {
"Scheme is set to http when TLS not set",
&url.URL{Scheme: ""},
&url.URL{Scheme: "http"},
&http.Request{TLS: nil},
}, {
"Scheme is set to https when TLS is set",
&url.URL{Scheme: ""},
&url.URL{Scheme: "https"},
&http.Request{TLS: &tls.ConnectionState{}},
}} {
u, _ := url.Parse(ti.originalURL.String())
setRequestURLFromRequest(u, ti.req)
beq := reflect.DeepEqual(ti.expectedURL, u)
if !beq {
t.Error(ti.msg, "<urls don't match>", ti.expectedURL, u)
}
}
}
func TestSetRequestUrlForDynamicBackend(t *testing.T) {
for _, ti := range []struct {
msg string
expectedUrl *url.URL
stateBag map[string]interface{}
}{{
"DynamicBackendURLKey is set",
&url.URL{Scheme: "https", Host: "example.com"},
map[string]interface{}{filters.DynamicBackendURLKey: "https://example.com"},
}, {
"DynamicBackendURLKey is set with not url",
&url.URL{},
map[string]interface{}{filters.DynamicBackendURLKey: "some string"},
}, {
"DynamicBackendHostKey is set",
&url.URL{Host: "example.com"},
map[string]interface{}{filters.DynamicBackendHostKey: "example.com"},
}, {
"DynamicBackendSchemeKey is set",
&url.URL{Scheme: "http"},
map[string]interface{}{filters.DynamicBackendSchemeKey: "http"},
}, {
"All keys are set, DynamicBackendURLKey has priority",
&url.URL{Scheme: "https", Host: "priority.com"},
map[string]interface{}{
filters.DynamicBackendSchemeKey: "http",
filters.DynamicBackendHostKey: "example.com",
filters.DynamicBackendURLKey: "https://priority.com"},
}} {
u := &url.URL{}
setRequestURLForDynamicBackend(u, ti.stateBag)
beq := reflect.DeepEqual(ti.expectedUrl, u)
if !beq {
t.Error(ti.msg, "<urls don't match>", ti.expectedUrl, u)
}
}
}
func TestGetRoundtripForDynamicBackend(t *testing.T) {
payload := []byte("Hello World!")
s := startTestServer(payload, 0, func(r *http.Request) {
if th, ok := r.Header["X-Test-Header"]; !ok || th[0] != "test value" {
t.Error("wrong request header")
}
})
defer s.Close()
fr := make(filters.Registry)
fr.Register(builtin.NewSetDynamicBackendHost())
fr.Register(builtin.NewSetDynamicBackendScheme())
fr.Register(builtin.NewSetDynamicBackendUrl())
w := httptest.NewRecorder()
bu, _ := url.ParseRequestURI(s.URL)
doc := fmt.Sprintf(
`dynamic: Method("GET") -> setDynamicBackendScheme(%q) ->setDynamicBackendHost(%q) -> <dynamic>;`+
`dynamic2: Method("POST") -> setDynamicBackendUrl(%q) -> <dynamic>;`+
`dynamic3: Path("/defaults") -> <dynamic>;`, bu.Scheme, bu.Host, s.URL)
tp, err := newTestProxyWithFilters(fr, doc, FlagsNone)
if err != nil {
t.Error(err)
return
}
defer tp.close()
u1, _ := url.ParseRequestURI("https://example1.com")
r1 := &http.Request{
URL: u1,
Method: "GET",
Header: http.Header{"X-Test-Header": []string{"test value"}}}
tp.proxy.ServeHTTP(w, r1)
if w.Code != http.StatusOK {
t.Error("wrong status", w.Code)
}
u2, _ := url.ParseRequestURI("https://example2.com")
r2 := &http.Request{
URL: u2,
Method: "POST",
Header: http.Header{"X-Test-Header": []string{"test value"}}}
tp.proxy.ServeHTTP(w, r2)
if w.Code != http.StatusOK {
t.Error("wrong status", w.Code)
}
u3 := &url.URL{Path: "/defaults"}
r3 := &http.Request{
URL: u3,
Method: "HEAD",
Host: bu.Host,
Header: http.Header{"X-Test-Header": []string{"test value"}},
}
tp.proxy.ServeHTTP(w, r3)
if w.Code != http.StatusOK {
t.Error("wrong status", w.Code)
}
}
func TestPostRoundtrip(t *testing.T) {
s := startTestServer(nil, 0, func(r *http.Request) {
if r.Method != "POST" {
t.Error("wrong request method", r.Method)
}
if th, ok := r.Header["X-Test-Header"]; !ok || th[0] != "test value" {
t.Error("wrong request header")
}
})
defer s.Close()
u, _ := url.ParseRequestURI("https://www.example.org/hello")
r := &http.Request{
URL: u,
Method: "POST",
Header: http.Header{"X-Test-Header": []string{"test value"}}}
w := httptest.NewRecorder()
doc := fmt.Sprintf(`hello: Path("/hello") -> "%s"`, s.URL)
tp, err := newTestProxy(doc, FlagsNone)
if err != nil {
t.Error(err)
return
}
defer tp.close()
tp.proxy.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Error("wrong status", w.Code)
}
if w.Body.Len() != 0 {
t.Error("wrong content", w.Body.String())
}
}
func TestRoute(t *testing.T) {
payload1 := []byte("host one")
s1 := startTestServer(payload1, 0, voidCheck)
defer s1.Close()
payload2 := []byte("host two")
s2 := startTestServer(payload2, 0, voidCheck)
defer s2.Close()
doc := fmt.Sprintf(`
route1: Path("/host-one/*any") -> "%s";
route2: Path("/host-two/*any") -> "%s"
`, s1.URL, s2.URL)
tp, err := newTestProxy(doc, FlagsNone)
if err != nil {
t.Error(err)
return
}
defer tp.close()
var (
r *http.Request
w *httptest.ResponseRecorder
u *url.URL
)
u, _ = url.ParseRequestURI("https://www.example.org/host-one/some/path")
r = &http.Request{
URL: u,
Method: "GET"}
w = httptest.NewRecorder()
tp.proxy.ServeHTTP(w, r)
if w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), payload1) {
t.Error("wrong routing 1")
}
u, _ = url.ParseRequestURI("https://www.example.org/host-two/some/path")
r = &http.Request{
URL: u,
Method: "GET"}
w = httptest.NewRecorder()
tp.proxy.ServeHTTP(w, r)
if w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), payload2) {
t.Error("wrong routing 2")
}
}
func TestFastCgi(t *testing.T) {
testTables := []struct {
path string
payload []byte
requestURI string
httpRetCode int
}{
{"/hello", []byte("Hello, World!"), "https://www.example.org/hello", http.StatusOK},
{"/world", []byte("404 page not found\n"), "https://www.example.org/world/test.php", http.StatusNotFound},
}
for _, table := range testTables {
payload := table.payload
http.HandleFunc(table.path, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Test-Response-Header", "response header value")
if len(payload) <= 0 {
return
}
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Content-Length", strconv.Itoa(len(payload)))
w.WriteHeader(http.StatusOK)
w.Write(payload)
})
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
defer l.Close()
go fcgi.Serve(l, nil)
doc := fmt.Sprintf(`fastcgi: * -> "%s"`, "fastcgi://"+l.Addr().String())
tp, err := newTestProxy(doc, FlagsNone)
if err != nil {
t.Error(err)
return
}
defer tp.close()
var (
r *http.Request
w *httptest.ResponseRecorder
u *url.URL
)
u, _ = url.ParseRequestURI(table.requestURI)
r = &http.Request{
URL: u,
Method: "GET"}
w = httptest.NewRecorder()
tp.proxy.ServeHTTP(w, r)
if w.Code != table.httpRetCode || !bytes.Equal(w.Body.Bytes(), table.payload) {
t.Errorf("wrong routing for %s, body got:%s want:%s", table.requestURI, w.Body.Bytes(), table.payload)
t.Errorf("wrong routing for %s, status got: %d, want: %d.", table.requestURI, w.Code, table.httpRetCode)
}
}
}
func TestFastCgiServiceUnavailable(t *testing.T) {
tp, err := newTestProxy(`fastcgi: * -> "fastcgi://invalid.test"`, FlagsNone)
if err != nil {
t.Fatal(err)
}
defer tp.close()
ps := httptest.NewServer(tp.proxy)
defer ps.Close()
rsp, err := http.Get(ps.URL)
if err != nil {
t.Fatal(err)
}
defer rsp.Body.Close()
if rsp.StatusCode != http.StatusBadGateway {
t.Fatalf("expected 502, got: %v", rsp)
}
}
// This test is sensitive for timing, and occasionally fails.
// To run this test, set `-args stream` for the test command.
func TestStreaming(t *testing.T) {
if !hasArg("stream") {
t.Skip()
}
const expectedParts = 3
payload := []byte("some data to stream")
s := startTestServer(payload, expectedParts, voidCheck)
defer s.Close()
doc := fmt.Sprintf(`hello: Path("/hello") -> "%s"`, s.URL)
tp, err := newTestProxy(doc, FlagsNone)
if err != nil {
t.Error(err)
return
}
defer tp.close()
u, _ := url.ParseRequestURI("https://www.example.org/hello")
r := &http.Request{
URL: u,
Method: "GET"}
w := newSyncResponseWriter()
parts := 0
total := 0
done := make(chan int)
go tp.proxy.ServeHTTP(w, r)
go func() {
readPayload := make([]byte, len(payload))
for {
n, err := w.Read(readPayload)
if err != nil && err != io.EOF {
close(done)
return
}
if n == 0 {
time.Sleep(streamingDelay)
continue
}
readPayload = readPayload[n:]
parts++
total += n
if len(readPayload) == 0 {
close(done)
return
}
}
}()
select {
case <-done:
if parts < expectedParts {
t.Error("streaming failed", parts)
}
case <-time.After(150 * time.Millisecond):
t.Error("streaming timeout")
}
}
func TestAppliesFilters(t *testing.T) {
payload := []byte("Hello World!")
s := startTestServer(payload, 0, func(r *http.Request) {
if h, ok := r.Header["X-Test-Request-Header"]; !ok ||
h[0] != "request header value" {
t.Error("request header is missing")
}
})
defer s.Close()
u, _ := url.ParseRequestURI("https://www.example.org/hello")
r := &http.Request{
URL: u,
Method: "GET",
Header: http.Header{"X-Test-Header": []string{"test value"}}}
w := httptest.NewRecorder()
fr := make(filters.Registry)
fr.Register(builtin.NewAppendRequestHeader())
fr.Register(builtin.NewAppendResponseHeader())
doc := fmt.Sprintf(`hello: Path("/hello")
-> appendRequestHeader("X-Test-Request-Header", "request header value")
-> appendResponseHeader("X-Test-Response-Header", "response header value")
-> "%s"
`, s.URL)
tp, err := newTestProxyWithFilters(fr, doc, FlagsNone)
if err != nil {
t.Error(err)
return
}
defer tp.close()
tp.proxy.ServeHTTP(w, r)
if h, ok := w.Header()["X-Test-Response-Header"]; !ok || h[0] != "response header value" {
t.Error("missing response header")
}
}
func TestAppliesFiltersAndDefaultFilters(t *testing.T) {
payload := []byte("Hello World!")
s := startTestServer(payload, 0, func(r *http.Request) {
if h, ok := r.Header["X-Test-Request-Header"]; !ok ||
h[0] != "request header value" {
t.Error("request header is missing")
}
})
defer s.Close()
u, _ := url.ParseRequestURI("https://www.example.org/hello")
r := &http.Request{
URL: u,
Method: "GET",
Header: http.Header{"X-Test-Header": []string{"test value"}}}
w := httptest.NewRecorder()
fr := make(filters.Registry)
fr.Register(builtin.NewDropQuery())
fr.Register(builtin.NewAppendRequestHeader())
fr.Register(builtin.NewAppendResponseHeader())
doc := fmt.Sprintf(`hello: Path("/hello")
-> dropQuery("f00")
-> "%s"
`, s.URL)
appendFilter, err := eskip.ParseFilters(`appendResponseHeader("X-Test-Response-Header", "response header value")`)
if err != nil {
t.Errorf("Failed to parse append filter: %v", err)
}
prependFilter, err := eskip.ParseFilters(`appendRequestHeader("X-Test-Request-Header", "request header value")`)
if err != nil {
t.Errorf("Failed to parse prepend filter: %v", err)
}
tp, err := newTestProxyWithFiltersAndPreProcessors(fr, doc, FlagsNone, []routing.PreProcessor{
&eskip.DefaultFilters{
Append: appendFilter,
Prepend: prependFilter,
},
})
if err != nil {
t.Error(err)
return
}
defer tp.close()
tp.proxy.ServeHTTP(w, r)
if h, ok := w.Header()["X-Test-Response-Header"]; !ok || h[0] != "response header value" {
t.Error("missing response header")
}
}
type shunter struct {
resp *http.Response
}
func (b *shunter) Request(c filters.FilterContext) { c.Serve(b.resp) }
func (*shunter) Response(filters.FilterContext) {}
func (b *shunter) CreateFilter(fc []interface{}) (filters.Filter, error) { return b, nil }
func (*shunter) Name() string { return "shunter" }
func TestBreakFilterChain(t *testing.T) {
s := startTestServer([]byte("Hello World!"), 0, func(r *http.Request) {
t.Error("This should never be called")
})
defer s.Close()
fr := make(filters.Registry)
fr.Register(builtin.NewAppendRequestHeader())
resp1 := &http.Response{
Header: make(http.Header),
Body: io.NopCloser(new(bytes.Buffer)),
StatusCode: http.StatusUnauthorized,
Status: "Impossible body",
}
fr.Register(&shunter{resp1})
fr.Register(builtin.NewAppendResponseHeader())
doc := fmt.Sprintf(`breakerDemo:
Path("/shunter") ->
appendRequestHeader("X-Expected", "request header") ->
appendResponseHeader("X-Expected", "response header") ->
shunter() ->
appendRequestHeader("X-Unexpected", "foo") ->
appendResponseHeader("X-Unexpected", "bar") ->
"%s"`, s.URL)
tp, err := newTestProxyWithFilters(fr, doc, FlagsNone)
if err != nil {
t.Error(err)
return
}
defer tp.close()
r, _ := http.NewRequest("GET", "https://www.example.org/shunter", nil)
w := httptest.NewRecorder()
tp.proxy.ServeHTTP(w, r)
if _, has := r.Header["X-Expected"]; !has {
t.Error("Request is missing the expected header (added during filter chain winding)")
}
if _, has := w.Header()["X-Expected"]; !has {
t.Error("Response is missing the expected header (added during filter chain unwinding)")
}
if _, has := r.Header["X-Unexpected"]; has {