ultimo 0.6.1

Modern Rust web framework with automatic TypeScript client generation
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
//! WebSocket upgrade mechanism for Hyper

use super::connection::{ConnectionHandler, WebSocket};
use super::frame::Message;
use super::pubsub::ChannelManager;
use super::WebSocketConfig;
use bytes::Bytes;
use http_body_util::Full;
use hyper::header::{
    CONNECTION, ORIGIN, SEC_WEBSOCKET_ACCEPT, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_VERSION, UPGRADE,
};
use hyper::{Request as HyperRequest, Response as HyperResponse, StatusCode};
use sha1::{Digest, Sha1};
use std::future::Future;
use std::sync::Arc;
use tokio::sync::mpsc;

const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

/// WebSocket upgrade builder
pub struct WebSocketUpgrade<T = ()> {
    request: HyperRequest<hyper::body::Incoming>,
    data: Option<T>,
    headers: Vec<(String, String)>,
    protocols: Vec<String>,
    config: WebSocketConfig,
    channel_manager: Arc<ChannelManager>,
    allowed_origins: Vec<String>,
}

impl<T> WebSocketUpgrade<T>
where
    T: Send + 'static,
{
    /// Create new WebSocket upgrade from HTTP request
    pub fn new(request: HyperRequest<hyper::body::Incoming>) -> Self {
        Self {
            request,
            data: None,
            headers: Vec::new(),
            protocols: Vec::new(),
            config: WebSocketConfig::default(),
            channel_manager: Arc::new(ChannelManager::new()),
            allowed_origins: Vec::new(),
        }
    }

    /// Set typed context data for the WebSocket
    pub fn with_data(mut self, data: T) -> Self {
        self.data = Some(data);
        self
    }

    /// Add custom header to upgrade response
    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((key.into(), value.into()));
        self
    }

    /// Set accepted WebSocket subprotocols
    pub fn with_protocols(mut self, protocols: Vec<String>) -> Self {
        self.protocols = protocols;
        self
    }

    /// Set WebSocket configuration
    pub fn with_config(mut self, config: WebSocketConfig) -> Self {
        self.config = config;
        self
    }

    /// Use shared channel manager for pub/sub
    pub fn with_channel_manager(mut self, channel_manager: Arc<ChannelManager>) -> Self {
        self.channel_manager = channel_manager;
        self
    }

    /// Restrict the handshake to the given `Origin` header allow-list —
    /// defense against Cross-Site WebSocket Hijacking (a page on another
    /// origin opening a WebSocket connection to this server; browsers don't
    /// enforce same-origin for WebSocket the way they do for `fetch`).
    ///
    /// **Empty (default) disables the check.** Set this whenever the
    /// connection carries ambient authority (cookies). The literal `"*"`
    /// matches any origin; otherwise comparison is an exact, case-sensitive
    /// match against the full `Origin` value (e.g. `"https://example.com"`).
    /// A request missing the `Origin` header is rejected once this list is
    /// non-empty.
    pub fn with_allowed_origins(mut self, origins: Vec<String>) -> Self {
        self.allowed_origins = origins;
        self
    }

    /// Set callback to be executed when WebSocket is upgraded
    pub fn on_upgrade<F, Fut>(self, callback: F) -> HyperResponse<Full<Bytes>>
    where
        F: FnOnce(WebSocket<T>) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
        T: Send + 'static,
    {
        // Validate WebSocket upgrade request
        if !is_valid_upgrade_request(&self.request) {
            return HyperResponse::builder()
                .status(StatusCode::BAD_REQUEST)
                .body(Full::new(Bytes::from("Invalid WebSocket upgrade request")))
                .unwrap();
        }

        // Origin allow-list (Cross-Site WebSocket Hijacking defense).
        if !origin_allowed(&self.allowed_origins, request_origin(&self.request)) {
            return HyperResponse::builder()
                .status(StatusCode::FORBIDDEN)
                .body(Full::new(Bytes::from("Origin not allowed")))
                .unwrap();
        }

        // Extract WebSocket key
        let key = match self.request.headers().get(SEC_WEBSOCKET_KEY) {
            Some(key) => key.to_str().unwrap_or(""),
            None => {
                return HyperResponse::builder()
                    .status(StatusCode::BAD_REQUEST)
                    .body(Full::new(Bytes::from("Missing Sec-WebSocket-Key header")))
                    .unwrap();
            }
        };

        // Calculate accept key
        let accept_key = calculate_accept_key(key);

        // Build upgrade response
        let mut response = HyperResponse::builder()
            .status(StatusCode::SWITCHING_PROTOCOLS)
            .header(UPGRADE, "websocket")
            .header(CONNECTION, "Upgrade")
            .header(SEC_WEBSOCKET_ACCEPT, accept_key);

        // Add custom headers
        for (key, value) in self.headers {
            response = response.header(key, value);
        }

        let response = response.body(Full::new(Bytes::new())).unwrap();

        // Spawn upgrade handler
        let data = self.data.expect("WebSocket data not set");
        let channel_manager = self.channel_manager;
        let config = Arc::new(self.config);

        tokio::spawn(async move {
            match hyper::upgrade::on(self.request).await {
                Ok(upgraded) => {
                    let (handler, sender, mut incoming_rx, mut _drain_rx) =
                        ConnectionHandler::new(upgraded, channel_manager.clone(), config.clone());
                    let connection_id = uuid::Uuid::new_v4();
                    let remote_addr = None; // TODO: Get from request

                    let ws = WebSocket::new(
                        data,
                        sender,
                        channel_manager,
                        connection_id,
                        remote_addr,
                        config.clone(),
                    );

                    // Spawn the connection handler
                    let handler_task = tokio::spawn(async move {
                        if let Err(e) = handler.handle().await {
                            tracing::error!("WebSocket handler error: {}", e);
                        }
                    });

                    // Spawn user callback with message receiver
                    let callback_task = tokio::spawn(async move {
                        // Call user callback first
                        callback(ws).await;

                        // Keep receiving messages to keep task alive
                        while incoming_rx.recv().await.is_some() {
                            // Messages handled by user's on_message callback
                        }
                    });

                    // Wait for both tasks
                    let _ = tokio::join!(handler_task, callback_task);
                }
                Err(e) => {
                    tracing::error!("WebSocket upgrade error: {}", e);
                }
            }
        });

        response
    }

    /// Set callback that receives incoming messages through a channel
    pub fn on_upgrade_with_receiver<F, Fut>(self, callback: F) -> HyperResponse<Full<Bytes>>
    where
        F: FnOnce(
                WebSocket<T>,
                mpsc::UnboundedReceiver<Message>,
                mpsc::UnboundedReceiver<()>,
            ) -> Fut
            + Send
            + 'static,
        Fut: Future<Output = ()> + Send + 'static,
        T: Send + 'static,
    {
        // Validate WebSocket upgrade request
        if !is_valid_upgrade_request(&self.request) {
            return HyperResponse::builder()
                .status(StatusCode::BAD_REQUEST)
                .body(Full::new(Bytes::from("Invalid WebSocket upgrade request")))
                .unwrap();
        }

        // Origin allow-list (Cross-Site WebSocket Hijacking defense).
        if !origin_allowed(&self.allowed_origins, request_origin(&self.request)) {
            return HyperResponse::builder()
                .status(StatusCode::FORBIDDEN)
                .body(Full::new(Bytes::from("Origin not allowed")))
                .unwrap();
        }

        // Extract WebSocket key
        let key = match self.request.headers().get(SEC_WEBSOCKET_KEY) {
            Some(key) => key.to_str().unwrap_or(""),
            None => {
                return HyperResponse::builder()
                    .status(StatusCode::BAD_REQUEST)
                    .body(Full::new(Bytes::from("Missing Sec-WebSocket-Key header")))
                    .unwrap();
            }
        };

        // Calculate accept key
        let accept_key = calculate_accept_key(key);

        // Build upgrade response
        let mut response = HyperResponse::builder()
            .status(StatusCode::SWITCHING_PROTOCOLS)
            .header(UPGRADE, "websocket")
            .header(CONNECTION, "Upgrade")
            .header(SEC_WEBSOCKET_ACCEPT, accept_key);

        // Add custom headers
        for (key, value) in self.headers {
            response = response.header(key, value);
        }

        let response = response.body(Full::new(Bytes::new())).unwrap();

        // Spawn upgrade handler
        let data = self.data.expect("WebSocket data not set");
        let channel_manager = self.channel_manager;
        let config = Arc::new(self.config);

        tokio::spawn(async move {
            match hyper::upgrade::on(self.request).await {
                Ok(upgraded) => {
                    let (handler, sender, incoming_rx, drain_rx) =
                        ConnectionHandler::new(upgraded, channel_manager.clone(), config.clone());
                    let connection_id = uuid::Uuid::new_v4();
                    let remote_addr = None; // TODO: Get from request

                    let ws = WebSocket::new(
                        data,
                        sender,
                        channel_manager,
                        connection_id,
                        remote_addr,
                        config.clone(),
                    );

                    // Spawn the connection handler
                    let handler_task = tokio::spawn(async move {
                        if let Err(e) = handler.handle().await {
                            tracing::error!("WebSocket handler error: {}", e);
                        }
                    });

                    // Spawn user callback with message receiver
                    let callback_task = tokio::spawn(async move {
                        callback(ws, incoming_rx, drain_rx).await;
                    });

                    // Wait for both tasks
                    let _ = tokio::join!(handler_task, callback_task);
                }
                Err(e) => {
                    tracing::error!("WebSocket upgrade error: {}", e);
                }
            }
        });

        response
    }

    /// Build the upgrade response without a callback (for manual handling)
    pub fn build(self) -> HyperResponse<Full<Bytes>>
    where
        T: Default,
    {
        self.on_upgrade(|_ws| async {
            // Default handler does nothing
        })
    }
}

