httpwg 0.2.7

Test cases for RFC 9113 (HTTP/2)
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
//! Section 6: Frame Definitions

use buffet::{IntoHalves, Piece};
use enumflags2::BitFlags;
use loona_h2::{
    ContinuationFlags, Frame, FrameType, GoAway, HeadersFlags, IntoPiece, KnownErrorCode,
    PrioritySpec, Setting, SettingPairs, SettingsFlags, StreamId,
};

use crate::{dummy_bytes, Conn, ErrorC, FrameT};

//---- Section 6.1: DATA

/// DATA frames MUST be associated with a stream. If a DATA frame is
/// received whose stream identifier field is 0x0, the recipient
/// MUST respond with a connection error (Section 5.4.1) of type
/// PROTOCOL_ERROR.
pub async fn sends_data_frame_with_zero_stream_id<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_data(StreamId::CONNECTION, true, b"test").await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// If a DATA frame is received whose stream is not in "open" or
/// "half-closed (local)" state, the recipient MUST respond with
/// a stream error (Section 5.4.2) of type STREAM_CLOSED.
///
/// Note: This test case is duplicated with 5.1.
pub async fn sends_data_frame_on_invalid_stream_state<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;
    conn.write_headers(
        stream_id,
        HeadersFlags::EndStream | HeadersFlags::EndHeaders,
        block_fragment,
    )
    .await?;

    conn.write_data(stream_id, true, b"test").await?;

    conn.verify_stream_error(ErrorC::StreamClosed).await?;

    Ok(())
}

/// If the length of the padding is the length of the frame payload
/// or greater, the recipient MUST treat this as a connection error
/// (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_data_frame_with_invalid_pad_length<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let mut headers = conn.common_headers("POST");
    headers.append("content-length", "4");
    let block_fragment = conn.encode_headers(&headers)?;

    conn.write_headers(stream_id, HeadersFlags::EndHeaders, block_fragment)
        .await?;

    // DATA frame:
    // frame length: 5, pad length: 6
    conn.send(b"\x00\x00\x05\x00\x09\x00\x00\x00\x01").await?;
    conn.send(b"\x06\x54\x65\x73\x74").await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

//---- Section 6.2: HEADERS

/// HEADERS frames MUST be associated with a stream. If a HEADERS
/// frame is received whose stream identifier field is 0x0, the
/// recipient MUST respond with a connection error (Section 5.4.1)
/// of type PROTOCOL_ERROR.
pub async fn sends_headers_frame_with_zero_stream_id<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;

    conn.write_headers(
        StreamId::CONNECTION,
        HeadersFlags::EndStream | HeadersFlags::EndHeaders,
        block_fragment,
    )
    .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// The HEADERS frame can include padding. Padding fields and flags
/// are identical to those defined for DATA frames (Section 6.1).
/// Padding that exceeds the size remaining for the header block
/// fragment MUST be treated as a PROTOCOL_ERROR.
pub async fn sends_headers_frame_with_invalid_pad_length<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;

    let frame = Frame::new(
        FrameType::Headers(
            HeadersFlags::Padded | HeadersFlags::EndHeaders | HeadersFlags::EndStream,
        ),
        StreamId(1),
    )
    .with_len((block_fragment.len() + 1) as _);
    let frame_header = frame.into_piece(&mut conn.scratch)?;

    conn.send(frame_header).await?;
    conn.send(vec![(block_fragment.len() + 2) as u8]).await?;
    conn.send(block_fragment).await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

//---- Section 6.3: PRIORITY

/// The PRIORITY frame always identifies a stream. If a PRIORITY
/// frame is received with a stream identifier of 0x0, the recipient
/// MUST respond with a connection error (Section 5.4.1) of type
/// PROTOCOL_ERROR.
pub async fn sends_priority_frame_with_zero_stream_id<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_priority(
        StreamId::CONNECTION,
        PrioritySpec {
            stream_dependency: StreamId::CONNECTION,
            exclusive: false,
            weight: 255,
        },
    )
    .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// A PRIORITY frame with a length other than 5 octets MUST be
/// treated as a stream error (Section 5.4.2) of type
/// FRAME_SIZE_ERROR.
pub async fn sends_priority_frame_with_invalid_length<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;

    conn.write_headers(
        stream_id,
        HeadersFlags::EndStream | HeadersFlags::EndHeaders,
        block_fragment,
    )
    .await?;

    conn.write_frame(
        Frame::new(FrameType::Priority, stream_id),
        b"\x80\x00\x00\x01",
    )
    .await?;

    conn.verify_stream_error(ErrorC::FrameSizeError).await?;

    Ok(())
}

