Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-cli/src/login_cancellation.rs

Raw
//! SMH-SPEC-SPEC0001, SMH-SPEC-PLUG0001: Unix `SIGINT` bridge for foreground OAuth login.
//!
//! The process blocks `SIGINT` before it creates worker threads.
//! One waiter receives it through `sigwait`; login then durably aborts its admitted root.

use smith::error::{Result, SmithError};
use std::sync::mpsc::{self, Receiver};

/// Receive one process interrupt for one foreground login.
pub struct LoginCancellation {
    receiver: Option<Receiver<()>>,
    #[cfg(target_os = "linux")]
    waiter: Option<std::thread::JoinHandle<nix::Result<()>>>,
    #[cfg(target_os = "linux")]
    waiter_thread: nix::sys::pthread::Pthread,
    #[cfg(target_os = "linux")]
    old_mask: Option<nix::sys::signal::SigSet>,
}

impl LoginCancellation {
    /// Install the process-local interrupt waiter before starting OAuth work.
    ///
    /// # Errors
    /// Returns a configuration error when Linux cannot block or wait for `SIGINT`.
    #[cfg(target_os = "linux")]
    pub(crate) fn install() -> Result<Self> {
        use nix::sys::pthread::pthread_self;
        use nix::sys::signal::{SigSet, SigmaskHow, Signal};

        let mut signals = SigSet::empty();
        signals.add(Signal::SIGINT);
        signals.add(Signal::SIGUSR1);
        let old_mask = signals
            .thread_swap_mask(SigmaskHow::SIG_BLOCK)
            .map_err(|_| signal_fault())?;
        let (send, receiver) = mpsc::sync_channel(1);
        let (ready_send, ready_receive) = mpsc::sync_channel(1);
        let waiter = std::thread::spawn(move || {
            if ready_send.send(pthread_self()).is_err() {
                return Ok(());
            }
            loop {
                match signals.wait()? {
                    Signal::SIGINT => {
                        let _sent = send.try_send(());
                    }
                    Signal::SIGUSR1 => return Ok(()),
                    _ => {}
                }
            }
        });
        let Ok(waiter_thread) = ready_receive.recv() else {
            let _joined = waiter.join();
            let _restored = old_mask.thread_set_mask();
            return Err(signal_fault());
        };
        Ok(Self {
            receiver: Some(receiver),
            waiter: Some(waiter),
            waiter_thread,
            old_mask: Some(old_mask),
        })
    }

    /// Unsupported hosts retain normal platform signal semantics.
    #[cfg(not(target_os = "linux"))]
    pub(crate) fn install() -> Result<Self> {
        let (_send, receiver) = mpsc::sync_channel(1);
        Ok(Self {
            receiver: Some(receiver),
        })
    }

    /// Transfer the one-shot interrupt signal to the admitted login while retaining its guard.
    pub(crate) fn take_receiver(&mut self) -> Result<Receiver<()>> {
        self.receiver.take().ok_or_else(signal_fault)
    }

    /// Wake, join, and restore the caller's exact previous signal mask.
    ///
    /// # Errors
    /// Returns a configuration error when the waiter cannot stop or the previous mask cannot restore.
    pub(crate) fn finish(&mut self) -> Result<()> {
        #[cfg(target_os = "linux")]
        {
            use nix::sys::pthread::pthread_kill;
            use nix::sys::signal::Signal;

            let wake = self
                .waiter
                .as_ref()
                .map(|_| pthread_kill(self.waiter_thread, Signal::SIGUSR1));
            let joined = self.waiter.take().map_or(Ok(()), |waiter| {
                waiter
                    .join()
                    .map_err(|_| signal_fault())?
                    .map_err(|_| signal_fault())
            });
            let restored = self.old_mask.take().map_or(Ok(()), |old_mask| {
                old_mask.thread_set_mask().map_err(|_| signal_fault())
            });
            wake.transpose().map_err(|_| signal_fault())?;
            joined?;
            restored?;
        }
        Ok(())
    }
}

impl Drop for LoginCancellation {
    fn drop(&mut self) {
        let _finished = self.finish();
    }
}

fn signal_fault() -> SmithError {
    SmithError::Config {
        field: "login".into(),
        message: "OAuth login interrupt setup failed".into(),
    }
}

#[cfg(all(test, target_os = "linux"))]
mod tests {
    //! SMH-SPEC-SPEC0001, SMH-SPEC-PLUG0001: Linux signal guard lifecycle.
    use super::LoginCancellation;

    #[test]
    fn normal_completion_restores_the_calling_thread_mask() {
        let before = nix::sys::signal::SigSet::thread_get_mask().unwrap();
        let mut cancellation = LoginCancellation::install().unwrap();
        cancellation.finish().unwrap();
        assert_eq!(nix::sys::signal::SigSet::thread_get_mask().unwrap(), before);
    }
}