Enforce data limits on host receivers and indexers

This commit is contained in:
dotCooCoo committed 2026-11-26 09:53:08 -08:00
1 parent f040538a39
commit 72984fddaa
3 files changed
+103 -21

No files matched your search

+46 -17
View File
@@ -30,6 +30,7 @@ pub enum Data {
}
/// How much one crossing may carry.
/// Host receivers, their handles and explicit arguments share these limits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DataLimits {
/// How deeply arrays and objects may nest.
@@ -265,9 +266,7 @@ impl Interp {
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
}
let shape = match &self.object(id)?.class {
Class::Host(_) if r.hosted => {
return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into()));
}
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")),
Class::Array { length, .. } => Shape::Array(*length),
Class::Ordinary => {
@@ -299,6 +298,14 @@ impl Interp {
out
}
fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult<Data> {
let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) };
self.charge_entries(r, len.saturating_add(2))?;
let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8);
self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?;
self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into()))
}
fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult<Data> {
self.charge_entries(r, length as usize)?;
let mut items = Vec::with_capacity(length as usize);
@@ -407,16 +414,8 @@ impl Interp {
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, this: &Value, args: &[Value], how: &ArgRead) -> JsResult<Value> {
let data = match how {
ArgRead::Site => site_data(self.call_site()),
ArgRead::Hosted => {
let this = match this {
Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined),
_ => Data::Undefined,
};
let mut data = vec![this];
data.extend(self.read_args(name, args, how)?);
data
}
_ => self.read_args(name, args, how)?,
ArgRead::Hosted => self.read_args(name, Some(this), args, how)?,
_ => self.read_args(name, None, args, how)?,
};
// Only the script's own code, in a run that can pause, can wait for a result, and a host
// class's constructor called with `new` cannot.
@@ -463,7 +462,7 @@ impl Interp {
name: &Rc<str>,
args: &[Value],
) -> JsResult<Value> {
let data = self.read_args(name, args, &ArgRead::Data)?;
let data = self.read_args(name, None, args, &ArgRead::Data)?;
let source = match f(data) {
Ok(Data::String(source)) => source,
Ok(d) => return self.write_data(d, 0, false),
@@ -505,8 +504,8 @@ impl Interp {
r
}
/// The arguments of host function `name` as [`Data`], read as `how` says.
fn read_args(&mut self, name: &Rc<str>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
/// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first.
fn read_args(&mut self, name: &Rc<str>, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
let mut reading = Reading {
limits: self.data_limits,
bytes: 0,
@@ -520,7 +519,14 @@ impl Interp {
ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args),
_ => args,
};
let mut data = Vec::with_capacity(args.len());
let mut data = Vec::with_capacity(args.len() + 1);
if let Some(this) = this {
let this = match this {
Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?,
_ => Data::Undefined,
};
data.push(this);
}
// A conversion can run the script's own `toString`, which may collect garbage.
let mark = self.temp_roots.len();
if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) {
@@ -552,6 +558,29 @@ impl Interp {
Ok(data)
}
pub(crate) fn read_index_args(&mut self, id: ObjId, key: Data, probe: bool) -> JsResult<Vec<Data>> {
let mut reading = Reading {
limits: self.data_limits,
bytes: 0,
entries: 0,
ancestors: Vec::new(),
path: Vec::new(),
function: Rc::from("host indexer"),
hosted: true,
};
let receiver = self.read_host_ref(id, &mut reading)?;
match &key {
Data::String(s) => self.charge_reading(&mut reading, s.encode_utf16().count().saturating_mul(3).saturating_add(2))?,
Data::Number(_) => {}
_ => return Err(Abrupt::Internal("a host indexer key is not a number or string".into())),
}
let mut args = vec![receiver, key];
if probe {
args.push(Data::Bool(true));
}
Ok(args)
}
/// What host error `e` throws, or the limit it ends the run with. A function that waits
/// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal
/// error.
+9 -4
View File
@@ -172,6 +172,12 @@ impl Interp {
Ok(Some(host_ref(&name, &h.handle)))
}
pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult<Option<(usize, usize)>> {
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?;
Ok(Some((name, h.handle.len())))
}
/// The object of a host class that `d`, which a host function gave, stands for.
pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult<Value> {
let Some((name, handle)) = host_ref_parts(d) else {
@@ -220,11 +226,10 @@ impl Interp {
/// gets `true` as a third argument.
pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult<Value> {
self.use_fuel()?;
let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) };
let mut args = vec![this, k];
if probe {
args.push(Data::Bool(true));
if self.host_ref_size(id)?.is_none() {
return Ok(Value::Undefined);
}
let args = self.read_index_args(id, k, probe)?;
match f(args) {
Ok(d) => self.write_hosted(d),
Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())),
+48
View File
@@ -11,6 +11,54 @@ fn realm(fuel: u64) -> Realm {
r
}
#[test]
fn non_finite_indexer_keys_reach_the_host_unchanged() {
let mut r = realm(1_000_000);
let index: HostFunction = Rc::new(|args| Ok(Data::Bool(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite()))));
let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None };
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap();
let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')";
assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into()));
}
#[test]
fn host_receivers_obey_limits_lowered_after_the_object_was_created() {
for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] {
for expression in ["it[0]", "0 in it", "it.method()", "it.take(it)"] {
let mut r = realm(1_000_000);
let calls = Rc::new(Cell::new(0));
let called = calls.clone();
let function: HostFunction = Rc::new(move |_| {
called.set(called.get() + 1);
Ok(Data::Undefined)
});
let class = HostClass {
name: "Indexed".into(),
parent: None,
members: vec![("method".into(), HostMember::Method(function.clone())), ("take".into(), HostMember::Method(function.clone()))],
index: Some(function),
construct: None,
};
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0, 2.0, 3.0]))]).unwrap();
r.set_data_limits(limits);
let source = format!("var result = 'called'; try {{ {expression}; }} catch (e) {{ result = e.name; }} result");
assert_eq!(r.run(&source).unwrap(), JsValue::String("RangeError".into()), "{expression}: {limits:?}");
assert_eq!(calls.get(), 0, "{expression}");
}
}
}
#[test]
fn index_keys_share_the_receivers_data_budget() {
let mut r = realm(1_000_000);
let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(Rc::new(|_| Ok(Data::Bool(true)))), construct: None };
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap();
r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 });
assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true));
let source = "var result = 'called'; try { it[new Array(200).join('x')]; } catch (e) { result = e.name; } result";
assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into()));
}
/// A realm with `host.take(value)`, which records what it was given and returns it.
fn with_take(r: &mut Realm) -> Rc<RefCell<Vec<Data>>> {
let seen: Rc<RefCell<Vec<Data>>> = Rc::default();