Skip to main content

teamcraft/
auth.rs

1//! Authentication primitives: password hashing, random tokens, cookies and
2//! the request extractors that resolve the current user.
3//!
4//! * Browser users authenticate with a session cookie (`tc_session`).
5//! * API clients authenticate with a personal access token sent as
6//!   `Authorization: Bearer tc_pat_…`. The API never accepts cookies, which
7//!   keeps it immune to CSRF.
8
9use std::{
10    collections::HashMap,
11    net::IpAddr,
12    sync::{LazyLock, Mutex},
13    time::{Duration, Instant},
14};
15
16use argon2::{
17    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
18    Argon2,
19};
20use axum::{
21    extract::{FromRequestParts, OriginalUri},
22    http::{header, request::Parts, HeaderMap},
23};
24use rand::{rngs::OsRng, RngCore};
25use serde::Serialize;
26use sha2::{Digest, Sha256};
27use uuid::Uuid;
28
29use crate::{
30    config::Config,
31    domain::{Role, TokenScope},
32    error::{AppError, AppResult},
33    services, AppState,
34};
35
36pub const SESSION_COOKIE: &str = "tc_session";
37pub const FLASH_COOKIE: &str = "tc_flash";
38pub const SESSION_TOKEN_PREFIX: &str = "tc_sess_";
39pub const API_TOKEN_PREFIX: &str = "tc_pat_";
40
41/// The authenticated user on whose behalf a request is executed.
42#[derive(Clone, Debug, Serialize)]
43pub struct Actor {
44    pub id: Uuid,
45    pub username: String,
46    pub display_name: String,
47    pub role: Role,
48    /// UI skin (see `domain::SKINS`).
49    pub skin: String,
50    /// Preferred CAD program (a format family, see `cadformat::families`);
51    /// `""` = show all files alike.
52    pub preferred_cad: String,
53    /// Project groups the user is a member of.
54    pub projects: Vec<Uuid>,
55    /// Restricted project groups the user is NOT a member of; always empty
56    /// for administrators. Never serialized: it names groups the user may
57    /// not know about. The SQL guards in `services::access` bind it.
58    #[serde(skip)]
59    pub hidden_projects: Vec<Uuid>,
60}
61
62impl Actor {
63    /// Whether the actor may read data of a project group (`None` = items
64    /// without a group, readable by everyone).
65    pub fn can_see_project(&self, project_id: Option<Uuid>) -> bool {
66        project_id.is_none_or(|p| !self.hidden_projects.contains(&p))
67    }
68
69    /// The same actor without the read rights to `groups` (an interface that
70    /// is switched off for them, see `services::project_policy`): they are
71    /// hidden like groups the user is no member of.
72    pub fn without_groups(mut self, groups: &[Uuid]) -> Actor {
73        for g in groups {
74            if !self.hidden_projects.contains(g) {
75                self.hidden_projects.push(*g);
76            }
77        }
78        self.projects.retain(|p| !groups.contains(p));
79        self
80    }
81
82    /// A webhook evaluated as a virtual reader: it sees its own group and
83    /// every internal group; a global webhook (`project_id = None`) sees
84    /// internal groups only. `restricted` = all restricted groups.
85    pub fn for_webhook(project_id: Option<Uuid>, restricted: &[Uuid]) -> Actor {
86        Actor {
87            id: Uuid::nil(),
88            username: "webhook".into(),
89            display_name: "Webhook".into(),
90            role: Role::Viewer,
91            skin: String::new(),
92            preferred_cad: String::new(),
93            projects: project_id.into_iter().collect(),
94            hidden_projects: restricted
95                .iter()
96                .copied()
97                .filter(|p| Some(*p) != project_id)
98                .collect(),
99        }
100    }
101
102    /// An actor for unit tests.
103    #[doc(hidden)]
104    pub fn test(role: Role, projects: Vec<Uuid>, hidden_projects: Vec<Uuid>) -> Actor {
105        Actor {
106            id: Uuid::new_v4(),
107            username: "test".into(),
108            display_name: "Test".into(),
109            role,
110            skin: "teamcraft".into(),
111            preferred_cad: String::new(),
112            projects,
113            hidden_projects,
114        }
115    }
116
117    /// The system itself (background workers): sees everything.
118    pub fn system() -> Actor {
119        Actor {
120            id: Uuid::nil(),
121            username: "system".into(),
122            display_name: "TeamCraft".into(),
123            role: Role::Admin,
124            skin: String::new(),
125            preferred_cad: String::new(),
126            projects: Vec::new(),
127            hidden_projects: Vec::new(),
128        }
129    }
130
131    /// Fails with `403 Forbidden` unless the actor has at least role `min`.
132    pub fn require(&self, min: Role) -> AppResult<()> {
133        if self.role >= min {
134            Ok(())
135        } else {
136            Err(AppError::Forbidden(format!(
137                "This action requires the '{}' role.",
138                min.label()
139            )))
140        }
141    }
142
143    pub fn is_admin(&self) -> bool {
144        self.role >= Role::Admin
145    }
146
147    /// CAD editor or admin (may edit at least somewhere).
148    pub fn can_edit(&self) -> bool {
149        self.role >= Role::Editor
150    }
151
152    /// Whether the actor may modify data of a project group. Admins may edit
153    /// everything, CAD editors only the projects they are members of; items
154    /// without a project (legacy data) are editable by every CAD editor.
155    pub fn can_edit_project(&self, project_id: Option<Uuid>) -> bool {
156        match self.role {
157            Role::Admin => true,
158            Role::Editor => project_id.is_none_or(|p| self.projects.contains(&p)),
159            Role::Viewer => false,
160        }
161    }
162}
163
164// ---------------------------------------------------------------------------
165// Passwords
166// ---------------------------------------------------------------------------
167
168/// Hashes a password with Argon2id (OWASP recommended default parameters).
169pub fn hash_password(password: &str) -> AppResult<String> {
170    let salt = SaltString::generate(&mut OsRng);
171    Argon2::default()
172        .hash_password(password.as_bytes(), &salt)
173        .map(|h| h.to_string())
174        .map_err(|e| AppError::Other(anyhow::anyhow!("password hashing failed: {e}")))
175}
176
177/// Verifies a password against a stored PHC hash string.
178pub fn verify_password(password: &str, hash: &str) -> bool {
179    match PasswordHash::new(hash) {
180        Ok(parsed) => Argon2::default()
181            .verify_password(password.as_bytes(), &parsed)
182            .is_ok(),
183        Err(_) => false,
184    }
185}
186
187/// A valid hash used to spend the same time on unknown usernames as on
188/// wrong passwords, so login timing does not reveal which users exist.
189/// It hashes a random value made at start-up: the hash never verifies
190/// anything (the unknown-user branch always answers `false`), so the code
191/// holds no fixed "dummy password" either.
192static DUMMY_HASH: LazyLock<String> =
193    LazyLock::new(|| hash_password(&random_hex()).expect("hashing works"));
194
195/// Runs Argon2 on the blocking thread pool (it is deliberately CPU heavy).
196pub async fn hash_password_async(password: String) -> AppResult<String> {
197    tokio::task::spawn_blocking(move || hash_password(&password))
198        .await
199        .map_err(|e| AppError::Other(anyhow::anyhow!("hashing task failed: {e}")))?
200}
201
202/// Verifies on the blocking pool. `hash = None` performs a dummy verification.
203pub async fn verify_password_async(password: String, hash: Option<String>) -> bool {
204    tokio::task::spawn_blocking(move || match hash {
205        Some(hash) => verify_password(&password, &hash),
206        None => {
207            let _ = verify_password(&password, &DUMMY_HASH);
208            false
209        }
210    })
211    .await
212    .unwrap_or(false)
213}
214
215// ---------------------------------------------------------------------------
216// Tokens
217// ---------------------------------------------------------------------------
218
219/// Generates a random token with 256 bits of entropy, e.g. `tc_pat_3f9a…`.
220pub fn generate_token(prefix: &str) -> String {
221    format!("{prefix}{}", random_hex())
222}
223
224/// 256 random bits from the OS, hex-encoded (64 characters).
225fn random_hex() -> String {
226    let mut bytes = [0u8; 32];
227    OsRng.fill_bytes(&mut bytes);
228    hex::encode(bytes)
229}
230
231/// The one-time code of the first-start setup (128 random bits, hex): the
232/// server logs the setup link with it, and only that link offers *Create the
233/// administrator* – a request through a reverse proxy on the same computer
234/// looks local otherwise (see `web::auth_pages::setup_open`).
235pub fn setup_code() -> String {
236    let mut bytes = [0u8; 16];
237    OsRng.fill_bytes(&mut bytes);
238    hex::encode(bytes)
239}
240
241/// Compares two secrets without stopping at the first difference.
242pub fn secrets_equal(given: &str, expected: &str) -> bool {
243    let (a, b) = (given.as_bytes(), expected.as_bytes());
244    let mut diff = a.len() ^ b.len();
245    for i in 0..a.len().max(b.len()) {
246        diff |= usize::from(a.get(i).copied().unwrap_or(0) ^ b.get(i).copied().unwrap_or(0));
247    }
248    diff == 0
249}
250
251/// Tokens are high-entropy, so a fast hash is sufficient for storage.
252pub fn hash_token(token: &str) -> String {
253    hex::encode(Sha256::digest(token.as_bytes()))
254}
255
256// ---------------------------------------------------------------------------
257// Cookies
258// ---------------------------------------------------------------------------
259
260/// Returns the value of the cookie `name` from the request headers.
261pub fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
262    headers
263        .get_all(header::COOKIE)
264        .iter()
265        .filter_map(|v| v.to_str().ok())
266        .flat_map(|v| v.split(';'))
267        .filter_map(|pair| pair.trim().split_once('='))
268        .find(|(k, _)| *k == name)
269        .map(|(_, v)| v.trim().to_string())
270}
271
272fn cookie_attributes(config: &Config, max_age_secs: u64) -> String {
273    let secure = if config.cookie_secure { "; Secure" } else { "" };
274    format!("Path=/; HttpOnly; SameSite=Lax; Max-Age={max_age_secs}{secure}")
275}
276
277pub fn session_cookie(config: &Config, token: &str) -> String {
278    format!(
279        "{SESSION_COOKIE}={token}; {}",
280        cookie_attributes(config, config.session_ttl.as_secs())
281    )
282}
283
284pub fn clear_session_cookie(config: &Config) -> String {
285    format!("{SESSION_COOKIE}=; {}", cookie_attributes(config, 0))
286}
287
288pub fn flash_cookie(config: &Config, encoded: &str) -> String {
289    format!(
290        "{FLASH_COOKIE}={encoded}; {}",
291        cookie_attributes(config, 60)
292    )
293}
294
295pub fn clear_flash_cookie(config: &Config) -> String {
296    format!("{FLASH_COOKIE}=; {}", cookie_attributes(config, 0))
297}
298
299// ---------------------------------------------------------------------------
300// Extractors
301// ---------------------------------------------------------------------------
302
303/// Extracts the user of a browser session. Rejects with `401`, which the web
304/// UI turns into a redirect to the login page.
305pub struct WebUser(pub Actor);
306
307impl FromRequestParts<AppState> for WebUser {
308    type Rejection = AppError;
309
310    async fn from_request_parts(
311        parts: &mut Parts,
312        state: &AppState,
313    ) -> Result<Self, Self::Rejection> {
314        if let Some(actor) = parts.extensions.get::<Actor>() {
315            return Ok(WebUser(actor.clone()));
316        }
317        let token = cookie_value(&parts.headers, SESSION_COOKIE)
318            .filter(|t| !t.is_empty())
319            .ok_or(AppError::Unauthorized)?;
320        let (actor, started) = services::users::session_actor(&state.db, &token)
321            .await?
322            .ok_or(AppError::Unauthorized)?;
323        // conditions on membership that depend on the request (#151)
324        let origin = Origin {
325            client: request_client(parts),
326            session_started: Some(started),
327            key: Some(hash_token(&token)[..16].to_string()),
328            token: false,
329        };
330        let actor = services::membership_conditions::apply(&state.db, actor, &origin).await?;
331        parts.extensions.insert(actor.clone());
332        parts.extensions.insert(origin);
333        Ok(WebUser(actor))
334    }
335}
336
337/// The client address of a request (see [`client_address`]).
338fn request_client(parts: &Parts) -> Option<IpAddr> {
339    let peer = parts
340        .extensions
341        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
342        .map(|c| c.0.ip());
343    client_address(&parts.headers, peer)
344}
345
346/// Where the signed-in request comes from (client address, session start, a
347/// key of the session or token), set by [`WebUser`] and [`ApiCaller`]; long
348/// work on behalf of the request (the assistant) applies the conditions on
349/// membership again with it. Empty when the request has no user.
350pub use services::membership_conditions::Origin;
351
352impl FromRequestParts<AppState> for Origin {
353    type Rejection = std::convert::Infallible;
354
355    async fn from_request_parts(
356        parts: &mut Parts,
357        _state: &AppState,
358    ) -> Result<Self, Self::Rejection> {
359        Ok(parts
360            .extensions
361            .get::<Origin>()
362            .cloned()
363            .unwrap_or_default())
364    }
365}
366
367/// Extracts the user of an API request from a bearer token.
368///
369/// Built on [`ApiCaller`], so the token's scope is enforced on every API
370/// route that takes an `ApiUser`.
371pub struct ApiUser(pub Actor);
372
373impl FromRequestParts<AppState> for ApiUser {
374    type Rejection = AppError;
375
376    async fn from_request_parts(
377        parts: &mut Parts,
378        state: &AppState,
379    ) -> Result<Self, Self::Rejection> {
380        let caller = ApiCaller::from_request_parts(parts, state).await?;
381        Ok(ApiUser(caller.actor))
382    }
383}
384
385/// The user of an API request and the scope of its token. Refuses (403) a
386/// request outside the scope: a `read_only` token may only send `GET`/`HEAD`
387/// requests and post to the MCP endpoint (whose dispatcher allows it the
388/// read-only tools only), an `mcp_only` token may only post to the MCP
389/// endpoint (`domain::TokenScope::allows_request`).
390#[derive(Clone, Debug)]
391pub struct ApiCaller {
392    pub actor: Actor,
393    pub scope: TokenScope,
394}
395
396impl FromRequestParts<AppState> for ApiCaller {
397    type Rejection = AppError;
398
399    async fn from_request_parts(
400        parts: &mut Parts,
401        state: &AppState,
402    ) -> Result<Self, Self::Rejection> {
403        let caller = if let Some(caller) = parts.extensions.get::<ApiCaller>() {
404            caller.clone()
405        } else if let Some(actor) = parts.extensions.get::<Actor>() {
406            // resolved from a browser session by `WebUser`: no token, no scope
407            ApiCaller {
408                actor: actor.clone(),
409                scope: TokenScope::Full,
410            }
411        } else {
412            let token = parts
413                .headers
414                .get(header::AUTHORIZATION)
415                .and_then(|v| v.to_str().ok())
416                .and_then(|v| {
417                    v.strip_prefix("Bearer ")
418                        .or_else(|| v.strip_prefix("bearer "))
419                })
420                .map(str::trim)
421                .filter(|t| !t.is_empty())
422                .ok_or(AppError::Unauthorized)?;
423            let (actor, scope) = services::users::actor_for_api_token(&state.db, token)
424                .await?
425                .ok_or(AppError::Unauthorized)?;
426            // conditions on membership that depend on the request (#151);
427            // a token's age is the user's last sign-in (checked in SQL)
428            let origin = Origin {
429                client: request_client(parts),
430                session_started: None,
431                key: Some(hash_token(token)[..16].to_string()),
432                token: true,
433            };
434            let actor = services::membership_conditions::apply(&state.db, actor, &origin).await?;
435            let caller = ApiCaller { actor, scope };
436            parts.extensions.insert(caller.actor.clone());
437            parts.extensions.insert(caller.clone());
438            parts.extensions.insert(origin);
439            caller
440        };
441        // the full path: routes nested under /api/v1 see only their own part
442        let path = parts
443            .extensions
444            .get::<OriginalUri>()
445            .map_or_else(|| parts.uri.path(), |uri| uri.0.path());
446        if !caller.scope.allows_request(parts.method.as_str(), path) {
447            return Err(AppError::Forbidden(caller.scope.refusal().into()));
448        }
449        Ok(caller)
450    }
451}
452
453/// Channel and client address of a request, for the read log of restricted
454/// groups (`services::access_log`). Never rejects: a bearer token means the
455/// API channel, otherwise the browser session.
456impl FromRequestParts<AppState> for services::access_log::AccessCtx {
457    type Rejection = std::convert::Infallible;
458
459    async fn from_request_parts(
460        parts: &mut Parts,
461        _state: &AppState,
462    ) -> Result<Self, Self::Rejection> {
463        let bearer = parts
464            .headers
465            .get(header::AUTHORIZATION)
466            .and_then(|v| v.to_str().ok())
467            .is_some_and(|v| v.len() > 7 && v[..7].eq_ignore_ascii_case("bearer "));
468        Ok(services::access_log::AccessCtx {
469            channel: if bearer {
470                services::access_log::Channel::Api
471            } else {
472                services::access_log::Channel::Web
473            },
474            client: request_client(parts),
475        })
476    }
477}
478
479// ---------------------------------------------------------------------------
480// Sign-in throttle
481// ---------------------------------------------------------------------------
482
483/// How long failed sign-ins are counted (from the first failure).
484pub const SIGN_IN_WINDOW: Duration = Duration::from_secs(15 * 60);
485/// A client address may fail this many times the per-username limit: an
486/// office behind one NAT address shares it.
487pub const SIGN_IN_ADDRESS_FACTOR: u32 = 5;
488/// Counters kept at most; beyond, new usernames are not counted (client
489/// addresses still are), so the map stays bounded under a spray.
490const SIGN_IN_MAX_ENTRIES: usize = 100_000;
491
492/// Failed password sign-ins per username and per client address
493/// (`TEAMCRAFT_SIGNIN_MAX_FAILURES` within [`SIGN_IN_WINDOW`]); once a
494/// counter is full, sign-in for that name or address is refused with 429
495/// until the window has passed – without checking the password. Counted in
496/// memory per server process; a successful sign-in clears the username's
497/// counter, not the address's (else an attacker with an account of their
498/// own could reset it between guesses).
499#[derive(Debug)]
500pub struct SignInThrottle {
501    max_failures: u32,
502    window: Duration,
503    counters: Mutex<HashMap<String, (Instant, u32)>>,
504}
505
506impl SignInThrottle {
507    /// `max_failures` 0 turns the throttle off.
508    pub fn new(max_failures: u32, window: Duration) -> SignInThrottle {
509        SignInThrottle {
510            max_failures,
511            window,
512            counters: Mutex::new(HashMap::new()),
513        }
514    }
515
516    /// The counters a sign-in attempt touches.
517    pub fn keys(username: &str, client: Option<IpAddr>) -> Vec<String> {
518        let mut keys = vec![format!("user:{}", username.trim().to_ascii_lowercase())];
519        if let Some(ip) = client {
520            keys.push(format!("ip:{ip}"));
521        }
522        keys
523    }
524
525    fn limit(&self, key: &str) -> u32 {
526        if key.starts_with("ip:") {
527            self.max_failures.saturating_mul(SIGN_IN_ADDRESS_FACTOR)
528        } else {
529            self.max_failures
530        }
531    }
532
533    fn counters(&self) -> std::sync::MutexGuard<'_, HashMap<String, (Instant, u32)>> {
534        self.counters.lock().unwrap_or_else(|e| e.into_inner())
535    }
536
537    /// `Some(wait)` when one of the counters is full.
538    pub fn blocked(&self, keys: &[String]) -> Option<Duration> {
539        if self.max_failures == 0 {
540            return None;
541        }
542        let now = Instant::now();
543        let counters = self.counters();
544        keys.iter()
545            .filter_map(|k| {
546                let (start, n) = counters.get(k)?;
547                let elapsed = now.saturating_duration_since(*start);
548                (elapsed < self.window && *n >= self.limit(k)).then(|| self.window - elapsed)
549            })
550            .max()
551    }
552
553    /// Counts a failed attempt.
554    pub fn failed(&self, keys: &[String]) {
555        if self.max_failures == 0 {
556            return;
557        }
558        let now = Instant::now();
559        let window = self.window;
560        let mut counters = self.counters();
561        if counters.len() >= SIGN_IN_MAX_ENTRIES {
562            counters.retain(|_, (start, _)| now.saturating_duration_since(*start) < window);
563        }
564        for key in keys {
565            let full = counters.len() >= SIGN_IN_MAX_ENTRIES;
566            if full && !key.starts_with("ip:") && !counters.contains_key(key) {
567                continue;
568            }
569            let entry = counters.entry(key.clone()).or_insert((now, 0));
570            if now.saturating_duration_since(entry.0) >= window {
571                *entry = (now, 0);
572            }
573            entry.1 = entry.1.saturating_add(1);
574        }
575    }
576
577    /// A successful sign-in clears the username's counter.
578    pub fn succeeded(&self, username: &str) {
579        self.counters()
580            .remove(&format!("user:{}", username.trim().to_ascii_lowercase()));
581    }
582}
583
584/// The client address of a request: the peer, or – when the peer is a
585/// reverse proxy on an internal address – the last `X-Forwarded-For` entry,
586/// the one that proxy added (a client can only prepend to the header). In
587/// tests without a peer address, the header alone.
588pub fn client_address(headers: &HeaderMap, peer: Option<IpAddr>) -> Option<IpAddr> {
589    let forwarded = || {
590        headers
591            .get("x-forwarded-for")?
592            .to_str()
593            .ok()?
594            .rsplit(',')
595            .next()?
596            .trim()
597            .parse::<IpAddr>()
598            .ok()
599    };
600    match peer {
601        Some(ip) if !crate::webhooks::is_internal(ip) => Some(ip),
602        Some(ip) => forwarded().or(Some(ip)),
603        None => forwarded(),
604    }
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610    use axum::http::HeaderValue;
611
612    #[test]
613    fn sign_in_throttle_counts_per_name_and_address() {
614        let t = SignInThrottle::new(3, Duration::from_secs(60));
615        let ip: IpAddr = "203.0.113.7".parse().unwrap();
616        let erika = SignInThrottle::keys(" Erika ", Some(ip));
617        assert_eq!(erika, ["user:erika", "ip:203.0.113.7"]);
618        for _ in 0..3 {
619            assert_eq!(t.blocked(&erika), None);
620            t.failed(&erika);
621        }
622        let wait = t.blocked(&erika).expect("the name is blocked");
623        assert!(wait <= Duration::from_secs(60) && wait > Duration::from_secs(50));
624        // another name from the same address: the address has room (3 × 5)
625        let max = SignInThrottle::keys("max", Some(ip));
626        assert_eq!(t.blocked(&max), None);
627        for _ in 0..11 {
628            t.failed(&max);
629        }
630        assert!(
631            t.blocked(&SignInThrottle::keys("anna", Some(ip))).is_none(),
632            "14 of 15"
633        );
634        t.failed(&SignInThrottle::keys("anna", Some(ip)));
635        assert!(
636            t.blocked(&SignInThrottle::keys("anna", Some(ip))).is_some(),
637            "the address is full"
638        );
639        assert!(t.blocked(&SignInThrottle::keys("anna", None)).is_none());
640        // success clears the name, not the address
641        t.succeeded("ERIKA");
642        assert!(t.blocked(&["user:erika".to_string()]).is_none());
643        assert!(t.blocked(&erika).is_some(), "the address stays counted");
644
645        // the window passes
646        let short = SignInThrottle::new(1, Duration::from_millis(30));
647        let k = SignInThrottle::keys("x", None);
648        short.failed(&k);
649        assert!(short.blocked(&k).is_some());
650        std::thread::sleep(Duration::from_millis(40));
651        assert!(short.blocked(&k).is_none());
652        short.failed(&k);
653        assert!(short.blocked(&k).is_some(), "a new window starts");
654
655        // 0 = off
656        let off = SignInThrottle::new(0, Duration::from_secs(60));
657        for _ in 0..100 {
658            off.failed(&k);
659        }
660        assert!(off.blocked(&k).is_none());
661    }
662
663    #[test]
664    fn client_addresses_behind_a_proxy() {
665        let mut h = HeaderMap::new();
666        h.insert(
667            "x-forwarded-for",
668            HeaderValue::from_static("198.51.100.1, 203.0.113.9"),
669        );
670        let proxy: IpAddr = "127.0.0.1".parse().unwrap();
671        let public: IpAddr = "192.0.2.44".parse().unwrap();
672        // the proxy's own entry, not what the client prepended
673        assert_eq!(client_address(&h, Some(proxy)), "203.0.113.9".parse().ok());
674        // a client talking to the server directly cannot choose its address
675        assert_eq!(client_address(&h, Some(public)), Some(public));
676        assert_eq!(client_address(&HeaderMap::new(), Some(proxy)), Some(proxy));
677        assert_eq!(client_address(&h, None), "203.0.113.9".parse().ok());
678        let mut bad = HeaderMap::new();
679        bad.insert("x-forwarded-for", HeaderValue::from_static("not-an-ip"));
680        assert_eq!(client_address(&bad, Some(proxy)), Some(proxy));
681    }
682
683    #[test]
684    fn password_hash_round_trip() {
685        // random passwords: no hard-coded credential, even in a test
686        let (password, other) = (random_hex(), random_hex());
687        let hash = hash_password(&password).unwrap();
688        assert!(hash.starts_with("$argon2id$"));
689        assert!(verify_password(&password, &hash));
690        assert!(!verify_password(&other, &hash));
691        assert!(!verify_password(&password, "not-a-hash"));
692    }
693
694    #[test]
695    fn tokens_are_random_and_hashed() {
696        let a = generate_token(API_TOKEN_PREFIX);
697        let b = generate_token(API_TOKEN_PREFIX);
698        assert_ne!(a, b);
699        assert!(a.starts_with("tc_pat_"));
700        assert_eq!(a.len(), "tc_pat_".len() + 64);
701        assert_eq!(hash_token(&a), hash_token(&a));
702        assert_ne!(hash_token(&a), hash_token(&b));
703        assert_eq!(hash_token(&a).len(), 64);
704    }
705
706    #[test]
707    fn cookie_parsing() {
708        let mut headers = HeaderMap::new();
709        headers.append(
710            header::COOKIE,
711            HeaderValue::from_static("a=1; tc_session=abc ; b=2"),
712        );
713        headers.append(header::COOKIE, HeaderValue::from_static("tc_flash=ff"));
714        assert_eq!(
715            cookie_value(&headers, SESSION_COOKIE).as_deref(),
716            Some("abc")
717        );
718        assert_eq!(cookie_value(&headers, FLASH_COOKIE).as_deref(), Some("ff"));
719        assert_eq!(cookie_value(&headers, "missing"), None);
720    }
721
722    #[test]
723    fn actor_role_checks() {
724        let rocket = Uuid::new_v4();
725        let rover = Uuid::new_v4();
726        let mut actor = Actor {
727            id: Uuid::new_v4(),
728            username: "eng".into(),
729            display_name: "Eng".into(),
730            role: Role::Editor,
731            skin: "teamcraft".into(),
732            preferred_cad: String::new(),
733            projects: vec![rocket],
734            hidden_projects: vec![],
735        };
736        assert!(actor.require(Role::Viewer).is_ok());
737        assert!(actor.require(Role::Editor).is_ok());
738        assert!(actor.require(Role::Admin).is_err());
739        assert!(actor.can_edit());
740        assert!(!actor.is_admin());
741        // project groups
742        assert!(actor.can_edit_project(Some(rocket)));
743        assert!(!actor.can_edit_project(Some(rover)));
744        assert!(
745            actor.can_edit_project(None),
746            "legacy items without a project"
747        );
748        actor.role = Role::Admin;
749        assert!(
750            actor.can_edit_project(Some(rover)),
751            "admins edit everything"
752        );
753        actor.role = Role::Viewer;
754        assert!(!actor.can_edit_project(Some(rocket)), "viewers never edit");
755    }
756
757    #[test]
758    fn actor_read_visibility() {
759        let open = Uuid::new_v4();
760        let secret = Uuid::new_v4();
761        let actor = Actor::test(Role::Editor, vec![open], vec![secret]);
762        assert!(actor.can_see_project(None), "items without a group");
763        assert!(actor.can_see_project(Some(open)));
764        assert!(!actor.can_see_project(Some(secret)));
765        let admin = Actor::test(Role::Admin, vec![], vec![]);
766        assert!(admin.can_see_project(Some(secret)));
767        // webhooks: own group plus internal groups
768        let hook = Actor::for_webhook(Some(secret), &[secret, open]);
769        assert!(hook.can_see_project(Some(secret)));
770        assert!(!hook.can_see_project(Some(open)));
771        let global = Actor::for_webhook(None, &[secret]);
772        assert!(!global.can_see_project(Some(secret)));
773    }
774
775    #[test]
776    fn actor_serialization_skips_hidden_projects() {
777        let secret = Uuid::new_v4();
778        let actor = Actor::test(Role::Viewer, vec![], vec![secret]);
779        let json = serde_json::to_string(&actor).unwrap();
780        assert!(!json.contains("hidden_projects"));
781        assert!(!json.contains(&secret.to_string()));
782    }
783}