Skip to main content

mq_lang/module/
resolver.rs

1#[cfg(feature = "http-import")]
2pub mod http_import;
3#[cfg(feature = "http-import")]
4pub mod http_resolver;
5pub(crate) mod local_fs_resolver;
6#[cfg(feature = "http-import")]
7pub mod lockfile;
8#[cfg(any(feature = "http-import", feature = "http"))]
9pub mod ssrf;
10pub(crate) mod std_resolver;
11
12use crate::module::error::ModuleError;
13use crate::{STANDARD_MODULES, Shared};
14use std::path::PathBuf;
15
16/// Core interface for resolving mq module source code by name.
17pub trait ModuleResolver: Clone + Default {
18    /// Returns the source content of `module_name`.
19    fn resolve(&self, module_name: &str) -> Result<String, ModuleError>;
20    /// Returns the canonical path string for `module_name` (for diagnostics / LSP).
21    fn get_path(&self, module_name: &str) -> Result<String, ModuleError>;
22    /// Returns the filesystem directories this resolver searches.
23    fn search_paths(&self) -> Vec<PathBuf>;
24    /// Replaces the filesystem search directories.
25    fn set_search_paths(&mut self, paths: Vec<PathBuf>);
26    /// Returns the short identifier to store the module under.
27    ///
28    /// For most resolvers this is `module_path` unchanged.  HTTP-based resolvers
29    /// strip the URL prefix and `.mq` suffix so that, for example,
30    /// `github.com/alice/mymod.mq@v1.0` becomes `"mymod"`.
31    fn canonical_name<'a>(&self, module_path: &'a str) -> &'a str {
32        module_path
33    }
34    /// Whether this module's source is embedded in the current binary and therefore cannot
35    /// change during the lifetime of an Engine.
36    fn is_immutable_module(&self, _module_path: &str) -> bool {
37        false
38    }
39}
40
41/// The default resolver, combining standard library, local filesystem, and (optionally) HTTP sources.
42#[derive(Debug, Clone, Default)]
43pub struct DefaultModuleResolver {
44    local_fs_resolver: local_fs_resolver::LocalFsModuleResolver,
45    std_resolver: std_resolver::StdModuleResolver,
46    #[cfg(feature = "http-import-ureq")]
47    http_resolver: http_resolver::HttpModuleResolver<http_resolver::UreqFetcher>,
48}
49
50impl ModuleResolver for DefaultModuleResolver {
51    fn resolve(&self, module_name: &str) -> Result<String, ModuleError> {
52        match self.std_resolver.resolve(module_name) {
53            Ok(content) => return Ok(content),
54            Err(ModuleError::NotFound(_)) => {}
55            Err(e) => return Err(e),
56        }
57
58        match self.local_fs_resolver.resolve(module_name) {
59            Ok(content) => return Ok(content),
60            Err(ModuleError::NotFound(_)) => {}
61            Err(e) => return Err(e),
62        }
63
64        #[cfg(feature = "http-import-ureq")]
65        match self.http_resolver.resolve(module_name) {
66            Ok(content) => return Ok(content),
67            Err(ModuleError::NotFound(_)) => {}
68            Err(e) => return Err(e),
69        }
70
71        Err(ModuleError::NotFound(format!("{}.mq", module_name).into()))
72    }
73
74    fn get_path(&self, module_name: &str) -> Result<String, ModuleError> {
75        match self.std_resolver.get_path(module_name) {
76            Ok(path) => return Ok(path),
77            Err(ModuleError::NotFound(_)) => {}
78            Err(e) => return Err(e),
79        }
80
81        match self.local_fs_resolver.get_path(module_name) {
82            Ok(path) => return Ok(path),
83            Err(ModuleError::NotFound(_)) => {}
84            Err(e) => return Err(e),
85        }
86
87        #[cfg(feature = "http-import-ureq")]
88        match self.http_resolver.get_path(module_name) {
89            Ok(path) => return Ok(path),
90            Err(ModuleError::NotFound(_)) => {}
91            Err(e) => return Err(e),
92        }
93
94        Err(ModuleError::NotFound(format!("{}.mq", module_name).into()))
95    }
96
97    fn search_paths(&self) -> Vec<PathBuf> {
98        self.local_fs_resolver.search_paths()
99    }
100
101    fn set_search_paths(&mut self, paths: Vec<PathBuf>) {
102        self.local_fs_resolver.set_search_paths(paths)
103    }
104
105    fn canonical_name<'a>(&self, module_path: &'a str) -> &'a str {
106        #[cfg(feature = "http-import-ureq")]
107        {
108            if http_import::is_github_url(module_path) || http_import::is_remote_url(module_path) {
109                return self.http_resolver.canonical_name(module_path);
110            }
111        }
112        module_path
113    }
114
115    fn is_immutable_module(&self, module_path: &str) -> bool {
116        STANDARD_MODULES.contains_key(module_path)
117    }
118}
119
120impl DefaultModuleResolver {
121    /// Creates a new resolver with the given filesystem search paths, backed by
122    /// [`NativeIo`](crate::io::NativeIo) for local module resolution, i.e. full,
123    /// ungated disk access, matching this resolver's historical behavior.
124    ///
125    /// An empty `paths` slice falls back to the built-in default search directories.
126    pub fn new(paths: Vec<PathBuf>) -> Self {
127        Self {
128            local_fs_resolver: local_fs_resolver::LocalFsModuleResolver::new(if paths.is_empty() {
129                None
130            } else {
131                Some(paths)
132            }),
133            std_resolver: std_resolver::StdModuleResolver,
134            #[cfg(feature = "http-import-ureq")]
135            http_resolver: http_resolver::HttpModuleResolver::default(),
136        }
137    }
138
139    /// Creates a new resolver whose local filesystem module resolution goes through `io`
140    /// instead of a bare [`NativeIo`](crate::io::NativeIo), e.g. a
141    /// [`SandboxedIo`](crate::io::SandboxedIo) so `include`/`import` respect the same
142    /// read permission as the `read_file`/`write_file`/`http` builtins. HTTP module
143    /// imports are unaffected (still `NativeIo`-only, if the `http-import-ureq` feature
144    /// is enabled).
145    ///
146    /// An empty `paths` slice falls back to the built-in default search directories.
147    pub fn with_io(io: Shared<dyn crate::io::Io>, paths: Vec<PathBuf>) -> Self {
148        Self {
149            local_fs_resolver: local_fs_resolver::LocalFsModuleResolver::with_io(
150                io,
151                if paths.is_empty() { None } else { Some(paths) },
152            ),
153            std_resolver: std_resolver::StdModuleResolver,
154            #[cfg(feature = "http-import-ureq")]
155            http_resolver: http_resolver::HttpModuleResolver::default(),
156        }
157    }
158
159    /// Names of the standard modules and the `.mq` files in the local search directories,
160    /// sorted and without duplicates. Default search directories are used when none were given.
161    pub fn module_names(&self) -> Vec<String> {
162        let mut names = STANDARD_MODULES
163            .keys()
164            .map(|name| name.to_string())
165            .chain(self.local_fs_resolver.module_names())
166            .collect::<Vec<_>>();
167        names.sort();
168        names.dedup();
169        names
170    }
171
172    /// Configures the HTTP resolver with a domain allowlist and request timeout.
173    ///
174    /// An empty `allowed_domains` list restricts access to the built-in default domain
175    /// (`raw.githubusercontent.com/harehare`) only; it does not open up all URLs.
176    /// Only available when the `http-import-ureq` feature is enabled.
177    #[cfg(feature = "http-import-ureq")]
178    pub fn with_http(mut self, allowed_domains: Vec<String>, timeout: Option<std::time::Duration>) -> Self {
179        let lockfile_path = self.http_resolver.lockfile_path();
180        let lockfile_enabled = self.http_resolver.lockfile_enabled();
181        let lockfile_frozen = self.http_resolver.lockfile_frozen();
182        let mut http_resolver = http_resolver::HttpModuleResolver::new(
183            allowed_domains,
184            http_resolver::UreqFetcher::new(timeout.unwrap_or(std::time::Duration::from_secs(10))),
185        );
186        http_resolver.set_lockfile_path(lockfile_path);
187        http_resolver.set_lockfile_enabled(lockfile_enabled);
188        http_resolver.set_lockfile_frozen(lockfile_frozen);
189        self.http_resolver = http_resolver;
190        self
191    }
192
193    /// Replaces the HTTP resolver's domain allowlist.
194    ///
195    /// An empty list restricts access to the built-in default domain only.
196    /// Entries in the form `github.com/{user}/{repo}` are automatically expanded.
197    #[cfg(feature = "http-import-ureq")]
198    pub fn set_allowed_domains(&mut self, domains: Vec<String>) {
199        self.http_resolver.set_allowed_domains(domains);
200    }
201
202    /// Enables or disables HTTP module imports outright, independent of the domain allowlist.
203    #[cfg(feature = "http-import-ureq")]
204    pub fn set_http_import_enabled(&mut self, enabled: bool) {
205        self.http_resolver.set_enabled(enabled);
206    }
207
208    /// Clears all locally-cached HTTP module files (mutable/HEAD only).
209    #[cfg(feature = "http-import-ureq")]
210    pub fn clear_http_cache(&self) -> Result<(), crate::module::error::ModuleError> {
211        self.http_resolver.clear_cache()
212    }
213
214    /// Clears all HTTP module cache including versioned modules.
215    #[cfg(feature = "http-import-ureq")]
216    pub fn clear_http_cache_all(&self) -> Result<(), crate::module::error::ModuleError> {
217        self.http_resolver.clear_all_cache()
218    }
219
220    /// Enables or disables the `mq.lock` integrity check/update for HTTP imports.
221    #[cfg(feature = "http-import-ureq")]
222    pub fn set_lockfile_enabled(&mut self, enabled: bool) {
223        self.http_resolver.set_lockfile_enabled(enabled);
224    }
225
226    /// When `true`, a URL with no existing `mq.lock` entry is a hard error instead of being
227    /// recorded as a new entry. See `http_resolver::UreqFetcher::set_lockfile_frozen`.
228    #[cfg(feature = "http-import-ureq")]
229    pub fn set_lockfile_frozen(&mut self, frozen: bool) {
230        self.http_resolver.set_lockfile_frozen(frozen);
231    }
232
233    /// Sets the path used for `mq.lock`.
234    #[cfg(feature = "http-import-ureq")]
235    pub fn set_lockfile_path(&mut self, path: PathBuf) {
236        self.http_resolver.set_lockfile_path(path);
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use rstest::rstest;
243    use tempfile::TempDir;
244
245    use super::*;
246
247    fn write_module(dir: &TempDir, name: &str, content: &str) {
248        std::fs::write(dir.path().join(format!("{}.mq", name)), content).unwrap();
249    }
250
251    #[rstest]
252    #[case("csv")]
253    #[case("gron")]
254    #[case("json")]
255    #[case("yaml")]
256    #[case("toml")]
257    #[case("md")]
258    fn test_resolve_standard_module(#[case] name: &str) {
259        let resolver = DefaultModuleResolver::default();
260        assert!(resolver.resolve(name).is_ok());
261    }
262
263    #[rstest]
264    #[case("csv")]
265    #[case("json")]
266    #[case("md")]
267    fn test_get_path_standard_module(#[case] name: &str) {
268        let resolver = DefaultModuleResolver::default();
269        assert!(resolver.get_path(name).is_ok());
270    }
271
272    #[rstest]
273    #[case("nonexistent_xyz")]
274    fn test_resolve_unknown_module_returns_error(#[case] name: &str) {
275        let resolver = DefaultModuleResolver::new(vec![]);
276        assert!(resolver.resolve(name).is_err());
277    }
278
279    #[test]
280    fn test_resolve_local_module() {
281        let dir = TempDir::new().unwrap();
282        write_module(&dir, "mymod", "def foo(): 1;");
283
284        let resolver = DefaultModuleResolver::new(vec![dir.path().to_path_buf()]);
285        assert!(resolver.resolve("mymod").is_ok());
286    }
287
288    #[test]
289    fn test_std_takes_priority_over_local() {
290        let dir = TempDir::new().unwrap();
291        write_module(&dir, "csv", "def foo(): 1;");
292
293        let resolver = DefaultModuleResolver::new(vec![dir.path().to_path_buf()]);
294        let content = resolver.resolve("csv").unwrap();
295        assert!(!content.contains("def foo(): 1;"));
296    }
297
298    #[test]
299    fn test_search_paths_empty_uses_defaults() {
300        let resolver = DefaultModuleResolver::new(vec![]);
301        assert!(!resolver.search_paths().is_empty());
302    }
303
304    #[test]
305    fn test_search_paths_custom() {
306        let paths = vec![PathBuf::from("/custom")];
307        let resolver = DefaultModuleResolver::new(paths.clone());
308        assert_eq!(resolver.search_paths(), paths);
309    }
310
311    #[test]
312    fn test_set_search_paths() {
313        let mut resolver = DefaultModuleResolver::new(vec![]);
314        let paths = vec![PathBuf::from("/new")];
315        resolver.set_search_paths(paths.clone());
316        assert_eq!(resolver.search_paths(), paths);
317    }
318
319    #[cfg(feature = "http-import-ureq")]
320    #[rstest]
321    #[case("https://nonexistent.invalid/foo.mq")]
322    fn test_http_url_not_in_local(#[case] url: &str) {
323        let resolver = DefaultModuleResolver::new(vec![]);
324        assert!(resolver.resolve(url).is_err());
325    }
326
327    #[cfg(feature = "http-import-ureq")]
328    #[test]
329    fn test_set_http_import_enabled_blocks_resolution() {
330        let mut resolver = DefaultModuleResolver::new(vec![]);
331        resolver.set_http_import_enabled(false);
332
333        let err = resolver.resolve("github.com/harehare/lisp").unwrap_err();
334        assert!(
335            err.to_string().contains("HTTP module imports are disabled"),
336            "error was: {err}"
337        );
338    }
339
340    #[cfg(feature = "http-import-ureq")]
341    #[test]
342    fn test_with_http_normalizes_github_domains() {
343        let resolver = DefaultModuleResolver::new(vec![]).with_http(vec!["github.com/alice/myrepo".to_string()], None);
344        assert!(
345            resolver
346                .http_resolver
347                .is_allowed_domain("https://raw.githubusercontent.com/alice/myrepo/HEAD/mod.mq")
348        );
349        assert!(
350            !resolver
351                .http_resolver
352                .is_allowed_domain("https://raw.githubusercontent.com/alice/other/HEAD/mod.mq")
353        );
354    }
355
356    #[cfg(feature = "http-import-ureq")]
357    #[test]
358    fn test_with_http_preserves_previously_set_lockfile_config() {
359        let mut resolver = DefaultModuleResolver::new(vec![]);
360        resolver.set_lockfile_path(PathBuf::from("custom/mq.lock"));
361        resolver.set_lockfile_enabled(false);
362
363        let resolver = resolver.with_http(vec![], None);
364
365        assert_eq!(resolver.http_resolver.lockfile_path(), PathBuf::from("custom/mq.lock"));
366        assert!(!resolver.http_resolver.lockfile_enabled());
367    }
368
369    #[cfg(feature = "http-import-ureq")]
370    #[test]
371    fn test_set_allowed_domains_normalizes_github_domains() {
372        let mut resolver = DefaultModuleResolver::new(vec![]);
373        resolver.set_allowed_domains(vec!["github.com/bob/myrepo".to_string()]);
374        assert!(
375            resolver
376                .http_resolver
377                .is_allowed_domain("https://raw.githubusercontent.com/bob/myrepo/HEAD/mod.mq")
378        );
379        assert!(
380            !resolver
381                .http_resolver
382                .is_allowed_domain("https://raw.githubusercontent.com/bob/other/HEAD/mod.mq")
383        );
384    }
385}