subc-daemon 0.54.17

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
//! The trusted-build list has no disk-backed or unsigned mode.

use std::{
    collections::HashMap,
    sync::{
        atomic::{AtomicU64, Ordering},
        Mutex,
    },
    time::{Instant, SystemTime},
};
use subc_control::TrustedAppBuild;
use subc_os::config_keychain::TrustedBuildKeychain;
use subc_os::local_peer::SignedAppBundle;

pub(crate) const IDENTIFIER: &str = "dev.cortexkit.alfonso";
const MAX_BUILDS: usize = 64;
const STORE_UNAVAILABLE: &str = "Trusted builds require a signed daemon with access to its macOS keychain group; no file fallback is available.";
const STORE_INVALID: &str = "The trusted-build keychain item is invalid.";
const STORE_FULL: &str =
    "The trusted-build list is full (64 builds); untrust an older build first.";
pub(crate) const MISSING_VERSION: &str = "The app must have a signed CFBundleShortVersionString.";

#[derive(Default, Debug)]
pub(crate) struct TrustedBuilds {
    // Never hold this across a presence prompt. The mutation reloads the
    // authoritative list after approval so unrelated changes are preserved.
    // This serializes read/modify/write for the one provisioned daemon using
    // the item. In-place upgrades exec the replacement in the same process.
    transaction: Mutex<HashMap<String, Instant>>,
    pub(crate) approval: tokio::sync::Mutex<()>,
    pub(crate) scan_slots: std::sync::OnceLock<std::sync::Arc<tokio::sync::Semaphore>>,
    revocations: AtomicU64,
    #[cfg(test)]
    memory: Option<Mutex<Vec<TrustedAppBuild>>>,
    #[cfg(test)]
    pub(crate) fail_reads: std::sync::atomic::AtomicBool,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct ConnectionOpened {
    instant: Instant,
    wall_ms: u64,
}

impl ConnectionOpened {
    pub(crate) fn now() -> Self {
        Self {
            instant: Instant::now(),
            wall_ms: crate::stderr_tail::unix_ms(SystemTime::now()),
        }
    }
}

impl TrustedBuilds {
    #[cfg(test)]
    pub(crate) fn memory_for_tests() -> Self {
        Self {
            memory: Some(Mutex::default()),
            ..Default::default()
        }
    }

    pub(crate) fn revocation_revision(&self) -> u64 {
        self.revocations.load(Ordering::Acquire)
    }

    pub(crate) fn list(&self) -> Result<Vec<TrustedAppBuild>, &'static str> {
        let _guard = self.transaction.lock().unwrap_or_else(|p| p.into_inner());
        self.load()
    }

