diff --git a/crates/arena-core/tests/epic.rs b/crates/arena-core/tests/epic.rs new file mode 100644 index 0000000..347edfb --- /dev/null +++ b/crates/arena-core/tests/epic.rs @@ -0,0 +1,120 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Epic `.item` manifests: valid fixtures and the hostile ones that are Epic-specific. + +use arena_core::{CoverHint, Launch, ParseError, Source, WinPath, epic, limits}; + +#[test] +fn valid_item() { + let g = epic::item(include_bytes!("fixtures/epic/valid.item")).unwrap(); + assert_eq!(g.id.as_str(), "epic:exampleracer_main-01"); + assert_eq!(g.source, Source::Epic); + assert_eq!(g.title, "Example Racer"); + assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"C:\Program Files\Epic Games\ExampleRacer")); + assert_eq!(g.launch, Launch::Epic { app_name: "ExampleRacer_Main-01".into() }); + assert_eq!( + g.launch.uri().as_deref(), + Some("com.epicgames.launcher://apps/ExampleRacer_Main-01?action=launch&silent=true") + ); + assert!(matches!(g.cover, Some(CoverHint::Lettered { letter: 'E', .. })), "{:?}", g.cover); +} + +#[test] +fn bom_is_accepted() { + let mut bytes = vec![0xEF, 0xBB, 0xBF]; + bytes.extend_from_slice(include_bytes!("fixtures/epic/valid.item")); + assert!(epic::item(&bytes).is_ok()); +} + +#[test] +fn addon_is_not_a_game() { + let r = epic::item(include_bytes!("fixtures/epic/addon.item")); + assert!(matches!(r, Err(ParseError::NotAGame(_))), "{r:?}"); +} + +#[test] +fn wrong_type_app_name() { + assert_eq!(epic::item(include_bytes!("fixtures/epic/wrongtype.item")), Err(ParseError::WrongType("AppName"))); +} + +#[test] +fn wrong_type_for_each_field() { + let cases = [ + (r#"{"AppName":"A","DisplayName":["x"],"InstallLocation":"C:\\G"}"#, "DisplayName"), + (r#"{"AppName":"A","DisplayName":"x","InstallLocation":{"a":1}}"#, "InstallLocation"), + (r#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G","MainGameAppName":7}"#, "MainGameAppName"), + (r#"{"AppName":null,"DisplayName":"x","InstallLocation":"C:\\G"}"#, "AppName"), + ]; + for (json, field) in cases { + assert_eq!(epic::item(json.as_bytes()), Err(ParseError::WrongType(field)), "{json}"); + } + assert_eq!(epic::item(b"[]"), Err(ParseError::WrongType("item"))); + assert_eq!(epic::item(b"\"text\""), Err(ParseError::WrongType("item"))); +} + +#[test] +fn duplicate_key() { + assert_eq!(epic::item(include_bytes!("fixtures/epic/dupkey.item")), Err(ParseError::Duplicate("AppName"))); +} + +#[test] +fn traversal_in_install_location() { + assert_eq!(epic::item(include_bytes!("fixtures/epic/traversal.item")), Err(ParseError::BadPath("InstallLocation"))); +} + +#[test] +fn unc_install_location() { + assert_eq!(epic::item(include_bytes!("fixtures/epic/unc.item")), Err(ParseError::BadPath("InstallLocation"))); +} + +#[test] +fn injected_app_name() { + assert_eq!(epic::item(include_bytes!("fixtures/epic/badappname.item")), Err(ParseError::BadId)); +} + +#[test] +fn app_name_rules() { + let long = "a".repeat(limits::MAX_EPIC_APP + 1); + for bad in ["", " A", "A B", "a.b", "a/b", "a%20", "a?b", "ä", long.as_str()] { + let json = format!(r#"{{"AppName":"{bad}","DisplayName":"x","InstallLocation":"C:\\G"}}"#); + assert_eq!(epic::item(json.as_bytes()), Err(ParseError::BadId), "{bad:?}"); + } + let ok = "A".repeat(limits::MAX_EPIC_APP); + let json = format!(r#"{{"AppName":"{ok}","DisplayName":"x","InstallLocation":"C:\\G"}}"#); + assert!(epic::item(json.as_bytes()).is_ok()); +} + +#[test] +fn missing_fields() { + assert_eq!(epic::item(include_bytes!("fixtures/epic/missing.item")), Err(ParseError::Missing("AppName"))); + assert_eq!(epic::item(br#"{"AppName":"A","InstallLocation":"C:\\G"}"#), Err(ParseError::Missing("DisplayName"))); + assert_eq!(epic::item(br#"{"AppName":"A","DisplayName":"x"}"#), Err(ParseError::Missing("InstallLocation"))); +} + +#[test] +fn trailing_garbage() { + assert!(matches!(epic::item(include_bytes!("fixtures/epic/trailing.item")), Err(ParseError::Syntax { .. }))); +} + +#[test] +fn absurd_number() { + let r = epic::item(include_bytes!("fixtures/epic/absurd.item")); + assert!(matches!(r, Err(ParseError::Syntax { .. }) | Err(ParseError::WrongType("AppName"))), "{r:?}"); +} + +#[test] +fn syntax_error_offset_points_into_the_input() { + let json = b"{\n \"AppName\": \"A\",\n oops\n}"; + match epic::item(json) { + Err(ParseError::Syntax { at }) => assert!(at < json.len(), "{at}"), + other => panic!("{other:?}"), + } +} + +#[test] +fn main_game_equal_to_app_name_is_a_game() { + let json = br#"{"AppName":"A","MainGameAppName":"A","DisplayName":"x","InstallLocation":"C:\\G"}"#; + assert!(epic::item(json).is_ok()); +} diff --git a/crates/arena-core/tests/fixtures/epic/absurd.item b/crates/arena-core/tests/fixtures/epic/absurd.item new file mode 100644 index 0000000..b258722 --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/absurd.item @@ -0,0 +1,6 @@ +{ + "FormatVersion": 0, + "DisplayName": "Absurd Number", + "InstallLocation": "C:\Games\Absurd", + "AppName": 1e999999 +} diff --git a/crates/arena-core/tests/fixtures/epic/addon.item b/crates/arena-core/tests/fixtures/epic/addon.item new file mode 100644 index 0000000..32c6eb8 --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/addon.item @@ -0,0 +1,7 @@ +{ + "FormatVersion": 0, + "DisplayName": "Example Racer - Bonus Cars", + "InstallLocation": "C:\Program Files\Epic Games\ExampleRacer", + "AppName": "ExampleRacerBonusCars", + "MainGameAppName": "ExampleRacer_Main-01" +} diff --git a/crates/arena-core/tests/fixtures/epic/badappname.item b/crates/arena-core/tests/fixtures/epic/badappname.item new file mode 100644 index 0000000..2c18832 --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/badappname.item @@ -0,0 +1,5 @@ +{ + "DisplayName": "Injected", + "InstallLocation": "C:\Games\Injected", + "AppName": "x?action=uninstall&a=../../" +} diff --git a/crates/arena-core/tests/fixtures/epic/dupkey.item b/crates/arena-core/tests/fixtures/epic/dupkey.item new file mode 100644 index 0000000..c92b489 --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/dupkey.item @@ -0,0 +1,6 @@ +{ + "DisplayName": "Twice", + "InstallLocation": "C:\Games\Twice", + "AppName": "TwiceA", + "AppName": "TwiceB" +} diff --git a/crates/arena-core/tests/fixtures/epic/missing.item b/crates/arena-core/tests/fixtures/epic/missing.item new file mode 100644 index 0000000..64a76b6 --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/missing.item @@ -0,0 +1,4 @@ +{ + "DisplayName": "No App Name", + "InstallLocation": "C:\Games\NoAppName" +} diff --git a/crates/arena-core/tests/fixtures/epic/trailing.item b/crates/arena-core/tests/fixtures/epic/trailing.item new file mode 100644 index 0000000..c1dd1d5 --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/trailing.item @@ -0,0 +1,5 @@ +{ + "DisplayName": "Trailing", + "InstallLocation": "C:\Games\Trailing", + "AppName": "Trailing" +} {"AppName": "Second"} diff --git a/crates/arena-core/tests/fixtures/epic/traversal.item b/crates/arena-core/tests/fixtures/epic/traversal.item new file mode 100644 index 0000000..04c2771 --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/traversal.item @@ -0,0 +1,5 @@ +{ + "DisplayName": "Escape Artist", + "InstallLocation": "C:\Games\..\Windows\System32", + "AppName": "EscapeArtist" +} diff --git a/crates/arena-core/tests/fixtures/epic/unc.item b/crates/arena-core/tests/fixtures/epic/unc.item new file mode 100644 index 0000000..131faa6 --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/unc.item @@ -0,0 +1,5 @@ +{ + "DisplayName": "Remote", + "InstallLocation": "\\evil-server\share\Game", + "AppName": "Remote" +} diff --git a/crates/arena-core/tests/fixtures/epic/valid.item b/crates/arena-core/tests/fixtures/epic/valid.item new file mode 100644 index 0000000..d794eac --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/valid.item @@ -0,0 +1,26 @@ +{ + "FormatVersion": 0, + "bIsIncompleteInstall": false, + "LaunchCommand": "", + "LaunchExecutable": "ExampleRacer/Binaries/Win64/ExampleRacer.exe", + "ManifestLocation": "C:\ProgramData\Epic\EpicGamesLauncher\Data\Manifests", + "bIsApplication": true, + "bIsExecutable": true, + "bIsManaged": false, + "bNeedsValidation": false, + "bRequiresAuth": true, + "bCanRunOffline": true, + "DisplayName": "Example Racer", + "InstallationGuid": "00000000000000000000000000000001", + "InstallLocation": "C:\Program Files\Epic Games\ExampleRacer", + "CatalogNamespace": "example", + "CatalogItemId": "00000000000000000000000000000002", + "AppName": "ExampleRacer_Main-01", + "AppVersionString": "1.0.0", + "MainGameCatalogNamespace": "example", + "MainGameCatalogItemId": "00000000000000000000000000000002", + "MainGameAppName": "ExampleRacer_Main-01", + "AppCategories": ["public", "games", "applications"], + "ExpectingDLCInstalled": {}, + "InstallTags": [] +} diff --git a/crates/arena-core/tests/fixtures/epic/wrongtype.item b/crates/arena-core/tests/fixtures/epic/wrongtype.item new file mode 100644 index 0000000..aa7aa21 --- /dev/null +++ b/crates/arena-core/tests/fixtures/epic/wrongtype.item @@ -0,0 +1,5 @@ +{ + "DisplayName": "Wrong Type", + "InstallLocation": "C:\Games\WrongType", + "AppName": 12345 +} diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_1234560.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_1234560.acf new file mode 100644 index 0000000..6b13a3a --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_1234560.acf @@ -0,0 +1,33 @@ +"AppState" +{ + "appid" "1234560" + "universe" "1" + "LauncherPath" "C:\Program Files (x86)\Steam\steam.exe" + "name" "Example Quest: The \"Quoted\" Edition" + "StateFlags" "4" + "installdir" "Example Quest" + "LastUpdated" "0" + "SizeOnDisk" "1000" + "StagingSize" "0" + "buildid" "1" + "LastOwner" "0" + "AutoUpdateBehavior" "0" + "AllowOtherDownloadsWhileRunning" "0" + "ScheduledAutoUpdate" "0" + "InstalledDepots" + { + "1234561" + { + "manifest" "1" + "size" "1000" + } + } + "UserConfig" + { + "language" "english" + } + "MountedConfig" + { + "language" "english" + } +} diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_228980.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_228980.acf new file mode 100644 index 0000000..ac03a59 --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_228980.acf @@ -0,0 +1,8 @@ +"AppState" +{ + "appid" "228980" + "universe" "1" + "name" "Steamworks Common Redistributables" + "StateFlags" "4" + "installdir" "Steamworks Shared" +} diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_absolute.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_absolute.acf new file mode 100644 index 0000000..2d3c18c --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_absolute.acf @@ -0,0 +1,6 @@ +"AppState" +{ + "appid" "1234571" + "name" "Somewhere Else" + "installdir" "C:\Windows" +} diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_absurd.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_absurd.acf new file mode 100644 index 0000000..c277219 --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_absurd.acf @@ -0,0 +1,6 @@ +"AppState" +{ + "appid" "99999999999999999999999999" + "name" "Absurd" + "installdir" "Absurd" +} diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_dupkey.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_dupkey.acf new file mode 100644 index 0000000..3701e5a --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_dupkey.acf @@ -0,0 +1,7 @@ +"AppState" +{ + "appid" "1234573" + "name" "First Name" + "installdir" "Twice" + "Name" "Second Name" +} diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_traversal.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_traversal.acf new file mode 100644 index 0000000..8fcdde2 --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_traversal.acf @@ -0,0 +1,6 @@ +"AppState" +{ + "appid" "1234570" + "name" "Escape Artist" + "installdir" "..\..\..\Windows\System32" +} diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_unterminated.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_unterminated.acf new file mode 100644 index 0000000..75434b8 --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_unterminated.acf @@ -0,0 +1,5 @@ +"AppState" +{ + "appid" "1234574" + "name" "Never Ends +} diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_wrongtype.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_wrongtype.acf new file mode 100644 index 0000000..04ddf14 --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_wrongtype.acf @@ -0,0 +1,9 @@ +"AppState" +{ + "appid" + { + "value" "1234572" + } + "name" "Wrong Type" + "installdir" "Wrong Type" +} diff --git a/crates/arena-core/tests/fixtures/steam/libraryfolders.vdf b/crates/arena-core/tests/fixtures/steam/libraryfolders.vdf new file mode 100644 index 0000000..e7f9aa0 --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/libraryfolders.vdf @@ -0,0 +1,30 @@ +"libraryfolders" +{ + "0" + { + "path" "C:\Program Files (x86)\Steam" + "label" "" + "contentid" "1111111111111111111" + "totalsize" "0" + "update_clean_bytes_tally" "0" + "time_last_update_verified" "0" + "apps" + { + "228980" "0" + "1234560" "1000" + } + } + "1" + { + "path" "D:\SteamLibrary" + "label" "Games" + "contentid" "2222222222222222222" + "totalsize" "1000000000000" + "update_clean_bytes_tally" "0" + "time_last_update_verified" "0" + "apps" + { + "7654320" "2000" + } + } +} diff --git a/crates/arena-core/tests/fixtures/steam/libraryfolders_dup.vdf b/crates/arena-core/tests/fixtures/steam/libraryfolders_dup.vdf new file mode 100644 index 0000000..7d2d726 --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/libraryfolders_dup.vdf @@ -0,0 +1,11 @@ +"libraryfolders" +{ + "0" + { + "path" "D:\SteamLibrary" + } + "1" + { + "path" "d:\steamlibrary\\" + } +} diff --git a/crates/arena-core/tests/fixtures/steam/libraryfolders_old.vdf b/crates/arena-core/tests/fixtures/steam/libraryfolders_old.vdf new file mode 100644 index 0000000..e00b0d2 --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/libraryfolders_old.vdf @@ -0,0 +1,8 @@ +// An older Steam layout: numbered keys hold the path directly. +"LibraryFolders" +{ + "TimeNextStatsReport" "0" + "ContentStatsID" "-1" + "1" "D:\SteamLibrary" + "2" "E:/Games/Steam" +} diff --git a/crates/arena-core/tests/fixtures/steam/libraryfolders_unc.vdf b/crates/arena-core/tests/fixtures/steam/libraryfolders_unc.vdf new file mode 100644 index 0000000..7683d08 --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/libraryfolders_unc.vdf @@ -0,0 +1,7 @@ +"libraryfolders" +{ + "0" + { + "path" "\\evil-server\share\Steam" + } +} diff --git a/crates/arena-core/tests/fixtures/steam/libraryfolders_wrongtype.vdf b/crates/arena-core/tests/fixtures/steam/libraryfolders_wrongtype.vdf new file mode 100644 index 0000000..d0b899a --- /dev/null +++ b/crates/arena-core/tests/fixtures/steam/libraryfolders_wrongtype.vdf @@ -0,0 +1,10 @@ +"libraryfolders" +{ + "0" + { + "path" + { + "drive" "C:" + } + } +} diff --git a/crates/arena-core/tests/gog.rs b/crates/arena-core/tests/gog.rs new file mode 100644 index 0000000..44b5aae --- /dev/null +++ b/crates/arena-core/tests/gog.rs @@ -0,0 +1,147 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! GOG entries built from registry values the app passes in. + +use arena_core::gog::{GogEntry, game}; +use arena_core::{Launch, ParseError, Source, WinPath, limits}; + +fn entry() -> GogEntry { + GogEntry { + game_id: "1207658924".into(), + name: "Example Saga".into(), + path: r"C:\GOG Games\Example Saga".into(), + exe: r"C:\GOG Games\Example Saga\bin\x64\saga.exe".into(), + working_dir: Some(r"C:\GOG Games\Example Saga\bin\x64".into()), + launch_params: Some(r#"-skipintro "-profile=Slot One""#.into()), + } +} + +fn exe_parts(l: &Launch) -> (&str, &str, Vec<&str>) { + match l { + Launch::Exe { exe, working_dir, args } => { + (exe.as_str(), working_dir.as_str(), args.iter().map(String::as_str).collect()) + } + other => panic!("{other:?}"), + } +} + +#[test] +fn valid_entry() { + let g = game(&entry()).unwrap(); + assert_eq!(g.id.as_str(), "gog:1207658924"); + assert_eq!(g.source, Source::Gog); + assert_eq!(g.title, "Example Saga"); + assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"C:\GOG Games\Example Saga")); + let (exe, wd, args) = exe_parts(&g.launch); + assert_eq!(exe, r"C:\GOG Games\Example Saga\bin\x64\saga.exe"); + assert_eq!(wd, r"C:\GOG Games\Example Saga\bin\x64"); + assert_eq!(args, ["-skipintro", "-profile=Slot One"]); + assert_eq!(g.launch.uri(), None, "an exe launch has no URI"); +} + +#[test] +fn relative_exe_and_defaults() { + let mut e = entry(); + e.exe = r"bin\x64\saga.exe".into(); + e.working_dir = Some(String::new()); + e.launch_params = Some(" ".into()); + let g = game(&e).unwrap(); + let (exe, wd, args) = exe_parts(&g.launch); + assert_eq!(exe, r"C:\GOG Games\Example Saga\bin\x64\saga.exe"); + assert_eq!(wd, r"C:\GOG Games\Example Saga\bin\x64"); + assert!(args.is_empty()); + + e.working_dir = None; + e.launch_params = None; + let g = game(&e).unwrap(); + let (_, wd, args) = exe_parts(&g.launch); + assert_eq!(wd, r"C:\GOG Games\Example Saga\bin\x64"); + assert!(args.is_empty()); + + e.working_dir = Some("data".into()); + let g = game(&e).unwrap(); + let (_, wd, _) = exe_parts(&g.launch); + assert_eq!(wd, r"C:\GOG Games\Example Saga\data"); +} + +#[test] +fn bad_ids() { + for bad in ["", "abc", "12a", "-1", " 1", "123456789012345678901", "1.5"] { + let mut e = entry(); + e.game_id = bad.into(); + assert_eq!(game(&e), Err(ParseError::BadId), "{bad:?}"); + } + let mut e = entry(); + e.game_id = "1".repeat(limits::MAX_GOG_ID); + assert!(game(&e).is_ok()); +} + +#[test] +fn bad_paths() { + let cases: [(&str, &str, &str); 9] = [ + (r"\\server\share\Game", r"\\server\share\Game\g.exe", "path"), + (r"C:\GOG Games\..\Windows", r"C:\Windows\g.exe", "path"), + (r"relative\Game", r"relative\Game\g.exe", "path"), + (r"C:\GOG Games\Example Saga", r"C:\Windows\System32\cmd.exe", "exe"), + (r"C:\GOG Games\Example Saga", r"..\..\Windows\System32\cmd.exe", "exe"), + (r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga\run.bat", "exe"), + (r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga\run.cmd", "exe"), + (r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga\game.exe.lnk", "exe"), + (r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga Evil\g.exe", "exe"), + ]; + for (path, exe, field) in cases { + let mut e = entry(); + e.path = path.into(); + e.exe = exe.into(); + e.working_dir = None; + assert_eq!(game(&e), Err(ParseError::BadPath(field)), "{path} {exe}"); + } + let mut e = entry(); + e.working_dir = Some(r"\\?\C:\x".into()); + assert_eq!(game(&e), Err(ParseError::BadPath("working_dir"))); +} + +#[test] +fn exe_extension_ignores_case() { + let mut e = entry(); + e.exe = r"C:\GOG Games\Example Saga\SAGA.EXE".into(); + assert!(game(&e).is_ok()); +} + +#[test] +fn bad_args() { + for bad in ["a\u{0}b", "a\nb", "a\rb", "\"unclosed", "a\u{7}"] { + let mut e = entry(); + e.launch_params = Some(bad.into()); + assert_eq!(game(&e), Err(ParseError::BadValue("launch_params")), "{bad:?}"); + } + let mut e = entry(); + e.launch_params = Some(vec!["-a"; limits::MAX_ARGS + 1].join(" ")); + assert_eq!(game(&e), Err(ParseError::TooMany("args"))); + e.launch_params = Some("x".repeat(limits::MAX_ARG + 1)); + assert_eq!(game(&e), Err(ParseError::TooLong("arg"))); + e.launch_params = Some("x ".repeat(limits::MAX_ARGS_LINE)); + assert_eq!(game(&e), Err(ParseError::TooLong("launch_params"))); +} + +#[test] +fn shell_metacharacters_stay_inside_one_argument() { + let mut e = entry(); + e.launch_params = Some(r#""a & calc" |b ^c %PATH%"#.into()); + let g = game(&e).unwrap(); + let (_, _, args) = exe_parts(&g.launch); + assert_eq!(args, ["a & calc", "|b", "^c", "%PATH%"]); +} + +#[test] +fn bad_title() { + let mut e = entry(); + e.name = " ".into(); + assert_eq!(game(&e), Err(ParseError::Missing("name"))); + e.name = "x".repeat(limits::MAX_TITLE + 1); + assert_eq!(game(&e), Err(ParseError::TooLong("name"))); + e.name = "a\u{1b}[31mred".into(); + assert_eq!(game(&e), Err(ParseError::BadValue("name"))); +} diff --git a/crates/arena-core/tests/hostile.rs b/crates/arena-core/tests/hostile.rs new file mode 100644 index 0000000..b212f8d --- /dev/null +++ b/crates/arena-core/tests/hostile.rs @@ -0,0 +1,323 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Hostile input across every parser: refused with a typed error, never a panic. + +use arena_core::gog::GogEntry; +use arena_core::limits::{MAX_DEPTH, MAX_ENTRIES, MAX_ESCAPES, MAX_FILE, MAX_KEY, MAX_VALUE}; +use arena_core::{ParseError, WinPath, epic, gog, manual, steam, vdf}; + +fn lib() -> WinPath { + WinPath::parse(r"D:\SteamLibrary").unwrap() +} + +const FIXTURES: [&[u8]; 23] = [ + include_bytes!("fixtures/steam/libraryfolders.vdf"), + include_bytes!("fixtures/steam/libraryfolders_old.vdf"), + include_bytes!("fixtures/steam/libraryfolders_wrongtype.vdf"), + include_bytes!("fixtures/steam/libraryfolders_unc.vdf"), + include_bytes!("fixtures/steam/libraryfolders_dup.vdf"), + include_bytes!("fixtures/steam/appmanifest_1234560.acf"), + include_bytes!("fixtures/steam/appmanifest_228980.acf"), + include_bytes!("fixtures/steam/appmanifest_traversal.acf"), + include_bytes!("fixtures/steam/appmanifest_absolute.acf"), + include_bytes!("fixtures/steam/appmanifest_wrongtype.acf"), + include_bytes!("fixtures/steam/appmanifest_dupkey.acf"), + include_bytes!("fixtures/steam/appmanifest_absurd.acf"), + include_bytes!("fixtures/steam/appmanifest_unterminated.acf"), + include_bytes!("fixtures/epic/valid.item"), + include_bytes!("fixtures/epic/addon.item"), + include_bytes!("fixtures/epic/wrongtype.item"), + include_bytes!("fixtures/epic/dupkey.item"), + include_bytes!("fixtures/epic/traversal.item"), + include_bytes!("fixtures/epic/unc.item"), + include_bytes!("fixtures/epic/badappname.item"), + include_bytes!("fixtures/epic/missing.item"), + include_bytes!("fixtures/epic/trailing.item"), + include_bytes!("fixtures/epic/absurd.item"), +]; + +/// Runs every byte parser over `input`; any panic fails the test. +fn all_parsers(input: &[u8]) { + let _ = vdf::tokenize(input); + let _ = vdf::parse(input); + let _ = steam::library_folders(input); + let _ = steam::app_manifest(input, &lib()); + let _ = epic::item(input); +} + +// ---- huge files ------------------------------------------------------------------------------------------- + +#[test] +fn huge_file_is_refused_before_parsing() { + let mut big = b"\"AppState\" { \"appid\" \"10\" \"name\" \"N\" \"installdir\" \"N\" }".to_vec(); + big.resize(MAX_FILE + 1, b' '); + assert_eq!(vdf::tokenize(&big), Err(ParseError::TooLarge)); + assert_eq!(vdf::parse(&big), Err(ParseError::TooLarge)); + assert_eq!(steam::library_folders(&big), Err(ParseError::TooLarge)); + assert_eq!(steam::app_manifest(&big, &lib()), Err(ParseError::TooLarge)); + + let mut json = br#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G"}"#.to_vec(); + json.resize(MAX_FILE + 1, b' '); + assert_eq!(epic::item(&json), Err(ParseError::TooLarge)); +} + +#[test] +fn exactly_max_file_is_still_read() { + let mut ok = b"\"AppState\" { \"appid\" \"10\" \"name\" \"N\" \"installdir\" \"N\" }".to_vec(); + ok.resize(MAX_FILE, b' '); + assert!(steam::app_manifest(&ok, &lib()).is_ok()); +} + +// ---- deep nesting ----------------------------------------------------------------------------------------- + +fn nested_vdf(depth: usize) -> Vec { + let mut s = Vec::new(); + for _ in 0..depth { + s.extend_from_slice(b"\"k\" { "); + } + for _ in 0..depth { + s.extend_from_slice(b"} "); + } + s +} + +#[test] +fn deep_vdf_is_refused() { + assert!(vdf::parse(&nested_vdf(MAX_DEPTH)).is_ok()); + assert_eq!(vdf::parse(&nested_vdf(MAX_DEPTH + 1)), Err(ParseError::TooDeep)); + // Far deeper than any stack would survive with naive recursion. + assert_eq!(vdf::parse(&nested_vdf(100_000)), Err(ParseError::TooDeep)); + assert_eq!(steam::library_folders(&nested_vdf(5_000)), Err(ParseError::TooDeep)); +} + +#[test] +fn deep_json_is_refused() { + let deep = |n: usize| { + let mut s = String::from(r#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G","Deep":"#); + s.push_str(&"[".repeat(n)); + s.push_str(&"]".repeat(n)); + s.push('}'); + s + }; + assert!(epic::item(deep(MAX_DEPTH - 1).as_bytes()).is_ok()); + assert_eq!(epic::item(deep(MAX_DEPTH).as_bytes()), Err(ParseError::TooDeep)); + assert_eq!(epic::item(deep(200_000).as_bytes()), Err(ParseError::TooDeep)); + // Brackets inside strings do not count. + let in_string = format!(r#"{{"AppName":"A","DisplayName":"{}","InstallLocation":"C:\\G"}}"#, "[".repeat(200)); + assert!(epic::item(in_string.as_bytes()).is_ok()); +} + +// ---- wrong types ------------------------------------------------------------------------------------------ + +#[test] +fn wrong_types_everywhere() { + let acf = |body: &str| format!("\"AppState\" {{ {body} }}"); + let cases = [ + (acf("\"appid\" { } \"name\" \"N\" \"installdir\" \"N\""), "appid"), + (acf("\"appid\" \"10\" \"name\" { } \"installdir\" \"N\""), "name"), + (acf("\"appid\" \"10\" \"name\" \"N\" \"installdir\" { }"), "installdir"), + ("\"AppState\" \"text\"".to_string(), "AppState"), + ]; + for (text, field) in cases { + assert_eq!(steam::app_manifest(text.as_bytes(), &lib()), Err(ParseError::WrongType(field)), "{text}"); + } + assert_eq!( + steam::library_folders(b"\"libraryfolders\" { \"0\" { \"path\" { } } }"), + Err(ParseError::WrongType("path")) + ); +} + +// ---- bad paths -------------------------------------------------------------------------------------------- + +#[test] +fn bad_library_paths() { + for bad in [r"..\\Steam", r"C:\\Steam\\..\\..\\Windows", r"\\\\?\\C:\\Steam", r"Steam", "C:\\\\CON", "C:"] { + let text = format!("\"libraryfolders\" {{ \"0\" {{ \"path\" \"{bad}\" }} }}"); + assert_eq!(steam::library_folders(text.as_bytes()), Err(ParseError::BadPath("path")), "{bad}"); + } +} + +#[test] +fn bad_paths_in_every_source() { + let r = epic::item(include_bytes!("fixtures/epic/traversal.item")); + assert_eq!(r, Err(ParseError::BadPath("InstallLocation"))); + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_traversal.acf"), &lib()); + assert_eq!(r, Err(ParseError::BadPath("installdir"))); + let e = GogEntry { + game_id: "1".into(), + name: "G".into(), + path: r"C:\G\..\..".into(), + exe: r"C:\g.exe".into(), + working_dir: None, + launch_params: None, + }; + assert_eq!(gog::game(&e), Err(ParseError::BadPath("path"))); + assert_eq!(manual::game(r"C:\G\..\g.exe", None), Err(ParseError::BadPath("exe"))); +} + +// ---- non-UTF-8 -------------------------------------------------------------------------------------------- + +#[test] +fn non_utf8_names_are_refused() { + let mut acf = b"\"AppState\" { \"appid\" \"10\" \"name\" \"Bad ".to_vec(); + acf.extend_from_slice(&[0xC3, 0x28, 0xFF]); + acf.extend_from_slice(b"\" \"installdir\" \"N\" }"); + assert_eq!(vdf::tokenize(&acf), Err(ParseError::NotUtf8)); + assert_eq!(steam::app_manifest(&acf, &lib()), Err(ParseError::NotUtf8)); + + let mut key = b"\"AppState\" { \"".to_vec(); + key.extend_from_slice(&[0xED, 0xA0, 0x80]); // an encoded surrogate + key.extend_from_slice(b"\" \"x\" }"); + assert_eq!(steam::app_manifest(&key, &lib()), Err(ParseError::NotUtf8)); + + let mut json = br#"{"AppName":"A","DisplayName":""#.to_vec(); + json.extend_from_slice(&[0x80, 0x80]); + json.extend_from_slice(br#"","InstallLocation":"C:\\G"}"#); + assert_eq!(epic::item(&json), Err(ParseError::NotUtf8)); + + // Outside a string too. + assert_eq!(epic::item(&[b'{', 0xFF, b'}']), Err(ParseError::NotUtf8)); +} + +#[test] +fn bytes_outside_strings_are_refused_too() { + assert_eq!(vdf::tokenize(&[0xFF]), Err(ParseError::NotUtf8)); + assert_eq!(vdf::tokenize(&[&b"\"a\" \"b\" // comment "[..], &[0xFF]].concat()), Err(ParseError::NotUtf8)); +} + +// ---- NUL and control bytes -------------------------------------------------------------------------------- + +#[test] +fn nul_bytes_are_refused() { + assert_eq!(vdf::tokenize(b"\"a\0b\" \"c\""), Err(ParseError::Syntax { at: 2 })); + assert_eq!(vdf::tokenize(b"\"a\" \0 \"c\""), Err(ParseError::Syntax { at: 4 })); + assert!(matches!(epic::item(b"{\"AppName\":\"A\0\"}"), Err(ParseError::Syntax { .. }))); + let json = br#"{"AppName":"A","DisplayName":"x\u0000y","InstallLocation":"C:\\G"}"#; + assert_eq!(epic::item(json), Err(ParseError::BadValue("DisplayName"))); + let json = br#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G\u0000"}"#; + assert_eq!(epic::item(json), Err(ParseError::BadPath("InstallLocation"))); +} + +#[test] +fn raw_control_characters_in_vdf_strings_are_refused() { + for b in [0x01u8, 0x07, 0x0A, 0x0D, 0x1B, 0x7F] { + let input = [b'"', b'a', b, b'"']; + assert_eq!(vdf::tokenize(&input), Err(ParseError::Syntax { at: 2 }), "{b:#x}"); + } + assert!(vdf::tokenize(b"\"a\tb\"").is_ok(), "a raw tab is allowed"); +} + +// ---- unterminated ----------------------------------------------------------------------------------------- + +#[test] +fn unterminated_strings_and_objects() { + assert_eq!(vdf::tokenize(b"\"abc"), Err(ParseError::Syntax { at: 0 })); + assert_eq!(vdf::tokenize(b"\"a\" \"b"), Err(ParseError::Syntax { at: 4 })); + assert!(matches!(vdf::parse(b"\"a\" { \"b\" \"c\""), Err(ParseError::Syntax { .. }))); + assert!(matches!(epic::item(br#"{"AppName":"A"#), Err(ParseError::Syntax { .. }))); + assert!(matches!(epic::item(b"{"), Err(ParseError::Syntax { .. }))); + assert!(matches!(epic::item(b""), Err(ParseError::Syntax { .. }))); +} + +// ---- duplicates ------------------------------------------------------------------------------------------- + +#[test] +fn duplicate_keys_and_ids() { + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_dupkey.acf"), &lib()); + assert_eq!(r, Err(ParseError::Duplicate("key"))); + let r = + steam::library_folders(b"\"libraryfolders\" { \"0\" { \"path\" \"C:\\\\A\" } \"0\" { \"path\" \"C:\\\\B\" } }"); + assert_eq!(r, Err(ParseError::Duplicate("key"))); + let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_dup.vdf")); + assert_eq!(r, Err(ParseError::Duplicate("path"))); + assert_eq!(epic::item(include_bytes!("fixtures/epic/dupkey.item")), Err(ParseError::Duplicate("AppName"))); + let json = br#"{"AppName":"A","DisplayName":"x","DisplayName":"y","InstallLocation":"C:\\G"}"#; + assert_eq!(epic::item(json), Err(ParseError::Duplicate("DisplayName"))); +} + +// ---- caps on lengths, counts, escapes --------------------------------------------------------------------- + +#[test] +fn long_keys_and_values() { + let key = format!("\"{}\" \"v\"", "k".repeat(MAX_KEY + 1)); + assert_eq!(vdf::parse(key.as_bytes()), Err(ParseError::TooLong("key"))); + let key_ok = format!("\"{}\" \"v\"", "k".repeat(MAX_KEY)); + assert!(vdf::parse(key_ok.as_bytes()).is_ok()); + let value = format!("\"k\" \"{}\"", "v".repeat(MAX_VALUE + 1)); + assert_eq!(vdf::parse(value.as_bytes()), Err(ParseError::TooLong("value"))); + assert_eq!(vdf::tokenize(value.as_bytes()), Err(ParseError::TooLong("value"))); + let value_ok = format!("\"k\" \"{}\"", "v".repeat(MAX_VALUE)); + assert!(vdf::parse(value_ok.as_bytes()).is_ok()); +} + +#[test] +fn too_many_escapes() { + let s = format!("\"k\" \"{}\"", "\\\\".repeat(MAX_ESCAPES + 1)); + assert_eq!(vdf::tokenize(s.as_bytes()), Err(ParseError::TooMany("escapes"))); + let ok = format!("\"k\" \"{}\"", "\\\\".repeat(MAX_ESCAPES)); + assert!(vdf::tokenize(ok.as_bytes()).is_ok()); +} + +#[test] +fn too_many_entries() { + let mut s = String::from("\"root\" {\n"); + for i in 0..MAX_ENTRIES { + s.push_str(&format!("\"{i}\" \"\"\n")); + } + s.push_str("}\n"); + assert!(s.len() <= MAX_FILE, "the test document must fit the file cap"); + assert_eq!(vdf::parse(s.as_bytes()), Err(ParseError::TooMany("entries"))); +} + +#[test] +fn absurd_numbers() { + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_absurd.acf"), &lib()); + assert_eq!(r, Err(ParseError::BadId)); + let r = epic::item(include_bytes!("fixtures/epic/absurd.item")); + assert!(r.is_err()); + let e = GogEntry { + game_id: "9".repeat(10_000), + name: "G".into(), + path: r"C:\G".into(), + exe: r"C:\G\g.exe".into(), + working_dir: None, + launch_params: None, + }; + assert_eq!(gog::game(&e), Err(ParseError::BadId)); +} + +#[test] +fn huge_strings_into_value_builders() { + let huge = "a".repeat(10 * MAX_FILE); + assert!(manual::game(&huge, None).is_err()); + assert!(manual::game(r"C:\G\g.exe", Some(&huge)).is_err()); + assert!(WinPath::parse(&huge).is_err()); + assert!(huge.parse::().is_err()); +} + +// ---- never panics ----------------------------------------------------------------------------------------- + +#[test] +fn every_truncation_of_every_fixture() { + for f in FIXTURES { + for end in 0..=f.len() { + all_parsers(&f[..end]); + } + } +} + +#[test] +fn every_single_byte_corruption_of_every_fixture() { + let replacements = [0x00u8, b'"', b'\\', b'{', b'}', b'[', b']', b':', b',', 0xFF, 0xC3, b'\n']; + for f in FIXTURES { + for i in 0..f.len() { + for &r in &replacements { + let mut m = f.to_vec(); + m[i] = r; + all_parsers(&m); + } + } + } +} diff --git a/crates/arena-core/tests/launch.rs b/crates/arena-core/tests/launch.rs new file mode 100644 index 0000000..8a085dd --- /dev/null +++ b/crates/arena-core/tests/launch.rs @@ -0,0 +1,222 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Launch strings contain only parsed, validated fields: nothing raw from a file reaches a URI or an argument. + +use arena_core::gog::GogEntry; +use arena_core::{Launch, ParseError, WinPath, epic, gog, limits, steam}; +use proptest::prelude::*; + +fn is_epic_app(s: &str) -> bool { + !s.is_empty() + && s.len() <= limits::MAX_EPIC_APP + && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') +} + +fn is_domi_id(s: &str) -> bool { + !s.is_empty() + && s.len() <= limits::MAX_DOMI_ID + && !s.starts_with('-') + && !s.ends_with('-') + && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +/// The URI is exactly the template filled with the field, and the field passes its rule. +fn check_uri(l: &Launch) { + let uri = l.uri(); + match l { + Launch::SteamRunGameId(id) => { + assert_eq!(uri, (*id != 0).then(|| format!("steam://rungameid/{id}"))); + } + Launch::Epic { app_name } => { + let want = is_epic_app(app_name) + .then(|| format!("com.epicgames.launcher://apps/{app_name}?action=launch&silent=true")); + assert_eq!(uri, want, "{app_name:?}"); + } + Launch::DomiLink { app } => { + assert_eq!(uri, is_domi_id(app).then(|| format!("domi-{app}://open")), "{app:?}"); + } + Launch::Exe { .. } => assert_eq!(uri, None), + Launch::Url(u) => { + if let Some(got) = &uri { + assert_eq!(got, u); + assert!(got.starts_with("https://")); + assert!(got.bytes().all(|b| b.is_ascii_graphic() && b != b'\\' && b != b'"'), "{got:?}"); + } + } + } +} + +#[test] +fn fixture_uris_are_templates_of_parsed_fields() { + let lib = WinPath::parse(r"D:\SteamLibrary").unwrap(); + let s = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_1234560.acf"), &lib).unwrap(); + check_uri(&s.launch); + assert_eq!(s.launch.uri().unwrap(), "steam://rungameid/1234560"); + + let e = epic::item(include_bytes!("fixtures/epic/valid.item")).unwrap(); + check_uri(&e.launch); + assert_eq!(e.launch.uri().unwrap(), "com.epicgames.launcher://apps/ExampleRacer_Main-01?action=launch&silent=true"); +} + +#[test] +fn hand_built_bad_values_give_no_uri() { + let bad = [ + Launch::SteamRunGameId(0), + Launch::Epic { app_name: String::new() }, + Launch::Epic { app_name: "Fortnite?action=uninstall".into() }, + Launch::Epic { app_name: "a/../../b".into() }, + Launch::Epic { app_name: "a b".into() }, + Launch::Epic { app_name: "a".repeat(65) }, + Launch::DomiLink { app: "Lapilli".into() }, + Launch::DomiLink { app: "x://evil".into() }, + Launch::DomiLink { app: "-x".into() }, + Launch::Url("javascript:alert(1)".into()), + Launch::Url("http://example.org/".into()), + Launch::Url("https://example.org/a b".into()), + Launch::Url("https://user@example.org/".into()), + Launch::Url("file:///C:/Windows/System32/calc.exe".into()), + ]; + for l in &bad { + assert_eq!(l.uri(), None, "{l:?}"); + assert_eq!(l.uri_checked(&["example.org"]), None, "{l:?}"); + check_uri(l); + } + let exe = Launch::Exe { + exe: WinPath::parse(r"C:\G\g.exe").unwrap(), + working_dir: WinPath::parse(r"C:\G").unwrap(), + args: vec![], + }; + assert_eq!(exe.uri(), None); +} + +#[test] +fn url_needs_allowed_host_when_checked() { + let l = Launch::web("https://games.example.org/x", &["games.example.org"]).unwrap(); + assert_eq!(l.uri_checked(&["GAMES.example.org"]).as_deref(), Some("https://games.example.org/x")); + assert_eq!(l.uri_checked(&[]), None); + assert_eq!(Launch::web("https://games.example.org/x", &[]), Err(ParseError::BadValue("url"))); +} + +#[test] +fn builders_validate() { + assert_eq!(Launch::steam(0), Err(ParseError::BadId)); + assert_eq!(Launch::steam(10).unwrap(), Launch::SteamRunGameId(10)); + assert_eq!(Launch::epic("a?b"), Err(ParseError::BadId)); + assert_eq!(Launch::domi_link("A"), Err(ParseError::BadId)); + let exe = WinPath::parse(r"C:\G\g.exe").unwrap(); + let dir = WinPath::parse(r"C:\G").unwrap(); + assert_eq!( + Launch::exe(WinPath::parse(r"C:\G\g.bat").unwrap(), dir.clone(), vec![]), + Err(ParseError::BadPath("exe")) + ); + assert_eq!(Launch::exe(exe.clone(), dir.clone(), vec!["a\u{0}".into()]), Err(ParseError::BadValue("args"))); + assert_eq!(Launch::exe(exe.clone(), dir.clone(), vec!["a\nb".into()]), Err(ParseError::BadValue("args"))); + assert_eq!( + Launch::exe(exe.clone(), dir.clone(), vec!["x".repeat(limits::MAX_ARG + 1)]), + Err(ParseError::TooLong("arg")) + ); + assert_eq!( + Launch::exe(exe.clone(), dir.clone(), vec![String::new(); limits::MAX_ARGS + 1]), + Err(ParseError::TooMany("args")) + ); + assert!(Launch::exe(exe, dir, vec!["--fine".into(), "with space".into()]).is_ok()); +} + +#[test] +fn gog_args_are_exactly_the_split_params() { + let e = GogEntry { + game_id: "1".into(), + name: "G".into(), + path: r"C:\G".into(), + exe: r"C:\G\g.exe".into(), + working_dir: None, + launch_params: Some(r#" -a "b c" d"#.into()), + }; + let g = gog::game(&e).unwrap(); + match g.launch { + Launch::Exe { args, .. } => assert_eq!(args, ["-a", "b c", "d"]), + other => panic!("{other:?}"), + } +} + +#[test] +fn deserialising_validates_every_field() { + let good = r#"{"epic":{"app_name":"Fortnite"}}"#; + assert_eq!(serde_json::from_str::(good).unwrap(), Launch::Epic { app_name: "Fortnite".into() }); + for bad in [ + r#"{"epic":{"app_name":"a?b"}}"#, + r#"{"steam_run_game_id":0}"#, + r#"{"steam_run_game_id":4294967296}"#, + r#"{"domi_link":{"app":"X"}}"#, + r#"{"url":"http://example.org/"}"#, + r#"{"exe":{"exe":"C:\\G\\g.bat","working_dir":"C:\\G","args":[]}}"#, + r#"{"exe":{"exe":"C:\\G\\..\\g.exe","working_dir":"C:\\G","args":[]}}"#, + r#"{"exe":{"exe":"C:\\G\\g.exe","working_dir":"C:\\G","args":["a\u0000"]}}"#, + ] { + assert!(serde_json::from_str::(bad).is_err(), "{bad}"); + } +} + +#[test] +fn serde_round_trip() { + let all = [ + Launch::steam(10).unwrap(), + Launch::epic("A_b-1").unwrap(), + Launch::domi_link("lapilli").unwrap(), + Launch::web("https://games.example.org/p?q=1", &["games.example.org"]).unwrap(), + Launch::exe(WinPath::parse(r"C:\G\g.exe").unwrap(), WinPath::parse(r"C:\G").unwrap(), vec!["-x".into()]) + .unwrap(), + ]; + for l in all { + let json = serde_json::to_string(&l).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), l, "{json}"); + } +} + +proptest! { + #[test] + fn epic_uri_only_from_valid_names(name in ".{0,80}") { + let l = Launch::Epic { app_name: name.clone() }; + check_uri(&l); + prop_assert_eq!(Launch::epic(&name).is_ok(), is_epic_app(&name)); + } + + #[test] + fn epic_uri_from_generated_valid_names(name in "[A-Za-z0-9_-]{1,64}") { + let l = Launch::epic(&name).unwrap(); + prop_assert_eq!(l.uri().unwrap(), format!("com.epicgames.launcher://apps/{name}?action=launch&silent=true")); + } + + #[test] + fn domi_uri_only_from_valid_ids(app in ".{0,40}") { + check_uri(&Launch::DomiLink { app }); + } + + #[test] + fn steam_uri_any_id(id in any::()) { + check_uri(&Launch::SteamRunGameId(id)); + } + + #[test] + fn url_uri_never_escapes_the_rules(url in "(https?://)?[a-zA-Z0-9.:@/?#%&=_ \\\\\"-]{0,60}") { + let l = Launch::Url(url); + check_uri(&l); + } + + #[test] + fn epic_manifest_app_name_reaches_uri_only_when_valid(name in "[ -~]{0,70}") { + let json = serde_json::json!({"AppName": name, "DisplayName": "x", "InstallLocation": "C:\\G"}).to_string(); + match epic::item(json.as_bytes()) { + Ok(g) => { + prop_assert!(is_epic_app(&name)); + prop_assert_eq!(g.launch.uri().unwrap(), format!("com.epicgames.launcher://apps/{name}?action=launch&silent=true")); + } + Err(e) => { + prop_assert!(!is_epic_app(&name)); + prop_assert_eq!(e, ParseError::BadId); + } + } + } +} diff --git a/crates/arena-core/tests/manual_domi.rs b/crates/arena-core/tests/manual_domi.rs new file mode 100644 index 0000000..d49d14e --- /dev/null +++ b/crates/arena-core/tests/manual_domi.rs @@ -0,0 +1,136 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Manual games (an `.exe` the user picked) and Domi games (Atrium registry entries). + +use arena_core::{CoverHint, DomiLaunch, Launch, ParseError, Source, WinPath, domi, limits, manual}; + +#[test] +fn manual_game() { + let g = manual::game(r"D:\Games\Old Thing\OldThing.exe", None).unwrap(); + assert_eq!(g.source, Source::Manual); + assert_eq!(g.title, "OldThing"); + assert!(g.id.as_str().starts_with("manual:")); + assert_eq!(g.id.native().len(), 16); + assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"D:\Games\Old Thing")); + match &g.launch { + Launch::Exe { exe, working_dir, args } => { + assert_eq!(exe.as_str(), r"D:\Games\Old Thing\OldThing.exe"); + assert_eq!(working_dir.as_str(), r"D:\Games\Old Thing"); + assert!(args.is_empty()); + } + other => panic!("{other:?}"), + } + assert!(matches!(g.cover, Some(CoverHint::Lettered { letter: 'O', hue }) if hue < 360)); +} + +#[test] +fn manual_id_is_stable_and_ignores_case_and_slashes() { + let a = manual::game(r"D:\Games\Old Thing\OldThing.exe", None).unwrap(); + let b = manual::game("d:/games/old thing/OLDTHING.EXE", Some("Renamed")).unwrap(); + assert_eq!(a.id, b.id); + assert_eq!(b.title, "Renamed"); + let c = manual::game(r"D:\Games\Other\OldThing.exe", None).unwrap(); + assert_ne!(a.id, c.id); +} + +#[test] +fn manual_refuses_bad_exe() { + for bad in [ + r"OldThing.exe", + r"\\server\share\x.exe", + r"\\?\C:\x.exe", + r"\\.\C:\x.exe", + r"C:\Games\..\Windows\x.exe", + r"C:\Games\run.bat", + r"C:\Games\run.cmd", + r"C:\", + r"C:\Games\CON.exe", + "C:\\Games\\x\u{0}.exe", + "", + ] { + assert_eq!(manual::game(bad, None), Err(ParseError::BadPath("exe")), "{bad:?}"); + } +} + +#[test] +fn manual_refuses_bad_title() { + assert_eq!(manual::game(r"C:\G\x.exe", Some(" ")), Err(ParseError::Missing("title"))); + assert_eq!(manual::game(r"C:\G\x.exe", Some("a\u{0}b")), Err(ParseError::BadValue("title"))); +} + +#[test] +fn domi_link_game() { + let g = domi::game("lapilli", "Lapilli", DomiLaunch::Link { app: "lapilli" }).unwrap(); + assert_eq!(g.id.as_str(), "domi:lapilli"); + assert_eq!(g.source, Source::Domi); + assert_eq!(g.title, "Lapilli"); + assert_eq!(g.install_dir, None); + assert_eq!(g.launch, Launch::DomiLink { app: "lapilli".into() }); + assert_eq!(g.launch.uri().as_deref(), Some("domi-lapilli://open")); +} + +#[test] +fn domi_web_game() { + let hosts = ["rosea.example.org", "moin.example.org"]; + let g = domi::game( + "rosea", + "Rosea", + DomiLaunch::Web { url: "HTTPS://Rosea.Example.org/play?x=1#top", allowed_hosts: &hosts }, + ) + .unwrap(); + assert_eq!(g.launch, Launch::Url("https://rosea.example.org/play?x=1#top".into())); + assert_eq!(g.launch.uri().as_deref(), Some("https://rosea.example.org/play?x=1#top")); + assert_eq!(g.launch.uri_checked(&hosts).as_deref(), Some("https://rosea.example.org/play?x=1#top")); + assert_eq!(g.launch.uri_checked(&["other.example.org"]), None); +} + +#[test] +fn domi_refuses_bad_ids() { + let long = "a".repeat(limits::MAX_DOMI_ID + 1); + for bad in ["", "-x", "x-", "X", "a_b", "a.b", "a b", "ä", long.as_str()] { + assert_eq!(domi::game(bad, "N", DomiLaunch::Link { app: "ok" }), Err(ParseError::BadId), "{bad:?}"); + assert_eq!(domi::game("ok", "N", DomiLaunch::Link { app: bad }), Err(ParseError::BadId), "{bad:?}"); + } + assert!(domi::game(&"a".repeat(limits::MAX_DOMI_ID), "N", DomiLaunch::Link { app: "a-1" }).is_ok()); +} + +#[test] +fn domi_refuses_bad_urls() { + let hosts = ["rosea.example.org"]; + let long = format!("https://rosea.example.org/{}", "a".repeat(limits::MAX_URL)); + for bad in [ + "http://rosea.example.org/", + "javascript:alert(1)", + "file:///C:/Windows/System32/calc.exe", + "https://evil.example.org/", + "https://rosea.example.org.evil.example/", + "https://sub.rosea.example.org/", + "https://user@rosea.example.org/", + "https://rosea.example.org:8443/", + "https://rosea.example.org/a b", + "https://rosea.example.org/a\\b", + "https://rosea.example.org/\u{0}", + "https://rosea.example.org/%zz", + "https://rosea.example.org/\"quote", + "https:///path", + "https://", + " https://rosea.example.org/", + "https://[::1]/", + "https://rosea..example.org/", + "https://-rosea.example.org/", + long.as_str(), + ] { + let r = domi::game("rosea", "Rosea", DomiLaunch::Web { url: bad, allowed_hosts: &hosts }); + assert!(matches!(r, Err(ParseError::BadValue("url")) | Err(ParseError::TooLong("url"))), "{bad:?}: {r:?}"); + } +} + +#[test] +fn domi_web_host_without_path() { + let hosts = ["moin.example.org"]; + let g = + domi::game("moin", "Moin", DomiLaunch::Web { url: "https://moin.example.org", allowed_hosts: &hosts }).unwrap(); + assert_eq!(g.launch.uri().as_deref(), Some("https://moin.example.org")); +} diff --git a/crates/arena-core/tests/merge.rs b/crates/arena-core/tests/merge.rs new file mode 100644 index 0000000..ac73a89 --- /dev/null +++ b/crates/arena-core/tests/merge.rs @@ -0,0 +1,153 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Dedupe and ordering in `merge`. + +use arena_core::{CoverHint, DomiLaunch, Game, GameId, Launch, Library, Source, WinPath, domi, gog, manual, merge}; + +fn game(source: Source, native: &str, title: &str, dir: Option<&str>) -> Game { + let id = GameId::new(source, native).unwrap(); + let launch = match source { + Source::Steam => Launch::steam(native.parse().unwrap()).unwrap(), + Source::Epic => Launch::epic(native).unwrap(), + Source::Domi => Launch::domi_link(native).unwrap(), + _ => { + let d = WinPath::parse(dir.unwrap()).unwrap(); + Launch::exe(d.join("g.exe").unwrap(), d, vec![]).unwrap() + } + }; + Game { + cover: Some(CoverHint::lettered(title, &id)), + id, + source, + title: title.into(), + install_dir: dir.map(|d| WinPath::parse(d).unwrap()), + launch, + } +} + +fn ids(lib: &Library) -> Vec<&str> { + lib.games.iter().map(|g| g.id.as_str()).collect() +} + +#[test] +fn same_id_kept_once_first_wins() { + let a = game(Source::Steam, "10", "Alpha", Some(r"D:\S\common\Alpha")); + let mut a2 = a.clone(); + a2.title = "Alpha (again)".into(); + let lib = merge(vec![vec![a.clone(), a2.clone()], vec![a2]]); + assert_eq!(lib.len(), 1); + assert_eq!(lib.games[0].title, "Alpha"); +} + +#[test] +fn same_install_dir_keeps_the_best_source() { + let dir = r"C:\Games\Shared"; + let steam = game(Source::Steam, "10", "Shared S", Some(dir)); + let epic = game(Source::Epic, "shared", "Shared E", Some(r"c:\games\SHARED")); + let gog = game(Source::Gog, "20", "Shared G", Some(dir)); + let man = game(Source::Manual, "0123456789abcdef", "Shared M", Some(dir)); + let lib = merge(vec![vec![man.clone()], vec![gog.clone()], vec![epic.clone()], vec![steam.clone()]]); + assert_eq!(ids(&lib), ["steam:10"]); + + let lib = merge(vec![vec![man.clone()], vec![gog.clone()], vec![epic.clone()]]); + assert_eq!(ids(&lib), ["epic:shared"]); + let lib = merge(vec![vec![man.clone(), gog.clone()]]); + assert_eq!(ids(&lib), ["gog:20"]); +} + +#[test] +fn domi_beats_manual_on_the_same_folder() { + let dir = r"C:\Domi\Lapilli"; + let mut d = domi::game("lapilli", "Lapilli", DomiLaunch::Link { app: "lapilli" }).unwrap(); + d.install_dir = Some(WinPath::parse(dir).unwrap()); + let m = manual::game(r"C:\Domi\Lapilli\lapilli.exe", None).unwrap(); + let lib = merge(vec![vec![m], vec![d]]); + assert_eq!(ids(&lib), ["domi:lapilli"]); +} + +#[test] +fn same_source_same_folder_keeps_both() { + let a = game(Source::Steam, "10", "A", Some(r"D:\S\common\X")); + let b = game(Source::Steam, "11", "B", Some(r"D:\S\common\X")); + let lib = merge(vec![vec![a, b]]); + assert_eq!(ids(&lib), ["steam:10", "steam:11"]); +} + +#[test] +fn no_install_dir_never_dedupes_by_folder() { + let a = domi::game("rosea", "Rosea", DomiLaunch::Link { app: "rosea" }).unwrap(); + let b = domi::game("moin", "Moin", DomiLaunch::Link { app: "moin" }).unwrap(); + let lib = merge(vec![vec![a], vec![b]]); + assert_eq!(ids(&lib), ["domi:moin", "domi:rosea"]); +} + +#[test] +fn different_folders_are_different_games() { + let a = game(Source::Steam, "10", "Same Title", Some(r"D:\S\common\X")); + let b = game(Source::Gog, "20", "Same Title", Some(r"C:\GOG Games\X")); + let lib = merge(vec![vec![a], vec![b]]); + assert_eq!(lib.len(), 2); +} + +#[test] +fn ordered_by_title_ignoring_case_then_id_and_independent_of_scan_order() { + let games = vec![ + game(Source::Steam, "30", "zeta", Some(r"D:\z")), + game(Source::Epic, "b", "Beta", Some(r"D:\b")), + game(Source::Gog, "1", "alpha", Some(r"D:\a1")), + game(Source::Steam, "2", "Alpha", Some(r"D:\a2")), + game(Source::Manual, "0123456789abcdef", "Ärger", Some(r"D:\ae")), + ]; + let forward = merge(vec![games.clone()]); + let mut rev = games.clone(); + rev.reverse(); + let backward = merge(vec![rev.into_iter().map(|g| vec![g]).collect::>().concat()]); + assert_eq!(forward, backward); + assert_eq!(ids(&forward), ["gog:1", "steam:2", "epic:b", "steam:30", "manual:0123456789abcdef"]); +} + +#[test] +fn library_lookup() { + let g = gog::game(&gog::GogEntry { + game_id: "5".into(), + name: "Five".into(), + path: r"C:\G5".into(), + exe: r"C:\G5\five.exe".into(), + working_dir: None, + launch_params: None, + }) + .unwrap(); + let lib = merge(vec![vec![g.clone()]]); + assert_eq!(lib.get(&"gog:5".parse().unwrap()), Some(&g)); + assert_eq!(lib.get(&"gog:6".parse().unwrap()), None); + assert!(merge(vec![]).is_empty()); +} + +#[test] +fn library_json_round_trip() { + let a = game(Source::Steam, "10", "Alpha", Some(r"D:\S\common\Alpha")); + let b = domi::game( + "rosea", + "Rosea", + DomiLaunch::Web { url: "https://rosea.example.org/", allowed_hosts: &["rosea.example.org"] }, + ) + .unwrap(); + let lib = merge(vec![vec![a, b]]); + let json = serde_json::to_string(&lib).unwrap(); + let back: Library = serde_json::from_str(&json).unwrap(); + assert_eq!(back, lib); +} + +#[test] +fn library_json_refuses_mismatched_or_bad_games() { + let a = game(Source::Steam, "10", "Alpha", Some(r"D:\S\common\Alpha")); + let json = serde_json::to_string(&Library { games: vec![a] }).unwrap(); + let wrong_source = json.replace(r#""source":"steam""#, r#""source":"epic""#); + assert!(serde_json::from_str::(&wrong_source).is_err()); + let bad_title = json.replace(r#""title":"Alpha""#, r#""title":"\u0000""#); + assert!(serde_json::from_str::(&bad_title).is_err()); + let bad_path = json.replace(r#"D:\\S\\common\\Alpha"#, r#"D:\\S\\..\\Alpha"#); + assert!(serde_json::from_str::(&bad_path).is_err()); +} diff --git a/crates/arena-core/tests/paths_ids.rs b/crates/arena-core/tests/paths_ids.rs new file mode 100644 index 0000000..21be83a --- /dev/null +++ b/crates/arena-core/tests/paths_ids.rs @@ -0,0 +1,190 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! `WinPath` and `GameId`: the two validated value types everything else is built from. + +use arena_core::{GameId, ParseError, Source, WinPath, limits}; + +fn p(s: &str) -> WinPath { + WinPath::parse(s).unwrap() +} + +#[test] +fn winpath_accepts_and_normalises() { + assert_eq!(p(r"C:\Games\X").as_str(), r"C:\Games\X"); + assert_eq!(p(r"c:\Games\X\").as_str(), r"C:\Games\X"); + assert_eq!(p("d:/Games//X/").as_str(), r"D:\Games\X"); + assert_eq!(p(r"C:\").as_str(), r"C:\"); + assert_eq!(p("C:/").as_str(), r"C:\"); + assert_eq!(p(r"C:\Program Files (x86)\Steam").as_str(), r"C:\Program Files (x86)\Steam"); + assert_eq!(p(r"C:\Hry\Příliš žluťoučký kůň").as_str(), r"C:\Hry\Příliš žluťoučký kůň"); + assert_eq!(p(r"C:\a.b\.hidden\x..y").as_str(), r"C:\a.b\.hidden\x..y"); + assert_eq!(p(r"C:\CONSOLE\NULL\COM10\LPT").as_str(), r"C:\CONSOLE\NULL\COM10\LPT"); +} + +#[test] +fn winpath_refuses() { + let long = format!(r"C:\{}", "a".repeat(limits::MAX_PATH)); + for bad in [ + "", + "C:", + "C:Games", + r"\Games", + "Games", + r"1:\x", + r"\\server\share", + r"\\?\C:\x", + r"\\.\C:\x", + r"\??\C:\x", + "//server/share", + r"C:\..", + r"C:\Games\..\Windows", + r"C:\Games\.\x", + "C:\\Games\\x\u{0}", + "C:\\Games\\x\ny", + "C:\\Games\\x\u{1f}", + r"C:\Games\x:stream", + r"C:\Games\a*b", + r"C:\Games\a?b", + r#"C:\Games\a"b"#, + r"C:\Games\ab", + r"C:\Games\a|b", + r"C:\CON", + r"C:\con.txt", + r"C:\Games\nul", + r"C:\Games\Aux.log", + r"C:\Games\prn", + r"C:\Games\COM1", + r"C:\Games\lpt9.dat", + r"C:\Games\COM¹", + r"C:\Games\CONIN$", + r"C:\Games\conout$", + r"C:\Games\NUL .txt", + r"C:\Games\trailing.", + r"C:\Games\trailing ", + long.as_str(), + ] { + assert!(matches!(WinPath::parse(bad), Err(ParseError::BadPath(_))), "{bad:?}"); + } +} + +#[test] +fn winpath_length_counts_utf16_units() { + let ok = format!(r"C:\{}", "a".repeat(limits::MAX_PATH - 3)); + assert!(WinPath::parse(&ok).is_ok()); + // One astral character is two UTF-16 units. + let astral = format!(r"C:\{}😀", "a".repeat(limits::MAX_PATH - 4)); + assert!(WinPath::parse(&astral).is_err()); +} + +#[test] +fn winpath_join_parent_file_name() { + let base = p(r"C:\Games"); + assert_eq!(base.join(r"A\b.exe").unwrap().as_str(), r"C:\Games\A\b.exe"); + assert_eq!(base.join("A/b.exe").unwrap().as_str(), r"C:\Games\A\b.exe"); + for bad in ["", r"..\x", r"A\..\..\x", r"\x", r"D:\x", "D:x", r"\\s\x", "a\u{0}"] { + assert!(base.join(bad).is_err(), "{bad:?}"); + } + assert_eq!(p(r"C:\Games\A").parent(), Some(p(r"C:\Games"))); + assert_eq!(p(r"C:\Games").parent(), Some(p(r"C:\"))); + assert_eq!(p(r"C:\").parent(), None); + assert_eq!(p(r"C:\Games\b.exe").file_name(), Some("b.exe")); + assert_eq!(p(r"C:\").file_name(), None); + assert_eq!(p(r"C:\a\b").components().collect::>(), ["a", "b"]); +} + +#[test] +fn winpath_join_respects_length() { + let base = p(r"C:\Games"); + assert!(base.join(&"a".repeat(limits::MAX_PATH)).is_err()); +} + +#[test] +fn winpath_compare_ignoring_case() { + assert!(p(r"C:\Games\X").eq_ignore_case(&p(r"c:\GAMES\x"))); + assert!(p(r"C:\Games\X\bin\x.exe").starts_with(&p(r"c:\games\x"))); + assert!(p(r"C:\Games\X").starts_with(&p(r"C:\Games\X"))); + assert!(p(r"C:\Games\X").starts_with(&p(r"C:\"))); + assert!(!p(r"C:\Games\XY").starts_with(&p(r"C:\Games\X"))); + assert!(!p(r"D:\Games\X").starts_with(&p(r"C:\Games"))); + assert!(!p(r"C:\Games").starts_with(&p(r"C:\Games\X"))); +} + +#[test] +fn winpath_serde_validates() { + let ok: WinPath = serde_json::from_str(r#""C:\\Games""#).unwrap(); + assert_eq!(ok.as_str(), r"C:\Games"); + assert!(serde_json::from_str::(r#""C:\\Games\\..\\x""#).is_err()); + assert_eq!(serde_json::to_string(&ok).unwrap(), r#""C:\\Games""#); +} + +#[test] +fn game_id_round_trip() { + for s in ["steam:1234560", "epic:exampleracer_main-01", "gog:1207658924", "manual:0123456789abcdef", "domi:lapilli"] + { + let id: GameId = s.parse().unwrap(); + assert_eq!(id.to_string(), s); + assert_eq!(id.source().as_str(), s.split(':').next().unwrap()); + assert_eq!(id.native(), s.split_once(':').unwrap().1); + } + assert_eq!(GameId::new(Source::Steam, "10").unwrap().as_str(), "steam:10"); + assert_eq!("epic:a".parse::().unwrap().source(), Source::Epic); +} + +#[test] +fn game_id_refuses() { + let long = format!("epic:{}", "a".repeat(limits::MAX_GAME_ID)); + for bad in [ + "", + "steam", + "steam:", + ":10", + "Steam:10", + "steam:0", + "steam:01", + "steam:4294967296", + "steam:-1", + "steam:1a", + "xbox:10", + "epic:A", + "epic:a.b", + "epic:a:b", + "gog:abc", + "gog:123456789012345678901", + "manual:0123", + "manual:0123456789ABCDEF", + "manual:0123456789abcdeg", + "domi:-x", + "domi:a_b", + "domi:../x", + "steam:10 ", + " steam:10", + "steam:10\u{0}", + long.as_str(), + ] { + assert_eq!(bad.parse::(), Err(ParseError::BadId), "{bad:?}"); + } + assert_eq!(GameId::new(Source::Gog, "x"), Err(ParseError::BadId)); +} + +#[test] +fn game_id_serde_validates() { + let id: GameId = serde_json::from_str(r#""steam:10""#).unwrap(); + assert_eq!(serde_json::to_string(&id).unwrap(), r#""steam:10""#); + assert!(serde_json::from_str::(r#""steam:../x""#).is_err()); +} + +#[test] +fn source_names() { + for s in Source::ALL { + assert_eq!(s.as_str().parse::().unwrap(), s); + assert_eq!(s.to_string(), s.as_str()); + } + assert!("Steam".parse::().is_err()); + assert!(Source::Steam.priority() > Source::Epic.priority()); + assert!(Source::Epic.priority() > Source::Gog.priority()); + assert!(Source::Gog.priority() > Source::Domi.priority()); + assert!(Source::Domi.priority() > Source::Manual.priority()); +} diff --git a/crates/arena-core/tests/steam.rs b/crates/arena-core/tests/steam.rs new file mode 100644 index 0000000..4872ef2 --- /dev/null +++ b/crates/arena-core/tests/steam.rs @@ -0,0 +1,181 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Steam: valid fixtures and the hostile ones that are Steam-specific. + +use arena_core::{CoverHint, Launch, ParseError, Source, WinPath, steam}; + +fn lib() -> WinPath { + WinPath::parse(r"D:\SteamLibrary").unwrap() +} + +#[test] +fn library_folders_current_layout() { + let dirs = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders.vdf")).unwrap(); + let dirs: Vec<&str> = dirs.iter().map(WinPath::as_str).collect(); + assert_eq!(dirs, [r"C:\Program Files (x86)\Steam", r"D:\SteamLibrary"]); +} + +#[test] +fn library_folders_old_layout() { + let dirs = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_old.vdf")).unwrap(); + let dirs: Vec<&str> = dirs.iter().map(WinPath::as_str).collect(); + assert_eq!(dirs, [r"D:\SteamLibrary", r"E:\Games\Steam"]); +} + +#[test] +fn library_folders_empty_root_is_empty_list() { + assert_eq!(steam::library_folders(b"\"libraryfolders\"\n{\n}\n").unwrap(), Vec::::new()); +} + +#[test] +fn library_folders_needs_the_root_key() { + assert_eq!(steam::library_folders(b"\"other\" { }"), Err(ParseError::Missing("libraryfolders"))); + assert_eq!(steam::library_folders(b"\"libraryfolders\" \"x\""), Err(ParseError::WrongType("libraryfolders"))); +} + +#[test] +fn library_folders_refuses_path_object() { + let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_wrongtype.vdf")); + assert_eq!(r, Err(ParseError::WrongType("path"))); +} + +#[test] +fn library_folders_refuses_missing_path() { + let r = steam::library_folders(b"\"libraryfolders\" { \"0\" { \"label\" \"\" } }"); + assert_eq!(r, Err(ParseError::Missing("path"))); +} + +#[test] +fn library_folders_refuses_unc() { + let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_unc.vdf")); + assert_eq!(r, Err(ParseError::BadPath("path"))); +} + +#[test] +fn library_folders_refuses_the_same_folder_twice() { + let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_dup.vdf")); + assert_eq!(r, Err(ParseError::Duplicate("path"))); +} + +#[test] +fn library_folders_caps_the_count() { + let mut s = String::from("\"libraryfolders\"\n{\n"); + for i in 0..=arena_core::limits::MAX_LIBRARIES { + s.push_str(&format!("\"{i}\" {{ \"path\" \"D:\\\\Lib{i}\" }}\n")); + } + s.push_str("}\n"); + assert_eq!(steam::library_folders(s.as_bytes()), Err(ParseError::TooMany("libraries"))); +} + +#[test] +fn app_manifest_valid() { + let g = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_1234560.acf"), &lib()).unwrap(); + assert_eq!(g.id.as_str(), "steam:1234560"); + assert_eq!(g.source, Source::Steam); + assert_eq!(g.title, "Example Quest: The \"Quoted\" Edition"); + assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"D:\SteamLibrary\steamapps\common\Example Quest")); + assert_eq!(g.launch, Launch::SteamRunGameId(1_234_560)); + assert_eq!(g.launch.uri().as_deref(), Some("steam://rungameid/1234560")); + assert_eq!(g.cover, Some(CoverHint::SteamLibraryCache { app_id: 1_234_560 })); +} + +#[test] +fn app_manifest_redistributable_is_not_a_game() { + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_228980.acf"), &lib()); + assert!(matches!(r, Err(ParseError::NotAGame(_))), "{r:?}"); + assert!(steam::is_tool(228_980)); + assert!(!steam::is_tool(1_234_560)); +} + +#[test] +fn app_manifest_refuses_traversal_in_installdir() { + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_traversal.acf"), &lib()); + assert_eq!(r, Err(ParseError::BadPath("installdir"))); +} + +#[test] +fn app_manifest_refuses_absolute_installdir() { + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_absolute.acf"), &lib()); + assert_eq!(r, Err(ParseError::BadPath("installdir"))); +} + +#[test] +fn app_manifest_refuses_appid_object() { + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_wrongtype.acf"), &lib()); + assert_eq!(r, Err(ParseError::WrongType("appid"))); +} + +#[test] +fn app_manifest_refuses_duplicate_keys_ignoring_case() { + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_dupkey.acf"), &lib()); + assert_eq!(r, Err(ParseError::Duplicate("key"))); +} + +#[test] +fn app_manifest_refuses_absurd_appid() { + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_absurd.acf"), &lib()); + assert_eq!(r, Err(ParseError::BadId)); +} + +#[test] +fn app_manifest_refuses_line_break_in_string() { + let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_unterminated.acf"), &lib()); + assert!(matches!(r, Err(ParseError::Syntax { .. })), "{r:?}"); +} + +#[test] +fn app_manifest_appid_rules() { + for bad in ["0", "-1", "+5", "01", " 5", "5 ", "4294967296", "1e3", "0x10", ""] { + let acf = format!("\"AppState\" {{ \"appid\" \"{bad}\" \"name\" \"N\" \"installdir\" \"N\" }}"); + assert_eq!(steam::app_manifest(acf.as_bytes(), &lib()), Err(ParseError::BadId), "appid {bad:?}"); + } + let acf = "\"AppState\" { \"appid\" \"4294967295\" \"name\" \"N\" \"installdir\" \"N\" }"; + assert_eq!(steam::app_manifest(acf.as_bytes(), &lib()).unwrap().launch, Launch::SteamRunGameId(u32::MAX)); +} + +#[test] +fn app_manifest_missing_fields() { + let no_name = "\"AppState\" { \"appid\" \"10\" \"installdir\" \"N\" }"; + assert_eq!(steam::app_manifest(no_name.as_bytes(), &lib()), Err(ParseError::Missing("name"))); + let no_dir = "\"AppState\" { \"appid\" \"10\" \"name\" \"N\" }"; + assert_eq!(steam::app_manifest(no_dir.as_bytes(), &lib()), Err(ParseError::Missing("installdir"))); + let no_id = "\"AppState\" { \"name\" \"N\" \"installdir\" \"N\" }"; + assert_eq!(steam::app_manifest(no_id.as_bytes(), &lib()), Err(ParseError::Missing("appid"))); + assert_eq!(steam::app_manifest(b"\"Other\" { }", &lib()), Err(ParseError::Missing("AppState"))); +} + +#[test] +fn app_manifest_refuses_blank_or_control_title() { + let blank = "\"AppState\" { \"appid\" \"10\" \"name\" \" \" \"installdir\" \"N\" }"; + assert_eq!(steam::app_manifest(blank.as_bytes(), &lib()), Err(ParseError::Missing("name"))); + let ctl = "\"AppState\" { \"appid\" \"10\" \"name\" \"a\\tb\" \"installdir\" \"N\" }"; + assert_eq!(steam::app_manifest(ctl.as_bytes(), &lib()), Err(ParseError::BadValue("name"))); +} + +#[test] +fn app_manifest_refuses_device_name_installdir() { + for bad in ["CON", "nul", "COM1", "lpt9.txt", "a/b", "a\\b", ".", "..", "x:", "dots.", ""] { + let acf = format!("\"AppState\" {{ \"appid\" \"10\" \"name\" \"N\" \"installdir\" \"{bad}\" }}"); + assert_eq!(steam::app_manifest(acf.as_bytes(), &lib()), Err(ParseError::BadPath("installdir")), "{bad:?}"); + } +} + +#[test] +fn manifest_names() { + assert_eq!(steam::app_id_from_manifest_name("appmanifest_1234560.acf"), Some(1_234_560)); + for bad in [ + "appmanifest_0.acf", + "appmanifest_01.acf", + "appmanifest_.acf", + "appmanifest_12.acf.bak", + "APPMANIFEST_12.ACF", + "appmanifest_99999999999.acf", + "appmanifest_-1.acf", + "libraryfolders.vdf", + "appmanifest_1 2.acf", + ] { + assert_eq!(steam::app_id_from_manifest_name(bad), None, "{bad}"); + } +} diff --git a/crates/arena-core/tests/vdf.rs b/crates/arena-core/tests/vdf.rs new file mode 100644 index 0000000..a279d9b --- /dev/null +++ b/crates/arena-core/tests/vdf.rs @@ -0,0 +1,114 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The VDF tokenizer, parser and writer on hand-written input. + +use arena_core::ParseError; +use arena_core::vdf::{self, Obj, TokenKind, Value}; + +#[test] +fn tokens_and_offsets() { + let t = vdf::tokenize(b"\"a\" {\n\t\"b\\\\c\" \"d\\\"e\"\n}").unwrap(); + let kinds: Vec<&TokenKind> = t.iter().map(|t| &t.kind).collect(); + assert_eq!( + kinds, + [ + &TokenKind::Str("a".into()), + &TokenKind::Open, + &TokenKind::Str("b\\c".into()), + &TokenKind::Str("d\"e".into()), + &TokenKind::Close + ] + ); + let at: Vec = t.iter().map(|t| t.at).collect(); + assert_eq!(at, [0, 4, 7, 14, 21]); +} + +#[test] +fn escapes() { + let t = vdf::tokenize(br#""\n\t\r\\\"""#).unwrap(); + assert_eq!(t[0].kind, TokenKind::Str("\n\t\r\\\"".into())); + for bad in [&br#""\x""#[..], br#""\0""#, br#""\'""#, br#""\""#, b"\"\\"] { + assert!(matches!(vdf::tokenize(bad), Err(ParseError::Syntax { .. })), "{:?}", String::from_utf8_lossy(bad)); + } +} + +#[test] +fn comments_and_whitespace() { + let doc = vdf::parse(b"// top\r\n\"a\" // after key\r\n{ \"b\" \"c\" } // end").unwrap(); + let Some(Value::Obj(a)) = doc.get("A") else { panic!("{doc:?}") }; + assert_eq!(a.get("b"), Some(&Value::Str("c".into()))); +} + +#[test] +fn refuses_unquoted_and_directives() { + for bad in [ + &b"a { }"[..], + b"\"a\" b", + b"#include \"x.vdf\"", + b"#base \"x\"", + b"\"a\" \"b\" [$WIN32]", + b"/ x", + b"\"a\" { \"b\" \"c\" }}", + ] { + assert!(matches!(vdf::parse(bad), Err(ParseError::Syntax { .. })), "{:?}", String::from_utf8_lossy(bad)); + } +} + +#[test] +fn structure_errors() { + assert!(matches!(vdf::parse(b"\"a\""), Err(ParseError::Syntax { .. }))); + assert!(matches!(vdf::parse(b"\"a\" {"), Err(ParseError::Syntax { .. }))); + assert!(matches!(vdf::parse(b"{ }"), Err(ParseError::Syntax { at: 0 }))); + assert!(matches!(vdf::parse(b"\"a\" { { } }"), Err(ParseError::Syntax { .. }))); + assert_eq!(vdf::parse(b"\"\" \"v\""), Err(ParseError::Missing("key"))); + assert_eq!(vdf::parse(b"\"a\" \"1\" \"A\" \"2\""), Err(ParseError::Duplicate("key"))); + assert!(vdf::parse(b"\"a\" { \"k\" \"1\" } \"b\" { \"k\" \"2\" }").is_ok(), "same key on different objects"); + assert_eq!(vdf::parse(b"").unwrap(), Obj::new()); + assert_eq!(vdf::parse(b" \n// only a comment").unwrap(), Obj::new()); +} + +#[test] +fn syntax_offset_is_where_the_problem_is() { + assert_eq!(vdf::parse(b"\"a\" \"b\"\n\"c\" x"), Err(ParseError::Syntax { at: 12 })); + assert_eq!(vdf::tokenize(b"\"ab\0\""), Err(ParseError::Syntax { at: 3 })); +} + +#[test] +fn bom_only_at_the_start() { + assert!(vdf::parse(b"\xEF\xBB\xBF\"a\" \"b\"").is_ok()); + assert!(vdf::parse(b"\"a\" \xEF\xBB\xBF\"b\"").is_err()); +} + +#[test] +fn obj_insert_rules() { + let mut o = Obj::new(); + o.insert("Key".into(), Value::Str("v".into())).unwrap(); + assert_eq!(o.insert("KEY".into(), Value::Str("w".into())), Err(ParseError::Duplicate("key"))); + assert_eq!(o.insert(String::new(), Value::Str("w".into())), Err(ParseError::Missing("key"))); + assert_eq!(o.insert("k".repeat(257), Value::Str("w".into())), Err(ParseError::TooLong("key"))); + assert_eq!(o.insert("k2".into(), Value::Str("v".repeat(4097))), Err(ParseError::TooLong("value"))); + assert_eq!(o.len(), 1); + assert_eq!(o.iter().next(), Some(("Key", &Value::Str("v".into())))); +} + +#[test] +fn write_then_parse() { + let mut inner = Obj::new(); + inner.insert("path".into(), Value::Str("C:\\Program Files (x86)\\Steam".into())).unwrap(); + inner.insert("quote".into(), Value::Str("say \"hi\"\n\tbye".into())).unwrap(); + let mut root = Obj::new(); + root.insert("0".into(), Value::Obj(inner)).unwrap(); + let mut doc = Obj::new(); + doc.insert("libraryfolders".into(), Value::Obj(root)).unwrap(); + let text = vdf::write(&doc); + assert!(text.contains(r#""path" "C:\\Program Files (x86)\\Steam""#), "{text}"); + assert_eq!(vdf::parse(text.as_bytes()).unwrap(), doc); +} + +#[test] +fn fixture_round_trips_through_the_writer() { + let doc = vdf::parse(include_bytes!("fixtures/steam/libraryfolders.vdf")).unwrap(); + assert_eq!(vdf::parse(vdf::write(&doc).as_bytes()).unwrap(), doc); +} diff --git a/crates/arena-core/tests/vdf_prop.rs b/crates/arena-core/tests/vdf_prop.rs new file mode 100644 index 0000000..10c4707 --- /dev/null +++ b/crates/arena-core/tests/vdf_prop.rs @@ -0,0 +1,140 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Property tests on the VDF tokenizer and parser: no panics on arbitrary bytes, and generated documents survive +//! a write/parse round trip. + +use arena_core::vdf::{self, Obj, TokenKind, Value}; +use arena_core::{WinPath, epic, steam}; +use proptest::prelude::*; + +/// Strings the format can carry: anything printable plus the characters the writer must escape. +fn vdf_string(max: usize) -> impl Strategy { + proptest::collection::vec( + prop_oneof![ + 8 => proptest::char::range(' ', '~'), + 2 => Just('"'), + 2 => Just('\\'), + 1 => Just('\n'), + 1 => Just('\t'), + 1 => Just('\r'), + 1 => proptest::char::range('\u{a0}', '\u{2fff}'), + 1 => proptest::char::range('\u{1f300}', '\u{1f64f}'), + ], + 0..max, + ) + .prop_map(|cs| cs.into_iter().collect()) +} + +fn key() -> impl Strategy { + vdf_string(12).prop_filter("keys are not empty", |k| !k.is_empty()) +} + +#[derive(Debug, Clone)] +enum Gen { + Str(String), + Obj(Vec<(String, Gen)>), +} + +fn gen_value() -> impl Strategy { + let leaf = vdf_string(24).prop_map(Gen::Str); + leaf.prop_recursive(6, 64, 6, |inner| proptest::collection::vec((key(), inner), 0..6).prop_map(Gen::Obj)) +} + +/// Builds an `Obj`, dropping keys that repeat (ignoring ASCII case) as the format requires. +fn build(pairs: Vec<(String, Gen)>) -> Obj { + let mut o = Obj::new(); + for (k, v) in pairs { + let v = match v { + Gen::Str(s) => Value::Str(s), + Gen::Obj(p) => Value::Obj(build(p)), + }; + let _ = o.insert(k, v); + } + o +} + +fn gen_doc() -> impl Strategy { + proptest::collection::vec((key(), gen_value()), 0..6).prop_map(build) +} + +fn lib() -> WinPath { + WinPath::parse(r"D:\SteamLibrary").unwrap() +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(512))] + + #[test] + fn tokenizer_never_panics(bytes in proptest::collection::vec(any::(), 0..2048)) { + let _ = vdf::tokenize(&bytes); + let _ = vdf::parse(&bytes); + let _ = steam::library_folders(&bytes); + let _ = steam::app_manifest(&bytes, &lib()); + let _ = epic::item(&bytes); + } + + #[test] + fn tokenizer_never_panics_on_vdf_like_bytes( + parts in proptest::collection::vec( + prop_oneof![ + Just(&b"\""[..]), Just(&b"{"[..]), Just(&b"}"[..]), Just(&b"\\"[..]), Just(&b"//"[..]), + Just(&b"\n"[..]), Just(&b" "[..]), Just(&b"\\\""[..]), Just(&b"\\n"[..]), Just(&b"\0"[..]), + Just(&b"\xff"[..]), Just(&b"\xc3"[..]), Just(&b"key"[..]), Just(&b"\xEF\xBB\xBF"[..]), + Just(&b"\"AppState\""[..]), Just(&b"\"appid\""[..]), Just(&b"\"10\""[..]), + Just(&b"\"libraryfolders\""[..]), Just(&b"\"path\""[..]), Just(&b"\"C:\\\\G\""[..]), + ], + 0..200, + ) + ) { + let bytes: Vec = parts.concat(); + let _ = vdf::tokenize(&bytes); + let _ = vdf::parse(&bytes); + let _ = steam::library_folders(&bytes); + let _ = steam::app_manifest(&bytes, &lib()); + } + + #[test] + fn tokens_carry_valid_offsets(bytes in proptest::collection::vec(any::(), 0..512)) { + if let Ok(tokens) = vdf::tokenize(&bytes) { + let mut last = None; + for t in &tokens { + prop_assert!(t.at < bytes.len()); + prop_assert!(last.is_none_or(|l| l < t.at), "offsets increase"); + last = Some(t.at); + let first = bytes[t.at]; + match t.kind { + TokenKind::Open => prop_assert_eq!(first, b'{'), + TokenKind::Close => prop_assert_eq!(first, b'}'), + TokenKind::Str(_) => prop_assert_eq!(first, b'"'), + } + } + } + } + + #[test] + fn syntax_errors_point_inside_the_input(bytes in proptest::collection::vec(any::(), 0..512)) { + if let Err(arena_core::ParseError::Syntax { at }) = vdf::parse(&bytes) { + prop_assert!(at <= bytes.len()); + } + } + + #[test] + fn generated_documents_round_trip(doc in gen_doc()) { + let text = vdf::write(&doc); + let back = vdf::parse(text.as_bytes()); + prop_assert_eq!(back.as_ref(), Ok(&doc), "{}", text); + // Writing again is byte-identical. + prop_assert_eq!(vdf::write(&back.unwrap()), text); + } + + #[test] + fn generated_strings_round_trip_through_tokens(s in vdf_string(200)) { + let mut o = Obj::new(); + o.insert("k".into(), Value::Str(s.clone())).unwrap(); + let tokens = vdf::tokenize(vdf::write(&o).as_bytes()).unwrap(); + let kinds: Vec = tokens.into_iter().map(|t| t.kind).collect(); + prop_assert_eq!(kinds, vec![TokenKind::Str("k".into()), TokenKind::Str(s)]); + } +}