1use crate::utils::error::{Error, Result};
22use std::collections::{HashMap, HashSet};
23use tera::{Context, Tera, Value};
24
25pub const MAX_TEMPLATE_SIZE: usize = 1_048_576;
27
28pub const MAX_VARIABLE_NAME_LENGTH: usize = 256;
30
31#[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
62pub trait TemplateSandbox {
64 fn validate_template(&self, source: &str) -> Result<()>;
66
67 fn render_safe(&self, source: &str, context: &Context) -> Result<String>;
69
70 fn is_function_allowed(&self, name: &str) -> bool;
72
73 fn validate_variable_name(&self, name: &str) -> Result<()>;
75}
76
77pub struct SecureTeraEnvironment {
79 allowed_functions: HashSet<String>,
81 forbidden_patterns: Vec<&'static str>,
83 max_size: usize,
85}
86
87impl SecureTeraEnvironment {
88 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 pub fn with_max_size(mut self, max_size: usize) -> Self {
99 self.max_size = max_size;
100 self
101 }
102
103 fn default_allowed_functions() -> HashSet<String> {
105 let mut set = HashSet::new();
106
107 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 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 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 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 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 fn default_forbidden_patterns() -> Vec<&'static str> {
158 vec![
159 "include_raw",
161 "read_file",
162 "write_file",
163 "http",
165 "https",
166 "fetch",
167 "curl",
168 "exec",
170 "system",
171 "shell",
172 "cmd",
173 "bash",
174 "../",
176 "..\\",
177 "/etc/",
178 "/proc/",
179 "/sys/",
180 "C:\\Windows",
181 ]
182 }
183
184 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 fn check_forbidden_patterns(&self, source: &str) -> Result<()> {
195 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 fn validate_includes(&self, source: &str) -> Result<()> {
219 for line in source.lines() {
221 let trimmed = line.trim();
222 if trimmed.starts_with("{%") && trimmed.contains("include") {
223 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 self.validate_size(source)?;
246
247 self.check_forbidden_patterns(source)?;
249
250 self.validate_includes(source)?;
252
253 Ok(())
254 }
255
256 fn render_safe(&self, source: &str, context: &Context) -> Result<String> {
257 self.validate_template(source)?;
259
260 let mut tera = Tera::default();
262
263 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 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
282pub struct TemplateValidator;
284
285impl TemplateValidator {
286 pub fn validate_variable_name(name: &str) -> Result<()> {
310 if name.is_empty() {
312 return Err(TemplateSecurityError::InvalidVariableName(
313 "Variable name is empty".to_string(),
314 )
315 .into());
316 }
317
318 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 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 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 pub fn validate_context(_context: &Context) -> Result<()> {
350 Ok(())
354 }
355
356 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
367pub struct ContextEscaper;
369
370impl ContextEscaper {
371 pub fn escape_html(input: &str) -> String {
386 input
387 .replace('&', "&")
388 .replace('<', "<")
389 .replace('>', ">")
390 .replace('"', """)
391 .replace('\'', "'")
392 .replace('/', "/")
393 }
394
395 pub fn escape_sql(input: &str) -> String {
410 input.replace('\'', "''")
412 }
413
414 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 '$' | '`' | '"' | '\\' | '!' | '\n' | '&' | ';' | '|' | '(' | ')' | '<' | '>'
434 | ' ' | '\t' | '*' | '?' | '[' | ']' | '{' | '}' | '~' | '#' => {
435 result.push('\\');
436 result.push(c);
437 }
438 _ => result.push(c),
439 }
440 }
441 result
442 }
443
444 pub fn escape_url(input: &str) -> String {
450 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 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
475fn 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 #[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 #[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 assert!(TemplateValidator::validate_variable_name("").is_err());
541
542 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 assert!(TemplateValidator::validate_variable_name("../etc/passwd").is_err());
550 assert!(TemplateValidator::validate_variable_name("..\\windows").is_err());
551
552 assert!(TemplateValidator::validate_variable_name("123abc").is_err());
554
555 let long_name = "a".repeat(MAX_VARIABLE_NAME_LENGTH + 1);
557 assert!(TemplateValidator::validate_variable_name(&long_name).is_err());
558 }
559
560 #[test]
563 fn test_forbidden_patterns_detected() {
564 let sandbox = SecureTeraEnvironment::new();
565
566 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 assert!(sandbox
576 .check_forbidden_patterns("{{ http('evil.com') }}")
577 .is_err());
578
579 assert!(sandbox
581 .check_forbidden_patterns("{{ exec('rm -rf /') }}")
582 .is_err());
583
584 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 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 #[test]
606 fn test_include_path_traversal_detection() {
607 let sandbox = SecureTeraEnvironment::new();
608
609 assert!(sandbox
611 .validate_includes("{% include '../../../etc/passwd' %}")
612 .is_err());
613
614 assert!(sandbox
616 .validate_includes("{% include 'header.html' %}")
617 .is_ok());
618 }
619
620 #[test]
623 fn test_allowed_functions() {
624 let sandbox = SecureTeraEnvironment::new();
625
626 assert!(sandbox.is_function_allowed("upper"));
628 assert!(sandbox.is_function_allowed("lower"));
629 assert!(sandbox.is_function_allowed("trim"));
630
631 assert!(sandbox.is_function_allowed("round"));
633 assert!(sandbox.is_function_allowed("abs"));
634
635 assert!(sandbox.is_function_allowed("length"));
637 assert!(sandbox.is_function_allowed("first"));
638
639 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 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 #[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 "<script>alert('xss')</script>"
665 );
666 }
667
668 #[test]
669 fn test_escape_html_all_chars() {
670 assert_eq!(ContextEscaper::escape_html("&"), "&");
671 assert_eq!(ContextEscaper::escape_html("<"), "<");
672 assert_eq!(ContextEscaper::escape_html(">"), ">");
673 assert_eq!(ContextEscaper::escape_html("\""), """);
674 assert_eq!(ContextEscaper::escape_html("'"), "'");
675 assert_eq!(ContextEscaper::escape_html("/"), "/");
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 #[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 #[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 #[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 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 let valid_template = "Hello {{ user_name | upper }}!";
770 assert!(sandbox.validate_template(valid_template).is_ok());
771
772 let large_template = "a".repeat(MAX_TEMPLATE_SIZE + 1);
774 assert!(sandbox.validate_template(&large_template).is_err());
775
776 let dangerous_template = "{{ exec('rm -rf /') }}";
778 assert!(sandbox.validate_template(dangerous_template).is_err());
779
780 let traversal_template = "{% include '../../../etc/passwd' %}";
782 assert!(sandbox.validate_template(traversal_template).is_err());
783 }
784}