mwoauth 0.1.0-rc.1

MediaWiki OAuth 2.0 client with optional Rocket, Axum, and Actix Web adapters
Documentation
// SPDX-License-Identifier: GPL-3.0-or-later

use serde::{Deserialize, Serialize};

/// OAuth token response returned by MediaWiki.
#[derive(Clone, Deserialize, Serialize)]
pub struct OAuthToken {
    access_token: String,
    #[serde(default)]
    refresh_token: Option<String>,
    #[serde(default)]
    expires_in: Option<i64>,
    #[serde(default)]
    token_type: Option<String>,
    #[serde(default)]
    scope: Option<String>,
}

impl std::fmt::Debug for OAuthToken {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("OAuthToken")
            .field("access_token", &"[REDACTED]")
            .field(
                "refresh_token",
                &self.refresh_token.as_ref().map(|_| "[REDACTED]"),
            )
            .field("expires_in", &self.expires_in)
            .field("token_type", &self.token_type)
            .field("scope", &self.scope)
            .finish()
    }
}

impl OAuthToken {
    pub(crate) fn retain_refresh_token(&mut self, previous: &str) {
        if self.refresh_token.is_none() {
            self.refresh_token = Some(previous.to_owned());
        }
    }

    /// Bearer token used to make authenticated MediaWiki requests.
    pub fn access_token(&self) -> &str {
        &self.access_token
    }

    /// Token used to renew an expired access token, when supplied by MediaWiki.
    pub fn refresh_token(&self) -> Option<&str> {
        self.refresh_token.as_deref()
    }

    /// Access-token lifetime in seconds, when supplied by MediaWiki.
    pub fn expires_in(&self) -> Option<i64> {
        self.expires_in
    }

    /// Token type supplied by MediaWiki.
    pub fn token_type(&self) -> Option<&str> {
        self.token_type.as_deref()
    }

    /// Granted scopes supplied by MediaWiki.
    pub fn scope(&self) -> Option<&str> {
        self.scope.as_deref()
    }
}

/// Information returned by MediaWiki's OAuth profile endpoint.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct UserProfile {
    #[serde(rename = "sub")]
    central_id: String,
    username: String,
    blocked: bool,
    confirmed_email: bool,
    editcount: u64,
    email_verified: bool,
    #[serde(default)]
    grants: Vec<String>,
    #[serde(default)]
    groups: Vec<String>,
    registered: String,
    #[serde(default)]
    rights: Vec<String>,
    #[serde(default)]
    realname: Option<String>,
    #[serde(default)]
    email: Option<String>,
}

impl UserProfile {
    pub fn central_id(&self) -> &str {
        &self.central_id
    }

    pub fn username(&self) -> &str {
        &self.username
    }

    pub fn blocked(&self) -> bool {
        self.blocked
    }

    pub fn confirmed_email(&self) -> bool {
        self.confirmed_email
    }

    pub fn editcount(&self) -> u64 {
        self.editcount
    }

    pub fn email_verified(&self) -> bool {
        self.email_verified
    }

    pub fn grants(&self) -> &[String] {
        &self.grants
    }

    pub fn groups(&self) -> &[String] {
        &self.groups
    }

    pub fn registered(&self) -> &str {
        &self.registered
    }

    pub fn rights(&self) -> &[String] {
        &self.rights
    }

    pub fn realname(&self) -> Option<&str> {
        self.realname.as_deref()
    }

    pub fn email(&self) -> Option<&str> {
        self.email.as_deref()
    }
}

/// Authenticated user information stored by framework adapters.
#[derive(Clone, Deserialize, Serialize)]
pub struct AuthenticatedUser {
    profile: UserProfile,
    token: OAuthToken,
    token_expires_at: Option<u64>,
    session_expires_at: u64,
}

impl AuthenticatedUser {
    pub(crate) fn new(profile: UserProfile, token: OAuthToken, now: u64) -> Self {
        let token_expires_at = token
            .expires_in()
            .and_then(|seconds| u64::try_from(seconds).ok())
            .and_then(|seconds| now.checked_add(seconds));
        Self {
            profile,
            token,
            token_expires_at,
            session_expires_at: now.saturating_add(crate::DEFAULT_SESSION_TTL.as_secs()),
        }
    }

    pub fn profile(&self) -> &UserProfile {
        &self.profile
    }

    pub fn token(&self) -> &OAuthToken {
        &self.token
    }

    pub fn token_expires_at(&self) -> Option<u64> {
        self.token_expires_at
    }

    pub(crate) fn refreshed(
        profile: UserProfile,
        token: OAuthToken,
        current: &Self,
        now: u64,
    ) -> Self {
        let mut refreshed = Self::new(profile, token, now);
        refreshed.session_expires_at = current.session_expires_at;
        refreshed
    }

    /// Absolute Unix timestamp after which this login session is invalid.
    pub fn session_expires_at(&self) -> u64 {
        self.session_expires_at
    }
}

impl std::fmt::Debug for AuthenticatedUser {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("AuthenticatedUser")
            .field("profile", &"[REDACTED]")
            .field("token", &self.token)
            .field("token_expires_at", &self.token_expires_at)
            .field("session_expires_at", &self.session_expires_at)
            .finish()
    }
}

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

    #[test]
    fn refresh_response_keeps_previous_token_only_when_no_replacement_is_returned() {
        let mut without_replacement: OAuthToken =
            serde_json::from_str(r#"{"access_token":"new-access"}"#).unwrap();
        without_replacement.retain_refresh_token("old-refresh");
        assert_eq!(without_replacement.refresh_token(), Some("old-refresh"));

        let mut with_replacement: OAuthToken =
            serde_json::from_str(r#"{"access_token":"new-access","refresh_token":"new-refresh"}"#)
                .unwrap();
        with_replacement.retain_refresh_token("old-refresh");
        assert_eq!(with_replacement.refresh_token(), Some("new-refresh"));
    }
}