freemarker 0.1.1

Apache FreeMarker 语义兼容的 Rust 模板引擎(freemarker-core 迁移)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! `?new` 类解析器 —— 对应 Java `freemarker.core.TemplateClassResolver`
//! (接口 + UNRESTRICTED/SAFER/ALLOWS_NOTHING 三个常量实现,TemplateClassResolver.java)
//! 与 `freemarker.core.OptInTemplateClassResolver`(allowed_classes + trusted_templates)。
//!
//! 设置字符串解析对应 Configurable.setSetting 的 NEW_BUILTIN_CLASS_RESOLVER 分支
//! (Configurable.java:2837-2876:"unrestricted"/"safer"/"allows_nothing" 精确名;
//! 含 `:` 的值走 SettingStringParser.parseAsSegmentedList 的分段列表——`key: v1, v2`
//! 中带 `:` 的项开启新段,其余项追加当前段)。
//!
//! `resolve` 只做权限判定(Java resolve 的类加载部分由
//! `utility_transforms::new_utility_class` 承接——本引擎无 Java 类加载器;
//! 放行后未知类仍按 ClassNotFoundException 语义报错,与 Java ClassUtil.forName 一致)。

use crate::error::{Result, TemplateError};

/// `?new` 类解析策略 —— 对应 Java `TemplateClassResolver` 接口的三个常量实现 +
/// `OptInTemplateClassResolver`(Rust 特有枚举形态,见 docs/02 §4.1 角色槽位设计)
#[derive(Debug, Clone, PartialEq)]
pub enum NewBuiltinClassResolver {
    /// 不设限 —— Java `TemplateClassResolver.UNRESTRICTED_RESOLVER`
    /// (ClassUtil.forName 直通;Configurable.java:477 默认值)
    Unrestricted,
    /// 仅禁可执行任意代码的类 —— Java `SAFER_RESOLVER`(TemplateClassResolver.java:62-73):
    /// ObjectConstructor / Execute / JythonRuntime
    Safer,
    /// 全部拒绝 —— Java `ALLOWS_NOTHING_RESOLVER`(TemplateClassResolver.java:75-82)
    AllowsNothing,
    /// 白名单 + 信任模板 —— Java `OptInTemplateClassResolver`
    OptIn(OptInClassResolver),
}

/// 对应 Java `OptInTemplateClassResolver`:allowed_classes(全限定类名集合)+
/// trusted_templates(模板名或 `*` 结尾前缀;前导 "/" 剥离)。
/// 信任模板内走 SAFER 策略,其余模板的类必须 ∈ allowed_classes
/// (OptInTemplateClassResolver.java:69-87)。
#[derive(Debug, Clone, PartialEq)]
pub struct OptInClassResolver {
    /// 允许的类全限定名(Java allowedClasses Set,构造 :44-66)
    allowed_classes: Vec<String>,
    /// 精确模板名(Java trustedTemplateNames Set)
    trusted_template_names: Vec<String>,
    /// 前缀模式(`foo*` 匹配 `foobar`/`foo/bar/baaz` 等;Java trustedTemplatePrefixes)
    trusted_template_prefixes: Vec<String>,
}

impl OptInClassResolver {
    /// 对应 Java OptInTemplateClassResolver 构造(:44-66):`*` 结尾 → 前缀模式
    /// (`foo*` → 前缀 `foo`);前导 "/" 剥离;其余为精确名
    pub fn new(allowed_classes: Vec<String>, trusted_templates: Vec<String>) -> Self {
        let mut names = Vec::new();
        let mut prefixes = Vec::new();
        for li in trusted_templates {
            let li = li.strip_prefix('/').unwrap_or(&li).to_string();
            if let Some(p) = li.strip_suffix('*') {
                prefixes.push(p.to_string());
            } else {
                names.push(li);
            }
        }
        OptInClassResolver {
            allowed_classes,
            trusted_template_names: names,
            trusted_template_prefixes: prefixes,
        }
    }

    fn resolve(&self, class_name: &str, template_name: Option<&str>) -> Result<()> {
        // Java OptInTemplateClassResolver.resolve(:69-87):模板名(?new 词法所在
        // 模板,含 include 链)∈ trusted → SAFER 语义;否则须 ∈ allowed_classes
        if template_name
            .and_then(safe_template_name)
            .is_some_and(|n| self.is_trusted(&n))
        {
            return NewBuiltinClassResolver::Safer.resolve(class_name, None);
        }
        if !self.allowed_classes.iter().any(|c| c == class_name) {
            return Err(instantiating_not_allowed(
                class_name,
                true, // Java OptIn 分支的消息含设置名提示(OptInTemplateClassResolver.java:79-84)
            ));
        }
        Ok(())
    }

