redseat-api 0.19.1

Rust client for Redseat media servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Random access to the files of encrypted (`crypt`) libraries, for players that
//! stream and seek.
//!
//! A media file is stored as a header, the encrypted thumbnail, then the encrypted
//! data (redseat-crypto, AES-256-CBC with PKCS#7 padding and the media's IV). The
//! server serves the data part with range requests (redseat_rust `docs/MEDIA_FILES.md`).
//! CBC decrypts any block on its own: plaintext block `i` is `AES-decrypt(C[i]) XOR
//! C[i-1]`, with the media's IV before block 0. So [`EncryptedMediaReader::read_at`]
//! fetches only the blocks it needs and the one before them.
//!
//! The decryption goes through redseat-crypto's one-shot functions. Those check the
//! PKCS#7 padding, which only the last block of the data has: blocks from the middle
//! of the data get a padding block appended, encrypted from their last block with
//! the key, so they decrypt to exactly their plaintext.

use crate::crypto::{Iv, Key};
use crate::error::{Error, Result};
use crate::library::LibraryApi;
use crate::transport::{Request, Response};

/// AES block size.
const BLOCK: u64 = 16;

/// Reads the plaintext of an encrypted media by ranges. Get one with
/// [`LibraryApi::open_encrypted_media`], or for a file kept on this device with
/// [`Downloads::source`](crate::app::downloads::Downloads::source). Cheap to clone.
#[derive(Clone)]
pub struct EncryptedMediaReader {
    source: DataSource,
    key: Key,
    iv: Iv,
    /// Bytes of encrypted data, a multiple of 16.
    data_len: u64,
    /// Bytes of plaintext.
    len: u64,
}

/// Where the encrypted data is read: from the server by range requests, or from a
/// file holding the data part as the server serves it (a download kept offline).
// One per reader: its size does not matter.
#[allow(clippy::large_enum_variant)]
#[derive(Clone)]
enum DataSource {
    Server {
        library: LibraryApi,
        media_id: String,
    },
    /// Read on `runtime`'s blocking threads, so any executor can await the reader.
    #[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
    File {
        path: std::path::PathBuf,
        runtime: tokio::runtime::Handle,
    },
}

impl std::fmt::Debug for EncryptedMediaReader {
    // Never print the key.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let source = match &self.source {
            DataSource::Server { media_id, .. } => media_id.clone(),
            #[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
            DataSource::File { path, .. } => path.display().to_string(),
        };
        f.debug_struct("EncryptedMediaReader")
            .field("source", &source)
            .field("len", &self.len)
            .finish_non_exhaustive()
    }
}

/// A range of the encrypted data to fetch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DataRange {
    /// From the first to the last byte, inclusive.
    Bytes(u64, u64),
    /// The last bytes.
    Suffix(u64),
}

impl DataRange {
    fn header(self) -> String {
        match self {
            DataRange::Bytes(start, end) => format!("bytes={start}-{end}"),
            DataRange::Suffix(count) => format!("bytes=-{count}"),
        }
    }
}

/// The blocks to fetch to read plaintext `offset..end` of `data_len` bytes of data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Span {
    /// The first and last block holding the plaintext.
    first: u64,
    last: u64,
    /// The bytes to fetch: the blocks, and the one before them (their IV) if any.
    fetch: (u64, u64),
}

fn span(offset: u64, end: u64) -> Span {
    let (first, last) = (offset / BLOCK, (end - 1) / BLOCK);
    Span {
        first,
        last,
        fetch: (first.saturating_sub(1) * BLOCK, (last + 1) * BLOCK - 1),
    }
}

fn to_block(bytes: &[u8]) -> Result<Iv> {
    bytes
        .try_into()
        .map_err(|_| Error::malformed("encrypted data is not made of whole blocks", None))
}

/// Decrypts whole CBC blocks that follow `prev` (the previous ciphertext block, or
/// the IV). `last_of_data`: they end the data, padding included.
fn decrypt_blocks(key: &Key, prev: &Iv, blocks: &[u8], last_of_data: bool) -> Result<Vec<u8>> {
    if blocks.is_empty() || !blocks.len().is_multiple_of(BLOCK as usize) {
        return Err(Error::malformed(
            "encrypted data is not made of whole blocks",
            None,
        ));
    }
    if last_of_data {
        return Ok(redseat_crypto::decrypt_buffer(key, prev, blocks)?);
    }
    // A block encrypted from the last one decrypts to a full padding block.
    let last = to_block(&blocks[blocks.len() - BLOCK as usize..])?;
    let mut with_padding = blocks.to_vec();
    with_padding.extend(redseat_crypto::encrypt_buffer(key, &last, &[]));
    Ok(redseat_crypto::decrypt_buffer(key, prev, &with_padding)?)
}

