use std::sync::Arc; use axum::extract::FromRequestParts; use axum::http::header::AUTHORIZATION; use axum::http::request::Parts; use axum::http::StatusCode; use axum_login::{AuthUser, AuthnBackend, UserId}; use password_auth::verify_password; use serde::Deserialize; use tokio::task; use tracing::error; use crate::db::app_db::{AppDb, UserRecord}; use crate::kobo::auth::AppState; use crate::ldap::LdapProvider; /// A web UI user with session-based authentication. #[derive(Debug, Clone)] pub struct User { id: i64, pub username: String, password_hash: String, /// Server administrator: sees every book, edits global settings, manages /// users. pub is_admin: bool, } impl User { fn from_record(r: UserRecord) -> Self { Self { id: r.id, username: r.username, password_hash: r.password_hash, is_admin: r.is_admin, } } } impl AuthUser for User { type Id = i64; fn id(&self) -> Self::Id { self.id } fn session_auth_hash(&self) -> &[u8] { self.password_hash.as_bytes() } } /// Credentials submitted via the login form. #[derive(Debug, Clone, Deserialize)] pub struct Credentials { pub username: String, pub password: String, } /// Authentication backend for the username/password form: local (database) /// accounts, then the LDAP directory when one is configured. #[derive(Clone)] pub struct Backend { db: Arc, ldap: Option>, /// Whether local password accounts may log in at all. local_login: bool, } impl std::fmt::Debug for Backend { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Backend") .field("ldap", &self.ldap.as_ref().map(|l| l.url().to_string())) .field("local_login", &self.local_login) .finish_non_exhaustive() } } impl Backend { /// Create a new auth backend over the application database, with an /// optional LDAP directory as the second password check. pub fn new(db: Arc, ldap: Option>, local_login: bool) -> Self { Self { db, ldap, local_login, } } /// Verify a local account's password (argon2 is blocking, so it runs on a /// blocking task). `None` when there is no matching local account. async fn authenticate_local(&self, creds: &Credentials) -> Result, BackendError> { if !self.local_login { return Ok(None); } let user = self .db .find_user_by_username(&creds.username) .await? .map(User::from_record); let password = creds.password.clone(); task::spawn_blocking(move || { Ok(user.filter(|u| verify_password(password, &u.password_hash).is_ok())) }) .await? } /// Verify against the directory and provision/link the account. `None` when /// LDAP is off or rejects the credentials. async fn authenticate_ldap(&self, creds: &Credentials) -> Result, BackendError> { let Some(ldap) = &self.ldap else { return Ok(None); }; let Some(identity) = ldap .authenticate(&creds.username, &creds.password) .await .map_err(|e| { error!("LDAP authentication failed: {e:?}"); BackendError::Ldap(format!("{e}")) })? else { return Ok(None); }; let user_id = ldap.provision(&self.db, &identity).await?; Ok(self .db .find_user_by_id(user_id) .await? .map(User::from_record)) } } #[derive(Debug, thiserror::Error)] pub enum BackendError { #[error("Database error: {0}")] Database(String), #[error("LDAP error: {0}")] Ldap(String), #[error(transparent)] TaskJoin(#[from] task::JoinError), } impl From> for BackendError { fn from(report: error_stack::Report) -> Self { BackendError::Database(format!("{report:?}")) } } impl AuthnBackend for Backend { type User = User; type Credentials = Credentials; type Error = BackendError; async fn authenticate( &self, creds: Self::Credentials, ) -> Result, Self::Error> { // A local account with a valid password wins; anything else (unknown // username, LDAP-provisioned account with its sentinel hash, or a // wrong local password) falls through to the directory. if let Some(user) = self.authenticate_local(&creds).await? { return Ok(Some(user)); } self.authenticate_ldap(&creds).await } async fn get_user(&self, user_id: &UserId) -> Result, Self::Error> { Ok(self .db .find_user_by_id(*user_id) .await? .map(User::from_record)) } } /// Type alias for the auth session used in handlers. pub type AuthSession = axum_login::AuthSession; /// The authenticated principal for web `/api` endpoints that accept either an /// interactive browser session or a programmatic API client (e.g. the Calibre /// upload plugin). /// /// Resolution order: /// 1. An established `axum-login` session cookie (the browser UI). /// 2. An `Authorization: Bearer ` header matched against `auth_tokens` /// — the same per-user tokens minted for Kobo devices (`POST /api/tokens`). /// Unlike the Kobo `/kobo/*` path, the token here is the raw value, not /// JWT-wrapped. /// /// Yields the acting user's id and role. Endpoints using this extractor must sit /// outside the `login_required!` layer, which would redirect a token-only client /// to the HTML login page before this extractor ever runs. #[derive(Debug, Clone, Copy)] pub struct ApiUser { pub id: i64, pub is_admin: bool, } impl ApiUser { /// `403` unless the user is an admin. For endpoints that change global /// server state (settings, ingest, bulk conversions). pub fn require_admin(self) -> Result { self.is_admin .then_some(self) .ok_or((StatusCode::FORBIDDEN, "Admin access required")) } } impl FromRequestParts for ApiUser { type Rejection = (StatusCode, &'static str); async fn from_request_parts( parts: &mut Parts, state: &AppState, ) -> Result { // 1. Browser session cookie. if let Ok(session) = AuthSession::from_request_parts(parts, state).await { if let Some(user) = session.user { return Ok(ApiUser { id: user.id(), is_admin: user.is_admin, }); } } // 2. Bearer token (raw, looked up directly in `auth_tokens`). let token = parts .headers .get(AUTHORIZATION) .and_then(|v| v.to_str().ok()) .and_then(|v| { v.strip_prefix("Bearer ") .or_else(|| v.strip_prefix("bearer ")) }) .map(str::trim) .filter(|t| !t.is_empty()) .ok_or((StatusCode::UNAUTHORIZED, "Not logged in"))?; let record = state .app_db .find_user_by_token(token) .await .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Auth lookup failed"))? .ok_or((StatusCode::UNAUTHORIZED, "Invalid API token"))?; let user = state .app_db .find_user_by_id(record.user_id) .await .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Auth lookup failed"))? .ok_or((StatusCode::UNAUTHORIZED, "Invalid API token"))?; Ok(ApiUser { id: user.id, is_admin: user.is_admin, }) } }