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 crate::{AuthenticatedUser, Error};
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Maximum age used for newly-created authorization flows.
pub const DEFAULT_FLOW_TTL: Duration = Duration::from_secs(10 * 60);

/// Maximum age used for newly-authenticated sessions.
pub const DEFAULT_SESSION_TTL: Duration = Duration::from_secs(24 * 60 * 60);

/// Secret data that must survive between authorization and callback requests.
///
/// Adapters must protect this value from disclosure and modification. A pending
/// flow is consumed before callback validation, so every callback attempt is
/// terminal and authorization codes and PKCE verifiers cannot be replayed.
#[derive(Clone, Deserialize, Serialize)]
pub struct PendingOAuthFlow {
    state: String,
    pkce_verifier: String,
    expires_at: u64,
}

impl std::fmt::Debug for PendingOAuthFlow {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PendingOAuthFlow")
            .field("state", &"[REDACTED]")
            .field("pkce_verifier", &"[REDACTED]")
            .field("expires_at", &self.expires_at)
            .finish()
    }
}

impl PendingOAuthFlow {
    pub(crate) fn new(
        state: String,
        pkce_verifier: String,
        created_at: u64,
        ttl: Duration,
    ) -> Result<Self, Error> {
        let expires_at = created_at
            .checked_add(ttl.as_secs())
            .ok_or_else(|| Error::configuration("OAuth flow lifetime is too large"))?;
        Ok(Self {
            state,
            pkce_verifier,
            expires_at,
        })
    }

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

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

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

/// Framework-neutral storage used by OAuth adapters.
///
/// Methods are synchronous because cookie and in-request session adapters do
/// not require I/O. Implementations must not perform blocking network or disk
/// operations. Server-side implementations should atomically remove and return
/// the flow. Cookie-backed adapters can only send a removal cookie in the
/// response; a retained copy remains valid until the flow expires.
pub trait SessionStore {
    /// Read pending flow data without consuming it.
    fn pending_flow(&self) -> Result<Option<PendingOAuthFlow>, Error>;
    /// Replace pending flow data.
    fn set_pending_flow(&mut self, flow: PendingOAuthFlow) -> Result<(), Error>;
    /// Remove and return pending flow data.
    fn take_pending_flow(&mut self) -> Result<Option<PendingOAuthFlow>, Error>;
    /// Read the authenticated user.
    fn authenticated_user(&self) -> Result<Option<AuthenticatedUser>, Error>;
    /// Store or replace the authenticated user.
    fn set_authenticated_user(&mut self, user: AuthenticatedUser) -> Result<(), Error>;
    /// Clear authenticated user data.
    fn clear_authenticated_user(&mut self) -> Result<(), Error>;
    /// Clear pending flow data.
    fn clear_pending_flow(&mut self) -> Result<(), Error>;

    /// Clear all OAuth-related session data.
    fn clear(&mut self) -> Result<(), Error> {
        self.clear_pending_flow()?;
        self.clear_authenticated_user()
    }
}

#[cfg(test)]
#[derive(Default)]
pub(crate) struct MemorySessionStore {
    pending: Option<PendingOAuthFlow>,
    authenticated: Option<AuthenticatedUser>,
}

#[cfg(test)]
impl SessionStore for MemorySessionStore {
    fn pending_flow(&self) -> Result<Option<PendingOAuthFlow>, Error> {
        Ok(self.pending.clone())
    }

    fn set_pending_flow(&mut self, flow: PendingOAuthFlow) -> Result<(), Error> {
        self.pending = Some(flow);
        Ok(())
    }

    fn take_pending_flow(&mut self) -> Result<Option<PendingOAuthFlow>, Error> {
        Ok(self.pending.take())
    }

    fn authenticated_user(&self) -> Result<Option<AuthenticatedUser>, Error> {
        Ok(self.authenticated.clone())
    }

    fn set_authenticated_user(&mut self, user: AuthenticatedUser) -> Result<(), Error> {
        self.authenticated = Some(user);
        Ok(())
    }

    fn clear_authenticated_user(&mut self) -> Result<(), Error> {
        self.authenticated = None;
        Ok(())
    }

    fn clear_pending_flow(&mut self) -> Result<(), Error> {
        self.pending = None;
        Ok(())
    }
}