Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/plugins/trust.rs

Raw
//! Persisted project trust decisions (`SMH-SPEC-PLUG0001`, Project trust).
//!
//! Discovery receives a resolved decision only.
//! This store canonicalizes project paths before recording grants, so aliases
//! cannot receive independent authority.

use super::{Capability, NetScope, canonical_grants, canonical_net_scopes, native_path_identity};
use crate::wasm::SecretGrantConfig;
use smith::error::{ProviderFault, Result, SmithError};
use smith_ai::auth::CredentialKey;
use smith_ai::models::ProviderKind;
use std::io::Read;
use std::path::{Path, PathBuf};

const DECISIONS_FILE: &str = "project-trust.kdl";
const DECISIONS_BYTES_MAX: usize = 1024 * 1024;

/// Project trust decisions rooted at one Smith-owned directory.
pub struct TrustStore {
    root: PathBuf,
}

impl TrustStore {
    /// Create a trust store at an explicit Smith-owned directory.
    #[must_use]
    pub const fn at(root: PathBuf) -> Self {
        Self { root }
    }

    /// Persist exactly these grants for a canonical project path.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the project cannot be canonicalized or the
    /// decision cannot be read or atomically replaced.
    pub fn grant(&self, project: &Path, grants: &[Capability]) -> Result<()> {
        self.grant_with_authority(project, grants, &[], &[])
    }

    /// Persist exactly these grants and network origins for a canonical project path.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the project cannot be canonicalized or the
    /// decision cannot be read or atomically replaced.
    pub fn grant_with_net_scopes(
        &self,
        project: &Path,
        grants: &[Capability],
        net_scopes: &[NetScope],
    ) -> Result<()> {
        self.grant_with_authority(project, grants, net_scopes, &[])
    }

    /// Persist exactly these grants, network origins, and secret authorities.
    ///
    /// # Errors
    ///
    /// Returns when project canonicalization or decision publication fails.
    pub fn grant_with_authority(
        &self,
        project: &Path,
        grants: &[Capability],
        net_scopes: &[NetScope],
        secret_grants: &[SecretGrantConfig],
    ) -> Result<()> {
        let identity = project_identity(project)?;
        let mut decisions = self.read()?;
        let grants = canonical_grants(grants);
        let net_scopes = canonical_net_scopes(net_scopes);
        if let Some(decision) = decisions
            .iter_mut()
            .find(|decision| decision.identity == identity)
        {
            decision.grants = grants;
            decision.net_scopes = net_scopes;
            decision.secret_grants = secret_grants.to_vec();
        } else {
            decisions.push(Decision {
                identity,
                grants,
                net_scopes,
                secret_grants: secret_grants.to_vec(),
            });
        }
        decisions.sort_by(|left, right| left.identity.cmp(&right.identity));
        self.write(&decisions)
    }

    /// Resolve prior grants for one canonical project path.
    ///
    /// `None` means trust remains unresolved and callers must not enumerate
    /// package files.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the project path or decision store is invalid.
    pub fn decision(&self, project: &Path) -> Result<Option<Vec<Capability>>> {
        let identity = project_identity(project)?;
        Ok(self
            .read()?
            .into_iter()
            .find(|decision| decision.identity == identity)
            .map(|decision| decision.grants))
    }

    /// Resolve prior network origins for one canonical project path.
    ///
    /// # Errors
    ///
    /// Returns a plugin fault when the project path or decision store is invalid.
    pub fn net_scopes(&self, project: &Path) -> Result<Option<Vec<NetScope>>> {
        let identity = project_identity(project)?;
        Ok(self
            .read()?
            .into_iter()
            .find(|decision| decision.identity == identity)
            .map(|decision| decision.net_scopes))
    }

    fn path(&self) -> PathBuf {
        self.root.join(DECISIONS_FILE)
    }