/// The total of a `Content-Range: bytes a-b/total` header.
fn content_range_total(response: &Response) -> Option<u64> {
    response
        .header("content-range")?
        .rsplit('/')
        .next()?
        .trim()
        .parse()
        .ok()
}

impl EncryptedMediaReader {
    pub(crate) async fn open(
        library: LibraryApi,
        media_id: String,
        key: Key,
        iv: Iv,
        size: Option<u64>,
    ) -> Result<Self> {
        let source = DataSource::Server { library, media_id };
        Self::open_source(source, key, iv, size).await
    }

    /// The data part of an encrypted media in a file of this device, as the server
    /// serves it by ranges, read on `runtime`.
    #[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
    pub(crate) async fn open_file(
        path: std::path::PathBuf,
        runtime: tokio::runtime::Handle,
        key: Key,
        iv: Iv,
    ) -> Result<Self> {
        Self::open_source(DataSource::File { path, runtime }, key, iv, None).await
    }

    async fn open_source(source: DataSource, key: Key, iv: Iv, size: Option<u64>) -> Result<Self> {
        let mut reader = EncryptedMediaReader {
            source,
            key,
            iv,
            data_len: 0,
            len: 0,
        };
        // The server writes no data for an empty file.
        if size == Some(0) {
            return Ok(reader);
        }
        // The last two blocks: the data size, and the padding of the last one.
        let (tail, data_len) = reader.fetch(DataRange::Suffix(2 * BLOCK)).await?;
        if data_len == 0 || !data_len.is_multiple_of(BLOCK) || tail.len() < BLOCK as usize {
            return Err(Error::malformed(
                format!("encrypted data of {data_len} bytes is not made of whole blocks"),
                None,
            ));
        }
        let (prev, last) = match tail.len() {
            32 => (to_block(&tail[..16])?, &tail[16..]),
            _ => (reader.iv, &tail[tail.len() - 16..]),
        };
        let last_plain = decrypt_blocks(&reader.key, &prev, last, true)?;
        reader.data_len = data_len;
        reader.len = data_len - BLOCK + last_plain.len() as u64;
        Ok(reader)
    }

    /// The plaintext size, in bytes.
    pub fn len(&self) -> u64 {
        self.len
    }

    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Up to `len` bytes of plaintext from `offset`: fewer at the end, none past it.
    pub async fn read_at(&self, offset: u64, len: usize) -> Result<Vec<u8>> {
        if offset >= self.len || len == 0 {
            return Ok(Vec::new());
        }
        let end = offset.saturating_add(len as u64).min(self.len);
        let span = span(offset, end);
        let (fetched, _) = self
            .fetch(DataRange::Bytes(span.fetch.0, span.fetch.1))
            .await?;
        if fetched.len() as u64 != span.fetch.1 - span.fetch.0 + 1 {
            return Err(Error::malformed(
                format!(
                    "asked for {} bytes of encrypted data, got {}",
                    span.fetch.1 - span.fetch.0 + 1,
                    fetched.len()
                ),
                None,
            ));
        }
        let (prev, blocks) = if span.first == 0 {
            (self.iv, &fetched[..])
        } else {
            (to_block(&fetched[..16])?, &fetched[16..])
        };
        let last_of_data = span.last == self.data_len / BLOCK - 1;
        let plain = decrypt_blocks(&self.key, &prev, blocks, last_of_data)?;
        let skip = (offset - span.first * BLOCK) as usize;
        let take = (end - offset) as usize;
        plain
            .get(skip..skip + take)
            .map(<[u8]>::to_vec)
            .ok_or_else(|| Error::malformed("encrypted data shorter than expected", None))
    }

    /// Fetches a range of the encrypted data; returns it and the data size.
    async fn fetch(&self, range: DataRange) -> Result<(Vec<u8>, u64)> {
        let (library, media_id) = match &self.source {
            DataSource::Server { library, media_id } => (library, media_id),
            #[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
            DataSource::File { path, runtime } => {
                let path = path.clone();
                return (runtime.spawn_blocking(move || read_file_range(&path, range)))
                    .await
                    .map_err(|error| Error::Storage {
                        message: format!("cannot read the downloaded file: {error}"),
                    })?;
            }
        };
        let request = Request::get(library.media_path(media_id)).header("Range", range.header());
        let response = library.client().request(request).await?;
        // An older server ignores the range and sends the whole data.
        let total = match (response.status, content_range_total(&response)) {
            (206, Some(total)) => total,
            _ => {
                return Err(Error::malformed(
                    "the server cannot serve parts of encrypted files: it needs an update",
                    None,
                ));
            }
        };
        Ok((response.body, total))
    }
}

