//! Mandatory tests 2 and 3. Hostile audio — truncated files, wrong extensions, absurd chapter counts, huge metadata //! blocks, impossible nesting — is rejected cleanly within a time cap. DRM-protected files are refused with the one //! sentence, and the crate has no decrypt path. Every fixture is built here. use liber_audio::DRM_MESSAGE; use liber_audio::container::{AudioError, Caps, Kind, cue, inspect}; use liber_audio::decode::{DecodeCaps, decode_all}; use std::time::{Duration, Instant}; const CAP: Duration = Duration::from_secs(2); fn bx(kind: &[u8; 4], body: &[u8]) -> Vec { let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec(); v.extend_from_slice(kind); v.extend_from_slice(body); v } fn ftyp(brand: &[u8; 4]) -> Vec { let mut b = brand.to_vec(); b.extend_from_slice(&0u32.to_be_bytes()); b.extend_from_slice(b"M4A isom"); bx(b"ftyp", &b) } fn mvhd(timescale: u32, duration: u32) -> Vec { let mut b = vec![0u8; 4]; // version 0, flags b.extend_from_slice(&[0; 8]); // creation, modification b.extend_from_slice(×cale.to_be_bytes()); b.extend_from_slice(&duration.to_be_bytes()); b.extend_from_slice(&[0; 80]); bx(b"mvhd", &b) } fn chpl(chapters: &[(u64, &str)], claim: Option) -> Vec { let mut b = vec![1, 0, 0, 0, 0, 0, 0, 0]; // version 1, flags, reserved b.push(claim.unwrap_or(chapters.len() as u8)); for (start_ms, t) in chapters { b.extend_from_slice(&(start_ms * 10_000).to_be_bytes()); b.push(t.len() as u8); b.extend_from_slice(t.as_bytes()); } bx(b"chpl", &b) } fn m4b(moov_children: &[Vec], brand: &[u8; 4]) -> Vec { let mut f = ftyp(brand); f.extend(bx(b"moov", &moov_children.concat())); f.extend(bx(b"mdat", &[0u8; 64])); f } fn timed(f: impl FnOnce() -> T) -> T { let t = Instant::now(); let r = f(); assert!(t.elapsed() < CAP, "took {:?}", t.elapsed()); r } fn wav(samples: &[i16], rate: u32) -> Vec { let data: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); let mut v = b"RIFF".to_vec(); v.extend_from_slice(&(36 + data.len() as u32).to_le_bytes()); v.extend_from_slice(b"WAVEfmt "); v.extend_from_slice(&16u32.to_le_bytes()); v.extend_from_slice(&1u16.to_le_bytes()); // PCM v.extend_from_slice(&1u16.to_le_bytes()); // mono v.extend_from_slice(&rate.to_le_bytes()); v.extend_from_slice(&(rate * 2).to_le_bytes()); v.extend_from_slice(&2u16.to_le_bytes()); v.extend_from_slice(&16u16.to_le_bytes()); v.extend_from_slice(b"data"); v.extend_from_slice(&(data.len() as u32).to_le_bytes()); v.extend(data); v } #[test] fn a_good_m4b_gives_duration_and_chapters() { let udta = bx(b"udta", &chpl(&[(0, "Opening"), (90_000, "The mill"), (300_000, "Winter")], None)); let f = m4b(&[mvhd(1000, 600_000), udta], b"M4B "); let info = timed(|| inspect(&f, Caps::default())).expect("reads"); assert_eq!(info.kind, Kind::Mp4); assert_eq!(info.duration_ms, Some(600_000)); let titles: Vec<&str> = info.chapters.iter().map(|c| c.title.as_str()).collect(); assert_eq!(titles, ["Opening", "The mill", "Winter"]); assert_eq!(info.chapters[2].end_ms, 600_000); } #[test] fn drm_is_refused_with_the_sentence() { // Audible AAX: the brand, an `adrm` box, an encrypted sample entry. let by_brand = m4b(&[mvhd(1000, 1000)], b"aax "); let by_aaxc = m4b(&[mvhd(1000, 1000)], b"aaxc"); let by_aabd = m4b(&[mvhd(1000, 1000), bx(b"aabd", &[0u8; 16])], b"M4B "); let by_box = m4b(&[mvhd(1000, 1000), bx(b"adrm", &[0u8; 56])], b"M4B "); let mut stsd = vec![0u8; 8]; stsd.extend(bx(b"enca", &[0u8; 28])); let entry = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd))))); let by_entry = m4b(&[mvhd(1000, 1000), entry], b"M4B "); for f in [by_brand, by_aaxc, by_aabd, by_box, by_entry] { let e = timed(|| inspect(&f, Caps::default())).expect_err("refused"); assert_eq!(e, AudioError::Drm); assert_eq!(e.message(), DRM_MESSAGE); assert_eq!(decode_all(f.clone(), DecodeCaps::default()).expect_err("refused"), AudioError::Drm); } assert_eq!(DRM_MESSAGE, "This audiobook is DRM-protected, so Liber cannot play it."); } #[test] fn there_is_no_decrypt_path() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); let manifest = std::fs::read_to_string(root.join("Cargo.toml")).unwrap(); for c in ["aes", "ctr", "cbc", "cipher", "openssl", "ring"] { assert!( !manifest .lines() .any(|l| l.trim_start().starts_with(&format!("{c} ")) || l.trim_start().starts_with(&format!("{c}="))), "{c} in Cargo.toml" ); } for e in std::fs::read_dir(root.join("src")).unwrap() { let p = e.unwrap().path(); let s = std::fs::read_to_string(&p).unwrap().to_lowercase(); for bad in ["decrypt(", "activation_bytes", "activation bytes", "aes::", "cipher::"] { assert!(!s.contains(bad), "{}: {bad}", p.display()); } } } #[test] fn hostile_mp4_is_rejected_cleanly() { // A chapter count that the bytes do not hold. let lying = m4b(&[mvhd(1000, 1000), bx(b"udta", &chpl(&[(0, "a")], Some(255)))], b"M4B "); assert!(matches!(timed(|| inspect(&lying, Caps::default())), Err(AudioError::Damaged(_)))); // A box claiming a terabyte inside a small file: read what is there, allocate nothing from the claim. let mut huge = ftyp(b"M4B "); huge.extend_from_slice(&1u32.to_be_bytes()); huge.extend_from_slice(b"mdat"); huge.extend_from_slice(&(1u64 << 40).to_be_bytes()); huge.extend_from_slice(&[0u8; 100]); assert!(timed(|| inspect(&huge, Caps::default())).is_ok()); // A box smaller than its own header. let mut tiny = ftyp(b"M4B "); tiny.extend_from_slice(&4u32.to_be_bytes()); tiny.extend_from_slice(b"moov"); assert!(matches!(timed(|| inspect(&tiny, Caps::default())), Err(AudioError::Damaged(_)))); // Nesting deeper than any real file. let mut nest = bx(b"udta", &[]); for _ in 0..40 { nest = bx(b"moov", &nest); } let mut deep = ftyp(b"M4B "); deep.extend(nest); assert!(matches!(timed(|| inspect(&deep, Caps::default())), Err(AudioError::Damaged(_)))); // Two hundred thousand empty boxes. let mut many = ftyp(b"M4B "); many.extend(bx(b"moov", &bx(b"free", &[]).repeat(250_000))); assert!(matches!(timed(|| inspect(&many, Caps::default())), Err(AudioError::Damaged(_)))); // A ftyp that claims to be bigger than the file. let mut bad_ftyp = ftyp(b"M4B "); bad_ftyp[..4].copy_from_slice(&9_999u32.to_be_bytes()); assert!(matches!(timed(|| inspect(&bad_ftyp, Caps::default())), Err(AudioError::Damaged(_)))); } fn id3(frames: &[u8], declared: Option) -> Vec { let size = declared.unwrap_or(frames.len()); let ss = [(size >> 21) as u8 & 0x7F, (size >> 14) as u8 & 0x7F, (size >> 7) as u8 & 0x7F, size as u8 & 0x7F]; let mut v = b"ID3\x03\x00\x00".to_vec(); v.extend_from_slice(&ss); v.extend_from_slice(frames); v } fn frame(id: &[u8; 4], body: &[u8]) -> Vec { let mut v = id.to_vec(); v.extend_from_slice(&(body.len() as u32).to_be_bytes()); v.extend_from_slice(&[0, 0]); v.extend_from_slice(body); v } fn chap(id: &str, start: u32, end: u32, title: &str) -> Vec { let mut b = id.as_bytes().to_vec(); b.push(0); for x in [start, end, u32::MAX, u32::MAX] { b.extend_from_slice(&x.to_be_bytes()); } let mut t = vec![3u8]; t.extend_from_slice(title.as_bytes()); b.extend(frame(b"TIT2", &t)); frame(b"CHAP", &b) } #[test] fn mp3_chapters_and_hostile_tags() { let good = id3( &[chap("c1", 0, 60_000, "Eins"), chap("c2", 60_000, 125_000, "Zwei"), frame(b"TIT2", b"\x03Die M\xc3\xbchle")] .concat(), None, ); let info = timed(|| inspect(&good, Caps::default())).expect("reads"); assert_eq!(info.title.as_deref(), Some("Die Mühle")); assert_eq!(info.chapters.iter().map(|c| c.title.as_str()).collect::>(), ["Eins", "Zwei"]); assert_eq!(info.duration_ms, Some(125_000)); // A tag that claims 200 MB. let huge = id3(&[], Some(200 << 20)); assert!(matches!(timed(|| inspect(&huge, Caps::default())), Err(AudioError::Damaged(_)))); // An absurd number of chapter frames. let many = id3(&chap("c", 0, 1, "x").repeat(30_000), None); assert!(matches!(timed(|| inspect(&many, Caps::default())), Err(AudioError::Damaged(_)))); // A frame larger than its tag. let mut lying = frame(b"TIT2", b"\x03abc"); lying[4..8].copy_from_slice(&1_000_000u32.to_be_bytes()); assert!(matches!(timed(|| inspect(&id3(&lying, None), Caps::default())), Err(AudioError::Damaged(_)))); } #[test] fn decoding_real_samples_and_broken_streams() { // A WAV the decoder reads end to end. let samples: Vec = (0..16_000).map(|i| ((i as f32 * 0.07).sin() * 12_000.0) as i16).collect(); let good = wav(&samples, 16_000); let (rate, ch, out) = timed(|| decode_all(good.clone(), DecodeCaps::default())).expect("decodes"); assert_eq!((rate, ch, out.len()), (16_000, 1, 16_000)); assert_eq!(inspect(&good, Caps::default()).unwrap().duration_ms, Some(1_000)); // Truncated: half the data is gone; it ends early or reports damage, never hangs or panics. let cut = good[..good.len() / 2].to_vec(); match timed(|| decode_all(cut, DecodeCaps::default())) { Ok((_, _, s)) => assert!(s.len() < 16_000), Err(e) => assert!(matches!(e, AudioError::Damaged(_) | AudioError::Unsupported)), } // Wrong extension or plain junk: refused by content. let junk = b"this is not audio, whatever its name says".repeat(100); assert_eq!(timed(|| decode_all(junk.clone(), DecodeCaps::default())).expect_err("junk"), AudioError::Unsupported); assert_eq!(timed(|| inspect(&junk, Caps::default())).expect_err("junk"), AudioError::Unsupported); // An MP4 container with no audio track at all. let empty = m4b(&[mvhd(1000, 1000)], b"M4B "); assert!(timed(|| decode_all(empty, DecodeCaps::default())).is_err()); } #[test] fn cue_sheets() { let sheet = "FILE \"book.mp3\" MP3\n TRACK 01 AUDIO\n TITLE \"Kapitel 1\"\n INDEX 01 00:00:00\n TRACK 02 AUDIO\n TITLE \"Kapitel 2\"\n INDEX 01 12:30:37\n"; let ch = cue(sheet, 3_600_000).expect("chapters"); assert_eq!(ch.len(), 2); assert_eq!(ch[1].title, "Kapitel 2"); assert_eq!(ch[1].start_ms, 12 * 60_000 + 30_000 + 37 * 1000 / 75); assert!(cue("garbage", 1000).is_none()); } /// An M4B whose chapters are a QuickTime chapter track: an audio track that refers (`tref`/`chap`) to a text track; /// the text track's samples (a 16-bit length, then the title) sit in `mdat`. fn m4b_with_chapter_track(titles: &[&str], starts_ms: &[u32]) -> Vec { let full = |v: u8| vec![v, 0, 0, 0]; let tkhd = |id: u32| bx(b"tkhd", &[full(0), vec![0; 8], id.to_be_bytes().to_vec(), vec![0; 64]].concat()); let mdhd = bx( b"mdhd", &[full(0), vec![0; 8], 1000u32.to_be_bytes().to_vec(), 0u32.to_be_bytes().to_vec(), vec![0; 4]].concat(), ); let hdlr = |h: &[u8; 4]| bx(b"hdlr", &[full(0), vec![0; 4], h.to_vec(), vec![0; 13]].concat()); // The text samples, laid out after ftyp + moov: we fix their offset after building moov once. let samples: Vec> = titles.iter().map(|t| [(t.len() as u16).to_be_bytes().to_vec(), t.as_bytes().to_vec()].concat()).collect(); let build = |mdat_at: u32| { let mut stts = full(0); stts.extend((starts_ms.len() as u32).to_be_bytes()); for (i, s) in starts_ms.iter().enumerate() { let next = starts_ms.get(i + 1).copied().unwrap_or(s + 1000); stts.extend(1u32.to_be_bytes()); stts.extend((next - s).to_be_bytes()); } let mut stsz = full(0); stsz.extend(0u32.to_be_bytes()); stsz.extend((samples.len() as u32).to_be_bytes()); for smp in &samples { stsz.extend((smp.len() as u32).to_be_bytes()); } let mut stsc = full(0); stsc.extend(1u32.to_be_bytes()); stsc.extend([1u32, samples.len() as u32, 1].iter().flat_map(|x| x.to_be_bytes())); let mut stco = full(0); stco.extend(1u32.to_be_bytes()); stco.extend((mdat_at + 8).to_be_bytes()); let stbl = bx(b"stbl", &[bx(b"stts", &stts), bx(b"stsz", &stsz), bx(b"stsc", &stsc), bx(b"stco", &stco)].concat()); let text = bx(b"trak", &[tkhd(2), bx(b"mdia", &[mdhd.clone(), hdlr(b"text"), bx(b"minf", &stbl)].concat())].concat()); let audio = bx( b"trak", &[ tkhd(1), bx(b"tref", &bx(b"chap", &2u32.to_be_bytes())), bx(b"mdia", &[mdhd.clone(), hdlr(b"soun")].concat()), ] .concat(), ); let mut f = ftyp(b"M4B "); f.extend(bx(b"moov", &[mvhd(1000, 600_000), audio, text].concat())); f }; let head_len = build(0).len() as u32; let mut f = build(head_len); f.extend(bx(b"mdat", &samples.concat())); f } #[test] fn quicktime_chapter_tracks_are_read() { let f = m4b_with_chapter_track(&["Part One", "Part Two", "Part Three"], &[0, 200_000, 400_000]); let info = timed(|| inspect(&f, Caps::default())).expect("reads"); let titles: Vec<&str> = info.chapters.iter().map(|c| c.title.as_str()).collect(); assert_eq!(titles, ["Part One", "Part Two", "Part Three"]); assert_eq!(info.chapters[1].start_ms, 200_000); assert!(info.chapter_samples.is_empty(), "titles read from the bytes given"); // Given only the metadata (no mdat), the samples come back for the caller to read from the file. let moov_end = f.len() - (8 + "Part One".len() + "Part Two".len() + "Part Three".len() + 6); let meta = inspect(&f[..moov_end], Caps::default()).expect("reads"); assert!(meta.chapters.is_empty()); assert_eq!(meta.chapter_samples.len(), 3); let chapters = liber_audio::container::titles_from_samples(&meta.chapter_samples, 600_000, |o, n| { f.get(o as usize..(o + n as u64) as usize).map(<[u8]>::to_vec) }); assert_eq!(chapters[2].title, "Part Three"); // A chapter track that lies about its sample count is refused. let mut lying = f.clone(); let at = lying.windows(4).position(|w| w == b"stsz").unwrap() + 12; lying[at..at + 4].copy_from_slice(&50_000u32.to_be_bytes()); assert!(matches!(timed(|| inspect(&lying, Caps::default())), Err(AudioError::Damaged(_)))); }