limes-common 0.3.0

Shared authentication, config, events, and errors for limes crates.
Documentation
use std::io::Write;
use std::sync::{Arc, Mutex};

use limes_proto::LimesEvent;

/// Synchronous observer. Panics are isolated; observers must still return
/// promptly and must not assume authentication/session control authority.
pub trait EventSink: Send + Sync {
    fn emit(&self, event: &LimesEvent);
}

#[derive(Debug, Clone, Copy, Default)]
pub struct StderrEventSink;

impl EventSink for StderrEventSink {
    fn emit(&self, event: &LimesEvent) {
        let _ = writeln!(std::io::stderr().lock(), "limes event: {event:?}");
    }
}

#[derive(Clone, Default)]
pub struct EventBus {
    sinks: Arc<Mutex<Vec<Arc<dyn EventSink>>>>,
}

impl EventBus {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn from_env() -> Self {
        let events = Self::new();
        if std::env::var_os("LIMES_LOG_EVENTS").is_some() {
            events.subscribe(Arc::new(StderrEventSink));
        }
        events
    }

    pub fn subscribe(&self, sink: Arc<dyn EventSink>) {
        if let Ok(mut sinks) = self.sinks.lock() {
            sinks.push(sink);
        }
    }

    pub fn emit(&self, event: LimesEvent) {
        let sinks = self
            .sinks
            .lock()
            .map(|sinks| sinks.clone())
            .unwrap_or_default();

        for sink in sinks {
            // Observers are untrusted with respect to transaction control flow.
            // No bus mutex is held while calling them, including on re-entry.
            if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                sink.emit(&event);
            })) {
                // A custom panic payload may itself panic in Drop. Keep that
                // exceptional payload from unwinding security-sensitive code.
                std::mem::forget(payload);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct Panicking;
    impl EventSink for Panicking {
        fn emit(&self, _: &LimesEvent) {
            panic!("observer panic");
        }
    }
    struct Reentrant {
        bus: EventBus,
        count: Arc<AtomicUsize>,
    }
    impl EventSink for Reentrant {
        fn emit(&self, event: &LimesEvent) {
            self.bus.subscribe(Arc::new(StderrEventSink));
            if self.count.fetch_add(1, Ordering::SeqCst) == 0 {
                self.bus.emit(event.clone());
            }
        }
    }
    #[test]
    fn observer_panics_do_not_stop_later_or_reentrant_observers() {
        let bus = EventBus::new();
        let count = Arc::new(AtomicUsize::new(0));
        bus.subscribe(Arc::new(Panicking));
        bus.subscribe(Arc::new(Reentrant {
            bus: bus.clone(),
            count: count.clone(),
        }));
        bus.emit(LimesEvent::AuthStarted {
            username: "alice".into(),
        });
        assert_eq!(count.load(Ordering::SeqCst), 2);
        bus.emit(LimesEvent::AuthStarted {
            username: "alice".into(),
        });
        assert_eq!(count.load(Ordering::SeqCst), 3);
    }
}