/// A range of a file holding encrypted data, and the file's size.
#[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
fn read_file_range(path: &std::path::Path, range: DataRange) -> Result<(Vec<u8>, u64)> {
    use std::io::{Read as _, Seek as _};
    let storage = |error: std::io::Error| Error::Storage {
        message: format!("cannot read the downloaded file: {error}"),
    };
    let mut file = std::fs::File::open(path).map_err(storage)?;
    let total = file.metadata().map_err(storage)?.len();
    let (start, end) = match range {
        DataRange::Bytes(start, end) => (start, end.min(total.saturating_sub(1))),
        DataRange::Suffix(count) => (total.saturating_sub(count), total.saturating_sub(1)),
    };
    if total == 0 || start > end {
        return Ok((Vec::new(), total));
    }
    file.seek(std::io::SeekFrom::Start(start))
        .map_err(storage)?;
    let mut bytes = vec![0; (end - start + 1) as usize];
    file.read_exact(&mut bytes).map_err(storage)?;
    Ok((bytes, total))
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use base64::Engine;

    use super::span;
    use crate::client::{ClientOptions, RedseatClient};
    use crate::cloud::ServerToken;
    use crate::library::LibraryApi;
    use crate::test_support::FakeTransport;
    use crate::transport::{Request, Response};
    use crate::types::media::Media;

    /// The encrypted data part of a file holding `plain`, as the server stores it.
    fn encrypted_data(key: &[u8; 32], iv: &[u8; 16], plain: &[u8]) -> Vec<u8> {
        let file = redseat_crypto::encrypt_file_bytes(
            key,
            iv,
            plain,
            Some("video/mp4"),
            Some((b"thumb", "image/jpeg")),
            None,
        )
        .unwrap();
        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
        file[header.data_offset() as usize..].to_vec()
    }

    /// Answers range requests on `data` as the server does since range support:
    /// 206 with a Content-Range relative to the data.
    fn serve_ranges(data: &[u8], request: &Request) -> Response {
        let range = request
            .headers
            .iter()
            .find(|(name, _)| name == "Range")
            .map(|(_, value)| value.trim_start_matches("bytes=").to_owned())
            .expect("a range request");
        let total = data.len() as u64;
        let (start, end) = match range.split_once('-').unwrap() {
            ("", count) => (total.saturating_sub(count.parse().unwrap()), total - 1),
            (start, "") => (start.parse().unwrap(), total - 1),
            (start, end) => (
                start.parse().unwrap(),
                end.parse::<u64>().unwrap().min(total - 1),
            ),
        };
        Response {
            status: 206,
            headers: vec![(
                "content-range".into(),
                format!("bytes {start}-{end}/{total}"),
            )],
            body: data[start as usize..=end as usize].to_vec(),
        }
    }

    fn library(fake: Arc<FakeTransport>, key: [u8; 32]) -> LibraryApi {
        let client = RedseatClient::new(ClientOptions::new(fake));
        client.set_token(ServerToken {
            token: "t".into(),
            expires: i64::MAX,
        });
        let library = serde_json::from_value(serde_json::json!({
            "id": "lib", "name": "Vault", "source": "PathProvider", "type": "photos", "crypt": true
        }))
        .unwrap();
        let api = LibraryApi::new(client, library);
        api.set_key(key);
        api
    }

    fn media(iv: &[u8; 16], size: u64) -> Media {
        Media {
            id: "m1".into(),
            size: Some(size),
            iv: Some(base64::engine::general_purpose::STANDARD.encode(iv)),
            ..Default::default()
        }
    }

    #[test]
    fn fetches_the_blocks_and_the_one_before() {
        // Inside block 0: no block before it.
        assert_eq!(span(3, 10).fetch, (0, 15));
        // Across blocks 1 and 2: from block 0, their IV.
        let crossing = span(20, 40);
        assert_eq!((crossing.first, crossing.last), (1, 2));
        assert_eq!(crossing.fetch, (0, 47));
        assert_eq!(span(160, 161).fetch, (144, 175));
    }

    #[tokio::test]
    async fn reads_any_range_of_the_plaintext() {
        let key = redseat_crypto::derive_key("secret");
        let iv = redseat_crypto::random_iv().unwrap();
        for size in [1usize, 15, 16, 17, 31, 32, 1000, 4096] {
            let plain: Vec<u8> = (0..size).map(|i| (i * 7 % 251) as u8).collect();
            let data = encrypted_data(&key, &iv, &plain);
            let served = data.clone();
            let fake = FakeTransport::new(move |request| {
                assert_eq!(request.path, "/libraries/lib/medias/m1");
                Ok(serve_ranges(&served, request))
            });
            let api = library(fake.clone(), key);
            let reader = api
                .open_encrypted_media(&media(&iv, data.len() as u64))
                .await
                .unwrap();
            assert_eq!(reader.len(), size as u64, "size {size}");

            let reads = [
                (0, 5),
                (0, size),
                (size / 2, 40),
                (15, 2),
                (16, 16),
                (size.saturating_sub(3), 10),
            ];
            for (offset, len) in reads {
                let got = reader.read_at(offset as u64, len).await.unwrap();
                let end = (offset + len).min(size);
                let expected = plain.get(offset..end).unwrap_or_default();
                assert_eq!(got, expected, "size {size}, read {offset}+{len}");
            }
            assert!(reader.read_at(size as u64, 10).await.unwrap().is_empty());
            // Only the blocks needed are fetched: a read of 5 bytes, one block.
            let requests = fake.requests();
            let first_read = &requests[1];
            assert!(
                first_read
                    .headers
                    .contains(&("Range".to_owned(), "bytes=0-15".to_owned())),
                "{:?}",
                first_read.headers
            );
        }
    }

    /// A download kept offline holds the data part as the server serves it.
    #[cfg(feature = "mirror")]
    #[tokio::test]
    async fn reads_a_downloaded_file_by_ranges() {
        let key = redseat_crypto::derive_key("secret");
        let iv = redseat_crypto::random_iv().unwrap();
        let path = std::env::temp_dir().join(format!(
            "redseat-encrypted-file-{}-{}",
            std::process::id(),
            crate::client::now_ms()
        ));
        for size in [1usize, 16, 17, 1000] {
            let plain: Vec<u8> = (0..size).map(|i| (i * 7 % 251) as u8).collect();
            std::fs::write(&path, encrypted_data(&key, &iv, &plain)).unwrap();
            let reader = super::EncryptedMediaReader::open_file(
                path.clone(),
                tokio::runtime::Handle::current(),
                key,
                iv,
            )
            .await
            .unwrap();
            assert_eq!(reader.len(), size as u64);
            assert_eq!(reader.read_at(0, size).await.unwrap(), plain);
            let middle = reader.read_at(size as u64 / 2, 20).await.unwrap();
            let end = (size / 2 + 20).min(size);
            assert_eq!(middle, plain[size / 2..end]);
        }
        std::fs::remove_file(&path).unwrap();
    }

    #[tokio::test]
    async fn an_empty_file_needs_no_request() {
        let fake = FakeTransport::new(|_| panic!("no request"));
        let key = redseat_crypto::derive_key("secret");
        let reader = library(fake, key)
            .open_encrypted_media(&media(&[0; 16], 0))
            .await
            .unwrap();
        assert!(reader.is_empty());
        assert!(reader.read_at(0, 10).await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn says_when_the_server_needs_an_update() {
        let key = redseat_crypto::derive_key("secret");
        let iv = [3u8; 16];
        let data = encrypted_data(&key, &iv, b"a video");
        // An older server ignores the range: 200 with the whole data.
        let fake = FakeTransport::new(move |_| Ok(FakeTransport::bytes(data.clone())));
        let error = library(fake, key)
            .open_encrypted_media(&media(&iv, 16))
            .await
            .unwrap_err();
        assert!(error.to_string().contains("update"), "{error}");
    }

    #[tokio::test]
    async fn a_wrong_key_fails_on_open() {
        let iv = [5u8; 16];
        let data = encrypted_data(&redseat_crypto::derive_key("secret"), &iv, &[1u8; 100]);
        let fake = FakeTransport::new(move |request| Ok(serve_ranges(&data, request)));
        let error = library(fake, redseat_crypto::derive_key("wrong"))
            .open_encrypted_media(&media(&iv, 112))
            .await
            .unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::Crypto);
    }
}