asupersync 0.3.4

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
//! WebSocket HTTP upgrade handler for the web framework.
//!
//! Provides [`WebSocketUpgrade`] as an extractor that validates WebSocket
//! upgrade requests and produces the 101 Switching Protocols response.
//! After the upgrade, the connection transitions into a [`WebSocket`]
//! for bidirectional message exchange.
//!
//! # Example
//!
//! ```ignore
//! use asupersync::web::websocket::{WebSocketUpgrade, WebSocket, Message};
//!
//! async fn ws_handler(upgrade: WebSocketUpgrade) -> Response {
//!     upgrade.protocols(["chat"]).into_response()
//! }
//!
//! // After upgrade, use the WebSocket:
//! // while let Some(msg) = ws.recv(&cx).await? { ... }
//! ```
//!
//! # Design
//!
//! The upgrade flow follows RFC 6455:
//!
//! 1. Client sends `GET` with `Upgrade: websocket` and `Sec-WebSocket-Key`
//! 2. [`WebSocketUpgrade::from_request`] validates the headers
//! 3. Handler calls [`WebSocketUpgrade::into_response`] to produce 101
//! 4. After 101 is written, the transport switches to WebSocket framing
//!
//! The actual bidirectional communication uses [`WebSocket`], which wraps
//! the existing `net::websocket::ServerWebSocket` with an ergonomic API.

use crate::net::websocket::{WebSocketAcceptor, compute_accept_key};

use super::extract::{ExtractionError, FromRequest, Request};
use super::response::{IntoResponse, Response, StatusCode};

// Re-export the key types users need for WebSocket communication.
pub use crate::net::websocket::{CloseReason, Message, ServerWebSocket};

/// WebSocket upgrade extractor.
///
/// Validates that an incoming HTTP request is a valid WebSocket upgrade
/// request per RFC 6455 Section 4.2.1. If validation succeeds, the
/// extractor holds the computed accept key and can produce the 101
/// Switching Protocols response.
///
/// # Validation
///
/// The extractor checks:
/// - HTTP method is GET
/// - `Upgrade` header contains "websocket" (case-insensitive)
/// - `Connection` header contains "Upgrade" (case-insensitive)
/// - `Sec-WebSocket-Version` is "13"
/// - `Sec-WebSocket-Key` is present and valid base64 of 16 bytes
///
/// # Rejection
///
/// Returns 400 Bad Request if any validation check fails.
/// Origin-validation policy applied during the WebSocket upgrade response.
///
/// Defends against Cross-Site WebSocket Hijacking (CSWSH): browsers
/// initiate WebSocket handshakes under the same-origin policy of HTTP
/// (i.e. they don't enforce one), so without server-side `Origin`
/// validation an attacker page at `evil.example` can open a WebSocket
/// to `legit.example` from a victim's browser session.
/// (br-asupersync-o2t5gz)
#[derive(Debug, Clone, Default)]
pub enum OriginPolicy {
    /// Default. Reject the upgrade unless the request's `Origin` host:port
    /// matches its `Host` header (case-insensitive). Requests with NO
    /// `Origin` header are accepted on the assumption that they come
    /// from a non-browser client (browsers always emit `Origin` for
    /// WebSocket handshakes per RFC 6455 §10.2).
    #[default]
    SameOrigin,
    /// Accept the upgrade if the request's `Origin` value (full URL,
    /// case-insensitive) appears in the allowlist. An empty allowlist
    /// rejects every request that has an `Origin` header. Requests with
    /// no `Origin` header are accepted (non-browser clients).
    AllowList(Vec<String>),
    /// No `Origin` validation. Opt-in for tests and non-browser
    /// integrations that don't need CSWSH defense.
    Disabled,
}

/// Builder returned by the WebSocket extractor after validating an upgrade request.
#[derive(Debug, Clone)]
pub struct WebSocketUpgrade {
    /// Computed Sec-WebSocket-Accept value.
    accept_key: String,
    /// Client's requested subprotocols.
    requested_protocols: Vec<String>,
    /// Client's requested extensions.
    requested_extensions: Vec<String>,
    /// Selected subprotocol (set via `.protocols()`).
    selected_protocol: Option<String>,
    /// Selected extensions (set via `.extensions()`).
    selected_extensions: Vec<String>,
    /// `Origin` header from the upgrade request (br-asupersync-o2t5gz).
    /// `None` if the client didn't send one (typically a non-browser
    /// client; browsers always send `Origin` per RFC 6455 §10.2).
    origin: Option<String>,
    /// `Host` header from the upgrade request, used to evaluate
    /// `OriginPolicy::SameOrigin`.
    host: Option<String>,
    /// Origin-validation policy applied at response time. Defaults to
    /// `SameOrigin` so any caller that forgets to call `.allow_origins()`
    /// or `.skip_origin_check()` still gets CSWSH defense.
    origin_policy: OriginPolicy,
}

