fix(loader): bound PBX input admission for PLN-0176 step 09
This commit is contained in:
@@ -278,6 +278,7 @@ pub enum CartridgeError {
|
|||||||
MissingProgram,
|
MissingProgram,
|
||||||
MissingAssets,
|
MissingAssets,
|
||||||
IoError,
|
IoError,
|
||||||
|
ProgramLoadFailed(prometeu_bytecode::load_limits::LoadFailure),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ use crate::cartridge::{
|
|||||||
CartridgeManifest,
|
CartridgeManifest,
|
||||||
};
|
};
|
||||||
use crate::syscalls::{CapFlags, caps};
|
use crate::syscalls::{CapFlags, caps};
|
||||||
|
use prometeu_bytecode::load_limits::{
|
||||||
|
LoadBudget, LoadFailure, LoadLimits, LoadReason, LoadResource,
|
||||||
|
};
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{Read, Seek, SeekFrom};
|
use std::io::{Read, Seek, SeekFrom};
|
||||||
@@ -58,7 +61,9 @@ impl DirectoryCartridgeLoader {
|
|||||||
return Err(CartridgeError::MissingProgram);
|
return Err(CartridgeError::MissingProgram);
|
||||||
}
|
}
|
||||||
|
|
||||||
let program = fs::read(program_path).map_err(|_| CartridgeError::IoError)?;
|
let mut program_file = fs::File::open(program_path).map_err(|_| CartridgeError::IoError)?;
|
||||||
|
let program_len = program_file.metadata().map_err(|_| CartridgeError::IoError)?.len();
|
||||||
|
let program = read_program(&mut program_file, program_len, LoadLimits::default())?;
|
||||||
|
|
||||||
let assets_pa_path = path.join("assets.pa");
|
let assets_pa_path = path.join("assets.pa");
|
||||||
let (assets, asset_table, preload) = if assets_pa_path.exists() {
|
let (assets, asset_table, preload) = if assets_pa_path.exists() {
|
||||||
@@ -98,6 +103,59 @@ impl DirectoryCartridgeLoader {
|
|||||||
|
|
||||||
pub struct PackedCartridgeLoader;
|
pub struct PackedCartridgeLoader;
|
||||||
|
|
||||||
|
/// Admit the PBX input separately from parsing scratch. Metadata rejects an
|
||||||
|
/// oversized file before reservation; bounded reads also cover file growth.
|
||||||
|
fn read_program(
|
||||||
|
reader: &mut impl Read,
|
||||||
|
size_hint: u64,
|
||||||
|
limits: LoadLimits,
|
||||||
|
) -> Result<Vec<u8>, CartridgeError> {
|
||||||
|
let budget = LoadBudget::new(limits);
|
||||||
|
let limit = budget.limit(LoadResource::PbxBytes);
|
||||||
|
budget.check(LoadResource::PbxBytes, size_hint).map_err(CartridgeError::ProgramLoadFailed)?;
|
||||||
|
let resource_error = |reason, requested| {
|
||||||
|
let mut error = LoadFailure::resource(LoadResource::PbxBytes, requested, limit);
|
||||||
|
error.reason = reason;
|
||||||
|
CartridgeError::ProgramLoadFailed(error)
|
||||||
|
};
|
||||||
|
let mut out = Vec::<u8>::new();
|
||||||
|
let initial =
|
||||||
|
usize::try_from(size_hint).map_err(|_| resource_error(LoadReason::Overflow, size_hint))?;
|
||||||
|
out.try_reserve_exact(initial)
|
||||||
|
.map_err(|_| resource_error(LoadReason::Allocation, size_hint))?;
|
||||||
|
budget
|
||||||
|
.check(LoadResource::PbxBytes, out.capacity() as u64)
|
||||||
|
.map_err(CartridgeError::ProgramLoadFailed)?;
|
||||||
|
let mut chunk = [0u8; 8192];
|
||||||
|
loop {
|
||||||
|
// At the ceiling inspect one extra byte without growing the input.
|
||||||
|
let remaining = limit - out.len() as u64;
|
||||||
|
let read_len = remaining.min(chunk.len() as u64).max(1) as usize;
|
||||||
|
let count = match reader.read(&mut chunk[..read_len]) {
|
||||||
|
Ok(count) => count,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||||
|
Err(_) => return Err(CartridgeError::IoError),
|
||||||
|
};
|
||||||
|
if count == 0 {
|
||||||
|
return Ok(out);
|
||||||
|
}
|
||||||
|
let requested = (out.len() as u64)
|
||||||
|
.checked_add(count as u64)
|
||||||
|
.ok_or_else(|| resource_error(LoadReason::Overflow, u64::MAX))?;
|
||||||
|
budget
|
||||||
|
.check(LoadResource::PbxBytes, requested)
|
||||||
|
.map_err(CartridgeError::ProgramLoadFailed)?;
|
||||||
|
// Reserve exact growth rather than allowing Vec's geometric growth to
|
||||||
|
// exceed admission. Existing spare capacity is reused without billing twice.
|
||||||
|
out.try_reserve_exact(count)
|
||||||
|
.map_err(|_| resource_error(LoadReason::Allocation, requested))?;
|
||||||
|
budget
|
||||||
|
.check(LoadResource::PbxBytes, out.capacity() as u64)
|
||||||
|
.map_err(CartridgeError::ProgramLoadFailed)?;
|
||||||
|
out.extend_from_slice(&chunk[..count]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl PackedCartridgeLoader {
|
impl PackedCartridgeLoader {
|
||||||
pub fn load(_path: &Path) -> Result<Cartridge, CartridgeError> {
|
pub fn load(_path: &Path) -> Result<Cartridge, CartridgeError> {
|
||||||
Err(CartridgeError::InvalidFormat)
|
Err(CartridgeError::InvalidFormat)
|
||||||
@@ -204,6 +262,7 @@ mod tests {
|
|||||||
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
|
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
|
||||||
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
|
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
|
||||||
use crate::glyph_bank::GLYPH_BANK_MAX_PALETTE_COUNT_V1;
|
use crate::glyph_bank::GLYPH_BANK_MAX_PALETTE_COUNT_V1;
|
||||||
|
use prometeu_bytecode::load_limits::LoadCode;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
@@ -289,6 +348,76 @@ mod tests {
|
|||||||
manifest
|
manifest
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn program_admission_accepts_exact_limit_and_rejects_growth_after_metadata() {
|
||||||
|
let limits = LoadLimits { pbx_bytes: 3, ..Default::default() };
|
||||||
|
for hint in [0, 1, 3] {
|
||||||
|
assert_eq!(read_program(&mut &b"abc"[..], hint, limits).unwrap(), b"abc");
|
||||||
|
let error = read_program(&mut &b"abcd"[..], hint, limits).unwrap_err();
|
||||||
|
let CartridgeError::ProgramLoadFailed(error) = error else {
|
||||||
|
panic!("typed PBX admission failure expected")
|
||||||
|
};
|
||||||
|
assert_eq!((error.code, error.reason), (LoadCode::ResourceLimit, LoadReason::Limit));
|
||||||
|
assert_eq!(
|
||||||
|
(error.resource, error.requested, error.limit),
|
||||||
|
(Some(LoadResource::PbxBytes), Some(4), Some(3))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn program_admission_rejects_oversized_metadata_before_reading() {
|
||||||
|
struct MustNotRead;
|
||||||
|
impl Read for MustNotRead {
|
||||||
|
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
|
||||||
|
panic!("must reject before reading")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let limits = LoadLimits { pbx_bytes: 3, ..Default::default() };
|
||||||
|
assert!(matches!(
|
||||||
|
read_program(&mut MustNotRead, 4, limits),
|
||||||
|
Err(CartridgeError::ProgramLoadFailed(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn program_admission_handles_empty_short_and_interrupted_reads() {
|
||||||
|
assert!(read_program(&mut &[][..], 0, LoadLimits::default()).unwrap().is_empty());
|
||||||
|
struct ShortReads {
|
||||||
|
interrupted: bool,
|
||||||
|
remaining: &'static [u8],
|
||||||
|
}
|
||||||
|
impl Read for ShortReads {
|
||||||
|
fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
|
||||||
|
if !self.interrupted {
|
||||||
|
self.interrupted = true;
|
||||||
|
return Err(std::io::ErrorKind::Interrupted.into());
|
||||||
|
}
|
||||||
|
if self.remaining.is_empty() {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
bytes[0] = self.remaining[0];
|
||||||
|
self.remaining = &self.remaining[1..];
|
||||||
|
Ok(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut reader = ShortReads { interrupted: false, remaining: b"abc" };
|
||||||
|
assert_eq!(read_program(&mut reader, 2, LoadLimits::default()).unwrap(), b"abc");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn directory_loader_rejects_oversized_pbx_with_default_limit() {
|
||||||
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(None));
|
||||||
|
let file = fs::OpenOptions::new().write(true).open(dir.path().join("program.pbx")).unwrap();
|
||||||
|
let limit = LoadLimits::default().pbx_bytes;
|
||||||
|
file.set_len(limit + 1).unwrap(); // Sparse file; no giant content allocation.
|
||||||
|
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
|
||||||
|
let CartridgeError::ProgramLoadFailed(error) = error else {
|
||||||
|
panic!("typed PBX admission failure expected")
|
||||||
|
};
|
||||||
|
assert_eq!((error.requested, error.limit), (Some(limit + 1), Some(64 * 1_048_576)));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn load_without_capabilities_defaults_to_none() {
|
fn load_without_capabilities_defaults_to_none() {
|
||||||
let dir = TestCartridgeDir::new(manifest_with_capabilities(None));
|
let dir = TestCartridgeDir::new(manifest_with_capabilities(None));
|
||||||
|
|||||||
Reference in New Issue
Block a user