7.3 KiB · text History 263b40b
//! Android sign-in without the QR: the app's half of neiam-auth's
//! `app-login`.
//!
//! * `GET /api/v1/auth/methods`: which buttons the app enables.
//! * `POST /api/v1/auth/password`: the web login's password check (the
//!   username, or the email here too), its refusals (`OIDC_PASSWORD_LOGIN`,
//!   `OIDC_LOGIN_MODE=sso`/`sso_strict`, deactivated and suspended
//!   accounts), then a device token exactly as the Devices page mints one.
//! * `/auth/oidc/<provider>/login?app=1&…` + `POST /api/v1/auth/oidc/exchange`:
//!   "Sign in with NEIAM" in a Custom Tab; the callback runs the same link
//!   policy as the web ([`super::oidc::AppLinker`]) and starts no session;
//!   the app redeems the one-time code (PKCE) for a device token.
//!
//! Tokens minted here are ordinary `api_tokens` rows (only the hash stored,
//! the 90-day sliding expiry): they show on /devices and are revoked there.
//! recourse has no second factor, so `SecondFactorRequired` never comes up.
use std::sync::LazyLock;

use axum::http::request::Parts;
use neiam_auth::app_login::{
    ApiError, AppLogin, AppLoginApp, AppLoginConfig, BoxError, Grant, Method, PasswordCheck,
};
use neiam_auth::sea_orm::app_login::SeaOrmCodeStore;
use sea_orm::sea_query::{Expr, Func};
use sea_orm::*;
use serde_json::json;
use tracing::error;

use crate::AppState;
use crate::auth::oidc::short_label;
use crate::auth::{api_tokens, password};
use crate::entities::users;

/// The scheme the Android app registers (as for `recourse://pair`). The
/// OIDC callback sends the one-time code to `recourse://auth?code=…`.
pub const REDIRECT_URI: &str = "recourse://auth";

/// A real argon2 hash of nothing in particular: an unknown account is
/// verified against it, so it costs what a known one does.
static DUMMY_HASH: LazyLock<String> =
    LazyLock::new(|| password::hash_password("recourse-dummy-password").expect("argon2 hashes"));

#[derive(Clone)]
pub struct RecourseAppLogin {
    pub state: AppState,
}

pub type Service = AppLogin<RecourseAppLogin, SeaOrmCodeStore>;

/// The service: the app's `APP_NAME` and `PUBLIC_URL`,
/// `APP_LOGIN_REDIRECT_URI` and `APP_LOGIN_OIDC_PROVIDER` from the
/// environment, per-IP limits on the `TRUSTED_PROXIES`-resolved address.
pub fn service(state: AppState) -> Service {
    let mut cfg = AppLoginConfig::from_env(state.config.app_name.clone(), REDIRECT_URI);
    // The app's own PUBLIC_URL (and its default) wins.
    cfg.public_url = Some(state.config.public_url.trim_end_matches('/').to_string());
    cfg.client_ip = super::password_reset::resolved_client_ip;
    service_with(state, cfg)
}

pub fn service_with(state: AppState, cfg: AppLoginConfig) -> Service {
    let store = SeaOrmCodeStore::new(state.db.clone());
    let providers = state.config.oidc.clone();
    AppLogin::new(RecourseAppLogin { state }, store, providers, cfg)
}

/// The user for a username or a (case-insensitive) email.
async fn find_user(db: &DatabaseConnection, login: &str) -> Result<Option<users::Model>, DbErr> {
    if let Some(u) = users::Entity::find()
        .filter(users::Column::Username.eq(login))
        .one(db)
        .await?
    {
        return Ok(Some(u));
    }
    if !login.contains('@') {
        return Ok(None);
    }
    let mut matches = users::Entity::find()
        .filter(Expr::expr(Func::lower(Expr::col(users::Column::Email))).eq(login.to_lowercase()))
        .limit(2)
        .all(db)
        .await?;
    // Two case-variants of one address would be ambiguous, and an
    // ambiguous login is no login.
    Ok(if matches.len() == 1 {
        matches.pop()
    } else {
        None
    })
}

/// "This account signs in with NEIAM." (the provider's short label).
fn sso_message(state: &AppState) -> String {
    let who = state
        .config
        .oidc
        .enabled()
        .into_iter()
        .next()
        .map(|p| short_label(&p.label))
        .unwrap_or_else(|| "single sign-on".into());
    format!("This account signs in with {who}.")
}

impl AppLoginApp for RecourseAppLogin {
    fn password_login_enabled(&self) -> bool {
        crate::handlers::auth::local_login(&self.state)
    }

    async fn check_password(&self, login: &str, pw: &str) -> Result<PasswordCheck, BoxError> {
        let db = self.state.db.as_ref();
        let user = find_user(db, login).await?;
        let usable =
            |u: &users::Model| u.is_active && !password::is_unusable_hash(&u.password_hash);
        // As the web form: deactivated accounts (its lookup skips them) and
        // accounts with no password (created through NEIAM) read as a wrong
        // password. Every path verifies one argon2 hash.
        let hash = match &user {
            Some(u) if usable(u) => u.password_hash.as_str(),
            _ => DUMMY_HASH.as_str(),
        };
        let ok = password::verify_password(pw, hash)?;
        let Some(user) = user.filter(|u| ok && usable(u)) else {
            return Ok(PasswordCheck::Invalid);
        };
        // Then the web form's refusals, in its order: suspended ("This
        // account is suspended until …"), then OIDC_LOGIN_MODE=sso for an
        // account linked to a REQUIRED_FOR_LINKED provider.
        if let Some(s) = crate::policy::suspension(&user) {
            return Ok(PasswordCheck::Refused(crate::policy::suspension_message(
                &s,
            )));
        }
        if !neiam_auth::sea_orm::password_login_allowed(db, &self.state.config.oidc, user.id)
            .await?
        {
            return Ok(PasswordCheck::Refused(sso_message(&self.state)));
        }
        let mut update: users::ActiveModel = user.clone().into();
        update.last_login_at = Set(Some(chrono::Utc::now().into()));
        let _ = update.update(db).await;
        Ok(PasswordCheck::Valid(user.id))
    }

    async fn issue_token(
        &self,
        grant: Grant,
        parts: &Parts,
    ) -> Result<serde_json::Value, ApiError> {
        let db = self.state.db.as_ref();
        let user = users::Entity::find_by_id(grant.user_id)
            .one(db)
            .await
            .map_err(|e| {
                error!(error = %e, "app login: user lookup failed");
                ApiError::internal()
            })?
            .filter(|u| u.is_active)
            .ok_or_else(|| ApiError::forbidden("This account has been deactivated."))?;
        if let Some(s) = crate::policy::suspension(&user) {
            return Err(ApiError::forbidden(crate::policy::suspension_message(&s)));
        }
        // The same issuance as the Devices page's pairing: labelled, the
        // default sliding expiry.
        let (row, token) =
            api_tokens::create_api_token(db, user.id, Some(grant.device_name.clone()), None)
                .await
                .map_err(|e| {
                    error!(error = %e, "app login: minting the device token failed");
                    ApiError::internal()
                })?;
        // The OIDC half recorded the address at the callback.
        if grant.method == Method::Password {
            let ip = super::password_reset::resolved_client_ip(parts);
            crate::ips::record(db, user.id, ip, crate::ips::Seen::SignIn).await;
        }
        Ok(json!({
            "token": token,
            "token_id": row.id,
            "label": row.label,
            "expires_at": row.expires_at,
            "user": { "id": user.id, "username": user.username, "email": user.email },
        }))
    }
}