//---- Section 6.4: RST_STREAM

/// RST_STREAM frames MUST be associated with a stream. If a
/// RST_STREAM frame is received with a stream identifier of 0x0,
/// the recipient MUST treat this as a connection error
/// (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_rst_stream_frame_with_zero_stream_id<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_rst_stream(StreamId::CONNECTION, ErrorC::Cancel)
        .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// RST_STREAM frames MUST NOT be sent for a stream in the "idle"
/// state. If a RST_STREAM frame identifying an idle stream is
/// received, the recipient MUST treat this as a connection error
/// (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_rst_stream_frame_on_idle_stream<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_rst_stream(StreamId(1), ErrorC::Cancel).await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// A RST_STREAM frame with a length other than 4 octets MUST be
/// treated as a connection error (Section 5.4.1) of type
/// FRAME_SIZE_ERROR.
pub async fn sends_rst_stream_frame_with_invalid_length<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;
    conn.write_headers(
        stream_id,
        HeadersFlags::EndStream | HeadersFlags::EndHeaders,
        block_fragment,
    )
    .await?;

    let frame = Frame::new(FrameType::RstStream, StreamId(1)).with_len(3);
    let frame_header = frame.into_piece(&mut conn.scratch)?;
    conn.send(frame_header).await?;
    conn.send(b"\x00\x00\x00").await?;

    conn.verify_stream_error(ErrorC::FrameSizeError).await?;

    Ok(())
}

//---- Section 6.5: SETTINGS
//---- Section 6.5.1: SETTINGS Format

/// ACK (0x1):
/// When set, bit 0 indicates that this frame acknowledges receipt
/// and application of the peer's SETTINGS frame. When this bit is
/// set, the payload of the SETTINGS frame MUST be empty. 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.
pub async fn sends_settings_frame_with_ack_and_payload<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_frame(
        Frame::new(
            FrameType::Settings(SettingsFlags::Ack.into()),
            StreamId::CONNECTION,
        ),
        b"\x00",
    )
    .await?;

    conn.verify_connection_error(ErrorC::FrameSizeError).await?;

    Ok(())
}

/// SETTINGS frames always apply to a connection, never a single
/// stream. The stream identifier for a SETTINGS frame MUST be
/// zero (0x0). If an endpoint receives a SETTINGS frame whose
/// stream identifier field is anything other than 0x0, the
/// endpoint MUST respond with a connection error (Section 5.4.1)
/// of type PROTOCOL_ERROR.
pub async fn sends_settings_frame_with_non_zero_stream_id<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_frame(
        Frame::new(FrameType::Settings(Default::default()), StreamId(1)).with_len(6),
        SettingPairs(&[(Setting::MaxConcurrentStreams, 0x64)]),
    )
    .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// The SETTINGS frame affects connection state. A badly formed or
/// incomplete SETTINGS frame MUST be treated as a connection error
/// (Section 5.4.1) of type PROTOCOL_ERROR.
///
/// A SETTINGS frame with a length other than a multiple of 6 octets
/// MUST be treated as a connection error (Section 5.4.1) of type
/// FRAME_SIZE_ERROR.
pub async fn sends_settings_frame_with_invalid_length<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_frame(
        Frame::new(
            FrameType::Settings(Default::default()),
            StreamId::CONNECTION,
        ),
        b"\x00\x03\x00",
    )
    .await?;

    conn.verify_connection_error(ErrorC::FrameSizeError).await?;

    Ok(())
}

//---- Section 6.5.2: Defined SETTINGS Parameters

/// SETTINGS_ENABLE_PUSH (0x2):
/// The initial value is 1, which indicates that server push is
/// permitted. Any value other than 0 or 1 MUST be treated as a
/// connection error (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_settings_enable_push_with_invalid_value<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_settings(&[(Setting::EnablePush, 2)]).await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// SETTINGS_INITIAL_WINDOW_SIZE (0x4):
/// Values above the maximum flow-control window size of 2^31-1
/// MUST be treated as a connection error (Section 5.4.1) of
/// type FLOW_CONTROL_ERROR.
pub async fn sends_settings_initial_window_size_with_invalid_value<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_settings(&[(Setting::InitialWindowSize, 1 << 31)])
        .await?;

    conn.verify_connection_error(ErrorC::FlowControlError)
        .await?;

    Ok(())
}

