use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, Once, OnceLock};
use sha2::{Digest, Sha256};
pub const ONNX_RUNTIME_MISSING_PREFIX: &str = "ONNX Runtime not found.";
pub const ORT_DYLIB_PATH_ENV: &str = "ORT_DYLIB_PATH";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PinnedOrtLibrary {
pub version: &'static str,
pub asset: &'static str,
pub library: &'static str,
pub sha256: &'static str,
}
pub const PINNED_ORT_LIBRARIES: &[PinnedOrtLibrary] = &[
PinnedOrtLibrary {
version: "1.24.4",
asset: "onnxruntime-osx-arm64-1.24.4.tgz",
library: "onnxruntime-osx-arm64-1.24.4/lib/libonnxruntime.dylib",
sha256: "872533f130f1839a5bc01788ddb4f75c83a189763441ba1178788ed965449289",
},
PinnedOrtLibrary {
version: "1.24.4",
asset: "microsoft.ml.onnxruntime.1.24.4.nupkg",
library: "runtimes/osx-arm64/native/libonnxruntime.dylib",
sha256: "0db33e160224e480c17932799d1dfaea59853b8e722b57bf61932c87e03586f0",
},
PinnedOrtLibrary {
version: "1.24.4",
asset: "microsoft.ml.onnxruntime.1.24.4.nupkg",
library: "runtimes/linux-x64/native/libonnxruntime.so",
sha256: "d132535d051344ff5c64c9c200004150559049a81ed330eb4422c1962fb6b7e4",
},
PinnedOrtLibrary {
version: "1.24.4",
asset: "microsoft.ml.onnxruntime.1.24.4.nupkg",
library: "runtimes/linux-arm64/native/libonnxruntime.so",
sha256: "52b2a0e75e79468404284fec38ad5ee1a7a996232274f5e1b84f3e793fb07554",
},
PinnedOrtLibrary {
version: "1.24.4",
asset: "microsoft.ml.onnxruntime.1.24.4.nupkg",
library: "runtimes/win-x64/native/onnxruntime.dll",
sha256: "b95efb2113b603bbbf3f191061c5516a871ed546893c820e4f3b7b6c358dbf2a",
},
PinnedOrtLibrary {
version: "1.24.4",
asset: "microsoft.ml.onnxruntime.1.24.4.nupkg",
library: "runtimes/win-arm64/native/onnxruntime.dll",
sha256: "724d81ac50b11bfaa01ab3ce01b99fb6734a4b762259a8be4395ca662ce99fe6",
},
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OrtLoadAuthorization {
Pinned { path: PathBuf, sha256: String },
OperatorUnpinned { path: PathBuf, sha256: String },
LoaderSearchUnpinned,
}
pub(crate) struct SpawnEnvValue(OnceLock<Option<OsString>>);
impl SpawnEnvValue {
pub(crate) const fn new() -> Self {
Self(OnceLock::new())
}
pub(crate) fn capture_with(&self, lookup: impl FnOnce() -> Option<OsString>) -> Option<&OsStr> {
self.0
.get_or_init(|| lookup().filter(|value| !value.is_empty()))
.as_deref()
}
}
static SPAWN_ORT_DYLIB_PATH: SpawnEnvValue = SpawnEnvValue::new();
pub fn capture_spawn_ort_dylib_path() -> Option<&'static OsStr> {
SPAWN_ORT_DYLIB_PATH.capture_with(|| std::env::var_os(ORT_DYLIB_PATH_ENV))
}
static PINNED_RUNTIME_REQUIRED: AtomicBool = AtomicBool::new(false);
pub fn require_pinned_onnx_runtime() {
PINNED_RUNTIME_REQUIRED.store(true, Ordering::SeqCst);
}
fn pinned_runtime_required() -> bool {
PINNED_RUNTIME_REQUIRED.load(Ordering::SeqCst)
}
static MANAGED_STORAGE_DIRS: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
pub fn register_managed_storage_dir(storage_dir: &Path) {
let mut dirs = MANAGED_STORAGE_DIRS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !dirs.iter().any(|known| known == storage_dir) {
dirs.push(storage_dir.to_path_buf());
}
}
fn managed_runtime_roots() -> Vec<PathBuf> {
let mut storage_dirs = MANAGED_STORAGE_DIRS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let default = crate::storage_path::storage_dir(None);
if !storage_dirs.contains(&default) {
storage_dirs.push(default);
}
storage_dirs
.into_iter()
.map(|dir| dir.join("onnxruntime"))
.collect()
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) struct OrtPinPolicy<'a> {
pub spawn_value: Option<&'a OsStr>,
pub require_pinned: bool,
pub managed_roots: &'a [PathBuf],
pub pinned_sha256: &'a [&'a str],
}
}
#[derive(Debug)]
pub struct AuthorizedOrtLibrary {
authorization: OrtLoadAuthorization,
held: Option<HeldLibrary>,
}
#[derive(Debug)]
struct HeldLibrary {
file: File,
path: PathBuf,
sha256: String,
#[cfg(unix)]
identity: FileIdentity,
}
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FileIdentity {
dev: u64,
ino: u64,
size: u64,
ctime: i64,
ctime_nsec: i64,
mtime: i64,
mtime_nsec: i64,
}
#[cfg(unix)]
impl FileIdentity {
fn of(file: &File) -> std::io::Result<Self> {
use std::os::unix::fs::MetadataExt;
let meta = file.metadata()?;
Ok(Self {
dev: meta.dev(),
ino: meta.ino(),
size: meta.size(),
ctime: meta.ctime(),
ctime_nsec: meta.ctime_nsec(),
mtime: meta.mtime(),
mtime_nsec: meta.mtime_nsec(),
})
}
}
impl AuthorizedOrtLibrary {
pub fn authorization(&self) -> &OrtLoadAuthorization {
&self.authorization
}
pub fn load_path(&self) -> Option<PathBuf> {
if let Some(held) = &self.held {
return Some(held_file_load_path(&held.file, &held.path));
}
match &self.authorization {
OrtLoadAuthorization::LoaderSearchUnpinned => None,
OrtLoadAuthorization::OperatorUnpinned { path, .. }
| OrtLoadAuthorization::Pinned { path, .. } => Some(path.clone()),
}
}
pub fn confirm_unchanged(&self) -> Result<(), String> {
let Some(held) = self.held.as_ref() else {
return Ok(());
};
let path = &held.path;
let changed = |detail: String| {
format!(
"onnx runtime library changed while it was being checked at {}: {detail}. \
It is not used, so semantic search is unavailable. Remove the file and \
reinstall with `npx @cortexkit/aft doctor --clear`.",
path.display()
)
};
#[cfg(unix)]
{
let now = FileIdentity::of(&held.file)
.map_err(|error| changed(format!("cannot read its metadata: {error}")))?;
if now != held.identity {
return Err(changed("it was replaced or written to".to_string()));
}
}
let mut file = &held.file;
let sha256 = file
.seek(SeekFrom::Start(0))
.and_then(|_| sha256_reader(&mut file))
.map_err(|error| changed(format!("cannot read it again: {error}")))?;
if sha256 != held.sha256 {
return Err(changed(format!("its sha256 is now {sha256}")));
}
Ok(())
}
}
#[cfg(target_os = "macos")]
fn held_file_load_path(file: &File, _path: &Path) -> PathBuf {
use std::os::fd::AsRawFd;
PathBuf::from(format!("/dev/fd/{}", file.as_raw_fd()))
}
#[cfg(all(unix, not(target_os = "macos")))]
fn held_file_load_path(file: &File, _path: &Path) -> PathBuf {
use std::os::fd::AsRawFd;
PathBuf::from(format!("/proc/self/fd/{}", file.as_raw_fd()))
}
#[cfg(windows)]
fn held_file_load_path(_file: &File, path: &Path) -> PathBuf {
path.to_path_buf()
}
fn open_library(path: &Path) -> std::io::Result<File> {
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
const FILE_SHARE_READ: u32 = 0x0000_0001;
std::fs::OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.open(path)
}
#[cfg(not(windows))]
{
File::open(path)
}
}
#[cfg(any(test, feature = "test-support"))]
pub fn authorize_with(
policy: &OrtPinPolicy<'_>,
candidate: Option<&OsStr>,
) -> Result<OrtLoadAuthorization, String> {
open_authorized_with(policy, candidate).map(|library| library.authorization)
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn open_authorized_with(
policy: &OrtPinPolicy<'_>,
candidate: Option<&OsStr>,
) -> Result<AuthorizedOrtLibrary, String> {
let Some(candidate) = candidate.filter(|value| !value.is_empty()) else {
if policy.require_pinned {
return Err(format!(
"{ONNX_RUNTIME_MISSING_PREFIX} No managed ONNX Runtime was found and \
ORT_DYLIB_PATH was not set when this module was spawned. The supervised \
module loads only a pinned runtime or one named by ORT_DYLIB_PATH at \
spawn, never a bare library name from the loader search path. Run \
`npx @cortexkit/aft doctor --fix` to install it."
));
}
return Ok(AuthorizedOrtLibrary {
authorization: OrtLoadAuthorization::LoaderSearchUnpinned,
held: None,
});
};
let path = Path::new(candidate);
let unreadable = |error: std::io::Error| {
format!(
"{ONNX_RUNTIME_MISSING_PREFIX} cannot read '{}' to check its sha256 before \
loading it: {error}. Run `npx @cortexkit/aft doctor --fix` to install it.",
path.display()
)
};
let mut file = open_library(path).map_err(unreadable)?;
#[cfg(unix)]
let identity = FileIdentity::of(&file).map_err(unreadable)?;
let sha256 = sha256_reader(&mut file).map_err(unreadable)?;
file.seek(SeekFrom::Start(0)).map_err(unreadable)?;
if policy
.pinned_sha256
.iter()
.any(|pinned| pinned.eq_ignore_ascii_case(&sha256))
{
return Ok(AuthorizedOrtLibrary {
authorization: OrtLoadAuthorization::Pinned {
path: path.to_path_buf(),
sha256: sha256.clone(),
},
held: Some(HeldLibrary {
file,
path: path.to_path_buf(),
sha256,
#[cfg(unix)]
identity,
}),
});
}
let named_at_spawn = policy.spawn_value == Some(candidate);
if named_at_spawn && !is_inside_any(path, policy.managed_roots) {
return Ok(AuthorizedOrtLibrary {
authorization: OrtLoadAuthorization::OperatorUnpinned {
path: path.to_path_buf(),
sha256,
},
held: None,
});
}
Err(format!(
"onnx runtime library hash mismatch at {}: sha256 {sha256} is not a pinned ONNX \
Runtime build, so semantic search is unavailable. Remove the file and reinstall \
with `npx @cortexkit/aft doctor --clear`, or name a runtime you trust with \
ORT_DYLIB_PATH in the environment AFT is started with.",
path.display()
))
}
}
fn is_inside_any(path: &Path, roots: &[PathBuf]) -> bool {
let resolved_path = std::fs::canonicalize(path).ok();
roots.iter().any(|root| {
if path.starts_with(root) {
return true;
}
let Some(resolved_path) = resolved_path.as_deref() else {
return false;
};
resolved_path.starts_with(root)
|| std::fs::canonicalize(root)
.map(|resolved_root| resolved_path.starts_with(resolved_root))
.unwrap_or(false)
})
}
#[cfg(any(test, feature = "test-support"))]
pub fn sha256_file(path: &Path) -> std::io::Result<String> {
sha256_reader(&mut File::open(path)?)
}
fn sha256_reader(reader: &mut impl Read) -> std::io::Result<String> {
let mut hasher = Sha256::new();
let mut buffer = vec![0u8; 1 << 16];
loop {
let read = reader.read(&mut buffer)?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(hasher
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect())
}
fn pinned_hashes() -> Vec<&'static str> {
PINNED_ORT_LIBRARIES
.iter()
.map(|library| library.sha256)
.collect()
}
pub fn open_onnx_runtime_for_load(
candidate: Option<&OsStr>,
) -> Result<AuthorizedOrtLibrary, String> {
let roots = managed_runtime_roots();
let pinned = pinned_hashes();
let policy = OrtPinPolicy {
spawn_value: capture_spawn_ort_dylib_path(),
require_pinned: pinned_runtime_required(),
managed_roots: &roots,
pinned_sha256: &pinned,
};
let library = open_authorized_with(&policy, candidate)?;
log_unpinned_once(library.authorization());
Ok(library)
}
fn log_unpinned_once(authorization: &OrtLoadAuthorization) {
static OPERATOR: Once = Once::new();
static LOADER_SEARCH: Once = Once::new();
match authorization {
OrtLoadAuthorization::Pinned { .. } => {}
OrtLoadAuthorization::OperatorUnpinned { path, sha256 } => OPERATOR.call_once(|| {
crate::slog_warn!(
"ONNX Runtime at {} (sha256 {sha256}) is not a pinned build; accepted unpinned \
because ORT_DYLIB_PATH named it when this process was spawned",
path.display()
);
}),
OrtLoadAuthorization::LoaderSearchUnpinned => LOADER_SEARCH.call_once(|| {
crate::slog_warn!(
"no ONNX Runtime path configured; loading it by name from the loader search \
path, unpinned"
);
}),
}
}
pub fn load_authorized_with<T>(
open: impl FnOnce(Option<&OsStr>) -> Result<AuthorizedOrtLibrary, String>,
candidate: Option<&OsStr>,
after_check: impl FnOnce(),
load: impl FnOnce(Option<&Path>) -> Result<T, String>,
) -> Result<T, String> {
let library = open(candidate)?;
after_check();
let loaded = load(library.load_path().as_deref())?;
library.confirm_unchanged()?;
Ok(loaded)
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod tests {
use super::*;
#[cfg(test)]
use std::cell::Cell;
#[cfg(test)]
use std::cell::RefCell;
pub fn write_library(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf {
let path = dir.join(name);
std::fs::write(&path, bytes).expect("write fake library");
path
}
pub fn hash_of(path: &Path) -> String {
sha256_file(path).expect("hash fake library")
}
pub fn policy<'a>(
spawn_value: Option<&'a OsStr>,
require_pinned: bool,
managed_roots: &'a [PathBuf],
pinned_sha256: &'a [&'a str],
) -> OrtPinPolicy<'a> {
OrtPinPolicy {
spawn_value,
require_pinned,
managed_roots,
pinned_sha256,
}
}
pub fn read_as_loader(load_path: Option<&Path>) -> Result<Vec<u8>, String> {
let load_path = load_path.ok_or("a pinned library must be loaded by path")?;
std::fs::read(load_path).map_err(|error| error.to_string())
}
#[test]
fn a_library_swapped_between_the_check_and_the_load_is_never_loaded() {
let dir = tempfile::tempdir().unwrap();
let path = write_library(dir.path(), "libonnxruntime.dylib", b"genuine build");
let replacement = write_library(dir.path(), "replacement.dylib", b"swapped build");
let hash = hash_of(&path);
let pinned = [hash.as_str()];
let roots = [dir.path().to_path_buf()];
let policy = policy(None, true, &roots, &pinned);
let swapped = Cell::new(None);
let mapped = RefCell::new(None);
let result = load_authorized_with(
|candidate| open_authorized_with(&policy, candidate),
Some(path.as_os_str()),
|| swapped.set(Some(std::fs::rename(&replacement, &path).is_ok())),
|load_path| {
*mapped.borrow_mut() = Some(read_as_loader(load_path)?);
Ok(())
},
);
assert_eq!(*mapped.borrow(), Some(b"genuine build".to_vec()));
if cfg!(unix) {
assert_eq!(swapped.get(), Some(true), "the swap ran");
assert_eq!(std::fs::read(&path).unwrap(), b"swapped build");
let error = result.expect_err("a swap during the load is reported");
assert!(
error.starts_with("onnx runtime library changed while it was being checked"),
"{error}"
);
} else {
assert_eq!(swapped.get(), Some(false), "the swap was refused");
assert_eq!(result, Ok(()));
}
}
#[test]
fn a_pinned_library_is_loaded_through_the_checked_file_not_its_path() {
let dir = tempfile::tempdir().unwrap();
let path = write_library(dir.path(), "libonnxruntime.dylib", b"genuine build");
let hash = hash_of(&path);
let pinned = [hash.as_str()];
let roots = [dir.path().to_path_buf()];
let library =
open_authorized_with(&policy(None, true, &roots, &pinned), Some(path.as_os_str()))
.expect("a pinned library is admitted");
let load_path = library
.load_path()
.expect("a pinned library has a load path");
#[cfg(target_os = "macos")]
assert!(load_path.starts_with("/dev/fd"), "{}", load_path.display());
#[cfg(all(unix, not(target_os = "macos")))]
assert!(
load_path.starts_with("/proc/self/fd"),
"{}",
load_path.display()
);
#[cfg(windows)]
assert_eq!(load_path, path);
assert_eq!(library.confirm_unchanged(), Ok(()));
}
#[test]
fn an_operator_library_is_loaded_by_its_own_path() {
let operator_dir = tempfile::tempdir().unwrap();
let storage = tempfile::tempdir().unwrap();
let path = write_library(operator_dir.path(), "libonnxruntime.dylib", b"brew build");
let roots = [storage.path().join("onnxruntime")];
let pinned: [&str; 0] = [];
let library = open_authorized_with(
&policy(Some(path.as_os_str()), true, &roots, &pinned),
Some(path.as_os_str()),
)
.expect("the operator's spawn-time choice is admitted");
assert_eq!(library.load_path(), Some(path.clone()));
std::fs::write(&path, b"other build").unwrap();
assert_eq!(library.confirm_unchanged(), Ok(()));
}
#[test]
fn a_bare_name_load_has_no_path() {
let roots: [PathBuf; 0] = [];
let pinned: [&str; 0] = [];
let library = open_authorized_with(&policy(None, false, &roots, &pinned), None)
.expect("standalone bare-name loads are allowed");
assert_eq!(library.load_path(), None);
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn real_pinned_runtime() -> Option<PathBuf> {
#[cfg(target_os = "macos")]
const NAME: &str = "libonnxruntime.dylib";
#[cfg(target_os = "linux")]
const NAME: &str = "libonnxruntime.so";
let dir = std::env::var_os("AFT_TEST_ORT_LIBRARY_DIR")
.map(PathBuf::from)
.or_else(|| {
let home = PathBuf::from(std::env::var_os("HOME")?);
Some(home.join(".local/share/cortexkit/aft/onnxruntime/1.24.4"))
})?;
let library = dir.join(NAME);
let hash = sha256_file(&library).ok()?;
pinned_hashes().contains(&hash.as_str()).then_some(library)
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[repr(C)]
struct OrtApiBase {
_get_api: unsafe extern "C" fn(u32) -> *const std::ffi::c_void,
get_version_string: unsafe extern "C" fn() -> *const std::ffi::c_char,
}
#[test]
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn real_dlopen_maps_the_checked_runtime_after_a_swap() {
let Some(real) = real_pinned_runtime() else {
eprintln!(
"skipping: no pinned ONNX Runtime on this machine (AFT_TEST_ORT_LIBRARY_DIR)"
);
return;
};
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(real.file_name().unwrap());
std::fs::copy(&real, &path).unwrap();
let replacement = write_library(dir.path(), "replacement", b"not a library");
let pinned = pinned_hashes();
let roots = [dir.path().to_path_buf()];
let policy = policy(None, true, &roots, &pinned);
let mapped_version = RefCell::new(None);
let result = load_authorized_with(
|candidate| open_authorized_with(&policy, candidate),
Some(path.as_os_str()),
|| std::fs::rename(&replacement, &path).unwrap(),
|load_path| {
let load_path = load_path.ok_or("a pinned library is loaded by path")?;
let c_path = std::ffi::CString::new(load_path.to_str().unwrap()).unwrap();
let symbol_name = std::ffi::CString::new("OrtGetApiBase").unwrap();
unsafe {
let handle = libc::dlopen(c_path.as_ptr(), libc::RTLD_NOW);
if handle.is_null() {
let error = std::ffi::CStr::from_ptr(libc::dlerror());
return Err(error.to_string_lossy().into_owned());
}
let symbol = libc::dlsym(handle, symbol_name.as_ptr());
assert!(!symbol.is_null(), "OrtGetApiBase is exported");
let get_api_base: unsafe extern "C" fn() -> *const OrtApiBase =
std::mem::transmute(symbol);
let version =
std::ffi::CStr::from_ptr(((*get_api_base()).get_version_string)())
.to_string_lossy()
.into_owned();
libc::dlclose(handle);
*mapped_version.borrow_mut() = Some(version);
Ok(())
}
},
);
assert_eq!(*mapped_version.borrow(), Some("1.24.4".to_string()));
assert!(result.is_err(), "{result:?}");
}
#[test]
fn sha256_file_matches_a_known_digest() {
let dir = tempfile::tempdir().unwrap();
let path = write_library(dir.path(), "lib", b"abc");
assert_eq!(
hash_of(&path),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn pinned_library_is_authorized_and_loaded() {
let dir = tempfile::tempdir().unwrap();
let path = write_library(dir.path(), "libonnxruntime.dylib", b"genuine build");
let hash = hash_of(&path);
let pinned = [hash.as_str()];
let roots = [dir.path().to_path_buf()];
let policy = policy(None, true, &roots, &pinned);
let loads = Cell::new(0);
let result = load_authorized_with(
|candidate| open_authorized_with(&policy, candidate),
Some(path.as_os_str()),
|| {},
|loaded| {
assert_eq!(read_as_loader(loaded), Ok(b"genuine build".to_vec()));
loads.set(loads.get() + 1);
Ok(())
},
);
assert_eq!(result, Ok(()));
assert_eq!(loads.get(), 1);
assert_eq!(
authorize_with(&policy, Some(path.as_os_str())),
Ok(OrtLoadAuthorization::Pinned {
path: path.clone(),
sha256: hash
})
);
}
#[test]
fn spawn_time_operator_path_outside_the_managed_folder_is_accepted_unpinned() {
let operator_dir = tempfile::tempdir().unwrap();
let storage = tempfile::tempdir().unwrap();
let path = write_library(operator_dir.path(), "libonnxruntime.dylib", b"brew build");
let roots = [storage.path().join("onnxruntime")];
let pinned = ["872533f130f1839a5bc01788ddb4f75c83a189763441ba1178788ed965449289"];
for require_pinned in [false, true] {
let policy = policy(Some(path.as_os_str()), require_pinned, &roots, &pinned);
assert_eq!(
authorize_with(&policy, Some(path.as_os_str())),
Ok(OrtLoadAuthorization::OperatorUnpinned {
path: path.clone(),
sha256: hash_of(&path)
}),
"require_pinned={require_pinned}"
);
}
}
#[test]
fn spawn_time_path_inside_the_managed_folder_must_still_match_the_pin() {
let storage = tempfile::tempdir().unwrap();
let version_dir = storage.path().join("onnxruntime").join("1.24.4");
std::fs::create_dir_all(&version_dir).unwrap();
let path = write_library(&version_dir, "libonnxruntime.dylib", b"swapped build");
let roots = [storage.path().join("onnxruntime")];
let pinned = ["872533f130f1839a5bc01788ddb4f75c83a189763441ba1178788ed965449289"];
for require_pinned in [false, true] {
let policy = policy(Some(path.as_os_str()), require_pinned, &roots, &pinned);
let error = authorize_with(&policy, Some(path.as_os_str()))
.expect_err("a managed library with a bad hash must be refused");
assert!(
error.starts_with("onnx runtime library hash mismatch at"),
"require_pinned={require_pinned}: {error}"
);
}
}
#[test]
fn managed_folder_reached_through_a_symlink_is_still_managed() {
#[cfg(unix)]
{
let storage = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let version_dir = storage.path().join("onnxruntime").join("1.24.4");
std::fs::create_dir_all(&version_dir).unwrap();
let real = write_library(&version_dir, "libonnxruntime.dylib", b"swapped build");
let link = outside.path().join("libonnxruntime.dylib");
std::os::unix::fs::symlink(&real, &link).unwrap();
let roots = [storage.path().join("onnxruntime")];
let pinned: [&str; 0] = [];
let policy = policy(Some(link.as_os_str()), false, &roots, &pinned);
assert!(authorize_with(&policy, Some(link.as_os_str())).is_err());
}
}
#[test]
fn a_value_aft_exported_itself_is_not_an_operator_override() {
let env: RefCell<Option<OsString>> = RefCell::new(None);
let spawn = SpawnEnvValue::new();
assert_eq!(spawn.capture_with(|| env.borrow().clone()), None);
let dir = tempfile::tempdir().unwrap();
let path = write_library(dir.path(), "libonnxruntime.dylib", b"swapped build");
*env.borrow_mut() = Some(path.as_os_str().to_os_string());
let spawn_value = spawn.capture_with(|| env.borrow().clone());
assert_eq!(spawn_value, None, "the first capture must win");
let roots: [PathBuf; 0] = [];
let pinned = ["872533f130f1839a5bc01788ddb4f75c83a189763441ba1178788ed965449289"];
let policy = policy(spawn_value, false, &roots, &pinned);
let error = authorize_with(&policy, Some(path.as_os_str()))
.expect_err("AFT's own export is not the operator's choice");
assert!(error.starts_with("onnx runtime library hash mismatch at"));
}
#[test]
fn spawn_capture_keeps_a_value_present_at_spawn() {
let spawn = SpawnEnvValue::new();
let value = OsString::from("/opt/onnxruntime/libonnxruntime.so");
assert_eq!(
spawn.capture_with(|| Some(value.clone())),
Some(value.as_os_str())
);
assert_eq!(
spawn.capture_with(|| None),
Some(value.as_os_str()),
"a later unset must not erase the spawn value"
);
let empty = SpawnEnvValue::new();
assert_eq!(empty.capture_with(|| Some(OsString::new())), None);
}
#[test]
fn bare_name_load_is_refused_under_the_supervised_module() {
let roots: [PathBuf; 0] = [];
let pinned: [&str; 0] = [];
let error = authorize_with(&policy(None, true, &roots, &pinned), None)
.expect_err("the supervised module must not load by bare name");
assert!(
error.starts_with(ONNX_RUNTIME_MISSING_PREFIX),
"the wait-for-download flow keys on this prefix: {error}"
);
}
#[test]
fn bare_name_load_is_allowed_standalone() {
let roots: [PathBuf; 0] = [];
let pinned: [&str; 0] = [];
assert_eq!(
authorize_with(&policy(None, false, &roots, &pinned), None),
Ok(OrtLoadAuthorization::LoaderSearchUnpinned)
);
assert_eq!(
authorize_with(&policy(None, false, &roots, &pinned), Some(OsStr::new(""))),
Ok(OrtLoadAuthorization::LoaderSearchUnpinned),
"an empty ORT_DYLIB_PATH is unset"
);
}
#[test]
fn unreadable_library_reports_a_missing_runtime() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("absent").join("libonnxruntime.dylib");
let roots: [PathBuf; 0] = [];
let pinned: [&str; 0] = [];
let error = authorize_with(
&policy(Some(path.as_os_str()), false, &roots, &pinned),
Some(path.as_os_str()),
)
.expect_err("a file that cannot be hashed cannot be loaded");
assert!(error.starts_with(ONNX_RUNTIME_MISSING_PREFIX), "{error}");
assert!(error.contains("doctor --fix"), "{error}");
}
#[test]
fn installer_pins_the_same_library_hashes() {
let installer = Path::new(crate::test_support::manifest_dir())
.join("../../packages/aft-bridge/src/onnx-runtime.ts");
let Ok(source) = std::fs::read_to_string(&installer) else {
eprintln!("skipping: {} not present", installer.display());
return;
};
let installer_pins: Vec<&str> = source
.lines()
.filter_map(|line| line.trim().strip_prefix("librarySha256: \""))
.filter_map(|rest| rest.split('"').next())
.collect();
let mut rust_pins: Vec<&str> = PINNED_ORT_LIBRARIES
.iter()
.filter(|library| library.asset.ends_with(".nupkg"))
.map(|library| library.sha256)
.collect();
let mut installer_sorted = installer_pins.clone();
rust_pins.sort_unstable();
installer_sorted.sort_unstable();
assert_eq!(installer_sorted, rust_pins);
}
#[test]
fn pinned_list_covers_every_platform_the_installer_downloads() {
for library in [
"runtimes/osx-arm64/native/libonnxruntime.dylib",
"runtimes/linux-x64/native/libonnxruntime.so",
"runtimes/linux-arm64/native/libonnxruntime.so",
"runtimes/win-x64/native/onnxruntime.dll",
"runtimes/win-arm64/native/onnxruntime.dll",
] {
let entry = PINNED_ORT_LIBRARIES
.iter()
.find(|entry| entry.library == library)
.unwrap_or_else(|| panic!("no pin for {library}"));
assert_eq!(entry.sha256.len(), 64, "{library}");
assert!(
entry
.sha256
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)),
"{library}: pins are lowercase hex"
);
}
}
#[test]
fn accepts_the_legacy_macos_cache_hash() {
assert!(PINNED_ORT_LIBRARIES.iter().any(|entry| {
entry.sha256 == "872533f130f1839a5bc01788ddb4f75c83a189763441ba1178788ed965449289"
}));
}
}