Skip to main content

capy_mail/
capture.rs

1use crate::{DeliveryReceipt, Mail, MailError, MailResult, MailTransport, Mailbox, PreparedMail};
2use fs2::FileExt;
3use serde::{Deserialize, Serialize};
4use std::{
5    fs::{self, File, OpenOptions},
6    future::Future,
7    io::{Read, Write},
8    path::{Path, PathBuf},
9    pin::Pin,
10    time::{SystemTime, UNIX_EPOCH},
11};
12const MAX_BYTES: u64 = 64 * 1024 * 1024;
13const MAX_MESSAGES: usize = 100;
14
15#[derive(Clone, Serialize, Deserialize)]
16pub(crate) struct CaptureContent {
17    from: Mailbox,
18    text: Option<String>,
19    html: Option<String>,
20    headers: Vec<(String, String)>,
21}
22impl CaptureContent {
23    pub(crate) fn new(mail: &Mail, default_from: &Mailbox) -> Self {
24        Self {
25            from: mail.from.clone().unwrap_or_else(|| default_from.clone()),
26            text: mail.text.clone(),
27            html: mail.html.clone(),
28            headers: mail.headers.clone(),
29        }
30    }
31}
32/// Explicitly inspectable message, redacted in Debug. Never include contents in logs.
33#[derive(Clone, Serialize, Deserialize)]
34pub struct CapturedMail {
35    id: String,
36    message_id: String,
37    message_type: String,
38    subject: String,
39    recipients: Vec<Mailbox>,
40    content: CaptureContent,
41    mime: String,
42    timestamp_ms: u64,
43}
44impl CapturedMail {
45    pub(crate) fn from_prepared(mail: PreparedMail) -> Self {
46        Self {
47            id: uuid::Uuid::new_v4().to_string(),
48            mime: String::from_utf8_lossy(&mail.message.formatted()).into_owned(),
49            message_id: mail.message_id,
50            message_type: mail.message_type,
51            subject: mail.subject,
52            recipients: mail.recipients,
53            content: mail.content,
54            timestamp_ms: SystemTime::now()
55                .duration_since(UNIX_EPOCH)
56                .unwrap_or_default()
57                .as_millis() as u64,
58        }
59    }
60    pub(crate) fn bytes(&self) -> usize {
61        self.mime.len()
62            + self.content.text.as_ref().map_or(0, String::len)
63            + self.content.html.as_ref().map_or(0, String::len)
64            + self.subject.len()
65            + self.recipients.len() * 512
66            + 8192
67    }
68    /// Local inbox UUID, distinct from the possibly replayed MIME Message-ID.
69    pub fn id(&self) -> &str {
70        &self.id
71    }
72    /// MIME Message-ID (stable for queued retries).
73    pub fn message_id(&self) -> &str {
74        &self.message_id
75    }
76    /// Capture time in Unix milliseconds.
77    pub fn timestamp_ms(&self) -> u64 {
78        self.timestamp_ms
79    }
80    /// Sender, explicitly accessible for private assertions/development inspection.
81    pub fn sender(&self) -> &Mailbox {
82        &self.content.from
83    }
84    /// All envelope recipients, including Bcc; treat this as private data.
85    pub fn recipients(&self) -> &[Mailbox] {
86        &self.recipients
87    }
88    /// Original subject.
89    pub fn subject(&self) -> &str {
90        &self.subject
91    }
92    /// Unencoded text alternative.
93    pub fn text(&self) -> Option<&str> {
94        self.content.text.as_deref()
95    }
96    /// Unencoded HTML alternative. The CLI displays source and never executes it.
97    pub fn html(&self) -> Option<&str> {
98        self.content.html.as_deref()
99    }
100    /// Application custom headers; standard headers are available in `raw_message`.
101    pub fn headers(&self) -> &[(String, String)] {
102        &self.content.headers
103    }
104    /// Full rendered MIME bytes for parser-based assertions.
105    pub fn raw_message(&self) -> Vec<u8> {
106        self.mime.as_bytes().to_vec()
107    }
108    /// Compare a recipient without printing PII on assertion failure.
109    pub fn was_sent_to(&self, address: &str) -> bool {
110        self.recipients.iter().any(|r| r.address() == address)
111    }
112    /// Compare a subject without printing it.
113    pub fn has_subject(&self, subject: &str) -> bool {
114        self.subject == subject
115    }
116    /// Compare a typed mailable name.
117    pub fn is_type<M: crate::Mailable>(&self) -> bool {
118        self.message_type == M::NAME
119    }
120}
121impl std::fmt::Debug for CapturedMail {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        f.write_str("CapturedMail([REDACTED])")
124    }
125}
126/// Private disk-backed development inbox shared by HTTP, workers and `capy mail`.
127/// Retains at most 100 messages/64 MiB until explicitly cleared; a full inbox fails
128/// delivery instead of silently evicting. No network listener or HTML renderer exists.
129/// Files contain plaintext development secrets: never use production recipient data.
130#[derive(Clone)]
131pub struct DevelopmentInbox {
132    directory: PathBuf,
133}
134impl DevelopmentInbox {
135    /// Choose a local directory (normally config.mail.capture_directory).
136    /// No filesystem access until a command/send; production Mailer rejects this transport.
137    pub fn new(path: impl Into<PathBuf>) -> Self {
138        Self {
139            directory: path.into(),
140        }
141    }
142    fn lock(&self) -> MailResult<File> {
143        let mut builder = fs::DirBuilder::new();
144        builder.recursive(true);
145        #[cfg(unix)]
146        {
147            use std::os::unix::fs::DirBuilderExt;
148            builder.mode(0o700);
149        }
150        builder
151            .create(&self.directory)
152            .map_err(|_| MailError::CaptureStorage)?;
153        let metadata =
154            fs::symlink_metadata(&self.directory).map_err(|_| MailError::CaptureStorage)?;
155        if !metadata.is_dir() || metadata.file_type().is_symlink() {
156            return Err(MailError::CaptureStorage);
157        }
158        #[cfg(unix)]
159        {
160            use std::os::unix::fs::PermissionsExt;
161            if metadata.permissions().mode() & 0o077 != 0 {
162                return Err(MailError::CaptureStorage);
163            }
164        }
165        let path = self.directory.join(".lock");
166        reject_symlink(&path)?;
167        let mut options = OpenOptions::new();
168        options.read(true).write(true).create(true).truncate(false);
169        #[cfg(unix)]
170        {
171            use std::os::unix::fs::OpenOptionsExt;
172            options.mode(0o600);
173        }
174        let lock = options.open(path).map_err(|_| MailError::CaptureStorage)?;
175        lock.lock_exclusive()
176            .map_err(|_| MailError::CaptureStorage)?;
177        Ok(lock)
178    }
179    fn files(&self) -> MailResult<Vec<PathBuf>> {
180        let mut files = Vec::new();
181        for entry in fs::read_dir(&self.directory).map_err(|_| MailError::CaptureStorage)? {
182            let entry = entry.map_err(|_| MailError::CaptureStorage)?;
183            let path = entry.path();
184            if path.extension().is_some_and(|v| v == "json") {
185                reject_symlink(&path)?;
186                files.push(path);
187            }
188        }
189        if files.len() > MAX_MESSAGES {
190            return Err(MailError::CaptureFull);
191        }
192        Ok(files)
193    }
194    fn read(path: &Path) -> MailResult<CapturedMail> {
195        reject_symlink(path)?;
196        let file = File::open(path).map_err(|_| MailError::CaptureStorage)?;
197        if file
198            .metadata()
199            .map_err(|_| MailError::CaptureStorage)?
200            .len()
201            > MAX_BYTES
202        {
203            return Err(MailError::CaptureFull);
204        }
205        let mut bytes = Vec::new();
206        file.take(MAX_BYTES + 1)
207            .read_to_end(&mut bytes)
208            .map_err(|_| MailError::CaptureStorage)?;
209        if bytes.len() as u64 > MAX_BYTES {
210            return Err(MailError::CaptureFull);
211        }
212        serde_json::from_slice(&bytes).map_err(|_| MailError::CaptureStorage)
213    }
214    /// Inspect messages in timestamp/UUID order. Blocking local I/O; use outside HTTP
215    /// handlers or in spawn_blocking. CLI contents are deliberately private output.
216    pub fn list(&self) -> MailResult<Vec<CapturedMail>> {
217        let _lock = self.lock()?;
218        let files = self.files()?;
219        let total = files
220            .iter()
221            .try_fold(0u64, |total, p| {
222                fs::metadata(p).map(|m| total.saturating_add(m.len()))
223            })
224            .map_err(|_| MailError::CaptureStorage)?;
225        if total > MAX_BYTES {
226            return Err(MailError::CaptureFull);
227        }
228        let mut messages = files
229            .iter()
230            .map(|p| Self::read(p))
231            .collect::<MailResult<Vec<_>>>()?;
232        messages.sort_by(|a, b| (a.timestamp_ms, &a.id).cmp(&(b.timestamp_ms, &b.id)));
233        Ok(messages)
234    }
235    /// Read one UUID; arbitrary paths and symlinks are rejected.
236    pub fn show(&self, id: &str) -> MailResult<CapturedMail> {
237        let id = uuid::Uuid::parse_str(id).map_err(|_| MailError::CaptureStorage)?;
238        let _lock = self.lock()?;
239        Self::read(&self.directory.join(format!("{id}.json")))
240    }
241    /// Delete captured JSON messages under the inbox lock, preserving unrelated files.
242    pub fn clear(&self) -> MailResult<usize> {
243        let _lock = self.lock()?;
244        let files = self.files()?;
245        for file in &files {
246            fs::remove_file(file).map_err(|_| MailError::CaptureStorage)?;
247        }
248        Ok(files.len())
249    }
250    fn store(&self, mail: CapturedMail) -> MailResult<()> {
251        let _lock = self.lock()?;
252        let bytes = serde_json::to_vec(&mail).map_err(|_| MailError::CaptureStorage)?;
253        let files = self.files()?;
254        let retained = files
255            .iter()
256            .try_fold(0u64, |total, p| {
257                fs::metadata(p).map(|m| total.saturating_add(m.len()))
258            })
259            .map_err(|_| MailError::CaptureStorage)?;
260        if files.len() >= MAX_MESSAGES || retained.saturating_add(bytes.len() as u64) > MAX_BYTES {
261            return Err(MailError::CaptureFull);
262        }
263        let mut file = tempfile::NamedTempFile::new_in(&self.directory)
264            .map_err(|_| MailError::CaptureStorage)?;
265        file.write_all(&bytes)
266            .map_err(|_| MailError::CaptureStorage)?;
267        file.as_file()
268            .sync_all()
269            .map_err(|_| MailError::CaptureStorage)?;
270        file.persist_noclobber(self.directory.join(format!("{}.json", mail.id)))
271            .map_err(|_| MailError::CaptureStorage)?;
272        tracing::debug!(event = "mail.capture.stored");
273        Ok(())
274    }
275}
276fn reject_symlink(path: &Path) -> MailResult<()> {
277    match fs::symlink_metadata(path) {
278        Ok(m) if m.file_type().is_symlink() || !m.is_file() => Err(MailError::CaptureStorage),
279        Ok(_) => Ok(()),
280        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
281        Err(_) => Err(MailError::CaptureStorage),
282    }
283}
284impl MailTransport for DevelopmentInbox {
285    fn name(&self) -> &'static str {
286        "capture"
287    }
288    fn development_only(&self) -> bool {
289        true
290    }
291    fn send(
292        &self,
293        mail: PreparedMail,
294    ) -> Pin<Box<dyn Future<Output = MailResult<DeliveryReceipt>> + Send + '_>> {
295        Box::pin(async move {
296            let inbox = self.clone();
297            let receipt = DeliveryReceipt {
298                message_id: mail.message_id.clone(),
299                provider_id: None,
300            };
301            tokio::task::spawn_blocking(move || inbox.store(CapturedMail::from_prepared(mail)))
302                .await
303                .map_err(|_| MailError::CaptureStorage)??;
304            Ok(receipt)
305        })
306    }
307}