    fn is_trusted(&self, name: &str) -> bool {
        if self.trusted_template_names.iter().any(|n| n == name) {
            return true;
        }
        self.trusted_template_prefixes
            .iter()
            .any(|p| name.starts_with(p.as_str()))
    }
}

impl NewBuiltinClassResolver {
    /// 设置字符串解析(Java Configurable.setSetting 的 NEW_BUILTIN_CLASS_RESOLVER
    /// 分支,Configurable.java:2837-2876)。无法识别的值 → Err
    /// (Java invalidSettingValueException 语义)
    pub fn parse(value: &str) -> Result<Self> {
        let v = value.trim();
        match v {
            "unrestricted" => return Ok(NewBuiltinClassResolver::Unrestricted),
            "safer" => return Ok(NewBuiltinClassResolver::Safer),
            "allows_nothing" | "allowsNothing" => {
                return Ok(NewBuiltinClassResolver::AllowsNothing)
            }
            _ => {}
        }
        if v.contains(':') {
            // Java SettingStringParser.parseAsSegmentedList(Configurable.java:3262-3292):
            // 分段列表 `key: v1, v2, key2: v3` —— 含 `:` 的项开启新段(键),
            // 其余项追加当前段的值列表;键支持 snake_case/camelCase 双写法。
            // 词法(SettingStringParser.fetchWord/fetchStringValue/skipWS):
            // 单双引号项剥首尾引号并做 FTL 字面量转义解码(\" \\ \n 等),
            // 引号内允许空白/逗号;键值间空白不敏感。
            let mut parser = SettingStringParser::new(v);
            let segments = parser.parse_as_segmented_list()?;
            let mut allowed: Vec<String> = Vec::new();
            let mut trusted: Vec<String> = Vec::new();
            for (key, vals) in segments {
                match key.as_str() {
                    "allowed_classes" | "allowedClasses" => {
                        allowed.extend(vals);
                    }
                    "trusted_templates" | "trustedTemplates" => {
                        trusted.extend(vals);
                    }
                    other => {
                        // Java ParseException(Configurable.java:2857-2867):
                        // "Unrecognized list segment key: {jQuote(key)}. Supported keys are: ..."
                        return Err(TemplateError::misc(format!(
                            "Unrecognized list segment key: {other:?}. Supported keys are: \
                             \"allowed_classes\", \"allowedClasses\", \"trusted_templates\", \
                             \"trustedTemplates\". "
                        )));
                    }
                }
            }
            return Ok(NewBuiltinClassResolver::OptIn(OptInClassResolver::new(
                allowed, trusted,
            )));
        }
        Err(TemplateError::misc(format!(
            "Invalid setting value for new_builtin_class_resolver: {v:?}"
        )))
    }

    /// 权限判定(Java `TemplateClassResolver.resolve`):拒绝 → Err(错误消息对齐
    /// `_MessageUtil.newInstantiatingClassNotAllowedException`,_MessageUtil.java:301-304);
    /// 放行 → Ok(类加载/实例化由调用方继续)
    pub fn resolve(&self, class_name: &str, template_name: Option<&str>) -> Result<()> {
        match self {
            NewBuiltinClassResolver::Unrestricted => Ok(()),
            NewBuiltinClassResolver::Safer => {
                // Java SAFER_RESOLVER(TemplateClassResolver.java:62-73):禁
                // ObjectConstructor / Execute / JythonRuntime(可执行任意代码的类)
                if matches!(
                    class_name,
                    "freemarker.template.utility.ObjectConstructor"
                        | "freemarker.template.utility.Execute"
                        | "freemarker.template.utility.JythonRuntime"
                ) {
                    return Err(instantiating_not_allowed(class_name, false));
                }
                Ok(())
            }
            NewBuiltinClassResolver::AllowsNothing => {
                Err(instantiating_not_allowed(class_name, false))
            }
            NewBuiltinClassResolver::OptIn(opt) => opt.resolve(class_name, template_name),
        }
    }
}

