Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions crates/tinybus/src/module/github_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ fn zip_archives_refuse_paths_outside_the_destination() {
archive.write_all(b"outside").unwrap();
archive.finish().unwrap();

assert!(extract("release.zip", &archive_path, &destination).is_err());
let error = extract("release.zip", &archive_path, &destination).unwrap_err();
assert!(error.to_string().contains("unsafe path"), "{error}");
assert!(!directory.path().join("outside").exists());
}

Expand All @@ -289,7 +290,11 @@ fn zip_archives_refuse_symlink_entries() {
.unwrap();
archive.finish().unwrap();

assert!(extract("release.zip", &archive_path, &destination).is_err());
let error = extract("release.zip", &archive_path, &destination).unwrap_err();
assert!(
error.to_string().contains("unsupported entry type"),
"{error}"
);
assert!(!directory.path().join("outside").exists());
assert!(!destination.join("module.so").exists());
}
Expand All @@ -314,7 +319,11 @@ fn zip_archives_refuse_special_file_entries() {
archive.write_all(b"not a regular file").unwrap();
archive.finish().unwrap();

assert!(extract("release.zip", &archive_path, &destination).is_err());
let error = extract("release.zip", &archive_path, &destination).unwrap_err();
assert!(
error.to_string().contains("unsupported entry type"),
"{error}"
);
assert!(!destination.join("module.so").exists());
}

Expand Down
81 changes: 50 additions & 31 deletions crates/tinybus/src/module/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ use crate::{build_info, version::Version};

type ManifestFn = unsafe extern "C" fn() -> TbSlice;

/// Largest manifest a module may hand the loader.
const MAX_MANIFEST_BYTES: usize = 1024 * 1024;

#[derive(Clone)]
pub(crate) struct LoadedArtifact {
pub(crate) descriptor: TbAbiDescriptor,
Expand All @@ -32,18 +35,12 @@ pub(crate) fn load(path: &Path, strict: bool) -> Result<LoadedArtifact> {
let descriptor_ptr = platform::symbol(handle, b"TINYBUS_MODULE_ABI_V1\0", path)?;

let prefix = unsafe { descriptor_ptr.cast::<DescriptorPrefix>().read_unaligned() };
if prefix.magic != ABI_MAGIC {
return Err(Error::module_refused(path, "ABI magic does not match"));
}
if prefix.abi_revision != ABI_REVISION {
return Err(Error::module_refused(path, "ABI revision does not match"));
}
if !(DESCRIPTOR_PREFIX_SIZE..=MAX_DESCRIPTOR_SIZE).contains(&prefix.descriptor_size) {
return Err(Error::module_refused(path, "descriptor size is invalid"));
}
if prefix.descriptor_size < size_of::<TbAbiDescriptor>() as u32 {
return Err(Error::module_refused(path, "descriptor is too small"));
}
gate_prefix(
path,
prefix.magic,
prefix.abi_revision,
prefix.descriptor_size,
)?;
let descriptor = unsafe { descriptor_ptr.cast::<TbAbiDescriptor>().read_unaligned() };
gate_descriptor(path, &descriptor, strict)?;

Expand All @@ -54,13 +51,7 @@ pub(crate) fn load(path: &Path, strict: bool) -> Result<LoadedArtifact> {
path,
)?)
};
let slice = unsafe { manifest_fn() };
if slice.ptr.is_null() || slice.len > 1024 * 1024 {
return Err(Error::module_refused(path, "manifest bytes are invalid"));
}
let bytes = unsafe { std::slice::from_raw_parts(slice.ptr, slice.len) };
let manifest = serde_json::from_slice(bytes)
.map_err(|_| Error::module_refused(path, "manifest is not valid JSON"))?;
let manifest = unsafe { manifest_from(path, manifest_fn())? };

let init: TbModuleInit = unsafe {
std::mem::transmute(platform::symbol(handle, b"tinybus_module_init_v1\0", path)?)
Expand All @@ -72,24 +63,52 @@ pub(crate) fn load(path: &Path, strict: bool) -> Result<LoadedArtifact> {
})
}

/// The checks an ABI descriptor's prefix must pass before the full descriptor
/// may be read through it, and again on the full descriptor.
fn gate_prefix(path: &Path, magic: u64, abi_revision: u32, descriptor_size: u32) -> Result<()> {
let refuse = |reason| Err(Error::module_refused(path, reason));
if magic != ABI_MAGIC {
return refuse("ABI magic does not match");
}
if abi_revision != ABI_REVISION {
return refuse("ABI revision does not match");
}
if !(DESCRIPTOR_PREFIX_SIZE..=MAX_DESCRIPTOR_SIZE).contains(&descriptor_size) {
return refuse("descriptor size is invalid");
}
if descriptor_size < size_of::<TbAbiDescriptor>() as u32 {
return refuse("descriptor is too small");
}
Ok(())
}

