src/commands/matrix_upload.rs

1aebd1afe96d6b9a2f26ca598c88d5aae0ba5008
weechat-matrix-rs/src/commands/matrix_upload.rs history · blame · raw

700 lines · 21533 bytes

42 symbols in this file
  1use std::{
  2    cell::RefCell,
  3    collections::BTreeMap,
  4    rc::Rc,
  5    time::{Duration, Instant},
  6};
  7
  8use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
  9use matrix_sdk::ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId};
 10use sha2::{Digest, Sha256};
 11use weechat::{
 12    buffer::Buffer,
 13    hooks::{CommandRun, CommandRunCallback},
 14    Prefix, ReturnCode, Weechat,
 15};
 16
 17use crate::{
 18    room::{thread_root_from_buffer, RoomHandle},
 19    Servers,
 20};
 21
 22const MAX_UPLOAD_BYTES: usize = 10 * 1024 * 1024;
 23const MAX_ENCODED_CHUNK_BYTES: usize = 32 * 1024;
 24const MAX_ACTIVE_UPLOADS: usize = 4;
 25const UPLOAD_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
 26const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
 27
 28struct MediaUpload {
 29    filename: String,
 30    mime: mime::Mime,
 31    declared_size: usize,
 32    expected_sha256: [u8; 32],
 33    next_chunk: u32,
 34    data: Vec<u8>,
 35}
 36
 37impl MediaUpload {
 38    fn begin(
 39        encoded_filename: &str,
 40        mime: &str,
 41        declared_size: &str,
 42        sha256: &str,
 43    ) -> Result<Self, &'static str> {
 44        let filename = decode_filename(encoded_filename)?;
 45        if !valid_filename(&filename) {
 46            return Err("filename must be a single non-empty file name");
 47        }
 48
 49        if mime.len() > 127 || mime.chars().any(char::is_control) {
 50            return Err("MIME type is invalid or too long");
 51        }
 52        let mime: mime::Mime =
 53            mime.parse().map_err(|_| "MIME type is invalid")?;
 54
 55        let declared_size = declared_size
 56            .parse::<usize>()
 57            .map_err(|_| "declared size must be a decimal byte count")?;
 58
 59        if declared_size == 0 || declared_size > MAX_UPLOAD_BYTES {
 60            return Err("declared size is outside the allowed range");
 61        }
 62
 63        let expected_sha256 = parse_sha256(sha256)?;
 64
 65        Ok(Self {
 66            filename,
 67            mime,
 68            declared_size,
 69            expected_sha256,
 70            next_chunk: 0,
 71            data: Vec::with_capacity(declared_size),
 72        })
 73    }
 74
 75    fn append_chunk(
 76        &mut self,
 77        chunk_index: &str,
 78        encoded: &str,
 79    ) -> Result<(), &'static str> {
 80        if encoded.len() > MAX_ENCODED_CHUNK_BYTES {
 81            return Err("encoded chunk exceeds the allowed size");
 82        }
 83
 84        let chunk_index = chunk_index
 85            .parse::<u32>()
 86            .map_err(|_| "chunk index must be an unsigned integer")?;
 87
 88        if chunk_index != self.next_chunk {
 89            return Err("chunk index is out of order");
 90        }
 91
 92        let chunk = URL_SAFE_NO_PAD
 93            .decode(encoded)
 94            .map_err(|_| "chunk is not valid base64")?;
 95        let new_len = self
 96            .data
 97            .len()
 98            .checked_add(chunk.len())
 99            .ok_or("decoded bytes exceed the declared size")?;
