Skip to main content

ggen_core/security/
template_secure.rs

1//! Template security hardening for sandboxed Tera environments
2//!
3//! **Week 3 Security Hardening: Template Security**
4//!
5//! This module implements comprehensive template security mechanisms:
6//! - Sandboxed Tera environment with restricted functions
7//! - Template variable validation (alphanumeric + underscore only)
8//! - Template source validation (prevent template injection)
9//! - Context-aware escaping filters (HTML, SQL, Shell)
10//! - Maximum template size enforcement (1MB)
11//! - Path traversal prevention in template includes
12//!
13//! ## Security Measures
14//!
15//! 1. **Function Whitelist**: Only safe Tera functions allowed (no file/network/shell access)
16//! 2. **Variable Validation**: All variables must be alphanumeric + underscore
17//! 3. **Size Limits**: Templates limited to 1MB maximum
18//! 4. **Escaping**: Context-aware output escaping (HTML, SQL, Shell)
19//! 5. **Path Security**: No path traversal in includes
20
21use crate::utils::error::{Error, Result};
22use std::collections::{HashMap, HashSet};
23use tera::{Context, Tera, Value};
24
25/// Maximum template size in bytes (1MB)
26pub const MAX_TEMPLATE_SIZE: usize = 1_048_576;
27
28/// Maximum variable name length
29pub const MAX_VARIABLE_NAME_LENGTH: usize = 256;
30
31/// Error type for template security violations
32#[derive(Debug, thiserror::Error)]
33pub enum TemplateSecurityError {
34    #[error("Template too large: {0} bytes (max: {1})")]
35    TemplateTooLarge(usize, usize),
36
37    #[error("Invalid variable name: {0}")]
38    InvalidVariableName(String),
39
40    #[error("Forbidden function: {0}")]
41    ForbiddenFunction(String),
42
43    #[error("Template injection detected: {0}")]
44    TemplateInjection(String),
45
46    #[error("Path traversal in include: {0}")]
47    PathTraversal(String),
48
49    #[error("Context required for escaping: {0}")]
50    MissingContext(String),
51
52    #[error("Invalid template syntax: {0}")]
53    InvalidSyntax(String),
54}
55
56impl From<TemplateSecurityError> for Error {
57    fn from(err: TemplateSecurityError) -> Self {
58        Error::new(&err.to_string())
59    }
60}
61
62/// Trait for sandboxed template environments
63pub trait TemplateSandbox {
64    /// Validate template source before rendering
65    fn validate_template(&self, source: &str) -> Result<()>;
66
67    /// Render template with validated context
68    fn render_safe(&self, source: &str, context: &Context) -> Result<String>;
69
70    /// Check if a function is allowed in the sandbox
71    fn is_function_allowed(&self, name: &str) -> bool;
72
73    /// Validate variable name for security
74    fn validate_variable_name(&self, name: &str) -> Result<()>;
75}
76
77/// Secure Tera environment with sandboxing
78pub struct SecureTeraEnvironment {
79    /// Allowed Tera functions (whitelist)
80    allowed_functions: HashSet<String>,
81    /// Forbidden patterns in templates
82    forbidden_patterns: Vec<&'static str>,
83    /// Maximum template size
84    max_size: usize,
85}
86
87impl SecureTeraEnvironment {
88    /// Create new secure Tera environment with default whitelist
89    pub fn new() -> Self {
90        Self {
91            allowed_functions: Self::default_allowed_functions(),
92            forbidden_patterns: Self::default_forbidden_patterns(),
93            max_size: MAX_TEMPLATE_SIZE,
94        }
95    }
96
97    /// Create with custom maximum size
98    pub fn with_max_size(mut self, max_size: usize) -> Self {
99        self.max_size = max_size;
100        self
101    }
102
103    /// Default allowed functions (whitelist - no file/network/shell access)
104    fn default_allowed_functions() -> HashSet<String> {
105        let mut set = HashSet::new();
106
107        // String manipulation (safe)
108        set.insert("upper".to_string());
109        set.insert("lower".to_string());
110        set.insert("trim".to_string());
111        set.insert("truncate".to_string());
112        set.insert("wordcount".to_string());
113        set.insert("replace".to_string());
114        set.insert("split".to_string());
115        set.insert("join".to_string());
116        set.insert("capitalize".to_string());
117        set.insert("title".to_string());
118
119        // Math operations (safe)
120        set.insert("round".to_string());
121        set.insert("abs".to_string());
122        set.insert("plus".to_string());
123        set.insert("minus".to_string());
124        set.insert("times".to_string());
125        set.insert("divided_by".to_string());
126
127        // Collections (safe)
128        set.insert("length".to_string());
129        set.insert("first".to_string());
130        set.insert("last".to_string());
131        set.insert("nth".to_string());
132        set.insert("slice".to_string());
133        set.insert("concat".to_string());
134        set.insert("reverse".to_string());
135        set.insert("sort".to_string());
136        set.insert("unique".to_string());
137        set.insert("group_by".to_string());
138        set.insert("filter".to_string());
139        set.insert("map".to_string());
140
141        // Formatting (safe)
142        set.insert("date".to_string());
143        set.insert("json_encode".to_string());
144        set.insert("urlencode".to_string());
145        set.insert("escape".to_string());
146        set.insert("safe".to_string());
147
148        // Security: Custom escaping filters
149        set.insert("escape_html".to_string());
150        set.insert("escape_sql".to_string());
151        set.insert("escape_shell".to_string());
152
153        set
154    }
155
156    /// Forbidden patterns that indicate potential security issues
157    fn default_forbidden_patterns() -> Vec<&'static str> {
158        vec![
159            // File system access attempts
160            "include_raw",
161            "read_file",
162            "write_file",
163            // Network access attempts
164            "http",
165            "https",
166            "fetch",
167            "curl",
168            // Shell execution attempts
169            "exec",
170            "system",
171            "shell",
172            "cmd",
173            "bash",
174            // Dangerous path patterns
175            "../",
176            "..\\",
177            "/etc/",
178            "/proc/",
179            "/sys/",
180            "C:\\Windows",
181        ]
182    }
183
184    /// Validate template size
185    fn validate_size(&self, source: &str) -> Result<()> {
186        let size = source.len();
187        if size > self.max_size {
188            return Err(TemplateSecurityError::TemplateTooLarge(size, self.max_size).into());
189        }
190        Ok(())
191    }
192
193    /// Check for forbidden patterns in template
194    fn check_forbidden_patterns(&self, source: &str) -> Result<()> {
195        // The escape filters provided by this sandbox (`escape_shell`, etc.) contain
196        // substrings that overlap with forbidden patterns (e.g. "shell"). Neutralize
197        // these legitimate, sandbox-provided filter names before substring-matching so
198        // they do not produce false positives, without weakening detection of genuine
199        // dangerous tokens like `exec`, `bash`, or `system`.
200        let mut scanned = source.to_string();
201        for safe in ["escape_shell", "escape_sql", "escape_html"] {
202            scanned = scanned.replace(safe, "");
203        }
204
205        for pattern in &self.forbidden_patterns {
206            if scanned.contains(pattern) {
207                return Err(TemplateSecurityError::TemplateInjection(format!(
208                    "Forbidden pattern detected: {}",
209                    pattern
210                ))
211                .into());
212            }
213        }
214        Ok(())
215    }
216
217    /// Validate template includes for path traversal
218    fn validate_includes(&self, source: &str) -> Result<()> {
219        // Check for include statements
220        for line in source.lines() {
221            let trimmed = line.trim();
222            if trimmed.starts_with("{%") && trimmed.contains("include") {
223                // Extract include path (simplified - production would use proper parsing)
224                if trimmed.contains("..") {
225                    return Err(TemplateSecurityError::PathTraversal(
226                        "Path traversal detected in include".to_string(),
227                    )
228                    .into());
229                }
230            }
231        }
232        Ok(())
233    }
234}
235
236impl Default for SecureTeraEnvironment {
237    fn default() -> Self {
238        Self::new()
239    }
240}
241
242impl TemplateSandbox for SecureTeraEnvironment {
243    fn validate_template(&self, source: &str) -> Result<()> {
244        // 1. Check template size
245        self.validate_size(source)?;
246
247        // 2. Check for forbidden patterns
248        self.check_forbidden_patterns(source)?;
249
250        // 3. Validate includes
251        self.validate_includes(source)?;
252
253        Ok(())
254    }
255
256    fn render_safe(&self, source: &str, context: &Context) -> Result<String> {
257        // Validate template first
258        self.validate_template(source)?;
259
260        // Create Tera instance with security filters
261        let mut tera = Tera::default();
262
263        // Register security filters
264        tera.register_filter("escape_html", escape_html_filter);
265        tera.register_filter("escape_sql", escape_sql_filter);
266        tera.register_filter("escape_shell", escape_shell_filter);
267
268        // Render template
269        tera.render_str(source, context)
270            .map_err(|e| Error::new(&format!("Template rendering failed: {}", e)))
271    }
272
273    fn is_function_allowed(&self, name: &str) -> bool {
274        self.allowed_functions.contains(name)
275    }
276
277    fn validate_variable_name(&self, name: &str) -> Result<()> {
278        TemplateValidator::validate_variable_name(name)
279    }
280}
281
282/// Template validator for security checks
283pub struct TemplateValidator;
284
285impl TemplateValidator {
286    /// Validate variable name (alphanumeric + underscore only)
287    ///
288    /// # Security
289    ///
290    /// Prevents injection via variable names with special characters
291    ///
292    /// # Examples
293    ///
294    /// ```rust
295    /// use crate::security::template_secure::TemplateValidator;
296    ///
297    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
298    /// // Valid variable names
299    /// assert!(TemplateValidator::validate_variable_name("user_name").is_ok());
300    /// assert!(TemplateValidator::validate_variable_name("count_123").is_ok());
301    ///
302    /// // Invalid variable names
303    /// assert!(TemplateValidator::validate_variable_name("user.name").is_err());
304    /// assert!(TemplateValidator::validate_variable_name("user[0]").is_err());
305    /// assert!(TemplateValidator::validate_variable_name("../etc/passwd").is_err());
306    /// # Ok(())
307    /// # }
308    /// ```
309    pub fn validate_variable_name(name: &str) -> Result<()> {
310        // Check empty
311        if name.is_empty() {
312            return Err(TemplateSecurityError::InvalidVariableName(
313                "Variable name is empty".to_string(),
314            )
315            .into());
316        }
317
318        // Check length
319        if name.len() > MAX_VARIABLE_NAME_LENGTH {
320            return Err(TemplateSecurityError::InvalidVariableName(format!(
321                "Variable name too long: {} (max: {})",
322                name.len(),
323                MAX_VARIABLE_NAME_LENGTH
324            ))
325            .into());
326        }
327
328        // Check characters (alphanumeric + underscore only)
329        if !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
330            return Err(TemplateSecurityError::InvalidVariableName(format!(
331                "Variable name contains invalid characters: {}",
332                name
333            ))
334            .into());
335        }
336
337        // Additional check: must not start with number
338        if name.chars().next().is_some_and(|c| c.is_numeric()) {
339            return Err(TemplateSecurityError::InvalidVariableName(
340                "Variable name cannot start with number".to_string(),
341            )
342            .into());
343        }
344
345        Ok(())
346    }
347
348    /// Validate all variables in a context
349    pub fn validate_context(_context: &Context) -> Result<()> {
350        // Extract variable names from context
351        // Note: Tera Context doesn't expose keys directly, so we validate during insertion
352        // This is a placeholder - actual validation happens in variable name validation
353        Ok(())
354    }
355
356    /// Validate template syntax without rendering
357    pub fn validate_syntax(source: &str) -> Result<()> {
358        let mut tera = Tera::default();
359        tera.render_str(source, &Context::new())
360            .map(|_| ())
361            .map_err(|e| {
362                TemplateSecurityError::InvalidSyntax(format!("Template syntax error: {}", e)).into()
363            })
364    }
365}
366
367/// Context-aware escaping for different output contexts
368pub struct ContextEscaper;
369
370impl ContextEscaper {
371    /// Escape for HTML context
372    ///
373    /// # Security
374    ///
375    /// Prevents XSS attacks by escaping HTML special characters
376    ///
377    /// # Examples
378    ///
379    /// ```rust
380    /// use crate::security::template_secure::ContextEscaper;
381    ///
382    /// let escaped = ContextEscaper::escape_html("<script>alert('xss')</script>");
383    /// assert_eq!(escaped, "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;&#x2F;script&gt;");
384    /// ```
385    pub fn escape_html(input: &str) -> String {
386        input
387            .replace('&', "&amp;")
388            .replace('<', "&lt;")
389            .replace('>', "&gt;")
390            .replace('"', "&quot;")
391            .replace('\'', "&#x27;")
392            .replace('/', "&#x2F;")
393    }
394
395    /// Escape for SQL context (prevent SQL injection)
396    ///
397    /// # Security
398    ///
399    /// Escapes SQL special characters to prevent injection
400    ///
401    /// # Examples
402    ///
403    /// ```rust
404    /// use crate::security::template_secure::ContextEscaper;
405    ///
406    /// let escaped = ContextEscaper::escape_sql("'; DROP TABLE users; --");
407    /// assert_eq!(escaped, "''; DROP TABLE users; --");
408    /// ```
409    pub fn escape_sql(input: &str) -> String {
410        // Escape single quotes by doubling them
411        input.replace('\'', "''")
412    }
413
414    /// Escape for shell context (prevent command injection)
415    ///
416    /// # Security
417    ///
418    /// Escapes shell metacharacters to prevent command injection
419    ///
420    /// # Examples
421    ///
422    /// ```rust
423    /// use crate::security::template_secure::ContextEscaper;
424    ///
425    /// let escaped = ContextEscaper::escape_shell("file.txt; rm -rf /");
426    /// assert_eq!(escaped, "file.txt\\;\\ rm\\ -rf\\ /");
427    /// ```
428    pub fn escape_shell(input: &str) -> String {
429        let mut result = String::with_capacity(input.len() * 2);
430        for c in input.chars() {
431            match c {
432                // Shell metacharacters that need escaping
433                '$' | '`' | '"' | '\\' | '!' | '\n' | '&' | ';' | '|' | '(' | ')' | '<' | '>'
434                | ' ' | '\t' | '*' | '?' | '[' | ']' | '{' | '}' | '~' | '#' => {
435                    result.push('\\');
436                    result.push(c);
437                }
438                _ => result.push(c),
439            }
440        }
441        result
442    }
443
444    /// Escape for URL context
445    ///
446    /// # Note
447    ///
448    /// For production use, consider using a URL encoding library
449    pub fn escape_url(input: &str) -> String {
450        // Simple URL encoding implementation
451        input
452            .chars()
453            .map(|c| match c {
454                'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => c.to_string(),
455                ' ' => "+".to_string(),
456                _ => format!("%{:02X}", c as u8),
457            })
458            .collect()
459    }
460
461    /// Escape for JavaScript string context
462    pub fn escape_js(input: &str) -> String {
463        input
464            .replace('\\', "\\\\")
465            .replace('"', "\\\"")
466            .replace('\'', "\\'")
467            .replace('\n', "\\n")
468            .replace('\r', "\\r")
469            .replace('\t', "\\t")
470            .replace('<', "\\x3C")
471            .replace('>', "\\x3E")
472    }
473}
474
475// Tera filter functions
476
477fn escape_html_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
478    match value {
479        Value::String(s) => Ok(Value::String(ContextEscaper::escape_html(s))),
480        _ => Ok(value.clone()),
481    }
482}
483
484fn escape_sql_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
485    match value {
486        Value::String(s) => Ok(Value::String(ContextEscaper::escape_sql(s))),
487        _ => Ok(value.clone()),
488    }
489}
490
491fn escape_shell_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
492    match value {
493        Value::String(s) => Ok(Value::String(ContextEscaper::escape_shell(s))),
494        _ => Ok(value.clone()),
495    }
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501
502    // === Template Size Validation Tests ===
503
504    #[test]
505    fn test_template_size_validation_valid() {
506        let sandbox = SecureTeraEnvironment::new();
507        let small_template = "Hello {{ name }}!";
508        assert!(sandbox.validate_size(small_template).is_ok());
509    }
510
511    #[test]
512    fn test_template_size_validation_too_large() {
513        let sandbox = SecureTeraEnvironment::new();
514        let large_template = "a".repeat(MAX_TEMPLATE_SIZE + 1);
515        let result = sandbox.validate_size(&large_template);
516        assert!(result.is_err());
517    }
518
519    #[test]
520    fn test_custom_max_size() {
521        let sandbox = SecureTeraEnvironment::new().with_max_size(100);
522        let template = "a".repeat(101);
523        assert!(sandbox.validate_size(&template).is_err());
524    }
525
526    // === Variable Name Validation Tests ===
527
528    #[test]
529    fn test_valid_variable_names() {
530        assert!(TemplateValidator::validate_variable_name("user_name").is_ok());
531        assert!(TemplateValidator::validate_variable_name("count_123").is_ok());
532        assert!(TemplateValidator::validate_variable_name("_private").is_ok());
533        assert!(TemplateValidator::validate_variable_name("CamelCase").is_ok());
534        assert!(TemplateValidator::validate_variable_name("snake_case_123").is_ok());
535    }
536
537    #[test]
538    fn test_invalid_variable_names() {
539        // Empty name
540        assert!(TemplateValidator::validate_variable_name("").is_err());
541
542        // Special characters
543        assert!(TemplateValidator::validate_variable_name("user.name").is_err());
544        assert!(TemplateValidator::validate_variable_name("user[0]").is_err());
545        assert!(TemplateValidator::validate_variable_name("user-name").is_err());
546        assert!(TemplateValidator::validate_variable_name("user@host").is_err());
547
548        // Path traversal attempts
549        assert!(TemplateValidator::validate_variable_name("../etc/passwd").is_err());
550        assert!(TemplateValidator::validate_variable_name("..\\windows").is_err());
551
552        // Starts with number
553        assert!(TemplateValidator::validate_variable_name("123abc").is_err());
554
555        // Too long
556        let long_name = "a".repeat(MAX_VARIABLE_NAME_LENGTH + 1);
557        assert!(TemplateValidator::validate_variable_name(&long_name).is_err());
558    }
559
560    // === Forbidden Pattern Detection Tests ===
561
562    #[test]
563    fn test_forbidden_patterns_detected() {
564        let sandbox = SecureTeraEnvironment::new();
565
566        // File access attempts
567        assert!(sandbox
568            .check_forbidden_patterns("{{ include_raw('secret.txt') }}")
569            .is_err());
570        assert!(sandbox
571            .check_forbidden_patterns("{{ read_file('/etc/passwd') }}")
572            .is_err());
573
574        // Network access attempts
575        assert!(sandbox
576            .check_forbidden_patterns("{{ http('evil.com') }}")
577            .is_err());
578
579        // Shell execution attempts
580        assert!(sandbox
581            .check_forbidden_patterns("{{ exec('rm -rf /') }}")
582            .is_err());
583
584        // Path traversal
585        assert!(sandbox
586            .check_forbidden_patterns("../../../etc/passwd")
587            .is_err());
588    }
589
590    #[test]
591    fn test_safe_patterns_allowed() {
592        let sandbox = SecureTeraEnvironment::new();
593
594        // Normal template operations
595        assert!(sandbox
596            .check_forbidden_patterns("Hello {{ name | upper }}!")
597            .is_ok());
598        assert!(sandbox
599            .check_forbidden_patterns("{{ items | length }}")
600            .is_ok());
601    }
602
603    // === Include Validation Tests ===
604
605    #[test]
606    fn test_include_path_traversal_detection() {
607        let sandbox = SecureTeraEnvironment::new();
608
609        // Path traversal in include
610        assert!(sandbox
611            .validate_includes("{% include '../../../etc/passwd' %}")
612            .is_err());
613
614        // Safe include
615        assert!(sandbox
616            .validate_includes("{% include 'header.html' %}")
617            .is_ok());
618    }
619
620    // === Function Whitelist Tests ===
621
622    #[test]
623    fn test_allowed_functions() {
624        let sandbox = SecureTeraEnvironment::new();
625
626        // String functions
627        assert!(sandbox.is_function_allowed("upper"));
628        assert!(sandbox.is_function_allowed("lower"));
629        assert!(sandbox.is_function_allowed("trim"));
630
631        // Math functions
632        assert!(sandbox.is_function_allowed("round"));
633        assert!(sandbox.is_function_allowed("abs"));
634
635        // Collection functions
636        assert!(sandbox.is_function_allowed("length"));
637        assert!(sandbox.is_function_allowed("first"));
638
639        // Security filters
640        assert!(sandbox.is_function_allowed("escape_html"));
641        assert!(sandbox.is_function_allowed("escape_sql"));
642        assert!(sandbox.is_function_allowed("escape_shell"));
643    }
644
645    #[test]
646    fn test_forbidden_functions() {
647        let sandbox = SecureTeraEnvironment::new();
648
649        // These should NOT be in whitelist
650        assert!(!sandbox.is_function_allowed("include_raw"));
651        assert!(!sandbox.is_function_allowed("read_file"));
652        assert!(!sandbox.is_function_allowed("http"));
653        assert!(!sandbox.is_function_allowed("exec"));
654    }
655
656    // === HTML Escaping Tests ===
657
658    #[test]
659    fn test_escape_html_basic() {
660        let input = "<script>alert('xss')</script>";
661        let escaped = ContextEscaper::escape_html(input);
662        assert_eq!(
663            escaped,
664            "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;&#x2F;script&gt;"
665        );
666    }
667
668    #[test]
669    fn test_escape_html_all_chars() {
670        assert_eq!(ContextEscaper::escape_html("&"), "&amp;");
671        assert_eq!(ContextEscaper::escape_html("<"), "&lt;");
672        assert_eq!(ContextEscaper::escape_html(">"), "&gt;");
673        assert_eq!(ContextEscaper::escape_html("\""), "&quot;");
674        assert_eq!(ContextEscaper::escape_html("'"), "&#x27;");
675        assert_eq!(ContextEscaper::escape_html("/"), "&#x2F;");
676    }
677
678    #[test]
679    fn test_escape_html_complex() {
680        let input = "<div onclick=\"alert('xss')\" data-value='test'>";
681        let escaped = ContextEscaper::escape_html(input);
682        assert!(!escaped.contains('<'));
683        assert!(!escaped.contains('>'));
684        assert!(!escaped.contains('"'));
685        assert!(!escaped.contains('\''));
686    }
687
688    // === SQL Escaping Tests ===
689
690    #[test]
691    #[ignore = "Test expectation contradicts test_escape_sql_multiple_quotes: standard SQL escaping doubles single quotes ('' not '''), making these two tests mutually exclusive. The multiple-quotes test is correct per SQL standard."]
692    fn test_escape_sql_basic() {
693        let input = "'; DROP TABLE users; --";
694        let escaped = ContextEscaper::escape_sql(input);
695        assert_eq!(escaped, "'''; DROP TABLE users; --");
696    }
697
698    #[test]
699    fn test_escape_sql_multiple_quotes() {
700        let input = "O'Reilly's book";
701        let escaped = ContextEscaper::escape_sql(input);
702        assert_eq!(escaped, "O''Reilly''s book");
703    }
704
705    #[test]
706    fn test_escape_sql_no_quotes() {
707        let input = "normal text";
708        let escaped = ContextEscaper::escape_sql(input);
709        assert_eq!(escaped, "normal text");
710    }
711
712    // === Shell Escaping Tests ===
713
714    #[test]
715    fn test_escape_shell_basic() {
716        let input = "file.txt; rm -rf /";
717        let escaped = ContextEscaper::escape_shell(input);
718        assert_eq!(escaped, "file.txt\\;\\ rm\\ -rf\\ /");
719    }
720
721    #[test]
722    fn test_escape_shell_metacharacters() {
723        assert!(ContextEscaper::escape_shell("$VAR").contains("\\$"));
724        assert!(ContextEscaper::escape_shell("`cmd`").contains("\\`"));
725        assert!(ContextEscaper::escape_shell("a & b").contains("\\&"));
726        assert!(ContextEscaper::escape_shell("a | b").contains("\\|"));
727        assert!(ContextEscaper::escape_shell("a; b").contains("\\;"));
728    }
729
730    #[test]
731    #[ignore = "Logically impossible: assert!(!escaped.contains('$')) and assert!(escaped.contains(\"\\\\$\")) are contradictory — '\\$' always contains '$'. The escape_shell function correctly escapes '$' as '\\$'; the test assertions are mutually exclusive."]
732    fn test_escape_shell_complex() {
733        let input = "$(whoami) && echo 'pwned'";
734        let escaped = ContextEscaper::escape_shell(input);
735        assert!(!escaped.contains('$'));
736        assert!(escaped.contains("\\$"));
737    }
738
739    // === Integration Tests ===
740
741    #[test]
742    fn test_sandbox_render_safe_simple() {
743        let sandbox = SecureTeraEnvironment::new();
744        let mut context = Context::new();
745        context.insert("name", &"World");
746
747        let template = "Hello {{ name }}!";
748        let result = sandbox.render_safe(template, &context);
749        assert!(result.is_ok());
750        assert_eq!(result.unwrap(), "Hello World!");
751    }
752
753    #[test]
754    fn test_sandbox_reject_dangerous_template() {
755        let sandbox = SecureTeraEnvironment::new();
756        let context = Context::new();
757
758        // Attempt to include file
759        let template = "{{ read_file('/etc/passwd') }}";
760        let result = sandbox.render_safe(template, &context);
761        assert!(result.is_err());
762    }
763
764    #[test]
765    fn test_full_validation_workflow() {
766        let sandbox = SecureTeraEnvironment::new();
767
768        // Valid template
769        let valid_template = "Hello {{ user_name | upper }}!";
770        assert!(sandbox.validate_template(valid_template).is_ok());
771
772        // Too large template
773        let large_template = "a".repeat(MAX_TEMPLATE_SIZE + 1);
774        assert!(sandbox.validate_template(&large_template).is_err());
775
776        // Forbidden pattern
777        let dangerous_template = "{{ exec('rm -rf /') }}";
778        assert!(sandbox.validate_template(dangerous_template).is_err());
779
780        // Path traversal
781        let traversal_template = "{% include '../../../etc/passwd' %}";
782        assert!(sandbox.validate_template(traversal_template).is_err());
783    }
784}