Skip to main content

slabs_realtime/
lib.rs

1//! In-process topic broadcast hub, presence tracking, and `WebSocket` origin validation for Slabs.
2//!
3//! [`Realtime`] maps string topic names to [`tokio::sync::broadcast`] channels so HTTP handlers
4//! and background jobs can push live updates to connected browsers, tracks Phoenix-style in-memory
5//! presence via [`Realtime::track_presence`] / [`Realtime::list_presence`], and validates
6//! `WebSocket` upgrade origins against Cross-Site WebSocket Hijacking (CSWSH) via
7//! [`validate_ws_origin`].
8//!
9//! # Delivery, memory bounds, and lag semantics
10//!
11//! - Single-node and in-memory: messages and presence stay inside one server process and are not
12//!   persisted or replicated across nodes.
13//! - Zero-leak topics: publishing to a topic with zero active subscribers never allocates a topic
14//!   entry and returns `0`. When the last subscriber drops, its drop guard removes the topic from
15//!   memory.
16//! - Bounded resources: at most [`MAX_TOPICS`] (10,000) concurrent topics and at most
17//!   [`MAX_MESSAGE_DATA_BYTES`] (64 KiB) per published payload.
18//! - Bounded buffer: each topic holds 256 messages per channel. When a slow receiver falls more
19//!   than 256 messages behind, `tokio::sync::broadcast` skips the oldest messages and reports lag.
20//! - SSE resilience: [`Realtime::sse_stream`] ignores lag errors so slow clients stay connected,
21//!   sanitizes event names against CRLF/NUL injection, and sends a `"ping"` keep-alive comment
22//!   every 15 seconds. Direct [`Realtime::subscribe`] callers (such as `WebSocket` loops) receive
23//!   a [`Subscription`] wrapping [`tokio::sync::broadcast::Receiver`] and must handle
24//!   `RecvError::Lagged` explicitly.
25//!
26//! # Usage
27//!
28//! ```rust,no_run
29//! use serde::Serialize;
30//! use serde_json::json;
31//! use slabs_realtime::Realtime;
32//!
33//! #[derive(Serialize)]
34//! struct Ping {
35//!     room_id: &'static str,
36//! }
37//!
38//! fn push_updates(realtime: &Realtime) {
39//!     let _presence = realtime.track_presence("room:lobby", "usr_1", json!({ "name": "Alice" }));
40//!     realtime.publish_html("room:lobby", "message", "<p>Hello</p>");
41//!     realtime.publish_json("room:lobby", "ping", &Ping { room_id: "lobby" });
42//! }
43//!
44//! fn sse_handler(realtime: &Realtime) -> impl axum::response::IntoResponse {
45//!     realtime.sse_stream("room:lobby")
46//! }
47//! ```
48
49use axum::http::{header, HeaderMap, Uri};
50use axum::response::sse::{Event, KeepAlive, Sse};
51use futures_util::Stream;
52use serde::{Deserialize, Serialize};
53use serde_json::{json, Value};
54use std::collections::HashMap;
55use std::convert::Infallible;
56use std::ops::{Deref, DerefMut};
57use std::pin::Pin;
58use std::sync::atomic::{AtomicU64, Ordering};
59use std::sync::{Arc, RwLock};
60use std::task::{Context, Poll};
61use std::time::{Duration, SystemTime, UNIX_EPOCH};
62use tokio::sync::broadcast;
63use tokio_stream::wrappers::BroadcastStream;
64
65/// Maximum number of concurrent active topics tracked in memory.
66pub const MAX_TOPICS: usize = 10_000;
67
68/// Maximum allowed byte length of a single published message payload (64 KiB).
69pub const MAX_MESSAGE_DATA_BYTES: usize = 64 * 1024;
70
71/// Recommended maximum `WebSocket` message size in bytes (64 KiB) for `WebSocketUpgrade::max_message_size`.
72pub const MAX_WS_MESSAGE_BYTES: usize = 64 * 1024;
73
74/// Recommended maximum `WebSocket` frame size in bytes (16 KiB) for `WebSocketUpgrade::max_frame_size`.
75pub const MAX_WS_FRAME_BYTES: usize = 16 * 1024;
76
77type TopicMap = Arc<RwLock<HashMap<String, broadcast::Sender<RealtimeMessage>>>>;
78type PresenceMap = Arc<RwLock<HashMap<String, HashMap<u64, PresenceEntry>>>>;
79
80/// Message delivered over a realtime topic to SSE and `WebSocket` subscribers.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct RealtimeMessage {
83    /// Topic channel name the message was published on.
84    pub topic: String,
85    /// Named event type sent as the SSE `event:` field.
86    pub event: String,
87    /// Serialized message body (plain text, HTML fragment, or JSON).
88    pub data: String,
89}
90
91/// Active presence entry tracked on a realtime topic.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93pub struct PresenceEntry {
94    /// Application-defined presence key (for example a user ID or session ID).
95    pub key: String,
96    /// Arbitrary JSON metadata attached to this presence entry (for example display name or status).
97    pub meta: Value,
98    /// UTC RFC 3339 timestamp when this presence entry joined.
99    pub joined_at: String,
100}
101
102/// Drop guard that removes an empty topic channel when the last subscriber disconnects.
103#[derive(Debug)]
104struct TopicGuard {
105    topics: TopicMap,
106    topic: String,
107    tracked: bool,
108}
109
110impl Drop for TopicGuard {
111    fn drop(&mut self) {
112        if !self.tracked {
113            return;
114        }
115        let mut guard = self
116            .topics
117            .write()
118            .unwrap_or_else(std::sync::PoisonError::into_inner);
119        if let Some(tx) = guard.get(&self.topic) {
120            if tx.receiver_count() == 0 {
121                guard.remove(&self.topic);
122            }
123        }
124    }
125}
126
127/// Subscribed broadcast receiver that automatically cleans up empty topics when dropped.
128#[derive(Debug)]
129pub struct Subscription {
130    // Field order matters: `rx` drops before `_guard` so `receiver_count()` decrements first.
131    rx: broadcast::Receiver<RealtimeMessage>,
132    _guard: TopicGuard,
133}
134
135impl Subscription {
136    /// Receive the next [`RealtimeMessage`] published to the subscribed topic.
137    pub async fn recv(&mut self) -> Result<RealtimeMessage, broadcast::error::RecvError> {
138        self.rx.recv().await
139    }
140
141    /// Attempt to receive a pending [`RealtimeMessage`] without awaiting.
142    pub fn try_recv(&mut self) -> Result<RealtimeMessage, broadcast::error::TryRecvError> {
143        self.rx.try_recv()
144    }
145}
146
147impl Deref for Subscription {
148    type Target = broadcast::Receiver<RealtimeMessage>;
149
150    fn deref(&self) -> &Self::Target {
151        &self.rx
152    }
153}
154
155impl DerefMut for Subscription {
156    fn deref_mut(&mut self) -> &mut Self::Target {
157        &mut self.rx
158    }
159}
160
161/// Guard representing an active presence registration on a topic.
162///
163/// Dropping this guard removes the presence entry and broadcasts an updated `"presence"` JSON
164/// event to all subscribers on the topic.
165#[derive(Debug)]
166pub struct PresenceGuard {
167    realtime: Realtime,
168    topic: String,
169    key: String,
170    conn_id: u64,
171    tracked: bool,
172}
173
174impl Drop for PresenceGuard {
175    fn drop(&mut self) {
176        if !self.tracked {
177            return;
178        }
179        let remaining = {
180            let mut guard = self
181                .realtime
182                .presence
183                .write()
184                .unwrap_or_else(std::sync::PoisonError::into_inner);
185            if let Some(entries) = guard.get_mut(&self.topic) {
186                entries.remove(&self.conn_id);
187                if entries.is_empty() {
188                    guard.remove(&self.topic);
189                    Vec::new()
190                } else {
191                    sorted_presence(entries)
192                }
193            } else {
194                Vec::new()
195            }
196        };
197        self.realtime.publish_json(
198            &self.topic,
199            "presence",
200            &json!({
201                "topic": self.topic,
202                "action": "leave",
203                "key": self.key,
204                "entries": remaining,
205            }),
206        );
207    }
208}
209
210struct SseTopicStream {
211    // Field order matters: `inner` drops its broadcast receiver before `_guard` checks receiver_count.
212    inner: BroadcastStream<RealtimeMessage>,
213    _guard: TopicGuard,
214}
215
216impl Stream for SseTopicStream {
217    type Item = Result<Event, Infallible>;
218
219    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
220        loop {
221            match Pin::new(&mut self.inner).poll_next(cx) {
222                Poll::Ready(Some(Ok(msg))) => {
223                    let event_name = sanitize_event_name(&msg.event);
224                    return Poll::Ready(Some(Ok(Event::default()
225                        .event(event_name)
226                        .data(msg.data))));
227                }
228                Poll::Ready(Some(Err(_))) => {
229                    // Skip lagged broadcast errors so slow SSE clients stay connected.
230                }
231                Poll::Ready(None) => return Poll::Ready(None),
232                Poll::Pending => return Poll::Pending,
233            }
234        }
235    }
236}
237
238/// Clonable, in-memory topic broadcast and presence hub for SSE and `WebSockets`.
239///
240/// Topics are created lazily on subscribe (capped at [`MAX_TOPICS`]) with a 256-message ring
241/// buffer per topic and automatically removed when the last subscriber disconnects.
242#[derive(Debug, Clone)]
243pub struct Realtime {
244    topics: TopicMap,
245    presence: PresenceMap,
246    next_presence_id: Arc<AtomicU64>,
247}
248
249impl Default for Realtime {
250    fn default() -> Self {
251        Self {
252            topics: Arc::new(RwLock::new(HashMap::new())),
253            presence: Arc::new(RwLock::new(HashMap::new())),
254            next_presence_id: Arc::new(AtomicU64::new(1)),
255        }
256    }
257}
258
259impl Realtime {
260    /// Create an empty in-memory broadcast and presence hub.
261    #[must_use]
262    pub fn new() -> Self {
263        Self::default()
264    }
265
266    /// Return the current number of active topics with at least one subscriber.
267    #[must_use]
268    pub fn active_topic_count(&self) -> usize {
269        self.topics
270            .read()
271            .unwrap_or_else(std::sync::PoisonError::into_inner)
272            .len()
273    }
274
275    fn subscribe_inner(&self, topic: &str) -> (broadcast::Receiver<RealtimeMessage>, TopicGuard) {
276        {
277            let guard = self
278                .topics
279                .read()
280                .unwrap_or_else(std::sync::PoisonError::into_inner);
281            if let Some(tx) = guard.get(topic) {
282                return (
283                    tx.subscribe(),
284                    TopicGuard {
285                        topics: Arc::clone(&self.topics),
286                        topic: topic.to_string(),
287                        tracked: true,
288                    },
289                );
290            }
291        }
292
293        let mut guard = self
294            .topics
295            .write()
296            .unwrap_or_else(std::sync::PoisonError::into_inner);
297        if let Some(tx) = guard.get(topic) {
298            return (
299                tx.subscribe(),
300                TopicGuard {
301                    topics: Arc::clone(&self.topics),
302                    topic: topic.to_string(),
303                    tracked: true,
304                },
305            );
306        }
307
308        if guard.len() >= MAX_TOPICS {
309            guard.retain(|_, tx| tx.receiver_count() > 0);
310        }
311        if guard.len() >= MAX_TOPICS {
312            let (tx, rx) = broadcast::channel(1);
313            drop(tx);
314            return (
315                rx,
316                TopicGuard {
317                    topics: Arc::clone(&self.topics),
318                    topic: topic.to_string(),
319                    tracked: false,
320                },
321            );
322        }
323
324        let (tx, rx) = broadcast::channel(256);
325        guard.insert(topic.to_string(), tx);
326        (
327            rx,
328            TopicGuard {
329                topics: Arc::clone(&self.topics),
330                topic: topic.to_string(),
331                tracked: true,
332            },
333        )
334    }
335
336    /// Subscribe to raw broadcast messages on `topic` for custom SSE or `WebSocket` loops.
337    ///
338    /// Slow receivers that fall more than 256 messages behind receive `RecvError::Lagged`.
339    /// Dropping the returned [`Subscription`] removes `topic` when no subscribers remain.
340    pub fn subscribe(&self, topic: &str) -> Subscription {
341        let (rx, guard) = self.subscribe_inner(topic);
342        Subscription { rx, _guard: guard }
343    }
344
345    /// Publish a text payload to `topic` under `event` and return the active subscriber count.
346    ///
347    /// Returns `0` without allocating a topic entry when `topic` has no active subscribers or
348    /// when `data` exceeds [`MAX_MESSAGE_DATA_BYTES`] (64 KiB). Strips `\r`, `\n`, and `\0`
349    /// from `event` (falling back to `"message"`).
350    pub fn publish_text(&self, topic: &str, event: &str, data: impl Into<String>) -> usize {
351        let data = data.into();
352        if data.len() > MAX_MESSAGE_DATA_BYTES {
353            return 0;
354        }
355        let tx = {
356            let guard = self
357                .topics
358                .read()
359                .unwrap_or_else(std::sync::PoisonError::into_inner);
360            let Some(tx) = guard.get(topic) else {
361                return 0;
362            };
363            tx.clone()
364        };
365        let msg = RealtimeMessage {
366            topic: topic.to_string(),
367            event: sanitize_event_name(event),
368            data,
369        };
370        tx.send(msg).unwrap_or(0)
371    }
372
373    /// Serialize `payload` as JSON and publish it to `topic` under `event`.
374    ///
375    /// Falls back to `"{}"` if serialization fails. Returns the active subscriber count.
376    pub fn publish_json<T: Serialize>(&self, topic: &str, event: &str, payload: &T) -> usize {
377        let data = serde_json::to_string(payload).unwrap_or_else(|_| "{}".into());
378        self.publish_text(topic, event, data)
379    }
380
381    /// Publish an HTML fragment to `topic` under `event` for HTMX `sse-swap="<event>"` listeners.
382    ///
383    /// Returns the active subscriber count.
384    pub fn publish_html(&self, topic: &str, event: &str, html: impl Into<String>) -> usize {
385        self.publish_text(topic, event, html)
386    }
387
388    /// Track an active presence entry for `key` on `topic` and broadcast a `"presence"` update.
389    ///
390    /// Hold the returned [`PresenceGuard`] for the lifetime of the connection (such as an SSE or
391    /// `WebSocket` task). Dropping it removes the entry and broadcasts the departure.
392    pub fn track_presence(
393        &self,
394        topic: &str,
395        key: impl Into<String>,
396        meta: Value,
397    ) -> PresenceGuard {
398        let key = key.into();
399        let conn_id = self.next_presence_id.fetch_add(1, Ordering::Relaxed);
400        let entry = PresenceEntry {
401            key: key.clone(),
402            meta,
403            joined_at: utc_now_rfc3339(),
404        };
405
406        let (tracked, entries_snapshot) = {
407            let mut guard = self
408                .presence
409                .write()
410                .unwrap_or_else(std::sync::PoisonError::into_inner);
411            if !guard.contains_key(topic) && guard.len() >= MAX_TOPICS {
412                guard.retain(|_, m| !m.is_empty());
413            }
414            if !guard.contains_key(topic) && guard.len() >= MAX_TOPICS {
415                (false, Vec::new())
416            } else {
417                let map = guard.entry(topic.to_string()).or_default();
418                map.insert(conn_id, entry);
419                (true, sorted_presence(map))
420            }
421        };
422
423        if tracked {
424            self.publish_json(
425                topic,
426                "presence",
427                &json!({
428                    "topic": topic,
429                    "action": "join",
430                    "key": key,
431                    "entries": entries_snapshot,
432                }),
433            );
434        }
435
436        PresenceGuard {
437            realtime: self.clone(),
438            topic: topic.to_string(),
439            key,
440            conn_id,
441            tracked,
442        }
443    }
444
445    /// List all currently active [`PresenceEntry`] values tracked on `topic`.
446    #[must_use]
447    pub fn list_presence(&self, topic: &str) -> Vec<PresenceEntry> {
448        let guard = self
449            .presence
450            .read()
451            .unwrap_or_else(std::sync::PoisonError::into_inner);
452        guard.get(topic).map_or_else(Vec::new, sorted_presence)
453    }
454
455    /// Build an Axum SSE response subscribed to `topic` with a 15-second `"ping"` keep-alive.
456    ///
457    /// Lagged broadcast errors are skipped so slow clients remain connected, and the topic is
458    /// cleaned up automatically when the SSE stream closes.
459    pub fn sse_stream(&self, topic: &str) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
460        let (rx, guard) = self.subscribe_inner(topic);
461        let stream = SseTopicStream {
462            inner: BroadcastStream::new(rx),
463            _guard: guard,
464        };
465        Sse::new(stream).keep_alive(
466            KeepAlive::new()
467                .interval(Duration::from_secs(15))
468                .text("ping"),
469        )
470    }
471}
472
473/// Validate `WebSocket` upgrade request headers against Cross-Site WebSocket Hijacking (CSWSH).
474///
475/// Rejects requests with `Sec-Fetch-Site: cross-site`. Requires a valid `Origin` header whose
476/// full origin matches an entry in `allowed_origins` (case-insensitive) or whose authority
477/// (`host[:port]`) matches the request `Host` header.
478#[must_use]
479pub fn validate_ws_origin(headers: &HeaderMap, allowed_origins: &[String]) -> bool {
480    if headers
481        .get("sec-fetch-site")
482        .and_then(|v| v.to_str().ok())
483        .is_some_and(|v| v.trim().eq_ignore_ascii_case("cross-site"))
484    {
485        return false;
486    }
487
488    let Some(origin_raw) = headers
489        .get(header::ORIGIN)
490        .and_then(|v| v.to_str().ok())
491        .map(str::trim)
492        .filter(|v| !v.is_empty() && !v.eq_ignore_ascii_case("null"))
493    else {
494        return false;
495    };
496
497    let Ok(origin_uri) = origin_raw.parse::<Uri>() else {
498        return false;
499    };
500    let Some(scheme) = origin_uri.scheme_str() else {
501        return false;
502    };
503    if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
504        return false;
505    }
506    let Some(authority) = origin_uri.authority() else {
507        return false;
508    };
509    if authority.as_str().contains('@') {
510        return false;
511    }
512
513    if allowed_origins
514        .iter()
515        .any(|allowed| allowed.trim().eq_ignore_ascii_case(origin_raw))
516    {
517        return true;
518    }
519
520    let Some(host_raw) = headers
521        .get(header::HOST)
522        .and_then(|v| v.to_str().ok())
523        .map(str::trim)
524        .filter(|v| !v.is_empty())
525    else {
526        return false;
527    };
528
529    authorities_match(scheme, authority.as_str(), host_raw)
530}
531
532fn authorities_match(scheme: &str, origin_authority: &str, host_header: &str) -> bool {
533    if origin_authority.eq_ignore_ascii_case(host_header) {
534        return true;
535    }
536    let default_port = if scheme.eq_ignore_ascii_case("https") {
537        ":443"
538    } else {
539        ":80"
540    };
541    let norm_origin = origin_authority
542        .strip_suffix(default_port)
543        .unwrap_or(origin_authority);
544    let norm_host = host_header
545        .strip_suffix(default_port)
546        .unwrap_or(host_header);
547    norm_origin.eq_ignore_ascii_case(norm_host)
548}
549
550fn sanitize_event_name(event: &str) -> String {
551    let clean: String = event
552        .chars()
553        .filter(|c| !matches!(c, '\r' | '\n' | '\0'))
554        .collect();
555    if clean.trim().is_empty() {
556        "message".to_string()
557    } else {
558        clean
559    }
560}
561
562fn sorted_presence(map: &HashMap<u64, PresenceEntry>) -> Vec<PresenceEntry> {
563    let mut entries: Vec<PresenceEntry> = map.values().cloned().collect();
564    entries.sort_by(|a, b| a.joined_at.cmp(&b.joined_at).then(a.key.cmp(&b.key)));
565    entries
566}
567
568fn utc_now_rfc3339() -> String {
569    let dur = SystemTime::now()
570        .duration_since(UNIX_EPOCH)
571        .unwrap_or_default();
572    let secs = dur.as_secs();
573    let days = i64::try_from(secs / 86_400).unwrap_or(0);
574    let rem = secs % 86_400;
575    let hour = rem / 3600;
576    let min = (rem % 3600) / 60;
577    let sec = rem % 60;
578
579    // Howard Hinnant's civil_from_days algorithm (days since 1970-01-01).
580    let z = days + 719_468;
581    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
582    let doe = u64::try_from(z - era * 146_097).unwrap_or(0);
583    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
584    let y = i64::try_from(yoe).unwrap_or(0) + era * 400;
585    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
586    let mp = (5 * doy + 2) / 153;
587    let d = doy - (153 * mp + 2) / 5 + 1;
588    let m = if mp < 10 { mp + 3 } else { mp - 9 };
589    let y = if m <= 2 { y + 1 } else { y };
590
591    format!("{y:04}-{m:02}-{d:02}T{hour:02}:{min:02}:{sec:02}Z")
592}
593
594#[cfg(test)]
595mod tests {
596    use super::*;
597    use axum::http::HeaderValue;
598
599    #[test]
600    fn publish_without_subscribers_does_not_leak_topics() {
601        let rt = Realtime::new();
602        for i in 0..500 {
603            let count = rt.publish_text(&format!("ephemeral:{i}"), "ping", "hi");
604            assert_eq!(count, 0);
605        }
606        assert_eq!(rt.active_topic_count(), 0);
607    }
608
609    #[tokio::test]
610    async fn dropping_last_subscriber_removes_topic() {
611        let rt = Realtime::new();
612        {
613            let mut sub1 = rt.subscribe("room:1");
614            let mut sub2 = rt.subscribe("room:1");
615            assert_eq!(rt.active_topic_count(), 1);
616            assert_eq!(rt.publish_text("room:1", "msg", "hello"), 2);
617            assert_eq!(sub1.recv().await.unwrap().data, "hello");
618            assert_eq!(sub2.recv().await.unwrap().data, "hello");
619            drop(sub1);
620            assert_eq!(rt.active_topic_count(), 1);
621        }
622        assert_eq!(rt.active_topic_count(), 0);
623    }
624
625    #[tokio::test]
626    async fn sanitizes_event_names_and_enforces_payload_limit() {
627        let rt = Realtime::new();
628        let mut sub = rt.subscribe("room:sec");
629
630        assert_eq!(
631            rt.publish_text("room:sec", "evil\r\ndata: injected\0", "ok"),
632            1
633        );
634        let msg = sub.recv().await.unwrap();
635        assert!(!msg.event.contains('\r'));
636        assert!(!msg.event.contains('\n'));
637        assert!(!msg.event.contains('\0'));
638
639        assert_eq!(rt.publish_text("room:sec", "\r\n\0", "fallback"), 1);
640        let msg2 = sub.recv().await.unwrap();
641        assert_eq!(msg2.event, "message");
642
643        let oversized = "a".repeat(MAX_MESSAGE_DATA_BYTES + 1);
644        assert_eq!(rt.publish_text("room:sec", "big", oversized), 0);
645    }
646
647    #[tokio::test]
648    async fn presence_tracks_lists_and_broadcasts_on_join_and_drop() {
649        let rt = Realtime::new();
650        let mut sub = rt.subscribe("room:lobby");
651
652        {
653            let _g1 = rt.track_presence("room:lobby", "usr_1", json!({ "name": "Alice" }));
654            let join_msg = sub.recv().await.unwrap();
655            assert_eq!(join_msg.event, "presence");
656            assert!(join_msg.data.contains("\"action\":\"join\""));
657            assert!(join_msg.data.contains("usr_1"));
658
659            let list = rt.list_presence("room:lobby");
660            assert_eq!(list.len(), 1);
661            assert_eq!(list[0].key, "usr_1");
662            assert_eq!(list[0].meta, json!({ "name": "Alice" }));
663            assert!(list[0].joined_at.ends_with('Z'));
664        }
665
666        let leave_msg = sub.recv().await.unwrap();
667        assert_eq!(leave_msg.event, "presence");
668        assert!(leave_msg.data.contains("\"action\":\"leave\""));
669        assert_eq!(rt.list_presence("room:lobby"), Vec::new());
670    }
671
672    #[test]
673    fn validate_ws_origin_blocks_cswsh_and_allows_same_or_configured_origin() {
674        // Same-origin passes
675        let mut same = HeaderMap::new();
676        same.insert(header::HOST, HeaderValue::from_static("app.example.com"));
677        same.insert(
678            header::ORIGIN,
679            HeaderValue::from_static("https://app.example.com"),
680        );
681        same.insert("sec-fetch-site", HeaderValue::from_static("same-origin"));
682        assert!(validate_ws_origin(&same, &[]));
683
684        // Cross-site Sec-Fetch-Site rejected even if Origin matches Host
685        let mut cross_site = same.clone();
686        cross_site.insert("sec-fetch-site", HeaderValue::from_static("cross-site"));
687        assert!(!validate_ws_origin(&cross_site, &[]));
688
689        // Mismatched Origin rejected unless allowlisted
690        let mut evil = HeaderMap::new();
691        evil.insert(header::HOST, HeaderValue::from_static("app.example.com"));
692        evil.insert(
693            header::ORIGIN,
694            HeaderValue::from_static("https://evil.test"),
695        );
696        assert!(!validate_ws_origin(&evil, &[]));
697        assert!(validate_ws_origin(
698            &evil,
699            &["https://evil.test".to_string()]
700        ));
701
702        // Missing or null Origin rejected
703        let mut missing = HeaderMap::new();
704        missing.insert(header::HOST, HeaderValue::from_static("app.example.com"));
705        assert!(!validate_ws_origin(&missing, &[]));
706        missing.insert(header::ORIGIN, HeaderValue::from_static("null"));
707        assert!(!validate_ws_origin(&missing, &[]));
708    }
709}