what-core 1.7.0

Core framework for What - an HTML-first web framework powered by 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
//! Authentication module for the What framework
//!
//! Provides JWT-based authentication with:
//! - Cookie-based JWT storage (HttpOnly, Secure, SameSite)
//! - Configurable protected routes
//! - Session integration for user data
//! - Backend API integration for login/logout

use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::OnceLock;

use crate::Result;
use crate::config::AuthConfig;

/// Auto-generated JWT secret used when no secret is configured.
/// Generated once per process lifetime using cryptographically secure random bytes.
static AUTO_JWT_SECRET: OnceLock<String> = OnceLock::new();

/// Get or generate a fallback JWT secret (32 random bytes, hex-encoded).
fn get_or_generate_jwt_secret() -> &'static str {
    AUTO_JWT_SECRET.get_or_init(|| {
        use rand::RngCore;
        let mut bytes = [0u8; 32];
        rand::thread_rng().fill_bytes(&mut bytes);
        let secret: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
        tracing::warn!(
            "No jwt_secret configured — generated a random secret. \
             JWTs signed by external services will fail validation. \
             Set [auth] jwt_secret in what.toml or WHAT_AUTH_JWT_SECRET env var."
        );
        secret
    })
}

/// JWT claims structure
/// Uses a flexible HashMap to support any claims from the backend
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwtClaims {
    /// Standard JWT claims
    #[serde(default)]
    pub exp: Option<u64>,
    #[serde(default)]
    pub iat: Option<u64>,
    #[serde(default)]
    pub sub: Option<String>,

    /// Custom claims (user_id, email, full_name, etc.)
    #[serde(flatten)]
    pub custom: HashMap<String, Value>,
}

impl JwtClaims {
    /// Extract specified claims into a context map for templates
    pub fn to_context(&self, claim_names: &[String]) -> HashMap<String, Value> {
        let mut context = HashMap::new();

        // Add standard claims if present
        if let Some(sub) = &self.sub {
            context.insert("sub".to_string(), json!(sub));
        }
        if let Some(exp) = self.exp {
            context.insert("exp".to_string(), json!(exp));
        }

        // Add requested custom claims
        for name in claim_names {
            if let Some(value) = self.custom.get(name) {
                context.insert(name.clone(), value.clone());
            }
        }

        context
    }

    /// Check if the token is expired
    pub fn is_expired(&self) -> bool {
        if let Some(exp) = self.exp {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            exp < now
        } else {
            false // No expiration = not expired
        }
    }
}

/// Authentication handler
#[derive(Clone)]
pub struct AuthHandler {
    config: AuthConfig,
}

impl AuthHandler {
    /// Create a new auth handler with the given configuration
    pub fn new(config: AuthConfig) -> Self {
        Self { config }
    }

    /// Load configuration with environment variable overrides
    pub fn from_config_with_env(mut config: AuthConfig) -> Self {
        // Override with environment variables
        if let Ok(val) = std::env::var("WHAT_AUTH_ENABLED") {
            config.enabled = val.parse().unwrap_or(config.enabled);
        }
        if let Ok(val) = std::env::var("WHAT_AUTH_LOGIN_ENDPOINT") {
            config.login_endpoint = Some(val);
        }
        if let Ok(val) = std::env::var("WHAT_AUTH_LOGOUT_ENDPOINT") {
            config.logout_endpoint = Some(val);
        }
        if let Ok(val) = std::env::var("WHAT_AUTH_JWT_SECRET") {
            config.jwt_secret = Some(val);
        }
        if let Ok(val) = std::env::var("WHAT_AUTH_JWT_COOKIE_NAME") {
            config.jwt_cookie_name = val;
        }
        if let Ok(val) = std::env::var("WHAT_AUTH_LOGIN_PATH") {
            config.login_path = val;
        }
        if let Ok(val) = std::env::var("WHAT_AUTH_AFTER_LOGIN") {
            config.after_login = val;
        }

        Self { config }
    }