/// Check if request is a valid WebSocket upgrade request
fn is_valid_upgrade_request(req: &HyperRequest<hyper::body::Incoming>) -> bool {
    // Must be GET request
    if req.method() != hyper::Method::GET {
        return false;
    }

    // Must have Upgrade: websocket header
    let upgrade = req.headers().get(UPGRADE);
    if upgrade.is_none() || upgrade.unwrap().to_str().unwrap_or("").to_lowercase() != "websocket" {
        return false;
    }

    // Must have Connection: Upgrade header
    let connection = req.headers().get(CONNECTION);
    if connection.is_none() {
        return false;
    }

    // Must have Sec-WebSocket-Version: 13
    let version = req.headers().get(SEC_WEBSOCKET_VERSION);
    if version.is_none() || version.unwrap() != "13" {
        return false;
    }

    // Must have Sec-WebSocket-Key header
    if req.headers().get(SEC_WEBSOCKET_KEY).is_none() {
        return false;
    }

    true
}

/// Extract the `Origin` header value from the upgrade request, if present.
fn request_origin(req: &HyperRequest<hyper::body::Incoming>) -> Option<&str> {
    req.headers().get(ORIGIN).and_then(|v| v.to_str().ok())
}

/// Check `origin` against the configured allow-list.
///
/// An empty `allowed` list disables the check entirely (backward-compatible
/// default). Otherwise `"*"` matches any origin, and a request with no
/// `Origin` header is rejected.
fn origin_allowed(allowed: &[String], origin: Option<&str>) -> bool {
    if allowed.is_empty() {
        return true;
    }
    match origin {
        Some(o) => allowed.iter().any(|a| a == "*" || a == o),
        None => false,
    }
}