/// SETTINGS_MAX_FRAME_SIZE (0x5):
/// The initial value is 2^14 (16,384) octets. The value advertised
/// by an endpoint MUST be between this initial value and the
/// maximum allowed frame size (2^24-1 or 16,777,215 octets),
/// inclusive. Values outside this range MUST be treated as a
/// connection error (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_settings_max_frame_size_with_invalid_value_below_initial<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_settings(&[(Setting::MaxFrameSize, (1 << 14) - 1)])
        .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// SETTINGS_MAX_FRAME_SIZE (0x5):
/// The initial value is 2^14 (16,384) octets. The value advertised
/// by an endpoint MUST be between this initial value and the
/// maximum allowed frame size (2^24-1 or 16,777,215 octets),
/// inclusive. Values outside this range MUST be treated as a
/// connection error (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_settings_max_frame_size_with_invalid_value_above_max<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_settings(&[(Setting::MaxFrameSize, 1 << 24)])
        .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// An endpoint that receives a SETTINGS frame with any unknown
/// or unsupported identifier MUST ignore that setting.
pub async fn sends_settings_frame_with_unknown_identifier<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_frame(
        Frame::new(
            FrameType::Settings(Default::default()),
            StreamId::CONNECTION,
        )
        .with_len(6),
        // identifier 0xff, value 0x00
        b"\x00\xff\x00\x00\x00\x00",
    )
    .await?;

    conn.verify_connection_still_alive().await?;

    Ok(())
}

//---- Section 6.5.3: Settings Synchronization

/// The values in the SETTINGS frame MUST be processed in the order
/// they appear, with no other frame processing between values.
pub async fn sends_multiple_values_of_settings_initial_window_size<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    conn.write_frame(
        Frame::new(
            FrameType::Settings(Default::default()),
            StreamId::CONNECTION,
        ),
        SettingPairs(&[
            (Setting::InitialWindowSize, 100),
            (Setting::InitialWindowSize, 1),
        ]),
    )
    .await?;

    conn.verify_settings_frame_with_ack().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;
    conn.write_headers(
        stream_id,
        HeadersFlags::EndStream | HeadersFlags::EndHeaders,
        block_fragment,
    )
    .await?;

    let (frame, _payload) = conn.wait_for_frame(FrameT::Data).await.unwrap();
    assert_eq!(frame.len, 1);

    Ok(())
}

/// Once all values have been processed, the recipient MUST
/// immediately emit a SETTINGS frame with the ACK flag set.
pub async fn sends_settings_frame_without_ack_flag<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_frame(
        Frame::new(
            FrameType::Settings(Default::default()),
            StreamId::CONNECTION,
        ),
        SettingPairs(&[(Setting::EnablePush, 0)]),
    )
    .await?;

    conn.verify_settings_frame_with_ack().await?;

    Ok(())
}

// (Note: Section 6.6 is skipped: push promise is discouraged nowadays)

//---- Section 6.7: PING

/// Receivers of a PING frame that does not include an ACK flag MUST
/// send a PING frame with the ACK flag set in response, with an
/// identical payload.
pub async fn sends_ping_frame<IO: IntoHalves>(mut conn: Conn<IO>) -> eyre::Result<()> {
    conn.handshake().await?;

    let data = b"h2spec\0\0";
    conn.write_ping(false, data.to_vec()).await?;

    conn.verify_ping_frame_with_ack(data).await?;

    Ok(())
}

/// ACK (0x1):
/// When set, bit 0 indicates that this PING frame is a PING
/// response. An endpoint MUST set this flag in PING responses.
/// An endpoint MUST NOT respond to PING frames containing this
/// flag.
pub async fn sends_ping_frame_with_ack<IO: IntoHalves>(mut conn: Conn<IO>) -> eyre::Result<()> {
    conn.handshake().await?;

    let unexpected_data = b"invalid\0";
    let expected_data = b"h2spec\0\0";
    conn.write_ping(true, unexpected_data.to_vec()).await?;
    conn.write_ping(false, expected_data.to_vec()).await?;

    conn.verify_ping_frame_with_ack(expected_data).await?;

    Ok(())
}

/// If a PING frame is received with a stream identifier field value
/// other than 0x0, the recipient MUST respond with a connection
/// error (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_ping_frame_with_non_zero_stream_id<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_frame(
        Frame::new(FrameType::Ping(Default::default()), StreamId(1)),
        dummy_bytes(8),
    )
    .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// Receipt of a PING frame with a length field value other than 8