impl FromRequest for WebSocketUpgrade {
    fn from_request(req: Request) -> Result<Self, ExtractionError> {
        // Validate method is GET.
        if req.method != "GET" {
            return Err(ExtractionError::bad_request(format!(
                "method must be GET, got {}",
                req.method
            )));
        }

        // Validate Upgrade header.
        let upgrade = req
            .header("upgrade")
            .ok_or_else(|| ExtractionError::bad_request("missing Upgrade header"))?;
        if !header_has_token(upgrade, "websocket") {
            return Err(ExtractionError::bad_request(format!(
                "Upgrade header must contain 'websocket', got '{upgrade}'"
            )));
        }

        // Validate Connection header contains "Upgrade".
        let connection = req
            .header("connection")
            .ok_or_else(|| ExtractionError::bad_request("missing Connection header"))?;
        if !header_has_token(connection, "upgrade") {
            return Err(ExtractionError::bad_request(format!(
                "Connection header must contain 'Upgrade', got '{connection}'"
            )));
        }

        // Validate Sec-WebSocket-Version.
        let version = req
            .header("sec-websocket-version")
            .ok_or_else(|| ExtractionError::bad_request("missing Sec-WebSocket-Version header"))?;
        if version != "13" {
            return Err(ExtractionError::bad_request(format!(
                "unsupported WebSocket version: {version}"
            )));
        }

        // Validate and extract Sec-WebSocket-Key.
        let key = req
            .header("sec-websocket-key")
            .ok_or_else(|| ExtractionError::bad_request("missing Sec-WebSocket-Key header"))?;

        // Validate key is valid base64 of 16 bytes.
        match base64::engine::general_purpose::STANDARD.decode(key) {
            Ok(bytes) if bytes.len() == 16 => {}
            _ => {
                return Err(ExtractionError::bad_request(
                    "Sec-WebSocket-Key must be 16 bytes of base64",
                ));
            }
        }

        let accept_key = compute_accept_key(key);

        // Parse requested protocols.
        let requested_protocols = req
            .header("sec-websocket-protocol")
            .map(|v| {
                v.split(',')
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(ToOwned::to_owned)
                    .collect()
            })
            .unwrap_or_default();

        // Parse requested extensions.
        let requested_extensions = req
            .header("sec-websocket-extensions")
            .map(|v| {
                v.split(',')
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(ToOwned::to_owned)
                    .collect()
            })
            .unwrap_or_default();

        // Capture Origin + Host for CSWSH defense (br-asupersync-o2t5gz).
        // The actual policy decision happens in `IntoResponse` so a caller
        // can override the default via `.allow_origins()` or
        // `.skip_origin_check()` before returning the upgrade.
        let origin = req.header("origin").map(ToOwned::to_owned);
        let host = req.header("host").map(ToOwned::to_owned);

        Ok(Self {
            accept_key,
            requested_protocols,
            requested_extensions,
            selected_protocol: None,
            selected_extensions: Vec::new(),
            origin,
            host,
            origin_policy: OriginPolicy::default(),
        })
    }
}

use base64::Engine;

fn header_has_token(value: &str, token: &str) -> bool {
    value
        .split(',')
        .map(str::trim)
        .any(|part| part.eq_ignore_ascii_case(token))
}

/// Strip the `scheme://` prefix from an `Origin` value, returning the
/// authority component (`host[:port]`) for same-origin comparison against
/// the `Host` header. Falls back to the raw value if no scheme is found
/// (an invalid Origin would then fail the comparison, which is the
/// fail-closed behavior we want). (br-asupersync-o2t5gz)
fn strip_origin_scheme(origin: &str) -> &str {
    if let Some(idx) = origin.find("://") {
        // RFC 6454 origins must not have a path; if one is present we
        // truncate at the first '/' so a malformed Origin like
        // `https://victim.com/../attacker.com:443` cannot smuggle an
        // attacker host past the comparison.
        let after_scheme = &origin[idx + 3..];
        match after_scheme.find('/') {
            Some(slash) => &after_scheme[..slash],
            None => after_scheme,
        }
    } else {
        origin
    }
}

