diff --git a/Cargo.lock b/Cargo.lock index bb4509a..1d74832 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7035,6 +7035,7 @@ dependencies = [ "idevice", "jiff", "nusb", + "tempfile", "tokio", "tunal-core", ] @@ -7066,6 +7067,7 @@ dependencies = [ "russh-sftp", "secrecy", "sha1 0.11.0", + "tempfile", "tokio", "tunal-core", "zeroize", @@ -7079,6 +7081,7 @@ dependencies = [ "rtrb", "rubato", "symphonia", + "tempfile", ] [[package]] @@ -7088,6 +7091,7 @@ dependencies = [ "lofty", "serde", "serde_json", + "tempfile", "ureq", ] @@ -7109,6 +7113,7 @@ dependencies = [ "mime_guess", "png", "resvg 0.50.0", + "tempfile", ] [[package]] diff --git a/Plans/12 Testing/S033-tests-media-net-devices.md b/Plans/12 Testing/S033-tests-media-net-devices.md index fc8d08c..38857aa 100644 --- a/Plans/12 Testing/S033-tests-media-net-devices.md +++ b/Plans/12 Testing/S033-tests-media-net-devices.md @@ -10,13 +10,13 @@ Tests for the media, network and device crates with fixtures, a local mock HTTP CLAUDE.md §4 (network tests); the public APIs of these crates. ## Steps -- [ ] Fixtures: tiny audio/video/image files (generated once with ffmpeg, committed, a few KB). -- [ ] thumbs: cache naming/metadata, each generator, ffmpeg-missing path (PATH without ffmpeg). -- [ ] tags: read/write/merge/Keep/cover on each fixture format; MusicBrainz: mock server responses, rate limiter spacing, 503 backoff, track matching. -- [ ] player: decode and waveform buckets on fixtures (no audio device needed). -- [ ] net: ssh config/known_hosts parsing; SFTP against an in-process russh server (temp dir root): auth paths, ops, host-key unknown/mismatch. -- [ ] MTP: container encode/decode and session flows on the replay transport. -- [ ] Fix bugs found (regression test each) or log them in PROGRESS. +- [x] Fixtures: tiny audio/video/image files (generated once with ffmpeg, committed, a few KB). +- [x] thumbs: cache naming/metadata, each generator, ffmpeg-missing path (PATH without ffmpeg). +- [x] tags: read/write/merge/Keep/cover on each fixture format; MusicBrainz: mock server responses, rate limiter spacing, 503 backoff, track matching. +- [x] player: decode and waveform buckets on fixtures (no audio device needed). +- [x] net: ssh config/known_hosts parsing; SFTP against an in-process russh server (temp dir root): auth paths, ops, host-key unknown/mismatch. +- [x] MTP: container encode/decode and session flows on the replay transport. +- [x] Fix bugs found (regression test each) or log them in PROGRESS. - [ ] PROGRESS entry, INDEX line, commit `S033: …` ## End criteria diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 901dadd..2aeb1d3 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -73,7 +73,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v ## 12 Testing - [x] [S032 — Automated tests: core, ops, trash, dirmeta, elevation protocol](12%20Testing/S032-tests-core.md) · Sonnet high -- [ ] [S033 — Automated tests: thumbs, tags, MusicBrainz, player, ssh, SFTP, MTP](12%20Testing/S033-tests-media-net-devices.md) · Sonnet high +- [x] [S033 — Automated tests: thumbs, tags, MusicBrainz, player, ssh, SFTP, MTP](12%20Testing/S033-tests-media-net-devices.md) · Sonnet high - [x] [S034 — Screenshot matrix and UI review](12%20Testing/S034-ui-review.md) · Opus high - [ ] [S035 — Motion audit and visual sign-off](12%20Testing/S035-motion-audit.md) · Opus high 🧑 - [ ] [S036 — Real-world checks with the user](12%20Testing/S036-real-world-checks.md) · Opus high 🧑 diff --git a/crates/tunal-devices/Cargo.toml b/crates/tunal-devices/Cargo.toml index 304a192..f5003eb 100644 --- a/crates/tunal-devices/Cargo.toml +++ b/crates/tunal-devices/Cargo.toml @@ -12,3 +12,6 @@ tunal-core = { path = "../tunal-core" } futures-lite.workspace = true idevice.workspace = true tokio.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/tunal-devices/tests/mtp.rs b/crates/tunal-devices/tests/mtp.rs new file mode 100644 index 0000000..30b2070 --- /dev/null +++ b/crates/tunal-devices/tests/mtp.rs @@ -0,0 +1,821 @@ +//! MTP containers, dataset encoding and session flows on the replay transport. + +use std::io::Cursor; + +#[path = "../examples/common/mod.rs"] +mod common; + +use common::*; +use tunal_devices::mtp::{ + Container, Error, Header, Kind, NewObject, Reader, ReplayTransport, Session, Step, Transport, + Value, Writer, code, format_date, parse_date, +}; + +const CHUNK: usize = 256 * 1024; + +// ------------------------------------------------------------ containers + +#[test] +fn header_round_trip_and_layout() { + let h = Header { + len: 20, + kind: Kind::Command, + code: 0x1002, + tid: 7, + }; + let bytes = h.encode(); + assert_eq!( + bytes, + [20, 0, 0, 0, 1, 0, 0x02, 0x10, 7, 0, 0, 0], + "little endian: length, type, code, transaction" + ); + assert_eq!(Header::decode(&bytes).unwrap(), h); +} + +#[test] +fn header_rejects_short_unknown_and_tiny_lengths() { + assert!(matches!(Header::decode(&[0; 5]), Err(Error::Protocol(_)))); + let mut bad_type = Header { + len: 12, + kind: Kind::Data, + code: 1, + tid: 1, + } + .encode(); + bad_type[4] = 9; + assert!(matches!(Header::decode(&bad_type), Err(Error::Protocol(_)))); + let mut tiny = Header { + len: 12, + kind: Kind::Data, + code: 1, + tid: 1, + } + .encode(); + tiny[0] = 4; + assert!(matches!(Header::decode(&tiny), Err(Error::Protocol(_)))); +} + +#[test] +fn container_round_trip_matches_the_independent_builder() { + let c = Container { + kind: Kind::Command, + code: code::GET_OBJECT_HANDLES, + tid: 3, + params: vec![STORAGE, 0, code::ROOT], + }; + let bytes = c.encode(); + assert_eq!( + bytes, + container( + 1, + code::GET_OBJECT_HANDLES, + 3, + ¶ms_bytes(&[STORAGE, 0, code::ROOT]) + ) + ); + assert_eq!(Container::decode(&bytes).unwrap(), c); + let r = Container::decode(&container(3, code::OK, 3, &[])).unwrap(); + assert_eq!( + (r.kind, r.code, r.params.len()), + (Kind::Response, code::OK, 0) + ); +} + +#[test] +fn container_decode_keeps_five_parameters_and_ignores_trailing_bytes() { + let bytes = container(3, code::OK, 1, ¶ms_bytes(&[1, 2, 3, 4, 5, 6, 7])); + assert_eq!(Container::decode(&bytes).unwrap().params, [1, 2, 3, 4, 5]); + let mut run_on = container(3, code::OK, 1, ¶ms_bytes(&[9])); + run_on.extend(container(3, code::OK, 2, ¶ms_bytes(&[8]))); + assert_eq!(Container::decode(&run_on).unwrap().params, [9]); +} + +// ------------------------------------------------------------ datasets + +#[test] +fn integers_and_arrays_round_trip() { + let mut w = Writer::new(); + w.u8(1) + .u16(0x0203) + .u32(0x04050607) + .u64(0x0809_0A0B_0C0D_0E0F); + assert_eq!( + w.buf, + [ + 1, 3, 2, 7, 6, 5, 4, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 9, 8 + ] + ); + let mut r = Reader::new(&w.buf); + assert_eq!(r.u8().unwrap(), 1); + assert_eq!(r.u16().unwrap(), 0x0203); + assert_eq!(r.u32().unwrap(), 0x04050607); + assert_eq!(r.u64().unwrap(), 0x0809_0A0B_0C0D_0E0F); + assert_eq!(r.remaining(), 0); + assert!(matches!(r.u8(), Err(Error::Protocol(_)))); + + assert_eq!( + Reader::new(&u32s(&[1, 2, 3])).u32_array().unwrap(), + [1, 2, 3] + ); + assert_eq!(Reader::new(&u16s(&[7, 8])).u16_array().unwrap(), [7, 8]); + let huge = 0xFFFF_FFF0u32.to_le_bytes(); + assert!(Reader::new(&huge).u32_array().is_err()); + assert!(Reader::new(&huge).u16_array().is_err()); +} + +#[test] +fn strings_encode_like_the_independent_builder() { + for s in ["", "a", "Music", "Ünïcödé ☃", "😀 emoji"] { + let mut w = Writer::new(); + w.string(s); + assert_eq!(w.buf, ptp_string(s), "{s:?}"); + assert_eq!(Reader::new(&w.buf).string().unwrap(), s); + } + let mut w = Writer::new(); + w.string(""); + assert_eq!(w.buf, [0]); +} + +#[test] +fn long_strings_are_cut_without_splitting_a_surrogate_pair() { + let long = "x".repeat(300); + let mut w = Writer::new(); + w.string(&long); + assert_eq!(w.buf[0], 255, "254 units and the terminator"); + assert_eq!(Reader::new(&w.buf).string().unwrap().len(), 254); + // The emoji's first half would be the 254th unit: both halves go. + let text = format!("{}😀", "y".repeat(253)); + let mut w = Writer::new(); + w.string(&text); + assert_eq!(Reader::new(&w.buf).string().unwrap(), "y".repeat(253)); +} + +#[test] +fn unpaired_surrogates_read_as_the_replacement_character() { + let mut data = vec![3u8]; + data.extend(0xD800u16.to_le_bytes()); + data.extend(0x0041u16.to_le_bytes()); + data.extend(0u16.to_le_bytes()); + assert_eq!(Reader::new(&data).string().unwrap(), "\u{FFFD}A"); +} + +#[test] +fn dates_parse_with_zones_fractions_and_garbage() { + let utc = parse_date("20251201T120000Z").unwrap(); + assert_eq!(utc, parse_date("20251201T130000+0100").unwrap()); + assert_eq!(utc, parse_date("20251201T100000-0200").unwrap()); + assert_eq!(parse_date("20251201T120000.7Z").unwrap(), utc); + assert_eq!( + utc.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(), + 1_764_590_400 + ); + assert!( + parse_date("20251231T235960Z").is_some(), + "leap second is clamped" + ); + for bad in [ + "", + "2025", + "20251201 120000", + "20251301T120000Z", + "20251201T120000X", + "20251201T120000+01", + ] { + assert_eq!(parse_date(bad), None, "{bad:?}"); + } +} + +#[test] +fn local_dates_round_trip_through_format_date() { + let t = parse_date("20240229T235959").unwrap(); + assert_eq!(format_date(t), "20240229T235959"); + let mut w = Writer::new(); + w.date(Some(t)).date(None); + let mut r = Reader::new(&w.buf); + assert_eq!(r.date().unwrap(), Some(t)); + assert_eq!(r.date().unwrap(), None); +} + +#[test] +fn values_of_every_width_widen_to_u128() { + let mut data = vec![0xFE]; + data.extend(0xBEEFu16.to_le_bytes()); + data.extend(0xDEADBEEFu32.to_le_bytes()); + data.extend(u64::MAX.to_le_bytes()); + data.extend(u128::MAX.to_le_bytes()); + let mut r = Reader::new(&data); + assert_eq!(r.value(0x0002).unwrap(), Value::Int(0xFE)); + assert_eq!(r.value(0x0004).unwrap(), Value::Int(0xBEEF)); + assert_eq!(r.value(0x0006).unwrap(), Value::Int(0xDEADBEEF)); + assert_eq!(r.value(0x0008).unwrap(), Value::Int(u64::MAX.into())); + assert_eq!(r.value(0x000A).unwrap(), Value::Int(u128::MAX)); + assert_eq!(Value::Int(5).int(), Some(5)); + assert_eq!(Value::Str("x".into()).int(), None); + assert_eq!(Value::Str("x".into()).str(), Some("x")); +} + +#[test] +fn string_and_array_values_and_bad_types() { + let s = ptp_string("name"); + assert_eq!( + Reader::new(&s).value(0xFFFF).unwrap(), + Value::Str("name".into()) + ); + let mut arr = 3u32.to_le_bytes().to_vec(); + arr.extend([1u8, 2, 3]); + assert_eq!( + Reader::new(&arr).value(0x4002).unwrap(), + Value::Array(vec![1, 2, 3]) + ); + assert!(matches!( + Reader::new(&[0; 8]).value(0x1234), + Err(Error::Protocol(_)) + )); + let huge = 0xFFFF_FFFFu32.to_le_bytes(); + assert!(Reader::new(&huge).value(0x4002).is_err()); +} + +#[test] +fn response_names_and_error_text() { + assert_eq!(code::response_name(0x2009), "invalid object handle"); + assert_eq!(code::response_name(0xA809), "object too large"); + assert_eq!(code::response_name(0x1), "unknown response"); + assert_eq!( + Error::Response(0x200F).to_string(), + "device error: access denied (0x200f)" + ); + assert!(Error::Response(0x2009).is_response(code::INVALID_OBJECT_HANDLE)); + assert!(!Error::Timeout.is_response(code::OK)); +} + +// ------------------------------------------------------------ sessions + +fn opened(script: Script) -> Session { + Session::new(ReplayTransport::new(PACKET, script.steps)) +} + +fn open_script() -> Script { + let mut s = Script::default(); + s.exchange(code::OPEN_SESSION, &[1], None, None, code::OK, &[]); + s.exchange( + code::GET_DEVICE_INFO, + &[], + None, + Some((device_info(), true)), + code::OK, + &[], + ); + s +} + +#[test] +fn open_reads_the_device_info_and_close_ends_the_session() { + let mut script = open_script(); + script.exchange(code::CLOSE_SESSION, &[], None, None, code::OK, &[]); + let mut s = opened(script); + assert!(!s.is_open()); + let info = s.open(1).unwrap().clone(); + assert!(s.is_open()); + assert_eq!(info.manufacturer, "Example Phones"); + assert_eq!(info.model, "Model X"); + assert_eq!(info.device_version, "1.0"); + assert_eq!(info.serial, "SER123"); + assert_eq!(info.standard_version, 100); + assert_eq!(info.vendor_extension_id, 6); + assert_eq!(info.events, [0x4002, 0x4003]); + assert_eq!(info.playback_formats, [0x3000, 0x3001, 0x3009]); + assert!(s.supports(code::GET_PARTIAL_OBJECT_64)); + assert!(!s.supports(0x1010)); + assert_eq!(s.info().unwrap().model, "Model X"); + s.close().unwrap(); + assert!(!s.is_open()); + s.close().unwrap(); // closing twice sends nothing + assert!(s.into_transport().finished()); +} + +#[test] +fn an_already_open_session_is_taken_over() { + let mut script = Script::default(); + script.exchange( + code::OPEN_SESSION, + &[1], + None, + None, + code::SESSION_ALREADY_OPEN, + &[], + ); + script.exchange( + code::GET_DEVICE_INFO, + &[], + None, + Some((device_info(), true)), + code::OK, + &[], + ); + let mut s = opened(script); + s.open(1).unwrap(); + assert!(s.is_open()); +} + +#[test] +fn open_fails_on_another_response() { + let mut script = Script::default(); + script.exchange(code::OPEN_SESSION, &[1], None, None, 0x2019, &[]); + let mut s = opened(script); + assert_eq!(s.open(1).unwrap_err(), Error::Response(0x2019)); + assert!(!s.is_open()); +} + +#[test] +fn storages_and_folder_listing() { + let mut script = open_script(); + script.exchange( + code::GET_STORAGE_IDS, + &[], + None, + Some((u32s(&[STORAGE]), true)), + code::OK, + &[], + ); + script.exchange( + code::GET_STORAGE_INFO, + &[STORAGE], + None, + Some((storage_info(), true)), + code::OK, + &[], + ); + script.exchange( + code::GET_OBJECT_HANDLES, + &[STORAGE, 0, code::ROOT], + None, + Some((u32s(&[1, 2]), true)), + code::OK, + &[], + ); + script.exchange( + code::GET_OBJECT_INFO, + &[1], + None, + Some((object_info(0x3001, 0, 0, "Music", ""), true)), + code::OK, + &[], + ); + script.exchange( + code::GET_OBJECT_INFO, + &[2], + None, + Some(( + object_info(0x3000, 1234, 0, "notes.txt", "20260115T093000Z"), + true, + )), + code::OK, + &[], + ); + let mut s = opened(script); + s.open(1).unwrap(); + assert_eq!(s.storage_ids().unwrap(), [STORAGE]); + let st = s.storage_info(STORAGE).unwrap(); + assert_eq!(st.description, "Internal shared storage"); + assert_eq!(st.volume_label, ""); + assert_eq!(st.max_capacity, 64_000_000_000); + assert_eq!(st.free_space, 12_345_678_901); + assert_eq!(st.storage_type, 3); + let objects = s.list(STORAGE, code::ROOT).unwrap(); + assert_eq!(objects.len(), 2); + assert!(objects[0].is_folder()); + assert_eq!(objects[0].name, "Music"); + assert_eq!(objects[0].parent, code::ROOT, "parent 0 means the top"); + assert!(!objects[1].is_folder()); + assert_eq!( + (objects[1].name.as_str(), objects[1].size), + ("notes.txt", 1234) + ); + assert_eq!(objects[1].modified, parse_date("20260115T093000Z")); + assert!(s.into_transport().finished()); +} + +fn entry(handle: u32, code: u16, ty: u16, value: Vec) -> Vec { + let mut e = handle.to_le_bytes().to_vec(); + e.extend(code.to_le_bytes()); + e.extend(ty.to_le_bytes()); + e.extend(value); + e +} + +#[test] +fn folder_listing_uses_one_property_list() { + let mut entries = Vec::new(); + for (handle, name, size) in [ + (3u32, "song.mp3", 5_000_000_000u64), + (4, "cover.jpg", 48_213), + ] { + entries.push(entry( + handle, + 0xDC01, + 0x0006, + STORAGE.to_le_bytes().to_vec(), + )); + entries.push(entry( + handle, + 0xDC02, + 0x0004, + 0x3009u16.to_le_bytes().to_vec(), + )); + entries.push(entry(handle, 0xDC04, 0x0008, size.to_le_bytes().to_vec())); + entries.push(entry(handle, 0xDC07, 0xFFFF, ptp_string(name))); + entries.push(entry( + handle, + 0xDC09, + 0xFFFF, + ptp_string("20251201T120000Z"), + )); + entries.push(entry(handle, 0xDC0B, 0x0006, 1u32.to_le_bytes().to_vec())); + } + let mut list = (entries.len() as u32).to_le_bytes().to_vec(); + for e in entries { + list.extend(e); + } + let mut script = open_script(); + script.exchange( + code::GET_OBJECT_HANDLES, + &[STORAGE, 0, 1], + None, + Some((u32s(&[3, 4]), true)), + code::OK, + &[], + ); + script.exchange( + code::GET_OBJECT_PROP_LIST, + &[1, 0, code::ALL, 0, 1], + None, + Some((list, true)), + code::OK, + &[], + ); + let mut s = opened(script); + s.open(1).unwrap(); + let objects = s.list(STORAGE, 1).unwrap(); + assert_eq!(objects.len(), 2); + assert_eq!(objects[0].name, "song.mp3"); + assert_eq!(objects[0].size, 5_000_000_000, "64-bit sizes survive"); + assert_eq!(objects[0].parent, 1); + assert_eq!(objects[1].name, "cover.jpg"); + assert_eq!(objects[1].format, 0x3009); + assert!(s.into_transport().finished()); +} + +#[test] +fn property_list_refusal_falls_back_to_object_info() { + let mut script = open_script(); + script.exchange( + code::GET_OBJECT_HANDLES, + &[STORAGE, 0, 1], + None, + Some((u32s(&[3]), true)), + code::OK, + &[], + ); + script.exchange( + code::GET_OBJECT_PROP_LIST, + &[1, 0, code::ALL, 0, 1], + None, + None, + 0x2005, + &[], + ); + script.exchange( + code::GET_OBJECT_INFO, + &[3], + None, + Some((object_info(0x3000, 10, 1, "a.bin", ""), true)), + code::OK, + &[], + ); + let mut s = opened(script); + s.open(1).unwrap(); + assert_eq!(s.list(STORAGE, 1).unwrap()[0].name, "a.bin"); + assert!(s.into_transport().finished()); +} + +#[test] +fn an_object_of_4_gib_or_more_asks_for_its_64_bit_size() { + let mut script = open_script(); + script.exchange( + code::GET_OBJECT_INFO, + &[9], + None, + Some((object_info(0x3000, u32::MAX, 1, "huge.mkv", ""), true)), + code::OK, + &[], + ); + script.exchange( + code::GET_OBJECT_PROP_VALUE, + &[9, 0xDC04], + None, + Some((6_000_000_000u64.to_le_bytes().to_vec(), true)), + code::OK, + &[], + ); + let mut s = opened(script); + s.open(1).unwrap(); + assert_eq!(s.object(9).unwrap().size, 6_000_000_000); +} + +#[test] +fn downloads_stream_in_chunks_and_a_partial_read_returns_the_range() { + // Exactly two bulk chunks: its zero-length packet arrives alone. + let song = pattern(2 * CHUNK - 12, 7); + let mut script = open_script(); + script.exchange( + code::GET_OBJECT, + &[3], + None, + Some((song.clone(), true)), + code::OK, + &[], + ); + script.exchange( + code::GET_PARTIAL_OBJECT_64, + &[3, 1000, 0, 100], + None, + Some((song[1000..1100].to_vec(), true)), + code::OK, + &[], + ); + // A device that leaves out the zero-length packet after an aligned data phase. + let aligned = pattern(PACKET - 12, 5); + script.exchange( + code::GET_OBJECT, + &[4], + None, + Some((aligned.clone(), false)), + code::OK, + &[], + ); + let mut s = opened(script); + s.open(1).unwrap(); + let mut got = Vec::new(); + s.get_object(3, &mut got).unwrap(); + assert_eq!(got, song); + let mut range = Vec::new(); + assert_eq!(s.get_partial_object(3, 1000, 100, &mut range).unwrap(), 100); + assert_eq!(range, song[1000..1100]); + let mut got = Vec::new(); + s.get_object(4, &mut got).unwrap(); + assert_eq!(got, aligned); + assert!(s.into_transport().finished()); +} + +#[test] +fn a_failing_sink_drains_the_phase_and_keeps_the_session_in_step() { + struct Broken; + impl std::io::Write for Broken { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::other("disk full")) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let song = pattern(2 * CHUNK + 100, 3); + let mut script = open_script(); + script.exchange( + code::GET_OBJECT, + &[3], + None, + Some((song, true)), + code::OK, + &[], + ); + script.exchange(code::DELETE_OBJECT, &[3, 0], None, None, code::OK, &[]); + let mut s = opened(script); + s.open(1).unwrap(); + assert_eq!( + s.get_object(3, &mut Broken).unwrap_err(), + Error::Io("disk full".into()) + ); + s.delete_object(3).unwrap(); + assert!(s.into_transport().finished()); +} + +#[test] +fn upload_rename_move_copy_delete_and_a_device_error() { + // Packet-aligned payload: the host must send a zero-length packet after it. + let upload = pattern(600 * PACKET - 12, 13); + let mut script = open_script(); + script.exchange( + code::SEND_OBJECT_INFO, + &[STORAGE, 1], + Some(new_object_info("upload.bin", upload.len() as u32, 1, false)), + None, + code::OK, + &[STORAGE, 1, 5], + ); + script.exchange( + code::SEND_OBJECT, + &[], + Some(upload.clone()), + None, + code::OK, + &[], + ); + script.exchange( + code::SET_OBJECT_PROP_VALUE, + &[5, 0xDC07], + Some(ptp_string("renamed.bin")), + None, + code::OK, + &[], + ); + script.exchange( + code::MOVE_OBJECT, + &[2, STORAGE, 1], + None, + None, + code::OK, + &[], + ); + script.exchange( + code::COPY_OBJECT, + &[2, STORAGE, 0], + None, + None, + code::OK, + &[6], + ); + script.exchange(code::DELETE_OBJECT, &[99, 0], None, None, 0x2009, &[]); + script.exchange(code::DELETE_OBJECT, &[6, 0], None, None, code::OK, &[]); + let mut s = opened(script); + s.open(1).unwrap(); + let new = NewObject { + name: "upload.bin".into(), + size: upload.len() as u64, + modified: None, + folder: false, + }; + let (storage, parent, handle) = s.send_object_info(STORAGE, 1, &new).unwrap(); + assert_eq!((storage, parent, handle), (STORAGE, 1, 5)); + s.send_object(&mut Cursor::new(upload.clone()), upload.len() as u64) + .unwrap(); + s.rename(handle, "renamed.bin").unwrap(); + s.move_object(2, STORAGE, 1).unwrap(); + assert_eq!(s.copy_object(2, STORAGE, code::ROOT).unwrap(), 6); + let err = s.delete_object(99).unwrap_err(); + assert_eq!(err, Error::Response(code::INVALID_OBJECT_HANDLE)); + s.delete_object(6).unwrap(); + assert!(s.into_transport().finished()); +} + +#[test] +fn a_file_shorter_than_its_declared_size_is_an_io_error() { + let mut script = open_script(); + script.exchange( + code::SEND_OBJECT_INFO, + &[STORAGE, 1], + Some(new_object_info("short.bin", 100, 1, false)), + None, + code::OK, + &[STORAGE, 1, 5], + ); + script + .steps + .push(Step::Out(container(1, code::SEND_OBJECT, 3, &[]))); + let mut s = opened(script); + s.open(1).unwrap(); + let new = NewObject { + name: "short.bin".into(), + size: 100, + modified: None, + folder: false, + }; + s.send_object_info(STORAGE, 1, &new).unwrap(); + let err = s + .send_object(&mut Cursor::new(vec![0u8; 10]), 100) + .unwrap_err(); + assert_eq!(err, Error::Io("file ended before its size".into())); +} + +#[test] +fn creating_a_folder_sends_an_association() { + let mut script = open_script(); + script.exchange( + code::SEND_OBJECT_INFO, + &[STORAGE, 1], + Some(new_object_info("New folder", 0, 1, true)), + None, + code::OK, + &[STORAGE, 1, 8], + ); + let mut s = opened(script); + s.open(1).unwrap(); + let new = NewObject { + name: "New folder".into(), + size: 0, + modified: None, + folder: true, + }; + assert_eq!(s.send_object_info(STORAGE, 1, &new).unwrap().2, 8); + assert!(s.into_transport().finished()); +} + +#[test] +fn protocol_violations_are_reported() { + // A response for the wrong transaction. + let mut script = Script::default(); + script.steps.push(Step::Out(container( + 1, + code::OPEN_SESSION, + 0, + ¶ms_bytes(&[1]), + ))); + script.steps.push(Step::In { + data: container(3, code::OK, 5, &[]), + zlp: true, + }); + assert!(matches!(opened(script).open(1), Err(Error::Protocol(m)) if m.contains("transaction"))); + + // An event where a response belongs. + let mut script = Script::default(); + script.steps.push(Step::Out(container( + 1, + code::OPEN_SESSION, + 0, + ¶ms_bytes(&[1]), + ))); + script.steps.push(Step::In { + data: container(4, code::OK, 0, &[]), + zlp: true, + }); + assert!(matches!(opened(script).open(1), Err(Error::Protocol(m)) if m.contains("response"))); + + // Data for another transaction. + let mut script = open_script(); + script + .steps + .push(Step::Out(container(1, code::GET_STORAGE_IDS, 2, &[]))); + script.steps.push(Step::In { + data: container(2, code::GET_STORAGE_IDS, 9, &u32s(&[1])), + zlp: true, + }); + let mut s = opened(script); + s.open(1).unwrap(); + assert!( + matches!(s.storage_ids(), Err(Error::Protocol(m)) if m.contains("data for transaction")) + ); + + // A data phase cut short. + let mut script = open_script(); + script + .steps + .push(Step::Out(container(1, code::GET_STORAGE_IDS, 2, &[]))); + let mut cut = container(2, code::GET_STORAGE_IDS, 2, &u32s(&[1, 2, 3])); + let declared = cut.len() as u32 + 100; + cut[..4].copy_from_slice(&declared.to_le_bytes()); + script.steps.push(Step::In { + data: cut, + zlp: true, + }); + let mut s = opened(script); + s.open(1).unwrap(); + assert!(s.storage_ids().is_err()); +} + +#[test] +fn a_dataset_that_ends_early_is_a_protocol_error() { + let mut script = open_script(); + script.exchange( + code::GET_STORAGE_INFO, + &[STORAGE], + None, + Some((vec![1, 2, 3], true)), + code::OK, + &[], + ); + let mut s = opened(script); + s.open(1).unwrap(); + assert!(matches!(s.storage_info(STORAGE), Err(Error::Protocol(_)))); +} + +#[test] +fn replay_transport_rejects_a_host_that_deviates() { + let mut t = ReplayTransport::new( + PACKET, + vec![Step::Out(vec![12, 0, 0, 0, 1, 0, 2, 16, 0, 0, 0, 0])], + ); + assert_eq!(t.max_packet_size(), PACKET); + let wrong = [12, 0, 0, 0, 1, 0, 3, 16, 0, 0, 0, 0]; + assert!(matches!(t.send(&wrong), Err(Error::Protocol(m)) if m.contains("first difference"))); + let mut t = ReplayTransport::new(PACKET, vec![]); + assert!(t.receive(PACKET).is_err()); + let mut t = ReplayTransport::new( + PACKET, + vec![Step::In { + data: vec![0; 20], + zlp: false, + }], + ); + assert!(t.receive(100).is_err()); + assert_eq!(t.receive(PACKET).unwrap().len(), 20); + assert!(t.finished()); +} diff --git a/crates/tunal-net/Cargo.toml b/crates/tunal-net/Cargo.toml index 8e68fb1..fd243ab 100644 --- a/crates/tunal-net/Cargo.toml +++ b/crates/tunal-net/Cargo.toml @@ -15,3 +15,6 @@ russh.workspace = true russh-sftp.workspace = true secrecy.workspace = true zeroize.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/tunal-net/src/auth.rs b/crates/tunal-net/src/auth.rs index 28b05e3..003f72f 100644 --- a/crates/tunal-net/src/auth.rs +++ b/crates/tunal-net/src/auth.rs @@ -244,15 +244,18 @@ async fn try_key_file( prompts: &Arc, ) -> bool { let mut key = keys::load_secret_key(file, None); - for _ in 0..MAX_TRIES { - if !matches!(key, Err(keys::Error::KeyIsEncrypted)) { - break; + if matches!(key, Err(keys::Error::KeyIsEncrypted)) { + // A wrong passphrase fails with another error, so ask again until the tries run out. + for _ in 0..MAX_TRIES { + let path = file.to_path_buf(); + let Some(Some(pass)) = ask(prompts, move |p| p.passphrase(&path)).await else { + return false; + }; + key = keys::load_secret_key(file, Some(pass.expose_secret())); + if key.is_ok() { + break; + } } - let path = file.to_path_buf(); - let Some(Some(pass)) = ask(prompts, move |p| p.passphrase(&path)).await else { - return false; - }; - key = keys::load_secret_key(file, Some(pass.expose_secret())); } let Ok(key) = key else { return false }; let key = PrivateKeyWithHashAlg::new(Arc::new(key), rsa_hash); diff --git a/crates/tunal-net/tests/fixtures/k_client b/crates/tunal-net/tests/fixtures/k_client new file mode 100644 index 0000000..35e6406 --- /dev/null +++ b/crates/tunal-net/tests/fixtures/k_client @@ -0,0 +1,7 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACAIUJUDpBnhv3HZDGySlqUtt/OUsRiSgvxIwaKciaTUtwAAAJBqOoSQajqE +kAAAAAtzc2gtZWQyNTUxOQAAACAIUJUDpBnhv3HZDGySlqUtt/OUsRiSgvxIwaKciaTUtw +AAAEDi6ige/QiPiEhNEntkBC3xdk8MEoLkVFtnMkBakVY3uQhQlQOkGeG/cdkMbJKWpS23 +85SxGJKC/EjBopyJpNS3AAAACXRlc3Qtb25seQECAwQ= +-----END OPENSSH PRIVATE KEY----- diff --git a/crates/tunal-net/tests/fixtures/k_client.pub b/crates/tunal-net/tests/fixtures/k_client.pub new file mode 100644 index 0000000..cfecd5d --- /dev/null +++ b/crates/tunal-net/tests/fixtures/k_client.pub @@ -0,0 +1 @@ +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAhQlQOkGeG/cdkMbJKWpS2385SxGJKC/EjBopyJpNS3 test-only diff --git a/crates/tunal-net/tests/fixtures/k_enc b/crates/tunal-net/tests/fixtures/k_enc new file mode 100644 index 0000000..330f4a1 --- /dev/null +++ b/crates/tunal-net/tests/fixtures/k_enc @@ -0,0 +1,8 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAk/KyEk0 +Z4/7ecql6tk3njAAAAIAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIOSb4Zt2jzQ1+oNI +lt6bXE84reFx8Qy2fKvTUub4eZHqAAAAkI5GsWt7EMI2fK5JYttMqUMjakjIjQNI7ayonx +cSPMp1RYv0Q6+gR5SZuvVHV2YD/BSmIOMCQ2XaPQq4InmY3uC1Ypa4RZpE/sleSYAaAcLB +DKhdoX5oPSC9XYn5JigIFy8g1wyBUdPElJtKRnyG+nCcGcuRCjFVBQE8EH6f45JPyNqbXN +GfIKJMApPB95MUbA== +-----END OPENSSH PRIVATE KEY----- diff --git a/crates/tunal-net/tests/fixtures/k_enc.pub b/crates/tunal-net/tests/fixtures/k_enc.pub new file mode 100644 index 0000000..ad3c10f --- /dev/null +++ b/crates/tunal-net/tests/fixtures/k_enc.pub @@ -0,0 +1 @@ +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOSb4Zt2jzQ1+oNIlt6bXE84reFx8Qy2fKvTUub4eZHq test-only diff --git a/crates/tunal-net/tests/fixtures/k_host b/crates/tunal-net/tests/fixtures/k_host new file mode 100644 index 0000000..b30c2aa --- /dev/null +++ b/crates/tunal-net/tests/fixtures/k_host @@ -0,0 +1,7 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACDpEVtoDUPPXZK1IQXKi89KSIYG+jUkvQJOEWR3nmavMAAAAJDeqIaq3qiG +qgAAAAtzc2gtZWQyNTUxOQAAACDpEVtoDUPPXZK1IQXKi89KSIYG+jUkvQJOEWR3nmavMA +AAAED3urR0BaAmZzUI2paSGq9oj6e45rjzMWl70shv7lGS/+kRW2gNQ89dkrUhBcqLz0pI +hgb6NSS9Ak4RZHeeZq8wAAAACXRlc3Qtb25seQECAwQ= +-----END OPENSSH PRIVATE KEY----- diff --git a/crates/tunal-net/tests/fixtures/k_host.pub b/crates/tunal-net/tests/fixtures/k_host.pub new file mode 100644 index 0000000..9ad4fe5 --- /dev/null +++ b/crates/tunal-net/tests/fixtures/k_host.pub @@ -0,0 +1 @@ +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOkRW2gNQ89dkrUhBcqLz0pIhgb6NSS9Ak4RZHeeZq8w test-only diff --git a/crates/tunal-net/tests/fixtures/k_host2 b/crates/tunal-net/tests/fixtures/k_host2 new file mode 100644 index 0000000..b2b1048 --- /dev/null +++ b/crates/tunal-net/tests/fixtures/k_host2 @@ -0,0 +1,7 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACBWBUVJ2QsTRdKayGye82iSEZLbQFku7cmlOfwYfDl4CwAAAJBySsXKckrF +ygAAAAtzc2gtZWQyNTUxOQAAACBWBUVJ2QsTRdKayGye82iSEZLbQFku7cmlOfwYfDl4Cw +AAAECxLDlB1EB8hK/3ast2Ejv2m8ubmaJD/oAZiM+7SBnmaFYFRUnZCxNF0prIbJ7zaJIR +kttAWS7tyaU5/Bh8OXgLAAAACXRlc3Qtb25seQECAwQ= +-----END OPENSSH PRIVATE KEY----- diff --git a/crates/tunal-net/tests/fixtures/k_host2.pub b/crates/tunal-net/tests/fixtures/k_host2.pub new file mode 100644 index 0000000..a37b528 --- /dev/null +++ b/crates/tunal-net/tests/fixtures/k_host2.pub @@ -0,0 +1 @@ +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFYFRUnZCxNF0prIbJ7zaJIRkttAWS7tyaU5/Bh8OXgL test-only diff --git a/crates/tunal-net/tests/parsers.rs b/crates/tunal-net/tests/parsers.rs new file mode 100644 index 0000000..ef79a75 --- /dev/null +++ b/crates/tunal-net/tests/parsers.rs @@ -0,0 +1,432 @@ +//! ssh config and known_hosts parsing. `HOME` and `XDG_CONFIG_HOME` are process-global, so the +//! tests that touch them hold one lock. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, MutexGuard}; + +use base64::Engine; +use base64::engine::general_purpose::STANDARD; +use hmac::{Hmac, KeyInit, Mac}; +use sha1::Sha1; +use tunal_net::known_hosts::{HostCheck, KnownHosts, accept_key, own_file}; +use tunal_net::ssh_config::SshConfig; + +static ENV: Mutex<()> = Mutex::new(()); + +fn env_lock() -> MutexGuard<'static, ()> { + ENV.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn parse(text: &str) -> SshConfig { + SshConfig::parse(text, Path::new("/nonexistent-ssh-dir")) +} + +#[test] +fn hosts_lists_concrete_aliases_once_in_file_order() { + let c = parse( + "Host b a\n HostName x\nHost *\n User u\nHost a c !d e*\n Port 1\nHost ?x\nHost !neg\n", + ); + assert_eq!(c.hosts(), ["b", "a", "c"]); +} + +#[test] +fn resolve_first_value_wins_and_lists_collect() { + let c = parse( + "Host web\n HostName web.example.com\n User alice\n Port 2222\n IdentityFile /k/one\n\n\ + Host *\n User bob\n Port 22\n HostName never\n IdentityFile /k/two\n IdentityFile /k/one\n IdentitiesOnly yes\n", + ); + let r = c.resolve("web"); + assert_eq!(r.alias, "web"); + assert_eq!(r.host_name, "web.example.com"); + assert_eq!(r.user.as_deref(), Some("alice")); + assert_eq!(r.port, 2222); + assert_eq!( + r.identity_files, + [PathBuf::from("/k/one"), PathBuf::from("/k/two")] + ); + assert!(r.identities_only); + assert!(!r.unsupported_proxy); + + // Another alias only gets the wildcard block. + let other = c.resolve("other"); + assert_eq!(other.host_name, "never"); + assert_eq!(other.user.as_deref(), Some("bob")); +} + +#[test] +fn unknown_host_resolves_to_itself_with_defaults() { + let r = parse("").resolve("somewhere"); + assert_eq!(r.host_name, "somewhere"); + assert_eq!(r.port, 22); + assert_eq!(r.user, None); + assert!(r.identity_files.is_empty()); + assert!(!r.identities_only); +} + +#[test] +fn syntax_variants_are_understood() { + let c = parse( + "# comment\n\nHOST q\n hostname=q.example.com\n PORT = 2200\n User \"quoted user\"\n IdentityFile \"/path with space/key\" # trailing\n IdentitiesOnly no\n", + ); + let r = c.resolve("q"); + assert_eq!(r.host_name, "q.example.com"); + assert_eq!(r.port, 2200); + assert_eq!(r.user.as_deref(), Some("quoted user")); + assert_eq!(r.identity_files, [PathBuf::from("/path with space/key")]); + assert!(!r.identities_only); +} + +#[test] +fn bad_values_are_ignored() { + let r = parse("Host x\n Port notaport\n IdentitiesOnly maybe\n User\n").resolve("x"); + assert_eq!(r.port, 22); + assert!(!r.identities_only); + assert_eq!(r.user, None); +} + +#[test] +fn percent_h_in_host_name_is_the_alias() { + let r = parse("Host box\n HostName %h.lan\n").resolve("box"); + assert_eq!(r.host_name, "box.lan"); +} + +#[test] +fn global_options_before_the_first_host_apply_to_all() { + let c = parse("User everyone\nHost a\n Port 5\n"); + assert_eq!(c.resolve("a").user.as_deref(), Some("everyone")); + assert_eq!(c.resolve("zzz").user.as_deref(), Some("everyone")); + assert_eq!(c.hosts(), ["a"]); +} + +#[test] +fn negated_pattern_excludes_a_host() { + let c = parse("Host * !secret\n User open\n"); + assert_eq!(c.resolve("a").user.as_deref(), Some("open")); + assert_eq!(c.resolve("secret").user, None); +} + +#[test] +fn proxy_options_mark_the_host_unsupported() { + let c = parse( + "Host jumped\n ProxyJump bastion\nHost cmd\n ProxyCommand nc %h %p\nHost direct\n ProxyJump none\n", + ); + assert!(c.resolve("jumped").unsupported_proxy); + assert!(c.resolve("cmd").unsupported_proxy); + assert!(!c.resolve("direct").unsupported_proxy); +} + +#[test] +fn match_blocks_are_skipped() { + let c = parse("Host a\n User one\nMatch host b\n User two\n Port 9\nHost c\n User three\n"); + assert_eq!(c.resolve("a").user.as_deref(), Some("one")); + assert_eq!(c.resolve("b").user, None); + assert_eq!(c.resolve("b").port, 22); + assert_eq!(c.resolve("c").user.as_deref(), Some("three")); +} + +#[test] +fn include_reads_files_globs_and_relative_paths_sorted() { + let dir = tempfile::tempdir().unwrap(); + let ssh = dir.path(); + fs::create_dir(ssh.join("conf.d")).unwrap(); + fs::write(ssh.join("conf.d/20-b.conf"), "Host b\n User bee\n").unwrap(); + fs::write(ssh.join("conf.d/10-a.conf"), "Host a\n User aye\n").unwrap(); + fs::write(ssh.join("conf.d/skip.txt"), "Host skipped\n").unwrap(); + fs::write(ssh.join("extra"), "Host e\n User eee\n").unwrap(); + fs::write( + ssh.join("config"), + "Include conf.d/*.conf\nInclude extra\nInclude missing\nHost last\n User l\n", + ) + .unwrap(); + let c = SshConfig::load(&ssh.join("config"), ssh); + assert_eq!(c.hosts(), ["a", "b", "e", "last"]); + assert_eq!(c.resolve("b").user.as_deref(), Some("bee")); +} + +#[test] +fn include_loops_stop() { + let dir = tempfile::tempdir().unwrap(); + let ssh = dir.path(); + fs::write(ssh.join("config"), "Include config\nHost loop\n User x\n").unwrap(); + let c = SshConfig::load(&ssh.join("config"), ssh); + assert!(c.hosts().contains(&"loop".to_owned())); +} + +#[test] +fn include_inside_a_match_block_is_skipped() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join("inner"), "Host inner\n").unwrap(); + let c = SshConfig::parse("Match all\n Include inner\n", dir.path()); + assert!(c.hosts().is_empty()); +} + +#[test] +fn missing_and_binary_files_give_an_empty_or_lossy_config() { + let dir = tempfile::tempdir().unwrap(); + assert!( + SshConfig::load(&dir.path().join("none"), dir.path()) + .hosts() + .is_empty() + ); + fs::write(dir.path().join("bin"), b"Host ok\n User \xff\xfe\n").unwrap(); + let c = SshConfig::load(&dir.path().join("bin"), dir.path()); + assert_eq!(c.hosts(), ["ok"]); +} + +#[test] +fn tilde_in_identity_files_uses_home() { + let _lock = env_lock(); + unsafe { std::env::set_var("HOME", "/home/tester") }; + let r = parse("Host h\n IdentityFile ~/.ssh/id_x\n").resolve("h"); + assert_eq!(r.identity_files, [PathBuf::from("/home/tester/.ssh/id_x")]); + assert_eq!( + tunal_net::ssh_config::ssh_dir(), + Some(PathBuf::from("/home/tester/.ssh")) + ); +} + +// known_hosts + +const KEY_A: &str = "AAAAC3NzaC1lZDI1NTE5AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; +const KEY_B: &str = "AAAAC3NzaC1lZDI1NTE5AAAAIBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; +const KEY_RSA: &str = "AAAAB3NzaC1yc2EAAAADAQABAAABgQCCCC"; + +fn hosts(text: &str) -> KnownHosts { + let mut k = KnownHosts::default(); + k.add_text(text); + k +} + +#[test] +fn plain_entries_match_exactly_and_on_the_default_port() { + let k = hosts(&format!("example.com,alias ssh-ed25519 {KEY_A}\n")); + assert_eq!( + k.check("example.com", 22, "ssh-ed25519", KEY_A), + HostCheck::Match + ); + assert_eq!( + k.check("EXAMPLE.com", 22, "ssh-ed25519", KEY_A), + HostCheck::Match + ); + assert_eq!(k.check("alias", 22, "ssh-ed25519", KEY_A), HostCheck::Match); + // Another port is another host. + assert_eq!( + k.check("example.com", 2222, "ssh-ed25519", KEY_A), + HostCheck::Unknown + ); + assert_eq!( + k.check("other.com", 22, "ssh-ed25519", KEY_A), + HostCheck::Unknown + ); +} + +#[test] +fn bracketed_port_entries() { + let k = hosts(&format!( + "[example.com]:2222 ssh-ed25519 {KEY_A}\n[example.com]:22 ssh-ed25519 {KEY_B}\n" + )); + assert_eq!( + k.check("example.com", 2222, "ssh-ed25519", KEY_A), + HostCheck::Match + ); + assert_eq!( + k.check("example.com", 2222, "ssh-ed25519", KEY_B), + HostCheck::Mismatch + ); + assert_eq!( + k.check("example.com", 22, "ssh-ed25519", KEY_B), + HostCheck::Match + ); +} + +#[test] +fn a_different_key_of_the_same_type_is_a_mismatch_other_types_are_unknown() { + let k = hosts(&format!("h ssh-ed25519 {KEY_A}\n")); + assert_eq!(k.check("h", 22, "ssh-ed25519", KEY_B), HostCheck::Mismatch); + assert_eq!(k.check("h", 22, "ssh-rsa", KEY_RSA), HostCheck::Unknown); + // A second key of the type on file makes the first one match. + let k = hosts(&format!("h ssh-ed25519 {KEY_A}\nh ssh-ed25519 {KEY_B}\n")); + assert_eq!(k.check("h", 22, "ssh-ed25519", KEY_B), HostCheck::Match); +} + +#[test] +fn wildcards_and_negation_in_host_lists() { + let k = hosts(&format!("*.lan,!bad.lan ssh-ed25519 {KEY_A}\n")); + assert_eq!( + k.check("box.lan", 22, "ssh-ed25519", KEY_A), + HostCheck::Match + ); + assert_eq!( + k.check("bad.lan", 22, "ssh-ed25519", KEY_A), + HostCheck::Unknown + ); + assert_eq!( + k.check("box.com", 22, "ssh-ed25519", KEY_A), + HostCheck::Unknown + ); +} + +#[test] +fn revoked_keys() { + let k = hosts(&format!( + "@revoked h ssh-ed25519 {KEY_A}\nh ssh-ed25519 {KEY_B}\n" + )); + assert_eq!(k.check("h", 22, "ssh-ed25519", KEY_A), HostCheck::Revoked); + assert_eq!(k.check("h", 22, "ssh-ed25519", KEY_B), HostCheck::Match); + // A revoked entry never makes another key a mismatch. + let k = hosts(&format!("@revoked h ssh-ed25519 {KEY_A}\n")); + assert_eq!(k.check("h", 22, "ssh-ed25519", KEY_B), HostCheck::Unknown); +} + +#[test] +fn comments_blanks_cas_and_garbage_are_ignored() { + let k = hosts(&format!( + "# note\n\n@cert-authority *.x ssh-ed25519 {KEY_A}\n@weird h ssh-ed25519 {KEY_A}\nonlytwo ssh-ed25519\n|1|notbase64|alsonot ssh-ed25519 {KEY_A}\n h ssh-ed25519 {KEY_A} trailing comment\n" + )); + assert_eq!(k.check("h", 22, "ssh-ed25519", KEY_A), HostCheck::Match); + assert_eq!(k.check("a.x", 22, "ssh-ed25519", KEY_A), HostCheck::Unknown); +} + +fn hashed(host: &str) -> String { + let salt = b"0123456789abcdefghij"; + let mut mac = Hmac::::new_from_slice(salt).unwrap(); + mac.update(host.as_bytes()); + format!( + "|1|{}|{}", + STANDARD.encode(salt), + STANDARD.encode(mac.finalize().into_bytes()) + ) +} + +#[test] +fn hashed_entries() { + let k = hosts(&format!( + "{} ssh-ed25519 {KEY_A}\n{} ssh-ed25519 {KEY_B}\n", + hashed("secret.example"), + hashed("[secret.example]:2200") + )); + assert_eq!( + k.check("secret.example", 22, "ssh-ed25519", KEY_A), + HostCheck::Match + ); + assert_eq!( + k.check("Secret.Example", 22, "ssh-ed25519", KEY_A), + HostCheck::Match + ); + assert_eq!( + k.check("secret.example", 22, "ssh-ed25519", KEY_B), + HostCheck::Mismatch + ); + assert_eq!( + k.check("secret.example", 2200, "ssh-ed25519", KEY_B), + HostCheck::Match + ); + assert_eq!( + k.check("public.example", 22, "ssh-ed25519", KEY_A), + HostCheck::Unknown + ); +} + +#[test] +fn files_are_read_and_a_missing_one_is_empty() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("kh"); + fs::write(&file, format!("h ssh-ed25519 {KEY_A}\n")).unwrap(); + let mut k = KnownHosts::default(); + k.add_file(&dir.path().join("missing")); + assert_eq!(k.check("h", 22, "ssh-ed25519", KEY_A), HostCheck::Unknown); + k.add_file(&file); + assert_eq!(k.check("h", 22, "ssh-ed25519", KEY_A), HostCheck::Match); +} + +#[test] +fn accept_key_appends_to_our_own_file_in_the_right_form() { + let _lock = env_lock(); + let dir = tempfile::tempdir().unwrap(); + unsafe { std::env::set_var("HOME", dir.path().join("home")) }; + let file = dir.path().join("cfg/tunal/known_hosts"); + accept_key(&file, "Example.com", 22, "ssh-ed25519", KEY_A).unwrap(); + accept_key(&file, "example.com", 2222, "ssh-ed25519", KEY_B).unwrap(); + let text = fs::read_to_string(&file).unwrap(); + assert_eq!( + text, + format!("example.com ssh-ed25519 {KEY_A}\n[example.com]:2222 ssh-ed25519 {KEY_B}\n") + ); + let mut k = KnownHosts::default(); + k.add_file(&file); + assert_eq!( + k.check("example.com", 22, "ssh-ed25519", KEY_A), + HostCheck::Match + ); + assert_eq!( + k.check("example.com", 2222, "ssh-ed25519", KEY_B), + HostCheck::Match + ); +} + +#[test] +fn accept_key_starts_a_new_line_after_a_file_without_final_newline() { + let _lock = env_lock(); + let dir = tempfile::tempdir().unwrap(); + unsafe { std::env::set_var("HOME", dir.path().join("home")) }; + let file = dir.path().join("kh"); + fs::write(&file, format!("old ssh-ed25519 {KEY_A}")).unwrap(); + accept_key(&file, "new", 22, "ssh-ed25519", KEY_B).unwrap(); + let mut k = KnownHosts::default(); + k.add_file(&file); + assert_eq!(k.check("old", 22, "ssh-ed25519", KEY_A), HostCheck::Match); + assert_eq!(k.check("new", 22, "ssh-ed25519", KEY_B), HostCheck::Match); +} + +#[test] +fn accept_key_refuses_to_write_under_ssh_dir() { + let _lock = env_lock(); + let dir = tempfile::tempdir().unwrap(); + unsafe { std::env::set_var("HOME", dir.path()) }; + let file = dir.path().join(".ssh/known_hosts"); + let err = accept_key(&file, "h", 22, "ssh-ed25519", KEY_A).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied); + assert!(!file.exists()); +} + +#[test] +fn own_file_follows_xdg_config_home_then_home() { + let _lock = env_lock(); + unsafe { + std::env::set_var("XDG_CONFIG_HOME", "/xdg"); + std::env::set_var("HOME", "/h"); + } + assert_eq!(own_file(), Some(PathBuf::from("/xdg/tunal/known_hosts"))); + unsafe { std::env::set_var("XDG_CONFIG_HOME", "") }; + assert_eq!( + own_file(), + Some(PathBuf::from("/h/.config/tunal/known_hosts")) + ); +} + +#[test] +fn load_default_reads_ssh_known_hosts_and_ours() { + let _lock = env_lock(); + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + fs::create_dir_all(home.join(".ssh")).unwrap(); + fs::create_dir_all(dir.path().join("cfg/tunal")).unwrap(); + fs::write( + home.join(".ssh/known_hosts"), + format!("one ssh-ed25519 {KEY_A}\n"), + ) + .unwrap(); + fs::write( + dir.path().join("cfg/tunal/known_hosts"), + format!("two ssh-ed25519 {KEY_B}\n"), + ) + .unwrap(); + unsafe { + std::env::set_var("HOME", &home); + std::env::set_var("XDG_CONFIG_HOME", dir.path().join("cfg")); + } + let k = KnownHosts::load_default(); + assert_eq!(k.check("one", 22, "ssh-ed25519", KEY_A), HostCheck::Match); + assert_eq!(k.check("two", 22, "ssh-ed25519", KEY_B), HostCheck::Match); +} diff --git a/crates/tunal-net/tests/sftp.rs b/crates/tunal-net/tests/sftp.rs new file mode 100644 index 0000000..eaa6dbb --- /dev/null +++ b/crates/tunal-net/tests/sftp.rs @@ -0,0 +1,1014 @@ +//! SFTP against an in-process russh server rooted in a temp dir: authentication paths, the +//! `Location` operations and host key handling. Everything stays on 127.0.0.1. +//! +//! The client reads `HOME`, `XDG_CONFIG_HOME` and `SSH_AUTH_SOCK`, so every test holds one lock +//! and points them into its own temp dir. + +use std::collections::HashMap; +use std::fs; +use std::io::{Read, Write}; +use std::net::SocketAddr; +use std::ops::ControlFlow; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; + +use russh::keys::{HashAlg, PrivateKey, PublicKey}; +use russh::server::{Auth, ChannelOpenHandle, Msg, Server as _, Session, VerifiedPublicKey}; +use russh::{Channel, ChannelId}; +use russh_sftp::protocol::{ + Attrs, Data, File, FileAttributes, Handle, Name, OpenFlags, Status, StatusCode, Version, +}; +use secrecy::SecretString; +use tunal_core::{Entry, Error, FileType, Kind, Location, Uri, WriteMode}; +use tunal_net::auth::{AuthPref, HostKeyChoice, HostKeyInfo, InteractiveRequest, Prompts}; +use tunal_net::sftp::SftpLocation; +use tunal_net::ssh_config::SshConfig; + +const USER: &str = "tester"; +const PASSWORD: &str = "pw-123"; +const PASSPHRASE: &str = "secret-pass"; + +fn fixture(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(name) +} + +fn private(name: &str) -> PrivateKey { + PrivateKey::from_openssh(fs::read_to_string(fixture(name)).unwrap()).unwrap() +} + +fn public(name: &str) -> PublicKey { + PublicKey::from_openssh(&fs::read_to_string(fixture(name)).unwrap()).unwrap() +} + +/// Base64 blob of a `.pub` fixture, as known_hosts holds it. +fn blob(name: &str) -> String { + fs::read_to_string(fixture(name)) + .unwrap() + .split_whitespace() + .nth(1) + .unwrap() + .to_owned() +} + +// ---------------------------------------------------------------- server + +#[derive(Default)] +struct Log { + /// `password`, `publickey` and `none` attempts, in order. + attempts: Mutex>, +} + +#[derive(Clone)] +struct SshServer { + root: PathBuf, + log: Arc, + client_key: PublicKey, +} + +impl russh::server::Server for SshServer { + type Handler = SshSession; + + fn new_client(&mut self, _: Option) -> SshSession { + SshSession { + server: self.clone(), + channels: Mutex::default(), + } + } +} + +struct SshSession { + server: SshServer, + channels: Mutex>>, +} + +impl russh::server::Handler for SshSession { + type Error = russh::Error; + + async fn auth_password(&mut self, user: &str, password: &str) -> Result { + self.server + .log + .attempts + .lock() + .unwrap() + .push(format!("password:{user}")); + Ok(if user == USER && password == PASSWORD { + Auth::Accept + } else { + Auth::reject() + }) + } + + async fn auth_publickey( + &mut self, + user: &str, + key: VerifiedPublicKey<'_>, + ) -> Result { + self.server + .log + .attempts + .lock() + .unwrap() + .push(format!("publickey:{user}")); + Ok( + if user == USER && key.public_key.key_data() == self.server.client_key.key_data() { + Auth::Accept + } else { + Auth::reject() + }, + ) + } + + async fn channel_open_session( + &mut self, + channel: Channel, + reply: ChannelOpenHandle, + _session: &mut Session, + ) -> Result<(), Self::Error> { + self.channels.lock().unwrap().insert(channel.id(), channel); + reply.accept().await; + Ok(()) + } + + async fn channel_eof( + &mut self, + channel: ChannelId, + session: &mut Session, + ) -> Result<(), Self::Error> { + session.close(channel)?; + Ok(()) + } + + async fn subsystem_request( + &mut self, + channel_id: ChannelId, + name: &str, + session: &mut Session, + ) -> Result<(), Self::Error> { + if name != "sftp" { + session.channel_failure(channel_id)?; + return Ok(()); + } + let channel = self.channels.lock().unwrap().remove(&channel_id).unwrap(); + session.channel_success(channel_id)?; + let sftp = Files { + root: self.server.root.clone(), + handles: HashMap::new(), + next: 0, + }; + russh_sftp::server::run(channel.into_stream(), sftp).await; + Ok(()) + } +} + +enum Open { + File(fs::File), + Dir(Option>), +} + +struct Files { + root: PathBuf, + handles: HashMap, + next: u32, +} + +fn status(code: StatusCode) -> StatusCode { + code +} + +fn io_status(e: std::io::Error) -> StatusCode { + match e.kind() { + std::io::ErrorKind::NotFound => StatusCode::NoSuchFile, + std::io::ErrorKind::PermissionDenied => StatusCode::PermissionDenied, + _ => status(StatusCode::Failure), + } +} + +fn ok(id: u32) -> Status { + Status { + id, + status_code: StatusCode::Ok, + error_message: "Ok".into(), + language_tag: "en-US".into(), + } +} + +impl Files { + fn real(&self, path: &str) -> PathBuf { + let mut out = self.root.clone(); + for part in path + .split('/') + .filter(|p| !p.is_empty() && *p != "." && *p != "..") + { + out.push(part); + } + out + } + + fn add(&mut self, open: Open) -> String { + self.next += 1; + let name = format!("h{}", self.next); + self.handles.insert(name.clone(), open); + name + } +} + +impl russh_sftp::server::Handler for Files { + type Error = StatusCode; + + fn unimplemented(&self) -> StatusCode { + StatusCode::OpUnsupported + } + + async fn init(&mut self, _: u32, _: HashMap) -> Result { + Ok(Version::new()) + } + + async fn open( + &mut self, + id: u32, + filename: String, + flags: OpenFlags, + _: FileAttributes, + ) -> Result { + let mut o = fs::OpenOptions::new(); + o.read(flags.contains(OpenFlags::READ)) + .write(flags.contains(OpenFlags::WRITE)) + .truncate(flags.contains(OpenFlags::TRUNCATE)); + if flags.contains(OpenFlags::CREATE) { + if flags.contains(OpenFlags::EXCLUDE) { + o.create_new(true); + } else { + o.create(true); + } + } + let file = o.open(self.real(&filename)).map_err(io_status)?; + Ok(Handle { + id, + handle: self.add(Open::File(file)), + }) + } + + async fn close(&mut self, id: u32, handle: String) -> Result { + self.handles.remove(&handle); + Ok(ok(id)) + } + + async fn read( + &mut self, + id: u32, + handle: String, + offset: u64, + len: u32, + ) -> Result { + use std::os::unix::fs::FileExt; + let Some(Open::File(f)) = self.handles.get(&handle) else { + return Err(StatusCode::Failure); + }; + let mut buf = vec![0; len as usize]; + let n = f.read_at(&mut buf, offset).map_err(io_status)?; + if n == 0 { + return Err(StatusCode::Eof); + } + buf.truncate(n); + Ok(Data { id, data: buf }) + } + + async fn write( + &mut self, + id: u32, + handle: String, + offset: u64, + data: Vec, + ) -> Result { + use std::os::unix::fs::FileExt; + let Some(Open::File(f)) = self.handles.get(&handle) else { + return Err(StatusCode::Failure); + }; + f.write_all_at(&data, offset).map_err(io_status)?; + Ok(ok(id)) + } + + async fn lstat(&mut self, id: u32, path: String) -> Result { + let m = fs::symlink_metadata(self.real(&path)).map_err(io_status)?; + Ok(Attrs { + id, + attrs: FileAttributes::from(&m), + }) + } + + async fn stat(&mut self, id: u32, path: String) -> Result { + let m = fs::metadata(self.real(&path)).map_err(io_status)?; + Ok(Attrs { + id, + attrs: FileAttributes::from(&m), + }) + } + + async fn fstat(&mut self, id: u32, handle: String) -> Result { + let Some(Open::File(f)) = self.handles.get(&handle) else { + return Err(StatusCode::Failure); + }; + let m = f.metadata().map_err(io_status)?; + Ok(Attrs { + id, + attrs: FileAttributes::from(&m), + }) + } + + async fn setstat( + &mut self, + id: u32, + _: String, + _: FileAttributes, + ) -> Result { + Ok(ok(id)) + } + + async fn opendir(&mut self, id: u32, path: String) -> Result { + let mut files = Vec::new(); + for e in fs::read_dir(self.real(&path)).map_err(io_status)? { + let e = e.map_err(io_status)?; + let m = fs::symlink_metadata(e.path()).map_err(io_status)?; + files.push(File::new( + e.file_name().to_string_lossy().into_owned(), + FileAttributes::from(&m), + )); + } + Ok(Handle { + id, + handle: self.add(Open::Dir(Some(files))), + }) + } + + async fn readdir(&mut self, id: u32, handle: String) -> Result { + match self.handles.get_mut(&handle) { + Some(Open::Dir(files)) => match files.take() { + Some(files) => Ok(Name { id, files }), + None => Err(StatusCode::Eof), + }, + _ => Err(StatusCode::Failure), + } + } + + async fn remove(&mut self, id: u32, filename: String) -> Result { + fs::remove_file(self.real(&filename)).map_err(io_status)?; + Ok(ok(id)) + } + + async fn mkdir( + &mut self, + id: u32, + path: String, + _: FileAttributes, + ) -> Result { + fs::create_dir(self.real(&path)).map_err(io_status)?; + Ok(ok(id)) + } + + async fn rmdir(&mut self, id: u32, path: String) -> Result { + fs::remove_dir(self.real(&path)).map_err(io_status)?; + Ok(ok(id)) + } + + async fn realpath(&mut self, id: u32, path: String) -> Result { + let parts: Vec<_> = path + .split('/') + .filter(|p| !p.is_empty() && *p != ".") + .collect(); + // The login folder is /home/tester, which exists inside the root. + let full = if path.starts_with('/') { + format!("/{}", parts.join("/")) + } else { + format!("/home/{USER}/{}", parts.join("/")) + }; + Ok(Name { + id, + files: vec![File::dummy(full.trim_end_matches('/').to_owned()).tap_root()], + }) + } + + async fn rename(&mut self, id: u32, from: String, to: String) -> Result { + fs::rename(self.real(&from), self.real(&to)).map_err(io_status)?; + Ok(ok(id)) + } + + async fn readlink(&mut self, id: u32, path: String) -> Result { + let target = fs::read_link(self.real(&path)).map_err(io_status)?; + Ok(Name { + id, + files: vec![File::dummy(target.to_string_lossy().into_owned())], + }) + } + + // OpenSSH's order on the wire: the first name is the target, the second the link. + async fn symlink( + &mut self, + id: u32, + target: String, + link: String, + ) -> Result { + std::os::unix::fs::symlink(&target, self.real(&link)).map_err(io_status)?; + Ok(ok(id)) + } +} + +trait TapRoot { + fn tap_root(self) -> Self; +} + +impl TapRoot for File { + /// An empty path means the root. + fn tap_root(mut self) -> Self { + if self.filename.is_empty() { + self.filename = "/".into(); + } + self + } +} + +// ---------------------------------------------------------------- harness + +/// Records what the user would be asked and answers from fixed settings. +#[derive(Default)] +struct Answers { + host_key: Mutex>, + password: Mutex>, + passphrase: Mutex>, + host_key_prompts: AtomicU32, + changed: Mutex>, + seen_host_key: Mutex>, + password_prompts: AtomicU32, + passphrase_prompts: AtomicUsize, +} + +impl Prompts for Answers { + fn confirm_host_key(&self, info: &HostKeyInfo) -> HostKeyChoice { + self.host_key_prompts.fetch_add(1, Ordering::Relaxed); + *self.seen_host_key.lock().unwrap() = Some(info.clone()); + self.host_key + .lock() + .unwrap() + .unwrap_or(HostKeyChoice::Refuse) + } + + fn host_key_changed(&self, info: &HostKeyInfo) { + self.changed.lock().unwrap().push(info.clone()); + } + + fn password(&self, _: &str, _: &str) -> Option { + self.password_prompts.fetch_add(1, Ordering::Relaxed); + self.password + .lock() + .unwrap() + .clone() + .map(SecretString::from) + } + + fn passphrase(&self, _: &Path) -> Option { + self.passphrase_prompts.fetch_add(1, Ordering::Relaxed); + self.passphrase + .lock() + .unwrap() + .clone() + .map(SecretString::from) + } + + fn interactive(&self, _: &InteractiveRequest) -> Option> { + None + } +} + +static ENV: Mutex<()> = Mutex::new(()); + +struct Fixture { + _lock: MutexGuard<'static, ()>, + _runtime: tokio::runtime::Runtime, + dir: tempfile::TempDir, + root: PathBuf, + port: u16, + log: Arc, + answers: Arc, + location: SftpLocation, +} + +impl Fixture { + /// A server with `host` as host key and `k_client` allowed; the client config names the + /// alias `box` with the client key. + fn new() -> Self { + Self::with(|_| {}) + } + + fn with(tweak: impl FnOnce(&Fixture)) -> Self { + let lock = ENV.lock().unwrap_or_else(|e| e.into_inner()); + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("root"); + fs::create_dir_all(root.join("home").join(USER)).unwrap(); + let home = dir.path().join("home"); + fs::create_dir_all(home.join(".ssh")).unwrap(); + unsafe { + std::env::set_var("HOME", &home); + std::env::set_var("XDG_CONFIG_HOME", dir.path().join("cfg")); + std::env::remove_var("SSH_AUTH_SOCK"); + } + + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let log = Arc::new(Log::default()); + let server = SshServer { + root: root.clone(), + log: log.clone(), + client_key: public("k_client.pub"), + }; + let config = russh::server::Config { + auth_rejection_time: std::time::Duration::from_millis(5), + auth_rejection_time_initial: Some(std::time::Duration::ZERO), + keys: vec![private("k_host")], + ..Default::default() + }; + let listener = runtime + .block_on(tokio::net::TcpListener::bind("127.0.0.1:0")) + .unwrap(); + let port = listener.local_addr().unwrap().port(); + let config = Arc::new(config); + runtime.spawn(async move { + let mut server = server; + let _ = server.run_on_socket(config, &listener).await; + }); + + let answers = Arc::new(Answers::default()); + let ssh_config = SshConfig::parse( + &format!( + "Host box\n HostName 127.0.0.1\n Port {port}\n User {USER}\n IdentityFile {}\n", + fixture("k_client").display() + ), + &home.join(".ssh"), + ); + let location = SftpLocation::with_config(ssh_config, answers.clone()); + let f = Fixture { + _lock: lock, + _runtime: runtime, + dir, + root, + port, + log, + answers, + location, + }; + tweak(&f); + f + } + + /// Trusts the server's host key (as `Trust and connect` would have). + fn trust(&self, key: &str) { + let line = format!("[127.0.0.1]:{} ssh-ed25519 {}\n", self.port, blob(key)); + let file = self.dir.path().join("cfg/tunal/known_hosts"); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(file, line).unwrap(); + } + + fn uri(&self, path: &str) -> Uri { + Uri::parse(&format!("sftp://box{path}")).unwrap() + } + + /// A URI that bypasses the ssh config (no key, no user from it). + fn direct(&self, path: &str) -> Uri { + Uri::parse(&format!("sftp://{USER}@127.0.0.1:{}{path}", self.port)).unwrap() + } + + fn attempts(&self) -> Vec { + self.log.attempts.lock().unwrap().clone() + } + + fn list(&self, uri: &Uri) -> Result, Error> { + let mut out = Vec::new(); + self.location.list(uri, &mut |chunk| { + out.extend(chunk); + ControlFlow::Continue(()) + })?; + out.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(out) + } +} + +fn trusted() -> Fixture { + Fixture::with(|f| f.trust("k_host.pub")) +} + +// ---------------------------------------------------------------- host keys + +#[test] +fn unknown_host_key_is_refused_by_default_and_names_the_fingerprint() { + let f = Fixture::new(); + let err = f.location.stat(&f.uri("/home")).unwrap_err(); + let Error::Remote(msg) = err else { + panic!("{err:?}") + }; + assert!(msg.contains("was not accepted"), "{msg}"); + assert_eq!(f.answers.host_key_prompts.load(Ordering::Relaxed), 1); + let info = f.answers.seen_host_key.lock().unwrap().clone().unwrap(); + assert_eq!(info.host, "127.0.0.1"); + assert_eq!(info.port, f.port); + assert_eq!(info.key_type, "ssh-ed25519"); + assert_eq!( + info.fingerprint, + public("k_host.pub") + .fingerprint(HashAlg::Sha256) + .to_string() + ); + assert!( + f.attempts().is_empty(), + "no login before the key is trusted" + ); +} + +#[test] +fn accept_once_connects_but_asks_again_next_time() { + let f = Fixture::new(); + *f.answers.host_key.lock().unwrap() = Some(HostKeyChoice::Once); + f.location.stat(&f.uri("/home")).unwrap(); + assert!(!f.dir.path().join("cfg/tunal/known_hosts").exists()); + f.location.disconnect(&f.uri("/home")); + f.location.stat(&f.uri("/home")).unwrap(); + assert_eq!(f.answers.host_key_prompts.load(Ordering::Relaxed), 2); +} + +#[test] +fn accept_always_is_remembered_in_our_own_file() { + let f = Fixture::new(); + *f.answers.host_key.lock().unwrap() = Some(HostKeyChoice::Always); + f.location.stat(&f.uri("/home")).unwrap(); + let saved = fs::read_to_string(f.dir.path().join("cfg/tunal/known_hosts")).unwrap(); + assert_eq!( + saved, + format!( + "[127.0.0.1]:{} ssh-ed25519 {}\n", + f.port, + blob("k_host.pub") + ) + ); + f.location.disconnect(&f.uri("/home")); + f.location.stat(&f.uri("/home")).unwrap(); + assert_eq!(f.answers.host_key_prompts.load(Ordering::Relaxed), 1); + // Nothing was written under ~/.ssh. + assert!(!f.dir.path().join("home/.ssh/known_hosts").exists()); +} + +#[test] +fn a_changed_host_key_is_refused_without_asking() { + let f = Fixture::with(|f| f.trust("k_host2.pub")); + *f.answers.host_key.lock().unwrap() = Some(HostKeyChoice::Always); + let err = f.location.stat(&f.uri("/home")).unwrap_err(); + let Error::Remote(msg) = err else { panic!() }; + assert!(msg.contains("changed"), "{msg}"); + assert_eq!(f.answers.host_key_prompts.load(Ordering::Relaxed), 0); + assert_eq!(f.answers.changed.lock().unwrap().len(), 1); + assert!(f.attempts().is_empty()); +} + +#[test] +fn a_revoked_host_key_is_refused() { + let f = Fixture::with(|f| { + let line = format!( + "@revoked [127.0.0.1]:{} ssh-ed25519 {}\n", + f.port, + blob("k_host.pub") + ); + let file = f.dir.path().join("cfg/tunal/known_hosts"); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(file, line).unwrap(); + }); + let Error::Remote(msg) = f.location.stat(&f.uri("/home")).unwrap_err() else { + panic!() + }; + assert!(msg.contains("revoked"), "{msg}"); +} + +#[test] +fn ssh_dir_known_hosts_is_honoured_read_only() { + let f = Fixture::new(); + fs::write( + f.dir.path().join("home/.ssh/known_hosts"), + format!( + "[127.0.0.1]:{} ssh-ed25519 {}\n", + f.port, + blob("k_host.pub") + ), + ) + .unwrap(); + f.location.stat(&f.uri("/home")).unwrap(); + assert_eq!(f.answers.host_key_prompts.load(Ordering::Relaxed), 0); +} + +// ---------------------------------------------------------------- authentication + +#[test] +fn identity_file_from_the_ssh_config_logs_in() { + let f = trusted(); + f.location.stat(&f.uri("/home")).unwrap(); + assert_eq!(f.attempts(), ["publickey:tester"]); + assert_eq!(f.answers.password_prompts.load(Ordering::Relaxed), 0); +} + +#[test] +fn explicit_key_file_preference() { + let f = trusted(); + f.location + .set_auth("127.0.0.1", AuthPref::Key(fixture("k_client"))); + f.location.stat(&f.direct("/home")).unwrap(); + assert_eq!(f.attempts(), ["publickey:tester"]); +} + +#[test] +fn wrong_key_is_denied_without_falling_back_to_a_password() { + let f = trusted(); + f.location + .set_auth("127.0.0.1", AuthPref::Key(fixture("k_host2"))); + let Error::Remote(msg) = f.location.stat(&f.direct("/home")).unwrap_err() else { + panic!() + }; + assert!(msg.contains("authentication failed"), "{msg}"); + assert_eq!(f.answers.password_prompts.load(Ordering::Relaxed), 0); +} + +#[test] +fn password_login_asks_once_and_remembers_the_connection() { + let f = trusted(); + *f.answers.password.lock().unwrap() = Some(PASSWORD.into()); + f.location.set_auth("127.0.0.1", AuthPref::Password); + f.location.stat(&f.direct("/home")).unwrap(); + f.location.stat(&f.direct("/home")).unwrap(); + assert_eq!(f.answers.password_prompts.load(Ordering::Relaxed), 1); + assert_eq!(f.attempts(), ["password:tester"]); + assert!(f.location.is_connected(&f.direct("/home"))); +} + +#[test] +fn wrong_password_gets_three_tries_then_fails() { + let f = trusted(); + *f.answers.password.lock().unwrap() = Some("nope".into()); + f.location.set_auth("127.0.0.1", AuthPref::Password); + let Error::Remote(msg) = f.location.stat(&f.direct("/home")).unwrap_err() else { + panic!() + }; + assert!(msg.contains("authentication failed"), "{msg}"); + assert_eq!(f.answers.password_prompts.load(Ordering::Relaxed), 3); + assert_eq!(f.attempts().len(), 3); +} + +#[test] +fn cancelled_password_prompt_fails_after_one_ask() { + let f = trusted(); + f.location.set_auth("127.0.0.1", AuthPref::Password); + assert!(f.location.stat(&f.direct("/home")).is_err()); + assert_eq!(f.answers.password_prompts.load(Ordering::Relaxed), 1); + assert!(f.attempts().is_empty()); +} + +#[test] +fn encrypted_key_asks_for_the_passphrase() { + let f = trusted(); + // The server only knows k_client, so the encrypted key logs in only after a wrong key: + // use the encrypted key with a matching server by swapping which key the server accepts. + // Here we just check the prompt flow: right passphrase decrypts, the login is then denied. + *f.answers.passphrase.lock().unwrap() = Some(PASSPHRASE.into()); + f.location + .set_auth("127.0.0.1", AuthPref::Key(fixture("k_enc"))); + assert!(f.location.stat(&f.direct("/home")).is_err()); + assert_eq!(f.answers.passphrase_prompts.load(Ordering::Relaxed), 1); + assert_eq!( + f.attempts(), + ["publickey:tester"], + "the key was decrypted and offered" + ); +} + +#[test] +// Regression: only the first wrong passphrase used to be asked. +fn wrong_passphrase_is_asked_up_to_three_times_and_nothing_is_offered() { + let f = trusted(); + *f.answers.passphrase.lock().unwrap() = Some("wrong".into()); + f.location + .set_auth("127.0.0.1", AuthPref::Key(fixture("k_enc"))); + assert!(f.location.stat(&f.direct("/home")).is_err()); + assert_eq!(f.answers.passphrase_prompts.load(Ordering::Relaxed), 3); + assert!(f.attempts().is_empty()); +} + +#[test] +fn refused_connection_and_proxy_hosts_give_plain_errors() { + let f = trusted(); + let dead = Uri::parse("sftp://tester@127.0.0.1:1/x").unwrap(); + let Error::Remote(msg) = f.location.stat(&dead).unwrap_err() else { + panic!() + }; + assert!(msg.contains("refused the connection"), "{msg}"); + + let proxied = SftpLocation::with_config( + SshConfig::parse("Host far\n ProxyJump bastion\n User u\n", Path::new("/x")), + f.answers.clone(), + ); + let Error::Remote(msg) = proxied + .stat(&Uri::parse("sftp://far/x").unwrap()) + .unwrap_err() + else { + panic!() + }; + assert!(msg.contains("ProxyJump"), "{msg}"); + + assert_eq!( + f.location + .stat(&Uri::parse("file:///x").unwrap()) + .unwrap_err(), + Error::Unsupported + ); +} + +// ---------------------------------------------------------------- operations + +fn path_of(f: &Fixture, rel: &str) -> PathBuf { + f.root.join(rel) +} + +#[test] +fn home_resolves_the_login_folder() { + let f = trusted(); + let home = f.location.home(&f.uri("/")).unwrap(); + assert_eq!(home.path(), b"/home/tester"); + assert_eq!(home.authority(), "box"); +} + +#[test] +fn list_and_stat_report_kinds_sizes_hidden_and_links() { + let f = trusted(); + fs::write(path_of(&f, "home/tester/a.txt"), b"hello").unwrap(); + fs::write(path_of(&f, "home/tester/.hidden"), b"").unwrap(); + fs::create_dir(path_of(&f, "home/tester/dir")).unwrap(); + std::os::unix::fs::symlink("a.txt", path_of(&f, "home/tester/ln")).unwrap(); + std::os::unix::fs::symlink("gone", path_of(&f, "home/tester/broken")).unwrap(); + + let entries = f.list(&f.uri("/home/tester")).unwrap(); + let names: Vec<_> = entries.iter().map(|e| e.display_name.as_str()).collect(); + assert_eq!(names, [".hidden", "a.txt", "broken", "dir", "ln"]); + let by = |n: &str| entries.iter().find(|e| e.display_name == n).unwrap(); + assert!(by(".hidden").hidden); + assert!(!by("a.txt").hidden); + assert_eq!(by("a.txt").size, 5); + assert!(matches!(by("a.txt").kind, Kind::File)); + assert!(matches!(by("dir").kind, Kind::Dir)); + match &by("ln").kind { + Kind::Symlink { + target, + target_type, + } => { + assert_eq!(target, b"a.txt"); + assert_eq!(*target_type, Some(FileType::File)); + } + other => panic!("{other:?}"), + } + match &by("broken").kind { + Kind::Symlink { target_type, .. } => assert_eq!(*target_type, None), + other => panic!("{other:?}"), + } + + let st = f.location.stat(&f.uri("/home/tester/a.txt")).unwrap(); + assert_eq!(st.size, 5); + assert_eq!(st.name, b"a.txt"); + assert_eq!( + f.location.stat(&f.uri("/home/tester/none")).unwrap_err(), + Error::NotFound + ); + assert_eq!(f.list(&f.uri("/nowhere")).unwrap_err(), Error::NotFound); +} + +#[test] +fn listing_in_chunks_can_be_cancelled() { + let f = trusted(); + for i in 0..600 { + fs::write(path_of(&f, &format!("home/tester/f{i}")), b"").unwrap(); + } + let mut chunks = Vec::new(); + let result = f.location.list(&f.uri("/home/tester"), &mut |c| { + chunks.push(c.len()); + ControlFlow::Break(()) + }); + assert_eq!(result.unwrap_err(), Error::Cancelled); + assert_eq!(chunks, [256], "stopped after the first chunk"); + let all = f.list(&f.uri("/home/tester")).unwrap(); + assert_eq!(all.len(), 600); +} + +#[test] +fn read_and_write_round_trip_including_a_large_file() { + let f = trusted(); + let uri = f.uri("/home/tester/big.bin"); + let data: Vec = (0..1_500_000u32).map(|i| (i % 251) as u8).collect(); + let mut w = f.location.open_write(&uri, WriteMode::CreateNew).unwrap(); + w.write_all(&data).unwrap(); + w.flush().unwrap(); + drop(w); + assert_eq!(fs::read(path_of(&f, "home/tester/big.bin")).unwrap(), data); + let mut got = Vec::new(); + f.location + .open_read(&uri) + .unwrap() + .read_to_end(&mut got) + .unwrap(); + assert_eq!(got, data); +} + +#[test] +fn create_new_refuses_an_existing_file_and_overwrite_truncates() { + let f = trusted(); + let uri = f.uri("/home/tester/x.txt"); + fs::write(path_of(&f, "home/tester/x.txt"), b"long old content").unwrap(); + assert_eq!( + f.location.open_write(&uri, WriteMode::CreateNew).err(), + Some(Error::Exists) + ); + let mut w = f.location.open_write(&uri, WriteMode::Overwrite).unwrap(); + w.write_all(b"new").unwrap(); + drop(w); + assert_eq!(fs::read(path_of(&f, "home/tester/x.txt")).unwrap(), b"new"); + assert_eq!( + f.location.open_read(&f.uri("/home/tester/missing")).err(), + Some(Error::NotFound) + ); +} + +#[test] +fn mkdir_rename_delete() { + let f = trusted(); + let dir = f.uri("/home/tester/d"); + f.location.mkdir(&dir).unwrap(); + assert!(path_of(&f, "home/tester/d").is_dir()); + assert_eq!(f.location.mkdir(&dir).unwrap_err(), Error::Exists); + + fs::write(path_of(&f, "home/tester/d/a"), b"1").unwrap(); + fs::write(path_of(&f, "home/tester/d/b"), b"2").unwrap(); + f.location + .rename(&f.uri("/home/tester/d/a"), &f.uri("/home/tester/d/c")) + .unwrap(); + assert!(path_of(&f, "home/tester/d/c").exists()); + assert!(!path_of(&f, "home/tester/d/a").exists()); + // Renaming over an existing name is refused, never silently replaced. + assert_eq!( + f.location + .rename(&f.uri("/home/tester/d/c"), &f.uri("/home/tester/d/b")) + .unwrap_err(), + Error::Exists + ); + assert_eq!(fs::read(path_of(&f, "home/tester/d/b")).unwrap(), b"2"); + // Another host is not renamed across. + assert_eq!( + f.location + .rename(&f.uri("/home/tester/d/c"), &f.direct("/home/tester/d/z")) + .unwrap_err(), + Error::Unsupported + ); + + f.location.delete(&f.uri("/home/tester/d/b")).unwrap(); + f.location.delete(&f.uri("/home/tester/d/c")).unwrap(); + f.location.delete(&dir).unwrap(); + assert!(!path_of(&f, "home/tester/d").exists()); + assert_eq!(f.location.delete(&dir).unwrap_err(), Error::NotFound); +} + +#[test] +fn symlink_creates_a_link_to_the_target() { + let f = trusted(); + fs::write(path_of(&f, "home/tester/real"), b"x").unwrap(); + f.location + .symlink(&f.uri("/home/tester/lnk"), b"real") + .unwrap(); + assert_eq!( + fs::read_link(path_of(&f, "home/tester/lnk")).unwrap(), + PathBuf::from("real") + ); +} + +#[test] +fn disconnect_closes_and_the_next_call_reconnects() { + let f = trusted(); + let uri = f.uri("/home/tester"); + f.location.stat(&uri).unwrap(); + assert!(f.location.is_connected(&uri)); + f.location.disconnect(&uri); + assert!(!f.location.is_connected(&uri)); + f.location.stat(&uri).unwrap(); + assert!(f.location.is_connected(&uri)); + assert_eq!(f.attempts().len(), 2, "two logins"); +} + +#[test] +fn capabilities_and_scheme() { + let f = trusted(); + assert_eq!(f.location.scheme(), "sftp"); + let c = f.location.capabilities(); + assert!(c.write && c.symlink && c.permissions && !c.trash && !c.watch); +} diff --git a/crates/tunal-player/Cargo.toml b/crates/tunal-player/Cargo.toml index 418b611..01fa0ee 100644 --- a/crates/tunal-player/Cargo.toml +++ b/crates/tunal-player/Cargo.toml @@ -10,3 +10,6 @@ symphonia.workspace = true cpal.workspace = true rubato.workspace = true rtrb.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/tunal-player/tests/fixtures/t.flac b/crates/tunal-player/tests/fixtures/t.flac new file mode 100644 index 0000000..1f5028d Binary files /dev/null and b/crates/tunal-player/tests/fixtures/t.flac differ diff --git a/crates/tunal-player/tests/fixtures/t.m4a b/crates/tunal-player/tests/fixtures/t.m4a new file mode 100644 index 0000000..45279ec Binary files /dev/null and b/crates/tunal-player/tests/fixtures/t.m4a differ diff --git a/crates/tunal-player/tests/fixtures/t.mp3 b/crates/tunal-player/tests/fixtures/t.mp3 new file mode 100644 index 0000000..d1ad5a3 Binary files /dev/null and b/crates/tunal-player/tests/fixtures/t.mp3 differ diff --git a/crates/tunal-player/tests/fixtures/t.ogg b/crates/tunal-player/tests/fixtures/t.ogg new file mode 100644 index 0000000..0290f82 Binary files /dev/null and b/crates/tunal-player/tests/fixtures/t.ogg differ diff --git a/crates/tunal-player/tests/fixtures/t.wav b/crates/tunal-player/tests/fixtures/t.wav new file mode 100644 index 0000000..d4dcf50 Binary files /dev/null and b/crates/tunal-player/tests/fixtures/t.wav differ diff --git a/crates/tunal-player/tests/waveform.rs b/crates/tunal-player/tests/waveform.rs new file mode 100644 index 0000000..327215f --- /dev/null +++ b/crates/tunal-player/tests/waveform.rs @@ -0,0 +1,171 @@ +//! Decoding and waveform peaks on fixtures; no audio device is needed. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::mpsc; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use tunal_player::{Error, Waveform, Waveforms}; + +fn fixture(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(name) +} + +fn wait(w: &Waveforms, path: &Path, buckets: usize) -> Result, Error> { + let (tx, rx) = mpsc::channel(); + w.request(path, buckets, move |r| tx.send(r).unwrap()); + rx.recv_timeout(Duration::from_secs(30)).unwrap() +} + +/// A mono 16-bit WAV: `quiet` seconds of silence then `loud` seconds of full-scale square wave. +fn write_wav(path: &Path, rate: u32, channels: u16, quiet: u32, loud: u32) { + let frames = |secs: u32| (rate * secs) as usize; + let mut data = Vec::new(); + for _ in 0..frames(quiet) { + for _ in 0..channels { + data.extend(0i16.to_le_bytes()); + } + } + for i in 0..frames(loud) { + let v: i16 = if i % 2 == 0 { 32767 } else { -32768 }; + for _ in 0..channels { + data.extend(v.to_le_bytes()); + } + } + let mut out = Vec::new(); + out.extend(b"RIFF"); + out.extend((36 + data.len() as u32).to_le_bytes()); + out.extend(b"WAVEfmt "); + out.extend(16u32.to_le_bytes()); + out.extend(1u16.to_le_bytes()); + out.extend(channels.to_le_bytes()); + out.extend(rate.to_le_bytes()); + out.extend((rate * u32::from(channels) * 2).to_le_bytes()); + out.extend((channels * 2).to_le_bytes()); + out.extend(16u16.to_le_bytes()); + out.extend(b"data"); + out.extend((data.len() as u32).to_le_bytes()); + out.extend(data); + fs::write(path, out).unwrap(); +} + +#[test] +fn every_fixture_decodes_with_about_one_second_and_a_signal() { + let w = Waveforms::new(); + for name in ["t.flac", "t.mp3", "t.ogg", "t.m4a", "t.wav"] { + let wave = wait(&w, &fixture(name), 20).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(wave.peaks.len(), 20, "{name}"); + let secs = wave.duration.as_secs_f64(); + assert!((0.9..=1.2).contains(&secs), "{name}: {secs}"); + let top = wave.peaks.iter().map(|p| p.1).fold(0.0, f32::max); + let bottom = wave.peaks.iter().map(|p| p.0).fold(0.0, f32::min); + assert!(top > 0.05 && top <= 0.3, "{name}: max {top}"); + assert!((-0.3..-0.05).contains(&bottom), "{name}: min {bottom}"); + for (lo, hi) in &wave.peaks { + assert!(lo <= hi, "{name}"); + } + } +} + +#[test] +fn buckets_follow_the_loudness_over_time() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("half.wav"); + // Two seconds of silence, then two seconds at full scale. + write_wav(&path, 8000, 1, 2, 2); + let wave = wait(&Waveforms::new(), &path, 8).unwrap(); + assert_eq!(wave.peaks.len(), 8); + assert!((wave.duration.as_secs_f64() - 4.0).abs() < 0.01); + for (i, (lo, hi)) in wave.peaks.iter().enumerate() { + if i < 4 { + assert_eq!((*lo, *hi), (0.0, 0.0), "bucket {i} is silent"); + } else { + assert!(*hi > 0.99 && *lo < -0.99, "bucket {i}: {lo} {hi}"); + } + } +} + +#[test] +fn stereo_peaks_cover_all_channels_and_duration_counts_frames() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("st.wav"); + write_wav(&path, 8000, 2, 0, 1); + let wave = wait(&Waveforms::new(), &path, 4).unwrap(); + assert!((wave.duration.as_secs_f64() - 1.0).abs() < 0.01); + assert!(wave.peaks.iter().all(|p| p.1 > 0.99 && p.0 < -0.99)); +} + +#[test] +fn more_buckets_than_blocks_still_gives_that_many() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("short.wav"); + write_wav(&path, 8000, 1, 0, 1); + // 8000 frames are ~32 blocks of 256; ask for far more buckets. + let wave = wait(&Waveforms::new(), &path, 500).unwrap(); + assert_eq!(wave.peaks.len(), 500); +} + +#[test] +fn results_are_cached_by_path_mtime_and_bucket_count() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("c.wav"); + write_wav(&path, 8000, 1, 0, 1); + let w = Waveforms::new(); + let first = wait(&w, &path, 10).unwrap(); + // A cached request is answered on the caller's thread, with the same allocation. + let second = Arc::new(Mutex::new(None)); + let slot = second.clone(); + w.request(&path, 10, move |r| *slot.lock().unwrap() = Some(r)); + let hit = second + .lock() + .unwrap() + .take() + .expect("answered at once") + .unwrap(); + assert!(Arc::ptr_eq(&first, &hit)); + // Another bucket count is a separate entry. + let other = wait(&w, &path, 11).unwrap(); + assert_eq!(other.peaks.len(), 11); + assert!(!Arc::ptr_eq(&first, &other)); + // A changed file is decoded again. + write_wav(&path, 8000, 1, 1, 1); + let f = fs::File::options().write(true).open(&path).unwrap(); + f.set_modified(std::time::SystemTime::now() + Duration::from_secs(120)) + .unwrap(); + drop(f); + let changed = wait(&w, &path, 10).unwrap(); + assert!(!Arc::ptr_eq(&first, &changed)); + assert!((changed.duration.as_secs_f64() - 2.0).abs() < 0.01); +} + +#[test] +fn errors_for_missing_garbage_and_unsupported_files() { + let dir = tempfile::tempdir().unwrap(); + let w = Waveforms::new(); + assert!(matches!( + wait(&w, &dir.path().join("none.wav"), 4), + Err(Error::Io(_)) + )); + let junk = dir.path().join("junk.mp3"); + fs::write(&junk, vec![0x13u8; 4096]).unwrap(); + assert!(wait(&w, &junk, 4).is_err()); + let empty = dir.path().join("empty.flac"); + fs::write(&empty, b"").unwrap(); + assert!(wait(&w, &empty, 4).is_err()); +} + +#[test] +fn a_cancelled_request_ends_with_cancelled() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("long.wav"); + // 600 s of mono audio at 8 kHz is about 9 MB: long enough to cancel mid-decode. + write_wav(&path, 8000, 1, 0, 600); + let (tx, rx) = mpsc::channel(); + let ticket = Waveforms::new().request(&path, 10, move |r| tx.send(r).unwrap()); + ticket.cancel(); + let result = rx.recv_timeout(Duration::from_secs(30)).unwrap(); + assert_eq!(result.unwrap_err(), Error::Cancelled); +} diff --git a/crates/tunal-tags/Cargo.toml b/crates/tunal-tags/Cargo.toml index 865caf3..b8145b9 100644 --- a/crates/tunal-tags/Cargo.toml +++ b/crates/tunal-tags/Cargo.toml @@ -10,3 +10,6 @@ lofty.workspace = true ureq.workspace = true serde.workspace = true serde_json.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/tunal-tags/src/io.rs b/crates/tunal-tags/src/io.rs index 4b9c756..47bc966 100644 --- a/crates/tunal-tags/src/io.rs +++ b/crates/tunal-tags/src/io.rs @@ -81,10 +81,10 @@ fn read_tag(tag: &Tag) -> TrackTags { artist: string(tag.artist()), album: string(tag.album()), album_artist: text(tag, ItemKey::AlbumArtist), - track_no: tag.track(), - track_total: tag.track_total(), - disc_no: tag.disk(), - disc_total: tag.disk_total(), + track_no: tag.track().filter(|&n| n != 0), + track_total: tag.track_total().filter(|&n| n != 0), + disc_no: tag.disk().filter(|&n| n != 0), + disc_total: tag.disk_total().filter(|&n| n != 0), date: text(tag, ItemKey::RecordingDate).or_else(|| text(tag, ItemKey::Year)), genre: string(tag.genre()), composer: text(tag, ItemKey::Composer), diff --git a/crates/tunal-tags/tests/fixtures/cover.jpg b/crates/tunal-tags/tests/fixtures/cover.jpg new file mode 100644 index 0000000..529cb7d Binary files /dev/null and b/crates/tunal-tags/tests/fixtures/cover.jpg differ diff --git a/crates/tunal-tags/tests/fixtures/cover.png b/crates/tunal-tags/tests/fixtures/cover.png new file mode 100644 index 0000000..b9ab8fd Binary files /dev/null and b/crates/tunal-tags/tests/fixtures/cover.png differ diff --git a/crates/tunal-tags/tests/fixtures/t.flac b/crates/tunal-tags/tests/fixtures/t.flac new file mode 100644 index 0000000..1f5028d Binary files /dev/null and b/crates/tunal-tags/tests/fixtures/t.flac differ diff --git a/crates/tunal-tags/tests/fixtures/t.m4a b/crates/tunal-tags/tests/fixtures/t.m4a new file mode 100644 index 0000000..45279ec Binary files /dev/null and b/crates/tunal-tags/tests/fixtures/t.m4a differ diff --git a/crates/tunal-tags/tests/fixtures/t.mp3 b/crates/tunal-tags/tests/fixtures/t.mp3 new file mode 100644 index 0000000..d1ad5a3 Binary files /dev/null and b/crates/tunal-tags/tests/fixtures/t.mp3 differ diff --git a/crates/tunal-tags/tests/fixtures/t.ogg b/crates/tunal-tags/tests/fixtures/t.ogg new file mode 100644 index 0000000..0290f82 Binary files /dev/null and b/crates/tunal-tags/tests/fixtures/t.ogg differ diff --git a/crates/tunal-tags/tests/fixtures/t.wav b/crates/tunal-tags/tests/fixtures/t.wav new file mode 100644 index 0000000..d4dcf50 Binary files /dev/null and b/crates/tunal-tags/tests/fixtures/t.wav differ diff --git a/crates/tunal-tags/tests/musicbrainz.rs b/crates/tunal-tags/tests/musicbrainz.rs new file mode 100644 index 0000000..7bea823 --- /dev/null +++ b/crates/tunal-tags/tests/musicbrainz.rs @@ -0,0 +1,477 @@ +//! MusicBrainz and Cover Art Archive client against a mock HTTP server on localhost, and the +//! track matching that uses its releases. The rate limit is global to the process, so the +//! request-heavy tests below also keep each other honest. + +use std::io::{BufRead, BufReader, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use tunal_tags::{Client, FileInfo, NetError, match_tracks}; + +struct Response { + status: u16, + headers: Vec<(&'static str, String)>, + body: Vec, +} + +fn json(body: &str) -> Response { + Response { + status: 200, + headers: vec![("Content-Type", "application/json".into())], + body: body.as_bytes().to_vec(), + } +} + +fn status(code: u16) -> Response { + Response { + status: code, + headers: vec![], + body: vec![], + } +} + +#[derive(Clone, Debug)] +struct Seen { + target: String, + user_agent: String, + at: Instant, +} + +struct Mock { + base: String, + seen: Arc>>, +} + +impl Mock { + /// Serves `handler` for every request, one connection at a time, until the process ends. + fn start(handler: impl Fn(&str, usize) -> Response + Send + 'static) -> Mock { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(Vec::new())); + let log = seen.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { break }; + let n = log.lock().unwrap().len(); + let Some(request) = read_request(&stream) else { + continue; + }; + let reply = handler(&request.target, n); + log.lock().unwrap().push(request); + write_response(stream, reply); + } + }); + Mock { base, seen } + } + + fn seen(&self) -> Vec { + self.seen.lock().unwrap().clone() + } + + fn client(&self) -> Client { + Client::with_bases(&self.base, &self.base) + } +} + +fn read_request(stream: &TcpStream) -> Option { + let mut reader = BufReader::new(stream.try_clone().ok()?); + let mut line = String::new(); + reader.read_line(&mut line).ok()?; + let target = line.split_whitespace().nth(1)?.to_owned(); + let mut user_agent = String::new(); + loop { + let mut header = String::new(); + if reader.read_line(&mut header).ok()? == 0 || header == "\r\n" { + break; + } + if header.to_ascii_lowercase().starts_with("user-agent:") { + user_agent = header["user-agent:".len()..].trim().to_owned(); + } + } + Some(Seen { + target, + user_agent, + at: Instant::now(), + }) +} + +fn write_response(mut stream: TcpStream, r: Response) { + let mut head = format!( + "HTTP/1.1 {} X\r\nContent-Length: {}\r\nConnection: close\r\n", + r.status, + r.body.len() + ); + for (k, v) in &r.headers { + head.push_str(&format!("{k}: {v}\r\n")); + } + head.push_str("\r\n"); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(&r.body); +} + +const REL: &str = "aaaaaaaa-0000-0000-0000-000000000001"; + +const RELEASE_SEARCH: &str = r#"{"releases":[ + {"id":"aaaaaaaa-0000-0000-0000-000000000001","title":"Album","score":100,"date":"2001-02-03", + "country":"XW","track-count":10, + "artist-credit":[{"name":"Foo","joinphrase":" & ","artist":{"id":"a1"}},{"name":"Bar","artist":{"id":"a2"}}], + "release-group":{"id":"rg1"}}, + {"id":"aaaaaaaa-0000-0000-0000-000000000002","title":"Other","score":50,"date":""} +]}"#; + +const RECORDING_SEARCH: &str = r#"{"recordings":[ + {"id":"rec1","title":"Song","score":99,"length":201000, + "artist-credit":[{"name":"Foo","artist":{"id":"a1"}}], + "releases":[{"id":"r1","title":"Album"},{"id":"r2","title":"Best of"}]} +]}"#; + +const RELEASE: &str = r#"{ + "id":"aaaaaaaa-0000-0000-0000-000000000001","title":"Album","date":"2001","country":"XW", + "artist-credit":[{"name":"Foo","artist":{"id":"a1"}}], + "release-group":{"id":"rg1","genres":[{"name":"Rock","count":5},{"name":"indie","count":9}]}, + "genres":[{"name":"rock","count":2},{"name":"Folk","count":1}], + "media":[ + {"position":1,"tracks":[ + {"id":"t1","position":1,"title":"One","length":180000, + "artist-credit":[{"name":"Foo","artist":{"id":"a1"}}],"recording":{"id":"rec1","length":181000}}, + {"id":"t2","position":2,"title":"Two","recording":{"id":"rec2","length":200000}}]}, + {"position":2,"tracks":[ + {"id":"t3","title":"Three","artist-credit":[{"name":"Foo","artist":{"id":"a1"}}],"recording":{"id":"rec3"}}]} + ]}"#; + +#[test] +fn searches_send_a_user_agent_and_escaped_lucene_query() { + let mock = Mock::start(|target, _| { + if target.starts_with("/ws/2/release?") { + json(RELEASE_SEARCH) + } else { + json(RECORDING_SEARCH) + } + }); + let client = mock.client(); + let hits = client + .search_releases(Some("Foo \"The\" Bar"), Some("Album"), Some(10), 5) + .unwrap(); + assert_eq!(hits.len(), 2); + assert_eq!(hits[0].artist, "Foo & Bar"); + assert_eq!(hits[0].title, "Album"); + assert_eq!(hits[0].date.as_deref(), Some("2001-02-03")); + assert_eq!(hits[0].track_count, Some(10)); + assert_eq!(hits[0].release_group_id.as_deref(), Some("rg1")); + assert_eq!(hits[0].score, 100); + assert_eq!(hits[1].date, None, "an empty date is none"); + + let rec = client + .search_recordings(Some("Song"), Some("Foo"), None, 3) + .unwrap(); + assert_eq!(rec[0].length_ms, Some(201000)); + assert_eq!(rec[0].releases.len(), 2); + assert_eq!(rec[0].releases[1], ("r2".to_owned(), "Best of".to_owned())); + + let seen = mock.seen(); + assert!(seen[0].user_agent.starts_with("Tunal/"), "{:?}", seen[0]); + assert!( + seen[0] + .user_agent + .contains("archlinux.tail7c4f5e.ts.net/git/astar76/Tunal") + ); + let target = &seen[0].target; + assert!( + target.contains("fmt=json") && target.contains("limit=5"), + "{target}" + ); + // The embedded quotes are backslash-escaped inside the phrase (%5C%22 = \"). + assert!(target.contains("%5C%22The%5C%22"), "{target}"); + assert!( + target.contains("tracks%3A10") || target.contains("tracks:10"), + "{target}" + ); +} + +#[test] +fn empty_search_makes_no_request() { + let mock = Mock::start(|_, _| json("{}")); + let client = mock.client(); + assert!( + client + .search_releases(None, Some(" "), None, 5) + .unwrap() + .is_empty() + ); + assert!( + client + .search_recordings(None, None, None, 5) + .unwrap() + .is_empty() + ); + assert!(mock.seen().is_empty()); +} + +#[test] +fn release_lookup_builds_tracks_discs_and_genres() { + let mock = Mock::start(|target, _| { + assert!( + target.starts_with(&format!("/ws/2/release/{REL}?")), + "{target}" + ); + assert!(target.contains("inc="), "{target}"); + json(RELEASE) + }); + let release = mock.client().release(REL).unwrap().unwrap(); + assert_eq!(release.title, "Album"); + assert_eq!(release.artist, "Foo"); + assert_eq!(release.release_group_id.as_deref(), Some("rg1")); + assert_eq!(release.disc_total, 2); + // Most voted first, case-insensitive duplicates dropped. + assert_eq!(release.genres, ["indie", "Rock", "Folk"]); + assert_eq!(release.tracks.len(), 3); + let t = &release.tracks; + assert_eq!((t[0].disc, t[0].position, t[0].disc_track_count), (1, 1, 2)); + assert_eq!(t[0].length_ms, Some(180000), "the track's own length wins"); + assert_eq!(t[0].recording_id, "rec1"); + assert_eq!(t[0].artist_ids, ["a1"]); + assert_eq!( + t[1].length_ms, + Some(200000), + "falls back to the recording's" + ); + assert_eq!((t[2].disc, t[2].position, t[2].disc_track_count), (2, 1, 1)); + assert_eq!(t[2].length_ms, None); +} + +#[test] +fn unknown_release_is_none_and_bad_ids_never_reach_the_network() { + let mock = Mock::start(|_, _| status(404)); + let client = mock.client(); + assert!(client.release(REL).unwrap().is_none()); + assert!(matches!( + client.release("../etc/passwd"), + Err(NetError::Parse(_)) + )); + assert!(matches!(client.release(""), Err(NetError::Parse(_)))); + assert!(matches!(client.front_cover("a/b"), Err(NetError::Parse(_)))); + assert_eq!(mock.seen().len(), 1); +} + +#[test] +fn errors_are_reported() { + let mock = Mock::start(|target, _| { + if target.contains("00000000000a") { + status(500) + } else { + json("this is not json") + } + }); + let client = mock.client(); + assert!(matches!( + client.release("aaaaaaaa-0000-0000-0000-00000000000a"), + Err(NetError::Status(500)) + )); + assert!(matches!(client.release(REL), Err(NetError::Parse(_)))); + // Nothing listens there. + let dead = Client::with_bases("http://127.0.0.1:1", "http://127.0.0.1:1"); + assert!(matches!(dead.release(REL), Err(NetError::Http(_)))); +} + +#[test] +fn requests_are_at_least_a_second_apart() { + let mock = Mock::start(|_, _| json(RELEASE_SEARCH)); + let client = mock.client(); + for _ in 0..3 { + client.search_releases(Some("a"), None, None, 1).unwrap(); + } + let seen = mock.seen(); + assert_eq!(seen.len(), 3); + for pair in seen.windows(2) { + let gap = pair[1].at - pair[0].at; + assert!(gap >= Duration::from_millis(950), "gap {gap:?}"); + } +} + +#[test] +fn the_limit_is_shared_by_clients_and_by_both_services() { + let a = Mock::start(|_, _| json(RELEASE_SEARCH)); + let b = Mock::start(|_, _| json(RELEASE_SEARCH)); + let client_a = a.client(); + let client_b = b.client(); + let started = Instant::now(); + client_a.search_releases(Some("a"), None, None, 1).unwrap(); + client_b.search_releases(Some("a"), None, None, 1).unwrap(); + client_a.search_releases(Some("a"), None, None, 1).unwrap(); + assert!(started.elapsed() >= Duration::from_millis(1900)); +} + +#[test] +fn a_503_is_retried_after_a_growing_pause() { + let mock = Mock::start(|_, n| { + if n == 0 { + status(503) + } else { + json(RELEASE_SEARCH) + } + }); + let hits = mock + .client() + .search_releases(Some("a"), None, None, 1) + .unwrap(); + assert_eq!(hits.len(), 2); + let seen = mock.seen(); + assert_eq!(seen.len(), 2); + assert!( + seen[1].at - seen[0].at >= Duration::from_millis(1900), + "backoff of 2 s" + ); +} + +#[test] +fn a_429_is_retried_too() { + let mock = Mock::start(|_, n| { + if n == 0 { + status(429) + } else { + json(RELEASE_SEARCH) + } + }); + assert!( + mock.client() + .search_releases(Some("a"), None, None, 1) + .is_ok() + ); + assert_eq!(mock.seen().len(), 2); +} + +#[test] +fn a_persistent_503_gives_up_after_four_attempts() { + let mock = Mock::start(|_, _| status(503)); + let started = Instant::now(); + let result = mock.client().search_releases(Some("a"), None, None, 1); + assert!(matches!(result, Err(NetError::Status(503)))); + assert_eq!(mock.seen().len(), 4); + // Pauses of 2 + 4 + 8 seconds. + assert!(started.elapsed() >= Duration::from_secs(14)); +} + +const JPEG: &[u8] = &[0xFF, 0xD8, 0xFF, 0xE0, 1, 2, 3]; +const PNG: &[u8] = &[0x89, b'P', b'N', b'G', 1, 2, 3]; + +fn bytes(body: &[u8]) -> Response { + Response { + status: 200, + headers: vec![], + body: body.to_vec(), + } +} + +#[test] +fn front_cover_follows_redirects_and_detects_the_type() { + let mock = Mock::start(|target, _| match target { + t if t.ends_with("/front-500") && t.contains("0001") => Response { + status: 307, + headers: vec![("Location", "/storage/cover".into())], + body: vec![], + }, + "/storage/cover" => bytes(JPEG), + t if t.contains("0002") => bytes(PNG), + t if t.contains("0003") => bytes(b"not an image"), + _ => status(404), + }); + let client = mock.client(); + let jpeg = client + .front_cover("aaaaaaaa-0000-0000-0000-000000000001") + .unwrap() + .unwrap(); + assert_eq!( + (jpeg.mime.as_str(), jpeg.data.as_slice()), + ("image/jpeg", JPEG) + ); + let png = client + .front_cover("aaaaaaaa-0000-0000-0000-000000000002") + .unwrap() + .unwrap(); + assert_eq!(png.mime, "image/png"); + assert!(matches!( + client.front_cover("aaaaaaaa-0000-0000-0000-000000000003"), + Err(NetError::Parse(_)) + )); + assert!( + client + .front_cover("aaaaaaaa-0000-0000-0000-000000000004") + .unwrap() + .is_none() + ); +} + +// Track matching on a release as the client returns it. + +fn release() -> tunal_tags::Release { + let mock = Mock::start(|_, _| json(RELEASE)); + mock.client().release(REL).unwrap().unwrap() +} + +fn info(disc: Option, track: Option, title: Option<&str>, ms: Option) -> FileInfo { + FileInfo { + disc, + track, + title: title.map(str::to_owned), + duration_ms: ms, + } +} + +#[test] +fn matches_by_disc_and_position() { + let r = release(); + let files = [ + info(Some(2), Some(1), None, None), + info(Some(1), Some(2), None, None), + info(Some(1), Some(1), None, None), + ]; + assert_eq!(match_tracks(&files, &r), [Some(2), Some(1), Some(0)]); +} + +#[test] +fn matches_by_title_when_numbers_are_missing_or_wrong() { + let r = release(); + let files = [ + info(None, None, Some("two"), None), + info(None, Some(1), Some("Three!"), Some(1000)), + info(None, None, Some("one"), Some(180_500)), + ]; + let got = match_tracks(&files, &r); + assert_eq!(got[0], Some(1)); + assert_eq!(got[2], Some(0)); + // Without a disc number a file is assumed to be on disc 1, so a title decides for "Three". + assert_eq!(got[1], Some(2)); +} + +#[test] +fn each_track_is_used_once_and_strangers_stay_unmatched() { + let r = release(); + let files = [ + info(Some(1), Some(1), Some("One"), Some(180_000)), + info(Some(1), Some(1), Some("One"), Some(180_000)), + info(None, None, Some("Zzzzzz"), Some(60_000)), + ]; + let got = match_tracks(&files, &r); + assert_eq!(got[0], Some(0)); + assert_eq!(got[1], None, "the track is taken"); + assert_eq!(got[2], None); +} + +#[test] +fn a_position_that_belongs_to_another_song_is_rejected() { + let r = release(); + // Position 2 on disc 1, but the title and length point elsewhere. + let files = [info( + Some(1), + Some(2), + Some("Completely Different"), + Some(30_000), + )]; + assert_eq!(match_tracks(&files, &r), [None]); +} + +#[test] +fn no_files_no_matches() { + assert!(match_tracks(&[], &release()).is_empty()); +} diff --git a/crates/tunal-tags/tests/tags.rs b/crates/tunal-tags/tests/tags.rs new file mode 100644 index 0000000..28c485f --- /dev/null +++ b/crates/tunal-tags/tests/tags.rs @@ -0,0 +1,367 @@ +//! Reading, writing, merging and Keep semantics on one fixture of each format. + +use std::fs; +use std::path::{Path, PathBuf}; + +use tunal_tags::{ + Cover, CoverEdit, Edit, Error, Merged, TagEdit, TagSet, TrackTags, duration_ms, read, read_set, + write, write_many, +}; + +const FORMATS: [&str; 5] = ["t.flac", "t.mp3", "t.ogg", "t.m4a", "t.wav"]; + +fn fixture(name: &str) -> Vec { + fs::read( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(name), + ) + .unwrap() +} + +/// A scratch copy of a fixture under its own name. +fn copy(dir: &Path, name: &str) -> PathBuf { + let to = dir.join(name); + fs::write(&to, fixture(name)).unwrap(); + to +} + +fn s(v: &str) -> Edit { + Edit::Set(v.to_owned()) +} + +fn full_edit() -> TagEdit { + TagEdit { + title: s("Song"), + artist: s("Band"), + album: s("Album"), + album_artist: s("Various"), + track_no: Edit::Set(3), + track_total: Edit::Set(12), + disc_no: Edit::Set(1), + disc_total: Edit::Set(2), + date: s("2021-05-04"), + genre: s("Rock"), + composer: s("Me"), + comment: s("hello"), + ..TagEdit::default() + } +} + +#[test] +fn untagged_files_read_as_empty_and_keep_their_duration() { + let dir = tempfile::tempdir().unwrap(); + for name in FORMATS { + let path = copy(dir.path(), name); + let tags = read(&path).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(tags.title, None, "{name}"); + assert_eq!(tags.cover, None, "{name}"); + let ms = duration_ms(&path).unwrap_or_else(|| panic!("{name}: no duration")); + assert!((900..=1250).contains(&ms), "{name}: {ms} ms"); + } +} + +#[test] +fn write_then_read_round_trips_every_field_in_every_format() { + let dir = tempfile::tempdir().unwrap(); + for name in FORMATS { + let path = copy(dir.path(), name); + write(&path, &full_edit()).unwrap_or_else(|e| panic!("{name}: {e}")); + let t = read(&path).unwrap(); + assert_eq!(t.title.as_deref(), Some("Song"), "{name}"); + assert_eq!(t.artist.as_deref(), Some("Band"), "{name}"); + assert_eq!(t.album.as_deref(), Some("Album"), "{name}"); + assert_eq!(t.genre.as_deref(), Some("Rock"), "{name}"); + assert_eq!(t.track_no, Some(3), "{name}"); + assert_eq!(t.track_total, Some(12), "{name}"); + assert_eq!(t.date.as_deref(), Some("2021-05-04"), "{name}"); + assert_eq!(t.comment.as_deref(), Some("hello"), "{name}"); + // The audio still decodes to the same length. + assert!(duration_ms(&path).is_some(), "{name}"); + } +} + +#[test] +fn keep_leaves_other_fields_alone_and_clear_removes_one() { + let dir = tempfile::tempdir().unwrap(); + for name in FORMATS { + let path = copy(dir.path(), name); + write(&path, &full_edit()).unwrap(); + let only_title = TagEdit { + title: s("Renamed"), + ..TagEdit::default() + }; + write(&path, &only_title).unwrap(); + let t = read(&path).unwrap(); + assert_eq!(t.title.as_deref(), Some("Renamed"), "{name}"); + assert_eq!(t.artist.as_deref(), Some("Band"), "{name}"); + assert_eq!(t.track_no, Some(3), "{name}"); + + let clear = TagEdit { + artist: Edit::Clear, + track_no: Edit::Clear, + comment: s(" "), + ..TagEdit::default() + }; + write(&path, &clear).unwrap(); + let t = read(&path).unwrap(); + assert_eq!(t.artist, None, "{name}"); + // Regression: ID3 keeps "0/12" when only the number goes; that is no track number. + assert_eq!(t.track_no, None, "{name}"); + assert_eq!(t.comment, None, "{name}: a blank value clears"); + assert_eq!(t.title.as_deref(), Some("Renamed"), "{name}"); + assert_eq!(t.album.as_deref(), Some("Album"), "{name}"); + } +} + +#[test] +fn empty_edit_does_not_touch_the_file() { + let dir = tempfile::tempdir().unwrap(); + let path = copy(dir.path(), "t.mp3"); + write(&path, &TagEdit::default()).unwrap(); + assert_eq!(fs::read(&path).unwrap(), fixture("t.mp3")); +} + +#[test] +fn musicbrainz_ids_round_trip() { + let dir = tempfile::tempdir().unwrap(); + for name in ["t.flac", "t.mp3", "t.m4a", "t.ogg"] { + let path = copy(dir.path(), name); + let id = "11111111-2222-3333-4444-555555555555"; + let edit = TagEdit { + mb_recording_id: s(id), + mb_release_id: s(id), + mb_artist_id: s(id), + mb_release_group_id: s(id), + ..TagEdit::default() + }; + write(&path, &edit).unwrap(); + let t = read(&path).unwrap(); + assert_eq!(t.mb_recording_id.as_deref(), Some(id), "{name}"); + assert_eq!(t.mb_release_id.as_deref(), Some(id), "{name}"); + assert_eq!(t.mb_artist_id.as_deref(), Some(id), "{name}"); + assert_eq!(t.mb_release_group_id.as_deref(), Some(id), "{name}"); + } +} + +fn jpeg() -> Cover { + Cover { + mime: "image/jpeg".into(), + data: fixture("cover.jpg"), + } +} + +fn png() -> Cover { + Cover { + mime: "image/png".into(), + data: fixture("cover.png"), + } +} + +#[test] +fn cover_set_replace_and_remove() { + let dir = tempfile::tempdir().unwrap(); + for name in ["t.flac", "t.mp3", "t.ogg", "t.m4a"] { + let path = copy(dir.path(), name); + let set = |cover| TagEdit { + cover: CoverEdit::Set(cover), + ..TagEdit::default() + }; + write(&path, &set(jpeg())).unwrap_or_else(|e| panic!("{name}: {e}")); + let t = read(&path).unwrap(); + assert_eq!(t.cover, Some(jpeg()), "{name}"); + assert_eq!(t.other_pictures, 0, "{name}"); + + // A second cover replaces the first instead of adding one. + write(&path, &set(png())).unwrap(); + let t = read(&path).unwrap(); + assert_eq!(t.cover, Some(png()), "{name}"); + assert_eq!(t.other_pictures, 0, "{name}"); + + // Keep leaves it; Remove drops it. + write( + &path, + &TagEdit { + title: s("x"), + ..TagEdit::default() + }, + ) + .unwrap(); + assert_eq!(read(&path).unwrap().cover, Some(png()), "{name}"); + write( + &path, + &TagEdit { + cover: CoverEdit::Remove, + ..TagEdit::default() + }, + ) + .unwrap(); + let t = read(&path).unwrap(); + assert_eq!(t.cover, None, "{name}"); + assert_eq!(t.title.as_deref(), Some("x"), "{name}"); + } +} + +#[test] +fn cover_that_is_not_jpeg_or_png_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = copy(dir.path(), "t.flac"); + let bad = TagEdit { + cover: CoverEdit::Set(Cover { + mime: "image/gif".into(), + data: b"GIF89a....".to_vec(), + }), + ..TagEdit::default() + }; + assert!(matches!(write(&path, &bad), Err(Error::BadImage))); +} + +#[test] +fn front_cover_in_the_source_file_is_read() { + // cover.flac is not in this crate's fixtures; build one by writing a cover. + let dir = tempfile::tempdir().unwrap(); + let path = copy(dir.path(), "t.flac"); + write( + &path, + &TagEdit { + cover: CoverEdit::Set(jpeg()), + ..TagEdit::default() + }, + ) + .unwrap(); + let t = read(&path).unwrap(); + assert_eq!(t.cover.unwrap().mime, "image/jpeg"); +} + +#[test] +fn read_set_merges_and_reports_failures() { + let dir = tempfile::tempdir().unwrap(); + let a = copy(dir.path(), "t.flac"); + let b = copy(dir.path(), "t.mp3"); + write( + &a, + &TagEdit { + artist: s("Band"), + album: s("One"), + title: s("A"), + ..TagEdit::default() + }, + ) + .unwrap(); + write( + &b, + &TagEdit { + artist: s("Band"), + album: s("Two"), + ..TagEdit::default() + }, + ) + .unwrap(); + let broken = dir.path().join("broken.mp3"); + fs::write(&broken, b"this is not audio").unwrap(); + let (set, failed) = read_set(&[a.clone(), b.clone(), broken.clone()]); + assert_eq!(set.count, 2); + assert_eq!(set.artist, Merged::Same(Some("Band".to_owned()))); + assert_eq!(set.album, Merged::Mixed); + assert_eq!(set.title, Merged::Mixed, "one has a title, the other none"); + assert_eq!(set.genre, Merged::Same(None)); + assert_eq!(failed.len(), 1); + assert_eq!(failed[0].0, broken); +} + +#[test] +fn write_many_gives_one_result_per_file() { + let dir = tempfile::tempdir().unwrap(); + let a = copy(dir.path(), "t.flac"); + let broken = dir.path().join("broken.flac"); + fs::write(&broken, b"nope").unwrap(); + let results = write_many( + &[a.clone(), broken.clone()], + &TagEdit { + genre: s("Jazz"), + ..TagEdit::default() + }, + ); + assert_eq!(results.len(), 2); + assert_eq!(results[0].0, a); + assert!(results[0].1.is_ok()); + assert!(results[1].1.is_err()); + assert_eq!(read(&a).unwrap().genre.as_deref(), Some("Jazz")); +} + +#[test] +fn missing_file_is_an_error() { + assert!(read(Path::new("/nonexistent/none.flac")).is_err()); + assert_eq!(duration_ms(Path::new("/nonexistent/none.flac")), None); +} + +// In-memory model. + +fn track(title: &str, artist: &str, no: u32) -> TrackTags { + TrackTags { + title: Some(title.into()), + artist: Some(artist.into()), + track_no: Some(no), + ..TrackTags::default() + } +} + +#[test] +fn merge_of_nothing_is_empty() { + let set = TagSet::merge(&[]); + assert_eq!(set.count, 0); + assert_eq!(set.title, Merged::Same(None)); + assert_eq!(set.cover, Merged::Same(None)); +} + +#[test] +fn merge_same_and_mixed() { + let set = TagSet::merge(&[track("A", "X", 1), track("B", "X", 2)]); + assert_eq!(set.artist, Merged::Same(Some("X".into()))); + assert_eq!(set.title, Merged::Mixed); + assert_eq!(set.track_no, Merged::Mixed); + let single = TagSet::merge(&[track("A", "X", 1)]); + assert_eq!(single.title, Merged::Same(Some("A".into()))); +} + +#[test] +fn merge_covers() { + let mut a = track("A", "X", 1); + let mut b = track("B", "X", 2); + a.cover = Some(jpeg()); + assert_eq!(TagSet::merge(&[a.clone(), b.clone()]).cover, Merged::Mixed); + b.cover = Some(jpeg()); + assert_eq!(TagSet::merge(&[a, b]).cover, Merged::Same(Some(jpeg()))); +} + +#[test] +fn apply_edit_in_memory() { + let mut tags = track("A", "X", 1); + tags.cover = Some(jpeg()); + let edit = TagEdit { + title: s("New"), + artist: Edit::Clear, + cover: CoverEdit::Remove, + ..TagEdit::default() + }; + assert!(!edit.is_empty()); + edit.apply(&mut tags); + assert_eq!(tags.title.as_deref(), Some("New")); + assert_eq!(tags.artist, None); + assert_eq!(tags.track_no, Some(1), "Keep"); + assert_eq!(tags.cover, None); + assert!(TagEdit::default().is_empty()); +} + +#[test] +fn set_all_mirrors_the_tags() { + let mut from = track("A", "X", 4); + from.cover = Some(png()); + let mut target = track("Other", "Y", 9); + target.genre = Some("Pop".into()); + TagEdit::set_all(&from).apply(&mut target); + assert_eq!(target.title, from.title); + assert_eq!(target.track_no, Some(4)); + assert_eq!(target.genre, None, "empty fields are cleared"); + assert_eq!(target.cover, Some(png())); +} diff --git a/crates/tunal-thumbs/Cargo.toml b/crates/tunal-thumbs/Cargo.toml index 6296b9d..856b388 100644 --- a/crates/tunal-thumbs/Cargo.toml +++ b/crates/tunal-thumbs/Cargo.toml @@ -12,3 +12,6 @@ lofty.workspace = true md-5.workspace = true png.workspace = true mime_guess.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/tunal-thumbs/tests/fixtures/clip.mp4 b/crates/tunal-thumbs/tests/fixtures/clip.mp4 new file mode 100644 index 0000000..e545f59 Binary files /dev/null and b/crates/tunal-thumbs/tests/fixtures/clip.mp4 differ diff --git a/crates/tunal-thumbs/tests/fixtures/cover.flac b/crates/tunal-thumbs/tests/fixtures/cover.flac new file mode 100644 index 0000000..c383be0 Binary files /dev/null and b/crates/tunal-thumbs/tests/fixtures/cover.flac differ diff --git a/crates/tunal-thumbs/tests/fixtures/photo.jpg b/crates/tunal-thumbs/tests/fixtures/photo.jpg new file mode 100644 index 0000000..529cb7d Binary files /dev/null and b/crates/tunal-thumbs/tests/fixtures/photo.jpg differ diff --git a/crates/tunal-thumbs/tests/fixtures/photo.png b/crates/tunal-thumbs/tests/fixtures/photo.png new file mode 100644 index 0000000..b9ab8fd Binary files /dev/null and b/crates/tunal-thumbs/tests/fixtures/photo.png differ diff --git a/crates/tunal-thumbs/tests/fixtures/t.mp3 b/crates/tunal-thumbs/tests/fixtures/t.mp3 new file mode 100644 index 0000000..d1ad5a3 Binary files /dev/null and b/crates/tunal-thumbs/tests/fixtures/t.mp3 differ diff --git a/crates/tunal-thumbs/tests/fixtures/vector.svg b/crates/tunal-thumbs/tests/fixtures/vector.svg new file mode 100644 index 0000000..28fbdce --- /dev/null +++ b/crates/tunal-thumbs/tests/fixtures/vector.svg @@ -0,0 +1 @@ + diff --git a/crates/tunal-thumbs/tests/no_ffmpeg.rs b/crates/tunal-thumbs/tests/no_ffmpeg.rs new file mode 100644 index 0000000..2b7666e --- /dev/null +++ b/crates/tunal-thumbs/tests/no_ffmpeg.rs @@ -0,0 +1,43 @@ +//! Own test binary: `ffmpeg_available` is cached per process, so PATH must be emptied before +//! its first use. + +use std::sync::mpsc; +use std::time::Duration; + +use tunal_thumbs::{Config, Outcome, Priority, Request, Skip, ThumbSize, Thumbnailer}; + +#[test] +fn video_without_ffmpeg_is_unsupported_and_not_a_failure() { + let dir = tempfile::tempdir().unwrap(); + let empty = dir.path().join("bin"); + std::fs::create_dir(&empty).unwrap(); + unsafe { + std::env::set_var("PATH", &empty); + std::env::set_var("XDG_CACHE_HOME", dir.path().join("cache")); + } + assert!(!tunal_thumbs::ffmpeg_available()); + + let video = dir.path().join("clip.mp4"); + std::fs::copy( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/clip.mp4"), + &video, + ) + .unwrap(); + let t = Thumbnailer::new(Config { + workers: 1, + ..Config::default() + }); + let (tx, rx) = mpsc::channel(); + t.request(Request { + path: video, + size: ThumbSize::Normal, + priority: Priority::Normal, + remote: false, + done: Box::new(move |o| tx.send(o).unwrap()), + }); + assert_eq!( + rx.recv_timeout(Duration::from_secs(30)).unwrap(), + Outcome::Skipped(Skip::Unsupported) + ); + assert!(!tunal_thumbs::thumbnail_dir().join("fail").exists()); +} diff --git a/crates/tunal-thumbs/tests/thumbs.rs b/crates/tunal-thumbs/tests/thumbs.rs new file mode 100644 index 0000000..167bde3 --- /dev/null +++ b/crates/tunal-thumbs/tests/thumbs.rs @@ -0,0 +1,471 @@ +//! Thumbnail cache naming, metadata, each generator and the request pool. +//! `XDG_CACHE_HOME` is process-global, so every test holds one lock and uses a temp cache. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::mpsc; +use std::sync::{Mutex, MutexGuard}; +use std::time::Duration; + +use tunal_thumbs::{ + Config, Outcome, Priority, Request, Skip, ThumbSize, Thumbnailer, cache_path, ffmpeg_available, + thumbnail_dir, +}; + +static LOCK: Mutex<()> = Mutex::new(()); + +struct Env { + _guard: MutexGuard<'static, ()>, + dir: tempfile::TempDir, +} + +impl Env { + fn new() -> Self { + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = tempfile::tempdir().unwrap(); + unsafe { std::env::set_var("XDG_CACHE_HOME", dir.path().join("cache")) }; + Self { _guard: guard, dir } + } + + /// Copies a fixture into the temp dir (the cache must not hold the source). + fn fixture(&self, name: &str) -> PathBuf { + let from = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(name); + let to = self.dir.path().join("files").join(name); + fs::create_dir_all(to.parent().unwrap()).unwrap(); + fs::copy(from, &to).unwrap(); + to + } +} + +fn request(t: &Thumbnailer, path: &Path, size: ThumbSize, remote: bool) -> Outcome { + request_with(t, path, size, remote, Priority::Normal) +} + +fn request_with( + t: &Thumbnailer, + path: &Path, + size: ThumbSize, + remote: bool, + priority: Priority, +) -> Outcome { + let (tx, rx) = mpsc::channel(); + t.request(Request { + path: path.to_owned(), + size, + priority, + remote, + done: Box::new(move |o| tx.send(o).unwrap()), + }); + rx.recv_timeout(Duration::from_secs(30)).unwrap() +} + +fn one_worker() -> Thumbnailer { + Thumbnailer::new(Config { + workers: 1, + ..Config::default() + }) +} + +/// PNG size and text chunks of a cached thumbnail. +fn read_png(path: &Path) -> (u32, u32, Vec<(String, String)>) { + let decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path).unwrap())); + let reader = decoder.read_info().unwrap(); + let info = reader.info(); + let texts = info + .uncompressed_latin1_text + .iter() + .map(|t| (t.keyword.clone(), t.text.clone())) + .collect(); + (info.width, info.height, texts) +} + +fn text<'a>(texts: &'a [(String, String)], key: &str) -> Option<&'a str> { + texts + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v.as_str()) +} + +#[test] +fn cache_dir_follows_xdg_cache_home() { + let env = Env::new(); + assert_eq!(thumbnail_dir(), env.dir.path().join("cache/thumbnails")); +} + +#[test] +fn cache_path_is_md5_of_the_percent_encoded_uri() { + let _env = Env::new(); + // Known vector: md5("file:///tmp/a%20b.png"). + let p = cache_path(Path::new("/tmp/a b.png"), ThumbSize::Normal); + assert_eq!(p.parent().unwrap(), thumbnail_dir().join("normal")); + let name = p.file_name().unwrap().to_str().unwrap(); + assert_eq!(name.len(), 32 + 4); + assert!(name.ends_with(".png")); + assert!(name[..32].bytes().all(|b| b.is_ascii_hexdigit())); + // The space is encoded, so it differs from the unencoded path's name. + assert_ne!(p, cache_path(Path::new("/tmp/a_b.png"), ThumbSize::Normal)); + // Same input, same name. + assert_eq!(p, cache_path(Path::new("/tmp/a b.png"), ThumbSize::Normal)); +} + +#[test] +fn cache_path_known_digest() { + let _env = Env::new(); + // echo -n file:///tmp/foo.png | md5sum + let p = cache_path(Path::new("/tmp/foo.png"), ThumbSize::Large); + assert_eq!( + p.file_name().unwrap().to_str().unwrap(), + "418019d5c43b6ecae463ef70e4efe32a.png" + ); +} + +#[test] +fn size_directories_and_pixels() { + let _env = Env::new(); + let p = Path::new("/tmp/x.png"); + for (size, dir, px) in [ + (ThumbSize::Normal, "normal", 128), + (ThumbSize::Large, "large", 256), + (ThumbSize::XLarge, "x-large", 512), + ] { + assert_eq!(size.pixels(), px); + assert_eq!( + cache_path(p, size).parent().unwrap(), + thumbnail_dir().join(dir) + ); + } +} + +#[test] +fn raster_thumbnail_has_spec_metadata() { + let env = Env::new(); + let file = env.fixture("photo.png"); + let t = one_worker(); + let Outcome::Ready(png_path) = request(&t, &file, ThumbSize::Normal, false) else { + panic!("expected a thumbnail"); + }; + assert_eq!(png_path, cache_path(&file, ThumbSize::Normal)); + let (w, h, texts) = read_png(&png_path); + assert_eq!((w, h), (96, 64), "smaller than 128 is not enlarged"); + let meta = fs::metadata(&file).unwrap(); + assert_eq!( + text(&texts, "Thumb::URI").unwrap(), + format!("file://{}", file.display()) + ); + assert_eq!(text(&texts, "Thumb::Size").unwrap(), meta.len().to_string()); + let mtime = meta + .modified() + .unwrap() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + assert_eq!(text(&texts, "Thumb::MTime").unwrap(), mtime.to_string()); + assert!(text(&texts, "Software").unwrap().starts_with("Tunal ")); +} + +#[test] +fn raster_is_shrunk_to_the_requested_edge() { + let env = Env::new(); + let file = env.fixture("photo.jpg"); + // The fixture is 96x64; an image bigger than the edge is scaled down keeping aspect. + let big = env.dir.path().join("files/big.png"); + image::RgbaImage::from_pixel(400, 200, image::Rgba([200, 30, 30, 255])) + .save(&big) + .unwrap(); + let t = one_worker(); + let Outcome::Ready(p) = request(&t, &big, ThumbSize::Normal, false) else { + panic!() + }; + let (w, h, _) = read_png(&p); + assert_eq!((w, h), (128, 64)); + let Outcome::Ready(p) = request(&t, &file, ThumbSize::Normal, false) else { + panic!("jpeg thumbnail") + }; + assert_eq!(read_png(&p).0, 96); +} + +#[test] +fn svg_is_rendered_to_the_edge() { + let env = Env::new(); + let file = env.fixture("vector.svg"); + let t = one_worker(); + let Outcome::Ready(p) = request(&t, &file, ThumbSize::Normal, false) else { + panic!("svg thumbnail") + }; + // 40x20 scales up to 128 on the longest edge. + assert_eq!(read_png(&p).0, 128); + assert_eq!(read_png(&p).1, 64); +} + +#[test] +fn audio_cover_becomes_a_thumbnail_and_no_cover_is_skipped() { + let env = Env::new(); + let with = env.fixture("cover.flac"); + let without = env.fixture("t.mp3"); + let t = one_worker(); + let Outcome::Ready(p) = request(&t, &with, ThumbSize::Normal, false) else { + panic!("cover thumbnail") + }; + assert_eq!((read_png(&p).0, read_png(&p).1), (96, 64)); + assert_eq!( + request(&t, &without, ThumbSize::Normal, false), + Outcome::Skipped(Skip::Unsupported) + ); + // No cover is no failure: nothing is recorded. + assert!(!thumbnail_dir().join("fail").exists()); +} + +#[test] +fn video_frame_thumbnail() { + if !ffmpeg_available() { + eprintln!("skipped: no ffmpeg"); + return; + } + let env = Env::new(); + let file = env.fixture("clip.mp4"); + let t = one_worker(); + let Outcome::Ready(p) = request(&t, &file, ThumbSize::Normal, false) else { + panic!("video thumbnail") + }; + // ffmpeg scales to the edge, small frames included (the 64x48 fixture grows to 128x96). + assert_eq!((read_png(&p).0, read_png(&p).1), (128, 96)); +} + +#[test] +fn video_time_past_the_end_falls_back_to_first_frame() { + if !ffmpeg_available() { + return; + } + let env = Env::new(); + let file = env.fixture("clip.mp4"); + let t = Thumbnailer::new(Config { + workers: 1, + video_time: tunal_thumbs::VideoTime::Seconds(500.0), + ..Config::default() + }); + assert!(matches!( + request(&t, &file, ThumbSize::Normal, false), + Outcome::Ready(_) + )); +} + +#[test] +fn second_request_is_served_from_the_cache_until_the_file_changes() { + let env = Env::new(); + let file = env.fixture("photo.png"); + let t = one_worker(); + let Outcome::Ready(p) = request(&t, &file, ThumbSize::Normal, false) else { + panic!() + }; + let first = fs::metadata(&p).unwrap().modified().unwrap(); + std::thread::sleep(Duration::from_millis(20)); + assert_eq!( + request(&t, &file, ThumbSize::Normal, false), + Outcome::Ready(p.clone()) + ); + assert_eq!( + fs::metadata(&p).unwrap().modified().unwrap(), + first, + "not rewritten" + ); + + // A newer mtime makes the entry stale: it is regenerated. + let f = fs::File::options().write(true).open(&file).unwrap(); + f.set_modified(std::time::SystemTime::now() + Duration::from_secs(3600)) + .unwrap(); + drop(f); + assert_eq!( + request(&t, &file, ThumbSize::Normal, false), + Outcome::Ready(p.clone()) + ); + let (_, _, texts) = read_png(&p); + let stored: u64 = text(&texts, "Thumb::MTime").unwrap().parse().unwrap(); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + assert!(stored > now + 3000); +} + +#[test] +fn broken_image_fails_once_then_is_a_known_failure() { + let env = Env::new(); + let file = env.dir.path().join("files/broken.png"); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(&file, b"not a png at all").unwrap(); + let t = one_worker(); + assert!(matches!( + request(&t, &file, ThumbSize::Normal, false), + Outcome::Failed(_) + )); + assert_eq!( + request(&t, &file, ThumbSize::Normal, false), + Outcome::Skipped(Skip::KnownFailure) + ); + assert!(thumbnail_dir().join("fail").is_dir()); + // A changed file is tried again (and fails again, with a fresh record). + let f = fs::File::options().write(true).open(&file).unwrap(); + f.set_modified(std::time::SystemTime::now() + Duration::from_secs(60)) + .unwrap(); + drop(f); + assert!(matches!( + request(&t, &file, ThumbSize::Normal, false), + Outcome::Failed(_) + )); +} + +#[test] +fn skips() { + let env = Env::new(); + let file = env.fixture("photo.png"); + let text_file = env.dir.path().join("files/notes.txt"); + fs::write(&text_file, "hi").unwrap(); + + let t = one_worker(); + assert_eq!( + request(&t, &text_file, ThumbSize::Normal, false), + Outcome::Skipped(Skip::Unsupported) + ); + assert_eq!( + request(&t, &file, ThumbSize::Normal, true), + Outcome::Skipped(Skip::Remote) + ); + // A file inside the cache is never thumbnailed. + let inside = thumbnail_dir().join("normal/x.png"); + fs::create_dir_all(inside.parent().unwrap()).unwrap(); + fs::copy(&file, &inside).unwrap(); + assert_eq!( + request(&t, &inside, ThumbSize::Normal, false), + Outcome::Skipped(Skip::InCache) + ); + // A folder named like an image is unsupported, a missing file fails. + let dir = env.dir.path().join("files/dir.png"); + fs::create_dir_all(&dir).unwrap(); + assert_eq!( + request(&t, &dir, ThumbSize::Normal, false), + Outcome::Skipped(Skip::Unsupported) + ); + assert!(matches!( + request( + &t, + &env.dir.path().join("files/gone.png"), + ThumbSize::Normal, + false + ), + Outcome::Failed(_) + )); +} + +#[test] +fn remote_files_are_thumbnailed_when_allowed() { + let env = Env::new(); + let file = env.fixture("photo.png"); + let t = Thumbnailer::new(Config { + workers: 1, + allow_remote: true, + ..Config::default() + }); + assert!(matches!( + request(&t, &file, ThumbSize::Normal, true), + Outcome::Ready(_) + )); +} + +#[test] +fn size_limit_bounds_images_only() { + let env = Env::new(); + let file = env.fixture("photo.png"); + let t = Thumbnailer::new(Config { + workers: 1, + max_file_size: 10, + ..Config::default() + }); + assert_eq!( + request(&t, &file, ThumbSize::Normal, false), + Outcome::Skipped(Skip::TooLarge) + ); + // Audio is read in part only, so the limit does not apply. + let audio = env.fixture("cover.flac"); + assert!(matches!( + request(&t, &audio, ThumbSize::Normal, false), + Outcome::Ready(_) + )); +} + +#[test] +fn cancelled_ticket_gives_cancelled() { + let env = Env::new(); + let file = env.fixture("photo.png"); + // Block the only worker with a callback, so the second request stays queued. + let t = one_worker(); + let (gate_tx, gate_rx) = mpsc::channel::<()>(); + let (started_tx, started_rx) = mpsc::channel(); + t.request(Request { + path: file.clone(), + size: ThumbSize::Normal, + priority: Priority::Normal, + remote: false, + done: Box::new(move |_| { + started_tx.send(()).unwrap(); + let _ = gate_rx.recv(); + }), + }); + started_rx.recv_timeout(Duration::from_secs(30)).unwrap(); + let (tx, rx) = mpsc::channel(); + let ticket = t.request(Request { + path: file, + size: ThumbSize::Large, + priority: Priority::Normal, + remote: false, + done: Box::new(move |o| tx.send(o).unwrap()), + }); + ticket.cancel(); + gate_tx.send(()).unwrap(); + assert_eq!( + rx.recv_timeout(Duration::from_secs(30)).unwrap(), + Outcome::Cancelled + ); +} + +#[test] +fn higher_priority_runs_first() { + let env = Env::new(); + let file = env.fixture("photo.png"); + let t = one_worker(); + let (gate_tx, gate_rx) = mpsc::channel::<()>(); + let (started_tx, started_rx) = mpsc::channel(); + t.request(Request { + path: file.clone(), + size: ThumbSize::Normal, + priority: Priority::Normal, + remote: false, + done: Box::new(move |_| { + started_tx.send(()).unwrap(); + let _ = gate_rx.recv(); + }), + }); + started_rx.recv_timeout(Duration::from_secs(30)).unwrap(); + let (tx, rx) = mpsc::channel(); + for (label, priority) in [ + ("low", Priority::Low), + ("normal", Priority::Normal), + ("high", Priority::High), + ("high2", Priority::High), + ] { + let tx = tx.clone(); + t.request(Request { + path: file.clone(), + size: ThumbSize::XLarge, + priority, + remote: false, + done: Box::new(move |_| tx.send(label).unwrap()), + }); + } + gate_tx.send(()).unwrap(); + let order: Vec<_> = (0..4) + .map(|_| rx.recv_timeout(Duration::from_secs(30)).unwrap()) + .collect(); + assert_eq!(order, ["high", "high2", "normal", "low"]); +} diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 28d2a27..9900464 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -267,5 +267,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: press squeeze not drawn by software renderer (pressed == hover in PNGs); conflict/errors dialogs have no hook (not in matrix); single-sentence captions keep their periods; Material You pink-tinted surfaces kept (D-035) though unslop prefers neutral. - Later: Network settings "Keep alive" subtitle elides (Setting subtitle should wrap); settings scrollbar sits tight to the switches. +## S033 — Tests: thumbs, tags, MusicBrainz, player, ssh, SFTP, MTP +- Done: `tests/` in five crates with tiny ffmpeg-made fixtures (flac, mp3, ogg, m4a, wav, mp4, png, jpg, svg; ~160 KB) and four test-only ed25519 keys in `tunal-net/tests/fixtures`. `tunal-thumbs`: cache naming/metadata, raster/SVG/cover/video, skips, known failures, size limit, priority and cancel, ffmpeg-missing in its own test binary (the probe is cached per process). `tunal-tags`: read/write/Keep/Clear/cover on five formats, merge, `set_all`; MusicBrainz and Cover Art Archive against a localhost mock (query escaping, user agent, redirects, 1 s spacing shared by clients, 503/429 backoff, give-up after 4); track matching. `tunal-player`: decode + waveform buckets, cache, cancel (no audio device). `tunal-net`: ssh config, known_hosts, and SFTP against an in-process russh server (host key unknown/once/always/changed/revoked, key/password/passphrase auth, list/stat/read/write/mkdir/rename/delete/symlink, reconnect). `tunal-devices`: PTP containers, datasets, dates, and session flows on the replay transport. +- Bugs fixed (with regression tests): a wrong key passphrase was asked only once instead of up to three times (`tunal-net/src/auth.rs`); clearing the track number of an MP3 left `0` (ID3 "0/12") that read back as track 0 (`tunal-tags/src/io.rs`: a zero track/disc number reads as none). +- Verified: build, clippy -D warnings, fmt --check, `cargo test --workspace`. +- Not done: `MtpLocation`/`IosLocation` not driven (no replay hook through the location layer); keyboard-interactive auth and the ssh agent path untested; `Player` engine itself needs an audio device, only waveforms are tested; MusicBrainz backoff tests really sleep (~30 s total). +- Later: video thumbnails of frames smaller than the edge are enlarged by ffmpeg (images are not): cap with `scale=min(...)`. + ## Later -