cedros-login-server 0.0.32

Authentication server for cedros-login with email/password, Google OAuth, and Solana wallet sign-in
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
//! Cookie building utilities for token storage

use axum::{
    http::{header, HeaderValue},
    response::IntoResponse,
    response::Response,
    Json,
};
use serde::Serialize;

use crate::config::CookieConfig;
use crate::models::TokenPair;

/// S-16/MW-03: Validate cookie domain format.
///
/// Valid domains:
/// - Contain only alphanumeric chars, dots, and hyphens
/// - Have at least 2 domain labels (e.g., `example.com`, not just `com`)
/// - Are not pure TLDs like `.com`, `.org`, `.net`
///
/// # Security (MW-03)
///
/// Overly broad domains like `.com` would make cookies accessible to ALL
/// websites on that TLD - a massive security vulnerability. We require
/// at least 2 labels to ensure cookies are scoped to a specific domain.
pub(crate) fn is_valid_cookie_domain(domain: &str) -> bool {
    if domain.is_empty() {
        return false;
    }

    // Check character validity
    if !domain
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
    {
        return false;
    }

    // MW-03: Require at least 2 domain labels
    // Strip leading dot if present (e.g., ".example.com" -> "example.com")
    let stripped = domain.strip_prefix('.').unwrap_or(domain);

    // Reject empty labels (e.g., "example..com" or "example.com.")
    if stripped.split('.').any(|s| s.is_empty()) {
        return false;
    }

    let labels: Vec<&str> = stripped.split('.').collect();

    // Must have at least 2 labels (e.g., "example.com" has 2: ["example", "com"])
    if labels.len() < 2 {
        return false;
    }

    // All labels must be non-empty (handled by filter above) and valid
    // Each label must start and end with alphanumeric (not hyphen)
    labels.iter().all(|label| {
        !label.is_empty()
            && label
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_alphanumeric())
            && label
                .chars()
                .last()
                .is_some_and(|c| c.is_ascii_alphanumeric())
    })
}

/// Build a Set-Cookie header value for the access token
pub fn build_access_cookie(config: &CookieConfig, token: &str, max_age_secs: u64) -> String {
    let path = access_cookie_path(config);
    build_cookie(
        &config.access_cookie_name,
        token,
        max_age_secs,
        &path,
        config,
        true, // HttpOnly
    )
}

/// Build a Set-Cookie header value for the refresh token
pub fn build_refresh_cookie(config: &CookieConfig, token: &str, max_age_secs: u64) -> String {
    let path = refresh_cookie_path(config);
    build_cookie(
        &config.refresh_cookie_name,
        token,
        max_age_secs,
        &path, // Restrict to refresh endpoint (with optional prefix)
        config,
        true, // HttpOnly
    )
}

/// Build a cookie deletion header (expired cookie)
pub fn build_delete_cookie(config: &CookieConfig, name: &str, path: &str) -> String {
    let mut cookie = format!("{}=deleted; Path={}; Max-Age=0", name, path);

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

    cookie.push_str("; HttpOnly");

    match config.same_site.to_lowercase().as_str() {
        "strict" => cookie.push_str("; SameSite=Strict"),
        "none" => cookie.push_str("; SameSite=None"),
        _ => cookie.push_str("; SameSite=Lax"),
    }

    // S-16: Validate domain before including in cookie
    if let Some(ref domain) = config.domain {
        if is_valid_cookie_domain(domain) {
            cookie.push_str(&format!("; Domain={}", domain));
        } else {
            tracing::warn!(
                domain = %domain,
                "Invalid cookie domain format, skipping Domain attribute"
            );
        }
    }

    cookie
}

/// Build a Set-Cookie header value
fn build_cookie(
    name: &str,
    value: &str,
    max_age_secs: u64,
    path: &str,
    config: &CookieConfig,
    http_only: bool,
) -> String {
    let mut cookie = format!(
        "{}={}; Path={}; Max-Age={}",
        name, value, path, max_age_secs
    );

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

    if http_only {
        cookie.push_str("; HttpOnly");
    }

    match config.same_site.to_lowercase().as_str() {
        "strict" => cookie.push_str("; SameSite=Strict"),
        "none" => cookie.push_str("; SameSite=None"),
        _ => cookie.push_str("; SameSite=Lax"),
    }

    // S-16: Validate domain before including in cookie
    if let Some(ref domain) = config.domain {
        if is_valid_cookie_domain(domain) {
            cookie.push_str(&format!("; Domain={}", domain));
        } else {
            tracing::warn!(
                domain = %domain,
                "Invalid cookie domain format, skipping Domain attribute"
            );
        }
    }

    cookie
}