100
101        if new_len > self.declared_size {
102            return Err("decoded bytes exceed the declared size");
103        }
104
105        self.data.extend_from_slice(&chunk);
106        self.next_chunk = self
107            .next_chunk
108            .checked_add(1)
109            .ok_or("too many upload chunks")?;
110        Ok(())
111    }
112
113    fn finish(self) -> Result<(String, mime::Mime, Vec<u8>), &'static str> {
114        if self.data.len() != self.declared_size {
115            return Err("decoded byte count does not match the declared size");
116        }
117
118        if self.mime == mime::IMAGE_PNG && !self.data.starts_with(PNG_SIGNATURE)
119        {
120            return Err("image/png payload does not have a PNG signature");
121        }
122
123        let actual_sha256: [u8; 32] = Sha256::digest(&self.data).into();
124        if actual_sha256 != self.expected_sha256 {
125            return Err("payload hash does not match the declared SHA-256");
126        }
127
128        Ok((self.filename, self.mime, self.data))
129    }
130}
131
132struct PendingMediaUpload {
133    room: RoomHandle,
134    thread_root: Option<OwnedEventId>,
135    identity: UploadIdentity,
136    upload: MediaUpload,
137    last_activity: Instant,
138}
139
140#[derive(Clone, Debug, Eq, PartialEq)]
141struct UploadIdentity {
142    room_id: OwnedRoomId,
143    thread_root: Option<OwnedEventId>,
144}
145
146#[derive(Default)]
147struct UploadState {
148    pending: BTreeMap<String, PendingMediaUpload>,
149}
150
151impl UploadState {
152    fn prune_expired(&mut self, now: Instant) {
153        self.pending.retain(|_, pending| {
154            !upload_is_expired(pending.last_activity, now)
155        });
156    }
157}
158
159pub struct MatrixUploadCommand {
160    servers: Servers,
161    state: Rc<RefCell<UploadState>>,
162}
163
164impl MatrixUploadCommand {
165    pub fn create(servers: &Servers) -> Result<CommandRun, ()> {
166        CommandRun::new(
167            "/matrix-upload",
168            MatrixUploadCommand {
169                servers: servers.clone(),
170                state: Rc::new(RefCell::new(UploadState::default())),
171            },
172        )
173    }
174
175    fn report_error(buffer: &Buffer, error: &str) {
176        buffer.print(&format!(
177            "{}matrix-upload: {}",
178            Weechat::prefix(Prefix::Error),
179            error
180        ));
181    }
182
183    fn current_context(
184        &self,
185        buffer: &Buffer,
186    ) -> Result<(RoomHandle, Option<OwnedEventId>, UploadIdentity), &'static str>
187    {
188        let room = self
189            .servers
190            .find_room(buffer)
191            .ok_or("command must be run in a Matrix room or thread buffer")?;
192        let thread_root = thread_root_from_buffer(buffer);
193        let identity = upload_identity(
194            room.room_id(),
195            thread_root.as_deref(),
196            buffer
197                .get_localvar("matrix_continuation_source_room_id")
198                .as_deref(),
199            buffer
200                .get_localvar("matrix_continuation_source_thread_root")
201                .as_deref(),
202        );
203        Ok((room, thread_root, identity))
204    }
205
206    fn matches_pending(
207        pending: &PendingMediaUpload,
208        identity: &UploadIdentity,
209    ) -> bool {
210        pending.identity == *identity
211    }
212
213    fn begin(&self, buffer: &Buffer, args: &[&str]) {
214        if args.len() != 6 {
215            Self::report_error(buffer, "usage: /matrix-upload begin <id> <filename-base64url> <mime> <bytes> <sha256>");
216            return;
217        }
218
219        if !valid_transfer_id(args[1]) {
220            Self::report_error(
221                buffer,
222                "transfer id must be 1-64 URL-safe characters",
223            );
224            return;
225        }
226
227        let Ok((room, thread_root, identity)) = self.current_context(buffer)
228        else {
229            Self::report_error(
230                buffer,
231                "command must be run in a Matrix room or thread buffer",
232            );
233            return;
234        };
235
236        let upload =
237            match MediaUpload::begin(args[2], args[3], args[4], args[5]) {
238                Ok(upload) => upload,
239                Err(error) => {
240                    Self::report_error(buffer, error);
241                    return;
242                }
243            };
244
245        let mut state = self.state.borrow_mut();
246        state.prune_expired(Instant::now());
247        if state.pending.contains_key(args[1]) {
248            Self::report_error(buffer, "transfer id is already active");
249            return;
250        }
251        if state.pending.len() >= MAX_ACTIVE_UPLOADS {
252            Self::report_error(buffer, "too many active media uploads");
253            return;
254        }
255
256        state.pending.insert(
257            args[1].to_owned(),
258            PendingMediaUpload {
259                room,
260                thread_root,
261                identity,
262                upload,
263                last_activity: Instant::now(),
264            },
265        );
266    }
267
268    fn chunk(&self, buffer: &Buffer, args: &[&str]) {
269        if args.len() != 4 {
270            Self::report_error(
271                buffer,
272                "usage: /matrix-upload chunk <id> <index> <base64url>",
273            );
274            return;
275        }
276        if !valid_transfer_id(args[1]) {
277            Self::report_error(
278                buffer,
279                "transfer id must be 1-64 URL-safe characters",
280            );
281            return;
282        }
283
284        let Ok((_room, _thread_root, identity)) = self.current_context(buffer)
285        else {
286            Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload");
287            return;
288        };
289
290        let mut state = self.state.borrow_mut();
291        state.prune_expired(Instant::now());
292        let error = {
293            let Some(pending) = state.pending.get_mut(args[1]) else {
294                Self::report_error(buffer, "no active upload");
295                return;
296            };
297
298            if !Self::matches_pending(pending, &identity) {
299                Self::report_error(
300                    buffer,
301                    "upload buffer or thread does not match transfer id",
302                );
303                return;
304            } else {
305                let result = pending.upload.append_chunk(args[2], args[3]);
306                if result.is_ok() {
307                    pending.last_activity = Instant::now();
308                }
309                result.err()
310            }
311        };
312
313        if let Some(error) = error {
314            state.pending.remove(args[1]);
315            Self::report_error(buffer, error);
316        }
317    }
318
319    fn commit(&self, buffer: &Buffer, args: &[&str]) {
320        if args.len() != 2 {
321            Self::report_error(buffer, "usage: /matrix-upload commit <id>");
322            return;
323        }
324        if !valid_transfer_id(args[1]) {
325            Self::report_error(
326                buffer,
327                "transfer id must be 1-64 URL-safe characters",
328            );
329            return;
330        }
331
332        let Ok((_room, _thread_root, identity)) = self.current_context(buffer)
333        else {
334            Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload");
335            return;
336        };
337
338        let pending = {
339            let mut state = self.state.borrow_mut();
340            state.prune_expired(Instant::now());
341            let Some(pending) = state.pending.get(args[1]) else {
342                Self::report_error(buffer, "no active upload");
343                return;
344            };
345            if !Self::matches_pending(pending, &identity) {
346                Self::report_error(
347                    buffer,
348                    "upload buffer or thread does not match transfer id",
349                );
350                return;
351            }
352            state.pending.remove(args[1])
353        };
354        let Some(pending) = pending else {
355            Self::report_error(buffer, "no active upload");
356            return;
357        };
358
359        let (filename, mime, data) = match pending.upload.finish() {
360            Ok(upload) => upload,
361            Err(error) => {
362                Self::report_error(buffer, error);
363                return;
364            }
365        };
366
367        let room = pending.room;
368        let thread_root = pending.thread_root;
369        Weechat::spawn(async move {
370            room.send_attachment_bytes(filename, mime, data, thread_root)
371                .await
372        })
373        .detach();
374    }
375
376    fn cancel(&self, buffer: &Buffer, args: &[&str]) {
377        if args.len() != 2 {
378            Self::report_error(buffer, "usage: /matrix-upload cancel <id>");
379            return;
380        }
381        if !valid_transfer_id(args[1]) {
382            Self::report_error(
383                buffer,
384                "transfer id must be 1-64 URL-safe characters",
385            );
386            return;
387        }
388
389        let Ok((_room, _thread_root, identity)) = self.current_context(buffer)
390        else {
391            Self::report_error(buffer, "command must be run in the Matrix buffer that began the upload");
392            return;
393        };
394
395        let mut state = self.state.borrow_mut();
396        state.prune_expired(Instant::now());
397        let Some(pending) = state.pending.get(args[1]) else {
398            Self::report_error(buffer, "no active upload");
399            return;
400        };
401        if !Self::matches_pending(pending, &identity) {
402            Self::report_error(
403                buffer,
404                "upload buffer or thread does not match transfer id",
405            );
406            return;
407        }
408
409        state.pending.remove(args[1]);
410    }
411}
412
413fn upload_identity(
414    current_room_id: &RoomId,
415    current_thread_root: Option<&EventId>,
416    source_room_id: Option<&str>,
417    source_thread_root: Option<&str>,
418) -> UploadIdentity {
419    let source = source_room_id
420        .and_then(|room_id| RoomId::parse(room_id).ok())
421        .zip(
422            source_thread_root
423                .and_then(|event_id| EventId::parse(event_id).ok()),
424        );
425
426    match source {
427        Some((room_id, thread_root)) => UploadIdentity {
428            room_id,
429            thread_root: Some(thread_root),
430        },
431        None => UploadIdentity {
432            room_id: current_room_id.to_owned(),
433            thread_root: current_thread_root.map(ToOwned::to_owned),
434        },
435    }
436}
437
438impl CommandRunCallback for MatrixUploadCommand {
439    fn callback(
440        &mut self,
441        _: &Weechat,
442        buffer: &Buffer,
443        cmd: std::borrow::Cow<str>,
444    ) -> ReturnCode {
445        let Some(arguments) = cmd.strip_prefix("/matrix-upload") else {
446            return ReturnCode::Ok;
447        };
448        let args = arguments.split_whitespace().collect::<Vec<_>>();
449
450        match args.first().copied() {
451            Some("begin") => self.begin(buffer, &args),
452            Some("chunk") => self.chunk(buffer, &args),
453            Some("commit") => self.commit(buffer, &args),
454            Some("cancel") => self.cancel(buffer, &args),
455            _ => Self::report_error(
456                buffer,
457                "usage: /matrix-upload <begin|chunk|commit|cancel>",
458            ),
459        }
460
461        // This hook implements the complete command. Letting WeeChat continue
462        // would run the same input through normal command dispatch as well and
463        // print a misleading "Unknown command" after a handled upload step.
464        ReturnCode::OkEat
465    }
466}
467
468fn valid_filename(filename: &str) -> bool {
469    !filename.is_empty()
470        && filename.len() <= 255
471        && !filename.contains(['/', '\\', '\0'])
472        && !filename.chars().any(char::is_control)
473}
474
475fn decode_filename(encoded: &str) -> Result<String, &'static str> {
476    let bytes = URL_SAFE_NO_PAD
477        .decode(encoded)
478        .map_err(|_| "filename must be URL-safe base64 without padding")?;
479    String::from_utf8(bytes).map_err(|_| "filename must be valid UTF-8")
480}
481
482fn valid_transfer_id(id: &str) -> bool {
483    !id.is_empty()
484        && id.len() <= 64
485        && id.bytes().all(|byte| {
486            byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-'
487        })
488}
489
490fn upload_is_expired(last_activity: Instant, now: Instant) -> bool {
491    now.saturating_duration_since(last_activity) >= UPLOAD_IDLE_TIMEOUT
492}
493
494fn parse_sha256(value: &str) -> Result<[u8; 32], &'static str> {
495    if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit())
496    {
497        return Err("SHA-256 must be 64 hexadecimal characters");
498    }
499
500    let mut hash = [0_u8; 32];
501    for (index, byte) in hash.iter_mut().enumerate() {
502        *byte = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)
503            .map_err(|_| "SHA-256 must be hexadecimal")?;
504    }
505    Ok(hash)
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511
512    fn png(bytes: &[u8]) -> Vec<u8> {
513        [PNG_SIGNATURE, bytes].concat()
514    }
515
516    fn sha256(bytes: &[u8]) -> String {
517        format!("{:x}", Sha256::digest(bytes))
518    }
519
520    fn upload_for(bytes: &[u8], filename: &str, mime: &str) -> MediaUpload {
521        MediaUpload::begin(
522            &URL_SAFE_NO_PAD.encode(filename),
523            mime,
524            &bytes.len().to_string(),
525            &sha256(bytes),
526        )
527        .unwrap()
528    }
529
530    #[test]
531    fn rejects_out_of_bounds_begin_metadata() {
532        assert!(MediaUpload::begin(
533            &URL_SAFE_NO_PAD.encode("image.png"),
534            "image/png",
535            &(MAX_UPLOAD_BYTES + 1).to_string(),
536            &"0".repeat(64),
537        )
538        .is_err());
539        assert!(MediaUpload::begin(
540            &URL_SAFE_NO_PAD.encode("../image.png"),
541            "image/png",
542            "1",
543            &"0".repeat(64),
544        )
545        .is_err());
546        assert!(MediaUpload::begin(
547            &URL_SAFE_NO_PAD.encode("payload.bin"),
548            "not a mime",
549            "1",
550            &"0".repeat(64),
551        )
552        .is_err());
553    }
554
555    #[test]
556    fn rejects_malformed_or_out_of_order_chunks() {
557        let bytes = png(b"payload");
558        let mut upload = upload_for(&bytes, "image.png", "image/png");
559        assert!(upload.append_chunk("1", "AA==").is_err());
560        assert!(upload.append_chunk("0", "not-base64").is_err());
561        assert!(upload
562            .append_chunk("0", &"A".repeat(MAX_ENCODED_CHUNK_BYTES + 1))
563            .is_err());
564    }
565
566    #[test]
567    fn preserves_exact_bytes_across_chunks() {
568        let bytes = png(b"split pixels");
569        let mut upload = upload_for(&bytes, "image.png", "image/png");
570        let split = 10;
571        upload
572            .append_chunk("0", &URL_SAFE_NO_PAD.encode(&bytes[..split]))
573            .unwrap();
574        upload
575            .append_chunk("1", &URL_SAFE_NO_PAD.encode(&bytes[split..]))
576            .unwrap();
577        let (_, content_type, actual) = upload.finish().unwrap();
578        assert_eq!(content_type, mime::IMAGE_PNG);
579        assert_eq!(actual, bytes);
580    }
581
582    #[test]
583    fn rejects_hash_mismatch_and_wrong_png_signature() {
584        let bytes = png(b"payload");
585        let mut upload = MediaUpload::begin(
586            &URL_SAFE_NO_PAD.encode("image.png"),
587            "image/png",
588            &bytes.len().to_string(),
589            &"0".repeat(64),
590        )
591        .unwrap();
592        upload
593            .append_chunk("0", &URL_SAFE_NO_PAD.encode(&bytes))
594            .unwrap();
595        assert!(upload.finish().is_err());
596
597        let bytes = b"not a png";
598        let mut upload = upload_for(bytes, "image.png", "image/png");
599        upload
600            .append_chunk("0", &URL_SAFE_NO_PAD.encode(bytes))
601            .unwrap();
602        assert!(upload.finish().is_err());
603    }
604
605    #[test]
606    fn accepts_pdf_and_octet_stream_without_png_validation() {
607        for (filename, mime, bytes) in [
608            ("report.pdf", "application/pdf", b"%PDF-1.7\n".as_slice()),
609            (
610                "archive.bin",
611                "application/octet-stream",
612                b"\x00\x01\x02".as_slice(),
613            ),
614        ] {
615            let mut upload = upload_for(bytes, filename, mime);
616            upload
617                .append_chunk("0", &URL_SAFE_NO_PAD.encode(bytes))
618                .unwrap();
619            let (actual_filename, actual_mime, actual_bytes) =
620                upload.finish().unwrap();
621            assert_eq!(actual_filename, filename);
622            assert_eq!(actual_mime.as_ref(), mime);
623            assert_eq!(actual_bytes, bytes);
624        }
625    }
626
627    #[test]
628    fn accepts_only_url_safe_ids_and_filenames() {
629        assert!(valid_transfer_id("upload-01_A"));
630        assert!(!valid_transfer_id(""));
631        assert!(!valid_transfer_id("contains space"));
632        assert!(!valid_transfer_id(&"a".repeat(65)));
633        assert_eq!(
634            decode_filename(&URL_SAFE_NO_PAD.encode("attachment image.png"))
635                .unwrap(),
636            "attachment image.png"
637        );
638        assert!(decode_filename("a==").is_err());
639    }
640
641    #[test]
642    fn expires_abandoned_transfers_after_one_minute() {
643        let started = Instant::now();
644        assert!(!upload_is_expired(
645            started,
646            started + UPLOAD_IDLE_TIMEOUT - Duration::from_millis(1)
647        ));
648        assert!(upload_is_expired(started, started + UPLOAD_IDLE_TIMEOUT));
649    }
650
651    #[test]
652    fn adopted_thread_keeps_its_original_upload_identity() {
653        let source_room = RoomId::parse("!old:example.org").unwrap();
654        let source_root = EventId::parse("$old-root:example.org").unwrap();
655        let target_room = RoomId::parse("!new:example.org").unwrap();
656        let target_root = EventId::parse("$new-root:example.org").unwrap();
657
658        let before = upload_identity(
659            &source_room,
660            Some(source_root.as_ref()),
661            None,
662            None,
663        );
664        let after = upload_identity(
665            &target_room,
666            Some(target_root.as_ref()),
667            Some(source_room.as_str()),
668            Some(source_root.as_str()),
669        );
670
671        assert_eq!(before, after);
672        assert_ne!(after.room_id, target_room);
673        assert_ne!(after.thread_root.as_deref(), Some(target_root.as_ref()));
674    }
675
676    #[test]
677    fn incomplete_or_invalid_adoption_metadata_falls_back_safely() {
678        let room = RoomId::parse("!room:example.org").unwrap();
679        let root = EventId::parse("$root:example.org").unwrap();
680
681        for (source_room, source_root) in [
682            (Some("!old:example.org"), None),
683            (None, Some("$old-root:example.org")),
684            (Some("not-a-room"), Some("$old-root:example.org")),
685        ] {
686            assert_eq!(
687                upload_identity(
688                    &room,
689                    Some(root.as_ref()),
690                    source_room,
691                    source_root,
692                ),
693                UploadIdentity {
694                    room_id: room.clone(),
695                    thread_root: Some(root.clone()),
696                }
697            );
698        }
699    }
700}