impl WebSocketUpgrade {
    /// Select a subprotocol from the client's requested list.
    ///
    /// The server picks the first protocol from `supported` that appears
    /// in the client's `Sec-WebSocket-Protocol` header. If none match,
    /// no protocol is selected (which is valid per RFC 6455).
    #[must_use]
    pub fn protocols<I, S>(mut self, supported: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let supported: Vec<String> = supported
            .into_iter()
            .map(|s| s.as_ref().to_string())
            .collect();

        self.selected_protocol = self
            .requested_protocols
            .iter()
            .find(|requested| supported.iter().any(|s| s.eq_ignore_ascii_case(requested)))
            .cloned();

        self
    }

    /// Select extensions to accept from the client's requested list.
    #[must_use]
    pub fn extensions<I, S>(mut self, supported: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let supported: Vec<String> = supported
            .into_iter()
            .map(|s| s.as_ref().to_string())
            .collect();

        self.selected_extensions = self
            .requested_extensions
            .iter()
            .filter(|requested| {
                let token = requested.split(';').next().unwrap_or("").trim();
                supported.iter().any(|s| s.eq_ignore_ascii_case(token))
            })
            .cloned()
            .collect();

        self
    }

    /// Get the computed Sec-WebSocket-Accept key.
    #[must_use]
    pub fn accept_key(&self) -> &str {
        &self.accept_key
    }

    /// Get the request's `Origin` header value, if present.
    /// (br-asupersync-o2t5gz)
    #[must_use]
    pub fn origin(&self) -> Option<&str> {
        self.origin.as_deref()
    }

    /// Override the origin-validation policy with an explicit allowlist.
    /// Origins are matched case-insensitively against the request's full
    /// `Origin` value. (br-asupersync-o2t5gz)
    #[must_use]
    pub fn allow_origins<I, S>(mut self, origins: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.origin_policy = OriginPolicy::AllowList(origins.into_iter().map(Into::into).collect());
        self
    }

    /// Disable origin validation entirely. Opt-in for tests and
    /// non-browser integrations that do not need CSWSH defense.
    /// (br-asupersync-o2t5gz)
    #[must_use]
    pub fn skip_origin_check(mut self) -> Self {
        self.origin_policy = OriginPolicy::Disabled;
        self
    }

    /// Evaluate the configured `OriginPolicy` against the captured
    /// `Origin` / `Host` headers. `Ok(())` means the upgrade may proceed;
    /// `Err(reason)` means the response must be a 403. Browsers always
    /// emit `Origin` for WebSocket handshakes per RFC 6455 §10.2, so a
    /// missing `Origin` is treated as a non-browser client and accepted.
    /// (br-asupersync-o2t5gz)
    fn evaluate_origin(&self) -> Result<(), &'static str> {
        match (&self.origin_policy, self.origin.as_deref()) {
            (OriginPolicy::Disabled, _) => Ok(()),
            (_, None) => Ok(()),
            (OriginPolicy::AllowList(list), Some(origin)) => {
                if list
                    .iter()
                    .any(|allowed| allowed.eq_ignore_ascii_case(origin))
                {
                    Ok(())
                } else {
                    Err("Origin not in allowlist")
                }
            }
            (OriginPolicy::SameOrigin, Some(origin)) => {
                let Some(host) = self.host.as_deref() else {
                    return Err("Origin present but no Host header to compare");
                };
                let origin_authority = strip_origin_scheme(origin);
                if origin_authority.eq_ignore_ascii_case(host) {
                    Ok(())
                } else {
                    Err("Origin does not match Host (cross-origin request rejected)")
                }
            }
        }
    }

    /// Get the client's requested protocols.
    #[must_use]
    pub fn requested_protocols(&self) -> &[String] {
        &self.requested_protocols
    }

    /// Get the client's requested extensions.
    #[must_use]
    pub fn requested_extensions(&self) -> &[String] {
        &self.requested_extensions
    }

    /// Get the selected protocol (if any).
    #[must_use]
    pub fn selected_protocol(&self) -> Option<&str> {
        self.selected_protocol.as_deref()
    }

    /// Build a [`WebSocketAcceptor`] configured with the negotiated
    /// protocols and extensions.
    #[must_use]
    pub fn acceptor(&self) -> WebSocketAcceptor {
        let mut acceptor = WebSocketAcceptor::new();
        if let Some(ref proto) = self.selected_protocol {
            acceptor = acceptor.protocol(proto.clone());
        }
        for ext in &self.selected_extensions {
            acceptor = acceptor.extension(ext.clone());
        }
        acceptor
    }
}