/// 拒绝消息 —— 对应 Java `_MessageUtil.newInstantiatingClassNotAllowedException`
/// (_MessageUtil.java:301-304):"Instantiating {className} is not allowed in the
/// template for security reasons."。optin=true 时追加
/// OptInTemplateClassResolver 的设置名提示(:79-84)
fn instantiating_not_allowed(class_name: &str, optin: bool) -> TemplateError {
    let msg = if optin {
        format!(
            "Instantiating {class_name} is not allowed in the template for security reasons. \
             (If you run into this problem when using ?new in a template, you may want to \
             check the \"new_builtin_class_resolver\" setting in the FreeMarker configuration.)"
        )
    } else {
        format!("Instantiating {class_name} is not allowed in the template for security reasons.")
    };
    TemplateError::misc(msg)
}

/// 设置串解析器 —— 对应 Java `Configurable.SettingStringParser`(Configurable.java:3248-3386):
/// `parseAsSegmentedList` + `fetchStringValue`(剥引号 + FTLStringLiteralDec)+
/// `fetchWord`(引号感知的单词扫描)+ `skipWS`。Java 按 char 处理,Rust 以
/// `Vec<char>` 等价(设置值均为 ASCII 场景,字符级语义一致)
struct SettingStringParser {
    text: Vec<char>,
    pos: usize,
}

impl SettingStringParser {
    fn new(text: &str) -> Self {
        SettingStringParser {
            text: text.chars().collect(),
            pos: 0,
        }
    }

    /// 对应 `skipWS`(Configurable.java:3337-3346):跳过空白;EOF 返回 None
    fn skip_ws(&mut self) -> Option<char> {
        while self.pos < self.text.len() {
            let c = self.text[self.pos];
            if !c.is_whitespace() {
                return Some(c);
            }
            self.pos += 1;
        }
        None
    }

    /// 对应 `fetchWord`(Configurable.java:3350-3386):引号内(`\` 转义)任意字符;
    /// 未引号 → [letterOrDigit, /, \, _, ., -, !, *, ?] 序列
    fn fetch_word(&mut self) -> Result<String> {
        if self.pos == self.text.len() {
            return Err(TemplateError::misc("Unexpeced end of text"));
        }
        let c = self.text[self.pos];
        let b = self.pos;
        if c == '\'' || c == '"' {
            let q = c;
            self.pos += 1;
            let mut escaped = false;
            while self.pos < self.text.len() {
                let c = self.text[self.pos];
                if !escaped {
                    if c == '\\' {
                        escaped = true;
                    } else if c == q {
                        break;
                    }
                } else {
                    escaped = false;
                }
                self.pos += 1;
            }
            if self.pos == self.text.len() {
                // Java "Missing " + q
                return Err(TemplateError::misc(format!("Missing {q}")));
            }
            self.pos += 1; // 跳过闭合引号
            return Ok(self.text[b..self.pos].iter().collect());
        }
        loop {
            if self.pos >= self.text.len() {
                break;
            }
            let c = self.text[self.pos];
            if !(c.is_alphanumeric()
                || c == '/'
                || c == '\\'
                || c == '_'
                || c == '.'
                || c == '-'
                || c == '!'
                || c == '*'
                || c == '?')
            {
                break;
            }
            self.pos += 1;
        }
        if b == self.pos {
            // Java "Unexpected character: " + c
            return Err(TemplateError::misc(format!("Unexpected character: {c}")));
        }
        Ok(self.text[b..self.pos].iter().collect())
    }

    /// 对应 `fetchStringValue`(Configurable.java:3317-3323):剥首尾引号 +
    /// `StringUtil.FTLStringLiteralDec`(StringUtil.java:559-660:`\` 转义解码)
    fn fetch_string_value(&mut self) -> Result<String> {
        let mut w = self.fetch_word()?;
        if w.starts_with('\'') || w.starts_with('"') {
            w = w[1..w.len() - 1].to_string();
        }
        ftl_string_literal_dec(&w)
    }