/// Calculate WebSocket accept key from client key
fn calculate_accept_key(key: &str) -> String {
    use base64::{engine::general_purpose, Engine as _};
    let mut hasher = Sha1::new();
    hasher.update(key.as_bytes());
    hasher.update(WEBSOCKET_GUID.as_bytes());
    let result = hasher.finalize();
    general_purpose::STANDARD.encode(result)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_calculate_accept_key() {
        let key = "dGhlIHNhbXBsZSBub25jZQ==";
        let accept = calculate_accept_key(key);
        assert_eq!(accept, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
    }

    #[test]
    fn test_origin_allowed_empty_list_permits_all() {
        // Backward-compatible default: no restriction configured.
        assert!(origin_allowed(&[], None));
        assert!(origin_allowed(&[], Some("https://evil.example")));
    }

    #[test]
    fn test_origin_allowed_exact_match() {
        let allowed = vec!["https://example.com".to_string()];
        assert!(origin_allowed(&allowed, Some("https://example.com")));
        assert!(!origin_allowed(&allowed, Some("https://evil.example")));
        assert!(!origin_allowed(&allowed, Some("http://example.com"))); // scheme differs
    }

    #[test]
    fn test_origin_allowed_missing_header_rejected_when_restricted() {
        let allowed = vec!["https://example.com".to_string()];
        assert!(!origin_allowed(&allowed, None));
    }

    #[test]
    fn test_origin_allowed_wildcard() {
        let allowed = vec!["*".to_string()];
        assert!(origin_allowed(&allowed, Some("https://anything.example")));
        assert!(!origin_allowed(&allowed, None)); // still requires the header
    }
}