/// MUST be treated as a connection error (Section 5.4.1) of type
/// FRAME_SIZE_ERROR.
pub async fn sends_ping_frame_with_invalid_length<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_frame(
        Frame::new(FrameType::Ping(Default::default()), StreamId::CONNECTION),
        dummy_bytes(6),
    )
    .await?;

    conn.verify_connection_error(ErrorC::FrameSizeError).await?;

    Ok(())
}

//---- Section 6.8: GOAWAY

/// An endpoint MUST treat a GOAWAY frame with a stream identifier
/// other than 0x0 as a connection error (Section 5.4.1) of type
/// PROTOCOL_ERROR.
pub async fn sends_goaway_frame_with_non_zero_stream_id<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_frame(
        Frame::new(FrameType::GoAway, StreamId(1)),
        GoAway {
            additional_debug_data: Piece::empty(),
            error_code: KnownErrorCode::NoError.into(),
            last_stream_id: StreamId(0),
        },
    )
    .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

//---- Section 6.9: WINDOW_UPDATE

/// A receiver MUST treat the receipt of a WINDOW_UPDATE frame with
/// a flow-control window increment of 0 as a stream error
/// (Section 5.4.2) of type PROTOCOL_ERROR; errors on the connection
/// flow-control window MUST be treated as a connection error
/// (Section 5.4.1).
pub async fn sends_window_update_frame_with_zero_increment<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_window_update(StreamId::CONNECTION, 0).await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// A receiver MUST treat the receipt of a WINDOW_UPDATE frame with
/// a flow-control window increment of 0 as a stream error
/// (Section 5.4.2) of type PROTOCOL_ERROR; errors on the connection
/// flow-control window MUST be treated as a connection error
/// (Section 5.4.1).
pub async fn sends_window_update_frame_with_zero_increment_on_stream<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let mut headers = conn.common_headers("POST");
    headers.append(":method", "POST");

    let block_fragment = conn.encode_headers(&headers)?;

    conn.write_headers(stream_id, HeadersFlags::EndHeaders, block_fragment)
        .await?;

    conn.write_window_update(stream_id, 0).await?;

    conn.verify_stream_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// A WINDOW_UPDATE frame with a length other than 4 octets MUST
/// be treated as a connection error (Section 5.4.1) of type
/// FRAME_SIZE_ERROR.
pub async fn sends_window_update_frame_with_invalid_length<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_frame(
        Frame::new(FrameType::WindowUpdate, StreamId::CONNECTION),
        b"\x00\x00\x01",
    )
    .await?;

    conn.verify_connection_error(ErrorC::FrameSizeError).await?;

    Ok(())
}

//---- Section 6.9.1: The Flow-Control Window

/// The sender MUST NOT send a flow-controlled frame with a length
/// that exceeds the space available in either of the flow-control
/// windows advertised by the receiver.
pub async fn sends_settings_frame_to_set_initial_window_size_to_1_and_sends_headers_frame<
    IO: IntoHalves,
>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    conn.write_and_ack_settings(&[(Setting::InitialWindowSize, 1)])
        .await?;

    conn.encode_and_write_headers(
        stream_id,
        HeadersFlags::EndStream | HeadersFlags::EndHeaders,
        &conn.common_headers("POST"),
    )
    .await?;

    let (frame, _payload) = conn.wait_for_frame(FrameT::Data).await.unwrap();
    assert_eq!(frame.len, 1);

    Ok(())
}

/// A sender MUST NOT allow a flow-control window to exceed 2^31-1
/// octets. If a sender receives a WINDOW_UPDATE that causes a
/// flow-control window to exceed this maximum, it MUST terminate
/// either the stream or the connection, as appropriate.
/// For streams, the sender sends a RST_STREAM with an error code
/// of FLOW_CONTROL_ERROR; for the connection, a GOAWAY frame with
/// an error code of FLOW_CONTROL_ERROR is sent.
pub async fn sends_multiple_window_update_frames_increasing_flow_control_window_above_max<
    IO: IntoHalves,
>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_window_update(StreamId::CONNECTION, (1 << 31) - 1)
        .await?;
    conn.write_window_update(StreamId::CONNECTION, (1 << 31) - 1)
        .await?;

    conn.verify_connection_error(ErrorC::FlowControlError)
        .await?;

    Ok(())
}

