forked from linkerd/linkerd2-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransparency.rs
More file actions
1421 lines (1176 loc) · 47.4 KB
/
transparency.rs
File metadata and controls
1421 lines (1176 loc) · 47.4 KB
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
#![deny(warnings, rust_2018_idioms)]
#![type_length_limit = "16289823"]
#![recursion_limit = "256"]
use linkerd2_app_integration::*;
use std::error::Error as _;
use tokio::sync::mpsc;
use tokio::time::timeout;
#[tokio::test]
async fn outbound_http1() {
let _trace = trace_init();
let srv = server::http1().route("/", "hello h1").run().await;
let ctrl = controller::new();
ctrl.profile_tx_default("transparency.test.svc.cluster.local");
ctrl.destination_tx("transparency.test.svc.cluster.local")
.send_addr(srv.addr);
let proxy = proxy::new()
.controller(ctrl.run().await)
.outbound(srv)
.run()
.await;
let client = client::http1(proxy.outbound, "transparency.test.svc.cluster.local");
assert_eq!(client.get("/").await, "hello h1");
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn inbound_http1() {
let _trace = trace_init();
let srv = server::http1().route("/", "hello h1").run().await;
let ctrl = controller::new();
ctrl.profile_tx_default("transparency.test.svc.cluster.local");
let proxy = proxy::new()
.controller(ctrl.run().await)
.inbound_fuzz_addr(srv)
.run()
.await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
assert_eq!(client.get("/").await, "hello h1");
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn outbound_tcp() {
let _trace = trace_init();
let msg1 = "custom tcp hello";
let msg2 = "custom tcp bye";
let srv = server::tcp()
.accept(move |read| {
assert_eq!(read, msg1.as_bytes());
msg2
})
.run()
.await;
let proxy = proxy::new().outbound(srv).run().await;
let client = client::tcp(proxy.outbound);
let tcp_client = client.connect().await;
tcp_client.write(msg1).await;
assert_eq!(tcp_client.read().await, msg2.as_bytes());
// TCP client must close first
tcp_client.shutdown().await;
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn inbound_tcp() {
let _trace = trace_init();
let msg1 = "custom tcp hello";
let msg2 = "custom tcp bye";
let srv = server::tcp()
.accept(move |read| {
assert_eq!(read, msg1.as_bytes());
msg2
})
.run()
.await;
let proxy = proxy::new().inbound_fuzz_addr(srv).run().await;
let client = client::tcp(proxy.inbound);
let tcp_client = client.connect().await;
tcp_client.write(msg1).await;
assert_eq!(tcp_client.read().await, msg2.as_bytes());
// TCP client must close first
tcp_client.shutdown().await;
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
#[cfg_attr(not(feature = "flaky_tests"), ignore)]
async fn loop_outbound_http1() {
let _trace = trace_init();
let listen_addr = SocketAddr::from(([127, 0, 0, 1], 10751));
let mut env = TestEnv::new();
env.put(app::env::ENV_OUTBOUND_LISTEN_ADDR, listen_addr.to_string());
let _proxy = proxy::new()
.outbound_ip(listen_addr)
.run_with_test_env_and_keep_ports(env);
let client = client::http1(listen_addr, "some.invalid.example.com");
let rsp = client
.request(client.request_builder("/").method("GET"))
.await
.unwrap();
assert_eq!(rsp.status(), http::StatusCode::BAD_GATEWAY);
}
#[tokio::test]
#[cfg_attr(not(feature = "flaky_tests"), ignore)]
async fn loop_inbound_http1() {
let _trace = trace_init();
let listen_addr = SocketAddr::from(([127, 0, 0, 1], 10752));
let mut env = TestEnv::new();
env.put(app::env::ENV_INBOUND_LISTEN_ADDR, listen_addr.to_string());
let _proxy = proxy::new()
.inbound_ip(listen_addr)
.run_with_test_env_and_keep_ports(env);
let client = client::http1(listen_addr, listen_addr.to_string());
let rsp = client
.request(client.request_builder("/").method("GET"))
.await
.unwrap();
assert_eq!(rsp.status(), http::StatusCode::FORBIDDEN);
}
async fn test_server_speaks_first(env: TestEnv) {
const TIMEOUT: Duration = Duration::from_secs(5);
let _trace = trace_init();
let msg1 = "custom tcp server starts";
let msg2 = "custom tcp client second";
let (mut tx, mut rx) = mpsc::channel(1);
let srv = server::tcp()
.accept_fut(move |mut sock| {
async move {
sock.write_all(msg1.as_bytes()).await?;
let mut vec = vec![0; 512];
let n = sock.read(&mut vec).await?;
assert_eq!(s(&vec[..n]), msg2);
tx.send(()).await.unwrap();
Ok(())
}
.map(|res: std::io::Result<()>| match res {
Err(e) => panic!("tcp server error: {}", e),
Ok(()) => {}
})
})
.run()
.await;
let proxy = proxy::new()
.disable_inbound_ports_protocol_detection(vec![srv.addr.port()])
.inbound(srv)
.run_with_test_env(env)
.await;
let client = client::tcp(proxy.inbound);
let tcp_client = client.connect().await;
assert_eq!(s(&tcp_client.read_timeout(TIMEOUT).await), msg1);
tcp_client.write(msg2).await;
timeout(TIMEOUT, rx.recv()).await.unwrap();
// TCP client must close first
tcp_client.shutdown().await;
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn tcp_server_first() {
test_server_speaks_first(TestEnv::new()).await;
}
#[tokio::test]
async fn tcp_server_first_tls() {
use std::path::PathBuf;
let (_cert, _key, _trust_anchors) = {
let path_to_string = |path: &PathBuf| {
path.as_path()
.to_owned()
.into_os_string()
.into_string()
.unwrap()
};
let mut tls = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
tls.push("src");
tls.push("transport");
tls.push("tls");
tls.push("testdata");
tls.push("foo-ns1-ca1.crt");
let cert = path_to_string(&tls);
tls.set_file_name("foo-ns1-ca1.p8");
let key = path_to_string(&tls);
tls.set_file_name("ca1.pem");
let trust_anchors = path_to_string(&tls);
(cert, key, trust_anchors)
};
let env = TestEnv::new();
// FIXME
//env.put(app::env::ENV_TLS_CERT, cert);
//env.put(app::env::ENV_TLS_PRIVATE_KEY, key);
//env.put(app::env::ENV_TLS_TRUST_ANCHORS, trust_anchors);
//env.put(
// app::env::ENV_TLS_LOCAL_IDENTITY,
// "foo.deployment.ns1.linkerd-managed.linkerd.svc.cluster.local".to_string(),
//);
test_server_speaks_first(env).await
}
#[tokio::test]
#[allow(warnings)]
async fn tcp_connections_close_if_client_closes() {
let _trace = trace_init();
let msg1 = "custom tcp hello";
let msg2 = "custom tcp bye";
let (mut tx, mut rx) = mpsc::channel(1);
let srv = server::tcp()
.accept_fut(move |mut sock| {
async move {
let mut vec = vec![0; 1024];
let n = sock.read(&mut vec).await?;
assert_eq!(s(&vec[..n]), msg1);
sock.write_all(msg2.as_bytes()).await?;
let n = sock.read(&mut [0; 16]).await?;
assert_eq!(n, 0);
panic!("lol");
tx.send(()).await.unwrap();
Ok(())
}
.map(|res: std::io::Result<()>| match res {
Err(e) => panic!("tcp server error: {}", e),
Ok(()) => {}
})
})
.run()
.await;
let proxy = proxy::new().inbound(srv).run().await;
let client = client::tcp(proxy.inbound);
let tcp_client = client.connect().await;
tcp_client.write(msg1).await;
assert_eq!(s(&tcp_client.read().await[..]), msg2);
tcp_client.shutdown().await;
// rx will be fulfilled when our tcp accept_fut sees
// a socket disconnect, which is what we are testing for.
// the timeout here is just to prevent this test from hanging
timeout(Duration::from_secs(5), rx.recv()).await.unwrap();
// ensure panics from the server are propagated
proxy.join_servers().await;
}
macro_rules! http1_tests {
(proxy: $proxy:expr) => {
#[tokio::test]
async fn inbound_http1() {
let _trace = trace_init();
let srv = server::http1().route("/", "hello h1").run().await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
assert_eq!(client.get("/").await, "hello h1");
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http1_removes_connection_headers() {
let _trace = trace_init();
let srv = server::http1()
.route_fn("/", |req| {
assert!(!req.headers().contains_key("x-foo-bar"));
Response::builder()
.header("x-server-quux", "lorem ipsum")
.header("connection", "close, x-server-quux")
.header("keep-alive", "500")
.header("proxy-connection", "a")
.body(Default::default())
.unwrap()
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
let res = client
.request(
client
.request_builder("/")
.header("x-foo-bar", "baz")
.header("connection", "x-foo-bar, close")
// These headers will fail in the proxy_to_proxy case if
// they are not stripped.
//
// normally would be stripped by `connection: keep-alive`,
// but test its removed even if the connection header forgot
// about it.
.header("keep-alive", "500")
.header("proxy-connection", "a"),
)
.await
.unwrap();
assert_eq!(res.status(), http::StatusCode::OK);
assert!(!res.headers().contains_key("x-server-quux"));
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http10_with_host() {
let _trace = trace_init();
let host = "transparency.test.svc.cluster.local";
let srv = server::http1()
.route_fn("/", move |req| {
assert_eq!(req.version(), http::Version::HTTP_10);
assert_eq!(req.headers().get("host").unwrap(), host);
Response::builder()
.version(http::Version::HTTP_10)
.body("".into())
.unwrap()
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, host);
let res = client
.request(
client
.request_builder("/")
.version(http::Version::HTTP_10)
.header("host", host),
)
.await
.unwrap();
assert_eq!(res.status(), http::StatusCode::OK);
assert_eq!(res.version(), http::Version::HTTP_10);
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http11_absolute_uri_differs_from_host() {
let _trace = trace_init();
// We shouldn't touch the URI or the Host, just pass directly as we got.
let auth = "transparency.test.svc.cluster.local";
let host = "foo.bar";
let srv = server::http1()
.route_fn("/", move |req| {
assert_eq!(req.headers()["host"], host);
assert_eq!(req.uri().to_string(), format!("http://{}/", auth));
Response::new("".into())
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1_absolute_uris(proxy.inbound, auth);
let res = client
.request(
client
.request_builder("/")
.version(http::Version::HTTP_11)
.header("host", host),
)
.await
.unwrap();
assert_eq!(res.status(), http::StatusCode::OK);
assert_eq!(res.version(), http::Version::HTTP_11);
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http11_upgrades() {
let _trace = trace_init();
// To simplify things for this test, we just use the test TCP
// client and server to do an HTTP upgrade.
//
// This is upgrading to 'chatproto', a made up plaintext protocol
// to simplify testing.
let upgrade_req = "\
GET /chat HTTP/1.1\r\n\
Host: transparency.test.svc.cluster.local\r\n\
Connection: upgrade\r\n\
Upgrade: chatproto\r\n\
\r\n\
";
let upgrade_res = "\
HTTP/1.1 101 Switching Protocols\r\n\
Upgrade: chatproto\r\n\
Connection: upgrade\r\n\
\r\n\
";
let upgrade_needle = "\r\nupgrade: chatproto\r\n";
let chatproto_req = "[chatproto-c]{send}: hi all\n";
let chatproto_res = "[chatproto-s]{recv}: welcome!\n";
let srv = server::tcp()
.accept_fut(move |mut sock| {
async move {
// Read upgrade_req...
let mut vec = vec![0; 512];
let n = sock.read(&mut vec).await?;
assert_contains!(s(&vec[..n]), upgrade_needle);
// Write upgrade_res back...
sock.write_all(upgrade_res.as_bytes()).await?;
// Read the message in 'chatproto' format
let mut vec = vec![0; 512];
let n = sock.read(&mut vec).await?;
assert_eq!(s(&vec[..n]), chatproto_req);
// Some processing... and then write back in chatproto...
sock.write_all(chatproto_res.as_bytes()).await
}
.map(|res: std::io::Result<()>| match res {
Ok(()) => {}
Err(e) => panic!("tcp server error: {}", e),
})
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::tcp(proxy.inbound);
let tcp_client = client.connect().await;
tcp_client.write(upgrade_req).await;
let resp = tcp_client.read().await;
let resp_str = s(&resp);
assert!(
resp_str.starts_with("HTTP/1.1 101 Switching Protocols\r\n"),
"response not an upgrade: {:?}",
resp_str
);
assert_contains!(resp_str, upgrade_needle);
// We've upgraded from HTTP to chatproto! Say hi!
tcp_client.write(chatproto_req).await;
// Did anyone respond?
let chat_resp = tcp_client.read().await;
assert_eq!(s(&chat_resp), chatproto_res);
// TCP client must close first
tcp_client.shutdown().await;
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn l5d_orig_proto_header_isnt_leaked() {
let _trace = trace_init();
let srv = server::http1()
.route_fn("/", |req| {
assert_eq!(req.headers().get("l5d-orig-proto"), None, "request");
Response::new(Default::default())
})
.run()
.await;
let proxy = $proxy(srv).await;
let host = "transparency.test.svc.cluster.local";
let client = client::http1(proxy.inbound, host);
let res = client.request(client.request_builder("/")).await.unwrap();
assert_eq!(res.status(), 200);
assert_eq!(res.headers().get("l5d-orig-proto"), None, "response");
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http11_upgrade_h2_stripped() {
let _trace = trace_init();
// If an `h2` upgrade over HTTP/1.1 were to go by the proxy,
// and it succeeded, there would an h2 connection, but it would
// be opaque-to-the-proxy, acting as just a TCP proxy.
//
// A user wouldn't be able to see any usual HTTP telemetry about
// requests going over that connection. Instead of that confusion,
// the proxy strips h2 upgrade headers.
//
// Eventually, the proxy will support h2 upgrades directly.
let srv = server::http1()
.route_fn("/", |req| {
assert!(!req.headers().contains_key("connection"));
assert!(!req.headers().contains_key("upgrade"));
assert!(!req.headers().contains_key("http2-settings"));
Response::default()
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
let res = client
.request(
client
.request_builder("/")
.header("upgrade", "h2c")
.header("http2-settings", "")
.header("connection", "upgrade, http2-settings"),
)
.await
.unwrap();
// If the assertion is trigger in the above test route, the proxy will
// just send back a 500.
assert_eq!(res.status(), http::StatusCode::OK);
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http11_connect() {
let _trace = trace_init();
// To simplify things for this test, we just use the test TCP
// client and server to do an HTTP CONNECT.
//
// We don't *actually* perfom a new connect to requested host,
// but client doesn't need to know that for our tests.
let connect_req = b"\
CONNECT transparency.test.svc.cluster.local HTTP/1.1\r\n\
Host: transparency.test.svc.cluster.local\r\n\
\r\n\
";
let connect_res = b"\
HTTP/1.1 200 OK\r\n\
\r\n\
";
let tunneled_req = b"{send}: hi all\n";
let tunneled_res = b"{recv}: welcome!\n";
let srv = server::tcp()
.accept_fut(move |mut sock| {
async move {
// Read connect_req...
let mut vec = vec![0; 512];
let n = sock.read(&mut vec).await?;
let head = s(&vec[..n]);
assert_contains!(
head,
"CONNECT transparency.test.svc.cluster.local HTTP/1.1\r\n"
);
// Write connect_res back...
sock.write_all(&connect_res[..]).await?;
// Read the message after tunneling...
let mut vec = vec![0; 512];
let n = sock.read(&mut vec).await?;
assert_eq!(s(&vec[..n]), s(&tunneled_req[..]));
// Some processing... and then write back tunneled res...
sock.write_all(&tunneled_res[..]).await
}
.map(|res: std::io::Result<()>| match res {
Ok(()) => {}
Err(e) => panic!("tcp server error: {}", e),
})
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::tcp(proxy.inbound);
let tcp_client = client.connect().await;
tcp_client.write(&connect_req[..]).await;
let resp = tcp_client.read().await;
let resp_str = s(&resp);
assert!(
resp_str.starts_with("HTTP/1.1 200 OK\r\n"),
"response not an upgrade: {:?}",
resp_str
);
// We've CONNECTed from HTTP to foo.bar! Say hi!
tcp_client.write(&tunneled_req[..]).await;
// Did anyone respond?
let resp2 = tcp_client.read().await;
assert_eq!(s(&resp2), s(&tunneled_res[..]));
// TCP client must close first
tcp_client.shutdown().await;
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http11_connect_bad_requests() {
let _trace = trace_init();
let srv = server::tcp()
.accept(move |_sock| -> Vec<u8> {
unreachable!("shouldn't get through the proxy");
})
.run()
.await;
let proxy = $proxy(srv).await;
// A TCP client is used since the HTTP client would stop these requests
// from ever touching the network.
let client = client::tcp(proxy.inbound);
let bad_uris = vec!["/origin-form", "/", "http://test/bar", "http://test", "*"];
for bad_uri in bad_uris {
let tcp_client = client.connect().await;
let req = format!("CONNECT {} HTTP/1.1\r\nHost: test\r\n\r\n", bad_uri);
tcp_client.write(req).await;
let resp = tcp_client.read().await;
let resp_str = s(&resp);
assert!(
resp_str.starts_with("HTTP/1.1 400 Bad Request\r\n"),
"bad URI ({:?}) should get 400 response: {:?}",
bad_uri,
resp_str
);
}
// origin-form URIs must be CONNECT
let tcp_client = client.connect().await;
tcp_client
.write("GET test HTTP/1.1\r\nHost: test\r\n\r\n")
.await;
let resp = tcp_client.read().await;
let resp_str = s(&resp);
assert!(
resp_str.starts_with("HTTP/1.1 400 Bad Request\r\n"),
"origin-form without CONNECT should get 400 response: {:?}",
resp_str
);
// check that HTTP/1.0 is not allowed for CONNECT
let tcp_client = client.connect().await;
tcp_client
.write("CONNECT test HTTP/1.0\r\nHost: test\r\n\r\n")
.await;
let resp = tcp_client.read().await;
let resp_str = s(&resp);
assert!(
resp_str.starts_with("HTTP/1.0 400 Bad Request\r\n"),
"HTTP/1.0 CONNECT should get 400 response: {:?}",
resp_str
);
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http1_request_with_body_content_length() {
let _trace = trace_init();
let srv = server::http1()
.route_fn("/", |req| {
assert_eq!(req.headers()["content-length"], "5");
Response::default()
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
let req = client
.request_builder("/")
.method("POST")
.body("hello".into())
.unwrap();
let resp = client.request_body(req).await;
assert_eq!(resp.status(), StatusCode::OK);
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http1_request_with_body_chunked() {
let _trace = trace_init();
let srv = server::http1()
.route_async("/", |req| async move {
assert_eq!(req.headers()["transfer-encoding"], "chunked");
let body = req
.into_body()
.fold(String::new(), |s, mut chunk| {
s + std::str::from_utf8(chunk.to_bytes().as_ref()).expect("req is utf8")
})
.await;
assert_eq!(body, "hello");
Ok::<_, std::io::Error>(
Response::builder()
.header("transfer-encoding", "chunked")
.body("world".into())
.unwrap(),
)
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
let req = client
.request_builder("/")
.method("POST")
.header("transfer-encoding", "chunked")
.body("hello".into())
.unwrap();
let resp = client.request_body(req).await;
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers()["transfer-encoding"], "chunked");
let mut body = hyper::body::aggregate(resp.into_body())
.await
.expect("rsp aggregate");
let body = std::str::from_utf8(body.to_bytes().as_ref())
.expect("rsp is utf8")
.to_owned();
assert_eq!(body, "world");
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http1_requests_without_body_doesnt_add_transfer_encoding() {
let _trace = trace_init();
let srv = server::http1()
.route_fn("/", |req| {
let has_body_header = req.headers().contains_key("transfer-encoding")
|| req.headers().contains_key("content-length");
let status = if has_body_header {
StatusCode::BAD_REQUEST
} else {
StatusCode::OK
};
let mut res = Response::new("".into());
*res.status_mut() = status;
res
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
let methods = &["GET", "POST", "PUT", "DELETE", "HEAD", "PATCH"];
for &method in methods {
let resp = client
.request(client.request_builder("/").method(method))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK, "method={:?}", method);
}
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http1_content_length_zero_is_preserved() {
let _trace = trace_init();
let srv = server::http1()
.route_fn("/", |req| {
let status = if req.headers()["content-length"] == "0" {
StatusCode::OK
} else {
StatusCode::BAD_REQUEST
};
Response::builder()
.status(status)
.header("content-length", "0")
.body("".into())
.unwrap()
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
let methods = &["GET", "POST", "PUT", "DELETE", "HEAD", "PATCH"];
for &method in methods {
let resp = client
.request(
client
.request_builder("/")
.method(method)
.header("content-length", "0"),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK, "method={:?}", method);
assert_eq!(resp.headers()["content-length"], "0", "method={:?}", method);
}
}
#[tokio::test]
async fn http1_bodyless_responses() {
let _trace = trace_init();
let req_status_header = "x-test-status-requested";
let srv = server::http1()
.route_fn("/", move |req| {
let status = req
.headers()
.get(req_status_header)
.map(|val| {
val.to_str()
.expect("req_status_header should be ascii")
.parse::<u16>()
.expect("req_status_header should be numbers")
})
.unwrap_or(200);
Response::builder().status(status).body("".into()).unwrap()
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
// https://tools.ietf.org/html/rfc7230#section-3.3.3
// > response to a HEAD request, any 1xx, 204, or 304 cannot contain a body
//TODO: the proxy doesn't support CONNECT requests yet, but when we do,
//they should be tested here as well. As RFC7230 says, a 2xx response to
//a CONNECT request is not allowed to contain a body (but 4xx, 5xx can!).
let resp = client
.request(client.request_builder("/").method("HEAD"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert!(!resp.headers().contains_key("transfer-encoding"));
let statuses = &[
//TODO: test some 1xx status codes.
//The current test server doesn't support sending 1xx responses
//easily. We could test this by making a new unit test with the
//server being a TCP server, and write the response manually.
StatusCode::NO_CONTENT, // 204
StatusCode::NOT_MODIFIED, // 304
];
for &status in statuses {
let resp = client
.request(
client
.request_builder("/")
.header(req_status_header, status.as_str()),
)
.await
.unwrap();
assert_eq!(resp.status(), status);
assert!(
!resp.headers().contains_key("transfer-encoding"),
"transfer-encoding with status={:?}",
status
);
}
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http1_head_responses() {
let _trace = trace_init();
let srv = server::http1()
.route_fn("/", move |req| {
assert_eq!(req.method(), "HEAD");
Response::builder()
.header("content-length", "55")
.body("".into())
.unwrap()
})
.run()
.await;
let proxy = $proxy(srv).await;
let client = client::http1(proxy.inbound, "transparency.test.svc.cluster.local");
let resp = client
.request(client.request_builder("/").method("HEAD"))
.await
.expect("request");
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers()["content-length"], "55");
let mut body = hyper::body::aggregate(resp.into_body())
.await
.expect("response body aggregate");
let body = std::str::from_utf8(body.to_bytes().as_ref())
.expect("empty body is utf8")
.to_owned();
assert_eq!(body, "");
// ensure panics from the server are propagated
proxy.join_servers().await;
}
#[tokio::test]
async fn http1_response_end_of_file() {
let _trace = trace_init();