    fn read(&self) -> Result<Vec<Decision>> {
        let path = self.path();
        let file = match std::fs::File::open(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(error) => return Err(trust_fault(format!("trust read failed: {error}"))),
        };
        let size = file
            .metadata()
            .map_err(|error| trust_fault(format!("trust metadata failed: {error}")))?
            .len();
        if size > DECISIONS_BYTES_MAX as u64 {
            return Err(trust_fault(format!(
                "trust decisions exceed byte limit of {DECISIONS_BYTES_MAX}"
            )));
        }
        let mut bytes = Vec::new();
        bytes
            .try_reserve_exact(
                usize::try_from(size)
                    .map_err(|_| trust_fault("trust decisions exceed addressable memory"))?,
            )
            .map_err(|_| trust_fault("trust decision allocation failed"))?;
        #[expect(
            clippy::disallowed_methods,
            reason = "Take caps the trust decision read at DECISIONS_BYTES_MAX + 1"
        )]
        file.take((DECISIONS_BYTES_MAX + 1) as u64)
            .read_to_end(&mut bytes)
            .map_err(|error| trust_fault(format!("trust read failed: {error}")))?;
        if bytes.len() > DECISIONS_BYTES_MAX {
            return Err(trust_fault(format!(
                "trust decisions exceed byte limit of {DECISIONS_BYTES_MAX}"
            )));
        }
        let source = std::str::from_utf8(&bytes)
            .map_err(|error| trust_fault(format!("trust decisions are not UTF-8: {error}")))?;
        let document: kdl::KdlDocument = source
            .parse()
            .map_err(|error| trust_fault(format!("invalid trust decision store: {error}")))?;
        document.nodes().iter().map(parse_decision).collect()
    }

    fn write(&self, decisions: &[Decision]) -> Result<()> {
        std::fs::create_dir_all(&self.root)
            .map_err(|error| trust_fault(format!("trust directory creation failed: {error}")))?;
        let path = self.path();
        let temporary = self.root.join("project-trust.kdl.new");
        std::fs::write(&temporary, render(decisions))
            .map_err(|error| trust_fault(format!("trust write failed: {error}")))?;
        std::fs::rename(&temporary, path)
            .map_err(|error| trust_fault(format!("trust publication failed: {error}")))
    }
}

struct Decision {
    identity: String,
    grants: Vec<Capability>,
    net_scopes: Vec<NetScope>,
    secret_grants: Vec<SecretGrantConfig>,
}

fn parse_decision(node: &kdl::KdlNode) -> Result<Decision> {
    if node.name().value() != "decision" || node.entries().len() != 1 {
        return Err(trust_fault("invalid trust decision"));
    }
    let identity = node
        .entry(0)
        .and_then(|entry| entry.value().as_string())
        .filter(|value| !value.is_empty())
        .ok_or_else(|| trust_fault("trust decision requires an identity"))?
        .to_string();
    let (grants, net_scopes, secret_grants) = node.children().map_or_else(
        || Ok((Vec::new(), Vec::new(), Vec::new())),
        |children| {
            let mut grants = Vec::new();
            let mut net_scopes = Vec::new();
            let mut secret_grants = Vec::new();
            for child in children.nodes() {
                match child.name().value() {
                    "grant" => grants.push(parse_grant(child)?),
                    "net-origin" => net_scopes.push(parse_net_scope(child)?),
                    "secret-grant" => secret_grants.push(parse_secret_grant(child)?),
                    _ => return Err(trust_fault("invalid trust decision authority")),
                }
            }
            Ok((grants, net_scopes, secret_grants))
        },
    )?;
    Ok(Decision {
        identity,
        grants: canonical_grants(&grants),
        net_scopes: canonical_net_scopes(&net_scopes),
        secret_grants,
    })
}

fn parse_grant(node: &kdl::KdlNode) -> Result<Capability> {
    let value = node
        .entries()
        .first()
        .and_then(|entry| entry.value().as_string())
        .filter(|_| node.name().value() == "grant" && node.entries().len() == 1)
        .ok_or_else(|| trust_fault("invalid trust grant"))?;
    Capability::parse(value).map_err(|_| trust_fault(format!("unknown trust grant {value}")))
}

fn parse_net_scope(node: &kdl::KdlNode) -> Result<NetScope> {
    let value = node
        .entries()
        .first()
        .and_then(|entry| entry.value().as_string())
        .filter(|_| node.name().value() == "net-origin" && node.entries().len() == 1)
        .ok_or_else(|| trust_fault("invalid trust net origin"))?;
    NetScope::parse(value).map_err(|_| trust_fault("invalid trust net origin"))
}