/// A sender MUST NOT allow a flow-control window to exceed 2^31-1
/// octets. If a sender receives a WINDOW_UPDATE that causes a
/// flow-control window to exceed this maximum, it MUST terminate
/// either the stream or the connection, as appropriate.
/// For streams, the sender sends a RST_STREAM with an error code
/// of FLOW_CONTROL_ERROR; for the connection, a GOAWAY frame with
/// an error code of FLOW_CONTROL_ERROR is sent.
pub async fn sends_multiple_window_update_frames_increasing_flow_control_window_above_max_on_stream<
    IO: IntoHalves,
>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    conn.encode_and_write_headers(
        stream_id,
        HeadersFlags::EndHeaders,
        &conn.common_headers("POST"),
    )
    .await?;

    conn.write_window_update(stream_id, (1 << 31) - 1).await?;
    // that write might fail: the window may already have exceeded the max
    _ = conn.write_window_update(stream_id, (1 << 31) - 1).await;

    conn.verify_stream_error(ErrorC::FlowControlError).await?;

    Ok(())
}

//---- Section 6.9.2: Initial Flow-Control Window Size

/// When the value of SETTINGS_INITIAL_WINDOW_SIZE changes,
/// a receiver MUST adjust the size of all stream flow-control
/// windows that it maintains by the difference between the new
/// value and the old value.
pub async fn changes_settings_initial_window_size_after_sending_headers_frame<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    // prevent the peer from sending us data frames
    conn.write_and_ack_settings(&[(Setting::InitialWindowSize, 0)])
        .await?;

    // make a request
    conn.encode_and_write_headers(
        stream_id,
        HeadersFlags::EndStream | HeadersFlags::EndHeaders,
        &conn.common_headers("POST"),
    )
    .await?;

    // allow the peer to send us one byte
    conn.write_settings(&[(Setting::InitialWindowSize, 1)])
        .await?;

    let (frame, _payload) = conn.wait_for_frame(FrameT::Data).await.unwrap();
    assert_eq!(frame.len, 1);

    Ok(())
}

/// A sender MUST track the negative flow-control window and
/// MUST NOT send new flow-controlled frames until it receives
/// WINDOW_UPDATE frames that cause the flow-control window to
/// become positive.
pub async fn sends_settings_frame_for_window_size_to_be_negative<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    // note: this test assumes the response body is 5 bytes or above

    // make window size 3 & send request
    conn.write_and_ack_settings(&[(Setting::InitialWindowSize, 3)])
        .await?;
    conn.send_empty_post_to_root(stream_id).await?;

    // wait for peer to send us all 3 bytes it can
    let (_, payload) = conn.wait_for_frame(FrameT::Data).await.unwrap();
    assert_eq!(payload.len(), 3);

    // window size is 0, if we set SETTINGS_INITIAL_WINDOW_SIZE to 2
    // (from 3 before), it should go to -1
    conn.write_and_ack_settings(&[(Setting::InitialWindowSize, 2)])
        .await?;

    // bring it back up to 1
    conn.write_window_update(stream_id, 2).await?;

    // we should get exactly 1 byte
    let (frame, _payload) = conn.wait_for_frame(FrameT::Data).await.unwrap();
    assert_eq!(frame.len, 1);

    Ok(())
}

/// An endpoint MUST treat a change to SETTINGS_INITIAL_WINDOW_SIZE
/// that causes any flow-control window to exceed the maximum size
/// as a connection error (Section 5.4.1) of type FLOW_CONTROL_ERROR.
pub async fn sends_settings_initial_window_size_with_exceeded_max_window_size_value<
    IO: IntoHalves,
>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    conn.handshake().await?;

    conn.write_settings(&[(Setting::InitialWindowSize, 1 << 31)])
        .await?;

    conn.verify_connection_error(ErrorC::FlowControlError)
        .await?;

    Ok(())
}

// Note: 6.9.3 (reducing the stream window size) is really tricky to test.

//---- Section 6.10: CONTINUATION

