mailrs-sieve-core 0.2.0

Native RFC 5228 Sieve interpreter — tokenizer + parser + evaluator. Built from the spec, no AGPL dependencies. The internal engine the `mailrs-sieve` wrapper will route to once parity with `sieve-rs` is reached (v8 ckpt 6).
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
//! RFC 5228 §4 evaluator — walk the AST against a parsed message,
//! emit a list of `Action`s.

mod context;
mod test_engine;

use crate::ast::{Action, Argument, Command, Envelope, Test};
use crate::capabilities::validate as validate_capabilities;
use crate::parse::{ParseError, parse_script};
use crate::vacation::parse_vacation_args;

use context::MessageContext;
use test_engine::eval_test;

/// Eval failure modes.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum EvalError {
    /// Parse failed before evaluation could start.
    #[error("parse: {0}")]
    Parse(#[from] ParseError),
    /// Unknown command in the script body (RFC 5228 §6.7
    /// requires `require` to whitelist any non-base command).
    #[error("unknown command {0:?}")]
    UnknownCommand(String),
    /// Unknown test inside a control-flow expression.
    #[error("unknown test {0:?}")]
    UnknownTest(String),
    /// A command argument was the wrong shape for the command.
    #[error("invalid argument for {cmd:?}: {detail}")]
    BadArg {
        /// Name of the command whose arg validation failed.
        cmd: String,
        /// Human-readable explanation.
        detail: String,
    },
    /// Script uses an extension feature without declaring the
    /// corresponding capability via `require` (RFC 5228 §3.2 —
    /// "implementations MUST treat scripts which contain capability
    /// declarations not satisfied by the implementation as
    /// containing a syntax error").
    #[error(
        "missing capability for {feature:?}: script must `require [\"{capability}\"]`"
    )]
    MissingCapability {
        /// Identifier of the unrequired feature (command / test /
        /// `:tag`).
        feature: String,
        /// Capability string the script must declare via `require`
        /// to use the feature.
        capability: String,
    },
    /// `require` declared a capability the implementation does not
    /// support (RFC 5228 §3.2).
    #[error("unsupported capability {0:?}")]
    UnsupportedCapability(String),
    /// `require` action appeared after a non-`require` command
    /// (RFC 5228 §3.2 — "If the 'require' action is used, it MUST
    /// be used before any other actions other than other 'require'
    /// actions").
    #[error("require out of order: must appear before any other action")]
    RequireOutOfOrder,
}

/// Evaluate a Sieve script against a message. Returns the
/// action list the delivery layer should apply, or `[Keep]` if
/// no script action fired (the RFC 5228 §2.10.6 implicit keep).
///
/// Equivalent to [`eval_script_with_envelope`] called with
/// `Envelope::default()` — use the envelope variant when the
/// script may inspect SMTP MAIL FROM / RCPT TO.
pub fn eval_script(script: &str, message: &[u8]) -> Result<Vec<Action>, EvalError> {
    eval_script_with_envelope(script, message, &Envelope::default())
}

/// Evaluate a Sieve script with an explicit SMTP envelope. The
/// RFC 5228 §5.4 `envelope` test inspects `from` / `to` / `auth`.
pub fn eval_script_with_envelope(
    script: &str,
    message: &[u8],
    envelope: &Envelope,
) -> Result<Vec<Action>, EvalError> {
    let commands = parse_script(script)?;
    validate_capabilities(&commands)?;
    let ctx = MessageContext::new(message);
    let mut state = EvalState::default();
    eval_block(&commands, &ctx, envelope, &mut state)?;
    if !state.explicit_action {
        state.actions.push(Action::Keep {
            flags: state.flags.clone(),
        });
    }
    Ok(state.actions)
}

#[derive(Default)]
struct EvalState {
    actions: Vec<Action>,
    explicit_action: bool,
    /// Index of the most recent `if`/`elsif` chain's outcome.
    /// Once an `if` branch matches, subsequent `elsif`/`else` are
    /// skipped per RFC 5228 §3.1.
    last_if_matched: bool,
    /// RFC 5228 §3.3 `stop` — terminate evaluation, do not run any
    /// subsequent commands in any enclosing block.
    stopped: bool,
    /// RFC 5232 `imap4flags` implicit flags variable. Mutated by
    /// `setflag` / `addflag` / `removeflag`; snapshotted into the
    /// next `keep` / `fileinto` action.
    flags: Vec<String>,
}

