Skip to main content

rpi_cli/host/
profile_set.rs

1//! Frozen trusted native profiles. Public refs contain no configuration or
2//! secret digest. This is not an IPC parser, grant issued by a client, filesystem
3//! sandbox, catalog mutation or execution coordinator.
4use super::{
5    ordinary::{BackendError, BackendResult, OrdinaryBinding, OrdinaryLimits},
6    AgentId, AgentMode, AgentSpec, ExecutionMode, HostStartupAgent, ProfileRef, ProfileVersion,
7};
8use std::collections::{BTreeMap, BTreeSet};
9
10/// Trusted inputs are still bounded, independently of the IPC frame budget.
11pub const MAX_TRUSTED_PROFILES: usize = 1024;
12
13struct FrozenProfile {
14    reference: ProfileRef,
15    agent: HostStartupAgent,
16}
17
18/// Owns private inputs without Debug/Serialize, replacement or insertion APIs.
19/// Construct only from Host-owned inputs, never a peer's profile JSON. Versions
20/// are random nonces, not hashes that could become a credential guessing oracle.
21pub struct TrustedProfileSet {
22    agents: BTreeMap<AgentId, FrozenProfile>,
23}
24
25/// A fresh, owned binding snapshot. Preparing creates no Session, acquires no
26/// Session writer and registers no Agent. Saved resource facts still have to be
27/// validated by strict restore before writer acquisition/repair.
28pub struct PreparedProfile {
29    pub reference: ProfileRef,
30    pub spec: AgentSpec,
31    pub limits: OrdinaryLimits,
32    pub binding: OrdinaryBinding,
33}
34
35impl TrustedProfileSet {
36    /// Validate all trusted inputs before publishing any refs. Reads path
37    /// metadata and resolves closed Provider configuration, but never runs an
38    /// Agent, probes its HTTP endpoint, writes files or touches a catalog.
39    /// Path checks reject aliases visible now, not external filesystem changes.
40    pub async fn freeze(agents: Vec<HostStartupAgent>) -> BackendResult<Self> {
41        if agents.len() > MAX_TRUSTED_PROFILES {
42            return Err(BackendError::Binding("too many trusted profiles"));
43        }
44        let mut frozen = BTreeMap::new();
45        let mut sessions = BTreeSet::new();
46        let mut paths = BTreeSet::new();
47        #[cfg(unix)]
48        let mut inodes = BTreeSet::new();
49        for agent in agents {
50            agent
51                .spec
52                .validate()
53                .map_err(|_| BackendError::Binding("invalid trusted Agent metadata"))?;
54            if agent.limits.max_input_bytes == 0 {
55                return Err(BackendError::Binding("input byte budget must be nonzero"));
56            }
57            if agent.spec.mode != AgentMode::Persistent
58                || agent.spec.execution != ExecutionMode::InProcess
59            {
60                return Err(BackendError::Binding(
61                    "trusted profile is not native ordinary",
62                ));
63            }
64            if frozen.contains_key(&agent.spec.id) {
65                return Err(BackendError::Binding("duplicate trusted Agent id"));
66            }
67            let session = agent
68                .spec
69                .session
70                .as_ref()
71                .ok_or(BackendError::Binding("trusted profile requires a Session"))?;
72            if !sessions.insert(session.id.clone()) {
73                return Err(BackendError::Binding("duplicate trusted Session id"));
74            }
75            let parent = session.path.parent().ok_or(BackendError::Binding(
76                "trusted Session parent is unavailable",
77            ))?;
78            let leaf = session
79                .path
80                .file_name()
81                .ok_or(BackendError::Binding("trusted Session filename is invalid"))?;
82            let parent = tokio::fs::canonicalize(parent)
83                .await
84                .map_err(|_| BackendError::Binding("trusted Session parent is unavailable"))?;
85            if !tokio::fs::metadata(&parent)
86                .await
87                .map_err(|_| BackendError::Binding("trusted Session parent is unavailable"))?
88                .is_dir()
89            {
90                return Err(BackendError::Binding(
91                    "trusted Session parent is not a directory",
92                ));
93            }
94            let path = parent.join(leaf);
95            if !paths.insert(path.clone()) {
96                return Err(BackendError::Binding("duplicate trusted Session path"));
97            }
98            match tokio::fs::symlink_metadata(&path).await {
99                Ok(metadata) => {
100                    // In particular reject final symlinks, including broken
101                    // links; only the existing strict restore may accept facts.
102                    if !metadata.is_file() {
103                        return Err(BackendError::Binding(
104                            "trusted Session is not a regular file",
105                        ));
106                    }
107                    #[cfg(unix)]
108                    {
109                        use std::os::unix::fs::MetadataExt;
110                        if !inodes.insert((metadata.dev(), metadata.ino())) {
111                            return Err(BackendError::Binding("aliased trusted Session file"));
112                        }
113                    }
114                }
115                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
116                Err(_) => return Err(BackendError::Binding("trusted Session is unavailable")),
117            }
118            // No binding/environment is cached: cleanup ownership must always
119            // belong to the actual load, never this immutable configuration set.
120            drop(agent.profile.bind(agent.spec.clone()).await?);
121            let reference = ProfileRef {
122                agent_id: agent.spec.id,
123                version: ProfileVersion::new(),
124            };
125            frozen.insert(agent.spec.id, FrozenProfile { reference, agent });
126        }
127        Ok(Self { agents: frozen })
128    }
129
130    pub fn references(&self) -> impl ExactSizeIterator<Item = ProfileRef> + '_ {
131        self.agents.values().map(|entry| entry.reference)
132    }
133
134    /// Look up the entire opaque ref before binding. Never reinterpret an old
135    /// version as the current inputs or resolve an arbitrary peer-supplied spec.
136    pub async fn prepare(&self, reference: ProfileRef) -> BackendResult<PreparedProfile> {
137        let entry = self
138            .agents
139            .get(&reference.agent_id)
140            .filter(|entry| entry.reference == reference)
141            .ok_or(BackendError::Binding("profile reference is not permitted"))?;
142        let binding = entry.agent.profile.bind(entry.agent.spec.clone()).await?;
143        Ok(PreparedProfile {
144            reference,
145            spec: entry.agent.spec.clone(),
146            limits: entry.agent.limits,
147            binding,
148        })
149    }
150}
151
152#[cfg(all(test, unix))]
153#[path = "profile_set_tests.rs"]
154mod tests;