    /// Check if authentication is enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Check if a path is protected
    pub fn is_protected(&self, path: &str) -> bool {
        if !self.config.enabled {
            return false;
        }

        for pattern in &self.config.protected_paths {
            if pattern_matches(pattern, path) {
                return true;
            }
        }
        false
    }

    /// Get the login path
    pub fn login_path(&self) -> &str {
        &self.config.login_path
    }

    /// Get the after-login redirect path
    pub fn after_login_path(&self) -> &str {
        &self.config.after_login
    }

    /// Get the login endpoint URL
    pub fn login_endpoint(&self) -> Option<&str> {
        self.config.login_endpoint.as_deref()
    }

    /// Get the logout endpoint URL
    pub fn logout_endpoint(&self) -> Option<&str> {
        self.config.logout_endpoint.as_deref()
    }

    /// Get the JWT cookie name
    pub fn jwt_cookie_name(&self) -> &str {
        &self.config.jwt_cookie_name
    }

    /// Get the list of claims to extract
    pub fn jwt_claims(&self) -> &[String] {
        &self.config.jwt_claims
    }

    /// Parse JWT from cookie header
    pub fn parse_jwt_cookie(&self, cookie_header: Option<&str>) -> Option<String> {
        cookie_header.and_then(|header| {
            header
                .split(';')
                .map(|s| s.trim())
                .find(|s| s.starts_with(&format!("{}=", self.config.jwt_cookie_name)))
                .map(|s| s[self.config.jwt_cookie_name.len() + 1..].to_string())
        })
    }

    /// Decode and validate a JWT token.
    ///
    /// Always validates the signature. If no jwt_secret is configured, a random
    /// secret is generated at startup (logged as WARN). This means externally-signed
    /// tokens will be rejected unless the correct secret is provided.
    pub fn decode_jwt(&self, token: &str) -> Result<JwtClaims> {
        let secret = match self.config.jwt_secret {
            Some(ref s) => s.as_str(),
            None => get_or_generate_jwt_secret(),
        };
        let key = DecodingKey::from_secret(secret.as_bytes());
        let validation = Validation::new(Algorithm::HS256);
        let token_data = decode::<JwtClaims>(token, &key, &validation)?;
        Ok(token_data.claims)
    }

    /// Build Set-Cookie header for JWT token
    pub fn build_jwt_cookie(&self, token: &str, max_age: i64, secure: bool) -> String {
        let mut cookie = format!(
            "{}={}; HttpOnly; SameSite=Strict; Path=/; Max-Age={}",
            self.config.jwt_cookie_name, token, max_age
        );

        if secure {
            cookie.push_str("; Secure");
        }

        cookie
    }

    /// Build Set-Cookie header to clear the JWT cookie
    pub fn build_clear_cookie(&self) -> String {
        format!(
            "{}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0",
            self.config.jwt_cookie_name
        )
    }
}

/// Simple glob-style pattern matching
/// Supports:
/// - Exact match: "/admin" matches "/admin"
/// - Wildcard suffix: "/admin/*" matches "/admin/users", "/admin/settings"
/// - Double wildcard: "/api/**" matches "/api/v1/users", "/api/v1/users/123"
fn pattern_matches(pattern: &str, path: &str) -> bool {
    if pattern.ends_with("/**") {
        let prefix = &pattern[..pattern.len() - 3];
        path.starts_with(prefix)
    } else if pattern.ends_with("/*") {
        // Include the trailing slash in prefix for proper matching
        // "/admin/*" → prefix "/admin/" should match "/admin/users" but not "/admin/users/edit"
        let prefix = &pattern[..pattern.len() - 1];
        path.starts_with(prefix) && !path[prefix.len()..].contains('/')
    } else {
        pattern == path
    }
}

/// User context for templates
/// Contains authenticated user information extracted from JWT
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserContext {
    /// Whether the user is authenticated
    pub authenticated: bool,
    /// User claims from JWT
    #[serde(flatten)]
    pub claims: HashMap<String, Value>,
}