/// Build both access and refresh cookies for a token pair
pub fn build_token_cookies(
    config: &CookieConfig,
    tokens: &TokenPair,
    refresh_expiry_secs: u64,
) -> Vec<String> {
    vec![
        build_access_cookie(config, &tokens.access_token, tokens.expires_in),
        build_refresh_cookie(config, &tokens.refresh_token, refresh_expiry_secs),
    ]
}

/// Build a JSON response and attach auth cookies when enabled.
pub fn build_json_response_with_cookies<T: Serialize>(
    config: &CookieConfig,
    tokens: &TokenPair,
    refresh_expiry_secs: u64,
    response: T,
) -> Response {
    let resp = Json(response).into_response();
    attach_auth_cookies(config, tokens, refresh_expiry_secs, resp)
}

/// Attach auth cookies to an existing response when enabled.
pub fn attach_auth_cookies(
    config: &CookieConfig,
    tokens: &TokenPair,
    refresh_expiry_secs: u64,
    mut response: Response,
) -> Response {
    if !config.enabled {
        return response;
    }

    let cookies = build_token_cookies(config, tokens, refresh_expiry_secs);
    let headers = response.headers_mut();
    for cookie in cookies {
        match HeaderValue::from_str(&cookie) {
            Ok(value) => {
                headers.append(header::SET_COOKIE, value);
            }
            Err(e) => {
                // R-02: Log serialization failures instead of silently ignoring
                tracing::warn!(
                    error = %e,
                    "Failed to serialize auth cookie header value"
                );
            }
        }
    }
    response
}

/// Build deletion cookies for both access and refresh tokens
pub fn build_logout_cookies(config: &CookieConfig) -> Vec<String> {
    let access_path = access_cookie_path(config);
    let refresh_path = refresh_cookie_path(config);
    vec![
        build_delete_cookie(config, &config.access_cookie_name, &access_path),
        build_delete_cookie(config, &config.refresh_cookie_name, &refresh_path),
    ]
}

fn access_cookie_path(config: &CookieConfig) -> String {
    let trimmed = config.path_prefix.trim_end_matches('/');
    if trimmed.is_empty() {
        "/".to_string()
    } else {
        trimmed.to_string()
    }
}

