/
test_puma_server.rb
1091 lines (810 loc) · 31.4 KB
/
test_puma_server.rb
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
require_relative "helper"
require "puma/events"
require "net/http"
class TestPumaServer < Minitest::Test
parallelize_me!
def setup
@host = "127.0.0.1"
@ios = []
@app = ->(env) { [200, {}, [env['rack.url_scheme']]] }
@events = Puma::Events.strings
@server = Puma::Server.new @app, @events
end
def teardown
@server.stop(true)
@ios.each { |io| io.close if io && !io.closed? }
end
def server_run(app: @app, early_hints: false)
@server.app = app
@port = (@server.add_tcp_listener @host, 0).addr[1]
@server.instance_variable_set(:@early_hints, true) if early_hints
@server.run
end
def header(sock)
header = []
while true
line = sock.gets
break if line == "\r\n"
header << line.strip
end
header
end
def send_http_and_read(req)
send_http(req).read
end
def send_http(req)
new_connection << req
end
def new_connection
TCPSocket.new(@host, @port).tap {|sock| @ios << sock}
end
def test_proper_stringio_body
data = nil
server_run app: ->(env) do
data = env['rack.input'].read
[200, {}, ["ok"]]
end
fifteen = "1" * 15
sock = send_http "PUT / HTTP/1.0\r\nContent-Length: 30\r\n\r\n#{fifteen}"
sleep 0.1 # important so that the previous data is sent as a packet
sock << fifteen
sock.read
assert_equal "#{fifteen}#{fifteen}", data
end
def test_puma_socket
body = "HTTP/1.1 750 Upgraded to Awesome\r\nDone: Yep!\r\n"
server_run app: ->(env) do
io = env['puma.socket']
io.write body
io.close
[-1, {}, []]
end
data = send_http_and_read "PUT / HTTP/1.0\r\n\r\nHello"
assert_equal body, data
end
def test_very_large_return
giant = "x" * 2056610
server_run app: ->(env) do
[200, {}, [giant]]
end
sock = send_http "GET / HTTP/1.0\r\n\r\n"
while true
line = sock.gets
break if line == "\r\n"
end
out = sock.read
assert_equal giant.bytesize, out.bytesize
end
def test_respect_x_forwarded_proto
env = {}
env['HOST'] = "example.com"
env['HTTP_X_FORWARDED_PROTO'] = "https,http"
assert_equal "443", @server.default_server_port(env)
end
def test_respect_x_forwarded_ssl_on
env = {}
env['HOST'] = 'example.com'
env['HTTP_X_FORWARDED_SSL'] = 'on'
assert_equal "443", @server.default_server_port(env)
end
def test_respect_x_forwarded_scheme
env = {}
env['HOST'] = 'example.com'
env['HTTP_X_FORWARDED_SCHEME'] = 'https'
assert_equal '443', @server.default_server_port(env)
end
def test_default_server_port
server_run app: ->(env) do
[200, {}, [env['SERVER_PORT']]]
end
req = Net::HTTP::Get.new '/'
req['HOST'] = 'example.com'
res = Net::HTTP.start @host, @port do |http|
http.request(req)
end
assert_equal "80", res.body
end
def test_default_server_port_respects_x_forwarded_proto
server_run app: ->(env) do
[200, {}, [env['SERVER_PORT']]]
end
req = Net::HTTP::Get.new("/")
req['HOST'] = "example.com"
req['X-FORWARDED-PROTO'] = "https,http"
res = Net::HTTP.start @host, @port do |http|
http.request(req)
end
assert_equal "443", res.body
end
def test_HEAD_has_no_body
server_run app: ->(env) { [200, {"Foo" => "Bar"}, ["hello"]] }
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\nFoo: Bar\r\nContent-Length: 5\r\n\r\n", data
end
def test_GET_with_empty_body_has_sane_chunking
server_run app: ->(env) { [200, {}, [""]] }
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\nContent-Length: 0\r\n\r\n", data
end
def test_early_hints_works
server_run early_hints: true, app: ->(env) do
env['rack.early_hints'].call("Link" => "</style.css>; rel=preload; as=style\n</script.js>; rel=preload")
[200, { "X-Hello" => "World" }, ["Hello world!"]]
end
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
expected_data = (<<EOF
HTTP/1.1 103 Early Hints
Link: </style.css>; rel=preload; as=style
Link: </script.js>; rel=preload
HTTP/1.0 200 OK
X-Hello: World
Content-Length: 12
EOF
).split("\n").join("\r\n") + "\r\n\r\n"
assert_equal true, @server.instance_variable_get(:@early_hints)
assert_equal expected_data, data
end
def test_early_hints_are_ignored_if_connection_lost
def @server.fast_write(*args)
raise Puma::ConnectionError
end
server_run early_hints: true, app: ->(env) do
env['rack.early_hints'].call("Link" => "</script.js>; rel=preload")
[200, { "X-Hello" => "World" }, ["Hello world!"]]
end
# This request will cause the server to try and send early hints
_ = send_http "HEAD / HTTP/1.0\r\n\r\n"
# Give the server some time to try to write (and fail)
sleep 0.1
# Expect no errors in stderr
assert @events.stderr.pos.zero?, "Server didn't swallow the connection error"
end
def test_early_hints_is_off_by_default
server_run app: ->(env) do
assert_nil env['rack.early_hints']
[200, { "X-Hello" => "World" }, ["Hello world!"]]
end
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
expected_data = (<<EOF
HTTP/1.0 200 OK
X-Hello: World
Content-Length: 12
EOF
).split("\n").join("\r\n") + "\r\n\r\n"
assert_nil @server.instance_variable_get :@early_hints
assert_equal expected_data, data
end
def test_GET_with_no_body_has_sane_chunking
server_run app: ->(env) { [200, {}, []] }
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\n\r\n", data
end
def test_doesnt_print_backtrace_in_production
@server.instance_variable_set :@leak_stack_on_error, false
server_run app: ->(env) { raise "don't leak me bro" }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
refute_match(/don't leak me bro/, data)
assert_match(/HTTP\/1.0 500 Internal Server Error/, data)
end
def test_eof_on_connection_close_is_not_logged_as_an_error
server_run
new_connection.close # Make a connection and close without writing
@server.stop(true)
stderr = @events.stderr.string
assert stderr.empty?, "Expected stderr from server to be empty but it was #{stderr.inspect}"
end
def test_force_shutdown_custom_error_message
handler = lambda {|err, env, status| [500, {"Content-Type" => "application/json"}, ["{}\n"]]}
@server = Puma::Server.new @app, @events, {:lowlevel_error_handler => handler, :force_shutdown_after => 2}
server_run app: ->(env) do
@server.stop
sleep 5
end
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/HTTP\/1.0 500 Internal Server Error/, data)
assert_match(/Content-Type: application\/json/, data)
assert_match(/{}\n$/, data)
end
def test_force_shutdown_error_default
@server = Puma::Server.new @app, @events, {force_shutdown_after: 2}
@server.instance_variable_set :@leak_stack_on_error, true
server_run app: ->(env) do
@server.stop
sleep 5
end
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/HTTP\/1.0 503 Service Unavailable/, data)
assert_match(/Puma caught this error.+Puma::ThreadPool::ForceShutdown/, data)
end
def test_prints_custom_error
re = lambda { |err| [302, {'Content-Type' => 'text', 'Location' => 'foo.html'}, ['302 found']] }
@server = Puma::Server.new @app, @events, {:lowlevel_error_handler => re}
server_run app: ->(env) { raise "don't leak me bro" }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/HTTP\/1.0 302 Found/, data)
end
def test_leh_gets_env_as_well
re = lambda { |err,env|
env['REQUEST_PATH'] || raise('where is env?')
[302, {'Content-Type' => 'text', 'Location' => 'foo.html'}, ['302 found']]
}
@server = Puma::Server.new @app, @events, {:lowlevel_error_handler => re}
server_run app: ->(env) { raise "don't leak me bro" }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/HTTP\/1.0 302 Found/, data)
end
def test_leh_has_status
re = lambda { |err, env, status|
raise "Cannot find status" unless status
[302, {'Content-Type' => 'text', 'Location' => 'foo.html'}, ['302 found']]
}
@server = Puma::Server.new @app, @events, {:lowlevel_error_handler => re}
server_run app: ->(env) { raise "don't leak me bro" }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_match(/HTTP\/1.0 302 Found/, data)
end
def test_custom_http_codes_10
server_run app: ->(env) { [449, {}, [""]] }
data = send_http_and_read "GET / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 449 CUSTOM\r\nContent-Length: 0\r\n\r\n", data
end
def test_custom_http_codes_11
server_run app: ->(env) { [449, {}, [""]] }
data = send_http_and_read "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.1 449 CUSTOM\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
end
def test_HEAD_returns_content_headers
server_run app: ->(env) { [200, {"Content-Type" => "application/pdf",
"Content-Length" => "4242"}, []] }
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\nContent-Type: application/pdf\r\nContent-Length: 4242\r\n\r\n", data
end
def test_status_hook_fires_when_server_changes_states
states = []
@events.register(:state) { |s| states << s }
server_run app: ->(env) { [200, {}, [""]] }
_ = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
assert_equal [:booting, :running], states
@server.stop(true)
assert_equal [:booting, :running, :stop, :done], states
end
def test_timeout_in_data_phase
@server.instance_variable_set :@first_data_timeout, 2
server_run
sock = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\n"
data = sock.gets
assert_equal "HTTP/1.1 408 Request Timeout\r\n", data
end
def test_timeout_data_no_queue
@server = Puma::Server.new @app, @events, queue_requests: false
test_timeout_in_data_phase
end
def test_http_11_keep_alive_with_body
server_run app: ->(env) { [200, {"Content-Type" => "plain/text"}, ["hello\n"]] }
sock = send_http "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n\r\n"
h = header sock
body = sock.gets
assert_equal ["HTTP/1.1 200 OK", "Content-Type: plain/text", "Content-Length: 6"], h
assert_equal "hello\n", body
sock.close
end
def test_http_11_close_with_body
server_run app: ->(env) { [200, {"Content-Type" => "plain/text"}, ["hello"]] }
data = send_http_and_read "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.1 200 OK\r\nContent-Type: plain/text\r\nConnection: close\r\nContent-Length: 5\r\n\r\nhello", data
end
def test_http_11_keep_alive_without_body
server_run app: ->(env) { [204, {}, []] }
sock = send_http "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n\r\n"
h = header sock
assert_equal ["HTTP/1.1 204 No Content"], h
end
def test_http_11_close_without_body
server_run app: ->(env) { [204, {}, []] }
sock = send_http "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"
h = header sock
assert_equal ["HTTP/1.1 204 No Content", "Connection: close"], h
end
def test_http_10_keep_alive_with_body
server_run app: ->(env) { [200, {"Content-Type" => "plain/text"}, ["hello\n"]] }
sock = send_http "GET / HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n"
h = header sock
body = sock.gets
assert_equal ["HTTP/1.0 200 OK", "Content-Type: plain/text", "Connection: Keep-Alive", "Content-Length: 6"], h
assert_equal "hello\n", body
end
def test_http_10_close_with_body
server_run app: ->(env) { [200, {"Content-Type" => "plain/text"}, ["hello"]] }
data = send_http_and_read "GET / HTTP/1.0\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\nContent-Type: plain/text\r\nContent-Length: 5\r\n\r\nhello", data
end
def test_http_10_partial_hijack_with_content_length
body_parts = ['abc', 'de']
server_run app: ->(env) do
hijack_lambda = proc do | io |
io.write(body_parts[0])
io.write(body_parts[1])
io.close
end
[200, {"Content-Length" => "5", 'rack.hijack' => hijack_lambda}, nil]
end
data = send_http_and_read "GET / HTTP/1.0\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\nContent-Length: 5\r\n\r\nabcde", data
end
def test_http_10_keep_alive_without_body
server_run app: ->(env) { [204, {}, []] }
sock = send_http "GET / HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n"
h = header sock
assert_equal ["HTTP/1.0 204 No Content", "Connection: Keep-Alive"], h
end
def test_http_10_close_without_body
server_run app: ->(env) { [204, {}, []] }
data = send_http_and_read "GET / HTTP/1.0\r\nConnection: close\r\n\r\n"
assert_equal "HTTP/1.0 204 No Content\r\n\r\n", data
end
def test_Expect_100
server_run app: ->(env) { [200, {}, [""]] }
data = send_http_and_read "GET / HTTP/1.1\r\nConnection: close\r\nExpect: 100-continue\r\n\r\n"
assert_equal "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
end
def test_chunked_request
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
data = send_http_and_read "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nh\r\n4\r\nello\r\n0\r\n\r\n"
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal "hello", body
assert_equal 5, content_length
end
def test_large_chunked_request
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
header = "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n"
chunk_header_size = 6 # 4fb8\r\n
# Current implementation reads one chunk of CHUNK_SIZE, then more chunks of size 4096.
# We want a chunk to split exactly after "#{request_body}\r", before the "\n".
edge_case_size = Puma::Const::CHUNK_SIZE + 4096 - header.size - chunk_header_size - 1
margin = 0 # 0 for only testing this specific case, increase to test more surrounding sizes
(-margin..margin).each do |i|
size = edge_case_size + i
request_body = '.' * size
request = "#{header}#{size.to_s(16)}\r\n#{request_body}\r\n0\r\n\r\n"
data = send_http_and_read request
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal size, content_length
assert_equal request_body, body
end
end
def test_chunked_request_pause_before_value
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
sock = send_http "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n1\r\n"
sleep 1
sock << "h\r\n4\r\nello\r\n0\r\n\r\n"
data = sock.read
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal "hello", body
assert_equal 5, content_length
end
def test_chunked_request_pause_between_chunks
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
sock = send_http "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nh\r\n"
sleep 1
sock << "4\r\nello\r\n0\r\n\r\n"
data = sock.read
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal "hello", body
assert_equal 5, content_length
end
def test_chunked_request_pause_mid_count
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
sock = send_http "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n1\r"
sleep 1
sock << "\nh\r\n4\r\nello\r\n0\r\n\r\n"
data = sock.read
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal "hello", body
assert_equal 5, content_length
end
def test_chunked_request_pause_before_count_newline
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
sock = send_http "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n1"
sleep 1
sock << "\r\nh\r\n4\r\nello\r\n0\r\n\r\n"
data = sock.read
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal "hello", body
assert_equal 5, content_length
end
def test_chunked_request_pause_mid_value
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
sock = send_http "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nh\r\n4\r\ne"
sleep 1
sock << "llo\r\n0\r\n\r\n"
data = sock.read
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal "hello", body
assert_equal 5, content_length
end
def test_chunked_request_pause_between_cr_lf_after_size_of_second_chunk
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
part1 = 'a' * 4200
chunked_body = "#{part1.size.to_s(16)}\r\n#{part1}\r\n1\r\nb\r\n0\r\n\r\n"
sock = send_http "PUT /path HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n"
sleep 0.1
sock << chunked_body[0..-10]
sleep 0.1
sock << chunked_body[-9..-1]
data = sock.read
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal (part1 + 'b'), body
assert_equal 4201, content_length
end
def test_chunked_request_pause_between_closing_cr_lf
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
sock = send_http "PUT /path HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r"
sleep 1
sock << "\n0\r\n\r\n"
data = sock.read
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal 'hello', body
assert_equal 5, content_length
end
def test_chunked_request_pause_before_closing_cr_lf
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
sock = send_http "PUT /path HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello"
sleep 1
sock << "\r\n0\r\n\r\n"
data = sock.read
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal 'hello', body
assert_equal 5, content_length
end
def test_chunked_request_header_case
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
data = send_http_and_read "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: Chunked\r\n\r\n1\r\nh\r\n4\r\nello\r\n0\r\n\r\n"
assert_equal "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", data
assert_equal "hello", body
assert_equal 5, content_length
end
def test_chunked_keep_alive
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
sock = send_http "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nh\r\n4\r\nello\r\n0\r\n\r\n"
h = header sock
assert_equal ["HTTP/1.1 200 OK", "Content-Length: 0"], h
assert_equal "hello", body
assert_equal 5, content_length
sock.close
end
def test_chunked_keep_alive_two_back_to_back
body = nil
content_length = nil
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
[200, {}, [""]]
}
sock = send_http "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nh\r\n4\r\nello\r\n0\r\n"
last_crlf_written = false
last_crlf_writer = Thread.new do
sleep 0.1
sock << "\r"
sleep 0.1
sock << "\n"
last_crlf_written = true
end
h = header(sock)
assert_equal ["HTTP/1.1 200 OK", "Content-Length: 0"], h
assert_equal "hello", body
assert_equal 5, content_length
assert_equal true, last_crlf_written
last_crlf_writer.join
sock << "GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ngood\r\n3\r\nbye\r\n0\r\n\r\n"
sleep 0.1
h = header(sock)
assert_equal ["HTTP/1.1 200 OK", "Content-Length: 0"], h
assert_equal "goodbye", body
assert_equal 7, content_length
sock.close
end
def test_chunked_keep_alive_two_back_to_back_with_set_remote_address
body = nil
content_length = nil
remote_addr =nil
@server = Puma::Server.new @app, @events, { remote_address: :header, remote_address_header: 'HTTP_X_FORWARDED_FOR'}
server_run app: ->(env) {
body = env['rack.input'].read
content_length = env['CONTENT_LENGTH']
remote_addr = env['REMOTE_ADDR']
[200, {}, [""]]
}
sock = send_http "GET / HTTP/1.1\r\nX-Forwarded-For: 127.0.0.1\r\nConnection: Keep-Alive\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nh\r\n4\r\nello\r\n0\r\n\r\n"
h = header sock
assert_equal ["HTTP/1.1 200 OK", "Content-Length: 0"], h
assert_equal "hello", body
assert_equal 5, content_length
assert_equal "127.0.0.1", remote_addr
sock << "GET / HTTP/1.1\r\nX-Forwarded-For: 127.0.0.2\r\nConnection: Keep-Alive\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ngood\r\n3\r\nbye\r\n0\r\n\r\n"
sleep 0.1
h = header(sock)
assert_equal ["HTTP/1.1 200 OK", "Content-Length: 0"], h
assert_equal "goodbye", body
assert_equal 7, content_length
assert_equal "127.0.0.2", remote_addr
sock.close
end
def test_empty_header_values
server_run app: ->(env) { [200, {"X-Empty-Header" => ""}, []] }
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
assert_equal "HTTP/1.0 200 OK\r\nX-Empty-Header: \r\n\r\n", data
end
def test_request_body_wait
request_body_wait = nil
server_run app: ->(env) {
request_body_wait = env['puma.request_body_wait']
[204, {}, []]
}
sock = send_http "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nh"
sleep 1
sock << "ello"
sock.gets
# Could be 1000 but the tests get flaky. We don't care if it's extremely precise so much as that
# it is set to a reasonable number.
assert_operator request_body_wait, :>=, 900
end
def test_request_body_wait_chunked
request_body_wait = nil
server_run app: ->(env) {
request_body_wait = env['puma.request_body_wait']
[204, {}, []]
}
sock = send_http "GET / HTTP/1.1\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nh\r\n"
sleep 3
sock << "4\r\nello\r\n0\r\n\r\n"
sock.gets
# Could be 1000 but the tests get flaky. We don't care if it's extremely precise so much as that
# it is set to a reasonable number.
assert_operator request_body_wait, :>=, 900
end
def test_open_connection_wait
server_run app: ->(_) { [200, {}, ["Hello"]] }
s = send_http nil
sleep 0.1
s << "GET / HTTP/1.0\r\n\r\n"
assert_equal 'Hello', s.readlines.last
end
def test_open_connection_wait_no_queue
@server = Puma::Server.new @app, @events, queue_requests: false
test_open_connection_wait
end
# Rack may pass a newline in a header expecting us to split it.
def test_newline_splits
server_run app: ->(_) { [200, {'X-header' => "first line\nsecond line"}, ["Hello"]] }
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
assert_match "X-header: first line\r\nX-header: second line\r\n", data
end
def test_newline_splits_in_early_hint
server_run early_hints: true, app: ->(env) do
env['rack.early_hints'].call({'X-header' => "first line\nsecond line"})
[200, {}, ["Hello world!"]]
end
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
assert_match "X-header: first line\r\nX-header: second line\r\n", data
end
# To comply with the Rack spec, we have to split header field values
# containing newlines into multiple headers.
def assert_does_not_allow_http_injection(app, opts = {})
server_run(early_hints: opts[:early_hints], app: app)
data = send_http_and_read "HEAD / HTTP/1.0\r\n\r\n"
refute_match(/[\r\n]Cookie: hack[\r\n]/, data)
end
# HTTP Injection Tests
#
# Puma should prevent injection of CR and LF characters into headers, either as
# CRLF or CR or LF, because browsers may interpret it at as a line end and
# allow untrusted input in the header to split the header or start the
# response body. While it's not documented anywhere and they shouldn't be doing
# it, Chrome and curl recognize a lone CR as a line end. According to RFC,
# clients SHOULD interpret LF as a line end for robustness, and CRLF is the
# specced line end.
#
# There are three different tests because there are three ways to set header
# content in Puma. Regular (rack env), early hints, and a special case for
# overriding content-length.
{"cr" => "\r", "lf" => "\n", "crlf" => "\r\n"}.each do |suffix, line_ending|
# The cr-only case for the following test was CVE-2020-5247
define_method("test_prevent_response_splitting_headers_#{suffix}") do
app = ->(_) { [200, {'X-header' => "untrusted input#{line_ending}Cookie: hack"}, ["Hello"]] }
assert_does_not_allow_http_injection(app)
end
define_method("test_prevent_response_splitting_headers_early_hint_#{suffix}") do
app = ->(env) do
env['rack.early_hints'].call("X-header" => "untrusted input#{line_ending}Cookie: hack")
[200, {}, ["Hello"]]
end
assert_does_not_allow_http_injection(app, early_hints: true)
end
define_method("test_prevent_content_length_injection_#{suffix}") do
app = ->(_) { [200, {'content-length' => "untrusted input#{line_ending}Cookie: hack"}, ["Hello"]] }
assert_does_not_allow_http_injection(app)
end
end
# Perform a server shutdown while requests are pending (one in app-server response, one still sending client request).
def shutdown_requests(s1_complete: true, s1_response: nil, post: false, s2_response: nil, **options)
@server = Puma::Server.new @app, @events, options
mutex = Mutex.new
app_finished = ConditionVariable.new
server_run app: ->(env) {
path = env['REQUEST_PATH']
mutex.synchronize do
app_finished.signal
app_finished.wait(mutex) if path == '/s1'
end
[204, {}, []]
}
s1 = nil
s2 = send_http post ?
"POST /s2 HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhi!" :
"GET /s2 HTTP/1.1\r\n"
mutex.synchronize do
s1 = send_http "GET /s1 HTTP/1.1\r\n\r\n"
app_finished.wait(mutex)
app_finished.signal if s1_complete
end
@server.stop
Thread.pass until @server.instance_variable_get(:@thread_pool).instance_variable_get(:@shutdown)
assert_match(s1_response, s1.gets) if s1_response
# Send s2 after shutdown begins
s2 << "\r\n" unless IO.select([s2], nil, nil, 0.1)
assert IO.select([s2], nil, nil, 10), 'timeout waiting for response'
s2_result = begin
s2.gets
rescue Errno::ECONNABORTED, Errno::ECONNRESET
# Some platforms raise errors instead of returning a response/EOF when a TCP connection is aborted.
post ? '408' : nil
end