Skip to main content

koan_server/auth/
mod.rs

1//! Authentication layer for the koan server.
2//!
3//! When `auth_enabled = true`:
4//!   - GraphQL requests must carry a valid JWT (see `middleware` for where it is
5//!     read from); the web UI takes it only as the `koan_access` cookie
6//!   - Auth routes (/auth/login, /auth/refresh, /auth/logout) are always accessible
7//!
8//! When `auth_enabled = false` (opt-in, not the default):
9//!   - All requests are treated as admin — no auth required.
10
11pub mod middleware;
12pub mod password;
13pub mod routes;
14
15use std::sync::{Arc, OnceLock};
16
17use koan_core::auth::{Claims, Role};
18use koan_core::db::pool::Pool;
19use koan_core::db::queries::auth as auth_queries;
20
21/// The server's signing keypair as PEM, private then public.
22pub(crate) type Keypair = (Arc<Vec<u8>>, Arc<Vec<u8>>);
23
24static SIGNING: OnceLock<Keypair> = OnceLock::new();
25
26/// Set once at startup to the keys sessions are signed with, so invite tokens
27/// are signed and checked with the same pair on every path, whatever happens
28/// to the files on disk while the server runs.
29pub(crate) fn set_signing_keys(private: Arc<Vec<u8>>, public: Arc<Vec<u8>>) {
30    let _ = SIGNING.set((private, public));
31}
32
33/// The keys `set_signing_keys` was given; read from disk, once, where nothing
34/// set them, as in tests.
35pub(crate) fn signing_keys() -> Result<&'static Keypair, koan_core::auth::AuthError> {
36    if let Some(keys) = SIGNING.get() {
37        return Ok(keys);
38    }
39    let (private, public) = koan_core::auth::load_or_generate_keypair()?;
40    Ok(SIGNING.get_or_init(|| (Arc::new(private), Arc::new(public))))
41}
42
43/// Authenticated user context injected into request extensions and GraphQL context.
44#[derive(Debug, Clone)]
45pub struct AuthUser {
46    pub user_id: i64,
47    pub username: String,
48    pub role: Role,
49}
50
51/// The account a token names, as it stands now.
52///
53/// A token's claims hold for its whole lifetime, so taken at their word a role
54/// change or a deletion would not reach GraphQL or the web UI until it
55/// expired: time enough for a demoted admin to restore the role. `None` once
56/// the account is gone, or when its id now belongs to another account.
57pub(crate) async fn current_user(pool: &Arc<Pool>, claims: Claims) -> Option<AuthUser> {
58    let pool = pool.clone();
59    tokio::task::spawn_blocking(move || {
60        let db = pool.get().ok()?;
61        let user = auth_queries::get_user_by_id(&db.conn, claims.sub).ok()??;
62        (user.username == claims.username).then_some(AuthUser {
63            user_id: user.id,
64            username: user.username,
65            role: user.role,
66        })
67    })
68    .await
69    .ok()
70    .flatten()
71}
72
73/// What a socket opened with a credential is held under: its account as of
74/// `mark` (see `koan_core::auth::account_mark`), and for a token, when it
75/// lapses.
76#[derive(Debug, Clone, Copy)]
77pub(crate) struct Lease {
78    pub user_id: i64,
79    pub mark: u64,
80    /// Unix seconds.
81    pub expires: Option<u64>,
82}
83
84impl Lease {
85    /// Resolves when a socket held under this lease must close: its account
86    /// changed, or its token lapsed. The client reconnects and authenticates
87    /// again, so it holds no more than its credential now gives it.
88    pub(crate) async fn ended(self) {
89        let lapsed = async {
90            match self.expires {
91                Some(at) => {
92                    let left = at.saturating_sub(koan_core::auth::now_unix());
93                    tokio::time::sleep(std::time::Duration::from_secs(left)).await;
94                }
95                None => std::future::pending().await,
96            }
97        };
98        tokio::select! {
99            _ = koan_core::auth::account_changed_since(self.user_id, self.mark) => {}
100            _ = lapsed => {}
101        }
102    }
103}
104
105impl AuthUser {
106    /// Anonymous admin user for when auth is disabled.
107    pub fn anonymous_admin() -> Self {
108        Self {
109            user_id: 0,
110            username: koan_core::auth::ANONYMOUS.into(),
111            role: Role::Admin,
112        }
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    use std::time::Duration;
120
121    #[tokio::test]
122    async fn a_lease_ends_when_its_account_changes_and_no_other() {
123        let lease = Lease {
124            user_id: 9001,
125            mark: koan_core::auth::account_mark(),
126            expires: None,
127        };
128        koan_core::auth::account_changed(9002);
129        assert!(
130            tokio::time::timeout(Duration::from_millis(50), lease.ended())
131                .await
132                .is_err()
133        );
134        koan_core::auth::account_changed(9001);
135        tokio::time::timeout(Duration::from_secs(1), lease.ended())
136            .await
137            .unwrap();
138    }
139
140    #[tokio::test]
141    async fn a_lease_ends_when_its_token_lapses() {
142        let lease = Lease {
143            user_id: 9003,
144            mark: koan_core::auth::account_mark(),
145            expires: Some(koan_core::auth::now_unix()),
146        };
147        tokio::time::timeout(Duration::from_secs(1), lease.ended())
148            .await
149            .unwrap();
150    }
151}