1use std::collections::BTreeMap;
2use std::fmt;
3use std::sync::Mutex;
4
5use rhai::{
6 AST, ASTFlags, Dynamic, Engine, EvalAltResult, Expr, Module, ModuleResolver, Position, Scope,
7 Shared, Stmt,
8};
9use serde::{Deserialize, Serialize};
10use thiserror::Error;
11
12use crate::{ModuleCompileCache, ScriptSource, ScriptSourceError};
13
14#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
15#[serde(try_from = "String", into = "String")]
16pub struct ModuleId(String);
17
18impl ModuleId {
19 pub fn parse(value: impl Into<String>) -> Result<Self, ModuleIdError> {
26 let value = value.into();
27 validate_module_id(&value)?;
28 Ok(Self(value))
29 }
30
31 #[must_use]
32 pub fn as_str(&self) -> &str {
33 &self.0
34 }
35}
36
37impl fmt::Display for ModuleId {
38 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39 self.0.fmt(formatter)
40 }
41}
42
43impl TryFrom<String> for ModuleId {
44 type Error = ModuleIdError;
45
46 fn try_from(value: String) -> Result<Self, Self::Error> {
47 Self::parse(value)
48 }
49}
50
51impl From<ModuleId> for String {
52 fn from(value: ModuleId) -> Self {
53 value.0
54 }
55}
56
57#[derive(Clone, Debug, Error, Eq, PartialEq)]
58pub enum ModuleIdError {
59 #[error("module id cannot be empty")]
60 Empty,
61 #[error("module id `{0}` must be relative and use `/` separators")]
62 AbsoluteOrPlatformPath(String),
63 #[error("module id `{0}` contains an empty, `.` or `..` segment")]
64 InvalidSegment(String),
65 #[error("module id `{0}` contains unsupported characters")]
66 UnsupportedCharacters(String),
67}
68
69fn validate_module_id(value: &str) -> Result<(), ModuleIdError> {
70 if value.is_empty() {
71 return Err(ModuleIdError::Empty);
72 }
73 if value.starts_with('/')
74 || value.starts_with('\\')
75 || value.contains('\\')
76 || value.contains(':')
77 {
78 return Err(ModuleIdError::AbsoluteOrPlatformPath(value.to_owned()));
79 }
80 if value
81 .split('/')
82 .any(|segment| segment.is_empty() || segment == "." || segment == "..")
83 {
84 return Err(ModuleIdError::InvalidSegment(value.to_owned()));
85 }
86 if !value
87 .chars()
88 .all(|character| character.is_ascii_alphanumeric() || matches!(character, '/' | '_' | '-'))
89 {
90 return Err(ModuleIdError::UnsupportedCharacters(value.to_owned()));
91 }
92 Ok(())
93}
94
95#[derive(Debug, Default)]
100pub struct RestrictedModuleResolver {
101 sources: BTreeMap<ModuleId, String>,
102 compiled: BTreeMap<ModuleId, AST>,
103 resolving: Mutex<Vec<ModuleId>>,
104}
105
106impl RestrictedModuleResolver {
107 #[must_use]
108 pub fn new() -> Self {
109 Self::default()
110 }
111
112 pub fn from_source(source: &impl ScriptSource) -> Result<Self, ScriptSourceError> {
118 let mut resolver = Self::new();
119 for id in source.module_ids() {
120 let asset = source.load(&id)?;
121 resolver.sources.insert(id, asset.source);
123 }
124 Ok(resolver)
125 }
126
127 pub fn from_source_with_cache(
133 source: &impl ScriptSource,
134 cache: &ModuleCompileCache,
135 ) -> Result<Self, ScriptSourceError> {
136 let mut resolver = Self::from_source(source)?;
137 for id in source.module_ids() {
138 let asset = source.load(&id)?;
139 if cache.content_hash(&id) == Some(asset.content_hash)
140 && let Some(ast) = cache.ast(&id)
141 {
142 resolver.compiled.insert(id, ast.clone());
143 }
144 }
145 Ok(resolver)
146 }
147
148 pub fn insert(
154 &mut self,
155 id: impl Into<String>,
156 source: impl Into<String>,
157 ) -> Result<(), ModuleIdError> {
158 self.sources.insert(ModuleId::parse(id)?, source.into());
159 Ok(())
160 }
161
162 #[must_use]
163 pub fn contains(&self, id: &ModuleId) -> bool {
164 self.sources.contains_key(id)
165 }
166
167 fn begin_resolution(
168 &self,
169 id: &ModuleId,
170 position: Position,
171 ) -> Result<(), Box<EvalAltResult>> {
172 let mut stack = self.resolving.lock().map_err(|_| {
173 Box::new(runtime_error(
174 "module resolver lock is poisoned".to_owned(),
175 position,
176 ))
177 })?;
178 if let Some(cycle_start) = stack.iter().position(|active| active == id) {
179 let mut cycle = stack[cycle_start..]
180 .iter()
181 .map(ToString::to_string)
182 .collect::<Vec<_>>();
183 cycle.push(id.to_string());
184 return Err(Box::new(runtime_error(
185 format!("cyclic module import: {}", cycle.join(" -> ")),
186 position,
187 )));
188 }
189 stack.push(id.clone());
190 Ok(())
191 }
192
193 fn end_resolution(&self, id: &ModuleId) {
194 if let Ok(mut stack) = self.resolving.lock() {
195 if stack.last() == Some(id) {
196 stack.pop();
197 } else if let Some(index) = stack.iter().rposition(|active| active == id) {
198 stack.remove(index);
199 }
200 }
201 }
202}
203
204impl ModuleResolver for RestrictedModuleResolver {
205 fn resolve(
206 &self,
207 engine: &Engine,
208 _source: Option<&str>,
209 path: &str,
210 position: Position,
211 ) -> Result<Shared<Module>, Box<EvalAltResult>> {
212 let id = ModuleId::parse(path)
213 .map_err(|error| Box::new(runtime_error(error.to_string(), position)))?;
214 let source = self.sources.get(&id).ok_or_else(|| {
215 if crate::script_lint::is_theme_id(path) {
216 Box::new(runtime_error(
217 format!("`{path}` is {}", crate::script_lint::THEME_IMPORT),
218 position,
219 ))
220 } else {
221 Box::new(EvalAltResult::ErrorModuleNotFound(
222 path.to_owned(),
223 position,
224 ))
225 }
226 })?;
227
228 self.begin_resolution(&id, position)?;
229 let result = (|| {
230 crate::dependency::extract_imports_with_depths(
231 source,
232 engine.max_expr_depth(),
233 engine.max_function_expr_depth(),
234 )
235 .map_err(|error| {
236 Box::new(EvalAltResult::ErrorInModule(
237 path.to_owned(),
238 Box::new(runtime_error(error.to_string(), position)),
239 position,
240 ))
241 })?;
242 let ast = if let Some(ast) = self.compiled.get(&id) {
243 ast.clone()
244 } else {
245 let mut ast = engine.compile(source).map_err(|error| {
246 Box::new(EvalAltResult::ErrorInModule(
247 path.to_owned(),
248 crate::engine::explain_keyword_name(source, error).into(),
249 position,
250 ))
251 })?;
252 crate::engine::validate_runtime_ast(&ast).map_err(|error| {
253 Box::new(EvalAltResult::ErrorInModule(
254 path.to_owned(),
255 Box::new(runtime_error(error.to_string(), position)),
256 position,
257 ))
258 })?;
259 ast.set_source(path);
260 ast
261 };
262 validate_module_init(&id, &ast, position)?;
263 Module::eval_ast_as_new(Scope::new(), &ast, engine)
264 .map(Into::into)
265 .map_err(|error| {
266 Box::new(EvalAltResult::ErrorInModule(
267 path.to_owned(),
268 error,
269 position,
270 ))
271 })
272 })();
273 self.end_resolution(&id);
274 result
275 }
276}
277
278fn validate_module_init(
279 id: &ModuleId,
280 ast: &AST,
281 import_position: Position,
282) -> Result<(), Box<EvalAltResult>> {
283 crate::engine::validate_runtime_ast(ast)
285 .map_err(|error| Box::new(runtime_error(error.to_string(), import_position)))?;
286 let mut definitions = 0_usize;
287 for statement in ast.statements() {
288 let accepted = match statement {
289 Stmt::Noop(_) | Stmt::Import(..) | Stmt::Export(..) => true,
290 Stmt::Var(variable, options, ..) => {
291 options.contains(ASTFlags::CONSTANT) && variable.1.get_literal_value(None).is_some()
292 }
293 Stmt::FnCall(call, ..) if call.name == "define_component" && !call.is_qualified() => {
294 definitions = definitions.saturating_add(1);
295 call.args.len() == 1 && pure_component_definition(&call.args[0])
296 }
297 _ => false,
298 };
299 if !accepted {
300 let position = statement.position();
301 let location = if position.is_none() {
302 String::new()
303 } else {
304 format!(" at {position}")
305 };
306 return Err(Box::new(runtime_error(
307 format!(
308 "module `{id}` init must contain only imports, literal const values, exports, and one direct define_component declaration{location}"
309 ),
310 if position.is_none() {
311 import_position
312 } else {
313 position
314 },
315 )));
316 }
317 }
318 if definitions > 1 {
319 return Err(Box::new(runtime_error(
320 format!("module `{id}` declares {definitions} components; exactly one is allowed"),
321 import_position,
322 )));
323 }
324 Ok(())
325}
326
327fn pure_component_definition(expression: &Expr) -> bool {
328 if expression.get_literal_value(None).is_some() {
329 return true;
330 }
331 match expression {
332 Expr::Array(values, ..) => values.iter().all(pure_component_definition),
333 Expr::Map(entries, ..) => entries
334 .0
335 .iter()
336 .all(|(_, value)| pure_component_definition(value)),
337 Expr::FnCall(call, ..)
338 if (call.name == "Fn" || call.name == crate::invocation::NAMED_FUNCTION)
339 && !call.is_qualified()
340 && call.args.len() == 1
341 && matches!(call.args[0], Expr::StringConstant(..)) =>
342 {
343 true
344 }
345 _ => false,
346 }
347}
348
349fn runtime_error(message: String, position: Position) -> EvalAltResult {
350 EvalAltResult::ErrorRuntime(Dynamic::from(message), position)
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356 use std::cell::Cell;
357 use std::rc::Rc;
358
359 #[test]
360 fn module_ids_reject_escape_paths() {
361 for invalid in [
362 "",
363 "/absolute",
364 "../outside",
365 "a/../b",
366 "C:/ui",
367 "a\\b",
368 "a//b",
369 ] {
370 assert!(ModuleId::parse(invalid).is_err(), "accepted `{invalid}`");
371 }
372 assert_eq!(
373 ModuleId::parse("components/button").unwrap().as_str(),
374 "components/button"
375 );
376 }
377
378 #[test]
379 fn registered_modules_can_be_imported() {
380 let mut resolver = RestrictedModuleResolver::new();
381 resolver
382 .insert("components/greeting", "fn greeting() { \"hello\" }")
383 .unwrap();
384
385 let mut engine = Engine::new();
386 engine.set_module_resolver(resolver);
387 let value: String = engine
388 .eval(
389 r#"
390 import "components/greeting" as greeting;
391 greeting::greeting()
392 "#,
393 )
394 .unwrap();
395 assert_eq!(value, "hello");
396 }
397
398 #[test]
399 fn importing_a_theme_says_themes_are_not_modules() {
400 let mut engine = Engine::new();
401 engine.set_module_resolver(RestrictedModuleResolver::new());
402 let error = engine
403 .run(r#"import "themes/dracula" as dracula;"#)
404 .unwrap_err()
405 .to_string();
406 assert!(
407 error.contains("`themes/dracula` is a theme, not a module"),
408 "{error}"
409 );
410 }
411
412 #[test]
413 fn module_init_rejects_effectful_calls_before_evaluation() {
414 let touched = Rc::new(Cell::new(false));
415 let observer = Rc::clone(&touched);
416 let mut resolver = RestrictedModuleResolver::new();
417 resolver
418 .insert(
419 "components/effectful",
420 "touch(); fn greeting() { \"hello\" }",
421 )
422 .unwrap();
423 let mut engine = Engine::new();
424 engine.register_fn("touch", move || observer.set(true));
425 engine.set_module_resolver(resolver);
426 let error = engine
427 .eval::<Dynamic>("import \"components/effectful\" as effectful;")
428 .unwrap_err();
429 assert!(
430 error.to_string().contains("init must contain only"),
431 "{error}"
432 );
433 assert!(!touched.get());
434 }
435
436 #[test]
437 fn module_init_accepts_literal_consts_and_direct_pure_definition() {
438 let engine = Engine::new();
439 let id = ModuleId::parse("components/pure").unwrap();
440 let ast = engine
441 .compile(
442 r#"
443 const LIMITS = #{ min: 1, values: [2, 3] };
444 define_component(#{
445 metadata: #{ id: "components/pure" },
446 render: Fn("render_Pure")
447 });
448 fn render_Pure(ctx, props) { () }
449 "#,
450 )
451 .unwrap();
452 validate_module_init(&id, &ast, Position::NONE).unwrap();
453 }
454
455 #[test]
456 fn module_init_rejects_mutable_globals_and_computed_definitions() {
457 let engine = Engine::new();
458 let id = ModuleId::parse("components/impure").unwrap();
459 for source in [
460 "let count = 0; fn read() { count }",
461 "fn build() { #{} } define_component(build());",
462 "define_component(#{}); define_component(#{});",
463 ] {
464 let ast = engine.compile(source).unwrap();
465 assert!(validate_module_init(&id, &ast, Position::NONE).is_err());
466 }
467 }
468
469 #[test]
470 fn resolver_reuses_only_content_matching_cached_asts() {
471 let id = ModuleId::parse("components/greeting").unwrap();
472 let source = crate::EmbeddedScriptSource::new(BTreeMap::from([(
473 id.clone(),
474 "fn greeting() { \"hello\" }".to_owned(),
475 )]));
476 let engine = Engine::new();
477 let mut cache = ModuleCompileCache::new();
478 cache.refresh(&engine, &source, [id.clone()]).unwrap();
479 let resolver = RestrictedModuleResolver::from_source_with_cache(&source, &cache).unwrap();
480 assert!(resolver.compiled.contains_key(&id));
481
482 let changed = crate::EmbeddedScriptSource::new(BTreeMap::from([(
483 id.clone(),
484 "fn greeting() { \"changed\" }".to_owned(),
485 )]));
486 let resolver = RestrictedModuleResolver::from_source_with_cache(&changed, &cache).unwrap();
487 assert!(!resolver.compiled.contains_key(&id));
488 }
489
490 #[test]
491 fn missing_modules_are_diagnostic_errors() {
492 let mut engine = Engine::new();
493 engine.set_module_resolver(RestrictedModuleResolver::new());
494 let error = engine
495 .eval::<Dynamic>("import \"components/missing\" as missing;")
496 .unwrap_err();
497 assert!(error.to_string().contains("components/missing"));
498 }
499
500 #[test]
501 fn cyclic_imports_report_the_cycle() {
502 let mut resolver = RestrictedModuleResolver::new();
503 resolver
504 .insert("components/a", "import \"components/b\" as b;")
505 .unwrap();
506 resolver
507 .insert("components/b", "import \"components/a\" as a;")
508 .unwrap();
509
510 let mut engine = Engine::new();
511 engine.set_module_resolver(resolver);
512 let error = engine
513 .eval::<Dynamic>("import \"components/a\" as a;")
514 .unwrap_err();
515 let message = error.to_string();
516 assert!(message.contains("cyclic module import"), "{message}");
517 assert!(message.contains("components/a -> components/b -> components/a"));
518 }
519}