impl UserContext {
    /// Create an unauthenticated context
    pub fn unauthenticated() -> Self {
        Self {
            authenticated: false,
            claims: HashMap::new(),
        }
    }

    /// Create an authenticated context from JWT claims
    pub fn from_claims(claims: HashMap<String, Value>) -> Self {
        Self {
            authenticated: true,
            claims,
        }
    }

    /// Convert to JSON Value for template context
    pub fn to_context(&self) -> Value {
        let mut map = serde_json::Map::new();
        map.insert("authenticated".to_string(), json!(self.authenticated));

        // Add all claims
        for (key, value) in &self.claims {
            map.insert(key.clone(), value.clone());
        }

        Value::Object(map)
    }

    /// Extract the user's roles from the JWT claims. Accepts a `roles` claim
    /// (JSON array or comma-separated string) and falls back to a `role` claim.
    pub fn roles(&self) -> Vec<String> {
        self.claims
            .get("roles")
            .or_else(|| self.claims.get("role"))
            .map(|v| match v {
                Value::Array(arr) => arr
                    .iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect(),
                Value::String(s) => s.split(',').map(|r| r.trim().to_string()).collect(),
                _ => Vec::new(),
            })
            .unwrap_or_default()
    }

    /// The `sub` (subject) claim, if present — the stable user identifier.
    pub fn sub(&self) -> Option<String> {
        self.claims.get("sub").and_then(|v| v.as_str().map(String::from))
    }
}

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

    #[test]
    fn test_pattern_matches() {
        // Exact match
        assert!(pattern_matches("/admin", "/admin"));
        assert!(!pattern_matches("/admin", "/admin/users"));

        // Single wildcard
        assert!(pattern_matches("/admin/*", "/admin/users"));
        assert!(pattern_matches("/admin/*", "/admin/settings"));
        assert!(!pattern_matches("/admin/*", "/admin/users/123"));
        assert!(!pattern_matches("/admin/*", "/admin"));

        // Double wildcard
        assert!(pattern_matches("/api/**", "/api/v1"));
        assert!(pattern_matches("/api/**", "/api/v1/users"));
        assert!(pattern_matches("/api/**", "/api/v1/users/123"));
    }

    #[test]
    fn test_jwt_claims_to_context() {
        let claims = JwtClaims {
            exp: Some(1234567890),
            iat: Some(1234567800),
            sub: Some("user123".to_string()),
            custom: [
                ("email".to_string(), json!("user@example.com")),
                ("full_name".to_string(), json!("John Doe")),
                ("role".to_string(), json!("admin")),
            ]
            .into_iter()
            .collect(),
        };

        let context = claims.to_context(&["email".to_string(), "full_name".to_string()]);

        assert_eq!(context.get("email"), Some(&json!("user@example.com")));
        assert_eq!(context.get("full_name"), Some(&json!("John Doe")));
        assert_eq!(context.get("sub"), Some(&json!("user123")));
        assert!(!context.contains_key("role")); // Not requested
    }

    #[test]
    fn test_user_context() {
        let unauthenticated = UserContext::unauthenticated();
        assert!(!unauthenticated.authenticated);

        let authenticated = UserContext::from_claims(
            [("email".to_string(), json!("user@example.com"))]
                .into_iter()
                .collect(),
        );
        assert!(authenticated.authenticated);

        let context = authenticated.to_context();
        assert_eq!(context.get("authenticated"), Some(&json!(true)));
        assert_eq!(context.get("email"), Some(&json!("user@example.com")));
    }

    #[test]
    fn test_auth_handler_parse_jwt_cookie() {
        let config = AuthConfig {
            enabled: true,
            jwt_cookie_name: "w_token".to_string(),
            ..Default::default()
        };
        let handler = AuthHandler::new(config);

        // Test valid cookie header
        let cookie_header = Some("w_token=abc123; other_cookie=xyz");
        let result = handler.parse_jwt_cookie(cookie_header);
        assert_eq!(result, Some("abc123".to_string()));

        // Test cookie at end of header
        let cookie_header = Some("other=value; w_token=def456");
        let result = handler.parse_jwt_cookie(cookie_header);
        assert_eq!(result, Some("def456".to_string()));

        // Test missing cookie
        let cookie_header = Some("other_cookie=xyz");
        let result = handler.parse_jwt_cookie(cookie_header);
        assert!(result.is_none());

        // Test None header
        let result = handler.parse_jwt_cookie(None);
        assert!(result.is_none());
    }

    #[test]
    fn test_auth_handler_is_protected() {
        let config = AuthConfig {
            enabled: true,
            protected_paths: vec![
                "/admin".to_string(),
                "/admin/*".to_string(),
                "/api/**".to_string(),
            ],
            ..Default::default()
        };
        let handler = AuthHandler::new(config);

        // Exact match
        assert!(handler.is_protected("/admin"));

        // Single wildcard match
        assert!(handler.is_protected("/admin/users"));
        assert!(handler.is_protected("/admin/settings"));

        // Single wildcard should NOT match deeper paths
        assert!(!handler.is_protected("/admin/users/123"));

        // Double wildcard matches all depths
        assert!(handler.is_protected("/api/v1"));
        assert!(handler.is_protected("/api/v1/users"));
        assert!(handler.is_protected("/api/v1/users/123"));

        // Non-matching paths
        assert!(!handler.is_protected("/"));
        assert!(!handler.is_protected("/public"));
        assert!(!handler.is_protected("/login"));
    }

    #[test]
    fn test_auth_handler_disabled() {
        let config = AuthConfig {
            enabled: false,
            protected_paths: vec!["/admin/**".to_string()],
            ..Default::default()
        };
        let handler = AuthHandler::new(config);

        // When auth is disabled, nothing should be protected
        assert!(!handler.is_protected("/admin"));
        assert!(!handler.is_protected("/admin/users"));
        assert!(!handler.is_enabled());
    }

    #[test]
    fn test_build_jwt_cookie() {
        let config = AuthConfig {
            enabled: true,
            jwt_cookie_name: "w_token".to_string(),
            ..Default::default()
        };
        let handler = AuthHandler::new(config);

        // Build cookie without Secure flag
        let cookie = handler.build_jwt_cookie("test_token_123", 3600, false);
        assert!(cookie.contains("w_token=test_token_123"));
        assert!(cookie.contains("HttpOnly"));
        assert!(cookie.contains("SameSite=Strict"));
        assert!(cookie.contains("Path=/"));
        assert!(cookie.contains("Max-Age=3600"));
        assert!(!cookie.contains("Secure"));

        // Build cookie with Secure flag
        let cookie = handler.build_jwt_cookie("test_token_123", 3600, true);
        assert!(cookie.contains("Secure"));
    }

    #[test]
    fn test_build_clear_cookie() {
        let config = AuthConfig {
            enabled: true,
            jwt_cookie_name: "w_token".to_string(),
            ..Default::default()
        };
        let handler = AuthHandler::new(config);

        let cookie = handler.build_clear_cookie();
        assert!(cookie.contains("w_token="));
        assert!(cookie.contains("Max-Age=0"));
        assert!(cookie.contains("HttpOnly"));
        assert!(cookie.contains("SameSite=Strict"));
        assert!(cookie.contains("Path=/"));
    }

    #[test]
    fn test_jwt_claims_is_expired() {
        // Not expired (future timestamp)
        let future_exp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 3600; // 1 hour in the future

        let claims = JwtClaims {
            exp: Some(future_exp),
            iat: None,
            sub: None,
            custom: HashMap::new(),
        };
        assert!(!claims.is_expired());

        // Expired (past timestamp)
        let past_exp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 3600; // 1 hour in the past

        let expired_claims = JwtClaims {
            exp: Some(past_exp),
            iat: None,
            sub: None,
            custom: HashMap::new(),
        };
        assert!(expired_claims.is_expired());

        // No expiration = not expired
        let no_exp_claims = JwtClaims {
            exp: None,
            iat: None,
            sub: None,
            custom: HashMap::new(),
        };
        assert!(!no_exp_claims.is_expired());
    }

    #[test]
    fn test_decode_jwt_with_configured_secret() {
        use jsonwebtoken::{EncodingKey, Header, encode};

        let secret = "test_secret_123";
        let config = AuthConfig {
            enabled: true,
            jwt_secret: Some(secret.to_string()),
            ..Default::default()
        };
        let handler = AuthHandler::new(config);

        // Create a valid token with the same secret
        let exp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 3600;

        let claims = JwtClaims {
            exp: Some(exp),
            iat: None,
            sub: Some("user1".to_string()),
            custom: [("email".to_string(), json!("a@b.com"))]
                .into_iter()
                .collect(),
        };

        let token = encode(
            &Header::default(),
            &claims,
            &EncodingKey::from_secret(secret.as_bytes()),
        )
        .unwrap();
        let decoded = handler.decode_jwt(&token).unwrap();
        assert_eq!(decoded.sub, Some("user1".to_string()));
        assert_eq!(decoded.custom.get("email"), Some(&json!("a@b.com")));
    }

    #[test]
    fn test_decode_jwt_rejects_wrong_secret() {
        use jsonwebtoken::{EncodingKey, Header, encode};

        let config = AuthConfig {
            enabled: true,
            jwt_secret: Some("correct_secret".to_string()),
            ..Default::default()
        };
        let handler = AuthHandler::new(config);

        let exp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 3600;

        let claims = JwtClaims {
            exp: Some(exp),
            iat: None,
            sub: None,
            custom: HashMap::new(),
        };

        // Sign with a different secret
        let token = encode(
            &Header::default(),
            &claims,
            &EncodingKey::from_secret(b"wrong_secret"),
        )
        .unwrap();
        let result = handler.decode_jwt(&token);
        assert!(
            result.is_err(),
            "Should reject JWT signed with wrong secret"
        );
    }

    #[test]
    fn test_decode_jwt_no_secret_uses_auto_generated() {
        // When no secret is configured, decode_jwt should use the auto-generated secret.
        // A token signed with an arbitrary secret should be rejected.
        use jsonwebtoken::{EncodingKey, Header, encode};

        let config = AuthConfig {
            enabled: true,
            jwt_secret: None, // No secret configured
            ..Default::default()
        };
        let handler = AuthHandler::new(config);

        let exp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 3600;

        let claims = JwtClaims {
            exp: Some(exp),
            iat: None,
            sub: None,
            custom: HashMap::new(),
        };

        // Sign with an arbitrary secret — this should NOT match the auto-generated one
        let token = encode(
            &Header::default(),
            &claims,
            &EncodingKey::from_secret(b"attacker_secret"),
        )
        .unwrap();
        let result = handler.decode_jwt(&token);
        assert!(
            result.is_err(),
            "Should reject JWT when no secret is configured (auto-generated secret won't match)"
        );
    }

    #[test]
    fn test_auth_handler_getters() {
        let config = AuthConfig {
            enabled: true,
            login_path: "/login".to_string(),
            after_login: "/dashboard".to_string(),
            login_endpoint: Some("https://api.example.com/login".to_string()),
            logout_endpoint: Some("https://api.example.com/logout".to_string()),
            jwt_cookie_name: "auth_token".to_string(),
            jwt_claims: vec!["email".to_string(), "name".to_string()],
            ..Default::default()
        };
        let handler = AuthHandler::new(config);

        assert!(handler.is_enabled());
        assert_eq!(handler.login_path(), "/login");
        assert_eq!(handler.after_login_path(), "/dashboard");
        assert_eq!(
            handler.login_endpoint(),
            Some("https://api.example.com/login")
        );
        assert_eq!(
            handler.logout_endpoint(),
            Some("https://api.example.com/logout")
        );
        assert_eq!(handler.jwt_cookie_name(), "auth_token");
        assert_eq!(
            handler.jwt_claims(),
            &["email".to_string(), "name".to_string()]
        );
    }
}