icedwright-probe 0.1.4

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
Documentation
//! The socket the endpoint listens on, behind traits so the serving logic is tested with
//! mocks. Plain `std::os::unix::net`, so it needs no async runtime.

use std::io::{self, Read, Write};
use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};

use icedwright_protocol::{HEADER_LEN, ProtocolError, WireFrame};

use super::policy::{DirFacts, Refusal, SocketPlan, check_dir};

/// Accepts connections.
#[cfg_attr(test, mockall::automock)]
pub trait Listener: Send {
    /// Waits for the next connection.
    fn accept(&mut self) -> io::Result<Box<dyn Socket>>;
}

/// One connection.
#[cfg_attr(test, mockall::automock)]
pub trait Socket: Send {
    /// Reads one frame.
    fn read_frame(&mut self) -> io::Result<WireFrame>;
    /// Writes one frame.
    fn write_frame(&mut self, frame: &WireFrame) -> io::Result<()>;
    /// Whether the peer runs as this process's user.
    fn peer_is_same_user(&self) -> io::Result<bool>;
    /// A second handle on the same connection, for the writer thread.
    fn try_clone(&self) -> io::Result<Box<dyn Socket>>;
}

/// The listening socket, removed again when dropped.
#[derive(Debug)]
pub struct UnixEndpoint {
    listener: UnixListener,
    path: PathBuf,
}

impl UnixEndpoint {
    /// Prepares the directory as `plan` says, checks it is private, and binds the socket with
    /// mode 0600.
    pub fn bind(plan: &SocketPlan) -> Result<Self, Refusal> {
        let io = |error: io::Error| Refusal::Io(error.to_string());
        if plan.create_dir && !plan.dir.exists() {
            std::fs::DirBuilder::new()
                .recursive(true)
                .mode(0o700)
                .create(&plan.dir)
                .map_err(io)?;
        }
        let metadata = std::fs::metadata(&plan.dir).map_err(io)?;
        let facts = DirFacts {
            owner: metadata.uid(),
            mode: metadata.mode(),
        };
        check_dir(&plan.dir, facts, rustix::process::getuid().as_raw())?;
        remove_stale(&plan.path).map_err(io)?;
        let listener = UnixListener::bind(&plan.path).map_err(io)?;
        std::fs::set_permissions(&plan.path, std::fs::Permissions::from_mode(0o600)).map_err(io)?;
        Ok(Self {
            listener,
            path: plan.path.clone(),
        })
    }

    /// Where it listens.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }
}

/// A socket file left by a process that exited is removed; anything else at the path is an
/// error from `bind`.
fn remove_stale(path: &Path) -> io::Result<()> {
    use std::os::unix::fs::FileTypeExt;
    match std::fs::symlink_metadata(path) {
        Ok(meta) if meta.file_type().is_socket() && UnixStream::connect(path).is_err() => {
            std::fs::remove_file(path)
        }
        _ => Ok(()),
    }
}

impl Drop for UnixEndpoint {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

impl Listener for UnixEndpoint {
    fn accept(&mut self) -> io::Result<Box<dyn Socket>> {
        let (stream, _) = self.listener.accept()?;
        Ok(Box::new(UnixSocket { stream }))
    }
}

/// A connection over a Unix stream.
#[derive(Debug)]
pub struct UnixSocket {
    stream: UnixStream,
}

impl UnixSocket {
    /// Wraps a connected stream.
    #[must_use]
    pub fn new(stream: UnixStream) -> Self {
        Self { stream }
    }
}

fn invalid(error: ProtocolError) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, error)
}

impl Socket for UnixSocket {
    fn read_frame(&mut self) -> io::Result<WireFrame> {
        let mut header = [0; HEADER_LEN];
        self.stream.read_exact(&mut header)?;
        let (kind, length) = WireFrame::decode_header(header).map_err(invalid)?;
        let mut payload = vec![0; length];
        self.stream.read_exact(&mut payload)?;
        Ok(WireFrame { kind, payload })
    }

    fn write_frame(&mut self, frame: &WireFrame) -> io::Result<()> {
        let bytes = frame.encode().map_err(invalid)?;
        self.stream.write_all(&bytes)?;
        self.stream.flush()
    }

    fn peer_is_same_user(&self) -> io::Result<bool> {
        let peer = rustix::net::sockopt::socket_peercred(&self.stream)?;
        Ok(peer.uid == rustix::process::getuid())
    }

    fn try_clone(&self) -> io::Result<Box<dyn Socket>> {
        Ok(Box::new(UnixSocket {
            stream: self.stream.try_clone()?,
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[ignore = "display: binds a real socket under XDG_RUNTIME_DIR; run through scripts/with-display.sh"]
    fn a_real_socket_round_trips_frames_and_sees_the_same_user() -> io::Result<()> {
        let Some(runtime) = std::env::var_os("XDG_RUNTIME_DIR") else {
            return Err(io::Error::other("XDG_RUNTIME_DIR is not set"));
        };
        let dir = Path::new(&runtime).join(format!("icedwright-probe-test-{}", std::process::id()));
        let plan = SocketPlan {
            dir: dir.clone(),
            create_dir: true,
            path: dir.join("t.sock"),
        };
        let mut endpoint = UnixEndpoint::bind(&plan).map_err(io::Error::other)?;
        let client = UnixStream::connect(endpoint.path())?;
        let mut server = endpoint.accept()?;
        let mut client = UnixSocket::new(client);
        client.write_frame(&WireFrame::json(b"{}".to_vec()))?;
        assert_eq!(server.read_frame()?, WireFrame::json(b"{}".to_vec()));
        assert!(server.peer_is_same_user()?);
        drop(endpoint);
        std::fs::remove_dir(&dir)
    }
}