    /// 对应 `parseAsSegmentedList`(Configurable.java:3262-3292):键段 + 值列表;
    /// 分隔符为 `,` 或 `:`;首项非键 → "The very first list item must be followed by \":\" ..."
    fn parse_as_segmented_list(&mut self) -> Result<Vec<(String, Vec<String>)>> {
        let mut segments: Vec<(String, Vec<String>)> = Vec::new();
        let mut current: Option<usize> = None;
        loop {
            let c = self.skip_ws();
            if c.is_none() {
                break;
            }
            let item = self.fetch_string_value()?;
            let c = self.skip_ws();
            if c == Some(':') {
                segments.push((item, Vec::new()));
                current = Some(segments.len() - 1);
            } else {
                match current {
                    Some(i) => segments[i].1.push(item),
                    None => {
                        // Java :3269-3273
                        return Err(TemplateError::misc(
                            "The very first list item must be followed by \":\" so it will be the key for the following sub-list.",
                        ));
                    }
                }
            }
            match c {
                None => break,
                Some(',') | Some(':') => self.pos += 1,
                Some(other) => {
                    // Java "Expected \",\" or \":\" or the end of text but found \"{c}\""
                    return Err(TemplateError::misc(format!(
                        "Expected \",\" or \":\" or the end of text but found \"{other}\""
                    )));
                }
            }
        }
        Ok(segments)
    }
}

/// 对应 `StringUtil.FTLStringLiteralDec`(StringUtil.java:559-660):`\` 转义解码
/// (\" \' \\ \n \r \t \f \b \g(>) \l(<) \a(&) \{ \= \xHH;其余 → 错误)
fn ftl_string_literal_dec(s: &str) -> Result<String> {
    let Some(idx) = s.find('\\') else {
        return Ok(s.to_string());
    };
    let chars: Vec<char> = s.chars().collect();
    let lidx = chars.len() - 1;
    let mut out = String::with_capacity(s.len());
    let mut bidx = 0usize;
    let mut idx = idx;
    loop {
        out.extend(&chars[bidx..idx]);
        if idx >= lidx {
            return Err(TemplateError::misc(
                "The last character of string literal is backslash",
            ));
        }
        let c = chars[idx + 1];
        match c {
            '"' | '\'' | '\\' => {
                out.push(c);
                bidx = idx + 2;
            }
            'n' => {
                out.push('\n');
                bidx = idx + 2;
            }
            'r' => {
                out.push('\r');
                bidx = idx + 2;
            }
            't' => {
                out.push('\t');
                bidx = idx + 2;
            }
            'f' => {
                out.push('\u{000c}');
                bidx = idx + 2;
            }
            'b' => {
                out.push('\u{0008}');
                bidx = idx + 2;
            }
            'g' => {
                out.push('>');
                bidx = idx + 2;
            }
            'l' => {
                out.push('<');
                bidx = idx + 2;
            }
            'a' => {
                out.push('&');
                bidx = idx + 2;
            }
            '{' | '=' => {
                out.push(c);
                bidx = idx + 2;
            }
            'x' => {
                // Java:x = idx(反斜杠)+2 = 'x' 之后;z = lidx > x+3 ? x+3 : lidx
                // (最多 4 位十六进制)
                let mut x = idx + 2;
                let mut y = 0u32;
                let z = if lidx > x + 3 { x + 3 } else { lidx };
                while x <= z {
                    let b = chars[x];
                    let digit = b.to_digit(16);
                    match digit {
                        Some(d) => {
                            y = (y << 4) + d;
                            x += 1;
                        }
                        None => break,
                    }
                }
                if x > idx + 2 {
                    let ch = char::from_u32(y).ok_or_else(|| {
                        TemplateError::misc("Invalid \\x escape in a string literal")
                    })?;
                    out.push(ch);
                } else {
                    return Err(TemplateError::misc(
                        "Invalid \\x escape in a string literal",
                    ));
                }
                bidx = x;
            }
            other => {
                return Err(TemplateError::misc(format!(
                    "Invalid escape sequence (\\{other}) in a string literal"
                )));
            }
        }
        idx = match s[bidx..].find('\\') {
            Some(i) => bidx + i,
            None => break,
        };
    }
    out.extend(&chars[bidx..]);
    Ok(out)
}