fn refresh_cookie_path(config: &CookieConfig) -> String {
    let trimmed = config.path_prefix.trim_end_matches('/');
    if trimmed.is_empty() {
        "/refresh".to_string()
    } else {
        format!("{}/refresh", trimmed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::response::Response;

    fn test_config() -> CookieConfig {
        CookieConfig {
            enabled: true,
            domain: None,
            secure: false,
            same_site: "lax".to_string(),
            access_cookie_name: "cedros_access".to_string(),
            refresh_cookie_name: "cedros_refresh".to_string(),
            path_prefix: "".to_string(),
        }
    }

    #[test]
    fn test_build_access_cookie() {
        let config = test_config();
        let cookie = build_access_cookie(&config, "test_token", 900);

        assert!(cookie.contains("cedros_access=test_token"));
        assert!(cookie.contains("Path=/"));
        assert!(cookie.contains("Max-Age=900"));
        assert!(cookie.contains("HttpOnly"));
        assert!(cookie.contains("SameSite=Lax"));
    }

    #[test]
    fn test_access_cookie_with_prefix() {
        let mut config = test_config();
        config.path_prefix = "/auth".to_string();

        let cookie = build_access_cookie(&config, "test_token", 900);
        assert!(cookie.contains("Path=/auth"));

        let logout_cookies = build_logout_cookies(&config);
        assert!(logout_cookies[0].contains("Path=/auth"));
    }

    #[test]
    fn test_build_refresh_cookie() {
        let config = test_config();
        let cookie = build_refresh_cookie(&config, "refresh_token", 604800);

        assert!(cookie.contains("cedros_refresh=refresh_token"));
        assert!(cookie.contains("Path=/refresh"));
        assert!(cookie.contains("Max-Age=604800"));
        assert!(cookie.contains("HttpOnly"));
    }

    #[test]
    fn test_secure_cookie() {
        let mut config = test_config();
        config.secure = true;
        let cookie = build_access_cookie(&config, "token", 900);

        assert!(cookie.contains("Secure"));
    }

    #[test]
    fn test_domain_cookie() {
        let mut config = test_config();
        config.domain = Some(".example.com".to_string());
        let cookie = build_access_cookie(&config, "token", 900);

        assert!(cookie.contains("Domain=.example.com"));
    }

    #[test]
    fn test_same_site_strict() {
        let mut config = test_config();
        config.same_site = "strict".to_string();
        let cookie = build_access_cookie(&config, "token", 900);

        assert!(cookie.contains("SameSite=Strict"));
    }

    #[test]
    fn test_delete_cookie() {
        let config = test_config();
        let cookie = build_delete_cookie(&config, "cedros_access", "/");

        assert!(cookie.contains("cedros_access=deleted"));
        assert!(cookie.contains("Max-Age=0"));
    }

    #[test]
    fn test_refresh_cookie_with_prefix() {
        let mut config = test_config();
        config.path_prefix = "/auth".to_string();

        let cookie = build_refresh_cookie(&config, "refresh_token", 60);
        assert!(cookie.contains("Path=/auth/refresh"));

        let logout_cookies = build_logout_cookies(&config);
        assert!(logout_cookies[1].contains("Path=/auth/refresh"));
    }

    #[test]
    fn test_build_json_response_with_cookies_enabled() {
        let config = test_config();
        let tokens = TokenPair {
            access_token: "access".to_string(),
            refresh_token: "refresh".to_string(),
            expires_in: 60,
        };

        let response = build_json_response_with_cookies(&config, &tokens, 120, "ok");
        let cookie_count = response
            .headers()
            .get_all(header::SET_COOKIE)
            .iter()
            .count();
        assert_eq!(cookie_count, 2);
    }

    #[test]
    fn test_build_json_response_with_cookies_disabled() {
        let mut config = test_config();
        config.enabled = false;
        let tokens = TokenPair {
            access_token: "access".to_string(),
            refresh_token: "refresh".to_string(),
            expires_in: 60,
        };

        let response = build_json_response_with_cookies(&config, &tokens, 120, "ok");
        let cookie_count = response
            .headers()
            .get_all(header::SET_COOKIE)
            .iter()
            .count();
        assert_eq!(cookie_count, 0);
    }

    #[test]
    fn test_attach_auth_cookies_on_non_json_response() {
        let config = test_config();
        let tokens = TokenPair {
            access_token: "access".to_string(),
            refresh_token: "refresh".to_string(),
            expires_in: 60,
        };

        let response = Response::new(Body::empty());
        let response = attach_auth_cookies(&config, &tokens, 120, response);
        let cookie_count = response
            .headers()
            .get_all(header::SET_COOKIE)
            .iter()
            .count();
        assert_eq!(cookie_count, 2);
    }

    #[test]
    fn test_is_valid_cookie_domain() {
        // Valid domains
        assert!(is_valid_cookie_domain(".example.com"));
        assert!(is_valid_cookie_domain("example.com"));
        assert!(is_valid_cookie_domain("sub-domain.example.com"));
        assert!(is_valid_cookie_domain("example123.com"));
        assert!(is_valid_cookie_domain("a.b.c.example.com"));

        // Invalid domains (S-16 - character validation)
        assert!(!is_valid_cookie_domain(""));
        assert!(!is_valid_cookie_domain("example.com; Secure"));
        assert!(!is_valid_cookie_domain("example.com\nEvil: header"));
        assert!(!is_valid_cookie_domain("example com"));

        // Invalid domains (MW-03 - structural validation)
        assert!(!is_valid_cookie_domain(".com")); // Pure TLD
        assert!(!is_valid_cookie_domain(".org")); // Pure TLD
        assert!(!is_valid_cookie_domain("com")); // Single label
        assert!(!is_valid_cookie_domain(".")); // Empty labels
        assert!(!is_valid_cookie_domain("example..com")); // Empty label
        assert!(!is_valid_cookie_domain("example.com.")); // Trailing dot
        assert!(!is_valid_cookie_domain("-example.com")); // Label starts with hyphen
        assert!(!is_valid_cookie_domain("example-.com")); // Label ends with hyphen
    }
}