/// The CONTINUATION frame (type=0x9) is used to continue a sequence
/// of header block fragments (Section 4.3). Any number of
/// CONTINUATION frames can be sent, as long as the preceding frame
/// is on the same stream and is a HEADERS, PUSH_PROMISE,
/// or CONTINUATION frame without the END_HEADERS flag set.
pub async fn sends_multiple_continuation_frames_preceded_by_headers_frame<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let headers = conn.common_headers("POST");
    let block_fragment = conn.encode_headers(&headers)?;
    conn.write_headers(stream_id, HeadersFlags::EndStream, block_fragment)
        .await?;

    let dummy_headers = conn.dummy_headers(1);
    let block_fragment = conn.encode_headers(&dummy_headers)?;
    conn.write_continuation(stream_id, BitFlags::empty(), block_fragment)
        .await?;
    let block_fragment = conn.encode_headers(&dummy_headers)?;
    conn.write_continuation(stream_id, ContinuationFlags::EndHeaders, block_fragment)
        .await?;

    conn.verify_headers_frame(stream_id).await?;

    Ok(())
}

/// END_HEADERS (0x4):
/// If the END_HEADERS bit is not set, this frame MUST be followed
/// by another CONTINUATION frame. A receiver MUST treat the receipt
/// of any other type of frame or a frame on a different stream as
/// a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_continuation_frame_followed_by_non_continuation_frame<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;
    conn.write_headers(stream_id, HeadersFlags::EndStream, block_fragment)
        .await?;

    let dummy_headers = conn.dummy_headers(1);
    let block_fragment = conn.encode_headers(&dummy_headers)?;
    conn.write_continuation(stream_id, BitFlags::empty(), block_fragment)
        .await?;
    conn.write_data(stream_id, true, b"test").await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// CONTINUATION frames MUST be associated with a stream. If a
/// CONTINUATION frame is received whose stream identifier field is
/// 0x0, the recipient MUST respond with a connection error
/// (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_continuation_frame_with_zero_stream_id<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;
    conn.write_headers(stream_id, HeadersFlags::EndStream, block_fragment)
        .await?;

    let block_fragment = conn.encode_headers(&conn.dummy_headers(1))?;
    conn.write_continuation(
        StreamId::CONNECTION,
        ContinuationFlags::EndHeaders,
        block_fragment,
    )
    .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// A CONTINUATION frame MUST be preceded by a HEADERS, PUSH_PROMISE
/// or CONTINUATION frame without the END_HEADERS flag set.
/// A recipient that observes violation of this rule MUST respond
/// with a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_continuation_frame_preceded_by_headers_frame_with_end_headers_flag<
    IO: IntoHalves,
>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;
    conn.write_headers(
        stream_id,
        HeadersFlags::EndStream | HeadersFlags::EndHeaders,
        block_fragment,
    )
    .await?;

    let dummy_headers = conn.dummy_headers(1);
    let block_fragment = conn.encode_headers(&dummy_headers)?;
    conn.write_continuation(stream_id, ContinuationFlags::EndHeaders, block_fragment)
        .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// A CONTINUATION frame MUST be preceded by a HEADERS, PUSH_PROMISE
/// or CONTINUATION frame without the END_HEADERS flag set.
/// A recipient that observes violation of this rule MUST respond
/// with a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_continuation_frame_preceded_by_continuation_frame_with_end_headers_flag<
    IO: IntoHalves,
>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;
    conn.write_headers(stream_id, HeadersFlags::EndStream, block_fragment)
        .await?;

    let dummy_headers = conn.dummy_headers(1);
    let block_fragment = conn.encode_headers(&dummy_headers)?;
    conn.write_continuation(stream_id, ContinuationFlags::EndHeaders, block_fragment)
        .await?;
    let block_fragment = conn.encode_headers(&dummy_headers)?;
    conn.write_continuation(stream_id, ContinuationFlags::EndHeaders, block_fragment)
        .await?;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}

/// A CONTINUATION frame MUST be preceded by a HEADERS, PUSH_PROMISE
/// or CONTINUATION frame without the END_HEADERS flag set.
/// A recipient that observes violation of this rule MUST respond
/// with a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
pub async fn sends_continuation_frame_preceded_by_data_frame<IO: IntoHalves>(
    mut conn: Conn<IO>,
) -> eyre::Result<()> {
    let stream_id = StreamId(1);

    conn.handshake().await?;

    let block_fragment = conn.encode_headers(&conn.common_headers("POST"))?;
    conn.write_headers(stream_id, HeadersFlags::EndStream, block_fragment)
        .await?;
    conn.write_data(stream_id, true, b"test").await?;

    let block_fragment = conn.encode_headers(&conn.dummy_headers(1))?;
    // this may fail with broken pipe, the server may close the connection
    // in the middle of the write
    _ = conn
        .write_continuation(stream_id, BitFlags::empty(), block_fragment)
        .await;

    conn.verify_connection_error(ErrorC::ProtocolError).await?;

    Ok(())
}