/// Parse the manifest `tinybus_module_manifest_v1` returned.
///
/// # Safety
///
/// Unless `slice.ptr` is null or `slice.len` is over the cap, `slice` must be
/// readable for `slice.len` bytes.
unsafe fn manifest_from(path: &Path, slice: TbSlice) -> Result<ModuleManifest> {
if slice.ptr.is_null() || slice.len > MAX_MANIFEST_BYTES {
return Err(Error::module_refused(path, "manifest bytes are invalid"));
}
let bytes = unsafe { std::slice::from_raw_parts(slice.ptr, slice.len) };
serde_json::from_slice(bytes)
.map_err(|_| Error::module_refused(path, "manifest is not valid JSON"))
}

pub(crate) fn gate_descriptor(
path: &Path,
descriptor: &TbAbiDescriptor,
strict: bool,
) -> Result<()> {
let refuse = |reason| Error::module_refused(path, reason);
if descriptor.magic != ABI_MAGIC {
return Err(refuse("ABI magic does not match"));
}
if descriptor.abi_revision != ABI_REVISION {
return Err(refuse("ABI revision does not match"));
}
if !(DESCRIPTOR_PREFIX_SIZE..=MAX_DESCRIPTOR_SIZE).contains(&descriptor.descriptor_size) {
return Err(refuse("descriptor size is invalid"));
}
if descriptor.descriptor_size < size_of::<TbAbiDescriptor>() as u32 {
return Err(refuse("descriptor is too small"));
}
gate_prefix(
path,
descriptor.magic,
descriptor.abi_revision,
descriptor.descriptor_size,
)?;
if descriptor.pointer_width != usize::BITS {
return Err(refuse("pointer width does not match"));
}
Expand Down
89 changes: 87 additions & 2 deletions crates/tinybus/src/module/loader_tests.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,100 @@
use super::*;

fn refusal(result: Result<impl Sized>) -> String {
match result {
Ok(_) => panic!("the loader accepted it"),
Err(error) => error.to_string(),
}
}

#[test]
fn descriptor_gate_rejects_invalid_size_and_endianness_declarations() {
let path = Path::new("module.so");
let mut descriptor = TbAbiDescriptor::current("module", crate::VERSION);
descriptor.descriptor_size = DESCRIPTOR_PREFIX_SIZE - 1;
assert!(gate_descriptor(path, &descriptor, false).is_err());
assert!(
refusal(gate_descriptor(path, &descriptor, false)).contains("descriptor size is invalid")
);

let mut descriptor = TbAbiDescriptor::current("module", crate::VERSION);
descriptor.flags ^= 1 << 2;
assert!(gate_descriptor(path, &descriptor, false).is_err());
assert!(
refusal(gate_descriptor(path, &descriptor, false))
.contains("target endianness does not match")
);
}

#[test]
fn the_descriptor_prefix_is_refused_for_each_reason() {
let path = Path::new("module.so");
let full = size_of::<TbAbiDescriptor>() as u32;
assert!(gate_prefix(path, ABI_MAGIC, ABI_REVISION, full).is_ok());
for (magic, revision, size, reason) in [
(
ABI_MAGIC ^ 1,
ABI_REVISION,
full,
"ABI magic does not match",
),
(
ABI_MAGIC,
ABI_REVISION + 1,
full,
"ABI revision does not match",
),
(
ABI_MAGIC,
ABI_REVISION,
DESCRIPTOR_PREFIX_SIZE - 1,
"descriptor size is invalid",
),
(
ABI_MAGIC,
ABI_REVISION,
MAX_DESCRIPTOR_SIZE + 1,
"descriptor size is invalid",
),
(ABI_MAGIC, ABI_REVISION, full - 1, "descriptor is too small"),
] {
let error = refusal(gate_prefix(path, magic, revision, size));
assert!(error.contains(reason), "{reason}: {error}");
}
}

#[test]
fn the_manifest_slice_is_refused_for_each_reason() {
let path = Path::new("module.so");
let slice = |bytes: &[u8]| TbSlice {
ptr: bytes.as_ptr(),
len: bytes.len(),
};
let manifest = serde_json::json!({
"tinybus_manifest": 1,
"module": {"name": "fixture", "version": "1.0.0"},
"bus_name": "ai.tinyhumans.Fixture",
"object_path": "/ai/tinyhumans/Fixture"
})
.to_string();
assert!(unsafe { manifest_from(path, slice(manifest.as_bytes())) }.is_ok());

let null = TbSlice {
ptr: std::ptr::null(),
len: 0,
};
// Over the cap is refused before the bytes are read, so no buffer that
// large has to exist.
let oversized = TbSlice {
ptr: manifest.as_ptr(),
len: MAX_MANIFEST_BYTES + 1,
};
for (bytes, reason) in [
(null, "manifest bytes are invalid"),
(oversized, "manifest bytes are invalid"),
(slice(b"{not json"), "manifest is not valid JSON"),
] {
let error = refusal(unsafe { manifest_from(path, bytes) });
assert!(error.contains(reason), "{reason}: {error}");
}
}

#[cfg(unix)]
Expand Down
Loading