Skip to main content

tea_cli/tui/
attachment.rs

1use std::fmt;
2use std::fs::File;
3use std::io::Read as _;
4use std::path::Path;
5
6use base64::Engine as _;
7use base64::engine::general_purpose::STANDARD;
8use tea_protocol::{ContentBlock, MAX_INLINE_IMAGE_BASE64_BYTES};
9use thiserror::Error;
10
11/// Maximum image attachments retained in one session composer.
12pub const MAX_COMPOSER_ATTACHMENTS: usize = 4;
13/// Maximum aggregate encoded image bytes retained in one session composer.
14pub const MAX_COMPOSER_IMAGE_BASE64_BYTES: usize = MAX_INLINE_IMAGE_BASE64_BYTES;
15pub(crate) const MAX_INLINE_IMAGE_RAW_BYTES: usize = MAX_INLINE_IMAGE_BASE64_BYTES / 4 * 3;
16pub(crate) const MAX_ATTACHMENT_DISPLAY_NAME_BYTES: usize = 96;
17
18/// Safe failure returned while validating a local composer attachment.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
20pub enum AttachmentError {
21    /// The local file could not be opened or read.
22    #[error("image could not be read")]
23    Read,
24    /// One image exceeds the per-block protocol limit.
25    #[error("image exceeds the attachment size limit")]
26    TooLarge,
27    /// The detected or declared MIME type is not supported by the TUI.
28    #[error("image format is unsupported")]
29    UnsupportedFormat,
30    /// The composer already contains the maximum number of attachments.
31    #[error("composer attachment limit reached")]
32    TooMany,
33    /// Adding the image would exceed the aggregate composer byte limit.
34    #[error("composer attachment bytes exceed the limit")]
35    TotalTooLarge,
36    /// The encoded payload is empty, malformed, or rejected by the protocol.
37    #[error("image content is invalid")]
38    InvalidContent,
39}
40
41/// One validated, path-free image retained in local composer state.
42#[derive(Clone, PartialEq)]
43pub struct ComposerAttachment {
44    content: ContentBlock,
45    mime_type: &'static str,
46    display_name: String,
47    decoded_bytes: usize,
48    encoded_bytes: usize,
49}
50
51impl ComposerAttachment {
52    /// Builds an attachment from a standard padded Base64 image payload.
53    ///
54    /// # Errors
55    ///
56    /// Returns [`AttachmentError`] when the MIME type is unsupported or the
57    /// payload violates the protocol image contract.
58    pub fn inline(
59        mime_type: &str,
60        data: impl Into<String>,
61        display_name: impl AsRef<Path>,
62    ) -> Result<Self, AttachmentError> {
63        let mime_type = supported_mime(mime_type).ok_or(AttachmentError::UnsupportedFormat)?;
64        let data = data.into();
65        if data.is_empty() {
66            return Err(AttachmentError::InvalidContent);
67        }
68        if data.len() > MAX_INLINE_IMAGE_BASE64_BYTES {
69            return Err(AttachmentError::TooLarge);
70        }
71        let decoded_bytes = STANDARD
72            .decode(data.as_bytes())
73            .map_err(|_| AttachmentError::InvalidContent)?
74            .len();
75        let encoded_bytes = data.len();
76        let content = ContentBlock::inline_image(mime_type, data)
77            .map_err(|_| AttachmentError::InvalidContent)?;
78
79        Ok(Self {
80            content,
81            mime_type,
82            display_name: safe_display_name(display_name.as_ref()),
83            decoded_bytes,
84            encoded_bytes,
85        })
86    }
87
88    /// Returns the canonical protocol content block.
89    #[must_use]
90    pub const fn content(&self) -> &ContentBlock {
91        &self.content
92    }
93
94    /// Returns the signature-derived MIME type.
95    #[must_use]
96    pub const fn mime_type(&self) -> &'static str {
97        self.mime_type
98    }
99
100    /// Returns the bounded path-free display name.
101    #[must_use]
102    pub fn display_name(&self) -> &str {
103        &self.display_name
104    }
105
106    /// Returns the decoded payload size in bytes.
107    #[must_use]
108    pub const fn decoded_bytes(&self) -> usize {
109        self.decoded_bytes
110    }
111
112    /// Returns the encoded payload size in bytes.
113    #[must_use]
114    pub const fn encoded_bytes(&self) -> usize {
115        self.encoded_bytes
116    }
117}
118
119impl fmt::Debug for ComposerAttachment {
120    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
121        formatter
122            .debug_struct("ComposerAttachment")
123            .field("mime_type", &self.mime_type)
124            .field("display_name", &self.display_name)
125            .field("decoded_bytes", &self.decoded_bytes)
126            .field("encoded_bytes", &self.encoded_bytes)
127            .finish_non_exhaustive()
128    }
129}
130
131pub(crate) fn load_local_image(path: &Path) -> Result<ComposerAttachment, AttachmentError> {
132    let file = File::open(path).map_err(|_| AttachmentError::Read)?;
133    let mut bytes = Vec::new();
134    file.take((MAX_INLINE_IMAGE_RAW_BYTES + 1) as u64)
135        .read_to_end(&mut bytes)
136        .map_err(|_| AttachmentError::Read)?;
137    let decoded_bytes = bytes.len();
138    let encoded_bytes = encoded_len(bytes.len())?;
139    let mime_type = detect_mime(&bytes).ok_or(AttachmentError::UnsupportedFormat)?;
140    let encoded = STANDARD.encode(bytes);
141    debug_assert_eq!(encoded.len(), encoded_bytes);
142    let attachment = ComposerAttachment::inline(mime_type, encoded, path)?;
143    debug_assert_eq!(attachment.decoded_bytes(), decoded_bytes);
144    debug_assert_eq!(attachment.encoded_bytes(), encoded_bytes);
145    Ok(attachment)
146}
147
148pub(crate) fn validate_addition(
149    current_count: usize,
150    current_encoded_bytes: usize,
151    added_encoded_bytes: usize,
152) -> Result<(), AttachmentError> {
153    if current_count >= MAX_COMPOSER_ATTACHMENTS {
154        return Err(AttachmentError::TooMany);
155    }
156    if current_encoded_bytes
157        .checked_add(added_encoded_bytes)
158        .is_none_or(|total| total > MAX_COMPOSER_IMAGE_BASE64_BYTES)
159    {
160        return Err(AttachmentError::TotalTooLarge);
161    }
162    Ok(())
163}
164
165pub(crate) fn decoded_inline_image_bytes(data: &str) -> Option<usize> {
166    if data.is_empty() || !data.len().is_multiple_of(4) {
167        return None;
168    }
169    let padding = if data.ends_with("==") {
170        2
171    } else {
172        usize::from(data.ends_with('='))
173    };
174    data.len()
175        .checked_div(4)?
176        .checked_mul(3)?
177        .checked_sub(padding)
178}
179
180pub(crate) fn format_byte_count(bytes: usize) -> String {
181    const KIB: usize = 1024;
182    const MIB: usize = 1024 * KIB;
183    if bytes < KIB {
184        format!("{bytes} B")
185    } else if bytes < MIB {
186        format_decimal_bytes(bytes, KIB, "KiB")
187    } else {
188        format_decimal_bytes(bytes, MIB, "MiB")
189    }
190}
191
192pub(crate) fn format_compact_byte_count(bytes: usize) -> String {
193    const KIB: usize = 1024;
194    const MIB: usize = 1024 * KIB;
195    if bytes < KIB {
196        format!("{bytes}B")
197    } else if bytes < MIB {
198        format!("{}K", bytes.div_ceil(KIB))
199    } else {
200        format!("{}M", bytes.div_ceil(MIB))
201    }
202}
203
204fn format_decimal_bytes(bytes: usize, unit: usize, suffix: &str) -> String {
205    let whole = bytes / unit;
206    let decimal = bytes % unit * 10 / unit;
207    if decimal == 0 {
208        format!("{whole} {suffix}")
209    } else {
210        format!("{whole}.{decimal} {suffix}")
211    }
212}
213
214fn encoded_len(raw_bytes: usize) -> Result<usize, AttachmentError> {
215    if raw_bytes > MAX_INLINE_IMAGE_RAW_BYTES {
216        return Err(AttachmentError::TooLarge);
217    }
218    raw_bytes
219        .checked_add(2)
220        .map(|rounded| rounded / 3 * 4)
221        .ok_or(AttachmentError::TooLarge)
222}
223
224fn detect_mime(bytes: &[u8]) -> Option<&'static str> {
225    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
226        Some("image/png")
227    } else if bytes.starts_with(b"\xff\xd8\xff") {
228        Some("image/jpeg")
229    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
230        Some("image/gif")
231    } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" {
232        Some("image/webp")
233    } else {
234        None
235    }
236}
237
238fn supported_mime(mime_type: &str) -> Option<&'static str> {
239    match mime_type {
240        "image/png" => Some("image/png"),
241        "image/jpeg" => Some("image/jpeg"),
242        "image/gif" => Some("image/gif"),
243        "image/webp" => Some("image/webp"),
244        _ => None,
245    }
246}
247
248fn safe_display_name(path: &Path) -> String {
249    let raw = path
250        .file_name()
251        .map_or_else(|| "image".into(), |name| name.to_string_lossy());
252    let mut result = String::new();
253    let mut pending_space = false;
254    for character in raw.chars().filter(|character| !character.is_control()) {
255        if character.is_whitespace() {
256            pending_space = !result.is_empty();
257            continue;
258        }
259        let needed = character.len_utf8() + usize::from(pending_space);
260        if result.len() + needed > MAX_ATTACHMENT_DISPLAY_NAME_BYTES {
261            break;
262        }
263        if pending_space {
264            result.push(' ');
265            pending_space = false;
266        }
267        result.push(character);
268    }
269    if result.is_empty() {
270        "image".to_owned()
271    } else {
272        result
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use std::fs;
279    use std::path::Path;
280    use std::sync::atomic::{AtomicU64, Ordering};
281
282    use tea_protocol::{ContentBlock, ImageSource, MAX_INLINE_IMAGE_BASE64_BYTES};
283
284    use super::*;
285
286    static ID: AtomicU64 = AtomicU64::new(0);
287
288    fn fixture_path(name: &str) -> std::path::PathBuf {
289        std::env::temp_dir().join(format!(
290            "tea-tui-attachment-{}-{}-{name}",
291            std::process::id(),
292            ID.fetch_add(1, Ordering::Relaxed)
293        ))
294    }
295
296    #[test]
297    fn loader_recognizes_supported_signatures_without_trusting_extension() {
298        let fixtures: [(&str, &[u8]); 4] = [
299            ("image/png", b"\x89PNG\r\n\x1a\nbody"),
300            ("image/jpeg", b"\xff\xd8\xffbody"),
301            ("image/gif", b"GIF89abody"),
302            ("image/webp", b"RIFF\x04\x00\x00\x00WEBPbody"),
303        ];
304
305        for (mime_type, bytes) in fixtures {
306            let path = fixture_path("misleading.txt");
307            fs::write(&path, bytes).unwrap();
308            let attachment = load_local_image(&path).unwrap();
309
310            assert_eq!(attachment.mime_type(), mime_type);
311            assert_eq!(attachment.decoded_bytes(), bytes.len());
312            assert!(attachment.display_name().ends_with("misleading.txt"));
313            assert!(matches!(
314                attachment.content(),
315                ContentBlock::Image {
316                    mime_type: content_mime,
317                    source: ImageSource::InlineBase64 { .. },
318                } if content_mime == mime_type
319            ));
320            fs::remove_file(path).unwrap();
321        }
322    }
323
324    #[test]
325    fn loader_rejects_empty_unsupported_and_oversized_content() {
326        for bytes in [b"".as_slice(), b"not an image".as_slice()] {
327            let path = fixture_path("invalid.bin");
328            fs::write(&path, bytes).unwrap();
329            assert_eq!(
330                load_local_image(&path).unwrap_err(),
331                AttachmentError::UnsupportedFormat
332            );
333            fs::remove_file(path).unwrap();
334        }
335
336        assert_eq!(
337            encoded_len(MAX_INLINE_IMAGE_RAW_BYTES).unwrap(),
338            MAX_INLINE_IMAGE_BASE64_BYTES
339        );
340        assert_eq!(
341            encoded_len(MAX_INLINE_IMAGE_RAW_BYTES + 1),
342            Err(AttachmentError::TooLarge)
343        );
344    }
345
346    #[test]
347    fn display_name_is_bounded_and_control_safe() {
348        let long = format!("{}\nsecret.png", "界".repeat(80));
349        let name = safe_display_name(Path::new(&long));
350
351        assert!(name.len() <= MAX_ATTACHMENT_DISPLAY_NAME_BYTES);
352        assert!(!name.chars().any(char::is_control));
353        assert!(name.is_char_boundary(name.len()));
354        assert_eq!(safe_display_name(Path::new("\n\t")), "image");
355    }
356
357    #[test]
358    fn attachment_limits_bound_count_and_aggregate_bytes() {
359        assert_eq!(validate_addition(0, 0, 4), Ok(()));
360        assert_eq!(
361            validate_addition(MAX_COMPOSER_ATTACHMENTS, 0, 4),
362            Err(AttachmentError::TooMany)
363        );
364        assert_eq!(
365            validate_addition(1, MAX_COMPOSER_IMAGE_BASE64_BYTES - 3, 4),
366            Err(AttachmentError::TotalTooLarge)
367        );
368    }
369
370    #[test]
371    fn attachment_debug_omits_encoded_content() {
372        let path = fixture_path("debug.png");
373        fs::write(&path, b"\x89PNG\r\n\x1a\nprivate-payload").unwrap();
374        let attachment = load_local_image(&path).unwrap();
375        let debug = format!("{attachment:?}");
376
377        assert!(debug.contains("image/png"));
378        assert!(!debug.contains("private-payload"));
379        assert!(!debug.contains("iVBOR"));
380        fs::remove_file(path).unwrap();
381    }
382
383    #[test]
384    fn inline_sizes_are_derived_without_decoding_the_payload() {
385        assert_eq!(decoded_inline_image_bytes("iVBORw0KGgo="), Some(8));
386        assert_eq!(decoded_inline_image_bytes("/9j/"), Some(3));
387        assert_eq!(decoded_inline_image_bytes("bad"), None);
388        assert_eq!(format_byte_count(8), "8 B");
389        assert_eq!(format_byte_count(1536), "1.5 KiB");
390        assert_eq!(format_compact_byte_count(1536), "2K");
391    }
392}