redseat-api 0.3.0

Rust client for Redseat media servers
Documentation
//! 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`]. Cheap to clone.
#[derive(Clone)]
pub struct EncryptedMediaReader {
    library: LibraryApi,
    media_id: String,
    key: Key,
    iv: Iv,
    /// Bytes of encrypted data, a multiple of 16.
    data_len: u64,
    /// Bytes of plaintext.
    len: u64,
}

impl std::fmt::Debug for EncryptedMediaReader {
    // Never print the key.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EncryptedMediaReader")
            .field("media_id", &self.media_id)
            .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 mut reader = EncryptedMediaReader {
            library,
            media_id,
            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 request =
            Request::get(self.library.media_path(&self.media_id)).header("Range", range.header());
        let response = self.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))
    }
}

#[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, library_from_json};
    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 = library_from_json(serde_json::json!({
            "id": "lib", "name": "Vault", "source": "PathProvider", "type": "photos", "crypt": true
        }))
        .unwrap();
        let api = LibraryApi::new(client, library);
        api.set_key_for_tests(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
            );
        }
    }

    #[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);
    }
}