fn eval_block(
    commands: &[Command],
    ctx: &MessageContext<'_>,
    envelope: &Envelope,
    state: &mut EvalState,
) -> Result<(), EvalError> {
    for cmd in commands {
        if state.stopped {
            break;
        }
        eval_command(cmd, ctx, envelope, state)?;
    }
    Ok(())
}

fn eval_command(
    cmd: &Command,
    ctx: &MessageContext<'_>,
    envelope: &Envelope,
    state: &mut EvalState,
) -> Result<(), EvalError> {
    match cmd.name.as_str() {
        "require" => Ok(()), // validated upstream by `capabilities::validate`
        "keep" => {
            let local = override_flags_from_tag(&cmd.args);
            state.actions.push(Action::Keep {
                flags: local.unwrap_or_else(|| state.flags.clone()),
            });
            state.explicit_action = true;
            Ok(())
        }
        "discard" => {
            state.actions.push(Action::Discard);
            state.explicit_action = true;
            Ok(())
        }
        "fileinto" => {
            let arg = first_string(&cmd.args).ok_or_else(|| EvalError::BadArg {
                cmd: "fileinto".into(),
                detail: "expects string mailbox name".into(),
            })?;
            let local = override_flags_from_tag(&cmd.args);
            state.actions.push(Action::FileInto {
                mailbox: arg.to_string(),
                flags: local.unwrap_or_else(|| state.flags.clone()),
            });
            state.explicit_action = true;
            Ok(())
        }
        "setflag" => {
            // RFC 5232 §4.4: replace the implicit flags variable.
            // Does NOT count as explicit_action (state mutation,
            // not delivery).
            state.flags = flag_list_from_args(&cmd.args);
            Ok(())
        }
        "addflag" => {
            // RFC 5232 §4.5: add flags (no duplicates).
            for f in flag_list_from_args(&cmd.args) {
                if !state.flags.iter().any(|existing| existing == &f) {
                    state.flags.push(f);
                }
            }
            Ok(())
        }
        "removeflag" => {
            // RFC 5232 §4.6: remove matching flags.
            let to_remove = flag_list_from_args(&cmd.args);
            state.flags.retain(|f| !to_remove.iter().any(|r| r == f));
            Ok(())
        }
        "redirect" => {
            let arg = first_string(&cmd.args).ok_or_else(|| EvalError::BadArg {
                cmd: "redirect".into(),
                detail: "expects string address".into(),
            })?;
            state.actions.push(Action::Redirect(arg.to_string()));
            state.explicit_action = true;
            Ok(())
        }
        "reject" => {
            let arg = first_string(&cmd.args).ok_or_else(|| EvalError::BadArg {
                cmd: "reject".into(),
                detail: "expects string reason".into(),
            })?;
            state.actions.push(Action::Reject(arg.to_string()));
            state.explicit_action = true;
            Ok(())
        }
        "stop" => {
            // RFC 5228 §4.5 — terminate evaluation but do NOT
            // cancel the implicit keep (leave `explicit_action`
            // unchanged).
            state.stopped = true;
            Ok(())
        }
        "vacation" => {
            // RFC 5230 §3: vacation emits an action but does NOT
            // cancel the implicit keep — leave `explicit_action`
            // unchanged.
            let va = parse_vacation_args(&cmd.args).map_err(|e| EvalError::BadArg {
                cmd: "vacation".into(),
                detail: e.to_string(),
            })?;
            state.actions.push(Action::Vacation(va));
            Ok(())
        }
        "if" => {
            let test = first_test(&cmd.args).ok_or_else(|| EvalError::BadArg {
                cmd: "if".into(),
                detail: "expects test expression".into(),
            })?;
            let matched = eval_test(test, ctx, &state.flags, envelope)?;
            state.last_if_matched = matched;
            if matched {
                eval_block(&cmd.block, ctx, envelope, state)?;
            }
            Ok(())
        }
        "elsif" => {
            if state.last_if_matched {
                // chain already matched — skip
                return Ok(());
            }
            let test = first_test(&cmd.args).ok_or_else(|| EvalError::BadArg {
                cmd: "elsif".into(),
                detail: "expects test expression".into(),
            })?;
            let matched = eval_test(test, ctx, &state.flags, envelope)?;
            state.last_if_matched = matched;
            if matched {
                eval_block(&cmd.block, ctx, envelope, state)?;
            }
            Ok(())
        }
        "else" => {
            if state.last_if_matched {
                return Ok(());
            }
            state.last_if_matched = true;
            eval_block(&cmd.block, ctx, envelope, state)?;
            Ok(())
        }
        other => Err(EvalError::UnknownCommand(other.to_string())),
    }
}

