lean-ctx 3.12.10

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! Reading the root-owned files cloud-init writes, failing closed.
//!
//! A file is read only when it is a regular file (never through a symlink),
//! owned by the expected user (root on the computer) and not writable by
//! anyone else; a token file must also be unreadable by anyone else (`0600`).
//! The checks run on the opened handle, so the file cannot be swapped between
//! check and read. Errors name the path and the failed check, never content.

#[cfg(unix)]
use std::io::Read;
use std::path::Path;

use zeroize::Zeroizing;

/// The longest token the cloud issues (cloud-init's token charset bound).
pub(crate) const MAX_TOKEN_LEN: usize = 256;

/// Who may read the file besides its owner.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Exposure {
    /// Owner-only (`0600`, `0400`): tokens.
    Private,
    /// World-readable but owner-writable only (`0644`): `computer.json`.
    Readable,
}

/// Read at most `max` bytes of `path` after the ownership and mode checks.
pub(crate) fn read_checked(
    path: &Path,
    owner: u32,
    exposure: Exposure,
    max: usize,
) -> Result<Zeroizing<Vec<u8>>, String> {
    read_checked_impl(path, owner, exposure, max)
}

#[cfg(unix)]
fn read_checked_impl(
    path: &Path,
    owner: u32,
    exposure: Exposure,
    max: usize,
) -> Result<Zeroizing<Vec<u8>>, String> {
    use std::os::unix::fs::{MetadataExt, OpenOptionsExt};

    let shown = path.display();
    let file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
        .open(path)
        .map_err(|e| format!("{shown}: cannot open ({})", e.kind()))?;
    let meta = file
        .metadata()
        .map_err(|e| format!("{shown}: cannot stat ({})", e.kind()))?;
    if !meta.file_type().is_file() {
        return Err(format!("{shown}: not a regular file"));
    }
    if meta.uid() != owner {
        return Err(format!("{shown}: not owned by uid {owner}"));
    }
    let forbidden = match exposure {
        Exposure::Private => 0o077,
        Exposure::Readable => 0o022,
    };
    if meta.mode() & forbidden != 0 {
        return Err(format!(
            "{shown}: mode {:o} is too open",
            meta.mode() & 0o7777
        ));
    }
    let mut bytes = Zeroizing::new(Vec::with_capacity(max.min(4096)));
    file.take(max as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| format!("{shown}: cannot read ({})", e.kind()))?;
    if bytes.len() > max {
        return Err(format!("{shown}: larger than {max} bytes"));
    }
    Ok(bytes)
}

/// Without Unix ownership and modes nothing can be checked: refuse.
#[cfg(not(unix))]
fn read_checked_impl(
    path: &Path,
    _owner: u32,
    _exposure: Exposure,
    _max: usize,
) -> Result<Zeroizing<Vec<u8>>, String> {
    Err(format!(
        "{}: a cloud computer's files are read on Linux only",
        path.display()
    ))
}

/// A token file: `prefix` and 64 lowercase hex digits, with one optional
/// trailing newline (cloud-init's YAML block adds it).
pub(crate) fn read_token(
    path: &Path,
    owner: u32,
    prefix: &str,
) -> Result<Zeroizing<String>, String> {
    let bytes = read_checked(path, owner, Exposure::Private, MAX_TOKEN_LEN + 2)?;
    parse_token(&bytes, prefix).map_err(|why| format!("{}: {why}", path.display()))
}

/// The token in `bytes`, checked against its documented form. The reason
/// never quotes the content.
pub(crate) fn parse_token(bytes: &[u8], prefix: &str) -> Result<Zeroizing<String>, &'static str> {
    let body = bytes
        .strip_suffix(b"\n")
        .map_or(bytes, |b| b.strip_suffix(b"\r").unwrap_or(b));
    if body.is_empty() {
        return Err("the token file is empty");
    }
    if body.len() > MAX_TOKEN_LEN
        || !body
            .iter()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
    {
        return Err("the token file holds something other than one token");
    }
    let Some(hex) = body.strip_prefix(prefix.as_bytes()) else {
        return Err("the token has the wrong prefix");
    };
    if hex.len() != 64 || !hex.iter().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
        return Err("the token is not its prefix followed by 64 hex digits");
    }
    // Checked ASCII above.
    let text = std::str::from_utf8(body).map_err(|_| "the token is not text")?;
    Ok(Zeroizing::new(text.to_string()))
}

