-
Notifications
You must be signed in to change notification settings - Fork 595
/
Http2ServerSpec.scala
1389 lines (1137 loc) · 66 KB
/
Http2ServerSpec.scala
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
/*
* Copyright (C) 2018-2020 Lightbend Inc. <https://www.lightbend.com>
*/
package akka.http.impl.engine.http2
import java.net.InetSocketAddress
import akka.NotUsed
import akka.event.Logging
import akka.http.impl.engine.http2.FrameEvent._
import akka.http.impl.engine.http2.Http2Protocol.ErrorCode
import akka.http.impl.engine.http2.Http2Protocol.Flags
import akka.http.impl.engine.http2.Http2Protocol.FrameType
import akka.http.impl.engine.http2.Http2Protocol.SettingIdentifier
import akka.http.impl.engine.server.HttpAttributes
import akka.http.impl.engine.ws.ByteStringSinkProbe
import akka.http.impl.util.AkkaSpecWithMaterializer
import akka.http.impl.util.LogByteStringTools
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.CacheDirectives
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.settings.ServerSettings
import akka.stream.Attributes
import akka.stream.Attributes.LogLevels
import akka.stream.OverflowStrategy
import akka.stream.impl.io.ByteStringParser.ByteReader
import akka.stream.scaladsl.BidiFlow
import akka.stream.scaladsl.Flow
import akka.stream.scaladsl.Sink
import akka.stream.scaladsl.Source
import akka.stream.scaladsl.SourceQueueWithComplete
import akka.stream.testkit.TestPublisher.ManualProbe
import akka.stream.testkit.scaladsl.StreamTestKit
import akka.stream.testkit.TestPublisher
import akka.stream.testkit.TestSubscriber
import akka.testkit._
import akka.util.ByteString
import com.github.ghik.silencer.silent
import javax.net.ssl.SSLContext
import org.scalatest.concurrent.Eventually
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import scala.collection.immutable
import scala.concurrent.duration._
import scala.concurrent.Await
import scala.concurrent.Future
import scala.concurrent.Promise
/**
* This tests the http2 server protocol logic.
*
* Tests typically:
* * provide incoming data frames
* * if applicable: validate the constructed incoming application-level request
* * if applicable: provide application-level response
* * validate the produced response frames
*/
class Http2ServerSpec extends AkkaSpecWithMaterializer("""
akka.http.server.remote-address-header = on
akka.http.server.http2.log-frames = on
""")
with WithInPendingUntilFixed with Eventually {
override def failOnSevereMessages: Boolean = true
"The Http/2 server implementation" should {
"support simple round-trips" should {
abstract class SimpleRequestResponseRoundtripSetup extends TestSetup with RequestResponseProbes {
def requestResponseRoundtrip(
streamId: Int,
requestHeaderBlock: ByteString,
expectedRequest: HttpRequest,
response: HttpResponse,
expectedResponseHeaderBlock: ByteString
): Unit = {
sendHEADERS(streamId, endStream = true, endHeaders = true, requestHeaderBlock)
expectRequest() shouldBe expectedRequest
responseOut.sendNext(response.addAttribute(Http2.streamId, streamId))
val headerPayload = expectHeaderBlock(streamId)
headerPayload shouldBe expectedResponseHeaderBlock
}
}
"GET request in one HEADERS frame" inAssertAllStagesStopped new SimpleRequestResponseRoundtripSetup {
requestResponseRoundtrip(
streamId = 1,
requestHeaderBlock = HPackSpecExamples.C41FirstRequestWithHuffman,
expectedRequest = HttpRequest(HttpMethods.GET, "http://www.example.com/", protocol = HttpProtocols.`HTTP/2.0`),
response = HPackSpecExamples.FirstResponse,
expectedResponseHeaderBlock = HPackSpecExamples.C61FirstResponseWithHuffman
)
}
"GOAWAY when invalid headers frame" inAssertAllStagesStopped new TestSetup with RequestResponseProbes {
override def handlerFlow: Flow[HttpRequest, HttpResponse, NotUsed] =
Flow[HttpRequest].map { req =>
HttpResponse(entity = req.entity).addAttribute(Http2.streamId, req.attribute(Http2.streamId).get)
}
val headerBlock = hex"00 00 01 01 05 00 00 00 01 40"
sendHEADERS(1, endStream = false, endHeaders = true, headerBlockFragment = headerBlock)
val (_, errorCode) = expectGOAWAY(0) // since we have not processed any stream
errorCode should ===(ErrorCode.COMPRESSION_ERROR)
}
"GOAWAY when second request on different stream has invalid headers frame" inAssertAllStagesStopped new SimpleRequestResponseRoundtripSetup {
requestResponseRoundtrip(
streamId = 1,
requestHeaderBlock = HPackSpecExamples.C41FirstRequestWithHuffman,
expectedRequest = HttpRequest(HttpMethods.GET, "http://www.example.com/", protocol = HttpProtocols.`HTTP/2.0`),
response = HPackSpecExamples.FirstResponse,
expectedResponseHeaderBlock = HPackSpecExamples.C61FirstResponseWithHuffman
)
// example from: https://github.com/summerwind/h2spec/blob/master/4_3.go#L18
val incorrectHeaderBlock = hex"00 00 01 01 05 00 00 00 01 40"
sendHEADERS(3, endStream = false, endHeaders = true, headerBlockFragment = incorrectHeaderBlock)
val (_, errorCode) = expectGOAWAY(1) // since we have successfully started processing stream `1`
errorCode should ===(ErrorCode.COMPRESSION_ERROR)
}
"Three consecutive GET requests" inAssertAllStagesStopped new SimpleRequestResponseRoundtripSetup {
import CacheDirectives._
import headers.`Cache-Control`
requestResponseRoundtrip(
streamId = 1,
requestHeaderBlock = HPackSpecExamples.C41FirstRequestWithHuffman,
expectedRequest = HttpRequest(HttpMethods.GET, "http://www.example.com/", protocol = HttpProtocols.`HTTP/2.0`),
response = HPackSpecExamples.FirstResponse,
expectedResponseHeaderBlock = HPackSpecExamples.C61FirstResponseWithHuffman
)
requestResponseRoundtrip(
streamId = 3,
requestHeaderBlock = HPackSpecExamples.C42SecondRequestWithHuffman,
expectedRequest = HttpRequest(
method = HttpMethods.GET,
uri = "http://www.example.com/",
headers = Vector(`Cache-Control`(`no-cache`)),
protocol = HttpProtocols.`HTTP/2.0`),
response = HPackSpecExamples.SecondResponse,
// our hpack compressor chooses the non-huffman form probably because it seems to have same length
expectedResponseHeaderBlock = HPackSpecExamples.C52SecondResponseWithoutHuffman
)
requestResponseRoundtrip(
streamId = 5,
requestHeaderBlock = HPackSpecExamples.C43ThirdRequestWithHuffman,
expectedRequest = HttpRequest(
method = HttpMethods.GET,
uri = "https://www.example.com/index.html",
headers = RawHeader("custom-key", "custom-value") :: Nil,
protocol = HttpProtocols.`HTTP/2.0`),
response = HPackSpecExamples.ThirdResponse,
expectedResponseHeaderBlock = HPackSpecExamples.C63ThirdResponseWithHuffman
)
}
"GET request in one HEADERS and one CONTINUATION frame" inAssertAllStagesStopped new TestSetup with RequestResponseProbes {
val headerBlock = HPackSpecExamples.C41FirstRequestWithHuffman
val fragment1 = headerBlock.take(8) // must be grouped by octets
val fragment2 = headerBlock.drop(8)
sendHEADERS(1, endStream = true, endHeaders = false, fragment1)
requestIn.ensureSubscription()
requestIn.expectNoMessage(100.millis)
sendCONTINUATION(1, endHeaders = true, fragment2)
val request = expectRequestRaw()
request.method shouldBe HttpMethods.GET
request.uri shouldBe Uri("http://www.example.com/")
val streamId = request.attribute(Http2.streamId).getOrElse(Http2Compliance.missingHttpIdHeaderException)
responseOut.sendNext(HPackSpecExamples.FirstResponse.addAttribute(Http2.streamId, streamId))
val headerPayload = expectHeaderBlock(1)
headerPayload shouldBe HPackSpecExamples.C61FirstResponseWithHuffman
}
"GET request in one HEADERS and two CONTINUATION frames" inAssertAllStagesStopped new TestSetup with RequestResponseProbes {
val headerBlock = HPackSpecExamples.C41FirstRequestWithHuffman
val fragment1 = headerBlock.take(8) // must be grouped by octets
val fragment2 = headerBlock.drop(8).take(8)
val fragment3 = headerBlock.drop(16)
sendHEADERS(1, endStream = true, endHeaders = false, fragment1)
requestIn.ensureSubscription()
requestIn.expectNoMessage(100.millis)
sendCONTINUATION(1, endHeaders = false, fragment2)
sendCONTINUATION(1, endHeaders = true, fragment3)
val request = expectRequestRaw()
request.method shouldBe HttpMethods.GET
request.uri shouldBe Uri("http://www.example.com/")
val streamId = request.attribute(Http2.streamId).getOrElse(Http2Compliance.missingHttpIdHeaderException)
responseOut.sendNext(HPackSpecExamples.FirstResponse.addAttribute(Http2.streamId, streamId))
val headerPayload = expectHeaderBlock(1)
headerPayload shouldBe HPackSpecExamples.C61FirstResponseWithHuffman
}
"fail if Http2StreamIdHeader missing" in pending
"automatically add `Date` header" in pending
"parse headers to modeled headers" inAssertAllStagesStopped new TestSetup with RequestResponseProbes with Http2FrameHpackSupport {
import CacheDirectives._
import headers._
val expectedRequest = HttpRequest(
method = HttpMethods.GET,
uri = "http://www.example.com/",
headers = Vector(`Cache-Control`(`no-cache`), `Cache-Control`(`max-age`(1000)), `Access-Control-Allow-Origin`.`*`),
protocol = HttpProtocols.`HTTP/2.0`)
val streamId = 1
val requestHeaderBlock = encodeRequestHeaders(HttpRequest(
method = HttpMethods.GET,
uri = "http://www.example.com/",
headers = Vector(
RawHeader("cache-control", "no-cache"),
RawHeader("cache-control", "max-age=1000"),
RawHeader("access-control-allow-origin", "*")),
protocol = HttpProtocols.`HTTP/2.0`))
sendHEADERS(streamId, endStream = true, endHeaders = true, requestHeaderBlock)
expectRequest().headers shouldBe expectedRequest.headers
}
"acknowledge change to SETTINGS_HEADER_TABLE_SIZE in next HEADER frame" inAssertAllStagesStopped new TestSetup with RequestResponseProbes {
sendSETTING(SettingIdentifier.SETTINGS_HEADER_TABLE_SIZE, 8192)
expectSettingsAck()
val headerBlock = HPackSpecExamples.C41FirstRequestWithHuffman
sendHEADERS(1, endStream = true, endHeaders = true, headerBlock)
requestIn.ensureSubscription()
requestIn.expectNoMessage(100.millis)
val request = expectRequestRaw()
request.method shouldBe HttpMethods.GET
request.uri shouldBe Uri("http://www.example.com/")
val streamId = request.attribute(Http2.streamId).getOrElse(Http2Compliance.missingHttpIdHeaderException)
responseOut.sendNext(HPackSpecExamples.FirstResponse.addAttribute(Http2.streamId, streamId))
val headerPayload = expectHeaderBlock(1)
// Dynamic Table Size Update (https://tools.ietf.org/html/rfc7541#section-6.3) is
//
// 0 1 2 3 4 5 6 7
// +---+---+---+---+---+---+---+---+
// | 0 | 0 | 1 | Max size (5+) |
// +---+---------------------------+
//
// 8192 is 10000000000000 = 14 bits, i.e. needs more than 4 bits
// 8192 - 16 = 8176 = 111111 1110000
// 001 11111 = 63
// 1 1110000 = 225
// 0 0111111 = 63
val dynamicTableUpdateTo8192 = ByteString(63, 225, 63)
headerPayload shouldBe dynamicTableUpdateTo8192 ++ HPackSpecExamples.C61FirstResponseWithHuffman
}
}
abstract class RequestEntityTestSetup extends TestSetup with RequestResponseProbes with Http2FrameHpackSupport {
val TheStreamId = 1
protected def sendRequest(): Unit
sendRequest()
val receivedRequest = expectRequest()
val entityDataIn = ByteStringSinkProbe()
receivedRequest.entity.dataBytes.runWith(entityDataIn.sink)
entityDataIn.ensureSubscription()
}
abstract class WaitingForRequest(request: HttpRequest) extends RequestEntityTestSetup {
protected def sendRequest(): Unit = sendRequest(TheStreamId, request)
}
abstract class WaitingForRequestData extends RequestEntityTestSetup {
lazy val request = HttpRequest(method = HttpMethods.POST, uri = "https://example.com/upload", protocol = HttpProtocols.`HTTP/2.0`)
protected def sendRequest(): Unit =
sendRequestHEADERS(TheStreamId, request, endStream = false)
def sendWindowFullOfData(): Int = {
val dataLength = remainingToServerWindowFor(TheStreamId)
sendDATA(TheStreamId, endStream = false, ByteString(Array.fill[Byte](dataLength)(23)))
dataLength
}
}
"support stream for request entity data" should {
"send data frames to entity stream" inAssertAllStagesStopped new WaitingForRequestData {
val data1 = ByteString("abcdef")
sendDATA(TheStreamId, endStream = false, data1)
entityDataIn.expectBytes(data1)
val data2 = ByteString("zyxwvu")
sendDATA(TheStreamId, endStream = false, data2)
entityDataIn.expectBytes(data2)
val data3 = ByteString("mnopq")
sendDATA(TheStreamId, endStream = true, data3)
entityDataIn.expectBytes(data3)
entityDataIn.expectComplete()
}
"handle content-length and content-type of incoming request" inAssertAllStagesStopped new WaitingForRequest(
HttpRequest(
method = HttpMethods.POST,
uri = "https://example.com/upload",
entity = HttpEntity(ContentTypes.`application/json`, 1337, Source.repeat("x").take(1337).map(ByteString(_))),
protocol = HttpProtocols.`HTTP/2.0`)) {
receivedRequest.entity.contentType should ===(ContentTypes.`application/json`)
receivedRequest.entity.isIndefiniteLength should ===(false)
receivedRequest.entity.contentLengthOption should ===(Some(1337L))
entityDataIn.expectBytes(ByteString("x" * 1337))
entityDataIn.expectComplete()
}
"fail entity stream if peer sends RST_STREAM frame" inAssertAllStagesStopped new WaitingForRequestData {
val data1 = ByteString("abcdef")
sendDATA(TheStreamId, endStream = false, data1)
entityDataIn.expectBytes(data1)
sendRST_STREAM(TheStreamId, ErrorCode.INTERNAL_ERROR)
val error = entityDataIn.expectError()
error.getMessage shouldBe "Stream with ID [1] was closed by peer with code INTERNAL_ERROR(0x02)"
}
// Reproducing https://github.com/akka/akka-http/issues/2957
"close the stream when we receive a RST after we have half-closed ourselves as well" inAssertAllStagesStopped new WaitingForRequestData {
// Client sends the request, but doesn't close the stream yet. This is a bit weird, but it's whet grpcurl does ;)
sendDATA(streamId = TheStreamId, endStream = false, ByteString(0, 0, 0, 0, 0x10, 0x22, 0x0e) ++ ByteString.fromString("GreeterService"))
// We emit a 404 response, half-closing the stream.
emitResponse(streamId = TheStreamId, HttpResponse(StatusCodes.NotFound))
// The client closes the stream with a protocol error. This is somewhat questionable but it's what grpc-go does
sendRST_STREAM(streamId = TheStreamId, ErrorCode.PROTOCOL_ERROR)
entityDataIn.expectError()
// Wait to give the warning (that we hope not to see) time to pop up.
Thread.sleep(100)
}
"not fail the whole connection when one stream is RST twice" inAssertAllStagesStopped new WaitingForRequestData {
sendRST_STREAM(TheStreamId, ErrorCode.STREAM_CLOSED)
val error = entityDataIn.expectError()
error.getMessage shouldBe "Stream with ID [1] was closed by peer with code STREAM_CLOSED(0x05)"
expectNoBytes(100.millis)
// https://http2.github.io/http2-spec/#StreamStates
// Endpoints MUST ignore WINDOW_UPDATE or RST_STREAM frames received in this state,
sendRST_STREAM(TheStreamId, ErrorCode.STREAM_CLOSED)
expectNoBytes(100.millis)
}
"not fail the whole connection when data frames are received after stream was cancelled" inAssertAllStagesStopped new WaitingForRequestData {
entityDataIn.cancel()
expectRST_STREAM(TheStreamId)
sendDATA(TheStreamId, endStream = false, ByteString("test"))
// should just be ignored, especially no GOAWAY frame should be sent in response
expectNoBytes(100.millis)
}
"send RST_STREAM if entity stream is canceled" inAssertAllStagesStopped new WaitingForRequestData {
val data1 = ByteString("abcdef")
sendDATA(TheStreamId, endStream = false, data1)
entityDataIn.expectBytes(data1)
pollForWindowUpdates(10.millis)
entityDataIn.cancel()
expectRST_STREAM(TheStreamId, ErrorCode.CANCEL)
}
"send out WINDOW_UPDATE frames when request data is read so that the stream doesn't stall" inAssertAllStagesStopped new WaitingForRequestData {
(1 to 10).foreach { _ =>
val bytesSent = sendWindowFullOfData()
bytesSent should be > 0
entityDataIn.expectBytes(bytesSent)
pollForWindowUpdates(10.millis)
remainingToServerWindowFor(TheStreamId) should be > 0
}
}
"backpressure until request entity stream is read (don't send out unlimited WINDOW_UPDATE before)" inAssertAllStagesStopped new WaitingForRequestData {
var totallySentBytes = 0
// send data until we don't receive any window updates from the implementation any more
eventually(Timeout(1.second.dilated)) {
totallySentBytes += sendWindowFullOfData()
// the implementation may choose to send a few window update until internal buffers are filled
pollForWindowUpdates(10.millis)
remainingToServerWindowFor(TheStreamId) shouldBe 0
}
// now drain entity source
entityDataIn.expectBytes(totallySentBytes)
eventually(Timeout(1.second.dilated)) {
pollForWindowUpdates(10.millis)
remainingToServerWindowFor(TheStreamId) should be > 0
}
}
"send data frames to entity stream and ignore trailing headers" inAssertAllStagesStopped new WaitingForRequestData {
val data1 = ByteString("abcdef")
sendDATA(TheStreamId, endStream = false, data1)
entityDataIn.expectBytes(data1)
sendHEADERS(TheStreamId, endStream = true, Seq(headers.`Cache-Control`(CacheDirectives.`no-cache`)))
entityDataIn.expectComplete()
}
"fail if more data is received than connection window allows" inAssertAllStagesStopped new WaitingForRequestData {
sendFrame(DataFrame(TheStreamId, endStream = false, ByteString("0" * 100000)))
val (_, errorCode) = expectGOAWAY()
errorCode shouldEqual ErrorCode.FLOW_CONTROL_ERROR
}
"fail if more data is received than stream-level window allows" inAssertAllStagesStopped new WaitingForRequestData {
// trigger a connection-level WINDOW_UPDATE
sendDATA(TheStreamId, endStream = false, ByteString("0000"))
entityDataIn.expectUtf8EncodedString("0000")
pollForWindowUpdates(500.millis) // window resize/update triggered
sendFrame(DataFrame(TheStreamId, endStream = false, ByteString("0" * 512001))) // more than default `incoming-stream-level-buffer-size = 512kB`
expectRST_STREAM(TheStreamId, ErrorCode.FLOW_CONTROL_ERROR)
}
"not leak stream if request entity is not fully pulled when connection dies" inAssertAllStagesStopped new WaitingForRequestData {
sendDATA(TheStreamId, endStream = false, ByteString("0000"))
entityDataIn.expectUtf8EncodedString("0000")
pollForWindowUpdates(500.millis)
sendDATA(TheStreamId, endStream = false, ByteString("1111"))
sendDATA(TheStreamId, endStream = true, ByteString.empty)
// DATA is left in IncomingStreamBuffer because we never pulled
// test infra closes connection
}
"fail if DATA frame arrives after incoming stream has already been closed (before response was sent)" inAssertAllStagesStopped new WaitingForRequestData {
sendDATA(TheStreamId, endStream = false, ByteString("0000"))
entityDataIn.expectUtf8EncodedString("0000")
pollForWindowUpdates(500.millis)
sendDATA(TheStreamId, endStream = false, ByteString("1111"))
sendDATA(TheStreamId, endStream = true, ByteString.empty) // close stream
// now send more DATA: checks that we have moved into a state where DATA is not expected any more
sendDATA(TheStreamId, endStream = false, ByteString("more data"))
val (_, errorCode) = expectGOAWAY()
errorCode shouldEqual ErrorCode.PROTOCOL_ERROR
}
"fail entity stream if advertised content-length doesn't match" in pending
}
"support stream support for sending response entity data" should {
abstract class WaitingForResponseSetup extends TestSetup with RequestResponseProbes with Http2FrameHpackSupport {
val TheStreamId = 1
val theRequest = HttpRequest(protocol = HttpProtocols.`HTTP/2.0`)
sendRequest(TheStreamId, theRequest)
expectRequest() shouldBe theRequest
}
abstract class WaitingForResponseDataSetup extends WaitingForResponseSetup {
val entityDataOut = TestPublisher.probe[ByteString]()
val response = HttpResponse(entity = HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(entityDataOut)))
emitResponse(TheStreamId, response)
expectDecodedHEADERS(streamId = TheStreamId, endStream = false) shouldBe response.withEntity(HttpEntity.Empty.withContentType(ContentTypes.`application/octet-stream`))
}
"encode Content-Length and Content-Type headers" inAssertAllStagesStopped new WaitingForResponseSetup {
val response = HttpResponse(entity = HttpEntity(ContentTypes.`application/octet-stream`, ByteString("abcde")))
emitResponse(TheStreamId, response)
val pairs = expectDecodedResponseHEADERSPairs(streamId = TheStreamId, endStream = false).toMap
pairs should contain(":status" -> "200")
pairs should contain("content-length" -> "5")
pairs should contain("content-type" -> "application/octet-stream")
}
"send entity data as data frames" inAssertAllStagesStopped new WaitingForResponseDataSetup {
val data1 = ByteString("abcd")
entityDataOut.sendNext(data1)
expectDATA(TheStreamId, endStream = false, data1)
val data2 = ByteString("efghij")
entityDataOut.sendNext(data2)
expectDATA(TheStreamId, endStream = false, data2)
entityDataOut.sendComplete()
expectDATA(TheStreamId, endStream = true, ByteString.empty)
}
"parse priority frames" inAssertAllStagesStopped new WaitingForResponseDataSetup {
sendPRIORITY(TheStreamId, true, 0, 5)
entityDataOut.sendComplete()
expectDATA(TheStreamId, endStream = true, ByteString.empty)
}
"cancel entity data source when peer sends RST_STREAM" inAssertAllStagesStopped new WaitingForResponseDataSetup {
val data1 = ByteString("abcd")
entityDataOut.sendNext(data1)
expectDATA(TheStreamId, endStream = false, data1)
sendRST_STREAM(TheStreamId, ErrorCode.CANCEL)
entityDataOut.expectCancellation()
}
"handle RST_STREAM while data is waiting in outgoing stream buffer" inAssertAllStagesStopped new WaitingForResponseDataSetup {
val data1 = ByteString("abcd")
entityDataOut.sendNext(data1)
sendRST_STREAM(TheStreamId, ErrorCode.CANCEL)
entityDataOut.expectCancellation()
toNet.expectNoBytes(100.millis) // the whole stage failed with bug #2236
}
"handle WINDOW_UPDATE correctly when received before started sending out response and while receiving request data" inAssertAllStagesStopped new WaitingForRequestData {
val bytesToSend = 70000 // > Http2Protocol.InitialWindowSize
val missingWindow = bytesToSend - Http2Protocol.InitialWindowSize
require(missingWindow >= 0)
// add missing window space immediately to both connection- and stream-level window
sendWINDOW_UPDATE(0, missingWindow)
sendWINDOW_UPDATE(TheStreamId, missingWindow)
val entityDataOut = TestPublisher.probe[ByteString]()
val response = HttpResponse(entity = HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(entityDataOut)))
emitResponse(TheStreamId, response)
expectDecodedHEADERS(streamId = TheStreamId, endStream = false) shouldBe response.withEntity(HttpEntity.Empty.withContentType(ContentTypes.`application/octet-stream`))
entityDataOut.sendNext(bytes(bytesToSend, 0x23))
expectDATA(TheStreamId, false, bytesToSend)
entityDataOut.sendComplete()
expectDATA(TheStreamId, true, 0)
}
"handle WINDOW_UPDATE correctly when received before started sending out response" inAssertAllStagesStopped new WaitingForResponseSetup {
val bytesToSend = 70000 // > Http2Protocol.InitialWindowSize
val missingWindow = bytesToSend - Http2Protocol.InitialWindowSize
require(missingWindow >= 0)
// add missing window space immediately to both connection- and stream-level window
sendWINDOW_UPDATE(0, missingWindow)
sendWINDOW_UPDATE(TheStreamId, missingWindow)
val entityDataOut = TestPublisher.probe[ByteString]()
val response = HttpResponse(entity = HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(entityDataOut)))
emitResponse(TheStreamId, response)
expectDecodedHEADERS(streamId = TheStreamId, endStream = false) shouldBe response.withEntity(HttpEntity.Empty.withContentType(ContentTypes.`application/octet-stream`))
entityDataOut.sendNext(bytes(bytesToSend, 0x23))
expectDATA(TheStreamId, false, bytesToSend)
entityDataOut.sendComplete()
expectDATA(TheStreamId, true, 0)
}
"distribute increases to SETTINGS_INITIAL_WINDOW_SIZE to streams correctly while sending out response" inAssertAllStagesStopped new WaitingForResponseDataSetup {
// changes to SETTINGS_INITIAL_WINDOW_SIZE need to be distributed to active streams: https://httpwg.org/specs/rfc7540.html#InitialWindowSize
val bytesToSend = 70000 // > Http2Protocol.InitialWindowSize
val missingWindow = bytesToSend - Http2Protocol.InitialWindowSize
require(missingWindow >= 0)
// SETTINGS_INITIAL_WINDOW_SIZE only has ab effect on stream-level window, so we give the connection-level
// window enough room immediately
sendWINDOW_UPDATE(0, missingWindow)
entityDataOut.sendNext(bytes(bytesToSend, 0x23))
expectDATA(TheStreamId, false, Http2Protocol.InitialWindowSize)
expectNoBytes(100.millis)
// now increase SETTINGS_INITIAL_WINDOW_SIZE so that all data fits into WINDOW
sendSETTING(Http2Protocol.SettingIdentifier.SETTINGS_INITIAL_WINDOW_SIZE, bytesToSend)
updateFromServerWindows(TheStreamId, _ + missingWindow) // test probe doesn't automatically update window
expectDATA(TheStreamId, false, missingWindow)
expectSettingsAck() // FIXME: bug: we must send ACK before making use of the new setting, see https://github.com/akka/akka-http/issues/3553
entityDataOut.sendComplete()
expectDATA(TheStreamId, true, 0)
}
"handle RST_STREAM while waiting for a window update" inAssertAllStagesStopped new WaitingForResponseDataSetup {
entityDataOut.sendNext(bytes(70000, 0x23)) // 70000 > Http2Protocol.InitialWindowSize
sendWINDOW_UPDATE(TheStreamId, 10000) // enough window for the stream but not for the window
expectDATA(TheStreamId, false, Http2Protocol.InitialWindowSize)
// enough stream-level WINDOW, but too little connection-level WINDOW
expectNoBytes(100.millis)
// now the demuxer is in the WaitingForConnectionWindow state, cancel the connection
sendRST_STREAM(TheStreamId, ErrorCode.CANCEL)
entityDataOut.expectCancellation()
expectNoBytes(100.millis)
// now increase connection-level window again and see if everything still works
sendWINDOW_UPDATE(0, 10000)
expectNoBytes(100.millis) // don't expect anything, stream has been cancelled in the meantime
}
"cancel entity data source when peer sends RST_STREAM before entity is subscribed" inAssertAllStagesStopped new TestSetup with RequestResponseProbes with Http2FrameHpackSupport {
val theRequest = HttpRequest(protocol = HttpProtocols.`HTTP/2.0`)
sendRequest(1, theRequest)
expectRequest() shouldBe theRequest
sendRST_STREAM(1, ErrorCode.CANCEL)
val entityDataOut = TestPublisher.probe[ByteString]()
val response = HttpResponse(entity = HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(entityDataOut)))
emitResponse(1, response)
expectNoBytes(100.millis) // don't expect response on closed connection
entityDataOut.expectCancellation()
}
"send RST_STREAM when entity data stream fails" inAssertAllStagesStopped new WaitingForResponseDataSetup {
val data1 = ByteString("abcd")
entityDataOut.sendNext(data1)
expectDATA(TheStreamId, endStream = false, data1)
class MyProblem extends RuntimeException
EventFilter[MyProblem](pattern = "Substream 1 failed with .*", occurrences = 1).intercept {
entityDataOut.sendError(new MyProblem)
expectRST_STREAM(1, ErrorCode.INTERNAL_ERROR)
}
}
"fail if advertised content-length doesn't match" in pending
"send data frame with exactly the number of remaining connection-level window bytes even when chunk is bigger than that" inAssertAllStagesStopped new WaitingForResponseDataSetup {
// otherwise, the stream may stall if the client doesn't send another window update (which it isn't required to do
// unless a window falls to 0)
entityDataOut.sendNext(bytes(70000, 0x23)) // 70000 > Http2Protocol.InitialWindowSize
expectDATA(TheStreamId, false, Http2Protocol.InitialWindowSize)
expectNoBytes(100.millis)
sendWINDOW_UPDATE(TheStreamId, 10000) // > than the remaining bytes (70000 - InitialWindowSize)
sendWINDOW_UPDATE(0, 10000)
expectDATA(TheStreamId, false, 70000 - Http2Protocol.InitialWindowSize)
}
"backpressure response entity stream until WINDOW_UPDATE was received" inAssertAllStagesStopped new WaitingForResponseDataSetup {
var totalSentBytes = 0
var totalReceivedBytes = 0
entityDataOut.ensureSubscription()
def receiveData(maxBytes: Int = Int.MaxValue): Unit = {
val (false, data) = expectDATAFrame(TheStreamId)
totalReceivedBytes += data.size
}
def sendAWindow(): Unit = {
val window = remainingFromServerWindowFor(TheStreamId)
val dataToSend = window max 60000 // send at least 10 bytes
entityDataOut.sendNext(bytes(dataToSend, 0x42))
totalSentBytes += dataToSend
if (window > 0) receiveData(window)
}
/**
* Loop that checks for a while that publisherProbe has outstanding demand and runs body to fulfill it
* Will fail if there's still demand after the timeout.
*/
def fulfillDemandWithin(publisherProbe: TestPublisher.Probe[_], timeout: FiniteDuration)(body: => Unit): Unit = {
// HACK to support `expectRequest` with a timeout
def within[T](publisherProbe: TestPublisher.Probe[_], dur: FiniteDuration)(t: => T): T = {
val field = classOf[ManualProbe[_]].getDeclaredField("probe")
field.setAccessible(true)
field.get(publisherProbe).asInstanceOf[TestProbe].within(dur)(t)
}
def expectRequest(timeout: FiniteDuration): Long =
within(publisherProbe, timeout)(publisherProbe.expectRequest())
eventually(Timeout(timeout)) {
while (publisherProbe.pending > 0) body
try expectRequest(10.millis.dilated)
catch {
case ex: Throwable => // ignore error here
}
publisherProbe.pending shouldBe 0 // fail here if there's still demand after the timeout
}
}
fulfillDemandWithin(entityDataOut, 3.seconds.dilated)(sendAWindow())
sendWINDOW_UPDATE(TheStreamId, totalSentBytes)
sendWINDOW_UPDATE(0, totalSentBytes)
while (totalReceivedBytes < totalSentBytes)
receiveData()
// we must get at least a bit of demand
entityDataOut.sendNext(bytes(1000, 0x23))
}
"give control frames priority over pending data frames" inAssertAllStagesStopped new WaitingForResponseDataSetup {
val responseDataChunk = bytes(1000, 0x42)
// send data first but expect it to be queued because of missing demand
entityDataOut.sendNext(responseDataChunk)
// no receive a PING frame which should be answered with a PING(ack = true) frame
val pingData = bytes(8, 0x23)
sendFrame(PingFrame(ack = false, pingData))
// now expect PING ack frame to "overtake" the data frame
expectFrame(FrameType.PING, Flags.ACK, 0, pingData)
expectDATA(TheStreamId, endStream = false, responseDataChunk)
}
"support trailing headers for chunked responses" inAssertAllStagesStopped new WaitingForResponseSetup {
val response = HttpResponse(entity = HttpEntity.Chunked(
ContentTypes.`application/octet-stream`,
Source(List(
HttpEntity.Chunk("foo"),
HttpEntity.Chunk("bar"),
HttpEntity.LastChunk(trailer = immutable.Seq[HttpHeader](RawHeader("Status", "grpc-status 10")))
))
))
emitResponse(TheStreamId, response)
expectDecodedHEADERS(streamId = TheStreamId, endStream = false)
expectDATA(TheStreamId, endStream = false, ByteString("foobar"))
expectDecodedHEADERS(streamId = TheStreamId).headers should be(immutable.Seq(RawHeader("status", "grpc-status 10")))
}
"include the trailing headers even when the buffer is emptied before sending the last chunk" inAssertAllStagesStopped new WaitingForResponseSetup {
val queuePromise = Promise[SourceQueueWithComplete[HttpEntity.ChunkStreamPart]]()
val response = HttpResponse(entity = HttpEntity.Chunked(
ContentTypes.`application/octet-stream`,
Source.queue[HttpEntity.ChunkStreamPart](100, OverflowStrategy.fail)
.mapMaterializedValue(queuePromise.success(_))
))
emitResponse(TheStreamId, response)
val chunkQueue = Await.result(queuePromise.future, 10.seconds)
chunkQueue.offer(HttpEntity.Chunk("foo"))
chunkQueue.offer(HttpEntity.Chunk("bar"))
expectDecodedHEADERS(streamId = TheStreamId, endStream = false)
expectDATA(TheStreamId, endStream = false, ByteString("foobar"))
chunkQueue.offer(HttpEntity.LastChunk(trailer = immutable.Seq[HttpHeader](RawHeader("Status", "grpc-status 10"))))
chunkQueue.complete()
expectDecodedHEADERS(streamId = TheStreamId).headers should be(immutable.Seq(RawHeader("status", "grpc-status 10")))
}
"send the trailing headers immediately, even when the stream window is depleted" inAssertAllStagesStopped new WaitingForResponseSetup {
val queuePromise = Promise[SourceQueueWithComplete[HttpEntity.ChunkStreamPart]]()
val response = HttpResponse(entity = HttpEntity.Chunked(
ContentTypes.`application/octet-stream`,
Source.queue[HttpEntity.ChunkStreamPart](100, OverflowStrategy.fail)
.mapMaterializedValue(queuePromise.success(_))
))
emitResponse(TheStreamId, response)
val chunkQueue = Await.result(queuePromise.future, 10.seconds)
def depleteWindow(): Unit = {
val toSend: Int = remainingFromServerWindowFor(TheStreamId) min 1000
if (toSend != 0) {
val data = "x" * toSend
Await.result(chunkQueue.offer(HttpEntity.Chunk(data)), 3.seconds)
expectDATA(TheStreamId, endStream = false, ByteString(data))
depleteWindow()
}
}
expectDecodedHEADERS(streamId = TheStreamId, endStream = false)
depleteWindow()
chunkQueue.offer(HttpEntity.LastChunk(trailer = immutable.Seq[HttpHeader](RawHeader("grpc-status", "10"))))
chunkQueue.complete()
expectDecodedHEADERS(streamId = TheStreamId, endStream = true).headers should be(immutable.Seq(RawHeader("grpc-status", "10")))
}
"send the trailing headers even when last data chunk was delayed by window depletion" inAssertAllStagesStopped new WaitingForResponseSetup {
val queuePromise = Promise[SourceQueueWithComplete[HttpEntity.ChunkStreamPart]]()
val response = HttpResponse(entity = HttpEntity.Chunked(
ContentTypes.`application/octet-stream`,
Source.queue[HttpEntity.ChunkStreamPart](100, OverflowStrategy.fail)
.mapMaterializedValue(queuePromise.success(_))
))
emitResponse(TheStreamId, response)
val chunkQueue = Await.result(queuePromise.future, 10.seconds)
def depleteWindow(): Unit = {
val toSend: Int = remainingFromServerWindowFor(TheStreamId) min 1000
if (toSend != 0) {
val data = "x" * toSend
Await.result(chunkQueue.offer(HttpEntity.Chunk(data)), 3.seconds)
expectDATA(TheStreamId, endStream = false, ByteString(data))
depleteWindow()
}
}
expectDecodedHEADERS(streamId = TheStreamId, endStream = false)
depleteWindow()
val lastData = ByteString("y" * 500)
chunkQueue.offer(HttpEntity.Chunk(lastData)) // even out of connection window try to send one last chunk that will be buffered
chunkQueue.offer(HttpEntity.LastChunk(trailer = immutable.Seq[HttpHeader](RawHeader("grpc-status", "10"))))
chunkQueue.complete()
toNet.request(1)
// now increase windows somewhat but not over the buffered amount
sendWINDOW_UPDATE(TheStreamId, 100)
sendWINDOW_UPDATE(0, 100)
expectDATA(TheStreamId, endStream = false, lastData.take(100))
// now send the remaining data
sendWINDOW_UPDATE(TheStreamId, 1000)
sendWINDOW_UPDATE(0, 1000)
expectDATA(TheStreamId, endStream = false, lastData.drop(100))
expectDecodedHEADERS(streamId = TheStreamId, endStream = true).headers should be(immutable.Seq(RawHeader("grpc-status", "10")))
}
}
"support multiple concurrent substreams" should {
"receive two requests concurrently" inAssertAllStagesStopped new TestSetup with RequestResponseProbes with Http2FrameHpackSupport {
val request1 =
HttpRequest(
protocol = HttpProtocols.`HTTP/2.0`,
entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, ""))
sendRequestHEADERS(1, request1, endStream = false)
val gotRequest1 = expectRequest()
gotRequest1.withEntity(HttpEntity.Empty) shouldBe request1.withEntity(HttpEntity.Empty)
val request1EntityProbe = ByteStringSinkProbe()
gotRequest1.entity.dataBytes.runWith(request1EntityProbe.sink)
val request2 =
HttpRequest(
protocol = HttpProtocols.`HTTP/2.0`,
entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, ""))
sendRequestHEADERS(3, request2, endStream = false)
val gotRequest2 = expectRequest()
gotRequest2.withEntity(HttpEntity.Empty) shouldBe request2.withEntity(HttpEntity.Empty)
val request2EntityProbe = ByteStringSinkProbe()
gotRequest2.entity.dataBytes.runWith(request2EntityProbe.sink)
sendDATA(3, endStream = false, ByteString("abc"))
request2EntityProbe.expectUtf8EncodedString("abc")
sendDATA(1, endStream = false, ByteString("def"))
request1EntityProbe.expectUtf8EncodedString("def")
// now fail stream 2
//sendRST_STREAM(3, ErrorCode.INTERNAL_ERROR)
//request2EntityProbe.expectError()
// make sure that other stream is not affected
sendDATA(1, endStream = true, ByteString("ghi"))
request1EntityProbe.expectUtf8EncodedString("ghi")
request1EntityProbe.expectComplete()
}
"send two responses concurrently" inAssertAllStagesStopped new TestSetup with RequestResponseProbes with Http2FrameHpackSupport {
val theRequest = HttpRequest(protocol = HttpProtocols.`HTTP/2.0`)
sendRequest(1, theRequest)
expectRequest() shouldBe theRequest
val entity1DataOut = TestPublisher.probe[ByteString]()
val response1 = HttpResponse(entity = HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(entity1DataOut)))
emitResponse(1, response1)
expectDecodedHEADERS(streamId = 1, endStream = false) shouldBe response1.withEntity(HttpEntity.Empty.withContentType(ContentTypes.`application/octet-stream`))
def sendDataAndExpectOnNet(outStream: TestPublisher.Probe[ByteString], streamId: Int, dataString: String, endStream: Boolean = false): Unit = {
val data = ByteString(dataString)
if (dataString.nonEmpty) outStream.sendNext(data)
if (endStream) outStream.sendComplete()
if (data.nonEmpty || endStream) expectDATA(streamId, endStream = endStream, data)
}
sendDataAndExpectOnNet(entity1DataOut, 1, "abc")
// send second request
sendRequest(3, theRequest)
expectRequest() shouldBe theRequest
val entity2DataOut = TestPublisher.probe[ByteString]()
val response2 = HttpResponse(entity = HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(entity2DataOut)))
emitResponse(3, response2)
expectDecodedHEADERS(streamId = 3, endStream = false) shouldBe response2.withEntity(HttpEntity.Empty.withContentType(ContentTypes.`application/octet-stream`))
// send again on stream 1
sendDataAndExpectOnNet(entity1DataOut, 1, "zyx")
// now send on stream 2
sendDataAndExpectOnNet(entity2DataOut, 3, "mnopq")
// now again on stream 1
sendDataAndExpectOnNet(entity1DataOut, 1, "jklm")
// send two data bits first but only pull and expect later
entity1DataOut.sendNext(ByteString("hihihi"))
entity2DataOut.sendNext(ByteString("hohoho"))
expectDATA(1, endStream = false, ByteString("hihihi"))
expectDATA(3, endStream = false, ByteString("hohoho"))
// last data of stream 2
sendDataAndExpectOnNet(entity2DataOut, 3, "uvwx", endStream = true)
// also complete stream 1
sendDataAndExpectOnNet(entity1DataOut, 1, "", endStream = true)
}
"close substreams when connection is shutting down" inAssertAllStagesStopped StreamTestKit.assertAllStagesStopped(new TestSetup with RequestResponseProbes with Http2FrameHpackSupport {
val requestEntity = HttpEntity.Empty.withContentType(ContentTypes.`application/octet-stream`)
val request = HttpRequest(entity = requestEntity)
sendRequestHEADERS(1, request, false)
val req = expectRequest()
val reqProbe = ByteStringSinkProbe()
req.entity.dataBytes.runWith(reqProbe.sink)
val responseEntityProbe = TestPublisher.probe[ByteString]()
val responseEntity = HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(responseEntityProbe))
val response = HttpResponse(200, entity = responseEntity)
emitResponse(1, response)
expectDecodedHEADERS(1, false)
// check data flow for request entity
sendDATA(1, false, ByteString("ping"))
reqProbe.expectUtf8EncodedString("ping")
// default settings will schedule a connection and a stream-level window update
expectWindowUpdate()
expectWindowUpdate()
// check data flow for response entity
responseEntityProbe.sendNext(ByteString("pong"))
expectDATA(1, false, ByteString("pong"))
fromNet.sendError(new RuntimeException("Connection broke"))
// now all stream stages should be closed
reqProbe.expectError().getMessage shouldBe "The HTTP/2 connection was shut down while the request was still ongoing"
responseEntityProbe.expectCancellation()
})
}
"respect flow-control" should {
"not exceed connection-level window while sending" in pending
"not exceed stream-level window while sending" in pending
"not exceed stream-level window while sending after SETTINGS_INITIAL_WINDOW_SIZE changed" in pending
"not exceed stream-level window while sending after SETTINGS_INITIAL_WINDOW_SIZE changed when window became negative through setting" in pending
"eventually send WINDOW_UPDATE frames for received data" in pending
"reject WINDOW_UPDATE for connection with zero increment with PROTOCOL_ERROR" inAssertAllStagesStopped new TestSetup with RequestResponseProbes {
sendWINDOW_UPDATE(0, 0) // illegal
val (_, errorCode) = expectGOAWAY()
errorCode should ===(ErrorCode.PROTOCOL_ERROR)
}
"reject WINDOW_UPDATE for stream with zero increment with PROTOCOL_ERROR" inAssertAllStagesStopped new TestSetup with RequestResponseProbes {
// making sure we don't handle stream 0 and others differently here
sendHEADERS(1, endStream = false, endHeaders = true, HPackSpecExamples.C41FirstRequestWithHuffman)
sendWINDOW_UPDATE(1, 0) // illegal
expectRST_STREAM(1, ErrorCode.PROTOCOL_ERROR)
}
"backpressure incoming frames when outgoing control frame buffer fills" inAssertAllStagesStopped new TestSetup with HandlerFunctionSupport {
override def settings: ServerSettings = super.settings.mapHttp2Settings(_.withOutgoingControlFrameBufferSize(1))
sendFrame(PingFrame(false, ByteString("abcdefgh")))
// now one PING ack buffered
// this one fills the input buffer between the probe and the server
sendFrame(PingFrame(false, ByteString("abcdefgh")))
// now there should be no new demand
fromNet.pending shouldEqual 0
fromNet.expectNoMessage(100.millis)
}
}
"respect settings" should {
"initial MAX_FRAME_SIZE" in pending
"received non-zero length payload Settings with ACK flag (invalid 6.5)" inAssertAllStagesStopped new TestSetup with RequestResponseProbes {
/*
Receipt of a SETTINGS frame with the ACK flag set and a length field value other than 0
MUST be treated as a connection error (Section 5.4.1) of type FRAME_SIZE_ERROR.
*/
// we ACK the settings with an incorrect ACK (it must not have a payload)
val ackFlag = new ByteFlag(0x1)
val illegalPayload = hex"cafe babe"
sendFrame(FrameType.SETTINGS, ackFlag, 0, illegalPayload)
val (_, error) = expectGOAWAY()
error should ===(ErrorCode.FRAME_SIZE_ERROR)
}
"received SETTINGS frame with a length other than a multiple of 6 octets (invalid 6_5)" inAssertAllStagesStopped new TestSetup with RequestResponseProbes {
val data = hex"00 00 02 04 00 00 00 00 00"
sendFrame(FrameType.SETTINGS, ByteFlag.Zero, 0, data)
val (_, error) = expectGOAWAY()
error should ===(ErrorCode.FRAME_SIZE_ERROR)
}
"received SETTINGS_MAX_FRAME_SIZE should cause outgoing DATA to be chunked up into at-most-that-size parts " inAssertAllStagesStopped new TestSetup with RequestResponseProbes {