/// Find the first **positional** string argument, skipping any
/// `:tag <value>` pairs (e.g. `:flags "\Seen"` in RFC 5232
/// `fileinto :flags "\Seen" "Inbox"`).
fn first_string(args: &[Argument]) -> Option<&str> {
    let mut i = 0;
    while i < args.len() {
        match &args[i] {
            Argument::Tag(_) => {
                // A tag consumes its value argument; jump past both.
                i += 2;
            }
            Argument::String(s) => return Some(s.as_str()),
            _ => i += 1,
        }
    }
    None
}

fn first_test(args: &[Argument]) -> Option<&Test> {
    args.iter().find_map(|a| match a {
        Argument::Test(t) => Some(t),
        _ => None,
    })
}

/// RFC 5232 `:flags` tag handling for `keep` / `fileinto`. Returns
/// `Some(list)` if the command carries an explicit `:flags`
/// argument (which overrides the implicit flags variable); returns
/// `None` if no tag is present (caller falls back to the variable).
fn override_flags_from_tag(args: &[Argument]) -> Option<Vec<String>> {
    for (i, a) in args.iter().enumerate() {
        if matches!(a, Argument::Tag(t) if t == "flags") {
            return match args.get(i + 1) {
                Some(Argument::String(s)) => Some(vec![s.clone()]),
                Some(Argument::StringList(v)) => Some(v.clone()),
                _ => Some(Vec::new()),
            };
        }
    }
    None
}

