resuma 0.4.1

Resuma — SSR + Resumability + Islands + Server Actions + JS Bridge 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
//! Security primitives for Resuma HTTP servers — CSRF, rate limiting, headers, origin checks.
//!
//! Enabled by default on `ResumaApp::serve()` and `FlowApp::serve()`. Configure via
//! [`SecurityConfig`] or environment variables (see `docs/SECURITY.md`).

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::core::Result;
use crate::core::ResumaError;
use axum::http::{header, HeaderMap, HeaderValue, Request};
use axum::response::Response;
use once_cell::sync::Lazy;
use parking_lot::RwLock;

/// Per-request CSP nonce stored in response extensions after HTML render.
#[derive(Clone, Debug)]
pub struct CspNonce(pub String);

/// Cookie name for double-submit CSRF protection.
pub const CSRF_COOKIE: &str = "__resuma-csrf";
/// Header clients must send on POST (actions + submits).
pub const CSRF_HEADER: &str = "x-resuma-csrf";
/// Form field name for progressive-enhancement submits.
pub const CSRF_FIELD: &str = "_csrf";

static CONFIG: Lazy<RwLock<SecurityConfig>> = Lazy::new(|| RwLock::new(SecurityConfig::from_env()));

static RATE_BUCKETS: Lazy<RwLock<HashMap<String, Vec<Instant>>>> =
    Lazy::new(|| RwLock::new(HashMap::new()));

/// Global security configuration (shared by ResumaApp and FlowApp).
#[derive(Debug, Clone)]
pub struct SecurityConfig {
    /// Require CSRF token on `POST /_resuma/action/*` and `POST /_resuma/submit/*`.
    pub csrf: bool,
    /// Validate `Origin` / `Referer` on mutating requests (same-origin).
    pub origin_check: bool,
    /// Trust `X-Forwarded-For` / `X-Forwarded-Proto` (set `RESUMA_TRUST_PROXY=1` behind Fly/nginx).
    pub trust_proxy: bool,
    /// Max POST body size in bytes.
    pub body_limit_bytes: usize,
    /// Max action RPC calls per client IP per minute.
    pub actions_per_minute: u32,
    /// Max form submits per client IP per minute.
    pub submits_per_minute: u32,
    /// Hide `/_resuma/benchmark.json` in production.
    pub hide_benchmark: bool,
    /// Sanitize error messages returned to clients.
    pub production: bool,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self::from_env()
    }
}

impl SecurityConfig {
    pub fn from_env() -> Self {
        let production = matches!(
            std::env::var("RESUMA_ENV").as_deref(),
            Ok("production") | Ok("prod")
        );
        let trust_proxy = matches!(
            std::env::var("RESUMA_TRUST_PROXY").as_deref(),
            Ok("1") | Ok("true") | Ok("TRUE")
        );
        Self {
            csrf: !env_flag_off("RESUMA_CSRF"),
            origin_check: !env_flag_off("RESUMA_ORIGIN_CHECK"),
            trust_proxy,
            body_limit_bytes: std::env::var("RESUMA_BODY_LIMIT")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1024 * 1024),
            actions_per_minute: std::env::var("RESUMA_RATE_ACTIONS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(120),
            submits_per_minute: std::env::var("RESUMA_RATE_SUBMITS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(60),
            hide_benchmark: production,
            production,
        }
    }
}

fn env_flag_off(name: &str) -> bool {
    matches!(
        std::env::var(name).as_deref(),
        Ok("0") | Ok("false") | Ok("FALSE") | Ok("off")
    )
}

/// Install global security config (call before `serve()` to override env defaults).
pub fn configure(config: SecurityConfig) {
    *CONFIG.write() = config;
}

pub fn config() -> SecurityConfig {
    CONFIG.read().clone()
}

/// Cryptographically random token (32 hex chars).
pub fn random_token() -> String {
    let mut bytes = [0u8; 16];
    getrandom::getrandom(&mut bytes).expect("OS random number generator");
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

pub fn csrf_token() -> String {
    random_token()
}

/// True when the request arrived over HTTPS (direct TLS or `X-Forwarded-Proto`).
pub fn request_is_https<B>(req: &Request<B>) -> bool {
    let cfg = config();
    if cfg.trust_proxy {
        if let Some(proto) = req
            .headers()
            .get("x-forwarded-proto")
            .and_then(|v| v.to_str().ok())
        {
            if proto.eq_ignore_ascii_case("https") {
                return true;
            }
        }
    }
    req.uri().scheme_str() == Some("https")
}

/// Best-effort client IP for rate limiting.
pub fn client_ip<B>(req: &Request<B>) -> String {
    client_ip_from_parts(req.headers(), connect_addr(req))
}

pub fn client_ip_from_parts(headers: &HeaderMap, connect: Option<SocketAddr>) -> String {
    let cfg = config();
    if cfg.trust_proxy {
        if let Some(xff) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()) {
            if let Some(first) = xff.split(',').next() {
                let ip = first.trim();
                if !ip.is_empty() {
                    return ip.to_string();
                }
            }
        }
        if let Some(xri) = headers.get("x-real-ip").and_then(|v| v.to_str().ok()) {
            if !xri.is_empty() {
                return xri.to_string();
            }
        }
    }
    connect
        .map(|a| a.ip().to_string())
        .unwrap_or_else(|| "unknown".to_string())
}

fn connect_addr<B>(req: &Request<B>) -> Option<SocketAddr> {
    req.extensions()
        .get::<axum::extract::ConnectInfo<SocketAddr>>()
        .map(|ci| ci.0)
}

/// Sliding-window rate limit. Returns `Err(RateLimited)` when exceeded.
pub fn check_rate_limit(ip: &str, bucket: &str, limit_per_minute: u32) -> Result<()> {
    if limit_per_minute == 0 {
        return Ok(());
    }
    let key = format!("{bucket}:{ip}");
    let now = Instant::now();
    let window = Duration::from_secs(60);
    let mut map = RATE_BUCKETS.write();
    let entries = map.entry(key).or_default();
    entries.retain(|t| now.duration_since(*t) < window);
    if entries.len() as u32 >= limit_per_minute {
        return Err(ResumaError::RateLimited);
    }
    entries.push(now);
    Ok(())
}

fn header_str(headers: &HeaderMap, name: &str) -> Option<String> {
    headers
        .get(name)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string())
}

fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
    let cookie = header_str(headers, header::COOKIE.as_str())?;
    for part in cookie.split(';') {
        let part = part.trim();
        if let Some((k, v)) = part.split_once('=') {
            if k.trim() == name {
                return Some(v.trim().to_string());
            }
        }
    }
    None
}

/// Validate double-submit CSRF: header (or form field) must match cookie.
pub fn validate_csrf(headers: &HeaderMap, form_csrf: Option<&str>) -> Result<()> {
    let cfg = config();
    if !cfg.csrf {
        return Ok(());
    }
    let cookie = cookie_value(headers, CSRF_COOKIE).ok_or(ResumaError::InvalidCsrf)?;
    let header = header_str(headers, CSRF_HEADER);
    let token = header
        .as_deref()
        .or(form_csrf)
        .ok_or(ResumaError::InvalidCsrf)?;
    if token != cookie || token.len() < 16 {
        return Err(ResumaError::InvalidCsrf);
    }
    Ok(())
}

/// Reject cross-origin POST when `Origin`/`Referer` do not match the host.
pub fn validate_origin(headers: &HeaderMap, host: &str) -> Result<()> {
    let cfg = config();
    if !cfg.origin_check {
        return Ok(());
    }
    let host = host.split(':').next().unwrap_or(host).to_lowercase();

    if let Some(origin) = header_str(headers, header::ORIGIN.as_str()) {
        if !origin_matches_host(&origin, &host) {
            return Err(ResumaError::Forbidden("cross-origin request".into()));
        }
        return Ok(());
    }

    if let Some(referer) = header_str(headers, header::REFERER.as_str()) {
        if !referer_host_matches(&referer, &host) {
            return Err(ResumaError::Forbidden("invalid referer".into()));
        }
    }
    Ok(())
}

fn origin_matches_host(origin: &str, host: &str) -> bool {
    origin
        .strip_prefix("http://")
        .or_else(|| origin.strip_prefix("https://"))
        .and_then(|rest| rest.split('/').next())
        // Browsers include the port in `Origin` (e.g. `http://localhost:3000`);
        // `host` arrives without it, so compare hostnames only.
        .map(|authority| authority.split(':').next().unwrap_or(authority))
        .map(|h| {
            h.eq_ignore_ascii_case(host)
                || h.strip_prefix("www.").unwrap_or(h) == host.strip_prefix("www.").unwrap_or(host)
        })
        .unwrap_or(false)
}

fn referer_host_matches(referer: &str, host: &str) -> bool {
    referer
        .strip_prefix("http://")
        .or_else(|| referer.strip_prefix("https://"))
        .and_then(|rest| rest.split('/').next())
        .map(|authority| authority.split(':').next().unwrap_or(authority))
        .map(|h| h.eq_ignore_ascii_case(host))
        .unwrap_or(false)
}

/// Build `Set-Cookie` for CSRF double-submit.
pub fn csrf_set_cookie(token: &str, https: bool) -> HeaderValue {
    let secure = if https { "; Secure" } else { "" };
    HeaderValue::from_str(&format!(
        "{CSRF_COOKIE}={token}; Path=/; SameSite=Strict; HttpOnly{secure}"
    ))
    .unwrap_or_else(|_| HeaderValue::from_static("invalid"))
}

/// Options passed to [`apply_security_headers`].
#[derive(Debug, Clone, Default)]
pub struct SecurityHeaderOptions {
    pub csp_nonce: Option<String>,
    pub https: bool,
}

