rusmes-core 0.1.2

Mailet processing engine for RusMES — composable mail processing pipeline with matchers, mailets, DKIM/SPF/DMARC, spam filtering, and AI integration
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
//! Virus scanning mailet (ClamAV integration)

use crate::mailet::{Mailet, MailetAction, MailetConfig};
use async_trait::async_trait;
use rusmes_proto::{Mail, MailState};
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpStream, UnixStream};

/// ClamAV connection mode
#[derive(Debug, Clone)]
pub enum ClamAVMode {
    UnixSocket(PathBuf),
    Tcp { host: String, port: u16 },
}

/// ClamAV configuration
#[derive(Debug, Clone)]
pub struct ClamAVConfig {
    pub mode: ClamAVMode,
    pub timeout: Duration,
}

impl Default for ClamAVConfig {
    fn default() -> Self {
        Self {
            mode: ClamAVMode::UnixSocket(PathBuf::from("/var/run/clamav/clamd.sock")),
            timeout: Duration::from_secs(30),
        }
    }
}

/// Scan result from ClamAV
#[derive(Debug)]
pub enum ScanResult {
    Clean,
    Infected { virus_name: String },
    Error { message: String },
}

/// ClamAV virus scanning mailet
pub struct VirusScanMailet {
    name: String,
    config: ClamAVConfig,
    reject_on_virus: bool,
}

impl VirusScanMailet {
    /// Create a new virus scan mailet
    pub fn new() -> Self {
        Self {
            name: "VirusScan".to_string(),
            config: ClamAVConfig::default(),
            reject_on_virus: true,
        }
    }

    /// Convert message to bytes for scanning
    ///
    /// For `MessageBody::Large`, the body is read asynchronously before
    /// serialisation.  On read failure the body section is empty and a warning
    /// is logged (fail-open to avoid blocking mail delivery).
    async fn message_to_bytes(mail: &Mail) -> Vec<u8> {
        let mut bytes = Vec::new();

        // Serialize headers
        let headers = mail.message().headers();
        for (name, values) in headers.iter() {
            for value in values {
                bytes.extend_from_slice(name.as_bytes());
                bytes.extend_from_slice(b": ");
                bytes.extend_from_slice(value.as_bytes());
                bytes.extend_from_slice(b"\r\n");
            }
        }

        // Empty line between headers and body
        bytes.extend_from_slice(b"\r\n");

        // Add body
        match mail.message().body() {
            rusmes_proto::MessageBody::Small(body_bytes) => {
                bytes.extend_from_slice(body_bytes);
            }
            rusmes_proto::MessageBody::Large(large) => match large.read_to_bytes().await {
                Ok(body_bytes) => {
                    bytes.extend_from_slice(&body_bytes);
                }
                Err(e) => {
                    tracing::warn!("Failed to read large message body for virus scan: {e}");
                }
            },
        }

        bytes
    }

    /// Connect to ClamAV daemon
    async fn connect_clamd(config: &ClamAVConfig) -> anyhow::Result<ClamAVStream> {
        match &config.mode {
            ClamAVMode::UnixSocket(path) => {
                let stream = UnixStream::connect(path).await?;
                Ok(ClamAVStream::Unix(stream))
            }
            ClamAVMode::Tcp { host, port } => {
                let stream = TcpStream::connect((host.as_str(), *port)).await?;
                Ok(ClamAVStream::Tcp(stream))
            }
        }
    }

    /// Scan message with ClamAV using INSTREAM protocol
    async fn scan_message(message: &[u8], config: &ClamAVConfig) -> anyhow::Result<ScanResult> {
        let mut stream = Self::connect_clamd(config).await?;

        // Send INSTREAM command
        stream.write_all(b"zINSTREAM\0").await?;

        // Send message in chunks
        const CHUNK_SIZE: usize = 2048;
        for chunk in message.chunks(CHUNK_SIZE) {
            // Send chunk size (4 bytes, network order)
            let len = (chunk.len() as u32).to_be_bytes();
            stream.write_all(&len).await?;

            // Send chunk data
            stream.write_all(chunk).await?;
        }

        // Send zero-length chunk to indicate end
        stream.write_all(&[0, 0, 0, 0]).await?;

        // Read response
        let mut response = String::new();
        stream.read_to_string(&mut response).await?;

        // Parse response
        Self::parse_clamd_response(&response)
    }

    /// Parse ClamAV daemon response
    fn parse_clamd_response(response: &str) -> anyhow::Result<ScanResult> {
        let response = response.trim();

        if response.ends_with("OK") {
            return Ok(ScanResult::Clean);
        }

        if response.contains("FOUND") {
            // Format: "stream: Eicar-Test-Signature FOUND"
            let parts: Vec<&str> = response.split_whitespace().collect();
            if parts.len() >= 2 {
                let virus_name = parts[1].to_string();
                return Ok(ScanResult::Infected { virus_name });
            }
        }

        if response.contains("ERROR") {
            return Ok(ScanResult::Error {
                message: response.to_string(),
            });
        }

        anyhow::bail!("Unknown clamd response: {}", response)
    }
}

