Skip to main content

zaun_community_protocol/command/
attachment.rs

1//! Attachment commands (specification §8.5, "Attachments"). Both are channel-scoped: the
2//! channel is the envelope's `channel_id`.
3//!
4//! The bytes never travel in a Zaun frame. An upload is declared with `attachment.upload`,
5//! then sent as an ordinary SimpleX file (XFTP) over the same post-quantum connection, with
6//! the caption [`caption`] names. A download is asked for with `attachment.download`, and the
7//! host sends the file back the same way. XFTP encrypts each file with a fresh symmetric key
8//! that only travels inside the connection's ratchet.
9
10use serde::{Deserialize, Serialize};
11
12use super::{BodyError, Validate, check};
13use crate::ids::AttachmentId;
14use crate::limits::{ATTACHMENT_MIME_MAX, ATTACHMENT_NAME, ATTACHMENT_SIZE_MAX};
15
16/// What every Zaun file transfer's caption starts with; the attachment id follows.
17pub const CAPTION_PREFIX: &str = "zaun-attachment:";
18
19/// The caption of the SimpleX file that carries attachment `id`, either way.
20#[must_use]
21pub fn caption(id: AttachmentId) -> String {
22    format!("{CAPTION_PREFIX}{}", id.to_b64())
23}
24
25/// The attachment a caption names, when it is a Zaun caption.
26#[must_use]
27pub fn parse_caption(text: &str) -> Option<AttachmentId> {
28    AttachmentId::from_b64(text.strip_prefix(CAPTION_PREFIX)?).ok()
29}
30
31/// `attachment.upload`: declares a file the member is about to send.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Upload {
34    /// The file name shown to readers: 1–255 scalars, no path separator or control character.
35    pub name: String,
36    /// Exact size in bytes, 1 to the host's limit (at most 1 GiB).
37    pub size: u64,
38    /// The media type, such as `image/png` (`type/subtype`, ASCII, at most 127 bytes).
39    pub mime: String,
40    /// SHA3-256 of the bytes, base64url. The host refuses a file that does not match.
41    #[serde(with = "crate::b64::bytes")]
42    pub sha3_256: Vec<u8>,
43}
44
45/// `attachment.upload` response.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47pub struct Uploading {
48    /// Host-assigned id; the file's caption names it ([`caption`]).
49    pub attachment_id: AttachmentId,
50    /// When the host stops waiting for the file, ms.
51    pub expires_at: u64,
52}
53
54/// `attachment.download`: asks the host to send an attachment's file.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56pub struct Download {
57    /// An attachment of a message in the envelope's channel.
58    pub attachment_id: AttachmentId,
59}
60
61impl Validate for Upload {
62    fn validate(&self) -> Result<(), BodyError> {
63        check::text("name", &self.name, ATTACHMENT_NAME)?;
64        if self
65            .name
66            .chars()
67            .any(|c| c.is_control() || matches!(c, '/' | '\\'))
68            || matches!(self.name.as_str(), "." | "..")
69        {
70            return Err(BodyError::bad("name", "not a plain file name"));
71        }
72        check::range("size", self.size, 1, ATTACHMENT_SIZE_MAX)?;
73        if !mime_ok(&self.mime) {
74            return Err(BodyError::bad("mime", "not a type/subtype media type"));
75        }
76        if self.sha3_256.len() != 32 {
77            return Err(BodyError::bad("sha3_256", "must be 32 bytes"));
78        }
79        Ok(())
80    }
81}
82
83impl Validate for Download {
84    fn validate(&self) -> Result<(), BodyError> {
85        Ok(())
86    }
87}
88
89/// `type/subtype` of RFC 6838 restricted-name characters, without parameters.
90fn mime_ok(mime: &str) -> bool {
91    let token = |s: &str| {
92        !s.is_empty()
93            && s.bytes()
94                .all(|b| b.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&b))
95    };
96    mime.len() <= ATTACHMENT_MIME_MAX
97        && mime
98            .split_once('/')
99            .is_some_and(|(t, sub)| token(t) && token(sub))
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    fn upload() -> Upload {
107        Upload {
108            name: "cat.png".into(),
109            size: 10,
110            mime: "image/png".into(),
111            sha3_256: vec![0; 32],
112        }
113    }
114
115    #[test]
116    fn a_plain_upload_is_valid() {
117        assert!(upload().validate().is_ok());
118    }
119
120    #[test]
121    fn names_with_paths_or_controls_are_refused() {
122        for name in ["", "a/b", "a\\b", "..", ".", "x\ny", "\u{7f}"] {
123            let u = Upload {
124                name: name.into(),
125                ..upload()
126            };
127            assert!(u.validate().is_err(), "{name:?}");
128        }
129    }
130
131    #[test]
132    fn size_hash_and_mime_are_checked() {
133        let big = Upload {
134            size: ATTACHMENT_SIZE_MAX + 1,
135            ..upload()
136        };
137        assert!(big.validate().is_err());
138        let empty = Upload {
139            size: 0,
140            ..upload()
141        };
142        assert!(empty.validate().is_err());
143        let short = Upload {
144            sha3_256: vec![0; 31],
145            ..upload()
146        };
147        assert!(short.validate().is_err());
148        for mime in ["image", "image/", "/png", "image/png; q=1", "ima ge/png"] {
149            let u = Upload {
150                mime: mime.into(),
151                ..upload()
152            };
153            assert!(u.validate().is_err(), "{mime:?}");
154        }
155        let ok = Upload {
156            mime: "application/vnd.oasis.opendocument.text".into(),
157            ..upload()
158        };
159        assert!(ok.validate().is_ok());
160    }
161
162    #[test]
163    fn captions_round_trip_and_reject_others() {
164        let id = AttachmentId::random().unwrap();
165        assert_eq!(parse_caption(&caption(id)), Some(id));
166        assert_eq!(parse_caption("hello"), None);
167        assert_eq!(parse_caption("zaun-attachment:not-an-id"), None);
168    }
169}