Skip to main content

microsandbox_utils/
lib.rs

1//! Shared constants and utilities for the microsandbox project.
2
3pub mod copy;
4pub mod extent;
5pub mod format;
6pub mod log_text;
7pub mod process;
8pub mod process_lock;
9pub mod secret;
10pub mod size;
11pub mod ttl_reverse_index;
12pub mod wake_pipe;
13
14//--------------------------------------------------------------------------------------------------
15// Constants: Directory Layout
16//--------------------------------------------------------------------------------------------------
17
18/// Name of the microsandbox home directory (relative to user's home).
19pub const BASE_DIR_NAME: &str = ".microsandbox";
20
21/// Subdirectory for shared libraries (libkrunfw).
22pub const LIB_SUBDIR: &str = "lib";
23
24/// Subdirectory for helper binaries.
25pub const BIN_SUBDIR: &str = "bin";
26
27/// Subdirectory for the database.
28pub const DB_SUBDIR: &str = "db";
29
30/// Subdirectory for OCI layer cache.
31pub const CACHE_SUBDIR: &str = "cache";
32
33/// Subdirectory for per-sandbox state.
34pub const SANDBOXES_SUBDIR: &str = "sandboxes";
35
36/// Subdirectory for named volumes.
37pub const VOLUMES_SUBDIR: &str = "volumes";
38
39/// Subdirectory for snapshot artifacts.
40pub const SNAPSHOTS_SUBDIR: &str = "snapshots";
41
42/// Subdirectory for logs.
43pub const LOGS_SUBDIR: &str = "logs";
44
45/// Subdirectory for secrets.
46pub const SECRETS_SUBDIR: &str = "secrets";
47
48/// Subdirectory for TLS certificates.
49pub const TLS_SUBDIR: &str = "tls";
50
51/// Subdirectory for SSH keys.
52pub const SSH_SUBDIR: &str = "ssh";
53
54/// Subdirectory for ephemeral runtime artifacts that should not be backed up.
55pub const RUN_SUBDIR: &str = "run";
56
57/// Subdirectory under `run` for metrics-related diagnostic artifacts.
58pub const METRICS_RUN_SUBDIR: &str = "metrics";
59
60/// Prefix used when constructing the POSIX shared-memory object name for the
61/// live metrics registry. Combined with a stable hash of `GlobalConfig::home()`
62/// so concurrent `MSB_HOME`-isolated environments do not collide.
63///
64/// Kept short because macOS limits `shm_open` names to ~31 bytes including the
65/// leading slash; the final form is `<prefix>-<hex16>-vN` (28 bytes for
66/// single-digit ABI versions).
67pub const METRICS_SHM_PREFIX: &str = "/msb-met";
68
69//--------------------------------------------------------------------------------------------------
70// Constants: Binary Names
71//--------------------------------------------------------------------------------------------------
72
73/// Guest agent binary name.
74pub const AGENTD_BINARY: &str = "agentd";
75
76/// CLI binary name.
77pub const MSB_BINARY: &str = "msb";
78
79//--------------------------------------------------------------------------------------------------
80// Constants: Versions
81//--------------------------------------------------------------------------------------------------
82
83/// Version for downloading prebuilt release artifacts.
84///
85/// This tracks the published crate/package version so the SDK and the
86/// downloaded runtime bundle stay aligned.
87pub const PREBUILT_VERSION: &str = env!("CARGO_PKG_VERSION");
88
89/// libkrunfw release version. Keep in sync with justfile.
90pub const LIBKRUNFW_VERSION: &str = "5.6.1";
91
92/// libkrunfw ABI version (soname major). Keep in sync with justfile.
93pub const LIBKRUNFW_ABI: &str = "5";
94
95//--------------------------------------------------------------------------------------------------
96// Constants: Filenames
97//--------------------------------------------------------------------------------------------------
98
99/// Database filename.
100pub const DB_FILENAME: &str = "msb.db";
101
102/// Global configuration filename.
103pub const CONFIG_FILENAME: &str = "config.json";
104
105/// Project-local sandbox configuration filename.
106pub const SANDBOXFILE_NAME: &str = "Sandboxfile";
107
108//--------------------------------------------------------------------------------------------------
109// Constants: GitHub
110//--------------------------------------------------------------------------------------------------
111
112/// GitHub organization.
113pub const GITHUB_ORG: &str = "superradcompany";
114
115/// Main repository name.
116pub const MICROSANDBOX_REPO: &str = "microsandbox";
117
118//--------------------------------------------------------------------------------------------------
119// Functions
120//--------------------------------------------------------------------------------------------------
121
122/// Derive a short, stable identifier from a path.
123///
124/// Used to build a POSIX shared-memory object name that depends only on the
125/// resolved home directory, so two processes pointed at the same `MSB_HOME`
126/// agree on a single registry without leaking the absolute path through a
127/// public name.
128pub fn stable_hash_path(path: &std::path::Path) -> String {
129    // Avoid pulling sha2 into the utils crate for one filename; a stable
130    // 64-bit FNV-1a over the OS-bytes is plenty for collision-resistance at
131    // this scale (one entry per concurrent MSB_HOME on a host).
132    let bytes = path.as_os_str().as_encoded_bytes();
133    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
134    for byte in bytes {
135        hash ^= u64::from(*byte);
136        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
137    }
138    format!("{hash:016x}")
139}
140
141/// Filename of the optional registry-name diagnostic file under `run/metrics`.
142pub fn metrics_registry_name_filename(registry_abi_version: u32) -> String {
143    format!("registry-v{registry_abi_version}.name")
144}
145
146/// Derive the POSIX shared-memory object name for a metrics registry.
147pub fn metrics_registry_shm_name(home: &std::path::Path, registry_abi_version: u32) -> String {
148    format!(
149        "{}-{}-v{}",
150        METRICS_SHM_PREFIX,
151        stable_hash_path(home),
152        registry_abi_version
153    )
154}
155
156/// Resolve the microsandbox home directory.
157///
158/// Order of resolution:
159/// 1. `MSB_HOME` env var (used as-is, no `.microsandbox` suffix appended)
160/// 2. `~/.microsandbox/` (i.e. `dirs::home_dir().join(BASE_DIR_NAME)`)
161/// 3. `./.microsandbox/` if no home is available
162///
163/// `MSB_HOME` lets CI and integration tests isolate microsandbox state
164/// (db, sandboxes, cache, logs) per process without disturbing other
165/// `$HOME`-rooted tooling.
166pub fn resolve_home() -> std::path::PathBuf {
167    if let Some(path) = std::env::var_os("MSB_HOME") {
168        return std::path::PathBuf::from(path);
169    }
170    dirs::home_dir()
171        .unwrap_or_else(|| std::path::PathBuf::from("."))
172        .join(BASE_DIR_NAME)
173}
174
175/// Returns the platform-specific libkrunfw filename.
176pub fn libkrunfw_filename(os: &str) -> String {
177    if os == "macos" {
178        format!("libkrunfw.{LIBKRUNFW_ABI}.dylib")
179    } else if os == "windows" {
180        "libkrunfw.dll".to_string()
181    } else {
182        format!("libkrunfw.so.{LIBKRUNFW_VERSION}")
183    }
184}
185
186/// Returns the platform-specific msb executable filename.
187pub fn msb_binary_filename(os: &str) -> String {
188    if os == "windows" {
189        format!("{MSB_BINARY}.exe")
190    } else {
191        MSB_BINARY.to_string()
192    }
193}
194
195/// Returns the GitHub release download URL for libkrunfw.
196pub fn libkrunfw_download_url(version: &str, arch: &str, os: &str) -> String {
197    let (target_os, ext) = if os == "macos" {
198        ("darwin", "dylib")
199    } else if os == "windows" {
200        ("windows", "dll")
201    } else {
202        ("linux", "so")
203    };
204
205    format!(
206        "https://github.com/{GITHUB_ORG}/{MICROSANDBOX_REPO}/releases/download/v{version}/libkrunfw-{target_os}-{arch}.{ext}"
207    )
208}
209
210/// Returns the GitHub release download URL for the agentd binary.
211pub fn agentd_download_url(version: &str, arch: &str) -> String {
212    format!(
213        "https://github.com/{GITHUB_ORG}/{MICROSANDBOX_REPO}/releases/download/v{version}/{AGENTD_BINARY}-{arch}"
214    )
215}
216
217/// Returns the GitHub release download URL for the microsandbox bundle tarball.
218pub fn bundle_download_url(version: &str, arch: &str, os: &str) -> String {
219    let target_os = if os == "macos" {
220        "darwin"
221    } else if os == "windows" {
222        "windows"
223    } else {
224        "linux"
225    };
226    format!(
227        "https://github.com/{GITHUB_ORG}/{MICROSANDBOX_REPO}/releases/download/v{version}/{MICROSANDBOX_REPO}-{target_os}-{arch}.tar.gz"
228    )
229}
230
231/// Returns an HTTP client configured for release asset downloads.
232#[cfg(feature = "http-client")]
233pub fn http_client() -> ureq::Agent {
234    ureq::Agent::config_builder()
235        .tls_config(
236            ureq::tls::TlsConfig::builder()
237                .root_certs(ureq::tls::RootCerts::PlatformVerifier)
238                .build(),
239        )
240        .build()
241        .new_agent()
242}
243
244/// Returns true when a user-provided text value should be interpreted as a
245/// local filesystem path rather than a named resource or OCI reference.
246pub fn looks_like_local_path_text(s: &str) -> bool {
247    if s == "." || s == ".." || s.starts_with('/') || s.starts_with("./") || s.starts_with("../") {
248        return true;
249    }
250
251    #[cfg(windows)]
252    {
253        s.starts_with(".\\")
254            || s.starts_with("..\\")
255            || s.starts_with('\\')
256            || is_windows_drive_path_text(s)
257    }
258    #[cfg(not(windows))]
259    {
260        false
261    }
262}
263
264/// Returns true when `s` starts with a Windows drive-rooted path prefix.
265pub fn is_windows_drive_path_text(s: &str) -> bool {
266    let bytes = s.as_bytes();
267    bytes.len() >= 3
268        && bytes[0].is_ascii_alphabetic()
269        && bytes[1] == b':'
270        && matches!(bytes[2], b'\\' | b'/')
271}
272
273/// Returns true when the colon at `index` is the drive separator in a Windows path.
274pub fn is_windows_drive_separator_at(s: &str, index: usize) -> bool {
275    let bytes = s.as_bytes();
276    index == 1
277        && bytes.len() >= 3
278        && bytes[0].is_ascii_alphabetic()
279        && bytes[1] == b':'
280        && matches!(bytes[2], b'\\' | b'/')
281}
282
283//--------------------------------------------------------------------------------------------------
284// Tests
285//--------------------------------------------------------------------------------------------------
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    /// `MSB_HOME` is honoured verbatim (no `.microsandbox` suffix appended)
292    /// so callers can isolate state per process without disturbing tooling
293    /// that reads `$HOME` (npm cache, ssh keys, etc.).
294    ///
295    /// Uses a unique env var per test process to avoid clashing with other
296    /// parallel tests that read `MSB_HOME`.
297    #[test]
298    fn test_resolve_home_respects_env_override() {
299        // SAFETY: This test sets a process-global env var. Vitest-style
300        // single-test isolation isn't available; rely on the test being
301        // the sole reader of `MSB_HOME` in this binary.
302        let custom = std::path::PathBuf::from("/tmp/msb-home-resolve-test-12345");
303        unsafe { std::env::set_var("MSB_HOME", &custom) };
304        let resolved = resolve_home();
305        unsafe { std::env::remove_var("MSB_HOME") };
306        assert_eq!(resolved, custom);
307    }
308
309    #[test]
310    fn test_metrics_registry_names_include_abi_version() {
311        let home = std::path::Path::new("/tmp/msb-home");
312
313        assert_eq!(metrics_registry_name_filename(2), "registry-v2.name");
314        assert_eq!(
315            metrics_registry_shm_name(home, 2),
316            format!("{}-{}-v2", METRICS_SHM_PREFIX, stable_hash_path(home))
317        );
318    }
319
320    #[test]
321    #[cfg(windows)]
322    fn test_looks_like_local_path_text_accepts_windows_paths() {
323        assert!(looks_like_local_path_text(r"C:\Users\Stephen\file.txt"));
324        assert!(looks_like_local_path_text(r".\relative"));
325        assert!(looks_like_local_path_text(r"\\server\share\file.txt"));
326        assert!(!looks_like_local_path_text("alpine"));
327    }
328}