Skip to main content

mockforge_smtp/
server.rs

1//! SMTP server implementation
2
3use crate::{SmtpConfig, SmtpSpecRegistry};
4use mockforge_protocol::protocol_abstraction::{
5    MessagePattern, MiddlewareChain, Protocol, ProtocolRequest, SpecRegistry,
6};
7use mockforge_protocol::Result;
8use std::collections::HashMap;
9use std::net::SocketAddr;
10use std::pin::Pin;
11use std::sync::Arc;
12use std::task::{Context, Poll};
13use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, ReadBuf};
14use tokio::net::{TcpListener, TcpStream};
15use tokio::sync::Semaphore;
16use tokio_rustls::{rustls, server::TlsStream, TlsAcceptor};
17use tracing::{debug, error, info, warn};
18
19/// Hard cap on a single SMTP protocol line (command or DATA line) before the
20/// connection is dropped. SMTP lines are spec-limited to ~1000 bytes, so 1 MiB
21/// is generous headroom while still bounding a newline-less flood (#754).
22const MAX_LINE_BYTES: usize = 1024 * 1024;
23
24/// Outcome of a bounded line read.
25enum LineRead {
26    /// A full line (terminated by `\n` or by EOF after some bytes) was read.
27    Ok,
28    /// The stream ended with no further bytes.
29    Eof,
30    /// The line exceeded the byte cap before a newline arrived.
31    TooLong,
32}
33
34/// Read a single `\n`-terminated line into `line`, but stop and report
35/// [`LineRead::TooLong`] once the accumulated line exceeds `max_bytes`.
36///
37/// This wraps `read_until` one byte chunk at a time so an attacker can't make
38/// the underlying buffer grow without bound by simply never sending a newline.
39async fn read_line_capped<R>(
40    reader: &mut R,
41    line: &mut Vec<u8>,
42    max_bytes: usize,
43) -> std::io::Result<LineRead>
44where
45    R: AsyncBufReadExt + Unpin,
46{
47    loop {
48        let before = line.len();
49        let n = reader.read_until(b'\n', line).await?;
50        if n == 0 {
51            // EOF: if we'd already accumulated a partial line, treat it as a
52            // final line; otherwise the stream is closed.
53            return Ok(if line.is_empty() {
54                LineRead::Eof
55            } else {
56                LineRead::Ok
57            });
58        }
59        let ends_with_newline = line.last() == Some(&b'\n');
60        if line.len() > max_bytes {
61            return Ok(LineRead::TooLong);
62        }
63        if ends_with_newline {
64            return Ok(LineRead::Ok);
65        }
66        // No newline yet and under the cap — `read_until` returned because the
67        // buffered chunk was exhausted; keep reading. Guard against a stuck
68        // reader that returns 0-growth without EOF.
69        if line.len() == before {
70            return Ok(LineRead::Ok);
71        }
72    }
73}
74
75/// Stream wrapper that can be either plaintext TCP or TLS-upgraded.
76/// The session handler starts each connection as `Plain` and swaps to
77/// `Tls` mid-stream when the client sends STARTTLS (RFC 3207). The
78/// enum-plus-manual-AsyncRead/Write-impl pattern is what lets us put
79/// the upgraded stream back into the existing `BufReader` without
80/// rewriting the whole session loop.
81pub enum SmtpStream {
82    /// Plaintext TCP before STARTTLS (or when STARTTLS is disabled).
83    Plain(TcpStream),
84    /// TLS-encrypted after STARTTLS completes. Boxed to keep the
85    /// enum size manageable — `TlsStream` is large.
86    Tls(Box<TlsStream<TcpStream>>),
87}
88
89impl AsyncRead for SmtpStream {
90    fn poll_read(
91        self: Pin<&mut Self>,
92        cx: &mut Context<'_>,
93        buf: &mut ReadBuf<'_>,
94    ) -> Poll<std::io::Result<()>> {
95        match self.get_mut() {
96            SmtpStream::Plain(s) => Pin::new(s).poll_read(cx, buf),
97            SmtpStream::Tls(s) => Pin::new(s.as_mut()).poll_read(cx, buf),
98        }
99    }
100}
101
102impl AsyncWrite for SmtpStream {
103    fn poll_write(
104        self: Pin<&mut Self>,
105        cx: &mut Context<'_>,
106        buf: &[u8],
107    ) -> Poll<std::io::Result<usize>> {
108        match self.get_mut() {
109            SmtpStream::Plain(s) => Pin::new(s).poll_write(cx, buf),
110            SmtpStream::Tls(s) => Pin::new(s.as_mut()).poll_write(cx, buf),
111        }
112    }
113
114    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
115        match self.get_mut() {
116            SmtpStream::Plain(s) => Pin::new(s).poll_flush(cx),
117            SmtpStream::Tls(s) => Pin::new(s.as_mut()).poll_flush(cx),
118        }
119    }
120
121    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
122        match self.get_mut() {
123            SmtpStream::Plain(s) => Pin::new(s).poll_shutdown(cx),
124            SmtpStream::Tls(s) => Pin::new(s.as_mut()).poll_shutdown(cx),
125        }
126    }
127}
128
129/// SMTP server
130pub struct SmtpServer {
131    config: SmtpConfig,
132    spec_registry: Arc<SmtpSpecRegistry>,
133    middleware_chain: Arc<MiddlewareChain>,
134    #[allow(dead_code)]
135    tls_acceptor: Option<TlsAcceptor>,
136}
137
138impl SmtpServer {
139    /// Create a new SMTP server
140    pub fn new(config: SmtpConfig, spec_registry: Arc<SmtpSpecRegistry>) -> Result<Self> {
141        let middleware_chain = Arc::new(MiddlewareChain::new());
142
143        let tls_acceptor = if config.enable_starttls {
144            Some(Self::load_tls_acceptor(&config)?)
145        } else {
146            None
147        };
148
149        Ok(Self {
150            config,
151            spec_registry,
152            middleware_chain,
153            tls_acceptor,
154        })
155    }
156
157    /// Load TLS acceptor from certificate and key files
158    fn load_tls_acceptor(config: &SmtpConfig) -> Result<TlsAcceptor> {
159        use rustls_pemfile::{certs, pkcs8_private_keys};
160        use std::fs::File;
161        use std::io::BufReader;
162
163        let cert_path = config.tls_cert_path.as_ref().ok_or_else(|| {
164            mockforge_protocol::Error::internal("TLS certificate path not configured")
165        })?;
166        let key_path = config.tls_key_path.as_ref().ok_or_else(|| {
167            mockforge_protocol::Error::internal("TLS private key path not configured")
168        })?;
169
170        let cert_file = File::open(cert_path)?;
171        let certs = certs(&mut BufReader::new(cert_file)).collect::<std::io::Result<Vec<_>>>()?;
172
173        let key_file = File::open(key_path)?;
174        let key = pkcs8_private_keys(&mut BufReader::new(key_file))
175            .next()
176            .ok_or_else(|| mockforge_protocol::Error::internal("No private keys found"))??;
177
178        // Explicit provider: ring and aws-lc-rs are both compiled into the
179        // workspace, so rustls can't pick a process default on its own.
180        let provider = Arc::new(rustls::crypto::ring::default_provider());
181        let mut server_config = rustls::ServerConfig::builder_with_provider(provider)
182            .with_safe_default_protocol_versions()
183            .map_err(|e| mockforge_protocol::Error::internal(format!("TLS config error: {}", e)))?
184            .with_no_client_auth()
185            .with_single_cert(certs, key.into())
186            .map_err(|e| mockforge_protocol::Error::internal(format!("TLS config error: {}", e)))?;
187
188        server_config.alpn_protocols = vec![b"smtp".to_vec()];
189
190        Ok(TlsAcceptor::from(Arc::new(server_config)))
191    }
192
193    /// Create a new SMTP server with custom middleware
194    pub fn with_middleware(
195        config: SmtpConfig,
196        spec_registry: Arc<SmtpSpecRegistry>,
197        middleware_chain: Arc<MiddlewareChain>,
198    ) -> Result<Self> {
199        let tls_acceptor = if config.enable_starttls {
200            Some(Self::load_tls_acceptor(&config)?)
201        } else {
202            None
203        };
204
205        Ok(Self {
206            config,
207            spec_registry,
208            middleware_chain,
209            tls_acceptor,
210        })
211    }
212
213    /// Start the SMTP server
214    pub async fn start(&self) -> Result<()> {
215        let addr = format!("{}:{}", self.config.host, self.config.port);
216        let listener = TcpListener::bind(&addr).await?;
217
218        info!("SMTP server listening on {}", addr);
219
220        // Cap concurrent sessions at `max_connections` so a connection flood
221        // can't spawn unbounded tasks (#755). A permit is acquired before each
222        // session task and moved into it, freeing on disconnect.
223        let max_connections = self.config.max_connections.max(1);
224        let connection_limiter = Arc::new(Semaphore::new(max_connections));
225        let max_message_bytes = self.config.max_message_bytes;
226
227        loop {
228            match listener.accept().await {
229                Ok((stream, peer_addr)) => {
230                    debug!("New SMTP connection from {}", peer_addr);
231
232                    let permit = match connection_limiter.clone().acquire_owned().await {
233                        Ok(permit) => permit,
234                        Err(_) => {
235                            // Semaphore closed — should not happen while the
236                            // server runs, but bail cleanly if it does.
237                            error!("SMTP connection limiter closed; stopping accept loop");
238                            break Ok(());
239                        }
240                    };
241
242                    let registry = self.spec_registry.clone();
243                    let middleware = self.middleware_chain.clone();
244                    let hostname = self.config.hostname.clone();
245                    let tls_acceptor = self.tls_acceptor.clone();
246
247                    tokio::spawn(async move {
248                        // Hold the permit for the lifetime of the session.
249                        let _permit = permit;
250                        if let Err(e) = handle_smtp_session(
251                            SmtpStream::Plain(stream),
252                            peer_addr,
253                            registry,
254                            middleware,
255                            hostname,
256                            tls_acceptor,
257                            max_message_bytes,
258                        )
259                        .await
260                        {
261                            error!("SMTP session error from {}: {}", peer_addr, e);
262                        }
263                    });
264                }
265                Err(e) => {
266                    error!("Failed to accept SMTP connection: {}", e);
267                }
268            }
269        }
270    }
271}
272
273/// Handle a single SMTP session. Accepts an `SmtpStream` (plaintext
274/// or TLS) so a STARTTLS mid-session upgrade can swap the underlying
275/// transport without tearing down the connection.
276async fn handle_smtp_session(
277    stream: SmtpStream,
278    peer_addr: SocketAddr,
279    registry: Arc<SmtpSpecRegistry>,
280    middleware: Arc<MiddlewareChain>,
281    hostname: String,
282    tls_acceptor: Option<TlsAcceptor>,
283    max_message_bytes: usize,
284) -> Result<()> {
285    // Keep read + write on the same `SmtpStream` so STARTTLS can
286    // upgrade both halves atomically. Writes go through
287    // `reader.get_mut()` to avoid an extra split.
288    let mut reader = BufReader::new(stream);
289
290    // Send greeting
291    let greeting = format!("220 {} ESMTP MockForge SMTP Server\r\n", hostname);
292    reader.get_mut().write_all(greeting.as_bytes()).await?;
293
294    let mut session_state = SessionState::with_max_message_bytes(max_message_bytes);
295    // Byte-level accumulator so 8BITMIME bodies (Latin-1, UTF-8 with
296    // explicit content-transfer-encoding, etc.) round-trip verbatim.
297    // `read_line` would fail on non-UTF-8 inputs.
298    let mut line: Vec<u8> = Vec::new();
299
300    loop {
301        // Bound each line read so a client that never sends a newline can't
302        // make `read_until` accumulate an unbounded buffer (#754).
303        match read_line_capped(&mut reader, &mut line, MAX_LINE_BYTES).await? {
304            LineRead::Eof => break,
305            LineRead::Ok => {}
306            LineRead::TooLong => {
307                warn!("SMTP line from {} exceeded {} bytes; closing", peer_addr, MAX_LINE_BYTES);
308                reader.get_mut().write_all(b"500 line too long\r\n").await?;
309                break;
310            }
311        }
312
313        // DATA mode bypasses command parsing entirely. Without this, the
314        // first word of every body line would be matched against the SMTP
315        // verb table — any body beginning with "Hello ..." / "Data ..." /
316        // "Quit ..." / etc. was being re-interpreted as a command and
317        // dropped on the floor. Inside DATA mode, only the bare "." ends
318        // the message; everything else (headers, blank separator, body
319        // lines, verbatim) accumulates *as bytes*.
320        if session_state.in_data_mode {
321            // Strip trailing \r\n / \n. If the line is exactly "." +
322            // newline, that terminates the DATA section per RFC 5321.
323            let trimmed = strip_line_terminator(&line);
324            if trimmed == b"." {
325                session_state.in_data_mode = false;
326                let response =
327                    process_email(&session_state, &registry, &middleware, peer_addr).await?;
328                reader.get_mut().write_all(response.as_bytes()).await?;
329                session_state.reset();
330            } else if session_state.data_would_overflow(trimmed.len() + 1) {
331                // Reject oversized messages instead of buffering them to OOM
332                // (#754). Per RFC 5321 the 552 response ends the DATA phase;
333                // reset the transaction and leave DATA mode.
334                warn!(
335                    "SMTP DATA from {} exceeded max_message_bytes ({}); rejecting",
336                    peer_addr, max_message_bytes
337                );
338                reader
339                    .get_mut()
340                    .write_all(b"552 message size exceeds fixed maximum message size\r\n")
341                    .await?;
342                session_state.reset();
343            } else {
344                session_state.data.extend_from_slice(trimmed);
345                session_state.data.push(b'\n');
346            }
347            line.clear();
348            continue;
349        }
350
351        // Outside DATA mode, SMTP verbs are ASCII-only per spec. Decode
352        // lossily so a malformed UTF-8 byte doesn't crash the session,
353        // then parse the verb table as before.
354        let as_str = String::from_utf8_lossy(&line);
355        let command = as_str.trim();
356        debug!("SMTP command from {}: {}", peer_addr, command);
357
358        // AUTH continuation: if the previous command opened an AUTH
359        // dialog, this line is base64 credential material, not an
360        // SMTP verb. Handle it here before the verb table would send
361        // back "502 Command not implemented".
362        if let Some(stage) = session_state.pending_auth.clone() {
363            handle_auth_continuation(stage, command, &mut session_state, reader.get_mut()).await?;
364            line.clear();
365            continue;
366        }
367
368        // Skip blank lines outside DATA mode — otherwise idle keep-alive
369        // newlines would reach the verb parser.
370        if command.is_empty() {
371            line.clear();
372            continue;
373        }
374
375        // STARTTLS is handled at this outer level (not in the verb
376        // table) because we need to swap out the BufReader's owned
377        // stream. Only fires when (a) client asked for STARTTLS,
378        // (b) we're still plaintext, and (c) a TLS acceptor is
379        // configured. Per RFC 3207, the upgraded session starts
380        // completely fresh — the client MUST re-EHLO.
381        if command.eq_ignore_ascii_case("STARTTLS") {
382            if !matches!(reader.get_ref(), SmtpStream::Plain(_)) {
383                // Already TLS — refuse per spec.
384                reader.get_mut().write_all(b"503 Command not allowed\r\n").await?;
385            } else if let Some(acceptor) = tls_acceptor.clone() {
386                reader.get_mut().write_all(b"220 Ready to start TLS\r\n").await?;
387                reader.get_mut().flush().await?;
388
389                let inner = reader.into_inner();
390                let tcp = match inner {
391                    SmtpStream::Plain(t) => t,
392                    SmtpStream::Tls(_) => unreachable!("checked is Plain above"),
393                };
394                let tls_stream = acceptor.accept(tcp).await.map_err(|e| {
395                    mockforge_protocol::Error::internal(format!("TLS accept failed: {e}"))
396                })?;
397                reader = BufReader::new(SmtpStream::Tls(Box::new(tls_stream)));
398                session_state = SessionState::with_max_message_bytes(max_message_bytes);
399                line.clear();
400                continue;
401            } else {
402                // STARTTLS requested but no cert configured.
403                reader
404                    .get_mut()
405                    .write_all(b"454 TLS not available due to temporary reason\r\n")
406                    .await?;
407            }
408            line.clear();
409            continue;
410        }
411
412        // Parse and handle SMTP command
413        match handle_smtp_command(
414            command,
415            &mut session_state,
416            reader.get_mut(),
417            &hostname,
418            &registry,
419            &middleware,
420            peer_addr,
421        )
422        .await
423        {
424            Ok(should_continue) => {
425                if !should_continue {
426                    debug!("SMTP session ended for {}", peer_addr);
427                    break;
428                }
429            }
430            Err(e) => {
431                error!("Error handling SMTP command: {}", e);
432                let error_response = "500 Internal server error\r\n";
433                reader.get_mut().write_all(error_response.as_bytes()).await?;
434            }
435        }
436
437        line.clear();
438    }
439
440    Ok(())
441}
442
443/// Decode `AUTH PLAIN`'s base64 credential blob. The SASL PLAIN
444/// payload is `\0authzid\0authcid\0passwd` (authzid may be empty).
445/// Returns the authcid (username) on success; `None` if the base64
446/// is malformed or the structure is wrong. The mock accepts any
447/// credentials — we only parse enough to pull out the username for
448/// mailbox observability.
449fn decode_plain_auth(b64: &str) -> Option<String> {
450    use base64::Engine as _;
451    let decoded = base64::engine::general_purpose::STANDARD.decode(b64.trim()).ok()?;
452    // Split on NULs. Valid forms produce 3 segments; we just need the
453    // middle one (authcid).
454    let mut parts = decoded.split(|b| *b == 0);
455    let _authzid = parts.next()?;
456    let authcid = parts.next()?;
457    let _passwd = parts.next()?;
458    Some(String::from_utf8_lossy(authcid).into_owned())
459}
460
461/// Handle the line *following* an AUTH open. Advances or completes
462/// the dialog depending on the stage we left off in.
463async fn handle_auth_continuation<W: AsyncWriteExt + Unpin>(
464    stage: AuthStage,
465    line: &str,
466    state: &mut SessionState,
467    writer: &mut W,
468) -> Result<()> {
469    use base64::Engine as _;
470    match stage {
471        AuthStage::AwaitingPlainCredentials => {
472            state.pending_auth = None;
473            match decode_plain_auth(line) {
474                Some(user) => {
475                    state.authenticated_user = Some(user);
476                    writer.write_all(b"235 2.7.0 Authentication successful\r\n").await?;
477                }
478                None => {
479                    writer.write_all(b"535 5.7.8 Authentication credentials invalid\r\n").await?;
480                }
481            }
482        }
483        AuthStage::AwaitingLoginUsername => {
484            let decoded = base64::engine::general_purpose::STANDARD
485                .decode(line.trim())
486                .ok()
487                .and_then(|b| String::from_utf8(b).ok());
488            match decoded {
489                Some(u) => {
490                    state.authenticated_user = Some(u);
491                    state.pending_auth = Some(AuthStage::AwaitingLoginPassword);
492                    // "Password:" base64 = "UGFzc3dvcmQ6".
493                    writer.write_all(b"334 UGFzc3dvcmQ6\r\n").await?;
494                }
495                None => {
496                    state.pending_auth = None;
497                    state.authenticated_user = None;
498                    writer.write_all(b"535 5.7.8 Authentication credentials invalid\r\n").await?;
499                }
500            }
501        }
502        AuthStage::AwaitingLoginPassword => {
503            state.pending_auth = None;
504            // We don't actually verify the password — accept anything
505            // that decodes as base64. On decode failure reject with
506            // 535 so clients that intentionally pass junk (negative
507            // tests) still get a sane response.
508            if base64::engine::general_purpose::STANDARD.decode(line.trim()).is_ok() {
509                writer.write_all(b"235 2.7.0 Authentication successful\r\n").await?;
510            } else {
511                state.authenticated_user = None;
512                writer.write_all(b"535 5.7.8 Authentication credentials invalid\r\n").await?;
513            }
514        }
515    }
516    Ok(())
517}
518
519/// Strip trailing `\r\n` or `\n` from an SMTP line read via
520/// `read_until(b'\n', ...)`. Keeps the rest of the bytes intact so
521/// a non-UTF-8 body round-trips verbatim.
522fn strip_line_terminator(line: &[u8]) -> &[u8] {
523    let mut end = line.len();
524    if end > 0 && line[end - 1] == b'\n' {
525        end -= 1;
526    }
527    if end > 0 && line[end - 1] == b'\r' {
528        end -= 1;
529    }
530    &line[..end]
531}
532
533/// Handle a single SMTP command
534async fn handle_smtp_command<W: AsyncWriteExt + Unpin>(
535    command: &str,
536    state: &mut SessionState,
537    writer: &mut W,
538    hostname: &str,
539    registry: &Arc<SmtpSpecRegistry>,
540    middleware: &Arc<MiddlewareChain>,
541    peer_addr: SocketAddr,
542) -> Result<bool> {
543    let parts: Vec<&str> = command.splitn(2, ' ').collect();
544    let cmd = parts[0].to_uppercase();
545
546    match cmd.as_str() {
547        "HELLO" | "EHLO" => {
548            let domain = parts.get(1).unwrap_or(&hostname);
549            let response = if cmd == "EHLO" {
550                // Advertise AUTH PLAIN LOGIN so clients that gate on the
551                // capability line (lettre with Credentials, Python's
552                // smtplib.login, etc.) actually try AUTH instead of
553                // skipping to MAIL FROM.
554                format!(
555                    "250-{} Hello {}\r\n\
556                     250-SIZE 10485760\r\n\
557                     250-8BITMIME\r\n\
558                     250-STARTTLS\r\n\
559                     250-AUTH PLAIN LOGIN\r\n\
560                     250 HELP\r\n",
561                    hostname, domain
562                )
563            } else {
564                format!("250 {} Hello {}\r\n", hostname, domain)
565            };
566            writer.write_all(response.as_bytes()).await?;
567            Ok(true)
568        }
569
570        "MAIL" => {
571            if let Some(from_part) = parts.get(1) {
572                // Parse MAIL FROM:<address>
573                let from = extract_email_address(from_part);
574                state.mail_from = Some(from);
575                writer.write_all(b"250 OK\r\n").await?;
576            } else {
577                writer.write_all(b"501 Syntax error in parameters\r\n").await?;
578            }
579            Ok(true)
580        }
581
582        "RCPT" => {
583            if let Some(to_part) = parts.get(1) {
584                // Parse RCPT TO:<address>
585                let to = extract_email_address(to_part);
586                state.rcpt_to.push(to);
587                writer.write_all(b"250 OK\r\n").await?;
588            } else {
589                writer.write_all(b"501 Syntax error in parameters\r\n").await?;
590            }
591            Ok(true)
592        }
593
594        "DATA" => {
595            writer.write_all(b"354 Start mail input; end with <CRLF>.<CRLF>\r\n").await?;
596            state.in_data_mode = true;
597            Ok(true)
598        }
599
600        "RSET" => {
601            state.reset();
602            writer.write_all(b"250 OK\r\n").await?;
603            Ok(true)
604        }
605
606        "NOOP" => {
607            writer.write_all(b"250 OK\r\n").await?;
608            Ok(true)
609        }
610
611        "QUIT" => {
612            writer.write_all(b"221 Bye\r\n").await?;
613            Ok(false) // End session
614        }
615
616        "STARTTLS" => {
617            // Mock STARTTLS implementation - accept but don't actually upgrade
618            writer.write_all(b"220 Ready to start TLS\r\n").await?;
619            Ok(true)
620        }
621
622        "AUTH" => {
623            // AUTH dispatch. Any credentials are accepted — this is a
624            // mock, not an authenticator — but we do go through the full
625            // handshake so clients that gate on the 334/235 responses
626            // work as expected.
627            //
628            // `parts` uses `splitn(2, ' ')`, so for `AUTH PLAIN <b64>`
629            // we get parts = ["AUTH", "PLAIN <b64>"]. Split the rest
630            // into its own mechanism + optional initial-response piece.
631            let rest = parts.get(1).copied().unwrap_or("");
632            let mut auth_args = rest.splitn(2, ' ');
633            let mechanism = auth_args.next().map(|s| s.to_ascii_uppercase()).unwrap_or_default();
634            let initial_response = auth_args.next().map(str::trim).filter(|s| !s.is_empty());
635            match mechanism.as_str() {
636                "PLAIN" => {
637                    // Two forms:
638                    //   "AUTH PLAIN <base64>"          — single-shot
639                    //   "AUTH PLAIN\r\n" then client → <base64>  — two-shot
640                    if let Some(b64) = initial_response {
641                        match decode_plain_auth(b64) {
642                            Some(user) => {
643                                state.authenticated_user = Some(user);
644                                writer
645                                    .write_all(b"235 2.7.0 Authentication successful\r\n")
646                                    .await?;
647                            }
648                            None => {
649                                writer
650                                    .write_all(b"535 5.7.8 Authentication credentials invalid\r\n")
651                                    .await?;
652                            }
653                        }
654                    } else {
655                        state.pending_auth = Some(AuthStage::AwaitingPlainCredentials);
656                        // 334 with empty challenge = "send me the SASL initial response".
657                        writer.write_all(b"334 \r\n").await?;
658                    }
659                    Ok(true)
660                }
661                "LOGIN" => {
662                    state.pending_auth = Some(AuthStage::AwaitingLoginUsername);
663                    // "Username:" base64-encoded = "VXNlcm5hbWU6".
664                    writer.write_all(b"334 VXNlcm5hbWU6\r\n").await?;
665                    Ok(true)
666                }
667                _ => {
668                    writer
669                        .write_all(b"504 5.5.4 Authentication mechanism not supported\r\n")
670                        .await?;
671                    Ok(true)
672                }
673            }
674        }
675
676        "HELP" => {
677            let help_text = "214-Commands supported:\r\n\
678                            214-  HELLO EHLO MAIL RCPT DATA\r\n\
679                            214-  RSET NOOP QUIT HELP STARTTLS\r\n\
680                            214 End of HELP info\r\n";
681            writer.write_all(help_text.as_bytes()).await?;
682            Ok(true)
683        }
684
685        _ => {
686            // DATA-mode lines are short-circuited before `handle_smtp_command`
687            // is called (see `handle_smtp_session`), so we only land here for
688            // genuinely unknown verbs.
689            if state.in_data_mode {
690                // Defensive fallback in case the short-circuit is ever
691                // bypassed — keep the original accumulator behavior so the
692                // session doesn't derail.
693                if command == "." {
694                    state.in_data_mode = false;
695                    let response = process_email(state, registry, middleware, peer_addr).await?;
696                    writer.write_all(response.as_bytes()).await?;
697                    state.reset();
698                } else if state.data_would_overflow(command.len() + 1) {
699                    // Mirror the primary DATA-path cap so the fallback can't be
700                    // used to bypass max_message_bytes (#754).
701                    warn!("SMTP DATA fallback exceeded max_message_bytes; rejecting");
702                    writer
703                        .write_all(b"552 message size exceeds fixed maximum message size\r\n")
704                        .await?;
705                    state.reset();
706                } else {
707                    // Command path: the caller already trimmed the line
708                    // into a `&str`. Non-ASCII bodies are accumulated
709                    // via the byte-level DATA-mode branch in
710                    // `handle_smtp_session`; this fallback just
711                    // preserves the UTF-8 subset.
712                    state.data.extend_from_slice(command.as_bytes());
713                    state.data.push(b'\n');
714                }
715                Ok(true)
716            } else {
717                warn!("Unknown SMTP command: {}", command);
718                writer.write_all(b"502 Command not implemented\r\n").await?;
719                Ok(true)
720            }
721        }
722    }
723}
724
725/// Process received email and generate response
726async fn process_email(
727    state: &SessionState,
728    registry: &Arc<SmtpSpecRegistry>,
729    middleware: &Arc<MiddlewareChain>,
730    peer_addr: SocketAddr,
731) -> Result<String> {
732    let from = state
733        .mail_from
734        .as_ref()
735        .ok_or_else(|| mockforge_protocol::Error::internal("Missing MAIL FROM"))?;
736    let to = state.rcpt_to.join(", ");
737
738    // Extract subject from data
739    let subject = extract_subject(&state.data);
740
741    // Capture the delivered message in the in-memory mailbox before we
742    // touch fixture-driven response generation. The spec-registry's
743    // storage logic used to live inside `generate_mock_response` gated on
744    // `fixture.storage.save_to_mailbox`, which meant that if no fixture
745    // matched (the common case: users running the mock SMTP to inspect
746    // outgoing mail from their application) the message would silently
747    // disappear AND the server would return a 500 to the client. Capture
748    // is the primary contract of a mock SMTP; fixture matching should only
749    // affect the reply.
750    let captured = crate::fixtures::StoredEmail {
751        id: uuid::Uuid::new_v4().to_string(),
752        from: from.clone(),
753        to: state.rcpt_to.clone(),
754        subject: subject.clone(),
755        // `body` is `String`; decode lossy so callers that only want a
756        // preview of a UTF-8 message aren't forced to round-trip
757        // through `raw`. Byte-exact consumers use `raw`.
758        body: String::from_utf8_lossy(&state.data).into_owned(),
759        headers: HashMap::from([
760            ("from".to_string(), from.clone()),
761            ("to".to_string(), to.clone()),
762            ("subject".to_string(), subject.clone()),
763        ]),
764        received_at: chrono::Utc::now(),
765        raw: Some(state.data.clone()),
766    };
767    if let Err(e) = registry.store_email(captured) {
768        warn!("Failed to store email in mailbox: {}", e);
769    }
770
771    // Create protocol request
772    let mut request = ProtocolRequest {
773        protocol: Protocol::Smtp,
774        pattern: MessagePattern::OneWay,
775        operation: "SEND".to_string(),
776        path: from.clone(),
777        topic: None,
778        routing_key: None,
779        partition: None,
780        qos: None,
781        metadata: HashMap::from([
782            ("from".to_string(), from.clone()),
783            ("to".to_string(), to.clone()),
784            ("subject".to_string(), subject.clone()),
785        ]),
786        body: Some(state.data.clone()),
787        client_ip: Some(peer_addr.ip().to_string()),
788    };
789
790    // Process through middleware (may short-circuit, e.g., auth rejection)
791    if let Some(short_circuit_response) = middleware.process_request(&mut request).await? {
792        return Ok(String::from_utf8_lossy(&short_circuit_response.body).to_string());
793    }
794
795    // Ask the spec registry for a fixture-driven reply. When no fixture
796    // matches, fall back to the standard 250 OK so clients accept the
797    // message (the message has already been captured above).
798    let response = match registry.generate_mock_response(&request) {
799        Ok(mut resp) => {
800            middleware.process_response(&request, &mut resp).await?;
801            String::from_utf8_lossy(&resp.body).to_string()
802        }
803        Err(_) => "250 OK\r\n".to_string(),
804    };
805
806    Ok(response)
807}
808
809/// Extract email address from SMTP command parameter
810fn extract_email_address(param: &str) -> String {
811    // Handle formats like "FROM:<user@example.com>" or "TO:<user@example.com>"
812    if let Some(start) = param.find('<') {
813        if let Some(end) = param.find('>') {
814            return param[start + 1..end].to_string();
815        }
816    }
817
818    // If no angle brackets, just trim and return
819    param.trim().to_string()
820}
821
822/// Extract subject from email data. Takes bytes so non-UTF-8 bodies
823/// still succeed; the header zone (above the blank line) is ASCII per
824/// RFC 5322, so lossy decoding for the search is safe.
825fn extract_subject(data: &[u8]) -> String {
826    let header_text = String::from_utf8_lossy(data);
827    for line in header_text.lines() {
828        // Headers end at the first blank line; stop searching there so we
829        // don't accidentally match a "Subject:" that appears in the body.
830        if line.is_empty() {
831            break;
832        }
833        if line.to_lowercase().starts_with("subject:") {
834            return line[8..].trim().to_string();
835        }
836    }
837    String::new()
838}
839
840/// AUTH dialog state. SMTP's AUTH LOGIN / AUTH PLAIN both need
841/// multi-round-trip exchanges where the *next* line from the client
842/// is not an SMTP verb — it's base64-encoded credential material.
843/// The main read loop consults `SessionState.pending_auth` before
844/// dispatching to the verb table so that continuation data isn't
845/// misrouted into `502 Command not implemented`.
846#[derive(Debug, Clone, PartialEq, Eq)]
847#[allow(clippy::enum_variant_names)] // all stages share the `Awaiting` prefix by design.
848enum AuthStage {
849    /// Client sent `AUTH LOGIN`. Next line should be the base64
850    /// username; we respond with `334 <base64("Password:")>`.
851    AwaitingLoginUsername,
852    /// Client sent the AUTH LOGIN username. Next line should be the
853    /// base64 password; we accept it and send 235.
854    AwaitingLoginPassword,
855    /// Client sent `AUTH PLAIN` on its own. Next line should be a
856    /// single base64 blob decoding to `\0user\0pass`.
857    AwaitingPlainCredentials,
858}
859
860/// Session state for SMTP connection.
861///
862/// `data` is `Vec<u8>` (not `String`) so the DATA body survives
863/// byte-for-byte even when the sender negotiated 8BITMIME and
864/// included non-ASCII / non-UTF-8 content. The mailbox API still
865/// exposes a `String` body via lossy decoding; `raw` holds the
866/// byte-accurate version for consumers that need it.
867struct SessionState {
868    mail_from: Option<String>,
869    rcpt_to: Vec<String>,
870    data: Vec<u8>,
871    in_data_mode: bool,
872    /// Mid-AUTH dialog state, `None` when not currently negotiating.
873    pending_auth: Option<AuthStage>,
874    /// Best-effort capture of the authenticated username so callers
875    /// inspecting the mailbox can filter by who sent what. Populated
876    /// on successful AUTH PLAIN / AUTH LOGIN; cleared by RSET/reset().
877    authenticated_user: Option<String>,
878    /// Maximum accepted DATA payload size in bytes. Carried on the
879    /// session so both the primary DATA path and the defensive fallback
880    /// can enforce the same cap (#754).
881    max_message_bytes: usize,
882}
883
884impl SessionState {
885    #[cfg(test)]
886    fn new() -> Self {
887        Self::with_max_message_bytes(SmtpConfig::default().max_message_bytes)
888    }
889
890    fn with_max_message_bytes(max_message_bytes: usize) -> Self {
891        Self {
892            mail_from: None,
893            rcpt_to: Vec::new(),
894            data: Vec::new(),
895            in_data_mode: false,
896            pending_auth: None,
897            authenticated_user: None,
898            max_message_bytes,
899        }
900    }
901
902    /// True if appending `additional` bytes to `data` would exceed the
903    /// configured `max_message_bytes` cap.
904    fn data_would_overflow(&self, additional: usize) -> bool {
905        self.data.len().saturating_add(additional) > self.max_message_bytes
906    }
907
908    fn reset(&mut self) {
909        self.mail_from = None;
910        self.rcpt_to.clear();
911        self.data.clear();
912        self.in_data_mode = false;
913        self.pending_auth = None;
914        // `authenticated_user` intentionally survives RSET — RFC 4954:
915        // the authenticated state is tied to the connection, not the
916        // mail transaction.
917    }
918}
919
920#[cfg(test)]
921mod tests {
922    use super::*;
923
924    #[test]
925    fn test_extract_email_address() {
926        assert_eq!(extract_email_address("FROM:<user@example.com>"), "user@example.com");
927        assert_eq!(extract_email_address("TO:<admin@test.com>"), "admin@test.com");
928        assert_eq!(extract_email_address("user@example.com"), "user@example.com");
929    }
930
931    #[test]
932    fn test_extract_email_address_whitespace() {
933        assert_eq!(extract_email_address("  user@example.com  "), "user@example.com");
934    }
935
936    #[test]
937    fn test_extract_email_address_no_brackets() {
938        assert_eq!(extract_email_address("plain@email.com"), "plain@email.com");
939    }
940
941    #[test]
942    fn test_extract_email_address_mail_from_format() {
943        assert_eq!(extract_email_address("FROM:<sender@domain.com>"), "sender@domain.com");
944    }
945
946    #[test]
947    fn test_extract_subject() {
948        let data =
949            "From: sender@example.com\nSubject: Test Email\nTo: recipient@example.com\n\nBody text";
950        assert_eq!(extract_subject(data.as_bytes()), "Test Email");
951    }
952
953    #[test]
954    fn test_extract_subject_not_found() {
955        let data = "From: sender@example.com\nTo: recipient@example.com\n\nBody text";
956        assert_eq!(extract_subject(data.as_bytes()), "");
957    }
958
959    #[test]
960    fn test_extract_subject_lowercase() {
961        let data = "subject: lowercase subject\nFrom: sender@example.com";
962        assert_eq!(extract_subject(data.as_bytes()), "lowercase subject");
963    }
964
965    #[test]
966    fn test_extract_subject_mixed_case() {
967        let data = "SUBJECT: UPPERCASE SUBJECT\nFrom: sender@example.com";
968        assert_eq!(extract_subject(data.as_bytes()), "UPPERCASE SUBJECT");
969    }
970
971    #[test]
972    fn test_session_state() {
973        let mut state = SessionState::new();
974        assert!(state.mail_from.is_none());
975        assert_eq!(state.rcpt_to.len(), 0);
976
977        state.mail_from = Some("sender@example.com".to_string());
978        state.rcpt_to.push("recipient@example.com".to_string());
979
980        state.reset();
981        assert!(state.mail_from.is_none());
982        assert_eq!(state.rcpt_to.len(), 0);
983    }
984
985    #[test]
986    fn test_session_state_new() {
987        let state = SessionState::new();
988        assert!(state.mail_from.is_none());
989        assert!(state.rcpt_to.is_empty());
990        assert!(state.data.is_empty());
991        assert!(!state.in_data_mode);
992    }
993
994    #[test]
995    fn test_session_state_reset() {
996        let mut state = SessionState::new();
997        state.mail_from = Some("test@example.com".to_string());
998        state.rcpt_to.push("recipient1@example.com".to_string());
999        state.rcpt_to.push("recipient2@example.com".to_string());
1000        state.data = b"Email body content".to_vec();
1001        state.in_data_mode = true;
1002
1003        state.reset();
1004
1005        assert!(state.mail_from.is_none());
1006        assert!(state.rcpt_to.is_empty());
1007        assert!(state.data.is_empty());
1008        assert!(!state.in_data_mode);
1009    }
1010
1011    #[test]
1012    fn test_session_state_multiple_recipients() {
1013        let mut state = SessionState::new();
1014        state.rcpt_to.push("a@example.com".to_string());
1015        state.rcpt_to.push("b@example.com".to_string());
1016        state.rcpt_to.push("c@example.com".to_string());
1017        assert_eq!(state.rcpt_to.len(), 3);
1018    }
1019
1020    #[test]
1021    fn test_session_state_data_accumulation() {
1022        let mut state = SessionState::new();
1023        state.data.extend_from_slice(b"Line 1\n");
1024        state.data.extend_from_slice(b"Line 2\n");
1025        state.data.extend_from_slice(b"Line 3\n");
1026        assert_eq!(state.data, b"Line 1\nLine 2\nLine 3\n");
1027    }
1028
1029    #[test]
1030    fn test_strip_line_terminator() {
1031        assert_eq!(strip_line_terminator(b"hello\r\n"), b"hello");
1032        assert_eq!(strip_line_terminator(b"hello\n"), b"hello");
1033        assert_eq!(strip_line_terminator(b"hello"), b"hello");
1034        assert_eq!(strip_line_terminator(b""), b"");
1035        // Non-UTF-8 bytes survive intact through the strip.
1036        assert_eq!(strip_line_terminator(b"\xff\xfe\r\n"), b"\xff\xfe");
1037    }
1038
1039    #[test]
1040    fn test_extract_subject_from_bytes_with_non_utf8_body() {
1041        let mut data = Vec::new();
1042        data.extend_from_slice(b"From: a@example.test\r\n");
1043        data.extend_from_slice(b"Subject: 8BITMIME body below\r\n");
1044        data.extend_from_slice(b"\r\n");
1045        data.extend_from_slice(&[0xff, 0xfe, 0xfd]); // garbage bytes
1046        assert_eq!(extract_subject(&data), "8BITMIME body below");
1047    }
1048
1049    #[tokio::test]
1050    async fn test_smtp_server_new() {
1051        let config = SmtpConfig::default();
1052        let registry = Arc::new(SmtpSpecRegistry::new());
1053        let server = SmtpServer::new(config, registry);
1054        assert!(server.is_ok());
1055    }
1056
1057    #[tokio::test]
1058    async fn test_smtp_server_with_middleware() {
1059        let config = SmtpConfig::default();
1060        let registry = Arc::new(SmtpSpecRegistry::new());
1061        let middleware = Arc::new(MiddlewareChain::new());
1062        let server = SmtpServer::with_middleware(config, registry, middleware);
1063        assert!(server.is_ok());
1064    }
1065}