subc-daemon 0.54.25

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
//! Owner-local control operations for the macOS trusted-build list.

use super::*;
use crate::operator_apps::dev_builds::{self, IDENTIFIER};
use crate::operator_confirm::DeclineKey;
use subc_control::{
    AppTrustReply, AppTrustRequest, AppTrustedReply, AppTrustedRequest, AppUntrustReply,
    AppUntrustRequest, TrustedAppBuild,
};
use subc_os::local_peer::{check_dev_app_bundle, AppBundleError};

const DENIED: &str = "Only an owner-local connection can manage trusted app builds.";

#[derive(Debug)]
struct Refusal {
    code: &'static str,
    message: String,
}

impl Refusal {
    fn new(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }

    fn store(message: &'static str) -> Self {
        Self::new("app_trust_store_unavailable", message)
    }
}

impl ControlHandler {
    pub(super) async fn handle_app_trust_ops(
        &self,
        ctx: &RouteCtx,
        frame: Frame,
        op: &str,
    ) -> Result<Vec<Frame>, RouterError> {
        if !self.app_trust_owner(ctx.connection_id) {
            return Ok(vec![control_error_frame(
                &frame,
                "caller_not_authorized",
                DENIED,
            )?]);
        }
        if !self.operator_app_policy.macos_enabled {
            return Ok(vec![control_error_frame(
                &frame,
                "app_trust_disabled",
                "Operator apps are disabled on this daemon.",
            )?]);
        }
        let store = self.operator_app_policy.trusted_builds.clone();
        let reply = match op {
            ops::APP_TRUST => match decode::<AppTrustRequest>(&frame, op) {
                Ok(request) => return self.handle_app_trust(ctx, frame, request).await,
                Err(error) => refusal(&frame, error),
            },
            ops::APP_TRUSTED => match decode::<AppTrustedRequest>(&frame, op) {
                Ok(_) => reply(
                    &frame,
                    ops::APP_TRUSTED,
                    keychain_work(move || {
                        store
                            .list()
                            .map(AppTrustedReply::new)
                            .map_err(Refusal::store)
                    })
                    .await,
                ),
                Err(error) => refusal(&frame, error),
            },
            ops::APP_UNTRUST => match decode::<AppUntrustRequest>(&frame, op).and_then(|request| {
                dev_builds::checked_hash(&request.cdhash).ok_or_else(|| {
                    Refusal::new(
                        "invalid_control_body",
                        "cdhash must contain exactly 40 hexadecimal characters.",
                    )
                })
            }) {
                Ok(cdhash) => {
                    let handler = self.clone();
                    reply(
                        &frame,
                        ops::APP_UNTRUST,
                        keychain_work(move || {
                            let removed = store.remove(&cdhash).map_err(Refusal::store)?;
                            if removed {
                                handler.close_revoked_app_connections(&cdhash);
                            }
                            Ok(AppUntrustReply::new(removed))
                        })
                        .await,
                    )
                }
                Err(error) => refusal(&frame, error),
            },
            _ => unreachable!("the caller only dispatches trusted-build operations"),
        }?;
        Ok(vec![reply])
    }

    fn app_trust_owner(&self, connection: ConnectionId) -> bool {
        let local = self
            .local_connections
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .contains(&connection);
        local && self.config_owner_connection(connection)
    }

    async fn handle_app_trust(
        &self,
        ctx: &RouteCtx,
        frame: Frame,
        request: AppTrustRequest,
    ) -> Result<Vec<Frame>, RouterError> {
        let store = self.operator_app_policy.trusted_builds.clone();
        let Ok(_approval) = store.approval.try_lock() else {
            return Ok(vec![control_error_frame(
                &frame,
                "app_trust_busy",
                "Another build is being reviewed; try again after that approval ends.",
            )?]);
        };
        let read_store = store.clone();
        let requested_path = request.path.clone();
        let checked = scan_bundle(&store, move || {
            let code = check_dev_app_bundle(std::path::Path::new(&request.path), IDENTIFIER)
                .map_err(|error| {
                    let message = if error == AppBundleError::WrongIdentifier {
                        format!("The signing identifier must be {IDENTIFIER}.")
                    } else {
                        error.message()
                    };
                    Refusal::new("app_build_ineligible", message)
                })?;
            let version = dev_builds::version(&code)
                .map_err(|message| Refusal::new("app_build_ineligible", message))?;
            let cdhash = dev_builds::format_hash(code.cdhash);
            let entries = read_store.list().map_err(Refusal::store)?;
            if let Some(entry) = entries.iter().find(|entry| entry.cdhash == cdhash) {
                return Ok((entry.clone(), true));
            }
            dev_builds::check_capacity(&entries).map_err(Refusal::store)?;
            // Validate the candidate here, but commit the cdhash, never the
            // path. Swapping the bundle during the prompt grants nothing to
            // the replacement.
            let entry = TrustedAppBuild::new(
                IDENTIFIER.into(),
                cdhash,
                version.into(),
                dev_builds::build_time(&code).map(str::to_owned),
                0,
            );
            Ok((entry, false))
        })
        .await;
        let (entry, known) = match checked {
            Ok(value) => value,
            Err(error) => return Ok(vec![refusal(&frame, error)?]),
        };
        if known {
            return Ok(vec![reply(
                &frame,
                ops::APP_TRUST,
                Ok(AppTrustReply::new(entry)),
            )?]);
        }
        let capture = self
            .captured_peers
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .get(&ctx.connection_id)
            .cloned();
        let caller = CallerIdentity::from_lookup_result(match capture {
            Some(capture) => crate::peer_identity_lane::PeerIdentityLane::native()
                .run(move || capture.local_caller())
                .await
                .flatten(),
            None => None,
        });
        let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
        let prompt = trust_prompt(
            &entry,
            std::path::Path::new(&requested_path),
            &caller,
            home.as_deref(),
        );
        let key = DeclineKey::for_caller(&caller, ctx.connection_id);
        let outcome = self
            .forwarding
            .operator_confirms()
            .approve_app_trust(ctx, &frame, prompt, caller.description(), key)
            .await;
        if outcome.code != "confirmed" {
            return Ok(vec![outcome.frame(&frame)]);
        }
        if !self.app_trust_owner(ctx.connection_id) {
            return Ok(vec![control_error_frame(
                &frame,
                "caller_not_authorized",
                DENIED,
            )?]);
        }
        let commit_store = store.clone();
        let result = keychain_work(move || {
            commit_store
                .add(entry)
                .map(AppTrustReply::new)
                .map_err(Refusal::store)
        })
        .await;
        Ok(vec![reply(&frame, ops::APP_TRUST, result)?])
    }
}