impl Default for VirusScanMailet {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Mailet for VirusScanMailet {
    async fn init(&mut self, config: MailetConfig) -> anyhow::Result<()> {
        // Parse connection mode
        if let Some(mode_str) = config.get_param("mode") {
            match mode_str {
                "unix_socket" => {
                    let socket_path = config
                        .get_param("socket_path")
                        .unwrap_or("/var/run/clamav/clamd.sock");
                    self.config.mode = ClamAVMode::UnixSocket(PathBuf::from(socket_path));
                }
                "tcp" => {
                    let host = config.get_param("host").unwrap_or("localhost").to_string();
                    let port: u16 = config
                        .get_param("port")
                        .and_then(|p| p.parse().ok())
                        .unwrap_or(3310);
                    self.config.mode = ClamAVMode::Tcp { host, port };
                }
                _ => {
                    anyhow::bail!("Invalid ClamAV mode: {}", mode_str);
                }
            }
        }

        // Parse timeout
        if let Some(timeout_str) = config.get_param("timeout") {
            if let Ok(timeout_secs) = timeout_str.parse::<u64>() {
                self.config.timeout = Duration::from_secs(timeout_secs);
            }
        }

        // Parse reject_on_virus
        if let Some(reject_str) = config.get_param("reject_on_virus") {
            self.reject_on_virus = reject_str.parse()?;
        }

        tracing::info!(
            "Initialized VirusScanMailet (mode: {:?}, reject on virus: {})",
            self.config.mode,
            self.reject_on_virus
        );
        Ok(())
    }

