6.1 KiB · text History 3d71adc
//! Device tokens: what the Android app (and any script) authenticates with.
//!
//! Only the SHA-256 of a token is stored — the same hashing as the email
//! verification tokens — so the token itself exists once, on the pairing
//! page, and then only on the device. A device token's expiry slides: it
//! stays valid for [`SLIDING_DAYS`] after it was last used, refreshed at most
//! once a [`REFRESH_AFTER_HOURS`] so a busy phone isn't a write per request.
use anyhow::{Context, Result};
use chrono::{Duration, Utc};
use sea_orm::*;
use uuid::Uuid;

use super::verification::{generate_token, hash_token};
use crate::entities::{api_tokens, users};

/// Prefix on every token, so one is recognisable in a log or a paste.
pub const TOKEN_PREFIX: &str = "recourse_";
/// A device token is good for this long after its last use.
pub const SLIDING_DAYS: i64 = 90;
/// `last_used_at` / `expires_at` are refreshed at most this often.
pub const REFRESH_AFTER_HOURS: i64 = 24;
/// Longest label kept (the column is unbounded; the page isn't).
const MAX_LABEL: usize = 80;

/// A new token: the prefix and 32 random bytes, hex.
pub fn generate_api_token() -> String {
    format!("{TOKEN_PREFIX}{}", generate_token())
}

/// What is stored for a token.
pub fn hash_api_token(token: &str) -> String {
    hash_token(token)
}

fn clean_label(label: Option<String>) -> Option<String> {
    label
        .map(|s| s.trim().chars().take(MAX_LABEL).collect::<String>())
        .filter(|s| !s.is_empty())
}

/// Mint a token for `user_id`. Returns the stored row and the token itself,
/// which the caller shows once. `expires_in_days: None` is the device default,
/// a [`SLIDING_DAYS`] sliding expiry.
pub async fn create_api_token(
    db: &DatabaseConnection,
    user_id: Uuid,
    label: Option<String>,
    expires_in_days: Option<i64>,
) -> Result<(api_tokens::Model, String)> {
    let token = generate_api_token();
    let now = Utc::now();
    let days = expires_in_days.filter(|d| *d > 0).unwrap_or(SLIDING_DAYS);
    let row = api_tokens::ActiveModel {
        id: Set(Uuid::now_v7()),
        user_id: Set(user_id),
        token_hash: Set(hash_api_token(&token)),
        label: Set(clean_label(label)),
        last_used_at: Set(None),
        expires_at: Set(Some((now + Duration::days(days)).into())),
        created_at: Set(now.into()),
    }
    .insert(db)
    .await
    .context("insert api_token")?;
    Ok((row, token))
}

/// The active user owning `token`, and the token's row. `Ok(None)` for an
/// unknown or expired token, or a deactivated account. A valid token's
/// `last_used_at` is bumped (and its expiry slid forward) when stale.
pub async fn validate_api_token(
    db: &DatabaseConnection,
    token: &str,
) -> Result<Option<(users::Model, api_tokens::Model)>> {
    let row = api_tokens::Entity::find()
        .filter(api_tokens::Column::TokenHash.eq(hash_api_token(token)))
        .one(db)
        .await
        .context("query api_token")?;
    let Some(row) = row else {
        return Ok(None);
    };
    let now = Utc::now();
    if row.expires_at.is_some_and(|exp| exp < now) {
        return Ok(None);
    }
    let user = users::Entity::find_by_id(row.user_id)
        .filter(users::Column::IsActive.eq(true))
        .one(db)
        .await
        .context("query user for api_token")?;
    let Some(user) = user.filter(|u| crate::policy::suspension(u).is_none()) else {
        return Ok(None);
    };

    let stale = row
        .last_used_at
        .is_none_or(|t| now - t.with_timezone(&Utc) >= Duration::hours(REFRESH_AFTER_HOURS));
    let row = if stale {
        let mut update: api_tokens::ActiveModel = row.clone().into();
        update.last_used_at = Set(Some(now.into()));
        // A token with an expiry slides; one minted before expiries existed
        // (none) keeps none.
        if row.expires_at.is_some() {
            update.expires_at = Set(Some((now + Duration::days(SLIDING_DAYS)).into()));
        }
        // Best effort: a failed bump must not fail the request.
        update.update(db).await.unwrap_or(row)
    } else {
        row
    };
    Ok(Some((user, row)))
}

/// Revoke one of `user_id`'s tokens. Returns how many rows went (0 or 1).
pub async fn delete_api_token(db: &DatabaseConnection, user_id: Uuid, token_id: Uuid) -> Result<u64> {
    let result = api_tokens::Entity::delete_many()
        .filter(api_tokens::Column::Id.eq(token_id))
        .filter(api_tokens::Column::UserId.eq(user_id))
        .exec(db)
        .await
        .context("delete api_token")?;
    Ok(result.rows_affected)
}

/// Rename one of `user_id`'s tokens. `Ok(false)` if it isn't theirs.
pub async fn rename_api_token(
    db: &DatabaseConnection,
    user_id: Uuid,
    token_id: Uuid,
    label: Option<String>,
) -> Result<bool> {
    let result = api_tokens::Entity::update_many()
        .col_expr(api_tokens::Column::Label, sea_orm::sea_query::Expr::value(clean_label(label)))
        .filter(api_tokens::Column::Id.eq(token_id))
        .filter(api_tokens::Column::UserId.eq(user_id))
        .exec(db)
        .await
        .context("rename api_token")?;
    Ok(result.rows_affected > 0)
}

/// Every token `user_id` holds, newest first.
pub async fn list_api_tokens(db: &DatabaseConnection, user_id: Uuid) -> Result<Vec<api_tokens::Model>> {
    api_tokens::Entity::find()
        .filter(api_tokens::Column::UserId.eq(user_id))
        .order_by_desc(api_tokens::Column::CreatedAt)
        .all(db)
        .await
        .context("list api_tokens")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tokens_are_prefixed_and_only_their_hash_is_kept() {
        let t = generate_api_token();
        assert!(t.starts_with(TOKEN_PREFIX));
        assert_eq!(t.len(), TOKEN_PREFIX.len() + 64);
        let h = hash_api_token(&t);
        assert_eq!(h.len(), 64);
        assert!(!h.contains(&t[TOKEN_PREFIX.len()..]));
        assert_ne!(generate_api_token(), t);
    }

    #[test]
    fn labels_are_trimmed_and_bounded() {
        assert_eq!(clean_label(Some("  Pixel 8 ".into())).as_deref(), Some("Pixel 8"));
        assert_eq!(clean_label(Some("   ".into())), None);
        assert_eq!(clean_label(Some("x".repeat(500))).map(|s| s.len()), Some(MAX_LABEL));
    }
}