use limes_proto::{AuthFailure, AuthOutcome, AuthRequest, AuthSuccess};
use crate::{LimesError, Result};
pub trait AuthBackend: Send + Sync {
fn authenticate(
&self,
request: &AuthRequest,
) -> std::result::Result<AuthenticatedLogin, AuthFailure>;
}
pub trait AuthSession: Send {
fn open(&mut self) -> Result<Vec<(String, String)>>;
fn close(&mut self) -> Result<()>;
}
#[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 {
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
}
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()
}
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();
}
}
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"]);
}
}