//! A manifest binds exact image bytes and requests rights; trusted caller policy //! supplies the authority. A matching SHA-256 is identity, not a signature. use sha2::{Digest,Sha256}; use super::handles::Rights; pub const WIRE_BYTES:usize=64; pub const MAX_IMAGE_BYTES:usize=64*1024; pub const MAGIC:[u8;8]=*b"TRKMAN1\0"; pub const NATIVE_ABI:u16=1; #[derive(Clone,Copy,Debug,PartialEq,Eq)]pub enum Error{Length,Magic,Format,Reserved,Abi,Rights,ImageSize,Hash,Denied} #[derive(Clone,Copy,Debug,PartialEq,Eq)]pub struct Manifest{abi:u16,file_rights:Rights,image_bytes:usize,sha256:[u8;32]} fn u16_at(b:&[u8],at:usize)->u16{u16::from_le_bytes(b[at..at+2].try_into().expect("fixed manifest"))} impl Manifest{ pub fn parse(wire:&[u8])->Result{ if wire.len()!=WIRE_BYTES{return Err(Error::Length);}if wire[..8]!=MAGIC{return Err(Error::Magic);}if u16_at(wire,8)!=1{return Err(Error::Format);} if wire[56..64].iter().any(|v|*v!=0){return Err(Error::Reserved);}let abi=u16_at(wire,10);if abi!=NATIVE_ABI{return Err(Error::Abi);} let bits=u32::from_le_bytes(wire[12..16].try_into().unwrap());let file_rights=match bits{1=>Rights::READ,2=>Rights::WRITE,3=>Rights::READ_WRITE,_=>return Err(Error::Rights)}; let bytes=u64::from_le_bytes(wire[16..24].try_into().unwrap());if bytes==0||bytes>MAX_IMAGE_BYTES as u64{return Err(Error::ImageSize);} Ok(Self{abi,file_rights,image_bytes:bytes as usize,sha256:wire[24..56].try_into().unwrap()}) } pub fn abi(self)->u16{self.abi} pub fn requested_file_rights(self)->Rights{self.file_rights} pub fn image_sha256(self)->[u8;32]{self.sha256} pub fn image_bytes(self)->usize{self.image_bytes} pub fn verify<'a>(self,image:&'a[u8],allowed_file_rights:Rights)->Result,Error>{ if image.len()!=self.image_bytes{return Err(Error::ImageSize);}let actual:[u8;32]=Sha256::digest(image).into(); if actual!=self.sha256{return Err(Error::Hash);} if !self.file_rights.is_nonempty_subset_of(allowed_file_rights){return Err(Error::Denied);} Ok(Verified{image,manifest:self}) } } /// This private construction binds the borrowed immutable image to its validated /// ABI/hash and policy-limited request. It does not itself mint a file handle. #[derive(Debug,PartialEq,Eq)]pub struct Verified<'a>{image:&'a[u8],manifest:Manifest} impl<'a>Verified<'a>{pub fn image(&self)->&'a[u8]{self.image}pub fn manifest(&self)->Manifest{self.manifest}} #[derive(Debug,PartialEq,Eq)]pub enum PrepareError{Manifest(Error),Resource(E)} pub fn prepare<'a,T,E>(wire:&[u8],image:&'a[u8],allowed:Rights,acquire:impl FnOnce(Verified<'a>)->Result)->Result>{ let verified=Manifest::parse(wire).and_then(|m|m.verify(image,allowed)).map_err(PrepareError::Manifest)?; acquire(verified).map_err(PrepareError::Resource) }