icedwright-probe 0.1.3

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
//! Whether the endpoint opens and where, decided from facts passed in so every branch is a
//! unit test.

use std::ffi::OsStr;
use std::fmt;
use std::path::{Path, PathBuf};

/// The environment variable that turns the endpoint on: `1` for the default path, or a path.
pub const ENV: &str = "ICEDWRIGHT_REMOTE";

/// Everything [`decide`] reads.
#[derive(Debug, Clone, Copy)]
pub struct Startup<'a> {
    /// `cfg!(debug_assertions)`.
    pub debug_assertions: bool,
    /// Whether the `remote-in-release` feature is on.
    pub allow_in_release: bool,
    /// The value of `ICEDWRIGHT_REMOTE`.
    pub remote_env: Option<&'a OsStr>,
    /// `$XDG_RUNTIME_DIR`.
    pub runtime_dir: Option<&'a Path>,
    /// The program's name.
    pub app: &'a str,
    /// The process id.
    pub pid: u32,
}

/// Where the socket goes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SocketPlan {
    /// Its directory, which must be private to this user.
    pub dir: PathBuf,
    /// Whether the probe creates the directory with mode 0700 if it is missing.
    pub create_dir: bool,
    /// The socket itself.
    pub path: PathBuf,
}

/// What the endpoint does at startup.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
    /// `ICEDWRIGHT_REMOTE` is unset: run the app without an endpoint.
    Off,
    /// Open the socket.
    Listen(SocketPlan),
}

/// Why the endpoint did not open.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Refusal {
    /// A release profile without the `remote-in-release` feature.
    Release,
    /// `ICEDWRIGHT_REMOTE=1` with no `XDG_RUNTIME_DIR`. The probe never falls back to `/tmp`.
    NoRuntimeDir,
    /// The explicit path has no parent directory.
    NoParent(PathBuf),
    /// The directory belongs to someone else.
    NotOwned {
        /// The directory.
        dir: PathBuf,
        /// Its owner.
        owner: u32,
    },
    /// The directory is writable by its group or by others.
    Writable {
        /// The directory.
        dir: PathBuf,
        /// Its permission bits.
        mode: u32,
    },
    /// The directory or socket could not be set up.
    Io(String),
}

impl fmt::Display for Refusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Refusal::Release => f.write_str(
                "this is a release build; the remote endpoint opens in release only with the \
                 probe's `remote-in-release` feature",
            ),
            Refusal::NoRuntimeDir => f.write_str(
                "XDG_RUNTIME_DIR is not set, and the endpoint never falls back to /tmp; set it \
                 or give ICEDWRIGHT_REMOTE a socket path",
            ),
            Refusal::NoParent(path) => {
                write!(f, "the socket path {} has no directory", path.display())
            }
            Refusal::NotOwned { dir, owner } => write!(
                f,
                "{} belongs to uid {owner}, not to this user",
                dir.display()
            ),
            Refusal::Writable { dir, mode } => write!(
                f,
                "{} is writable by its group or others (mode {mode:o}); it must be private",
                dir.display()
            ),
            Refusal::Io(error) => write!(f, "the socket could not be set up: {error}"),
        }
    }
}

impl std::error::Error for Refusal {}

/// Decides whether and where the endpoint listens.
pub fn decide(startup: &Startup<'_>) -> Result<Decision, Refusal> {
    let Some(value) = startup.remote_env.filter(|v| !v.is_empty()) else {
        return Ok(Decision::Off);
    };
    if !startup.debug_assertions && !startup.allow_in_release {
        return Err(Refusal::Release);
    }
    if value == "1" {
        let runtime = startup.runtime_dir.ok_or(Refusal::NoRuntimeDir)?;
        let dir = runtime.join("icedwright");
        let path = dir.join(format!("{}-{}.sock", file_safe(startup.app), startup.pid));
        return Ok(Decision::Listen(SocketPlan {
            dir,
            create_dir: true,
            path,
        }));
    }
    let path = PathBuf::from(value);
    let dir = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .ok_or_else(|| Refusal::NoParent(path.clone()))?
        .to_path_buf();
    Ok(Decision::Listen(SocketPlan {
        dir,
        create_dir: false,
        path,
    }))
}