    pub(crate) fn was_trusted_at(
        &self,
        cdhash: &str,
        opened: ConnectionOpened,
    ) -> Result<bool, &'static str> {
        let approvals = self.transaction.lock().unwrap_or_else(|p| p.into_inner());
        // Native verification may be deferred until the first use of a
        // connection. A later approval cannot upgrade that open socket. Use
        // monotonic time in this process to distinguish opens in the same ms.
        let entries = self.load()?;
        Ok(approvals
            .get(cdhash)
            .is_none_or(|approved| *approved <= opened.instant)
            && entries
                .iter()
                .any(|entry| entry.cdhash == cdhash && entry.added_ms <= opened.wall_ms))
    }

    pub(crate) fn add(&self, mut entry: TrustedAppBuild) -> Result<TrustedAppBuild, &'static str> {
        let mut approvals = self.transaction.lock().unwrap_or_else(|p| p.into_inner());
        let mut entries = self.load()?;
        if let Some(existing) = entries.iter().find(|e| e.cdhash == entry.cdhash) {
            return Ok(existing.clone());
        }
        check_capacity(&entries)?;
        entry.added_ms = crate::stderr_tail::unix_ms(SystemTime::now());
        entries.push(entry.clone());
        self.save(entries)?;
        approvals.insert(entry.cdhash.clone(), Instant::now());
        Ok(entry)
    }

    pub(crate) fn remove(&self, cdhash: &str) -> Result<bool, &'static str> {
        let mut approvals = self.transaction.lock().unwrap_or_else(|p| p.into_inner());
        let mut entries = self.load()?;
        let before = entries.len();
        entries.retain(|e| e.cdhash != cdhash);
        if entries.len() == before {
            return Ok(false);
        }
        self.save(entries)?;
        approvals.remove(cdhash);
        self.revocations.fetch_add(1, Ordering::AcqRel);
        Ok(true)
    }

    fn load(&self) -> Result<Vec<TrustedAppBuild>, &'static str> {
        #[cfg(test)]
        if self.fail_reads.load(Ordering::Relaxed) {
            return Err(STORE_UNAVAILABLE);
        }
        #[cfg(test)]
        if let Some(list) = &self.memory {
            return Ok(list.lock().unwrap_or_else(|p| p.into_inner()).clone());
        }
        let store = TrustedBuildKeychain::open().map_err(|_| STORE_UNAVAILABLE)?;
        let Some(bytes) = store.load().map_err(|error| {
            if matches!(error, subc_os::config_keychain::KeychainError::InvalidData) {
                STORE_INVALID
            } else {
                STORE_UNAVAILABLE
            }
        })?
        else {
            return Ok(Vec::new());
        };
        let entries: Vec<TrustedAppBuild> =
            serde_json::from_slice(&bytes).map_err(|_| STORE_INVALID)?;
        if entries.len() > MAX_BUILDS
            || entries.iter().any(|e| {
                e.identifier != IDENTIFIER
                    || checked_hash(&e.cdhash).as_deref() != Some(e.cdhash.as_str())
            })
        {
            return Err(STORE_INVALID);
        }
        Ok(entries)
    }

    fn save(&self, entries: Vec<TrustedAppBuild>) -> Result<(), &'static str> {
        #[cfg(test)]
        if let Some(list) = &self.memory {
            *list.lock().unwrap_or_else(|p| p.into_inner()) = entries;
            return Ok(());
        }
        let bytes = serde_json::to_vec(&entries).map_err(|_| STORE_INVALID)?;
        TrustedBuildKeychain::open()
            .and_then(|store| store.save(&bytes))
            .map_err(|_| STORE_UNAVAILABLE)
    }
}

pub(crate) fn check_capacity(entries: &[TrustedAppBuild]) -> Result<(), &'static str> {
    if entries.len() >= MAX_BUILDS {
        Err(STORE_FULL)
    } else {
        Ok(())
    }
}

pub(crate) fn format_hash(hash: [u8; 20]) -> String {
    use std::fmt::Write;
    let mut text = String::with_capacity(40);
    for byte in hash {
        write!(text, "{byte:02x}").expect("writing to String cannot fail");
    }
    text
}

pub(crate) fn checked_hash(text: &str) -> Option<String> {
    (text.len() == 40 && text.bytes().all(|b| b.is_ascii_hexdigit()))
        .then(|| text.to_ascii_lowercase())
}

pub(crate) fn version(code: &SignedAppBundle) -> Result<&str, &'static str> {
    code.short_version
        .as_deref()
        .filter(|text| {
            !text.is_empty()
                && text.len() <= 64
                && text
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b".-+_".contains(&b))
        })
        .ok_or(MISSING_VERSION)
}

pub(crate) fn build_time(code: &SignedAppBundle) -> Option<&str> {
    let time = code.build_time.as_deref()?;
    // Limit signed display metadata to the UTC form used in the prompt.
    let time_body = time.strip_suffix('Z')?;
    let (seconds, fraction) = time_body
        .split_once('.')
        .map_or((time_body, None), |(a, b)| (a, Some(b)));
    let form = b"####-##-##T##:##:##";
    (seconds.len() == form.len()
        && seconds.bytes().zip(form).all(|(b, &f)| {
            if f == b'#' {
                b.is_ascii_digit()
            } else {
                b == f
            }
        })
        && fraction.is_none_or(|part| {
            !part.is_empty() && part.len() <= 9 && part.bytes().all(|b| b.is_ascii_digit())
        }))
    .then_some(time)
}