fn trust_prompt(
    entry: &TrustedAppBuild,
    bundle: &std::path::Path,
    caller: &CallerIdentity,
    home: Option<&std::path::Path>,
) -> String {
    let requester = caller.executable().map_or_else(
        || "Unknown local program".into(),
        |path| {
            let name = path
                .file_name()
                .map(|name| prompt_text(&name.to_string_lossy()))
                .unwrap_or_else(|| "Unknown executable".into());
            format!("{name} ({})", prompt_path(path, home))
        },
    );
    format!("trust an Alfonso Desktop development build.\nApp: {}\nRequested by: {requester}\nVersion: {}\nBuild time: {}\nCode hash: {}\nOnly approve a build you just built or installed.",
        prompt_path(bundle, home), entry.version, entry.build_time.as_deref().unwrap_or("unknown"), &entry.cdhash[..16])
}

fn prompt_path(path: &std::path::Path, home: Option<&std::path::Path>) -> String {
    let shown = home
        .filter(|home| home.is_absolute())
        .and_then(|home| path.strip_prefix(home).ok())
        .map_or_else(
            || path.to_path_buf(),
            |relative| std::path::Path::new("~").join(relative),
        );
    prompt_text(&shown.to_string_lossy())
}

fn prompt_text(text: &str) -> String {
    // Render line breaks and invisible formatting as escapes rather than
    // allowing a path component to impersonate the fields below it.
    let printable = text.escape_debug().to_string();
    let len = printable.chars().count();
    if len <= 160 {
        return printable;
    }
    let start: String = printable.chars().take(36).collect();
    let end: String = printable.chars().skip(len - 120).collect();
    format!("{start}…{end}")
}

fn decode<T: serde::de::DeserializeOwned>(frame: &Frame, op: &str) -> Result<T, Refusal> {
    serde_json::from_slice(&frame.body)
        .map_err(|_| Refusal::new("invalid_control_body", format!("malformed {op} body")))
}

fn reply<T: serde::Serialize>(
    frame: &Frame,
    op: &'static str,
    result: Result<T, Refusal>,
) -> Result<Frame, RouterError> {
    match result {
        Ok(body) => control_response_body_frame(frame, &body, op),
        Err(error) => refusal(frame, error),
    }
}

fn refusal(frame: &Frame, error: Refusal) -> Result<Frame, RouterError> {
    control_error_frame(frame, error.code, error.message)
}

fn scan_slots(store: &dev_builds::TrustedBuilds) -> &Arc<tokio::sync::Semaphore> {
    store
        .scan_slots
        .get_or_init(|| Arc::new(tokio::sync::Semaphore::new(4)))
}

async fn scan_bundle<T: Send + 'static>(
    store: &dev_builds::TrustedBuilds,
    work: impl FnOnce() -> Result<T, Refusal> + Send + 'static,
) -> Result<T, Refusal> {
    // Bundle scans are blocking. Bound them separately from peer recognition
    // so concurrent trust requests cannot occupy the accept-time workers.
    let permit = scan_slots(store).clone().try_acquire_owned().map_err(|_| {
        Refusal::new(
            "app_trust_busy",
            "Too many trusted-build operations are running; try again.",
        )
    })?;
    keychain_work(move || {
        let _permit = permit;
        work()
    })
    .await
}

async fn keychain_work<T: Send + 'static>(
    work: impl FnOnce() -> Result<T, Refusal> + Send + 'static,
) -> Result<T, Refusal> {
    tokio::task::spawn_blocking(work).await.map_err(|_| {
        Refusal::new(
            "app_trust_store_unavailable",
            "The trusted-build operation could not finish.",
        )
    })?
}

#[cfg(test)]
#[path = "trust_ops/tests.rs"]
mod tests;