troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
use std::{io, path::Path};

use crate::{error::CliError, platform};

const TOKEN_BYTES: usize = 32;
const TOKEN_FILE: &str = "serve.token";
const HEX: &[u8; 16] = b"0123456789abcdef";

pub(super) struct SessionToken(String);

impl SessionToken {
    pub(super) fn generate() -> Result<Self, CliError> {
        let mut bytes = [0; TOKEN_BYTES];
        getrandom::fill(&mut bytes).map_err(|error| {
            CliError::Serve("generate the session token", io::Error::other(error))
        })?;
        let mut encoded = String::with_capacity(2 * TOKEN_BYTES);
        for byte in bytes {
            encoded.push(char::from(HEX[usize::from(byte >> 4)]));
            encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
        }
        Ok(Self(encoded))
    }

    pub(super) fn matches(&self, candidate: &[u8]) -> bool {
        // The required length is public. For that length, visit every byte
        // and prevent the optimizer from replacing the loop with an early exit.
        if candidate.len() != self.0.len() {
            return false;
        }
        let mut difference = 0;
        for (&expected, &actual) in self.0.as_bytes().iter().zip(candidate) {
            difference |= std::hint::black_box(expected ^ actual);
        }
        difference == 0
    }

    pub(super) fn as_str(&self) -> &str {
        &self.0
    }

    pub(super) fn redact<'a>(&self, text: &'a str) -> std::borrow::Cow<'a, str> {
        if text.contains(&self.0) {
            text.replace(&self.0, "[redacted]").into()
        } else {
            text.into()
        }
    }

    pub(super) fn write(&self, dir: &Path) -> io::Result<()> {
        platform::write_private_state_file(dir, TOKEN_FILE, self.0.as_bytes())
    }
}

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

    #[test]
    fn token_comparison_matches_every_byte() {
        let expected = SessionToken("ab".repeat(TOKEN_BYTES));
        let mut candidate = expected.0.clone().into_bytes();
        assert!(expected.matches(&candidate));
        for index in 0..candidate.len() {
            candidate[index] ^= 1;
            assert!(!expected.matches(&candidate));
            candidate[index] ^= 1;
        }
        assert!(!expected.matches(&[]));
        assert!(!expected.matches(&candidate[1..]));
        candidate.push(b'a');
        assert!(!expected.matches(&candidate));
    }

    #[test]
    fn log_redaction_covers_token_in_request_text() {
        let token = SessionToken("ab".repeat(TOKEN_BYTES));
        assert_eq!(token.redact("/api/v1/ports"), "/api/v1/ports");
        assert_eq!(
            token.redact(&format!("/api/{}", token.0)),
            "/api/[redacted]"
        );
    }

    #[cfg(unix)]
    #[test]
    fn token_file_is_private_and_atomically_replaced() {
        use std::{fs, io::Read, os::unix::fs::PermissionsExt};

        let fixture = crate::test_support::TempDir::new();
        let state = fixture.path().join("state/troll");
        let path = state.join(TOKEN_FILE);
        let before = SessionToken("ab".repeat(TOKEN_BYTES));
        let after = SessionToken("cd".repeat(TOKEN_BYTES));
        before.write(&state).unwrap();
        assert_eq!(
            fs::metadata(&state).unwrap().permissions().mode() & 0o777,
            0o700
        );

        let mut previous = fs::File::open(&path).unwrap();
        assert_eq!(
            previous.metadata().unwrap().permissions().mode() & 0o777,
            0o600
        );

        after.write(&state).unwrap();
        let mut retired = String::new();
        previous.read_to_string(&mut retired).unwrap();
        assert_eq!(retired, before.0);
        assert_eq!(fs::read_to_string(&path).unwrap(), after.0);
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert_eq!(fs::read_dir(&state).unwrap().count(), 1);
    }
}