limes-common 0.3.0

Shared authentication, config, events, and errors for limes crates.
Documentation
use limes_proto::{AuthFailure, AuthOutcome, AuthRequest, AuthSuccess};

use crate::{LimesError, Result};

/// Trusted authentication backend used by login managers.
///
/// Successful authentication transfers ownership of a transaction to the caller.
pub trait AuthBackend: Send + Sync {
    fn authenticate(
        &self,
        request: &AuthRequest,
    ) -> std::result::Result<AuthenticatedLogin, AuthFailure>;
}

/// An owned backend transaction. Implementers must attempt all cleanup even when
/// one cleanup step fails. `close` must be idempotent.
pub trait AuthSession: Send {
    fn open(&mut self) -> Result<Vec<(String, String)>>;
    fn close(&mut self) -> Result<()>;
}

/// A non-cloneable authenticated identity and its owned backend transaction.
///
/// The identity cannot be replaced or mutated by a session caller. Constructing
/// this capability is reserved for trusted backend implementations, not frontends.
#[must_use = "dropping an authenticated login closes its backend transaction"]
pub struct AuthenticatedLogin {
    identity: AuthSuccess,
    session: Box<dyn AuthSession>,
    open_attempted: bool,
    closed: bool,
}

impl std::fmt::Debug for AuthenticatedLogin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthenticatedLogin")
            .field("identity", &self.identity)
            .field("open_attempted", &self.open_attempted)
            .field("closed", &self.closed)
            .finish_non_exhaustive()
    }
}

impl AuthenticatedLogin {
    /// Create a capability in a trusted authentication backend.
    pub fn new(identity: AuthSuccess, session: Box<dyn AuthSession>) -> Self {
        Self {
            identity,
            session,
            open_attempted: false,
            closed: false,
        }
    }

    #[must_use]
    pub fn identity(&self) -> &AuthSuccess {
        &self.identity
    }

    /// Attempt session opening exactly once, including when opening fails.
    pub fn open_session(&mut self) -> Result<Vec<(String, String)>> {
        if self.closed || self.open_attempted {
            return Err(LimesError::Auth(
                "authentication transaction cannot be opened again".to_owned(),
            ));
        }
        self.open_attempted = true;
        self.session.open()
    }

    /// Finish the transaction once. Errors describe cleanup failure, not a
    /// reusable transaction; all later calls are no-ops.
    pub fn close_session(&mut self) -> Result<()> {
        if self.closed {
            return Ok(());
        }
        self.closed = true;
        self.session.close()
    }
}

impl Drop for AuthenticatedLogin {
    fn drop(&mut self) {
        let _ = self.close_session();
    }
}

/// Lock authentication never exposes or opens a login transaction.
pub trait LockAuthBackend: Send + Sync {
    fn authenticate(&self, request: &AuthRequest) -> AuthOutcome;
}

impl<T: AuthBackend + ?Sized> LockAuthBackend for T {
    fn authenticate(&self, request: &AuthRequest) -> AuthOutcome {
        let mut login = AuthBackend::authenticate(self, request)?;
        let identity = login.identity().clone();
        login
            .close_session()
            .map_err(|error| AuthFailure::Internal(error.to_string()))?;
        Ok(identity)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    struct Session {
        calls: Arc<Mutex<Vec<&'static str>>>,
        fail: bool,
    }
    impl AuthSession for Session {
        fn open(&mut self) -> Result<Vec<(String, String)>> {
            self.calls.lock().unwrap().push("open");
            if self.fail {
                return Err(LimesError::Auth("open failed".into()));
            }
            Ok(Vec::new())
        }
        fn close(&mut self) -> Result<()> {
            self.calls.lock().unwrap().push("close");
            if self.fail {
                return Err(LimesError::Auth("close failed".into()));
            }
            Ok(())
        }
    }
    fn login(calls: Arc<Mutex<Vec<&'static str>>>, fail: bool) -> AuthenticatedLogin {
        AuthenticatedLogin::new(
            AuthSuccess {
                username: "alice".into(),
                uid: 1000,
                gid: 1000,
                home: None,
                shell: None,
            },
            Box::new(Session { calls, fail }),
        )
    }
    #[test]
    fn open_is_once_only_and_close_is_idempotent() {
        let calls = Arc::default();
        let mut auth = login(Arc::clone(&calls), false);
        auth.open_session().unwrap();
        assert!(auth.open_session().is_err());
        auth.close_session().unwrap();
        auth.close_session().unwrap();
        assert!(auth.open_session().is_err());
        drop(auth);
        assert_eq!(*calls.lock().unwrap(), vec!["open", "close"]);
    }
    #[test]
    fn failure_does_not_allow_reopening_or_duplicate_cleanup() {
        let calls = Arc::default();
        let mut auth = login(Arc::clone(&calls), true);
        assert!(auth.open_session().is_err());
        assert!(auth.open_session().is_err());
        assert!(auth.close_session().is_err());
        auth.close_session().unwrap();
        drop(auth);
        assert_eq!(*calls.lock().unwrap(), vec!["open", "close"]);
    }
    #[test]
    fn pending_transaction_is_closed_on_drop() {
        let calls = Arc::default();
        drop(login(Arc::clone(&calls), false));
        assert_eq!(*calls.lock().unwrap(), vec!["close"]);
    }
    struct Backend {
        calls: Arc<Mutex<Vec<&'static str>>>,
    }
    impl AuthBackend for Backend {
        fn authenticate(
            &self,
            _: &AuthRequest,
        ) -> std::result::Result<AuthenticatedLogin, AuthFailure> {
            Ok(login(self.calls.clone(), true))
        }
    }
    #[test]
    fn lock_adapter_propagates_close_failure_without_opening() {
        let calls = Arc::default();
        let backend = Backend {
            calls: Arc::clone(&calls),
        };
        assert!(matches!(
            LockAuthBackend::authenticate(&backend, &AuthRequest::new("alice", "secret")),
            Err(AuthFailure::Internal(_))
        ));
        assert_eq!(*calls.lock().unwrap(), vec!["close"]);
    }
}