use std::collections::BTreeMap; use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use proptest::prelude::*; use rcom::actions::{ EditorSession, EditorSessionValidationError, EntryMutationKind, EntryMutationNode, EntryMutationPlan, EntryMutationValidationError, EntryNameError, TrashRecord, TrashRecordValidationError, validate_entry_name, }; use rcom::domain::{Entry, EntryKind, HostAlias, Location, SourceId}; use rcom::operations::{EntryFingerprint, ItemId, PlanGeneration, PlanId}; use uuid::Uuid; fn fingerprint(kind: EntryKind) -> EntryFingerprint { EntryFingerprint::from(&Entry::new("snapshot", kind).with_metadata(Some(17), None, Some(0o600))) } fn create_plan( name: impl Into, ) -> Result { EntryMutationPlan::create( PlanId::new(10), PlanGeneration::new(2), EntryMutationKind::CreateFile, ItemId::new(1), Location::local("/work"), name, BTreeMap::new(), ) } fn rename_plan( name: impl Into, ) -> Result { EntryMutationPlan::rename( PlanId::new(11), PlanGeneration::new(3), ItemId::new(1), Location::local("/work/old"), fingerprint(EntryKind::File), name, BTreeMap::new(), ) } fn delete_plan( nodes: Vec, ) -> Result { EntryMutationPlan::new( PlanId::new(12), PlanGeneration::new(4), EntryMutationKind::Delete, Location::local("/work"), None, nodes, BTreeMap::new(), ) } fn valid_unicode_name() -> impl Strategy { prop::collection::vec( any::().prop_filter("valid Unix filename character", |character| { *character != '/' && *character != '\0' }), 1..32, ) .prop_map(|characters| characters.into_iter().collect::()) .prop_filter("dot components are not entry names", |name| { name != "." && name != ".." }) } fn unsafe_name() -> impl Strategy { prop_oneof![ Just(String::new()), Just("/absolute".into()), Just(".".into()), Just("..".into()), Just("name/".into()), Just("./name".into()), prop::collection::vec( prop_oneof![Just("safe"), Just(".."), Just("."), Just("name")], 2..8, ) .prop_map(|components| components.join("/")), ] } #[test] fn create_and_rename_capture_immutable_typed_snapshots() { let host = HostAlias::new("edge"); let endpoint = SourceId::Ssh(host.clone()); let parent = Location::ssh(host.clone(), "/srv/app"); let name = OsString::from("данные-⌘"); let mut epochs = BTreeMap::from([(endpoint.clone(), 41)]); let create = EntryMutationPlan::create( PlanId::new(1), PlanGeneration::new(2), EntryMutationKind::CreateDirectory, ItemId::new(3), parent.clone(), name.clone(), epochs.clone(), ) .expect("a normal Unicode name should be accepted"); epochs.insert(endpoint.clone(), 99); assert_eq!(create.id(), PlanId::new(1)); assert_eq!(create.generation(), PlanGeneration::new(2)); assert_eq!(create.kind(), EntryMutationKind::CreateDirectory); assert_eq!(create.source(), &parent); assert_eq!(create.destination(), Some(&parent.join(&name))); assert_eq!( create.endpoint_epochs(), &BTreeMap::from([(endpoint.clone(), 41)]) ); assert_eq!(create.endpoint_epoch(&endpoint), Some(41)); assert_eq!(create.nodes().len(), 1); assert_eq!(create.nodes()[0].id(), ItemId::new(3)); assert_eq!(create.nodes()[0].location(), &parent.join(&name)); assert_eq!(create.nodes()[0].relative_path(), Path::new(&name)); assert_eq!(create.nodes()[0].fingerprint(), None); let source = parent.join("old"); let source_fingerprint = fingerprint(EntryKind::Directory); let rename = EntryMutationPlan::rename( PlanId::new(4), PlanGeneration::new(5), ItemId::new(6), source.clone(), source_fingerprint.clone(), name.clone(), BTreeMap::from([(endpoint, 42)]), ) .expect("rename should preserve the remote typed endpoint"); assert_eq!(rename.kind(), EntryMutationKind::Rename); assert_eq!(rename.source(), &source); assert_eq!(rename.destination(), Some(&parent.join(name))); assert_eq!(rename.nodes()[0].location(), &source); assert_eq!(rename.nodes()[0].relative_path(), Path::new("old")); assert_eq!(rename.nodes()[0].fingerprint(), Some(&source_fingerprint)); } #[test] fn name_validation_distinguishes_empty_absolute_dot_and_parent() { assert_eq!( validate_entry_name(OsStr::new("")), Err(EntryNameError::Empty) ); assert_eq!( validate_entry_name(OsStr::new("/absolute")), Err(EntryNameError::Absolute) ); assert_eq!( validate_entry_name(OsStr::new(".")), Err(EntryNameError::CurrentDirectory) ); assert_eq!( validate_entry_name(OsStr::new("..")), Err(EntryNameError::ParentDirectory) ); assert_eq!( validate_entry_name(OsStr::new("one/two")), Err(EntryNameError::MultipleComponents) ); assert_eq!( validate_entry_name(OsStr::new("name/")), Err(EntryNameError::NotNormalComponent) ); } #[test] fn create_constructor_rejects_other_mutation_kinds_and_same_name_rename() { let result = EntryMutationPlan::create( PlanId::new(1), PlanGeneration::new(0), EntryMutationKind::Delete, ItemId::new(1), Location::local("/work"), "new", BTreeMap::new(), ); assert_eq!( result.unwrap_err(), EntryMutationValidationError::InvalidCreateKind ); assert_eq!( rename_plan("old").unwrap_err(), EntryMutationValidationError::SameSourceAndDestination ); } #[test] fn generic_create_validation_rejects_mixed_endpoints_and_parents() { let source = Location::local("/work"); let remote = Location::ssh(HostAlias::new("edge"), "/work/new"); let remote_node = EntryMutationNode::new(ItemId::new(1), remote.clone(), "new", None); let mixed_endpoint = EntryMutationPlan::new( PlanId::new(1), PlanGeneration::new(0), EntryMutationKind::CreateFile, source.clone(), Some(remote), vec![remote_node], BTreeMap::new(), ); assert_eq!( mixed_endpoint.unwrap_err(), EntryMutationValidationError::MixedEndpoints ); let other_parent = Location::local("/other/new"); let node = EntryMutationNode::new(ItemId::new(1), other_parent.clone(), "new", None); let mixed_parent = EntryMutationPlan::new( PlanId::new(1), PlanGeneration::new(0), EntryMutationKind::CreateFile, source, Some(other_parent), vec![node], BTreeMap::new(), ); assert_eq!( mixed_parent.unwrap_err(), EntryMutationValidationError::MixedParents ); } #[test] fn generic_rename_validation_rejects_mixed_endpoints_and_parents() { let host = HostAlias::new("edge"); let source = Location::ssh(host.clone(), "/work/old"); let node = EntryMutationNode::new( ItemId::new(1), source.clone(), "old", Some(fingerprint(EntryKind::File)), ); let mixed_endpoint = EntryMutationPlan::new( PlanId::new(1), PlanGeneration::new(0), EntryMutationKind::Rename, source.clone(), Some(Location::local("/work/new")), vec![node.clone()], BTreeMap::new(), ); assert_eq!( mixed_endpoint.unwrap_err(), EntryMutationValidationError::MixedEndpoints ); let mixed_parent = EntryMutationPlan::new( PlanId::new(1), PlanGeneration::new(0), EntryMutationKind::Rename, source, Some(Location::ssh(host, "/other/new")), vec![node], BTreeMap::new(), ); assert_eq!( mixed_parent.unwrap_err(), EntryMutationValidationError::MixedParents ); } #[test] fn mutation_plan_rejects_missing_nodes_and_missing_fingerprints() { assert_eq!( delete_plan(Vec::new()).unwrap_err(), EntryMutationValidationError::EmptyNodes ); let node = EntryMutationNode::new(ItemId::new(1), Location::local("/work/file"), "file", None); assert_eq!( delete_plan(vec![node]).unwrap_err(), EntryMutationValidationError::MissingFingerprint ); let traversal = EntryMutationNode::new( ItemId::new(1), Location::local("/outside"), "../outside", Some(fingerprint(EntryKind::File)), ); assert_eq!( delete_plan(vec![traversal]).unwrap_err(), EntryMutationValidationError::InvalidRelativePath ); } #[test] fn trash_record_preserves_restore_identity_and_epoch() { let host = HostAlias::new("edge"); let original = Location::ssh(host.clone(), "/srv/file"); let trashed = Location::ssh(host, "/home/user/.local/share/Trash/files/id"); let original_fingerprint = fingerprint(EntryKind::File); let id = Uuid::from_u128(0x1234); let record = TrashRecord::new( original.clone(), trashed.clone(), original_fingerprint.clone(), 73, id, ) .expect("same-endpoint trash metadata should be valid"); assert_eq!(record.original(), &original); assert_eq!(record.trashed(), &trashed); assert_eq!(record.fingerprint(), &original_fingerprint); assert_eq!(record.epoch(), 73); assert_eq!(record.id(), id); } #[test] fn trash_record_rejects_cross_endpoint_and_identity() { let original = Location::local("/work/file"); let fingerprint = fingerprint(EntryKind::File); let id = Uuid::from_u128(1); assert_eq!( TrashRecord::new( original.clone(), Location::ssh(HostAlias::new("edge"), "/tmp/file"), fingerprint.clone(), 0, id, ) .unwrap_err(), TrashRecordValidationError::MixedEndpoints ); assert_eq!( TrashRecord::new(original.clone(), original, fingerprint, 0, id).unwrap_err(), TrashRecordValidationError::SameLocation ); } #[test] fn editor_session_retains_remote_source_owned_path_fingerprint_and_epoch() { let remote = Location::ssh(HostAlias::new("edge"), "/srv/файл"); let temporary = PathBuf::from("/tmp/rcom-owned/файл"); let original = fingerprint(EntryKind::File); let session = EditorSession::new(remote.clone(), temporary.clone(), original.clone(), 81) .expect("an SSH regular file and absolute local path should be valid"); assert_eq!(session.remote_source(), &remote); assert_eq!(session.local_temporary(), temporary.as_path()); assert_eq!(session.original_fingerprint(), &original); assert_eq!(session.epoch(), 81); } #[test] fn editor_session_rejects_local_non_regular_and_unsafe_temporary_inputs() { let remote = Location::ssh(HostAlias::new("edge"), "/srv/file"); let regular = fingerprint(EntryKind::File); assert_eq!( EditorSession::new( Location::local("/work/file"), "/tmp/rcom-owned/file", regular.clone(), 1, ) .unwrap_err(), EditorSessionValidationError::RemoteSourceRequired ); assert_eq!( EditorSession::new( remote.clone(), "/tmp/rcom-owned/file", fingerprint(EntryKind::Directory), 1, ) .unwrap_err(), EditorSessionValidationError::RegularFileRequired ); assert_eq!( EditorSession::new(remote, "relative/file", regular, 1).unwrap_err(), EditorSessionValidationError::TemporaryPathMustBeAbsolute ); } proptest! { #[test] fn unicode_names_are_preserved_by_create_and_rename(name in valid_unicode_name()) { let os_name = OsString::from(name.clone()); let create = create_plan(os_name.clone()).expect("one Unicode component should be valid"); let rename = rename_plan(os_name.clone()).expect("one Unicode component should be valid"); prop_assert_eq!(create.destination().and_then(Location::file_name), Some(OsStr::new(&name))); prop_assert_eq!(rename.destination().and_then(Location::file_name), Some(OsStr::new(&name))); prop_assert_eq!(create.nodes()[0].relative_path(), Path::new(&name)); } #[test] fn create_and_rename_reject_path_traversal_and_multi_component_names(name in unsafe_name()) { prop_assert!(create_plan(name.clone()).is_err()); prop_assert!(rename_plan(name).is_err()); } #[test] fn mutation_plan_order_is_independent_of_listing_sort_order( names in prop::collection::vec(valid_unicode_name(), 1..32), ) { let source = Location::local("/work"); let nodes: Vec<_> = names .iter() .enumerate() .map(|(index, name)| { EntryMutationNode::new( ItemId::new(index as u64), source.join(name), PathBuf::from(name), Some(fingerprint(EntryKind::File)), ) }) .collect(); let reversed = nodes.iter().rev().cloned().collect(); let forward_plan = delete_plan(nodes).expect("unique IDs and safe nodes should be valid"); let reversed_plan = delete_plan(reversed).expect("reversing input must not matter"); prop_assert_eq!(&forward_plan, &reversed_plan); prop_assert!(forward_plan.nodes().windows(2).all(|pair| pair[0].id() < pair[1].id())); } #[test] fn duplicate_node_ids_are_rejected_regardless_of_sort_order( names in prop::collection::vec(valid_unicode_name(), 2..32), reverse in any::(), ) { let source = Location::local("/work"); let mut nodes: Vec<_> = names .iter() .map(|name| { EntryMutationNode::new( ItemId::new(7), source.join(name), PathBuf::from(name), Some(fingerprint(EntryKind::File)), ) }) .collect(); if reverse { nodes.reverse(); } prop_assert_eq!( delete_plan(nodes).unwrap_err(), EntryMutationValidationError::DuplicateNodeId ); } } #[cfg(unix)] proptest! { #[test] fn unix_non_utf8_names_are_preserved_by_create_and_rename( bytes in prop::collection::vec(1u8..=u8::MAX, 1..32) .prop_filter("slash and dot components are not single names", |bytes| { !bytes.contains(&b'/') && bytes.as_slice() != b"." && bytes.as_slice() != b".." }), ) { use std::os::unix::ffi::OsStringExt; let name = OsString::from_vec(bytes.clone()); let create = create_plan(name.clone()).expect("a non-UTF-8 normal component should be valid"); let rename = rename_plan(name.clone()).expect("rename must not require UTF-8"); prop_assert_eq!(create.destination().and_then(Location::file_name), Some(name.as_os_str())); prop_assert_eq!(rename.destination().and_then(Location::file_name), Some(name.as_os_str())); prop_assert_eq!(create.nodes()[0].relative_path().as_os_str().as_encoded_bytes(), bytes.as_slice()); } }