Skip to main content

rpi_cli/host/
extension_artifacts.rs

1//! Read-only DLL snapshots and explicit-root, per-incarnation private staging.
2//! Neither a snapshot digest nor a staged file grants native code authority.
3use super::{
4    ordinary::{BackendError, BackendResult},
5    AgentId,
6};
7use sha2::{Digest, Sha256};
8use std::{
9    collections::BTreeSet,
10    fs::{self, OpenOptions},
11    io::{Read, Write},
12    os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
13    path::{Path, PathBuf},
14    sync::Arc,
15};
16
17pub const MAX_NATIVE_EXTENSION_ARTIFACTS: usize = 8;
18pub const MAX_NATIVE_EXTENSION_BYTES: u64 = 64 * 1024 * 1024;
19pub const MAX_NATIVE_EXTENSION_TOTAL_BYTES: usize = 128 * 1024 * 1024;
20
21struct Artifact {
22    source: PathBuf,
23    bytes: Vec<u8>,
24    sha256: String,
25}
26
27/// Pure reads only: no dlopen, registration, worker, staging or discovery.
28/// Bytes, order and canonical source provenance are immutable after freeze.
29/// Approvals must independently match this provenance/digest before loading.
30pub struct NativeExtensionArtifacts {
31    artifacts: Vec<Artifact>,
32    identity: String,
33}
34impl std::fmt::Debug for NativeExtensionArtifacts {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.write_str("NativeExtensionArtifacts { .. }")
37    }
38}
39impl NativeExtensionArtifacts {
40    pub fn freeze(files: &[PathBuf]) -> BackendResult<Self> {
41        Self::freeze_bounded(
42            files,
43            MAX_NATIVE_EXTENSION_BYTES,
44            MAX_NATIVE_EXTENSION_TOTAL_BYTES,
45        )
46    }
47    fn freeze_bounded(files: &[PathBuf], max_file: u64, max_total: usize) -> BackendResult<Self> {
48        if files.len() > MAX_NATIVE_EXTENSION_ARTIFACTS {
49            return Err(BackendError::Binding("too many explicit DLL artifacts"));
50        }
51        let mut paths = BTreeSet::new();
52        let mut identities = BTreeSet::new();
53        let mut opened = Vec::with_capacity(files.len());
54        // Validate the entire bounded set first; never silently skip a file.
55        for path in files {
56            if !path.is_absolute() || !fs::metadata(path)?.is_file() {
57                return Err(BackendError::Binding(
58                    "DLL artifact must be an absolute regular file",
59                ));
60            }
61            let source = fs::canonicalize(path)?;
62            if source.to_str().is_none() || !paths.insert(source.clone()) {
63                return Err(BackendError::Binding("duplicate or non-UTF8 DLL artifact"));
64            }
65            // A replacement FIFO cannot block freeze, and a final symlink
66            // replacement cannot redirect this canonical file's open.
67            let file = OpenOptions::new()
68                .read(true)
69                .custom_flags(nix::libc::O_NOFOLLOW | nix::libc::O_NONBLOCK)
70                .open(&source)?;
71            let metadata = file.metadata()?;
72            if !metadata.is_file()
73                || metadata.len() == 0
74                || metadata.len() > max_file
75                || !identities.insert((metadata.dev(), metadata.ino()))
76            {
77                return Err(BackendError::Binding(
78                    "invalid, oversized or aliased DLL artifact",
79                ));
80            }
81            opened.push((source, file));
82        }
83        let mut total = 0usize;
84        let mut artifacts = Vec::with_capacity(opened.len());
85        for (source, file) in opened {
86            let remaining = max_total - total;
87            let limit = max_file.min(remaining as u64);
88            let mut bytes = Vec::new();
89            file.take(limit + 1).read_to_end(&mut bytes)?;
90            if bytes.is_empty() || bytes.len() as u64 > limit {
91                return Err(BackendError::Binding("DLL artifact byte budget exceeded"));
92            }
93            total += bytes.len();
94            let sha256 = format!("{:x}", Sha256::digest(&bytes));
95            artifacts.push(Artifact {
96                source,
97                bytes,
98                sha256,
99            });
100        }
101        let provenance: Vec<_> = artifacts.iter().map(|artifact|
102            serde_json::json!({"path":artifact.source,"sha256":artifact.sha256,"bytes":artifact.bytes.len()})
103        ).collect();
104        let identity = format!(
105            "extensions-v1:{:x}",
106            Sha256::digest(
107                serde_json::to_vec(&provenance)
108                    .map_err(|_| BackendError::Binding("invalid DLL artifact identity"))?
109            )
110        );
111        Ok(Self {
112            artifacts,
113            identity,
114        })
115    }
116    pub fn identity(&self) -> &str {
117        &self.identity
118    }
119    pub fn provenance(&self) -> Vec<(PathBuf, String)> {
120        self.artifacts
121            .iter()
122            .map(|artifact| (artifact.source.clone(), artifact.sha256.clone()))
123            .collect()
124    }
125    /// Owned assembly only. Never uses ambient TMPDIR or a shared module path.
126    /// The existing root must be explicit, private and owned by this uid. Each
127    /// invocation (including the same Agent after reload) creates new inodes.
128    /// Move the returned Arc into the SDK host_guard, not a Harness hook: the
129    /// directory then survives late cleanup and remains retained on SDK failure.
130    pub fn stage(&self, root: &Path, agent: AgentId) -> BackendResult<Arc<NativeStagedExtensions>> {
131        if !root.is_absolute() {
132            return Err(BackendError::Binding("DLL staging root must be absolute"));
133        }
134        // Strip lexical trailing separators/dots before lstat: on Unix,
135        // lstat("symlink/") otherwise follows the final symlink as a directory.
136        let root: PathBuf = root.components().collect();
137        let metadata = fs::symlink_metadata(&root)?;
138        if !metadata.is_dir()
139            || metadata.uid() != nix::unistd::geteuid().as_raw()
140            || metadata.mode() & 0o077 != 0
141        {
142            return Err(BackendError::Binding(
143                "DLL staging root must be a private owned directory",
144            ));
145        }
146        let root = fs::canonicalize(&root)?;
147        let directory = tempfile::Builder::new()
148            .prefix(&format!("rpi-host-{agent}-"))
149            .permissions(fs::Permissions::from_mode(0o700))
150            .tempdir_in(root)?;
151        let mut paths = Vec::with_capacity(self.artifacts.len());
152        for (index, artifact) in self.artifacts.iter().enumerate() {
153            let path = directory.path().join(format!(
154                "artifact-{index}.{}",
155                std::env::consts::DLL_EXTENSION
156            ));
157            let mut file = OpenOptions::new()
158                .write(true)
159                .create_new(true)
160                .mode(0o400)
161                .open(&path)?;
162            file.write_all(&artifact.bytes)?;
163            file.sync_all()?;
164            drop(file);
165            paths.push(path);
166        }
167        // Not a persistent manifest or a crash-recovery acknowledgement. Only
168        // these exact complete files can now be passed to the owned loader.
169        Ok(Arc::new(NativeStagedExtensions {
170            paths,
171            _directory: directory,
172        }))
173    }
174}
175
176/// Only owns its newly created staging directory, never source/user data or the
177/// Host owner itself. SDK guard retention cannot create an owner/session cycle.
178pub struct NativeStagedExtensions {
179    paths: Vec<PathBuf>,
180    _directory: tempfile::TempDir,
181}
182impl NativeStagedExtensions {
183    pub fn paths(&self) -> &[PathBuf] {
184        &self.paths
185    }
186}
187impl std::fmt::Debug for NativeStagedExtensions {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        f.write_str("NativeStagedExtensions { .. }")
190    }
191}
192
193#[cfg(test)]
194mod tests;