-
Notifications
You must be signed in to change notification settings - Fork 244
/
file_upload.rs
1431 lines (1284 loc) 路 48.2 KB
/
file_upload.rs
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
use std::collections::BTreeMap;
use bytes::Bytes;
use http::header::CONTENT_ENCODING;
use http::header::CONTENT_LENGTH;
use http::header::CONTENT_TYPE;
use http::HeaderValue;
use tower::BoxError;
const FILE_CONFIG: &str = include_str!("../fixtures/file_upload/default.router.yaml");
const FILE_CONFIG_LARGE_LIMITS: &str = include_str!("../fixtures/file_upload/large.router.yaml");
/// Create a valid handler for the [helper::FileUploadTestServer].
macro_rules! make_handler {
($handler:expr) => {
::axum::Router::new().route("/", ::axum::routing::post($handler))
};
($($path:literal => $handler:expr),+) => {
::axum::Router::new()
$(.route($path, ::axum::routing::post($handler)))+
}
}
#[tokio::test(flavor = "multi_thread")]
async fn it_uploads_a_single_file() -> Result<(), BoxError> {
const FILE: &str = "Hello, world!";
const FILE_NAME: &str = "example.txt";
// Construct the parts of the multipart request as defined by the schema
let request = helper::create_request(
vec![FILE_NAME],
vec![tokio_stream::once(Ok(Bytes::from_static(FILE.as_bytes())))],
);
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::echo_single_file))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"data": {
"file0": {
"filename": "example.txt",
"body": "Hello, world!"
}
}
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_uploads_multiple_files() -> Result<(), BoxError> {
let files = BTreeMap::from([
("example.txt", "Hello, world!"),
("example.json", r#"{ "message": "Hello, world!" }"#),
(
"example.yaml",
"
message: |
Hello, world!
"
.trim(),
),
(
"example.toml",
"
[message]
Hello, world!
"
.trim(),
),
]);
// Construct the parts of the multipart request as defined by the schema for multiple files
let request = helper::create_request(
files.keys().cloned().collect::<Vec<_>>(),
files
.values()
.map(|contents| tokio_stream::once(Ok(bytes::Bytes::from_static(contents.as_bytes()))))
.collect::<Vec<_>>(),
);
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::echo_files))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(move |response| {
insta::assert_json_snapshot!(response, @r###"
{
"data": {
"file0": {
"filename": "example.json",
"body": "{ \"message\": \"Hello, world!\" }"
},
"file1": {
"filename": "example.toml",
"body": "[message]\n Hello, world!"
},
"file2": {
"filename": "example.txt",
"body": "Hello, world!"
},
"file3": {
"filename": "example.yaml",
"body": "message: |\n Hello, world!"
}
}
}
"###);
})
.await
}
// TODO: This test takes ~3 minutes to complete. Possible solutions:
// - Lower the amount of data sent
// - Don't check that all of the bytes match
// TODO: Can we measure memory usage from within the test and ensure that it doesn't blow up?
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn it_uploads_a_massive_file() -> Result<(), BoxError> {
// Upload a stream of 10GB
const ONE_MB: usize = 1024 * 1024;
const TEN_GB: usize = 10 * 1024 * ONE_MB;
const FILE_CHUNK: [u8; ONE_MB] = [0xAA; ONE_MB];
const CHUNK_COUNT: usize = TEN_GB / ONE_MB;
// Upload a file that is 1GB in size of 0xAA
let file =
tokio_stream::iter((0..CHUNK_COUNT).map(|_| Ok(bytes::Bytes::from_static(&FILE_CHUNK))));
// Construct the parts of the multipart request as defined by the schema
let request = helper::create_request(vec!["fat.payload.bin"], vec![file]);
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG_LARGE_LIMITS)
.handler(make_handler!(helper::verify_stream).with_state((TEN_GB, 0xAA)))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"data": {
"file0": {
"filename": "fat.payload.bin",
"body": "successfully verified all bytes as '0xAA'"
}
}
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_uploads_to_multiple_subgraphs() -> Result<(), BoxError> {
use reqwest::multipart::Form;
use reqwest::multipart::Part;
// Construct a manual multipart request with a valid file order
let request = Form::new()
.part(
"operations",
Part::text(
serde_json::json!({
"query": "mutation SomeMutation($file0: Upload, $file1: UploadClone) {
file0: singleUpload(file: $file0) { filename body }
file1: singleUploadClone(file: $file1) { filename body }
}",
"variables": {
"file0": null,
"file1": null,
},
})
.to_string(),
),
)
.part(
"map",
Part::text(
serde_json::json!({
"0": ["variables.file0"],
"1": ["variables.file1"],
})
.to_string(),
),
)
.part("0", Part::text("file0 contents").file_name("file0"))
.part("1", Part::text("file1 contents").file_name("file1"));
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(
"/s1" => helper::echo_single_file,
"/s2" => helper::echo_single_file
))
.request(request)
.subgraph_mapping("uploads", "/s1")
.subgraph_mapping("uploads_clone", "/s2")
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"data": {
"file0": {
"filename": "file0",
"body": "file0 contents"
},
"file1": {
"filename": "file1",
"body": "file1 contents"
}
}
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_supports_compression() -> Result<(), BoxError> {
use reqwest::multipart::Form;
const FILE_NAME: &str = "compressed.txt";
const FILE_CONTENTS: &str = "compression saves space sometimes!";
// We need to manually compress the body since reqwest does not yet support
// compressing the initial request.
// see: https://github.com/seanmonstar/reqwest/issues/1217
fn compress(req: reqwest::Request) -> reqwest::Request {
struct ManualRequest {
boundary: String,
body: Vec<u8>,
}
impl ManualRequest {
fn new() -> Self {
Self {
boundary: Form::new().boundary().to_string(),
body: Vec::new(),
}
}
fn add_boundary(&mut self) {
self.body
.extend(format!("--{}\r\n", self.boundary).as_bytes());
}
fn file(mut self, field_name: &str, file_name: &str, data: &str) -> Self {
self.add_boundary();
self.body.extend(format!("Content-Disposition: form-data; name=\"{field_name}\"; filename=\"{file_name}\"\r\n").as_bytes());
self.body
.extend("Content-Type: text/plain\r\n\r\n".as_bytes());
self.body.extend(data.as_bytes());
self.body.extend("\r\n".as_bytes());
self
}
fn text(mut self, field_name: &str, data: &str) -> Self {
self.add_boundary();
self.body.extend(
format!("Content-Disposition: form-data; name=\"{field_name}\"\r\n\r\n")
.as_bytes(),
);
self.body.extend(data.as_bytes());
self.body.extend("\r\n".as_bytes());
self
}
fn compress(mut self) -> (String, bytes::Bytes) {
use std::io::Read;
// Make sure to end the multipart stream
self.body
.extend(format!("--{}--\r\n", self.boundary).as_bytes());
// Values below are from the examples
// see: https://github.com/dropbox/rust-brotli/blob/343beb46b8fd7864b22e5d1de4761d5716a29fa5/examples/compress.rs#L12
let mut reader = brotli::CompressorReader::new(&self.body[..], 4096, 11, 22);
let mut buf = Vec::new();
reader
.read_to_end(&mut buf)
.expect("could not compress body");
(self.boundary, bytes::Bytes::from(buf))
}
}
let (boundary, request) = ManualRequest::new()
.text(
"operations",
&serde_json::json!({
"query": "mutation SomeMutation($file0: Upload) {
file0: singleUpload(file: $file0) { filename body }
}",
"variables": {
"file0": null,
},
})
.to_string(),
)
.text(
"map",
&serde_json::json!({
"0": ["variables.file0"],
})
.to_string(),
)
.file("0", FILE_NAME, FILE_CONTENTS)
.compress();
// Fix some headers to account for compression
let mut headers = req.headers().clone();
headers.remove(CONTENT_LENGTH);
headers.insert(
CONTENT_ENCODING,
reqwest::header::HeaderValue::from_static("br"),
);
headers.insert(
CONTENT_TYPE,
reqwest::header::HeaderValue::from_str(&format!(
"multipart/form-data; boundary={boundary}"
))
.unwrap(),
);
reqwest::Client::new()
.post(req.url().clone())
.headers(headers)
.body(request)
.build()
.unwrap()
}
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::echo_single_file))
.request(Form::new()) // Gets overwritten by the `compress` transformer
.subgraph_mapping("uploads", "/")
.transformer(compress)
.build()
.run_test(|request| {
insta::assert_json_snapshot!(request, @r###"
{
"data": {
"file0": {
"filename": "compressed.txt",
"body": "compression saves space sometimes!"
}
}
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_supports_non_nullable_file() -> Result<(), BoxError> {
use reqwest::multipart::Form;
use reqwest::multipart::Part;
// Construct a manual request for non nullable checks
let request = Form::new()
.part(
"operations",
Part::text(
serde_json::json!({
"query": "mutation SomeMutation($file0: Upload!) {
file0: singleUploadNonNull(file: $file0) { filename body }
}",
"variables": {
"file0": null,
},
})
.to_string(),
),
)
.part(
"map",
Part::text(
serde_json::json!({
"0": ["variables.file0"],
})
.to_string(),
),
)
.part("0", Part::text("file0 contents").file_name("file0"));
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::echo_single_file))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(|request| {
insta::assert_json_snapshot!(request, @r###"
{
"data": {
"file0": {
"filename": "file0",
"body": "file0 contents"
}
}
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_supports_nested_file() -> Result<(), BoxError> {
use reqwest::multipart::Form;
use reqwest::multipart::Part;
// Construct a manual request that sets up a nested structure containing a file to upload
let request = Form::new()
.part(
"operations",
Part::text(
serde_json::json!({
"query": "mutation SomeMutation($file0: NestedUpload) {
file0: nestedUpload(nested: $file0) { filename body }
}",
"variables": {
"file0": {
"file": null,
},
},
})
.to_string(),
),
)
.part(
"map",
Part::text(
serde_json::json!({
"0": ["variables.file0.file"],
})
.to_string(),
),
)
.part("0", Part::text("file0 contents").file_name("file0"));
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::echo_single_file))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(|request| {
insta::assert_json_snapshot!(request, @r###"
{
"data": {
"file0": {
"filename": "file0",
"body": "file0 contents"
}
}
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_supports_nested_file_list() -> Result<(), BoxError> {
use reqwest::multipart::Form;
use reqwest::multipart::Part;
// Construct a manual request that sets up a nested structure containing a file to upload
let request = Form::new()
.part(
"operations",
Part::text(
serde_json::json!({
"query": "mutation SomeMutation($files: [Upload!]!) {
files: multiUpload(files: $files) { filename body }
}",
"variables": {
"files": {
"0": null,
"1": null,
"2": null,
},
},
})
.to_string(),
),
)
.part(
"map",
Part::text(
serde_json::json!({
"0": ["variables.files.0"],
"1": ["variables.files.1"],
"2": ["variables.files.2"],
})
.to_string(),
),
)
.part("0", Part::text("file0 contents").file_name("file0"))
.part("1", Part::text("file1 contents").file_name("file1"))
.part("2", Part::text("file2 contents").file_name("file2"));
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::echo_file_list))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(|request| {
insta::assert_json_snapshot!(request, @r###"
{
"data": {
"files": [
{
"filename": "file0",
"body": "file0 contents"
},
{
"filename": "file1",
"body": "file1 contents"
},
{
"filename": "file2",
"body": "file2 contents"
}
]
}
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_fails_upload_without_file() -> Result<(), BoxError> {
// Construct a request with no attached files
let request = helper::create_request(vec!["missing.txt"], Vec::<tokio_stream::Once<_>>::new());
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::always_fail))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"errors": [
{
"message": "HTTP fetch failed from 'uploads': HTTP fetch failed from 'uploads': error from user's HttpBody stream: error reading a body from connection: Missing files in the request: '0'.",
"path": [],
"extensions": {
"code": "SUBREQUEST_HTTP_ERROR",
"service": "uploads",
"reason": "HTTP fetch failed from 'uploads': error from user's HttpBody stream: error reading a body from connection: Missing files in the request: '0'."
}
}
]
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_fails_with_file_count_limits() -> Result<(), BoxError> {
// Create a list of files that passes the limit set in the config (5)
let files = (0..100).map(|index| index.to_string());
// Construct the parts of the multipart request as defined by the schema for multiple files
let request = helper::create_request(
files.clone().collect::<Vec<_>>(),
files
.map(|_| tokio_stream::once(Ok(bytes::Bytes::new())))
.collect::<Vec<_>>(),
);
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::always_fail))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"errors": [
{
"message": "Exceeded the limit of 5 file uploads of files in a single request.",
"extensions": {
"code": "FILE_UPLOADS_LIMITS_MAX_FILES_EXCEEDED"
}
}
]
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_fails_with_file_size_limit() -> Result<(), BoxError> {
// Create a file that passes the limit set in the config (512KB)
const ONE_MB: usize = 1024 * 1024;
const FILE_CHUNK: [u8; ONE_MB] = [0xAA; ONE_MB];
// Construct the parts of the multipart request as defined by the schema for multiple files
let request = helper::create_request(
vec!["fat.payload.bin"],
vec![tokio_stream::once(Ok(bytes::Bytes::from_static(
&FILE_CHUNK,
)))],
);
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::always_fail))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"errors": [
{
"message": "HTTP fetch failed from 'uploads': HTTP fetch failed from 'uploads': error from user's HttpBody stream: error reading a body from connection: Exceeded the limit of 512.0 KB on 'fat.payload.bin' file.",
"path": [],
"extensions": {
"code": "SUBREQUEST_HTTP_ERROR",
"service": "uploads",
"reason": "HTTP fetch failed from 'uploads': error from user's HttpBody stream: error reading a body from connection: Exceeded the limit of 512.0 KB on 'fat.payload.bin' file."
}
}
]
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_fails_invalid_multipart_order() -> Result<(), BoxError> {
use reqwest::multipart::Form;
use reqwest::multipart::Part;
// Construct a manual multipart request out of order
// Note: The order is wrong, but the parts follow the spec
let request = Form::new()
.part(
"map",
Part::text(serde_json::json!({
"0": ["variables.file0"]
}).to_string()),
).part(
"operations",
Part::text(serde_json::json!({
"query": "mutation ($file0: Upload) { singleUpload(file: $file0) { filename } }",
"variables": {
"file0": null,
},
}).to_string())
).part("0", Part::text("file contents").file_name("file0"));
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::always_fail))
.request(request)
.subgraph_mapping("uploads", "/")
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"errors": [
{
"message": "Missing multipart field 'operations', it should be a first field in request body.",
"extensions": {
"code": "FILE_UPLOADS_OPERATION_CANNOT_STREAM"
}
}
]
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_fails_invalid_file_order() -> Result<(), BoxError> {
use reqwest::multipart::Form;
use reqwest::multipart::Part;
// Construct a manual multipart request with files out of order
let request = Form::new()
.part(
"operations",
Part::text(
serde_json::json!({
"query": "mutation ($file0: Upload, $file1: UploadClone) {
file0: singleUpload(file: $file0) { filename body }
file1: singleUploadClone(file: $file1) { filename body }
}",
"variables": {
"file0": null,
"file1": null,
},
})
.to_string(),
),
)
.part(
"map",
Part::text(
serde_json::json!({
"0": ["variables.file0"],
"1": ["variables.file1"],
})
.to_string(),
),
)
.part("1", Part::text("file1 contents").file_name("file1"))
.part("0", Part::text("file0 contents").file_name("file0"));
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(
"/s1" => helper::echo_single_file,
"/s2" => helper::always_fail
))
.request(request)
.subgraph_mapping("uploads", "/s1")
.subgraph_mapping("uploads_clone", "/s2")
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"data": {
"file0": {
"filename": "file0",
"body": "file0 contents"
},
"file1": null
},
"errors": [
{
"message": "HTTP fetch failed from 'uploads_clone': HTTP fetch failed from 'uploads_clone': error from user's HttpBody stream: error reading a body from connection: Missing files in the request: '1'.",
"path": [],
"extensions": {
"code": "SUBREQUEST_HTTP_ERROR",
"service": "uploads_clone",
"reason": "HTTP fetch failed from 'uploads_clone': error from user's HttpBody stream: error reading a body from connection: Missing files in the request: '1'."
}
}
]
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_fails_with_no_boundary_in_multipart() -> Result<(), BoxError> {
// Create multipart request and remove the boundary
let request = helper::create_request(
Vec::<&str>::new(),
Vec::<tokio_stream::Once<hyper::Result<bytes::Bytes>>>::new(),
);
// Remove the boundary from the request to fail
fn strip_boundary(mut req: reqwest::Request) -> reqwest::Request {
req.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static("multipart/form-data"),
);
req
}
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(helper::always_fail))
.request(request)
.subgraph_mapping("uploads", "/")
.transformer(strip_boundary)
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"errors": [
{
"message": "invalid multipart request: multipart boundary not found in Content-Type",
"extensions": {
"code": "FILE_UPLOADS_OPERATION_CANNOT_STREAM"
}
}
]
}
"###);
})
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn it_fails_incompatible_query_order() -> Result<(), BoxError> {
use reqwest::multipart::Form;
use reqwest::multipart::Part;
// Construct a manual multipart request with an impossible file order
// Note: With the `stream` mode of file upload this order is impossible since
// the second file needs to be processed first
let request = Form::new()
.part(
"operations",
Part::text(
serde_json::json!({
"query": "mutation SomeMutation($file0: UploadClone, $file1: Upload) {
file1: singleUpload(file: $file1) { filename }
file0: singleUploadClone(file: $file0) { filename }
}",
"variables": {
"file0": null,
"file1": null,
},
})
.to_string(),
),
)
.part(
"map",
Part::text(
serde_json::json!({
"0": ["variables.file0"],
"1": ["variables.file1"],
})
.to_string(),
),
)
.part("0", Part::text("file0 contents").file_name("file0"))
.part("1", Part::text("file1 contents").file_name("file1"));
// Run the test
helper::FileUploadTestServer::builder()
.config(FILE_CONFIG)
.handler(make_handler!(
"/s1" => helper::always_fail,
"/s2" => helper::always_fail
))
.request(request)
.subgraph_mapping("uploads", "/s1")
.subgraph_mapping("uploads_clone", "/s2")
.build()
.run_test(|response| {
insta::assert_json_snapshot!(response, @r###"
{
"errors": [
{
"message": "References to variables containing files are ordered in the way that prevent streaming of files.",
"extensions": {
"code": "FILE_UPLOADS_OPERATION_CANNOT_STREAM"
}
}
]
}
"###);
})
.await
}
mod helper {
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::SocketAddr;
use std::path::PathBuf;
use axum::extract::State;
use axum::response::IntoResponse;
use axum::BoxError;
use axum::Json;
use axum::Router;
use buildstructor::buildstructor;
use futures::StreamExt;
use http::header::CONTENT_TYPE;
use http::Request;
use http::StatusCode;
use hyper::Body;
use itertools::Itertools;
use multer::Multipart;
use reqwest::multipart::Form;
use reqwest::multipart::Part;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde::Serialize;
use serde_json::json;
use serde_json::Value;
use thiserror::Error;
use tokio::net::TcpListener;
use tokio_stream::Stream;
use super::super::common::IntegrationTest;
/// A helper server for testing multipart uploads.
///
/// Note: This is a shim until wiremock supports two needed features:
/// - [Streaming of the body](https://github.com/LukeMathWalker/wiremock-rs/pull/133)
/// - [Async handlers for responders](https://github.com/LukeMathWalker/wiremock-rs/issues/84)
///
/// Another alternative is to treat the handler (a [Router]) as a tower service and just [tower::ServiceExt::oneshot] it,
/// but since the integration test is running the router as a normal process, we don't have a nice way to
/// do so without running the HTTP server.
pub struct FileUploadTestServer {
config: &'static str,
handler: Router,
request: Form,
subgraph_mappings: HashMap<String, String>,
transformer: Option<fn(reqwest::Request) -> reqwest::Request>,
}
#[buildstructor]
impl FileUploadTestServer {
/// Create a test server with the supplied config, handler and request.
///
/// Prefer the builder so that tests are more descriptive.
///
/// See [make_handler] and [create_request].
#[builder]
pub fn new(
config: &'static str,
handler: Router,
subgraph_mappings: HashMap<String, String>,
request: Form,
transformer: Option<fn(reqwest::Request) -> reqwest::Request>,
) -> Self {
Self {
config,
handler,
request,
subgraph_mappings,
transformer,
}
}
/// Runs a test, using the provided validation_fn to ensure that the response matches
/// what is expected.
pub async fn run_test(
self,
validation_fn: impl Fn(apollo_router::graphql::Response),
) -> Result<(), BoxError> {
// Ensure that we have the test keys before running
// Note: The [IntegrationTest] ensures that these test credentials get
// set before running the router.
if std::env::var("TEST_APOLLO_KEY").is_err()
|| std::env::var("TEST_APOLLO_GRAPH_REF").is_err()
{
return Ok(());
};
// Bind to the first available port
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0);
let bound = TcpListener::bind(addr).await.unwrap();
let bound_url = bound.local_addr().unwrap();
let bound_url = format!("http://{bound_url}");
// Set up the router with the custom subgraph handler above
let mut router = IntegrationTest::builder()
.config(self.config)
.subgraph_overrides(
self.subgraph_mappings
.into_iter()
.map(|(name, path)| (name, format!("{bound_url}{path}")))
.collect(),
)
.supergraph(PathBuf::from_iter([