/// Extract the flag list from `setflag` / `addflag` / `removeflag`
/// command args (RFC 5232 §4.4–4.6). Accepts either a single string
/// or a string-list; variable-name form is not yet supported.
fn flag_list_from_args(args: &[Argument]) -> Vec<String> {
    for a in args {
        match a {
            Argument::String(s) => return vec![s.clone()],
            Argument::StringList(v) => return v.clone(),
            _ => {}
        }
    }
    Vec::new()
}

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

    const MSG: &[u8] = b"\
From: Alice <alice@example.com>\r\n\
To: bob@dest.com, carol@dest.com\r\n\
Subject: spam offer\r\n\
\r\n\
hello world\r\n";

    #[test]
    fn implicit_keep_on_empty_script() {
        assert_eq!(eval_script("", MSG).unwrap(), vec![Action::Keep { flags: vec![] }]);
    }

    #[test]
    fn explicit_keep() {
        assert_eq!(eval_script("keep;", MSG).unwrap(), vec![Action::Keep { flags: vec![] }]);
    }

    #[test]
    fn discard() {
        assert_eq!(eval_script("discard;", MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn fileinto() {
        let script = r#"require ["fileinto"]; fileinto "Junk";"#;
        assert_eq!(
            eval_script(script, MSG).unwrap(),
            vec![Action::FileInto { mailbox: "Junk".into(), flags: vec![] }]
        );
    }

    #[test]
    fn header_is_match_fires_discard() {
        let script = r#"if header :is "Subject" "spam offer" { discard; }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn header_is_no_match_falls_through_to_keep() {
        let script = r#"if header :is "Subject" "newsletter" { discard; }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Keep { flags: vec![] }]);
    }

    #[test]
    fn header_contains_substring() {
        let script = r#"require ["fileinto"];
                        if header :contains "Subject" "offer" { fileinto "Ads"; }"#;
        assert_eq!(
            eval_script(script, MSG).unwrap(),
            vec![Action::FileInto { mailbox: "Ads".into(), flags: vec![] }]
        );
    }

    #[test]
    fn header_matches_glob() {
        let script = r#"if header :matches "Subject" "*offer*" { discard; }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn exists_test_present() {
        let script = r#"if exists "Subject" { discard; }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn exists_test_missing() {
        let script = r#"if exists "X-Spam-Score" { discard; }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Keep { flags: vec![] }]);
    }

    #[test]
    fn size_over() {
        let script = "if size :over 1 { discard; }";
        // body is way bigger than 1 byte
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn size_under_huge() {
        let script = "if size :under 100K { discard; }";
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn not_invert() {
        let script = r#"if not header :is "Subject" "newsletter" { discard; }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn allof_true() {
        let script = r#"
            if allof(
                header :contains "Subject" "spam",
                header :is "From" "Alice <alice@example.com>"
            ) {
                discard;
            }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn anyof_one_true() {
        let script = r#"
            if anyof(
                header :is "Subject" "newsletter",
                header :contains "From" "alice"
            ) {
                discard;
            }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn elsif_chain_only_first_matching_branch_fires() {
        let script = r#"
            require ["fileinto"];
            if header :is "Subject" "no-match" { fileinto "A"; }
            elsif header :contains "Subject" "spam" { fileinto "Spam"; }
            elsif header :contains "Subject" "offer" { fileinto "Ads"; }
            else { keep; }"#;
        assert_eq!(
            eval_script(script, MSG).unwrap(),
            vec![Action::FileInto { mailbox: "Spam".into(), flags: vec![] }]
        );
    }

    #[test]
    fn else_branch() {
        let script = r#"
            if header :is "Subject" "no-match" { discard; }
            else { keep; }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Keep { flags: vec![] }]);
    }

    #[test]
    fn address_localpart() {
        let script = r#"if address :localpart "From" "alice" { discard; }"#;
        assert_eq!(eval_script(script, MSG).unwrap(), vec![Action::Discard]);
    }

    #[test]
    fn address_domain() {
        let script = r#"require ["fileinto"];
                        if address :domain "To" "dest.com" { fileinto "Sent"; }"#;
        assert_eq!(
            eval_script(script, MSG).unwrap(),
            vec![Action::FileInto { mailbox: "Sent".into(), flags: vec![] }]
        );
    }

    #[test]
    fn redirect_action() {
        let script = r#"redirect "alice@example.com";"#;
        assert_eq!(
            eval_script(script, MSG).unwrap(),
            vec![Action::Redirect("alice@example.com".into())]
        );
    }

    #[test]
    fn reject_action() {
        let script = r#"require ["reject"]; reject "policy reject";"#;
        assert_eq!(
            eval_script(script, MSG).unwrap(),
            vec![Action::Reject("policy reject".into())]
        );
    }

    // --- RFC 5228 §3.2 strict require enforcement ---

    #[test]
    fn fileinto_without_require_errors() {
        let err = eval_script(r#"fileinto "Junk";"#, MSG).unwrap_err();
        assert!(
            matches!(
                err,
                EvalError::MissingCapability { ref capability, .. } if capability == "fileinto"
            ),
            "got {err:?}",
        );
    }

    #[test]
    fn reject_without_require_errors() {
        let err = eval_script(r#"reject "no";"#, MSG).unwrap_err();
        assert!(
            matches!(err, EvalError::MissingCapability { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn unsupported_require_errors() {
        let err = eval_script(r#"require ["foreverbar"]; keep;"#, MSG).unwrap_err();
        assert!(
            matches!(err, EvalError::UnsupportedCapability(ref s) if s == "foreverbar"),
            "got {err:?}",
        );
    }

    #[test]
    fn require_out_of_order_errors() {
        let err =
            eval_script(r#"keep; require ["fileinto"];"#, MSG).unwrap_err();
        assert!(matches!(err, EvalError::RequireOutOfOrder), "got {err:?}");
    }
}