/// Apply standard security headers (Helmet-style baseline).
pub fn apply_security_headers(mut response: Response, opts: &SecurityHeaderOptions) -> Response {
    let headers = response.headers_mut();
    if opts.https {
        insert_header(
            headers,
            header::STRICT_TRANSPORT_SECURITY,
            "max-age=63072000; includeSubDomains; preload",
        );
    }
    insert_header(headers, header::X_FRAME_OPTIONS, "DENY");
    insert_header(headers, header::X_CONTENT_TYPE_OPTIONS, "nosniff");
    insert_header(
        headers,
        header::HeaderName::from_static("x-xss-protection"),
        "0",
    );
    insert_header(
        headers,
        header::REFERRER_POLICY,
        "strict-origin-when-cross-origin",
    );
    insert_header(
        headers,
        header::HeaderName::from_static("permissions-policy"),
        "camera=(), microphone=(), geolocation=()",
    );
    insert_header(
        headers,
        header::HeaderName::from_static("cross-origin-opener-policy"),
        "same-origin",
    );
    insert_header(
        headers,
        header::HeaderName::from_static("cross-origin-resource-policy"),
        "same-origin",
    );
    insert_header(
        headers,
        header::HeaderName::from_static("x-dns-prefetch-control"),
        "off",
    );

    let csp = if let Some(nonce) = &opts.csp_nonce {
        // The current resumability runtime compiles small inline handlers,
        // effects, and visible tasks with `new Function`. Keep CSP honest so
        // enabled Resuma features work under the default security headers.
        let mut policy = format!(
            "default-src 'self'; script-src 'self' 'nonce-{nonce}' 'unsafe-eval'; style-src 'self' 'nonce-{nonce}'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
        );
        if opts.https {
            policy.push_str("; upgrade-insecure-requests");
        }
        policy
    } else {
        let mut policy = "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'".to_string();
        if opts.https {
            policy.push_str("; upgrade-insecure-requests");
        }
        policy
    };
    insert_header(headers, header::CONTENT_SECURITY_POLICY, &csp);
    response
}

fn insert_header(headers: &mut axum::http::HeaderMap, name: header::HeaderName, value: &str) {
    if let Ok(v) = HeaderValue::from_str(value) {
        headers.insert(name, v);
    }
}

/// Guard mutating API requests (CSRF + origin + rate limit).
pub fn guard_mutation(
    headers: &HeaderMap,
    host: &str,
    ip: &str,
    bucket: &str,
    limit: u32,
    form_csrf: Option<&str>,
) -> Result<()> {
    check_rate_limit(ip, bucket, limit)?;
    validate_origin(headers, host)?;
    validate_csrf(headers, form_csrf)?;
    Ok(())
}

/// Map [`ResumaError`] to an HTTP status code.
pub fn http_status(err: &ResumaError) -> axum::http::StatusCode {
    axum::http::StatusCode::from_u16(err.status_code())
        .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
}

/// Shared state for security-aware routers.
#[derive(Clone, Default)]
pub struct SecurityState {
    pub config: Arc<SecurityConfig>,
}

impl SecurityState {
    pub fn new(config: SecurityConfig) -> Self {
        Self {
            config: Arc::new(config),
        }
    }

    pub fn current() -> Self {
        Self::new(config())
    }
}

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

    #[test]
    fn origin_matches_ignoring_port() {
        // Browsers send the port in `Origin`; `host` arrives without it.
        assert!(origin_matches_host("http://localhost:3000", "localhost"));
        assert!(origin_matches_host("http://127.0.0.1:3939", "127.0.0.1"));
        assert!(origin_matches_host("https://example.com", "example.com"));
        assert!(origin_matches_host(
            "https://example.com:8443",
            "example.com"
        ));
        assert!(origin_matches_host(
            "https://www.example.com:443",
            "example.com"
        ));
    }

    #[test]
    fn origin_rejects_other_hosts() {
        assert!(!origin_matches_host("http://evil.test:3000", "localhost"));
        assert!(!origin_matches_host(
            "https://attacker.example",
            "example.com"
        ));
    }

    #[test]
    fn referer_matches_ignoring_port() {
        assert!(referer_host_matches(
            "http://localhost:3000/items",
            "localhost"
        ));
        assert!(referer_host_matches(
            "https://example.com:8443/x",
            "example.com"
        ));
        assert!(!referer_host_matches(
            "http://evil.test:3000/x",
            "localhost"
        ));
    }

    #[test]
    fn validate_origin_allows_same_host_with_port() {
        let mut headers = HeaderMap::new();
        headers.insert(header::ORIGIN, "http://localhost:3000".parse().unwrap());
        // host carries the port as it would from the HTTP `Host` header.
        assert!(validate_origin(&headers, "localhost:3000").is_ok());
    }

    #[test]
    fn csp_allows_runtime_compiled_handlers() {
        let res = Response::new(axum::body::Body::empty());
        let res = apply_security_headers(
            res,
            &SecurityHeaderOptions {
                csp_nonce: Some("abc123".into()),
                https: false,
            },
        );
        let csp = res
            .headers()
            .get(header::CONTENT_SECURITY_POLICY)
            .and_then(|v| v.to_str().ok())
            .unwrap();

        assert!(csp.contains("'nonce-abc123'"));
        assert!(csp.contains("'unsafe-eval'"));
    }
}