fn parse_secret_grant(node: &kdl::KdlNode) -> Result<SecretGrantConfig> {
    if node.name().value() != "secret-grant" || node.entries().len() < 4 {
        return Err(trust_fault("invalid trust secret grant"));
    }
    let text = |index| {
        node.entry(index)
            .and_then(|entry| entry.value().as_string())
            .filter(|value| !value.is_empty())
            .ok_or_else(|| trust_fault("invalid trust secret grant"))
    };
    let credential_key = match text(1)? {
        "openai" => CredentialKey::Provider(ProviderKind::OpenAiCompatible),
        "anthropic" => CredentialKey::Provider(ProviderKind::Anthropic),
        "google" => CredentialKey::Provider(ProviderKind::Google),
        "zai" => CredentialKey::Provider(ProviderKind::Zai),
        "zai-coding-plan" => CredentialKey::ZaiCodingPlan,
        _ => return Err(trust_fault("invalid trust secret provider")),
    };
    let scopes = (3..node.entries().len())
        .map(|index| text(index).map(str::to_string))
        .collect::<Result<Vec<_>>>()?;
    SecretGrantConfig::new(
        text(0)?.to_string(),
        NetScope::parse(text(2)?).map_err(|_| trust_fault("invalid trust secret origin"))?,
        scopes,
        credential_key,
    )
}

fn render(decisions: &[Decision]) -> String {
    let mut text = String::new();
    for decision in decisions {
        text.push_str("decision \"");
        text.push_str(&decision.identity);
        text.push_str("\" {\n");
        for grant in &decision.grants {
            text.push_str("  grant \"");
            text.push_str(grant.name());
            text.push_str("\"\n");
        }
        for scope in &decision.net_scopes {
            text.push_str("  net-origin \"");
            text.push_str(scope.as_str());
            text.push_str("\"\n");
        }
        for grant in &decision.secret_grants {
            text.push_str("  secret-grant \"");
            text.push_str(grant.source_id());
            text.push_str("\" \"");
            text.push_str(grant.credential_key().slug());
            text.push_str("\" \"");
            text.push_str(grant.origin().as_str());
            text.push('"');
            for scope in grant.scopes() {
                text.push_str(" \"");
                text.push_str(scope);
                text.push('\"');
            }
            text.push('\n');
        }
        text.push_str("}\n");
    }
    text
}

fn project_identity(project: &Path) -> Result<String> {
    let project = std::fs::canonicalize(project)
        .map_err(|error| trust_fault(format!("project trust path failed: {error}")))?;
    Ok(native_path_identity(&project))
}

fn trust_fault(message: impl Into<String>) -> SmithError {
    SmithError::Provider {
        fault: ProviderFault::Plugin {
            message: message.into(),
        },
    }
}

#[cfg(test)]
mod tests {
    //! Persisted trust canonicalization (`SMH-SPEC-PLUG0001`).

    use super::*;

    #[test]
    fn trust_roundtrip_canonicalizes_unsorted_duplicate_authority() {
        let scratch =
            std::env::temp_dir().join(format!("smith-trust-canonical-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&scratch);
        let project = scratch.join("project");
        let store = TrustStore::at(scratch.join("decisions"));
        std::fs::create_dir_all(&project).unwrap();
        let grants = [
            Capability::Process,
            Capability::NetScope,
            Capability::Process,
        ];
        let scopes = [
            NetScope::parse("https://z.example.test").unwrap(),
            NetScope::parse("https://a.example.test").unwrap(),
            NetScope::parse("https://z.example.test").unwrap(),
        ];

        store
            .grant_with_net_scopes(&project, &grants, &scopes)
            .unwrap();

        assert_eq!(
            store.decision(&project).unwrap().unwrap(),
            [Capability::NetScope, Capability::Process]
        );
        assert_eq!(
            store.net_scopes(&project).unwrap().unwrap(),
            [
                NetScope::parse("https://a.example.test").unwrap(),
                NetScope::parse("https://z.example.test").unwrap(),
            ]
        );
        let persisted = std::fs::read_to_string(store.path()).unwrap();
        assert_eq!(
            persisted
                .lines()
                .filter(|line| line.trim_start().starts_with("grant "))
                .collect::<Vec<_>>(),
            ["  grant \"net-scope\"", "  grant \"process\""]
        );
        assert_eq!(persisted.matches("net-origin ").count(), 2);
        let _ = std::fs::remove_dir_all(&scratch);
    }
}