impl IntoResponse for WebSocketUpgrade {
    fn into_response(self) -> Response {
        // Default-deny CSWSH defense (br-asupersync-o2t5gz). Rejected
        // origins get a 403 Forbidden instead of the 101 switch. Body is
        // a fixed string and the rejected Origin is NOT echoed back, so
        // the response is not itself a per-request oracle.
        if let Err(reason) = self.evaluate_origin() {
            return Response::new(
                StatusCode::FORBIDDEN,
                crate::bytes::Bytes::from_static(reason.as_bytes()),
            )
            .header("content-type", "text/plain; charset=utf-8");
        }

        let mut resp = Response::empty(StatusCode::SWITCHING_PROTOCOLS)
            .header("upgrade", "websocket")
            .header("connection", "Upgrade")
            .header("sec-websocket-accept", &self.accept_key);

        if let Some(ref protocol) = self.selected_protocol {
            resp = resp.header("sec-websocket-protocol", protocol);
        }

        if !self.selected_extensions.is_empty() {
            resp = resp.header(
                "sec-websocket-extensions",
                self.selected_extensions.join(", "),
            );
        }

        resp
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;
    use crate::bytes::Bytes;
    use crate::net::websocket::ServerHandshake;

    /// Build a valid WebSocket upgrade request.
    fn ws_request() -> Request {
        Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==")
    }

    // ─── Extraction tests ─────────────────────────────────────────────

    #[test]
    fn valid_upgrade_request_extracts_successfully() {
        let req = ws_request();
        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        // RFC 6455 example: dGhlIHNhbXBsZSBub25jZQ== → s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
        assert_eq!(upgrade.accept_key(), "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
    }

    // ─── CSWSH origin-validation tests (br-asupersync-o2t5gz) ─────────

    #[test]
    fn cswsh_default_same_origin_accepts_matching_origin() {
        let req = ws_request()
            .with_header("host", "api.example.com")
            .with_header("origin", "https://api.example.com");
        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        let resp = upgrade.into_response();
        assert_eq!(resp.status, StatusCode::SWITCHING_PROTOCOLS);
    }

    #[test]
    fn cswsh_default_same_origin_rejects_cross_origin() {
        let req = ws_request()
            .with_header("host", "api.example.com")
            .with_header("origin", "https://evil.example");
        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        let resp = upgrade.into_response();
        assert_eq!(
            resp.status,
            StatusCode::FORBIDDEN,
            "cross-origin browser request must be rejected by the default policy"
        );
    }

    #[test]
    fn cswsh_origin_header_strips_path_to_prevent_smuggling() {
        // A malformed Origin like https://victim.com/../api.example.com:443
        // must NOT compare equal to api.example.com:443 — strip at first '/'.
        let req = ws_request()
            .with_header("host", "api.example.com")
            .with_header("origin", "https://victim.com/../api.example.com");
        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        let resp = upgrade.into_response();
        assert_eq!(resp.status, StatusCode::FORBIDDEN);
    }

    #[test]
    fn cswsh_no_origin_header_is_accepted_as_non_browser_client() {
        // Non-browser clients (curl, native apps, server-to-server) don't
        // send Origin. Default policy must not lock them out.
        let req = ws_request().with_header("host", "api.example.com");
        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        let resp = upgrade.into_response();
        assert_eq!(resp.status, StatusCode::SWITCHING_PROTOCOLS);
    }

    #[test]
    fn cswsh_allow_origins_accepts_listed_origin() {
        let req = ws_request()
            .with_header("host", "api.example.com")
            .with_header("origin", "https://app.example.com");
        let upgrade = WebSocketUpgrade::from_request(req)
            .unwrap()
            .allow_origins(["https://app.example.com", "https://other.example.com"]);
        let resp = upgrade.into_response();
        assert_eq!(resp.status, StatusCode::SWITCHING_PROTOCOLS);
    }

    #[test]
    fn cswsh_allow_origins_rejects_unlisted_origin() {
        let req = ws_request()
            .with_header("host", "api.example.com")
            .with_header("origin", "https://attacker.example");
        let upgrade = WebSocketUpgrade::from_request(req)
            .unwrap()
            .allow_origins(["https://app.example.com"]);
        let resp = upgrade.into_response();
        assert_eq!(resp.status, StatusCode::FORBIDDEN);
    }

    #[test]
    fn cswsh_skip_origin_check_lets_anything_through() {
        let req = ws_request()
            .with_header("host", "api.example.com")
            .with_header("origin", "https://anything-goes.example");
        let upgrade = WebSocketUpgrade::from_request(req)
            .unwrap()
            .skip_origin_check();
        let resp = upgrade.into_response();
        assert_eq!(resp.status, StatusCode::SWITCHING_PROTOCOLS);
    }

    #[test]
    fn cswsh_403_body_does_not_echo_origin() {
        // The 403 response must not echo the rejected Origin back to the
        // requester — that would leak the attacker's URL into logs and
        // make the response a per-request oracle.
        let req = ws_request()
            .with_header("host", "api.example.com")
            .with_header("origin", "https://leak-me.example");
        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        let resp = upgrade.into_response();
        assert_eq!(resp.status, StatusCode::FORBIDDEN);
        assert!(
            !resp.body.iter().any(|b| {
                std::str::from_utf8(&[*b])
                    .map(|s| s.contains("leak-me"))
                    .unwrap_or(false)
            }),
            "403 body must not contain the rejected origin"
        );
        // Stronger check: the body is a fixed string we control.
        let body_text = std::str::from_utf8(&resp.body).unwrap_or("");
        assert!(
            !body_text.contains("leak-me"),
            "403 body must not echo origin: {body_text}"
        );
    }

    #[test]
    fn valid_upgrade_request_accepts_mixed_case_header_names() {
        let req = Request::new("GET", "/ws")
            .with_header("UpGrAdE", "websocket")
            .with_header("cOnNeCtIoN", "Upgrade")
            .with_header("SeC-WebSocket-Version", "13")
            .with_header("sEc-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");

        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        assert_eq!(upgrade.accept_key(), "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
    }

    #[test]
    fn rejects_non_get_method() {
        let req = Request::new("POST", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("GET"));
    }

    #[test]
    fn rejects_missing_upgrade_header() {
        let req = Request::new("GET", "/ws")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("Upgrade"));
    }

    #[test]
    fn rejects_wrong_upgrade_value() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "h2c")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("websocket"));
    }

    #[test]
    fn rejects_missing_connection_header() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("Connection"));
    }

    #[test]
    fn rejects_connection_without_upgrade() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "keep-alive")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("Upgrade"));
    }

    #[test]
    fn rejects_connection_with_upgrade_only_as_substring() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "notupgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("Upgrade"));
    }

    #[test]
    fn rejects_missing_version() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("Version"));
    }

    #[test]
    fn rejects_unsupported_version() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "8")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("version"));
    }

    #[test]
    fn rejects_missing_key() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("Key"));
    }

    #[test]
    fn rejects_invalid_key() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "not-valid-base64!!!");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("Key"));
    }

    #[test]
    fn rejects_short_key() {
        // Valid base64 but only 8 bytes (need 16).
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "AAAAAAAAAAA=");

        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        assert!(err.message.contains("Key"));
    }

    // ─── Case insensitivity ───────────────────────────────────────────

    #[test]
    fn accepts_case_insensitive_upgrade_header() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "WebSocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        assert!(WebSocketUpgrade::from_request(req).is_ok());
    }

    #[test]
    fn accepts_upgrade_header_with_additional_tokens() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "h2c, WebSocket")
            .with_header("connection", "keep-alive, Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        assert!(WebSocketUpgrade::from_request(req).is_ok());
    }

    #[test]
    fn accepts_connection_upgrade_mixed_case() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "keep-alive, Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        assert!(WebSocketUpgrade::from_request(req).is_ok());
    }

    // ─── Protocol negotiation ─────────────────────────────────────────

    #[test]
    fn protocol_negotiation_selects_first_match() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==")
            .with_header("sec-websocket-protocol", "chat, superchat");

        let upgrade = WebSocketUpgrade::from_request(req)
            .unwrap()
            .protocols(["superchat", "chat"]);

        // Client requested "chat" first, and we support both → "chat" wins.
        assert_eq!(upgrade.selected_protocol(), Some("chat"));
    }

    #[test]
    fn protocol_negotiation_no_match() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==")
            .with_header("sec-websocket-protocol", "mqtt");

        let upgrade = WebSocketUpgrade::from_request(req)
            .unwrap()
            .protocols(["chat"]);

        assert_eq!(upgrade.selected_protocol(), None);
    }

    #[test]
    fn no_protocol_requested() {
        let req = ws_request();
        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        assert!(upgrade.requested_protocols().is_empty());
        assert_eq!(upgrade.selected_protocol(), None);
    }

    // ─── Extension negotiation ────────────────────────────────────────

    #[test]
    fn extension_negotiation_filters_supported() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==")
            .with_header(
                "sec-websocket-extensions",
                "permessage-deflate; client_max_window_bits, x-unsupported",
            );

        let upgrade = WebSocketUpgrade::from_request(req)
            .unwrap()
            .extensions(["permessage-deflate"]);

        assert_eq!(upgrade.selected_extensions.len(), 1);
        assert!(upgrade.selected_extensions[0].contains("permessage-deflate"));
    }

    // ─── IntoResponse ─────────────────────────────────────────────────

    #[test]
    fn into_response_produces_101() {
        let req = ws_request();
        let resp = WebSocketUpgrade::from_request(req).unwrap().into_response();

        assert_eq!(resp.status, StatusCode::SWITCHING_PROTOCOLS);
        assert_eq!(resp.headers.get("upgrade").unwrap(), "websocket");
        assert_eq!(resp.headers.get("connection").unwrap(), "Upgrade");
        assert_eq!(
            resp.headers.get("sec-websocket-accept").unwrap(),
            "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
        );
    }

    #[test]
    fn into_response_includes_selected_protocol() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==")
            .with_header("sec-websocket-protocol", "graphql-ws, graphql-transport-ws");

        let resp = WebSocketUpgrade::from_request(req)
            .unwrap()
            .protocols(["graphql-transport-ws"])
            .into_response();

        assert_eq!(
            resp.headers.get("sec-websocket-protocol").unwrap(),
            "graphql-transport-ws"
        );
    }

    #[test]
    fn into_response_omits_protocol_when_none_selected() {
        let req = ws_request();
        let resp = WebSocketUpgrade::from_request(req).unwrap().into_response();

        assert!(!resp.headers.contains_key("sec-websocket-protocol"));
    }

    #[test]
    fn into_response_includes_selected_extensions() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==")
            .with_header("sec-websocket-extensions", "permessage-deflate");

        let resp = WebSocketUpgrade::from_request(req)
            .unwrap()
            .extensions(["permessage-deflate"])
            .into_response();

        assert!(
            resp.headers
                .get("sec-websocket-extensions")
                .unwrap()
                .contains("permessage-deflate")
        );
    }

    // ─── Rejection response ───────────────────────────────────────────

    #[test]
    fn extraction_error_produces_400() {
        use super::super::extract::ExtractionError;

        let err = ExtractionError::bad_request("test rejection");
        let resp = err.into_response();
        assert_eq!(resp.status, StatusCode::BAD_REQUEST);
    }

    #[test]
    fn non_ws_request_produces_400_via_extraction() {
        let req = Request::new("POST", "/ws");
        let err = WebSocketUpgrade::from_request(req).unwrap_err();
        let resp = err.into_response();
        assert_eq!(resp.status, StatusCode::BAD_REQUEST);
    }

    // ─── Acceptor builder ─────────────────────────────────────────────

    #[test]
    fn acceptor_built_with_negotiated_protocol() {
        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==")
            .with_header("sec-websocket-protocol", "chat");

        let upgrade = WebSocketUpgrade::from_request(req)
            .unwrap()
            .protocols(["chat"]);

        let acceptor = upgrade.acceptor();
        let dbg = format!("{acceptor:?}");
        assert!(dbg.contains("WebSocketAcceptor"));
    }

    // ─── Message re-exports ───────────────────────────────────────────

    #[test]
    fn message_text_construction() {
        let msg = Message::text("hello");
        assert!(matches!(msg, Message::Text(_)));
    }

    #[test]
    fn message_binary_construction() {
        let msg = Message::binary(vec![1, 2, 3]);
        assert!(matches!(msg, Message::Binary(_)));
    }

    #[test]
    fn message_close_construction() {
        let msg = Message::Close(Some(CloseReason::normal()));
        assert!(matches!(msg, Message::Close(Some(_))));
    }

    #[test]
    fn message_ping_pong() {
        let heartbeat_ping = Message::Ping(Bytes::from_static(b"ping"));
        assert!(matches!(heartbeat_ping, Message::Ping(_)));

        let control_reply = Message::Pong(Bytes::from_static(b"pong"));
        assert!(matches!(control_reply, Message::Pong(_)));
    }

    // ─── Data type trait coverage ─────────────────────────────────────

    #[test]
    fn websocket_upgrade_debug_clone() {
        let req = ws_request();
        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        let dbg = format!("{upgrade:?}");
        assert!(dbg.contains("WebSocketUpgrade"));
        assert!(dbg.contains("accept_key"));
        assert_eq!(upgrade.accept_key(), "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
    }

    #[test]
    fn extraction_error_debug_clone() {
        let err = ExtractionError::bad_request("test rejection");
        let dbg = format!("{err:?}");
        assert!(dbg.contains("ExtractionError"));
        assert_eq!(err.message, "test rejection");
    }

    // ─── Accept key correctness ───────────────────────────────────────

    #[test]
    fn accept_key_rfc6455_vector() {
        // The canonical test vector from RFC 6455 Section 4.2.2.
        let req = Request::new("GET", "/chat")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");

        let upgrade = WebSocketUpgrade::from_request(req).unwrap();
        assert_eq!(upgrade.accept_key(), "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
    }

    #[test]
    fn accept_key_different_keys_produce_different_accepts() {
        let key1 = ws_request();
        let key2 = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "AAAAAAAAAAAAAAAAAAAAAA==");

        let u1 = WebSocketUpgrade::from_request(key1).unwrap();
        let u2 = WebSocketUpgrade::from_request(key2).unwrap();
        assert_ne!(u1.accept_key(), u2.accept_key());
    }

    // ─── Full handler integration ─────────────────────────────────────

    #[test]
    fn handler_pattern_produces_correct_response() {
        // Simulate a handler that receives WebSocketUpgrade and returns Response.
        fn ws_handler(req: Request) -> Response {
            let upgrade = match WebSocketUpgrade::from_request(req) {
                Ok(u) => u,
                Err(rej) => return rej.into_response(),
            };
            upgrade.protocols(["chat"]).into_response()
        }

        let req = Request::new("GET", "/ws")
            .with_header("upgrade", "websocket")
            .with_header("connection", "Upgrade")
            .with_header("sec-websocket-version", "13")
            .with_header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==")
            .with_header("sec-websocket-protocol", "chat, superchat");

        let resp = ws_handler(req);
        assert_eq!(resp.status, StatusCode::SWITCHING_PROTOCOLS);
        assert_eq!(resp.headers.get("upgrade").unwrap(), "websocket");
        assert_eq!(resp.headers.get("connection").unwrap(), "Upgrade");
        assert_eq!(
            resp.headers.get("sec-websocket-accept").unwrap(),
            "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
        );
        assert_eq!(resp.headers.get("sec-websocket-protocol").unwrap(), "chat");
    }

    #[test]
    fn handler_pattern_rejects_non_ws_request() {
        fn ws_handler(req: Request) -> Response {
            let upgrade = match WebSocketUpgrade::from_request(req) {
                Ok(u) => u,
                Err(rej) => return rej.into_response(),
            };
            upgrade.into_response()
        }

        // Normal HTTP request (not a WebSocket upgrade).
        let req = Request::new("GET", "/ws");
        let resp = ws_handler(req);
        assert_eq!(resp.status, StatusCode::BAD_REQUEST);
    }

    // ─── ServerHandshake compatibility ────────────────────────────────

    #[test]
    fn upgrade_accept_key_matches_server_handshake() {
        // Verify our accept key matches what the net::websocket layer computes.
        let key = "dGhlIHNhbXBsZSBub25jZQ==";
        let our_accept = compute_accept_key(key);

        let server = ServerHandshake::new();
        let http_req = crate::net::websocket::HttpRequest::parse(
            format!(
                "GET /ws HTTP/1.1\r\n\
                 Upgrade: websocket\r\n\
                 Connection: Upgrade\r\n\
                 Sec-WebSocket-Key: {key}\r\n\
                 Sec-WebSocket-Version: 13\r\n\
                 \r\n"
            )
            .as_bytes(),
        )
        .unwrap();

        let accept_response = server.accept(&http_req).unwrap();
        assert_eq!(our_accept, accept_response.accept_key);
    }
}