Something went wrong. Try again.
A self-hosted custom sync server for kobo devices.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258use 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<AppDb>, ldap: Option<Arc<LdapProvider>>, /// 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<AppDb>, ldap: Option<Arc<LdapProvider>>, 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<Option<User>, 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<Option<User>, 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<error_stack::Report<crate::errors::Error>> for BackendError { fn from(report: error_stack::Report<crate::errors::Error>) -> 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<Option<Self::User>, 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<Self>) -> Result<Option<Self::User>, 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<Backend>;
/// 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 <token>` 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, (StatusCode, &'static str)> { self.is_admin .then_some(self) .ok_or((StatusCode::FORBIDDEN, "Admin access required")) }}
impl FromRequestParts<AppState> for ApiUser { type Rejection = (StatusCode, &'static str);
async fn from_request_parts( parts: &mut Parts, state: &AppState, ) -> Result<Self, Self::Rejection> { // 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, }) }}