/// The effective uid of this process (0 = root).
#[cfg(unix)]
pub(crate) fn effective_uid() -> u32 {
    // SAFETY: geteuid has no preconditions and cannot fail.
    unsafe { libc::geteuid() }
}

#[cfg(not(unix))]
pub(crate) fn effective_uid() -> u32 {
    u32::MAX
}

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

    const HEX: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    #[test]
    fn a_token_is_its_prefix_and_64_hex_digits() {
        let token = format!("lcm_{HEX}");
        assert_eq!(
            parse_token(format!("{token}\n").as_bytes(), "lcm_")
                .unwrap()
                .as_str(),
            token
        );
        assert_eq!(
            parse_token(token.as_bytes(), "lcm_").unwrap().as_str(),
            token
        );
        for bad in [
            String::new(),
            "\n".to_string(),
            format!("het_{HEX}\n"),
            format!("lcm_{}\n", &HEX[..63]),
            format!("lcm_{HEX}0\n"),
            format!("lcm_{}\n", HEX.to_uppercase()),
            format!("lcm_{HEX}\n\n"),
            format!(" lcm_{HEX}\n"),
            format!("lcm_{HEX}\nlcm_{HEX}\n"),
        ] {
            assert!(
                parse_token(bad.as_bytes(), "lcm_").is_err(),
                "accepted {bad:?}"
            );
        }
    }

    #[test]
    fn a_refusal_never_quotes_the_token() {
        let secret = format!("het_{HEX}");
        let why = parse_token(secret.as_bytes(), "lcm_").unwrap_err();
        assert!(!why.contains(HEX));
    }

    #[cfg(unix)]
    mod unix {
        use super::super::*;
        use super::HEX;
        use std::os::unix::fs::PermissionsExt;

        fn write(dir: &Path, name: &str, body: &str, mode: u32) -> std::path::PathBuf {
            let path = dir.join(name);
            std::fs::write(&path, body).unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
            path
        }

        #[test]
        fn only_a_private_regular_file_of_the_owner_is_read() {
            let dir = tempfile::tempdir().unwrap();
            let me = effective_uid();
            let token = format!("lcm_{HEX}\n");
            let good = write(dir.path(), "meter.token", &token, 0o600);
            assert!(read_token(&good, me, "lcm_").is_ok());
            let read_only = write(dir.path(), "ro.token", &token, 0o400);
            assert!(read_token(&read_only, me, "lcm_").is_ok());

            for mode in [0o640, 0o604, 0o660, 0o644] {
                let open = write(dir.path(), &format!("m{mode:o}"), &token, mode);
                let why = read_token(&open, me, "lcm_").unwrap_err();
                assert!(why.contains("too open"), "{why}");
                assert!(!why.contains(HEX));
            }
            // Another owner (root when the tests do not run as root).
            let other = u32::from(me == 0);
            assert!(
                read_token(&good, other, "lcm_")
                    .unwrap_err()
                    .contains("not owned")
            );

            let link = dir.path().join("link.token");
            std::os::unix::fs::symlink(&good, &link).unwrap();
            assert!(read_token(&link, me, "lcm_").is_err());
            assert!(read_token(dir.path(), me, "lcm_").is_err());
            assert!(read_token(&dir.path().join("missing"), me, "lcm_").is_err());
        }

        #[test]
        fn the_config_may_be_world_readable_but_not_writable() {
            let dir = tempfile::tempdir().unwrap();
            let me = effective_uid();
            let readable = write(dir.path(), "computer.json", "{}", 0o644);
            assert!(read_checked(&readable, me, Exposure::Readable, 64).is_ok());
            assert!(read_checked(&readable, me, Exposure::Private, 64).is_err());
            let writable = write(dir.path(), "w.json", "{}", 0o664);
            assert!(read_checked(&writable, me, Exposure::Readable, 64).is_err());
            let big = write(dir.path(), "big.json", &"x".repeat(65), 0o644);
            assert!(read_checked(&big, me, Exposure::Readable, 64).is_err());
        }
    }
}