    async fn service(&self, mail: &mut Mail) -> anyhow::Result<MailetAction> {
        tracing::debug!("Scanning mail {} for viruses", mail.id());

        // Extract message content
        let message_bytes = Self::message_to_bytes(mail).await;

        // Scan with ClamAV
        let result = match Self::scan_message(&message_bytes, &self.config).await {
            Ok(result) => result,
            Err(e) => {
                tracing::error!("ClamAV scan error for {}: {}", mail.id(), e);
                mail.set_attribute("virus.scan_error", e.to_string());
                // Fail open - don't block mail if ClamAV is unavailable
                return Ok(MailetAction::Continue);
            }
        };

        match result {
            ScanResult::Clean => {
                mail.set_attribute("virus.result", "clean");
                tracing::info!("Virus scan clean for {}", mail.id());
            }
            ScanResult::Infected { virus_name } => {
                mail.set_attribute("virus.result", "infected");
                mail.set_attribute("virus.name", virus_name.clone());
                tracing::warn!("Virus detected in {}: {}", mail.id(), virus_name);

                if self.reject_on_virus {
                    mail.state = MailState::Ghost;
                }
            }
            ScanResult::Error { message } => {
                mail.set_attribute("virus.scan_error", message.clone());
                tracing::error!("ClamAV error for {}: {}", mail.id(), message);
            }
        }

        Ok(MailetAction::Continue)
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// Wrapper for Unix and TCP streams
enum ClamAVStream {
    Unix(UnixStream),
    Tcp(TcpStream),
}

impl ClamAVStream {
    async fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
        match self {
            ClamAVStream::Unix(stream) => stream.write_all(buf).await,
            ClamAVStream::Tcp(stream) => stream.write_all(buf).await,
        }
    }

    async fn read_to_string(&mut self, buf: &mut String) -> std::io::Result<usize> {
        match self {
            ClamAVStream::Unix(stream) => stream.read_to_string(buf).await,
            ClamAVStream::Tcp(stream) => stream.read_to_string(buf).await,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;
    use rusmes_proto::{HeaderMap, MailAddress, MessageBody, MimeMessage};
    use std::str::FromStr;

    fn create_test_mail(sender: &str, recipients: Vec<&str>) -> Mail {
        let sender_addr = MailAddress::from_str(sender).ok();
        let recipient_addrs: Vec<MailAddress> = recipients
            .iter()
            .filter_map(|r| MailAddress::from_str(r).ok())
            .collect();

        let message = MimeMessage::new(
            HeaderMap::new(),
            MessageBody::Small(Bytes::from("Test message")),
        );

        Mail::new(sender_addr, recipient_addrs, message, None, None)
    }

    #[tokio::test]
    async fn test_virus_scan_mailet_creation() {
        let mailet = VirusScanMailet::new();
        assert_eq!(mailet.name(), "VirusScan");
        assert!(mailet.reject_on_virus);
    }

    #[tokio::test]
    async fn test_virus_scan_mailet_default() {
        let mailet = VirusScanMailet::default();
        assert_eq!(mailet.name(), "VirusScan");
    }

    #[tokio::test]
    async fn test_clamav_config_default() {
        let config = ClamAVConfig::default();
        assert!(matches!(config.mode, ClamAVMode::UnixSocket(_)));
        assert_eq!(config.timeout, Duration::from_secs(30));
    }

    #[tokio::test]
    async fn test_virus_scan_init_unix_socket() {
        let mut mailet = VirusScanMailet::new();
        let config = MailetConfig::new("VirusScan")
            .with_param("mode".to_string(), "unix_socket".to_string())
            .with_param(
                "socket_path".to_string(),
                "/custom/path/clamd.sock".to_string(),
            );

        let result = mailet.init(config).await;
        assert!(result.is_ok());

        if let ClamAVMode::UnixSocket(path) = &mailet.config.mode {
            assert_eq!(path.to_str().unwrap(), "/custom/path/clamd.sock");
        } else {
            panic!("Expected UnixSocket mode");
        }
    }

    #[tokio::test]
    async fn test_virus_scan_init_tcp() {
        let mut mailet = VirusScanMailet::new();
        let config = MailetConfig::new("VirusScan")
            .with_param("mode".to_string(), "tcp".to_string())
            .with_param("host".to_string(), "clamav.example.com".to_string())
            .with_param("port".to_string(), "3310".to_string());

        let result = mailet.init(config).await;
        assert!(result.is_ok());

        if let ClamAVMode::Tcp { host, port } = &mailet.config.mode {
            assert_eq!(host, "clamav.example.com");
            assert_eq!(*port, 3310);
        } else {
            panic!("Expected TCP mode");
        }
    }

    #[tokio::test]
    async fn test_virus_scan_init_tcp_default_port() {
        let mut mailet = VirusScanMailet::new();
        let config = MailetConfig::new("VirusScan")
            .with_param("mode".to_string(), "tcp".to_string())
            .with_param("host".to_string(), "clamav.example.com".to_string());

        let result = mailet.init(config).await;
        assert!(result.is_ok());

        if let ClamAVMode::Tcp { host, port } = &mailet.config.mode {
            assert_eq!(host, "clamav.example.com");
            assert_eq!(*port, 3310);
        } else {
            panic!("Expected TCP mode");
        }
    }

    #[tokio::test]
    async fn test_virus_scan_init_invalid_mode() {
        let mut mailet = VirusScanMailet::new();
        let config = MailetConfig::new("VirusScan")
            .with_param("mode".to_string(), "invalid_mode".to_string());

        let result = mailet.init(config).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_virus_scan_init_timeout() {
        let mut mailet = VirusScanMailet::new();
        let config =
            MailetConfig::new("VirusScan").with_param("timeout".to_string(), "60".to_string());

        let result = mailet.init(config).await;
        assert!(result.is_ok());
        assert_eq!(mailet.config.timeout, Duration::from_secs(60));
    }

    #[tokio::test]
    async fn test_virus_scan_init_reject_on_virus() {
        let mut mailet = VirusScanMailet::new();
        let config = MailetConfig::new("VirusScan")
            .with_param("reject_on_virus".to_string(), "false".to_string());

        let result = mailet.init(config).await;
        assert!(result.is_ok());
        assert!(!mailet.reject_on_virus);
    }

    #[tokio::test]
    async fn test_message_to_bytes_no_headers() {
        let mail = create_test_mail("sender@example.com", vec!["recipient@test.com"]);
        let bytes = VirusScanMailet::message_to_bytes(&mail).await;
        let message = String::from_utf8_lossy(&bytes);

        // With no headers, we still have one separator before body
        assert!(message.starts_with("\r\n"));
        assert!(message.contains("Test message"));
    }

    #[test]
    fn test_parse_clamd_response_clean() {
        let response = "stream: OK";
        let result = VirusScanMailet::parse_clamd_response(response).unwrap();

        assert!(matches!(result, ScanResult::Clean));
    }

    #[test]
    fn test_parse_clamd_response_infected() {
        let response = "stream: Eicar-Test-Signature FOUND";
        let result = VirusScanMailet::parse_clamd_response(response).unwrap();

        if let ScanResult::Infected { virus_name } = result {
            assert_eq!(virus_name, "Eicar-Test-Signature");
        } else {
            panic!("Expected Infected result");
        }
    }

    #[test]
    fn test_parse_clamd_response_error() {
        let response = "stream: ERROR";
        let result = VirusScanMailet::parse_clamd_response(response).unwrap();

        assert!(matches!(result, ScanResult::Error { .. }));
    }

    #[test]
    fn test_parse_clamd_response_unknown() {
        let response = "unknown response format";
        let result = VirusScanMailet::parse_clamd_response(response);

        assert!(result.is_err());
    }

    #[test]
    fn test_parse_clamd_response_with_whitespace() {
        let response = "  stream: OK  \n";
        let result = VirusScanMailet::parse_clamd_response(response).unwrap();

        assert!(matches!(result, ScanResult::Clean));
    }

    #[test]
    fn test_parse_clamd_response_different_virus() {
        let response = "stream: Win.Test.Malware FOUND";
        let result = VirusScanMailet::parse_clamd_response(response).unwrap();

        if let ScanResult::Infected { virus_name } = result {
            assert_eq!(virus_name, "Win.Test.Malware");
        } else {
            panic!("Expected Infected result");
        }
    }
}