/// What [`check_dir`] needs to know about a directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DirFacts {
    /// Its owner's uid.
    pub owner: u32,
    /// Its mode bits.
    pub mode: u32,
}

/// Accepts a socket directory only when this user owns it and nobody else can write to it.
pub fn check_dir(dir: &Path, facts: DirFacts, uid: u32) -> Result<(), Refusal> {
    if facts.owner != uid {
        return Err(Refusal::NotOwned {
            dir: dir.to_path_buf(),
            owner: facts.owner,
        });
    }
    if facts.mode & 0o022 != 0 {
        return Err(Refusal::Writable {
            dir: dir.to_path_buf(),
            mode: facts.mode & 0o7777,
        });
    }
    Ok(())
}

fn file_safe(name: &str) -> String {
    let cleaned: String = name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if cleaned.is_empty() {
        "app".to_owned()
    } else {
        cleaned
    }
}

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

    fn startup<'a>(env: Option<&'a str>, runtime: Option<&'a Path>) -> Startup<'a> {
        Startup {
            debug_assertions: true,
            allow_in_release: false,
            remote_env: env.map(OsStr::new),
            runtime_dir: runtime,
            app: "remote demo",
            pid: 42,
        }
    }

    #[test]
    fn unset_or_empty_means_off() {
        assert_eq!(decide(&startup(None, None)), Ok(Decision::Off));
        assert_eq!(decide(&startup(Some(""), None)), Ok(Decision::Off));
    }

    #[test]
    fn release_profile_refuses_unless_allowed() {
        let mut s = startup(Some("1"), Some(Path::new("/run/user/1000")));
        s.debug_assertions = false;
        assert_eq!(decide(&s), Err(Refusal::Release));
        s.allow_in_release = true;
        assert!(matches!(decide(&s), Ok(Decision::Listen(_))));
    }

    #[test]
    fn release_profile_without_the_variable_stays_off() {
        let mut s = startup(None, None);
        s.debug_assertions = false;
        assert_eq!(decide(&s), Ok(Decision::Off));
    }

    #[test]
    fn default_path_lives_in_the_runtime_dir() {
        let decision = decide(&startup(Some("1"), Some(Path::new("/run/user/1000"))));
        assert_eq!(
            decision,
            Ok(Decision::Listen(SocketPlan {
                dir: PathBuf::from("/run/user/1000/icedwright"),
                create_dir: true,
                path: PathBuf::from("/run/user/1000/icedwright/remote_demo-42.sock"),
            }))
        );
    }

    #[test]
    fn missing_runtime_dir_is_refused_without_a_fallback() {
        assert_eq!(
            decide(&startup(Some("1"), None)),
            Err(Refusal::NoRuntimeDir)
        );
    }

    #[test]
    fn explicit_paths_use_their_parent() {
        let decision = decide(&startup(Some("/home/me/sockets/app.sock"), None));
        assert_eq!(
            decision,
            Ok(Decision::Listen(SocketPlan {
                dir: PathBuf::from("/home/me/sockets"),
                create_dir: false,
                path: PathBuf::from("/home/me/sockets/app.sock"),
            }))
        );
        assert!(matches!(
            decide(&startup(Some("app.sock"), None)),
            Err(Refusal::NoParent(_))
        ));
    }

    #[test]
    fn directories_must_be_private_and_ours() {
        let dir = Path::new("/d");
        let ok = DirFacts {
            owner: 1000,
            mode: 0o40700,
        };
        assert_eq!(check_dir(dir, ok, 1000), Ok(()));
        assert!(matches!(
            check_dir(
                dir,
                DirFacts {
                    mode: 0o40770,
                    ..ok
                },
                1000
            ),
            Err(Refusal::Writable { mode: 0o770, .. })
        ));
        assert!(matches!(
            check_dir(
                dir,
                DirFacts {
                    mode: 0o40702,
                    ..ok
                },
                1000
            ),
            Err(Refusal::Writable { .. })
        ));
        assert!(matches!(
            check_dir(dir, DirFacts { owner: 0, ..ok }, 1000),
            Err(Refusal::NotOwned { owner: 0, .. })
        ));
        assert_eq!(
            check_dir(
                dir,
                DirFacts {
                    mode: 0o40755,
                    ..ok
                },
                1000
            ),
            Ok(())
        );
    }
}