Skip to main content

eggsec_nse/resolver/
mod.rs

1//! Hardened script and module resolver for NSE.
2//!
3//! All script and module loading flows through `ScriptResolver` to enforce:
4//! - Explicit script source kinds
5//! - Profile-derived script and module policies
6//! - Strict module-name grammar before filesystem access
7//! - Canonical path validation under approved roots
8//! - Symlink-aware containment checks
9//! - File extension allowlists
10//! - Maximum script and module sizes
11//! - Structured diagnostics for load behavior
12
13pub mod registry;
14
15use std::fmt;
16use std::path::{Path, PathBuf};
17
18use crate::limits::NseExecutionLimits;
19use crate::profile::{NseModulePolicy, NseScriptPolicy};
20
21// ---------------------------------------------------------------------------
22// Module name validation
23// ---------------------------------------------------------------------------
24
25/// Validated NSE module name. Guaranteed to contain only safe characters
26/// and pass all containment checks.
27#[derive(Debug, Clone, PartialEq, Eq, Hash)]
28pub struct NseModuleName(String);
29
30impl NseModuleName {
31    /// The validated module name string.
32    pub fn as_str(&self) -> &str {
33        &self.0
34    }
35
36    /// Consume and return the inner string.
37    pub fn into_inner(self) -> String {
38        self.0
39    }
40}
41
42impl fmt::Display for NseModuleName {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(f, "{}", self.0)
45    }
46}
47
48/// Maximum module name length.
49const MAX_MODULE_NAME_LEN: usize = 256;
50
51/// Validate a module name against the strict grammar.
52///
53/// Rules:
54/// - Non-empty
55/// - ASCII letters, digits, `_`, `-`, `.`
56/// - Must not start with `.`
57/// - Must not contain `..` as a path segment
58/// - Must not contain `/`, `\`, `:`, `~`, null bytes, glob chars,
59///   shell expansion chars, or whitespace
60/// - Length <= 256
61pub fn validate_nse_module_name(name: &str) -> Result<NseModuleName, NseLoadError> {
62    if name.is_empty() {
63        return Err(NseLoadError::InvalidModuleName {
64            name: name.to_string(),
65            reason: "module name is empty".to_string(),
66        });
67    }
68
69    if name.len() > MAX_MODULE_NAME_LEN {
70        return Err(NseLoadError::InvalidModuleName {
71            name: name.to_string(),
72            reason: format!(
73                "module name exceeds maximum length ({} > {})",
74                name.len(),
75                MAX_MODULE_NAME_LEN
76            ),
77        });
78    }
79
80    if name.starts_with('.') {
81        return Err(NseLoadError::InvalidModuleName {
82            name: name.to_string(),
83            reason: "module name must not start with '.'".to_string(),
84        });
85    }
86
87    // Check for path traversal markers
88    if name.contains("..") {
89        return Err(NseLoadError::InvalidModuleName {
90            name: name.to_string(),
91            reason: "module name must not contain '..'".to_string(),
92        });
93    }
94
95    // Check for forbidden characters
96    for ch in name.chars() {
97        if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' && ch != '.' {
98            return Err(NseLoadError::InvalidModuleName {
99                name: name.to_string(),
100                reason: format!("module name contains forbidden character '{}'", ch),
101            });
102        }
103    }
104
105    Ok(NseModuleName(name.to_string()))
106}
107
108// ---------------------------------------------------------------------------
109// Script source model
110// ---------------------------------------------------------------------------
111
112/// Explicit script source kind. All script loading must declare its source.
113#[derive(Debug, Clone)]
114pub enum NseScriptSource {
115    /// Built-in script shipped with eggsec-nse.
116    Builtin { name: String },
117    /// Future: trusted bundled or generated script registry.
118    TrustedRegistry { name: String },
119    /// User-provided script file on disk.
120    File { path: PathBuf },
121    /// Inline script content (tests, manual CLI).
122    InlineManual { label: String, content: String },
123}
124
125impl fmt::Display for NseScriptSource {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        match self {
128            Self::Builtin { name } => write!(f, "builtin:{}", name),
129            Self::TrustedRegistry { name } => write!(f, "registry:{}", name),
130            Self::File { path } => write!(f, "file:{}", path.display()),
131            Self::InlineManual { label, .. } => write!(f, "inline:{}", label),
132        }
133    }
134}
135
136// ---------------------------------------------------------------------------
137// Load error type
138// ---------------------------------------------------------------------------
139
140/// Structured error for script/module load failures.
141#[derive(Debug, Clone)]
142pub enum NseLoadError {
143    /// Script or module not found in any allowed location.
144    NotFound { source: NseScriptSource },
145    /// Script file rejected by profile policy.
146    BlockedByPolicy {
147        source: NseScriptSource,
148        reason: String,
149    },
150    /// Path is outside all approved roots.
151    OutsideRoot {
152        path: PathBuf,
153        approved_roots: Vec<PathBuf>,
154    },
155    /// Symlink resolves outside approved roots.
156    SymlinkEscape { path: PathBuf, resolved: PathBuf },
157    /// File has invalid or disallowed extension.
158    InvalidExtension { path: PathBuf, extension: String },
159    /// Content exceeds size limit.
160    Oversized {
161        source: NseScriptSource,
162        size: usize,
163        limit: usize,
164    },
165    /// Module name failed grammar validation.
166    InvalidModuleName { name: String, reason: String },
167    /// Filesystem I/O error during load.
168    IoError { path: PathBuf, error: String },
169    /// Content failed to evaluate in Lua.
170    EvalError {
171        source: NseScriptSource,
172        error: String,
173    },
174}
175
176impl fmt::Display for NseLoadError {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match self {
179            Self::NotFound { source } => write!(f, "not found: {}", source),
180            Self::BlockedByPolicy { source, reason } => {
181                write!(f, "blocked by policy: {} ({})", source, reason)
182            }
183            Self::OutsideRoot {
184                path,
185                approved_roots,
186            } => write!(
187                f,
188                "path outside approved roots: {} (roots: {:?})",
189                path.display(),
190                approved_roots
191            ),
192            Self::SymlinkEscape { path, resolved } => write!(
193                f,
194                "symlink escapes approved roots: {} -> {}",
195                path.display(),
196                resolved.display()
197            ),
198            Self::InvalidExtension { path, extension } => {
199                write!(f, "invalid extension '{}': {}", extension, path.display())
200            }
201            Self::Oversized {
202                source,
203                size,
204                limit,
205            } => write!(
206                f,
207                "oversized content from {}: {} bytes (limit: {})",
208                source, size, limit
209            ),
210            Self::InvalidModuleName { name, reason } => {
211                write!(f, "invalid module name '{}': {}", name, reason)
212            }
213            Self::IoError { path, error } => {
214                write!(f, "I/O error reading {}: {}", path.display(), error)
215            }
216            Self::EvalError { source, error } => {
217                write!(f, "eval error for {}: {}", source, error)
218            }
219        }
220    }
221}
222
223impl std::error::Error for NseLoadError {}
224
225#[cfg(feature = "nse")]
226impl From<NseLoadError> for mlua::Error {
227    fn from(e: NseLoadError) -> Self {
228        mlua::Error::RuntimeError(e.to_string())
229    }
230}
231
232// ---------------------------------------------------------------------------
233// Load diagnostic
234// ---------------------------------------------------------------------------
235
236/// Diagnostic emitted during script/module loading for visibility.
237#[derive(Debug, Clone)]
238pub enum NseLoadDiagnostic {
239    /// A script source was resolved successfully.
240    Resolved {
241        source: NseScriptSource,
242        bytes: usize,
243    },
244    /// A script source was blocked by policy.
245    Blocked {
246        source: NseScriptSource,
247        reason: String,
248    },
249    /// A path was rejected for being outside roots.
250    OutsideRoot { path: PathBuf, root: PathBuf },
251    /// A symlink was rejected.
252    SymlinkRejected { path: PathBuf, resolved: PathBuf },
253    /// A module name was rejected before filesystem lookup.
254    ModuleNameRejected { name: String, reason: String },
255    /// Content was rejected for exceeding size limit.
256    OversizedRejected {
257        source: NseScriptSource,
258        size: usize,
259        limit: usize,
260    },
261    /// Filesystem module load failed (reported, not silently skipped).
262    ModuleLoadFailed {
263        name: String,
264        path: PathBuf,
265        error: String,
266    },
267}
268
269// ---------------------------------------------------------------------------
270// Resolved types
271// ---------------------------------------------------------------------------
272
273/// A resolved script with its content and metadata.
274#[derive(Debug, Clone)]
275pub struct ResolvedNseScript {
276    /// The original source.
277    pub source: NseScriptSource,
278    /// The script content.
279    pub content: String,
280    /// Size in bytes.
281    pub size: usize,
282}
283
284/// A resolved module with its content and metadata.
285#[derive(Debug, Clone)]
286pub struct ResolvedNseModule {
287    /// The validated module name.
288    pub name: NseModuleName,
289    /// The module content.
290    pub content: String,
291    /// Size in bytes.
292    pub size: usize,
293    /// The path it was loaded from (if filesystem).
294    pub path: Option<PathBuf>,
295}
296
297// ---------------------------------------------------------------------------
298// File extension allowlist
299// ---------------------------------------------------------------------------
300
301/// Allowed file extensions for scripts and modules.
302const ALLOWED_SCRIPT_EXTENSIONS: &[&str] = &["lua", "nse"];
303const ALLOWED_MODULE_EXTENSIONS: &[&str] = &["lua", "nse"];
304
305fn has_allowed_extension(path: &Path, allowed: &[&str]) -> bool {
306    path.extension()
307        .and_then(|e| e.to_str())
308        .map(|ext| allowed.contains(&ext))
309        .unwrap_or(false)
310}
311
312// ---------------------------------------------------------------------------
313// Path containment
314// ---------------------------------------------------------------------------
315
316/// Canonicalize a path. Returns `None` if the path cannot be canonicalized
317/// (e.g., does not exist and parent cannot be resolved).
318fn try_canonicalize(path: &Path) -> Option<PathBuf> {
319    path.canonicalize().ok()
320}
321
322/// Canonicalize a root path. Returns `Some(canonical)` only if the path
323/// can be fully resolved. Roots that cannot be canonicalized are rejected
324/// to prevent string-prefix fallback authorization.
325fn canonicalize_root(path: &Path) -> Option<PathBuf> {
326    path.canonicalize().ok()
327}
328
329/// Check whether a canonical path is under an approved root using
330/// path-component semantics (not string prefix).
331fn is_under_root(canonical_path: &Path, canonical_root: &Path) -> bool {
332    canonical_path.strip_prefix(canonical_root).is_ok()
333}
334
335/// Validate that an existing file path is under one of the approved roots.
336/// Returns the canonical path if allowed, or an error.
337///
338/// **Read-path helper**: this function only authorizes paths whose canonical
339/// form is fully resolvable. Non-existent files cannot be authorized here.
340/// Use [`validate_parent_under_roots`] only when write/create semantics
341/// require authorizing a path whose target does not yet exist; that helper
342/// is intentionally separate and must never be used for read authorization.
343///
344/// For existing files, the full canonical path is checked against canonical roots
345/// using path-component semantics (`Path::strip_prefix`).
346/// If the file does not exist or the canonical path is not under any approved
347/// root, the path is rejected.
348fn validate_existing_path_under_roots(
349    path: &Path,
350    approved_roots: &[PathBuf],
351) -> Result<PathBuf, NseLoadError> {
352    let canonical = try_canonicalize(path).ok_or_else(|| NseLoadError::IoError {
353        path: path.to_path_buf(),
354        error: "path does not exist or cannot be canonicalized".to_string(),
355    })?;
356
357    for root in approved_roots {
358        if let Some(canonical_root) = canonicalize_root(root) {
359            if is_under_root(&canonical, &canonical_root) {
360                return Ok(canonical);
361            }
362        }
363    }
364
365    Err(NseLoadError::OutsideRoot {
366        path: path.to_path_buf(),
367        approved_roots: approved_roots.to_vec(),
368    })
369}
370
371/// Validate that a parent directory is under one of the approved roots,
372/// returning the canonical child path constructed from that parent.
373///
374/// **Write-path helper**: this helper authorizes a path by canonicalizing
375/// only the parent directory and constructing the child path beneath it.
376/// It is intended for create/write semantics where the target does not yet
377/// exist. **It must not be used for read authorization** — read paths must
378/// always resolve to existing files via [`validate_existing_path_under_roots`].
379#[allow(dead_code)]
380fn validate_parent_under_roots(
381    path: &Path,
382    approved_roots: &[PathBuf],
383) -> Result<PathBuf, NseLoadError> {
384    let parent = path.parent().ok_or_else(|| NseLoadError::OutsideRoot {
385        path: path.to_path_buf(),
386        approved_roots: approved_roots.to_vec(),
387    })?;
388
389    let canonical_parent = try_canonicalize(parent).ok_or_else(|| NseLoadError::OutsideRoot {
390        path: path.to_path_buf(),
391        approved_roots: approved_roots.to_vec(),
392    })?;
393
394    for root in approved_roots {
395        if let Some(canonical_root) = canonicalize_root(root) {
396            if is_under_root(&canonical_parent, &canonical_root) {
397                return Ok(canonical_parent.join(path.file_name().unwrap_or_default()));
398            }
399        }
400    }
401
402    Err(NseLoadError::OutsideRoot {
403        path: path.to_path_buf(),
404        approved_roots: approved_roots.to_vec(),
405    })
406}
407
408/// Validate that a symlink resolves within approved roots.
409fn validate_symlink_containment(
410    path: &Path,
411    approved_roots: &[PathBuf],
412) -> Result<PathBuf, NseLoadError> {
413    let canonical = path.canonicalize().map_err(|e| NseLoadError::IoError {
414        path: path.to_path_buf(),
415        error: e.to_string(),
416    })?;
417
418    for root in approved_roots {
419        if let Some(canonical_root) = canonicalize_root(root) {
420            if is_under_root(&canonical, &canonical_root) {
421                return Ok(canonical);
422            }
423        }
424    }
425
426    Err(NseLoadError::SymlinkEscape {
427        path: path.to_path_buf(),
428        resolved: canonical,
429    })
430}
431
432// ---------------------------------------------------------------------------
433// Built-in script registry
434// ---------------------------------------------------------------------------
435
436/// Names of all built-in scripts.
437const BUILTIN_SCRIPT_NAMES: &[&str] = &[
438    "default",
439    "discovery",
440    "banner",
441    "http-headers",
442    "dns-check",
443    "ssl-cert",
444];
445
446/// Check whether a name refers to a built-in script.
447pub fn is_builtin_script(name: &str) -> bool {
448    BUILTIN_SCRIPT_NAMES.contains(&name)
449}
450
451// ---------------------------------------------------------------------------
452// ScriptResolver
453// ---------------------------------------------------------------------------
454
455/// Hardened script and module resolver.
456///
457/// Enforces profile-derived policies, module name grammar, path containment,
458/// size limits, and structured diagnostics for all loading operations.
459pub struct ScriptResolver {
460    script_policy: NseScriptPolicy,
461    module_policy: NseModulePolicy,
462    limits: NseExecutionLimits,
463    diagnostics: Vec<NseLoadDiagnostic>,
464}
465
466impl ScriptResolver {
467    /// Create a new resolver from profile policies and execution limits.
468    pub fn new(
469        script_policy: NseScriptPolicy,
470        module_policy: NseModulePolicy,
471        limits: NseExecutionLimits,
472    ) -> Self {
473        Self {
474            script_policy,
475            module_policy,
476            limits,
477            diagnostics: Vec::new(),
478        }
479    }
480
481    /// Get accumulated diagnostics.
482    pub fn diagnostics(&self) -> &[NseLoadDiagnostic] {
483        &self.diagnostics
484    }
485
486    /// Take accumulated diagnostics (consumes them).
487    pub fn take_diagnostics(&mut self) -> Vec<NseLoadDiagnostic> {
488        std::mem::take(&mut self.diagnostics)
489    }
490
491    /// Clear accumulated diagnostics.
492    pub fn clear_diagnostics(&mut self) {
493        self.diagnostics.clear();
494    }
495
496    // -- Script resolution --
497
498    /// Resolve a script source to content.
499    ///
500    /// Enforces policy, path containment, size limits, and emits diagnostics.
501    pub fn resolve_script(
502        &mut self,
503        source: NseScriptSource,
504    ) -> Result<ResolvedNseScript, NseLoadError> {
505        match &source {
506            NseScriptSource::Builtin { name } => self.resolve_builtin(name.clone()),
507            NseScriptSource::TrustedRegistry { name: _ } => {
508                // Future: look up in registry
509                Err(NseLoadError::NotFound {
510                    source: source.clone(),
511                })
512            }
513            NseScriptSource::File { path } => self.resolve_script_file(path.clone(), source),
514            NseScriptSource::InlineManual { label, content } => {
515                self.resolve_inline(label.clone(), content.clone(), source)
516            }
517        }
518    }
519
520    fn resolve_builtin(&mut self, name: String) -> Result<ResolvedNseScript, NseLoadError> {
521        if !self.script_policy.allow_builtin_scripts {
522            return Err(NseLoadError::BlockedByPolicy {
523                source: NseScriptSource::Builtin { name: name.clone() },
524                reason: "builtin scripts not allowed by profile".to_string(),
525            });
526        }
527
528        // Built-in content is provided by the caller via get_builtin_script()
529        // The resolver validates policy; the actual content is injected externally.
530        // For now, return a marker - the caller fills in content.
531        let source = NseScriptSource::Builtin { name };
532        let content = String::new(); // Caller replaces with actual content
533        let size = 0;
534
535        self.diagnostics.push(NseLoadDiagnostic::Resolved {
536            source: source.clone(),
537            bytes: size,
538        });
539
540        Ok(ResolvedNseScript {
541            source,
542            content,
543            size,
544        })
545    }
546
547    fn resolve_script_file(
548        &mut self,
549        path: PathBuf,
550        source: NseScriptSource,
551    ) -> Result<ResolvedNseScript, NseLoadError> {
552        // 1. Check policy allows script files
553        if !self.script_policy.allow_script_files {
554            self.diagnostics.push(NseLoadDiagnostic::Blocked {
555                source: source.clone(),
556                reason: "script files not allowed by profile".to_string(),
557            });
558            return Err(NseLoadError::BlockedByPolicy {
559                source: source.clone(),
560                reason: "script files not allowed by profile".to_string(),
561            });
562        }
563
564        // 2. Check file exists
565        if !path.exists() {
566            return Err(NseLoadError::NotFound {
567                source: source.clone(),
568            });
569        }
570
571        // 3. Check extension
572        if !has_allowed_extension(&path, ALLOWED_SCRIPT_EXTENSIONS) {
573            let ext = path
574                .extension()
575                .and_then(|e| e.to_str())
576                .unwrap_or("")
577                .to_string();
578            return Err(NseLoadError::InvalidExtension {
579                path: path.clone(),
580                extension: ext,
581            });
582        }
583
584        // 4. Validate path under approved roots (if any are specified).
585        //
586        // Empty roots + manual profile means unrestricted manual file selection
587        // (see `NseScriptPolicy` doc comments for the empty-roots semantic
588        // table); skip the root check entirely. Non-empty roots always require
589        // canonical containment via the read-path helper.
590        if !self.script_policy.allowed_script_roots.is_empty() {
591            validate_existing_path_under_roots(&path, &self.script_policy.allowed_script_roots)?;
592        }
593
594        // 5. Validate symlink containment — only when roots are configured.
595        // Without configured roots, symlink containment is not enforceable
596        // and would incorrectly reject normal files under manual permissive.
597        let canonical = if self.script_policy.allowed_script_roots.is_empty() {
598            // Manual unrestricted: canonicalize the existing file (no root containment).
599            path.canonicalize().map_err(|e| NseLoadError::IoError {
600                path: path.clone(),
601                error: e.to_string(),
602            })?
603        } else {
604            validate_symlink_containment(&path, &self.script_policy.allowed_script_roots)?
605        };
606
607        // 6. Read content
608        let content = std::fs::read_to_string(&canonical).map_err(|e| NseLoadError::IoError {
609            path: canonical.clone(),
610            error: e.to_string(),
611        })?;
612
613        // 7. Check size limit
614        let size = content.len();
615        if let Some(max) = self.limits.max_script_bytes {
616            if size > max {
617                self.diagnostics.push(NseLoadDiagnostic::OversizedRejected {
618                    source: source.clone(),
619                    size,
620                    limit: max,
621                });
622                return Err(NseLoadError::Oversized {
623                    source: source.clone(),
624                    size,
625                    limit: max,
626                });
627            }
628        }
629        if let Some(max) = self.script_policy.max_script_bytes {
630            if size > max {
631                self.diagnostics.push(NseLoadDiagnostic::OversizedRejected {
632                    source: source.clone(),
633                    size,
634                    limit: max,
635                });
636                return Err(NseLoadError::Oversized {
637                    source: source.clone(),
638                    size,
639                    limit: max,
640                });
641            }
642        }
643
644        self.diagnostics.push(NseLoadDiagnostic::Resolved {
645            source: source.clone(),
646            bytes: size,
647        });
648
649        Ok(ResolvedNseScript {
650            source,
651            content,
652            size,
653        })
654    }
655
656    fn resolve_inline(
657        &mut self,
658        _label: String,
659        content: String,
660        source: NseScriptSource,
661    ) -> Result<ResolvedNseScript, NseLoadError> {
662        let size = content.len();
663
664        // Check size limit for inline scripts
665        if let Some(max) = self.limits.max_script_bytes {
666            if size > max {
667                self.diagnostics.push(NseLoadDiagnostic::OversizedRejected {
668                    source: source.clone(),
669                    size,
670                    limit: max,
671                });
672                return Err(NseLoadError::Oversized {
673                    source: source.clone(),
674                    size,
675                    limit: max,
676                });
677            }
678        }
679        if let Some(max) = self.script_policy.max_script_bytes {
680            if size > max {
681                self.diagnostics.push(NseLoadDiagnostic::OversizedRejected {
682                    source: source.clone(),
683                    size,
684                    limit: max,
685                });
686                return Err(NseLoadError::Oversized {
687                    source: source.clone(),
688                    size,
689                    limit: max,
690                });
691            }
692        }
693
694        self.diagnostics.push(NseLoadDiagnostic::Resolved {
695            source: source.clone(),
696            bytes: size,
697        });
698
699        Ok(ResolvedNseScript {
700            source,
701            content,
702            size,
703        })
704    }
705
706    // -- Module resolution --
707
708    /// Validate a module name and resolve it from filesystem roots.
709    ///
710    /// Returns `None` if the module should be loaded from built-in registry
711    /// (caller handles that). Returns `Some(ResolvedNseModule)` for filesystem modules.
712    pub fn resolve_module(
713        &mut self,
714        name: &str,
715    ) -> Result<Option<ResolvedNseModule>, NseLoadError> {
716        // 1. Validate module name grammar
717        let validated_name = validate_nse_module_name(name).inspect_err(|e| {
718            self.diagnostics
719                .push(NseLoadDiagnostic::ModuleNameRejected {
720                    name: name.to_string(),
721                    reason: e.to_string(),
722                });
723        })?;
724
725        // 2. Check if filesystem modules are allowed
726        if !self.module_policy.allow_filesystem_modules {
727            return Ok(None);
728        }
729
730        // 3. If no module roots are configured, can't load from filesystem
731        if self.module_policy.allowed_module_roots.is_empty() {
732            return Ok(None);
733        }
734
735        // 4. Try to find the module in approved roots
736        for root in &self.module_policy.allowed_module_roots {
737            let Some(canonical_root) = canonicalize_root(root) else {
738                // Root cannot be canonicalized — skip it (do not fall back to string prefix)
739                continue;
740            };
741
742            for ext in ALLOWED_MODULE_EXTENSIONS {
743                let candidate = canonical_root.join(format!("{}.{}", validated_name.as_str(), ext));
744
745                if !candidate.exists() {
746                    continue;
747                }
748
749                // Validate path containment
750                match validate_existing_path_under_roots(
751                    &candidate,
752                    &self.module_policy.allowed_module_roots,
753                ) {
754                    Ok(canonical_path) => {
755                        // Validate symlink containment
756                        match validate_symlink_containment(
757                            &canonical_path,
758                            &self.module_policy.allowed_module_roots,
759                        ) {
760                            Ok(safe_path) => {
761                                // Read content
762                                match std::fs::read_to_string(&safe_path) {
763                                    Ok(content) => {
764                                        let size = content.len();
765
766                                        // Check size limit
767                                        if let Some(max) = self.limits.max_required_module_bytes {
768                                            if size > max {
769                                                self.diagnostics.push(
770                                                    NseLoadDiagnostic::OversizedRejected {
771                                                        source: NseScriptSource::File {
772                                                            path: safe_path.clone(),
773                                                        },
774                                                        size,
775                                                        limit: max,
776                                                    },
777                                                );
778                                                return Err(NseLoadError::Oversized {
779                                                    source: NseScriptSource::File {
780                                                        path: safe_path.clone(),
781                                                    },
782                                                    size,
783                                                    limit: max,
784                                                });
785                                            }
786                                        }
787                                        if let Some(max) = self.module_policy.max_module_bytes {
788                                            if size > max {
789                                                self.diagnostics.push(
790                                                    NseLoadDiagnostic::OversizedRejected {
791                                                        source: NseScriptSource::File {
792                                                            path: safe_path.clone(),
793                                                        },
794                                                        size,
795                                                        limit: max,
796                                                    },
797                                                );
798                                                return Err(NseLoadError::Oversized {
799                                                    source: NseScriptSource::File {
800                                                        path: safe_path.clone(),
801                                                    },
802                                                    size,
803                                                    limit: max,
804                                                });
805                                            }
806                                        }
807
808                                        self.diagnostics.push(NseLoadDiagnostic::Resolved {
809                                            source: NseScriptSource::File {
810                                                path: safe_path.clone(),
811                                            },
812                                            bytes: size,
813                                        });
814
815                                        return Ok(Some(ResolvedNseModule {
816                                            name: validated_name,
817                                            content,
818                                            size,
819                                            path: Some(safe_path),
820                                        }));
821                                    }
822                                    Err(e) => {
823                                        self.diagnostics.push(
824                                            NseLoadDiagnostic::ModuleLoadFailed {
825                                                name: name.to_string(),
826                                                path: safe_path,
827                                                error: e.to_string(),
828                                            },
829                                        );
830                                        // Continue searching other roots
831                                    }
832                                }
833                            }
834                            Err(NseLoadError::SymlinkEscape { path, resolved }) => {
835                                self.diagnostics
836                                    .push(NseLoadDiagnostic::SymlinkRejected { path, resolved });
837                                // Continue searching other roots
838                            }
839                            Err(e) => return Err(e),
840                        }
841                    }
842                    Err(NseLoadError::OutsideRoot {
843                        path,
844                        approved_roots,
845                    }) => {
846                        self.diagnostics.push(NseLoadDiagnostic::OutsideRoot {
847                            path,
848                            root: approved_roots.first().cloned().unwrap_or_default(),
849                        });
850                        // Continue searching other roots
851                    }
852                    Err(e) => return Err(e),
853                }
854            }
855        }
856
857        // Module not found in any approved root
858        Ok(None)
859    }
860}
861
862#[cfg(test)]
863mod tests {
864    use super::*;
865
866    #[test]
867    fn test_validate_module_name_valid() {
868        assert!(validate_nse_module_name("stdnse").is_ok());
869        assert!(validate_nse_module_name("http").is_ok());
870        assert!(validate_nse_module_name("my-module").is_ok());
871        assert!(validate_nse_module_name("my_module").is_ok());
872        assert!(validate_nse_module_name("module.v2").is_ok());
873        assert!(validate_nse_module_name("a1b2c3").is_ok());
874    }
875
876    #[test]
877    fn test_validate_module_name_empty() {
878        assert!(matches!(
879            validate_nse_module_name(""),
880            Err(NseLoadError::InvalidModuleName { .. })
881        ));
882    }
883
884    #[test]
885    fn test_validate_module_name_starts_with_dot() {
886        assert!(matches!(
887            validate_nse_module_name(".hidden"),
888            Err(NseLoadError::InvalidModuleName { .. })
889        ));
890    }
891
892    #[test]
893    fn test_validate_module_name_traversal() {
894        assert!(matches!(
895            validate_nse_module_name("..etc/passwd"),
896            Err(NseLoadError::InvalidModuleName { .. })
897        ));
898        assert!(matches!(
899            validate_nse_module_name("foo/../bar"),
900            Err(NseLoadError::InvalidModuleName { .. })
901        ));
902    }
903
904    #[test]
905    fn test_validate_module_name_forbidden_chars() {
906        assert!(validate_nse_module_name("foo/bar").is_err());
907        assert!(validate_nse_module_name("foo\\bar").is_err());
908        assert!(validate_nse_module_name("foo:bar").is_err());
909        assert!(validate_nse_module_name("foo~bar").is_err());
910        assert!(validate_nse_module_name("foo\0bar").is_err());
911        assert!(validate_nse_module_name("foo bar").is_err());
912        assert!(validate_nse_module_name("foo*bar").is_err());
913        assert!(validate_nse_module_name("foo?bar").is_err());
914        assert!(validate_nse_module_name("foo{bar").is_err());
915    }
916
917    #[test]
918    fn test_validate_module_name_too_long() {
919        let long_name = "a".repeat(257);
920        assert!(matches!(
921            validate_nse_module_name(&long_name),
922            Err(NseLoadError::InvalidModuleName { .. })
923        ));
924    }
925
926    #[test]
927    fn test_validate_module_name_max_length() {
928        let max_name = "a".repeat(256);
929        assert!(validate_nse_module_name(&max_name).is_ok());
930    }
931
932    #[test]
933    fn test_script_source_display() {
934        assert_eq!(
935            NseScriptSource::Builtin {
936                name: "default".to_string()
937            }
938            .to_string(),
939            "builtin:default"
940        );
941        assert_eq!(
942            NseScriptSource::File {
943                path: PathBuf::from("/tmp/test.lua")
944            }
945            .to_string(),
946            "file:/tmp/test.lua"
947        );
948        assert_eq!(
949            NseLoadError::NotFound {
950                source: NseScriptSource::Builtin {
951                    name: "x".to_string()
952                }
953            }
954            .to_string(),
955            "not found: builtin:x"
956        );
957    }
958
959    #[test]
960    fn test_is_builtin_script() {
961        assert!(is_builtin_script("default"));
962        assert!(is_builtin_script("discovery"));
963        assert!(is_builtin_script("banner"));
964        assert!(is_builtin_script("http-headers"));
965        assert!(is_builtin_script("dns-check"));
966        assert!(is_builtin_script("ssl-cert"));
967        assert!(!is_builtin_script("custom"));
968        assert!(!is_builtin_script(""));
969    }
970
971    #[test]
972    fn test_has_allowed_extension() {
973        assert!(has_allowed_extension(
974            Path::new("test.lua"),
975            ALLOWED_SCRIPT_EXTENSIONS
976        ));
977        assert!(has_allowed_extension(
978            Path::new("test.nse"),
979            ALLOWED_SCRIPT_EXTENSIONS
980        ));
981        assert!(!has_allowed_extension(
982            Path::new("test.txt"),
983            ALLOWED_SCRIPT_EXTENSIONS
984        ));
985        assert!(!has_allowed_extension(
986            Path::new("test"),
987            ALLOWED_SCRIPT_EXTENSIONS
988        ));
989    }
990
991    #[test]
992    fn test_resolver_rejects_script_file_when_policy_blocks() {
993        let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
994        let mut resolver =
995            ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
996
997        let result = resolver.resolve_script(NseScriptSource::File {
998            path: PathBuf::from("/tmp/test.lua"),
999        });
1000
1001        assert!(result.is_err());
1002        match result.unwrap_err() {
1003            NseLoadError::BlockedByPolicy { reason, .. } => {
1004                assert!(reason.contains("not allowed"));
1005            }
1006            other => panic!("Expected BlockedByPolicy, got {:?}", other),
1007        }
1008    }
1009
1010    #[test]
1011    fn test_resolver_rejects_oversized_inline_script() {
1012        let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1013        let mut resolver =
1014            ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1015
1016        // agent_safe has max_script_bytes = 1 MiB
1017        let large_content = "x".repeat(1024 * 1024 + 1);
1018        let result = resolver.resolve_script(NseScriptSource::InlineManual {
1019            label: "test".to_string(),
1020            content: large_content,
1021        });
1022
1023        assert!(result.is_err());
1024        match result.unwrap_err() {
1025            NseLoadError::Oversized { size, limit, .. } => {
1026                assert!(size > limit);
1027            }
1028            other => panic!("Expected Oversized, got {:?}", other),
1029        }
1030    }
1031
1032    #[test]
1033    fn test_resolver_allows_inline_script_within_limits() {
1034        let profile = crate::profile::ResolvedNseExecutionProfile::manual_permissive(None);
1035        let mut resolver =
1036            ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1037
1038        let result = resolver.resolve_script(NseScriptSource::InlineManual {
1039            label: "test".to_string(),
1040            content: "return 1".to_string(),
1041        });
1042
1043        assert!(result.is_ok());
1044        let resolved = result.unwrap();
1045        assert_eq!(resolved.content, "return 1");
1046    }
1047
1048    #[test]
1049    fn test_resolver_rejects_module_name_traversal() {
1050        let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1051        let mut resolver =
1052            ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1053
1054        let result = resolver.resolve_module("../../etc/passwd");
1055        assert!(result.is_err());
1056    }
1057
1058    #[test]
1059    fn test_resolver_rejects_module_name_slash() {
1060        let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1061        let mut resolver =
1062            ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1063
1064        let result = resolver.resolve_module("foo/bar");
1065        assert!(result.is_err());
1066    }
1067
1068    #[test]
1069    fn test_resolver_returns_none_for_module_when_filesystem_disallowed() {
1070        let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1071        let mut resolver =
1072            ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1073
1074        let result = resolver.resolve_module("stdnse").unwrap();
1075        assert!(result.is_none());
1076    }
1077
1078    #[test]
1079    fn test_resolver_allows_builtin_script() {
1080        let profile = crate::profile::ResolvedNseExecutionProfile::manual_permissive(None);
1081        let mut resolver =
1082            ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1083
1084        let result = resolver.resolve_script(NseScriptSource::Builtin {
1085            name: "default".to_string(),
1086        });
1087        assert!(result.is_ok());
1088    }
1089
1090    #[test]
1091    fn test_resolver_rejects_builtin_when_policy_blocks() {
1092        let mut script_policy = crate::profile::NseScriptPolicy {
1093            allow_builtin_scripts: false,
1094            allow_script_files: false,
1095            allowed_script_roots: Vec::new(),
1096            allow_conventional_nmap_paths: false,
1097            max_script_bytes: None,
1098        };
1099        let mut resolver = ScriptResolver::new(
1100            script_policy,
1101            crate::profile::NseModulePolicy {
1102                allow_builtin_modules: true,
1103                allow_filesystem_modules: false,
1104                allowed_module_roots: Vec::new(),
1105                max_module_bytes: None,
1106            },
1107            NseExecutionLimits::default(),
1108        );
1109
1110        let result = resolver.resolve_script(NseScriptSource::Builtin {
1111            name: "default".to_string(),
1112        });
1113        assert!(result.is_err());
1114    }
1115
1116    #[test]
1117    fn test_diagnostics_accumulate() {
1118        let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1119        let mut resolver =
1120            ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1121
1122        // This will emit a blocked diagnostic
1123        let _ = resolver.resolve_script(NseScriptSource::File {
1124            path: PathBuf::from("/tmp/test.lua"),
1125        });
1126
1127        let diags = resolver.take_diagnostics();
1128        assert!(!diags.is_empty());
1129    }
1130
1131    // -----------------------------------------------------------------------
1132    // WS2: Canonical root containment tests
1133    // -----------------------------------------------------------------------
1134
1135    #[test]
1136    fn test_is_under_root_component_semantics() {
1137        // /tmp/root2 must NOT match /tmp/root (sibling-prefix bypass)
1138        let root = PathBuf::from("/tmp/root");
1139        let child = PathBuf::from("/tmp/root2/file.nse");
1140        assert!(!is_under_root(&child, &root));
1141
1142        // /tmp/root/file.nse DOES match /tmp/root
1143        let child = PathBuf::from("/tmp/root/file.nse");
1144        assert!(is_under_root(&child, &root));
1145
1146        // /tmp/root/sub/file.nse DOES match /tmp/root
1147        let child = PathBuf::from("/tmp/root/sub/file.nse");
1148        assert!(is_under_root(&child, &root));
1149    }
1150
1151    #[test]
1152    fn test_validate_existing_path_under_roots_rejects_sibling_prefix() {
1153        let roots = vec![PathBuf::from("/tmp/root")];
1154        // /tmp/root2/file.nse should NOT be allowed under /tmp/root.
1155        // Since the file does not exist, the read helper rejects with
1156        // IoError before any root comparison. (Root mismatch would only be
1157        // observable for existing files.)
1158        let result = validate_existing_path_under_roots(Path::new("/tmp/root2/file.nse"), &roots);
1159        assert!(matches!(result, Err(NseLoadError::IoError { .. })));
1160    }
1161
1162    #[test]
1163    fn test_validate_existing_path_under_roots_rejects_sibling_prefix_existing_file() {
1164        // Sibling-prefix bypass: /tmp/root2/real.nse must NOT be authorized
1165        // under /tmp/root even when both directories exist and the file is real.
1166        let tmp = std::env::temp_dir().join("eggsec-nse-sibling-prefix-test");
1167        let root = tmp.join("root");
1168        let evil = tmp.join("root2");
1169        let _ = std::fs::create_dir_all(&root);
1170        let _ = std::fs::create_dir_all(&evil);
1171        std::fs::write(evil.join("real.nse"), "-- content").unwrap();
1172
1173        let result = validate_existing_path_under_roots(&evil.join("real.nse"), &[root.clone()]);
1174        assert!(matches!(result, Err(NseLoadError::OutsideRoot { .. })));
1175
1176        let _ = std::fs::remove_dir_all(&tmp);
1177    }
1178
1179    #[test]
1180    fn test_validate_existing_path_under_roots_rejects_nonexistent_path_outside_root() {
1181        let roots = vec![PathBuf::from("/tmp/root")];
1182        // Non-existent file outside root should be rejected with IoError
1183        // (NOT authorized just because parent canonicalizes).
1184        let result =
1185            validate_existing_path_under_roots(Path::new("/tmp/outside/secret.lua"), &roots);
1186        assert!(matches!(result, Err(NseLoadError::IoError { .. })));
1187    }
1188
1189    #[test]
1190    fn test_validate_existing_path_under_roots_rejects_nonexistent_path_inside_root() {
1191        // Non-existent file inside an approved root must NOT be authorized
1192        // merely because the root directory exists. The read helper requires
1193        // the canonical file path to resolve.
1194        let tmp = std::env::temp_dir().join("eggsec-nse-read-nonexistent-test");
1195        let _ = std::fs::create_dir_all(&tmp);
1196        let roots = vec![tmp.clone()];
1197
1198        let missing = tmp.join("does-not-exist.nse");
1199        let result = validate_existing_path_under_roots(&missing, &roots);
1200        assert!(
1201            matches!(result, Err(NseLoadError::IoError { .. })),
1202            "Expected IoError for non-existent file, got: {:?}",
1203            result
1204        );
1205
1206        let _ = std::fs::remove_dir_all(&tmp);
1207    }
1208
1209    #[test]
1210    fn test_validate_existing_path_under_roots_accepts_existing_inside_root() {
1211        let tmp = std::env::temp_dir().join("eggsec-nse-read-existing-test");
1212        let _ = std::fs::create_dir_all(&tmp);
1213        let file = tmp.join("real.nse");
1214        std::fs::write(&file, "-- script").unwrap();
1215
1216        let roots = vec![tmp.clone()];
1217        let result = validate_existing_path_under_roots(&file, &roots);
1218        assert!(result.is_ok());
1219        assert_eq!(result.unwrap(), file.canonicalize().unwrap());
1220
1221        let _ = std::fs::remove_dir_all(&tmp);
1222    }
1223
1224    #[test]
1225    fn test_validate_existing_path_under_roots_rejects_existing_outside_root() {
1226        // An existing file outside the approved root is rejected even when
1227        // the root itself exists.
1228        let tmp = std::env::temp_dir().join("eggsec-nse-read-outside-test");
1229        let root = tmp.join("root");
1230        let evil = tmp.join("root_evil");
1231        let _ = std::fs::create_dir_all(&root);
1232        let _ = std::fs::create_dir_all(&evil);
1233        let file = evil.join("real.nse");
1234        std::fs::write(&file, "-- script").unwrap();
1235
1236        let roots = vec![root.clone()];
1237        let result = validate_existing_path_under_roots(&file, &roots);
1238        assert!(matches!(result, Err(NseLoadError::OutsideRoot { .. })));
1239
1240        let _ = std::fs::remove_dir_all(&tmp);
1241    }
1242
1243    #[test]
1244    fn test_validate_symlink_containment_rejects_escape() {
1245        // Create a temp directory structure with a symlink
1246        let tmp = std::env::temp_dir().join("eggsec-nse-symlink-test");
1247        let allowed = tmp.join("allowed");
1248        let outside = tmp.join("outside");
1249        let _ = std::fs::create_dir_all(&allowed);
1250        let _ = std::fs::create_dir_all(&outside);
1251
1252        // Create a file outside the allowed root
1253        std::fs::write(outside.join("secret.txt"), "secret").unwrap();
1254
1255        // Create a symlink inside allowed pointing to the outside file
1256        let link = allowed.join("escape.txt");
1257        #[cfg(unix)]
1258        std::os::unix::fs::symlink(outside.join("secret.txt"), &link).unwrap();
1259
1260        // The symlink should be rejected
1261        let result = validate_symlink_containment(&link, &[allowed.clone()]);
1262        assert!(result.is_err());
1263        match result.unwrap_err() {
1264            NseLoadError::SymlinkEscape { path, resolved } => {
1265                assert_eq!(path, link);
1266                assert!(resolved.starts_with(&outside));
1267            }
1268            other => panic!("Expected SymlinkEscape, got {:?}", other),
1269        }
1270
1271        // Clean up
1272        let _ = std::fs::remove_dir_all(&tmp);
1273    }
1274
1275    #[test]
1276    fn test_validate_symlink_containment_allows_internal_symlink() {
1277        // Create a temp directory with a symlink to another file inside the root
1278        let tmp = std::env::temp_dir().join("eggsec-nse-symlink-ok-test");
1279        let allowed = tmp.join("allowed");
1280        let _ = std::fs::create_dir_all(allowed.join("sub"));
1281
1282        // Create a real file inside the root
1283        std::fs::write(allowed.join("real.txt"), "content").unwrap();
1284
1285        // Create a symlink inside allowed pointing to the real file
1286        let link = allowed.join("sub").join("link.txt");
1287        #[cfg(unix)]
1288        std::os::unix::fs::symlink(allowed.join("real.txt"), &link).unwrap();
1289
1290        // The symlink should be allowed (resolves inside root)
1291        let result = validate_symlink_containment(&link, &[allowed.clone()]);
1292        assert!(result.is_ok());
1293
1294        // Clean up
1295        let _ = std::fs::remove_dir_all(&tmp);
1296    }
1297
1298    #[test]
1299    fn test_validate_existing_path_under_roots_rejects_absolute_traversal() {
1300        let roots = vec![PathBuf::from("/tmp/root")];
1301        // Absolute path outside root should be rejected with IoError
1302        // (since /etc/passwd does not exist in the test environment is possible,
1303        // but the canonical form is also outside the root).
1304        let result = validate_existing_path_under_roots(Path::new("/etc/passwd"), &roots);
1305        assert!(result.is_err());
1306    }
1307
1308    #[test]
1309    fn test_canonicalize_root_rejects_nonexistent() {
1310        // A root that doesn't exist should return None
1311        let result = canonicalize_root(Path::new("/tmp/nonexistent-root-eggsec-nse"));
1312        assert!(result.is_none());
1313    }
1314
1315    #[test]
1316    fn test_canonicalize_root_accepts_existing() {
1317        // An existing root should return Some
1318        let tmp = std::env::temp_dir().join("eggsec-nse-root-test");
1319        let _ = std::fs::create_dir_all(&tmp);
1320        let result = canonicalize_root(&tmp);
1321        assert!(result.is_some());
1322        let _ = std::fs::remove_dir_all(&tmp);
1323    }
1324}