/// 模板名净化 —— 对应 Java `OptInTemplateClassResolver.safeGetTemplateName`(:88-124):
/// 前导 "/" 剥离;URL 解码 %2e/%2f/%5c 后做路径段 `..` 检测(命中 → None = 不信任,
/// 防目录穿越绕过白名单)
fn safe_template_name(name: &str) -> Option<String> {
    let decoded = if name.contains('%') {
        name.replace("%2e", ".")
            .replace("%2E", ".")
            .replace("%2f", "/")
            .replace("%2F", "/")
            .replace("%5c", "\\")
            .replace("%5C", "\\")
    } else {
        name.to_string()
    };
    let b = decoded.as_bytes();
    let mut i = 0usize;
    while i < b.len() {
        if b[i] == b'.' && i + 1 < b.len() && b[i + 1] == b'.' {
            let before = if i == 0 { -1 } else { b[i - 1] as i32 };
            let after = if i + 2 >= b.len() {
                -1
            } else {
                b[i + 2] as i32
            };
            if (before == -1 || before == b'/' as i32 || before == b'\\' as i32)
                && (after == -1 || after == b'/' as i32 || after == b'\\' as i32)
            {
                return None;
            }
        }
        i += 1;
    }
    Some(decoded.strip_prefix('/').unwrap_or(&decoded).to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_named_resolvers() {
        assert_eq!(
            NewBuiltinClassResolver::parse("unrestricted").unwrap(),
            NewBuiltinClassResolver::Unrestricted
        );
        assert_eq!(
            NewBuiltinClassResolver::parse("safer").unwrap(),
            NewBuiltinClassResolver::Safer
        );
        assert_eq!(
            NewBuiltinClassResolver::parse("allows_nothing").unwrap(),
            NewBuiltinClassResolver::AllowsNothing
        );
        assert_eq!(
            NewBuiltinClassResolver::parse("allowsNothing").unwrap(),
            NewBuiltinClassResolver::AllowsNothing
        );
        assert!(NewBuiltinClassResolver::parse("bogus").is_err());
    }

    #[test]
    fn parse_optin_segmented_list() {
        // Java 模板套件 new-optin 用例的设置串(manifest 原文,含缩进空白)
        let r = NewBuiltinClassResolver::parse(
            "         allowed_classes: freemarker.test.templatesuite.models.NewTestModel, \
             trusted_templates: subdir/new-optin.ftl, subdir/subsub/*",
        )
        .unwrap();
        let NewBuiltinClassResolver::OptIn(opt) = &r else {
            panic!("expected OptIn");
        };
        assert_eq!(
            opt.allowed_classes,
            vec!["freemarker.test.templatesuite.models.NewTestModel"]
        );
        assert_eq!(opt.trusted_template_names, vec!["subdir/new-optin.ftl"]);
        assert_eq!(opt.trusted_template_prefixes, vec!["subdir/subsub/"]);
    }

    #[test]
    fn safer_rejects_object_constructor() {
        let r = NewBuiltinClassResolver::parse("safer").unwrap();
        assert!(r
            .resolve("freemarker.template.utility.ObjectConstructor", None)
            .is_err());
        assert!(r
            .resolve("freemarker.test.templatesuite.models.NewTestModel", None)
            .is_ok());
        let err = r
            .resolve("freemarker.template.utility.ObjectConstructor", None)
            .unwrap_err();
        assert!(err
            .to_string()
            .contains("is not allowed in the template for security reasons"));
    }

    #[test]
    fn allows_nothing_rejects_all() {
        let r = NewBuiltinClassResolver::parse("allows_nothing").unwrap();
        assert!(r
            .resolve("freemarker.test.templatesuite.models.NewTestModel", None)
            .is_err());
    }

    #[test]
    fn optin_trusted_template_matching() {
        let r = NewBuiltinClassResolver::parse(
            "allowed_classes: a.B, trusted_templates: subdir/x.ftl, subdir/subsub/*",
        )
        .unwrap();
        // 非信任模板:白名单外类拒绝
        assert!(r.resolve("a.B", Some("main.ftl")).is_ok());
        assert!(r.resolve("a.C", Some("main.ftl")).is_err());
        // 精确信任名 → SAFER 语义(非 ObjectConstructor 放行)
        assert!(r.resolve("a.C", Some("subdir/x.ftl")).is_ok());
        // 前缀模式 `subdir/subsub/*`(Java 前缀匹配:startsWith)
        assert!(r.resolve("a.C", Some("subdir/subsub/deep.ftl")).is_ok());
        assert!(r.resolve("a.C", Some("subdir/subsub2/x.ftl")).is_err());
        // 信任模板内 ObjectConstructor 仍被 SAFER 拒绝
        assert!(r
            .resolve(
                "freemarker.template.utility.ObjectConstructor",
                Some("subdir/x.ftl")
            )
            .is_err());
        // 模板名缺失 → 不信任
        assert!(r.resolve("a.C", None).is_err());
    }
}