subc-daemon 0.56.20

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 {
    // Lock only to read or mutate the current list, never across a presence
    // prompt. This daemon is the only writer of the keychain item.
    transaction: Mutex<TrustState>,
    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(Default, Debug)]
struct TrustState {
    entries: Option<Vec<TrustedAppBuild>>,
    approvals: HashMap<String, Instant>,
}

#[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 mut state = self.transaction.lock().unwrap_or_else(|p| p.into_inner());
        Ok(self.entries(&mut state)?.to_vec())
    }

    pub(crate) fn was_trusted_at(
        &self,
        cdhash: &str,
        opened: ConnectionOpened,
    ) -> Result<bool, &'static str> {
        let mut state = 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 approved_before_open = state
            .approvals
            .get(cdhash)
            .is_none_or(|approved| *approved <= opened.instant);
        let entries = self.entries(&mut state)?;
        Ok(approved_before_open
            && 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 state = self.transaction.lock().unwrap_or_else(|p| p.into_inner());
        let entries = self.entries(&mut state)?;
        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());
        let mut entries = entries.to_vec();
        entries.push(entry.clone());
        self.save(&entries)?;
        state.entries = Some(entries);
        state.approvals.insert(entry.cdhash.clone(), Instant::now());
        Ok(entry)
    }

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

    fn entries<'a>(
        &self,
        state: &'a mut TrustState,
    ) -> Result<&'a [TrustedAppBuild], &'static str> {
        if state.entries.is_none() {
            state.entries = Some(self.load()?);
        }
        Ok(state.entries.as_deref().expect("trusted builds loaded"))
    }

    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: &[TrustedAppBuild]) -> Result<(), &'static str> {
        #[cfg(test)]
        if let Some(list) = &self.memory {
            *list.lock().unwrap_or_else(|p| p.into_inner()) = entries.to_vec();
            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)
}

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

    #[test]
    fn trusted_build_cache_retries_failed_load_and_tracks_writes() {
        let store = TrustedBuilds::memory_for_tests();
        let entry = |digit| {
            TrustedAppBuild::new(
                IDENTIFIER.into(),
                format!("{digit:040x}"),
                "1.0.0".into(),
                None,
                0,
            )
        };
        let initial = entry(1);
        *store.memory.as_ref().unwrap().lock().unwrap() = vec![initial.clone()];

        store.fail_reads.store(true, Ordering::Relaxed);
        assert_eq!(
            store.was_trusted_at(&initial.cdhash, ConnectionOpened::now()),
            Err(STORE_UNAVAILABLE)
        );
        store.fail_reads.store(false, Ordering::Relaxed);
        assert_eq!(
            store.was_trusted_at(&initial.cdhash, ConnectionOpened::now()),
            Ok(true)
        );

        // Once the first successful load fills the cache, no operation reads
        // the backend again, even if it is temporarily unavailable for reads.
        store.fail_reads.store(true, Ordering::Relaxed);
        assert_eq!(store.list().unwrap(), vec![initial.clone()]);
        let added = store.add(entry(2)).unwrap();
        assert_eq!(
            store.was_trusted_at(&added.cdhash, ConnectionOpened::now()),
            Ok(true)
        );
        assert!(store.remove(&initial.cdhash).unwrap());
        assert_eq!(
            store.was_trusted_at(&initial.cdhash, ConnectionOpened::now()),
            Ok(false)
        );
        assert_eq!(store.list().unwrap(), vec![added]);
    }
}