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 std::time::Duration;

/// Stable categories for mapping OAuth failures into framework responses.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
    Configuration,
    Callback,
    Network,
    Provider,
    Session,
    Unauthenticated,
}

/// Errors produced by the framework-independent MediaWiki OAuth flow.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Configuration is missing or invalid.
    #[error("invalid OAuth configuration: {0}")]
    Configuration(String),
    /// An OAuth endpoint URL could not be constructed.
    #[error("failed to construct an OAuth endpoint URL")]
    UrlConstruction,
    /// Secure random generation failed.
    #[error("secure random generation failed")]
    Randomness,
    /// No pending login flow was found.
    #[error("missing or already consumed OAuth flow state")]
    MissingFlowState,
    /// The pending login flow has expired.
    #[error("OAuth flow state expired after {0:?}")]
    ExpiredFlowState(Duration),
    /// Stored or supplied OAuth state was malformed.
    #[error("OAuth flow state was malformed")]
    InvalidFlowState,
    /// Callback state did not match the pending login flow.
    #[error("OAuth callback state did not match")]
    StateMismatch,
    /// PKCE flow data was malformed.
    #[error("invalid PKCE flow data")]
    InvalidPkce,
    /// An outbound HTTP request timed out.
    #[error("OAuth HTTP request timed out")]
    Timeout,
    /// An outbound HTTP request failed.
    #[error("OAuth HTTP request failed")]
    Http(#[source] reqwest::Error),
    /// The user denied authorization or the authorization endpoint returned an error.
    #[error("OAuth authorization was not completed (`{error}`)")]
    AuthorizationDenied { error: String },
    /// The provider returned an OAuth protocol error.
    #[error("OAuth provider returned error `{error}`")]
    OAuthProvider { error: String },
    /// The token endpoint returned a non-success response.
    #[error("OAuth token exchange failed with HTTP status {status}")]
    TokenExchange { status: u16 },
    /// A successful token response was invalid.
    #[error("failed to decode OAuth token response")]
    TokenDecode(#[source] serde_json::Error),
    /// The profile endpoint returned a non-success response.
    #[error("MediaWiki profile request failed with HTTP status {status}")]
    ProfileRequest { status: u16 },
    /// A successful profile response was invalid.
    #[error("failed to decode MediaWiki user profile")]
    ProfileDecode(#[source] serde_json::Error),
    /// An HTTP response exceeded the safety limit.
    #[error("OAuth HTTP response exceeded the {limit} byte limit")]
    ResponseTooLarge { limit: usize },
    /// The session backend failed.
    #[error("OAuth session operation failed")]
    Session,
    /// The user does not have an authenticated session.
    #[error("not logged in")]
    NotLoggedIn,
    /// The authenticated session can no longer be refreshed.
    #[error("session expired")]
    SessionExpired,
}

impl Error {
    /// Return the framework-independent category for this error.
    pub fn kind(&self) -> ErrorKind {
        match self {
            Self::Configuration(_) | Self::UrlConstruction | Self::Randomness => {
                ErrorKind::Configuration
            }
            Self::MissingFlowState
            | Self::ExpiredFlowState(_)
            | Self::InvalidFlowState
            | Self::StateMismatch
            | Self::InvalidPkce
            | Self::AuthorizationDenied { .. } => ErrorKind::Callback,
            Self::Timeout | Self::Http(_) => ErrorKind::Network,
            Self::OAuthProvider { .. }
            | Self::TokenExchange { .. }
            | Self::TokenDecode(_)
            | Self::ProfileRequest { .. }
            | Self::ProfileDecode(_)
            | Self::ResponseTooLarge { .. } => ErrorKind::Provider,
            Self::Session => ErrorKind::Session,
            Self::NotLoggedIn | Self::SessionExpired => ErrorKind::Unauthenticated,
        }
    }

    pub(crate) fn configuration(message: impl Into<String>) -> Self {
        Self::Configuration(message.into())
    }

    pub(crate) fn from_http(error: reqwest::Error) -> Self {
        if error.is_timeout() {
            Self::Timeout
        } else {
            Self::Http(error)
        }
    }
}

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

    #[test]
    fn errors_have_stable_categories() {
        assert_eq!(Error::NotLoggedIn.kind(), ErrorKind::Unauthenticated);
        assert_eq!(Error::StateMismatch.kind(), ErrorKind::Callback);
        assert_eq!(Error::Timeout.kind(), ErrorKind::Network);
        assert_eq!(
            Error::OAuthProvider {
                error: "invalid_grant".to_owned(),
            }
            .kind(),
            ErrorKind::Provider
        );
        assert_eq!(
            Error::Configuration("missing client_id".to_owned()).kind(),
            ErrorKind::Configuration
        );
    }
}