interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-mail-rs / src / smtp_server.rs

557 lines · 20174 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::cortex_sync::CortexSync;
17use crate::models::EmailMessage;
18use crate::store::MailStore;
19use chrono::Utc;
20use std::collections::HashMap;
21use std::os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, PermissionsExt};
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
25use tokio::net::{TcpListener, UnixListener};
26use uuid::Uuid;
27
28/// Where the SMTP ingest listener accepts mail.
29///
30/// `--smtp-addr` takes one of:
31/// - `off`: no SMTP listener at all (the API keeps running);
32/// - `unix:<path>`: a Unix socket, mode 0600, that only accepts a peer
33/// whose uid is the uid that owns the socket (checked with SO_PEERCRED);
34/// - `<host>:<port>`: plain TCP with no authentication. Any local process,
35/// and any page a local browser loads, can then write mail into the inbox
36/// and Cortex. Use it only on a host with no other users or sandboxes.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum SmtpBind {
39 Off,
40 Unix(PathBuf),
41 Tcp(String),
42}
43
44impl SmtpBind {
45 pub fn parse(spec: &str) -> Result<Self, String> {
46 let spec = spec.trim();
47 if spec.eq_ignore_ascii_case("off") {
48 return Ok(Self::Off);
49 }
50 if let Some(path) = spec.strip_prefix("unix:") {
51 let path = PathBuf::from(path);
52 if !path.is_absolute() {
53 return Err(format!(
54 "smtp unix socket path must be absolute: {:?}",
55 path.display().to_string()
56 ));
57 }
58 return Ok(Self::Unix(path));
59 }
60 match spec.rsplit_once(':') {
61 Some((host, port)) if !host.is_empty() && port.parse::<u16>().is_ok() => {
62 Ok(Self::Tcp(spec.to_string()))
63 }
64 _ => Err(format!(
65 "smtp address must be off, unix:<absolute path> or host:port, got {spec:?}"
66 )),
67 }
68 }
69
70 /// TCP port for status reports; 0 when there is no TCP listener.
71 pub fn port(&self) -> u16 {
72 match self {
73 Self::Tcp(addr) => addr
74 .rsplit_once(':')
75 .and_then(|(_, p)| p.parse().ok())
76 .unwrap_or(0),
77 _ => 0,
78 }
79 }
80}
81
82/// A Unix-socket peer may submit only when it runs as the socket owner.
83pub fn unix_peer_allowed(peer_uid: u32, owner_uid: u32) -> bool {
84 peer_uid == owner_uid
85}
86
87pub async fn run_smtp_server(
88 bind_addr: &str,
89 store: Arc<MailStore>,
90 cortex: Arc<CortexSync>,
91) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
92 match SmtpBind::parse(bind_addr)? {
93 SmtpBind::Off => {
94 tracing::info!("SMTP ingest listener is off");
95 std::future::pending::<()>().await;
96 Ok(())
97 }
98 SmtpBind::Unix(path) => run_unix_smtp_server(&path, store, cortex).await,
99 SmtpBind::Tcp(addr) => run_tcp_smtp_server(&addr, store, cortex).await,
100 }
101}
102
103async fn run_tcp_smtp_server(
104 bind_addr: &str,
105 store: Arc<MailStore>,
106 cortex: Arc<CortexSync>,
107) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
108 let listener = TcpListener::bind(bind_addr).await?;
109 tracing::warn!(
110 "SMTP ingest listener on TCP {} has no authentication; prefer unix:<path>",
111 bind_addr
112 );
113
114 loop {
115 let (socket, peer_addr) = match listener.accept().await {
116 Ok(res) => res,
117 Err(e) => {
118 tracing::warn!("Failed to accept SMTP connection: {}", e);
119 continue;
120 }
121 };
122
123 let store_clone = Arc::clone(&store);
124 let cortex_clone = Arc::clone(&cortex);
125
126 tokio::spawn(async move {
127 if let Err(e) = handle_smtp_session(socket, store_clone, cortex_clone).await {
128 tracing::debug!("SMTP session with {} closed with: {}", peer_addr, e);
129 }
130 });
131 }
132}
133
134/// Binds the Unix socket. Parent directories it creates are 0700, a stale
135/// socket is replaced, a socket another listener still serves is refused,
136/// any other existing file is refused, and the socket itself is set to 0600.
137/// Returns the listener and the owner uid.
138pub fn bind_unix_socket(path: &Path) -> std::io::Result<(UnixListener, u32)> {
139 if let Some(parent) = path.parent() {
140 std::fs::DirBuilder::new()
141 .recursive(true)
142 .mode(0o700)
143 .create(parent)?;
144 }
145 match std::fs::symlink_metadata(path) {
146 Ok(meta) if meta.file_type().is_socket() => {
147 if std::os::unix::net::UnixStream::connect(path).is_ok() {
148 return Err(std::io::Error::new(
149 std::io::ErrorKind::AddrInUse,
150 format!("{} is served by another listener", path.display()),
151 ));
152 }
153 std::fs::remove_file(path)?;
154 }
155 Ok(_) => {
156 return Err(std::io::Error::new(
157 std::io::ErrorKind::AlreadyExists,
158 format!("{} exists and is not a socket", path.display()),
159 ));
160 }
161 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
162 Err(e) => return Err(e),
163 }
164 let listener = UnixListener::bind(path)?;
165 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
166 let owner_uid = std::fs::metadata(path)?.uid();
167 Ok((listener, owner_uid))
168}
169
170async fn run_unix_smtp_server(
171 path: &Path,
172 store: Arc<MailStore>,
173 cortex: Arc<CortexSync>,
174) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
175 let (listener, owner_uid) = bind_unix_socket(path)?;
176 tracing::info!(
177 "SMTP ingest listener on unix socket {} (owner uid {} only)",
178 path.display(),
179 owner_uid
180 );
181 serve_unix(listener, owner_uid, store, cortex).await
182}
183
184/// Accepts on a bound Unix socket and serves only peers whose SO_PEERCRED uid
185/// is `owner_uid`; any other peer gets 554 5.7.1 and is disconnected.
186async fn serve_unix(
187 listener: UnixListener,
188 owner_uid: u32,
189 store: Arc<MailStore>,
190 cortex: Arc<CortexSync>,
191) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
192 loop {
193 let (mut socket, _) = match listener.accept().await {
194 Ok(res) => res,
195 Err(e) => {
196 tracing::warn!("Failed to accept SMTP connection: {}", e);
197 continue;
198 }
199 };
200 let peer_uid = match socket.peer_cred() {
201 Ok(cred) => cred.uid(),
202 Err(e) => {
203 tracing::warn!("SMTP peer credentials unavailable, refusing: {}", e);
204 continue;
205 }
206 };
207 if !unix_peer_allowed(peer_uid, owner_uid) {
208 tracing::warn!(
209 "SMTP refused peer uid {} (owner uid {})",
210 peer_uid,
211 owner_uid
212 );
213 let _ = socket.write_all(b"554 5.7.1 Access denied\r\n").await;
214 continue;
215 }
216
217 let store_clone = Arc::clone(&store);
218 let cortex_clone = Arc::clone(&cortex);
219
220 tokio::spawn(async move {
221 if let Err(e) = handle_smtp_session(socket, store_clone, cortex_clone).await {
222 tracing::debug!("SMTP session on unix socket closed with: {}", e);
223 }
224 });
225 }
226}
227
228async fn handle_smtp_session<S>(
229 stream: S,
230 store: Arc<MailStore>,
231 cortex: Arc<CortexSync>,
232) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
233where
234 S: AsyncRead + AsyncWrite + Unpin,
235{
236 let (reader, mut writer) = tokio::io::split(stream);
237 let mut buf_reader = BufReader::new(reader);
238
239 // Initial 220 banner
240 writer
241 .write_all(b"220 sovereign.spark ESMTP Spark-Mail 1.0 Ready\r\n")
242 .await?;
243
244 let mut sender = String::new();
245 let mut recipients: Vec<String> = Vec::new();
246 let mut line = String::new();
247
248 loop {
249 line.clear();
250 let bytes_read = buf_reader.read_line(&mut line).await?;
251 if bytes_read == 0 {
252 break;
253 }
254
255 let trimmed = line.trim();
256 let upper = trimmed.to_uppercase();
257
258 if upper.starts_with("HELO") || upper.starts_with("EHLO") {
259 writer
260 .write_all(b"250-sovereign.spark ESMTP\r\n250 8BITMIME\r\n")
261 .await?;
262 } else if upper.starts_with("MAIL FROM:") {
263 let s = trimmed["MAIL FROM:".len()..].trim();
264 sender = s.trim_matches(|c| c == '<' || c == '>').to_string();
265 writer.write_all(b"250 2.1.0 Ok\r\n").await?;
266 } else if upper.starts_with("RCPT TO:") {
267 let r = trimmed["RCPT TO:".len()..].trim();
268 let cleaned = r.trim_matches(|c| c == '<' || c == '>').to_string();
269 recipients.push(cleaned);
270 writer.write_all(b"250 2.1.5 Ok\r\n").await?;
271 } else if upper == "DATA" {
272 writer
273 .write_all(b"354 End data with <CR><LF>.<CR><LF>\r\n")
274 .await?;
275 let mut raw_data = String::new();
276
277 loop {
278 let mut data_line = String::new();
279 let n = buf_reader.read_line(&mut data_line).await?;
280 if n == 0 {
281 break;
282 }
283 if data_line.trim() == "." {
284 break;
285 }
286 raw_data.push_str(&data_line);
287 }
288
289 // Parse simple email
290 let id = Uuid::new_v4().to_string();
291 let now = Utc::now().to_rfc3339();
292 let (subject, body, mut headers) = parse_raw_email(&raw_data);
293 let inbound = crate::effect::InboundBody::from_raw(body);
294 headers.insert("x-aien-trust".to_string(), "untrusted-data".to_string());
295
296 let from_addr = if sender.is_empty() {
297 headers
298 .get("from")
299 .cloned()
300 .unwrap_or_else(|| "unknown@spark".to_string())
301 } else {
302 sender.clone()
303 };
304
305 let to_addrs = if recipients.is_empty() {
306 headers
307 .get("to")
308 .map(|t| vec![t.clone()])
309 .unwrap_or_default()
310 } else {
311 recipients.clone()
312 };
313
314 let mut msg = EmailMessage {
315 id: id.clone(),
316 from: from_addr,
317 to: to_addrs,
318 subject: if subject.is_empty() {
319 "(No Subject)".to_string()
320 } else {
321 subject
322 },
323 body: inbound.text().to_string(),
324 headers,
325 received_at: now,
326 folder: "inbox".to_string(),
327 cortex_indexed: false,
328 untrusted: inbound.is_untrusted(),
329 };
330
331 // Save to disk
332 let _ = store.save_message(&msg);
333
334 // Async commit to Cortex memory
335 if cortex.commit_mail(&msg).await.is_ok() {
336 msg.cortex_indexed = true;
337 let _ = store.save_message(&msg);
338 }
339
340 let resp = format!("250 2.0.0 Ok: queued as {}\r\n", id);
341 writer.write_all(resp.as_bytes()).await?;
342
343 // Reset state
344 sender.clear();
345 recipients.clear();
346 } else if upper == "RSET" {
347 sender.clear();
348 recipients.clear();
349 writer.write_all(b"250 2.0.0 Ok\r\n").await?;
350 } else if upper == "NOOP" {
351 writer.write_all(b"250 2.0.0 Ok\r\n").await?;
352 } else if upper == "QUIT" {
353 writer.write_all(b"221 2.0.0 Bye\r\n").await?;
354 break;
355 } else {
356 writer
357 .write_all(b"500 5.5.1 Command unrecognized\r\n")
358 .await?;
359 }
360 }
361
362 Ok(())
363}
364
365fn parse_raw_email(raw: &str) -> (String, String, HashMap<String, String>) {
366 let mut headers = HashMap::new();
367 let mut subject = String::new();
368 let mut in_headers = true;
369 let mut body = String::new();
370
371 for line in raw.lines() {
372 if in_headers {
373 if line.is_empty() {
374 in_headers = false;
375 continue;
376 }
377 if let Some((k, v)) = line.split_once(':') {
378 let key = k.trim().to_lowercase();
379 let val = v.trim().to_string();
380 if key == "subject" {
381 subject = val.clone();
382 }
383 headers.insert(key, val);
384 }
385 } else {
386 body.push_str(line);
387 body.push('\n');
388 }
389 }
390
391 (subject, body.trim().to_string(), headers)
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397 use tokio::net::UnixStream;
398
399 #[test]
400 fn parse_accepts_off_unix_and_tcp() {
401 assert_eq!(SmtpBind::parse("off").unwrap(), SmtpBind::Off);
402 assert_eq!(SmtpBind::parse("OFF").unwrap(), SmtpBind::Off);
403 assert_eq!(
404 SmtpBind::parse("unix:/run/user/1000/spark-mail/smtp.sock").unwrap(),
405 SmtpBind::Unix(PathBuf::from("/run/user/1000/spark-mail/smtp.sock"))
406 );
407 assert_eq!(
408 SmtpBind::parse("127.0.0.1:2525").unwrap(),
409 SmtpBind::Tcp("127.0.0.1:2525".to_string())
410 );
411 assert_eq!(SmtpBind::parse("127.0.0.1:2525").unwrap().port(), 2525);
412 assert_eq!(SmtpBind::parse("off").unwrap().port(), 0);
413 assert_eq!(SmtpBind::parse("unix:/tmp/x.sock").unwrap().port(), 0);
414 }
415
416 #[test]
417 fn parse_refuses_relative_unix_and_bad_tcp() {
418 assert!(SmtpBind::parse("unix:relative.sock").is_err());
419 assert!(SmtpBind::parse("unix:").is_err());
420 assert!(SmtpBind::parse("2525").is_err());
421 assert!(SmtpBind::parse("127.0.0.1:notaport").is_err());
422 assert!(SmtpBind::parse(":2525").is_err());
423 assert!(SmtpBind::parse("").is_err());
424 }
425
426 #[test]
427 fn peer_check_is_owner_only() {
428 assert!(unix_peer_allowed(1000, 1000));
429 assert!(!unix_peer_allowed(1001, 1000));
430 assert!(!unix_peer_allowed(0, 1000));
431 }
432
433 fn scratch_dir(tag: &str) -> PathBuf {
434 let dir = std::env::temp_dir().join(format!("spark-mail-{tag}-{}", Uuid::new_v4()));
435 std::fs::DirBuilder::new().mode(0o700).create(&dir).unwrap();
436 dir
437 }
438
439 #[tokio::test]
440 async fn bind_refuses_a_regular_file_and_sets_modes() {
441 let dir = scratch_dir("bind");
442 let file = dir.join("not-a-socket");
443 std::fs::write(&file, b"keep").unwrap();
444 assert!(bind_unix_socket(&file).is_err());
445 assert_eq!(std::fs::read(&file).unwrap(), b"keep");
446
447 let sock = dir.join("new/sub/smtp.sock");
448 let (listener, owner) = bind_unix_socket(&sock).unwrap();
449 let meta = std::fs::metadata(&sock).unwrap();
450 assert!(meta.file_type().is_socket());
451 assert_eq!(meta.permissions().mode() & 0o777, 0o600);
452 assert_eq!(owner, meta.uid());
453 let parent = std::fs::metadata(dir.join("new/sub")).unwrap();
454 assert_eq!(parent.permissions().mode() & 0o777, 0o700);
455 drop(listener);
456 // A stale socket left by an earlier run is replaced.
457 let (_again, _) = bind_unix_socket(&sock).unwrap();
458 std::fs::remove_dir_all(&dir).unwrap();
459 }
460
461 #[tokio::test]
462 async fn unix_socket_serves_the_owner() {
463 let dir = scratch_dir("serve");
464 let sock = dir.join("smtp.sock");
465 let store = Arc::new(MailStore::new(Some(dir.join("mail"))));
466 let cortex = Arc::new(CortexSync::new(None));
467 let spec = format!("unix:{}", sock.display());
468 let server = tokio::spawn(async move { run_smtp_server(&spec, store, cortex).await });
469 for _ in 0..200 {
470 if sock.exists() {
471 break;
472 }
473 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
474 }
475 let stream = UnixStream::connect(&sock).await.unwrap();
476 let (r, mut w) = stream.into_split();
477 let mut r = BufReader::new(r);
478 let mut line = String::new();
479 r.read_line(&mut line).await.unwrap();
480 assert!(line.starts_with("220 "), "banner {line:?}");
481 w.write_all(b"EHLO probe\r\n").await.unwrap();
482 line.clear();
483 r.read_line(&mut line).await.unwrap();
484 assert!(line.starts_with("250-"), "ehlo {line:?}");
485 line.clear();
486 r.read_line(&mut line).await.unwrap();
487 w.write_all(b"MAIL FROM:<owner@spark.invalid>\r\n")
488 .await
489 .unwrap();
490 line.clear();
491 r.read_line(&mut line).await.unwrap();
492 assert!(line.starts_with("250 "), "mail from {line:?}");
493 w.write_all(b"QUIT\r\n").await.unwrap();
494 line.clear();
495 r.read_line(&mut line).await.unwrap();
496 assert!(line.starts_with("221 "), "quit {line:?}");
497 server.abort();
498 std::fs::remove_dir_all(&dir).unwrap();
499 }
500
501 #[tokio::test]
502 async fn unix_socket_refuses_a_peer_that_is_not_the_owner() {
503 let dir = scratch_dir("refuse");
504 let sock = dir.join("smtp.sock");
505 let store = Arc::new(MailStore::new(Some(dir.join("mail"))));
506 let cortex = Arc::new(CortexSync::new(None));
507 let (listener, owner) = bind_unix_socket(&sock).unwrap();
508 // This test process is the peer; name another uid as the owner.
509 let other = owner.wrapping_add(1);
510 let server_store = Arc::clone(&store);
511 let server =
512 tokio::spawn(async move { serve_unix(listener, other, server_store, cortex).await });
513 let stream = UnixStream::connect(&sock).await.unwrap();
514 let (r, mut w) = stream.into_split();
515 let mut r = BufReader::new(r);
516 let mut line = String::new();
517 r.read_line(&mut line).await.unwrap();
518 assert_eq!(line, "554 5.7.1 Access denied\r\n");
519 // No session follows: the server has closed the connection.
520 let _ = w
521 .write_all(b"MAIL FROM:<x@spark.invalid>\r\nRCPT TO:<y@spark.invalid>\r\nDATA\r\n\r\nhi\r\n.\r\n")
522 .await;
523 line.clear();
524 assert_eq!(r.read_line(&mut line).await.unwrap_or(0), 0, "{line:?}");
525 assert!(store.list_folder("inbox").is_empty());
526 server.abort();
527 std::fs::remove_dir_all(&dir).unwrap();
528 }
529
530 #[tokio::test]
531 async fn bind_refuses_a_socket_another_listener_serves() {
532 let dir = scratch_dir("live");
533 let sock = dir.join("smtp.sock");
534 let (_live, _) = bind_unix_socket(&sock).unwrap();
535 let err = bind_unix_socket(&sock).unwrap_err();
536 assert_eq!(err.kind(), std::io::ErrorKind::AddrInUse);
537 assert!(
538 std::fs::symlink_metadata(&sock)
539 .unwrap()
540 .file_type()
541 .is_socket()
542 );
543 assert!(std::os::unix::net::UnixStream::connect(&sock).is_ok());
544 std::fs::remove_dir_all(&dir).unwrap();
545 }
546
547 #[tokio::test]
548 async fn off_never_listens_and_never_returns() {
549 let dir = scratch_dir("off");
550 let store = Arc::new(MailStore::new(Some(dir.join("mail"))));
551 let cortex = Arc::new(CortexSync::new(None));
552 let run = run_smtp_server("off", store, cortex);
553 let waited = tokio::time::timeout(std::time::Duration::from_millis(200), run).await;
554 assert!(waited.is_err(), "off must keep running so the API stays up");
555 std::fs::remove_dir_all(&dir).unwrap();
556 }
557}