using System.Security.Cryptography;
using System.Text;
using EvilEngine.Adapters.Steam;
using EvilEngine.Adapters.Tests.Support;
using EvilEngine.Mounts;
namespace EvilEngine.Adapters.Tests;
public sealed class SteamClaimsTests
{
private const string Library = "/library";
private const string InstallPath = "/library/steamapps/common/Amnesia The Bunker";
private static readonly VirtualPath[] Content =
["maps/trenches/trenches.hpm", "entities/door.ent", "empty.anim_info"];
private static readonly (string AppId, string[] Changed)[] RealInstalls =
[
("1944430", []),
("220", []),
("264710", []),
("1229490", []),
("550", []),
("220200",
[
"Ships/", "saves/", "PartDatabase.cfg", "KSP_Data/MonoBleedingEdge/etc/mono/registry/last-btime",
"GameData/Squad/KSPedia/squadcorefx.ksp"
])
];
private static string AppManifest(string installdir = "Amnesia The Bunker", string state = "4")
{
return $$"""
"AppState"
{
"appid" "1944430"
"StateFlags" "{{state}}"
"installdir" "{{installdir}}"
"InstalledDepots"
{
"1944432"
{
"manifest" "7744655607509449093"
"size" "12"
}
"1944435"
{
"manifest" "1407619913197510760"
"size" "3"
}
}
}
""";
}
private static DepotManifestWriter ContentDepot()
{
return new DepotManifestWriter(1944432, 7744655607509449093)
.Folder("maps")
.Folder("maps\\trenches")
.File("maps\\trenches\\trenches.hpm", "")
.File("entities\\door.ent", "door")
.File("empty.anim_info", "");
}
private static MemorySource Install(string location = InstallPath, string door = "door")
{
return new MemorySource(location, CaseRule.Insensitive)
.Add("maps/trenches/trenches.hpm", "")
.Add("entities/door.ent", door)
.Add("empty.anim_info", "")
.Add("AmnesiaTheBunker.exe", "MZ");
}
private static Externals Steam(string? appManifest = null, byte[]? content = null, byte[]? binaries = null,
Action? more = null)
{
var steamapps = new MemorySource($"{Library}/steamapps", CaseRule.Insensitive)
.Add("appmanifest_1944430.acf", appManifest ?? AppManifest());
var depotcache = new MemorySource($"{Library}/depotcache", CaseRule.Insensitive)
.Add("1944432_7744655607509449093.manifest", content ?? ContentDepot().Build());
if (binaries is not null)
depotcache.Add("1944435_1407619913197510760.manifest", binaries);
more?.Invoke(steamapps, depotcache);
return new Externals(
[
new ResolvedExternal(SteamClaims.Steamapps, ExternalState.Resolved, ExternalFrom.Hint)
{ Files = steamapps, Location = $"{Library}/steamapps" },
new ResolvedExternal(SteamClaims.Depotcache, ExternalState.Resolved, ExternalFrom.Hint)
{ Files = depotcache, Location = $"{Library}/depotcache" }
]);
}
private static string Sha1(string text)
{
return Convert.ToHexStringLower(SHA1.HashData(Encoding.UTF8.GetBytes(text)));
}
[Fact]
public void ReadsADepotManifest()
{
var manifest = DepotManifest.Read(ContentDepot().Build());
Assert.Equal((1944432u, 7744655607509449093ul, false), (manifest.Depot, manifest.Id, manifest.NamesEncrypted));
Assert.Equal(
["maps", "maps\\trenches", "maps\\trenches\\trenches.hpm", "entities\\door.ent", "empty.anim_info"],
manifest.Files.Select(file => file.Name));
Assert.Equal([false, false, true, true, true], manifest.Files.Select(file => file.IsFile));
Assert.Equal(Sha1("door"), Convert.ToHexStringLower(manifest.Files[3].Sha1));
Assert.Equal(4, manifest.Files[3].Size);
}
[Fact]
public void ReadsAZippedDepotManifestAsItsEntry()
{
Assert.Equal(DepotManifest.Read(ContentDepot().Build()).Files.Select(file => file.Name),
DepotManifest.Read(ContentDepot().BuildZipped()).Files.Select(file => file.Name));
}
[Fact]
public void RefusesATruncatedDepotManifest()
{
var bytes = ContentDepot().Build();
Assert.Throws(() => DepotManifest.Read(bytes[..(bytes.Length / 2)]));
}
[Fact]
public void ClaimsEveryFileTheManifestsListWithTheirSha1()
{
var notes = new List();
var claims = SteamClaims.For(Install(), Steam(), "1944430", notes);
Assert.Equal(new Dictionary
{
["maps/trenches/trenches.hpm"] = Sha1(""),
["entities/door.ent"] = Sha1("door"),
["empty.anim_info"] = Sha1("")
}, claims);
Assert.Equal(
"/library/depotcache has no 1944435_1407619913197510760.manifest, so depot 1944435's files hash from their bytes.",
Assert.Single(notes));
}
[Fact]
public void ClaimsASharedDepotsFilesUnderTheAppsOwnAndSkipsOneInstalledElsewhere()
{
var notes = new List();
var shared = AppManifest().Replace("\t\"InstalledDepots\"",
"\t\"SharedDepots\"\n\t{\n\t\t\"380\"\t\t\"380\"\n\t\t\"389\"\t\t\"389\"\n\t\t\"228981\"\t\t\"228980\"\n\t}\n\t\"InstalledDepots\"");
var owner = """
"AppState"
{
"appid" "380"
"StateFlags" "68"
"installdir" "Amnesia The Bunker"
"InstalledDepots"
{
"380"
{
"manifest" "2711482073477362647"
}
}
}
""";
var externals = Steam(shared, more: (steamapps, depotcache) =>
{
steamapps.Add("appmanifest_380.acf", owner);
steamapps.Add("appmanifest_228980.acf",
"\"AppState\" { \"installdir\" \"Steamworks Shared\" \"InstalledDepots\" { \"228981\" { \"manifest\" \"7613356809904826842\" } } }");
depotcache.Add("380_2711482073477362647.manifest",
new DepotManifestWriter(380, 2711482073477362647).File("entities\\door.ent", "dear")
.File("episodic\\map.bsp", "VBSP").Build());
});
var claims = SteamClaims.For(Install(), externals, "1944430", notes);
Assert.Equal(Sha1("door"), claims["entities/door.ent"]);
Assert.Equal(Sha1("VBSP"), claims["episodic/map.bsp"]);
Assert.Equal(
[
"/library/steamapps/appmanifest_389.acf doesn't list depot 389, which app 1944430 shares from it, so its files hash from their bytes.",
"/library/depotcache has no 1944435_1407619913197510760.manifest, so depot 1944435's files hash from their bytes."
],
notes);
}
[Fact]
public void FingerprintsASteamCopyAsACopyFromAnywhereElseWithTheSameBytes()
{
var steam = Install();
var elsewhere = Install("/run/media/me/Games/Amnesia The Bunker");
var claims = SteamClaims.For(steam, Steam(), "1944430", []);
Assert.Equal(Fingerprint.Of(elsewhere, Content, sha1Claims: true),
Fingerprint.Of(steam, Content, claims: claims, sha1Claims: true));
Assert.NotEqual(Fingerprint.Of(Install("/other", "dear"), Content, sha1Claims: true),
Fingerprint.Of(steam, Content, claims: claims, sha1Claims: true));
}
[Fact]
public void ClaimsNothingForACopyTheAppManifestDoesNotInstall()
{
var notes = new List();
Assert.Empty(SteamClaims.For(Install(), Steam(AppManifest("Amnesia The Bunker Beta")), "1944430", notes));
Assert.Equal(
"/library/steamapps/appmanifest_1944430.acf installs the app at common/Amnesia The Bunker Beta, not at /library/steamapps/common/Amnesia The Bunker, so its depot manifests aren't this copy's and every file hashes from its bytes.",
Assert.Single(notes));
}
[Fact]
public void ClaimsNothingWhileSteamIsUpdating()
{
var notes = new List();
Assert.Empty(SteamClaims.For(Install(), Steam(AppManifest(state: "6")), "1944430", notes));
Assert.Contains("StateFlags 6", Assert.Single(notes));
}
[Fact]
public void ClaimsNothingFromAManifestWithEncryptedNames()
{
var notes = new List();
var encrypted = new DepotManifestWriter(1944432, 7744655607509449093) { NamesEncrypted = true }
.File("bm9uc2Vuc2U=", "door");
Assert.Empty(SteamClaims.For(Install(), Steam(content: encrypted.Build()), "1944430", notes));
Assert.Contains(notes, note => note.Contains("keeps its file names encrypted"));
}
[Fact]
public void ClaimsNothingFromAnUnreadableManifest()
{
var notes = new List();
Assert.Empty(SteamClaims.For(Install(), Steam(content: "not a manifest"u8.ToArray()), "1944430", notes));
Assert.Contains(notes, note => note.Contains("can't be read"));
}
[Fact]
public void ClaimsNothingQuietlyWithNoSteamLibraryBesideTheCopy()
{
var notes = new List();
Assert.Empty(SteamClaims.For(Install(), Externals.None, "1944430", notes));
Assert.Empty(notes);
}
[Fact]
public void ClaimsEveryFileOfARealSteamInstallAsItsBytesHash()
{
var steam = Environment.GetEnvironmentVariable("EVIL_STEAM");
Assert.SkipWhen(steam is null, "Set EVIL_STEAM to a Steam folder to check its installs' depot manifests.");
var steamapps = Path.Combine(steam, "steamapps");
var checkedAny = false;
foreach (var (appId, changed) in RealInstalls)
{
var acf = Path.Combine(steamapps, $"appmanifest_{appId}.acf");
if (!File.Exists(acf))
continue;
var install = new FolderSource(
Path.Combine(steamapps, "common", KeyValues.Parse(File.ReadAllText(acf)).Get("installdir")!),
CaseRule.Insensitive);
var externals = new Externals(
[
new ResolvedExternal(SteamClaims.Steamapps, ExternalState.Resolved, ExternalFrom.Hint)
{ Files = new FolderSource(steamapps, CaseRule.Insensitive, true), Location = steamapps },
new ResolvedExternal(SteamClaims.Depotcache, ExternalState.Resolved, ExternalFrom.Hint)
{
Files = new FolderSource(Path.Combine(steam, "depotcache"), CaseRule.Insensitive, true),
Location = Path.Combine(steam, "depotcache")
}
]);
var notes = new List();
var claims = SteamClaims.For(install, externals, appId, notes);
Assert.Empty(notes);
Assert.NotEmpty(claims);
var differ = claims
.Where(claim => Sha1Of(install, claim.Key) != claim.Value)
.Select(claim => claim.Key.Value)
.Where(path => !changed.Any(file => path.StartsWith(file, StringComparison.OrdinalIgnoreCase)))
.ToArray();
Assert.Empty(differ);
checkedAny = true;
}
Assert.True(checkedAny, "None of the Steam installs this test knows is installed.");
}
private static string? Sha1Of(IFileSource files, VirtualPath path)
{
if (!files.TryOpen(path, out var stream))
return null;
using (stream)
{
return Convert.ToHexStringLower(SHA1.HashData(stream));
}
}
}