Skip to content
0.2.0-dev Download ZIP
303 lines ·11.8 KB Raw
1using System.Security.Cryptography;
2using System.Text;
3using EvilEngine.Adapters.Steam;
4using EvilEngine.Adapters.Tests.Support;
5using EvilEngine.Mounts;
6
7namespace EvilEngine.Adapters.Tests;
8
9public sealed class SteamClaimsTests
10{
11 private const string Library = "/library";
12 private const string InstallPath = "/library/steamapps/common/Amnesia The Bunker";
13
14 private static readonly VirtualPath[] Content =
15 ["maps/trenches/trenches.hpm", "entities/door.ent", "empty.anim_info"];
16
17 private static readonly (string AppId, string[] Changed)[] RealInstalls =
18 [
19 ("1944430", []),
20 ("220", []),
21 ("264710", []),
22 ("1229490", []),
23 ("550", []),
24 ("220200",
25 [
26 "Ships/", "saves/", "PartDatabase.cfg", "KSP_Data/MonoBleedingEdge/etc/mono/registry/last-btime",
27 "GameData/Squad/KSPedia/squadcorefx.ksp"
28 ])
29 ];
30
31 private static string AppManifest(string installdir = "Amnesia The Bunker", string state = "4")
32 {
33 return $$"""
34 "AppState"
35 {
36 "appid" "1944430"
37 "StateFlags" "{{state}}"
38 "installdir" "{{installdir}}"
39 "InstalledDepots"
40 {
41 "1944432"
42 {
43 "manifest" "7744655607509449093"
44 "size" "12"
45 }
46 "1944435"
47 {
48 "manifest" "1407619913197510760"
49 "size" "3"
50 }
51 }
52 }
53 """;
54 }
55
56 private static DepotManifestWriter ContentDepot()
57 {
58 return new DepotManifestWriter(1944432, 7744655607509449093)
59 .Folder("maps")
60 .Folder("maps\\trenches")
61 .File("maps\\trenches\\trenches.hpm", "<HPLMap/>")
62 .File("entities\\door.ent", "door")
63 .File("empty.anim_info", "");
64 }
65
66 private static MemorySource Install(string location = InstallPath, string door = "door")
67 {
68 return new MemorySource(location, CaseRule.Insensitive)
69 .Add("maps/trenches/trenches.hpm", "<HPLMap/>")
70 .Add("entities/door.ent", door)
71 .Add("empty.anim_info", "")
72 .Add("AmnesiaTheBunker.exe", "MZ");
73 }
74
75 private static Externals Steam(string? appManifest = null, byte[]? content = null, byte[]? binaries = null,
76 Action<MemorySource, MemorySource>? more = null)
77 {
78 var steamapps = new MemorySource($"{Library}/steamapps", CaseRule.Insensitive)
79 .Add("appmanifest_1944430.acf", appManifest ?? AppManifest());
80 var depotcache = new MemorySource($"{Library}/depotcache", CaseRule.Insensitive)
81 .Add("1944432_7744655607509449093.manifest", content ?? ContentDepot().Build());
82 if (binaries is not null)
83 depotcache.Add("1944435_1407619913197510760.manifest", binaries);
84 more?.Invoke(steamapps, depotcache);
85 return new Externals(
86 [
87 new ResolvedExternal(SteamClaims.Steamapps, ExternalState.Resolved, ExternalFrom.Hint)
88 { Files = steamapps, Location = $"{Library}/steamapps" },
89 new ResolvedExternal(SteamClaims.Depotcache, ExternalState.Resolved, ExternalFrom.Hint)
90 { Files = depotcache, Location = $"{Library}/depotcache" }
91 ]);
92 }
93
94 private static string Sha1(string text)
95 {
96 return Convert.ToHexStringLower(SHA1.HashData(Encoding.UTF8.GetBytes(text)));
97 }
98
99 [Fact]
100 public void ReadsADepotManifest()
101 {
102 var manifest = DepotManifest.Read(ContentDepot().Build());
103
104 Assert.Equal((1944432u, 7744655607509449093ul, false), (manifest.Depot, manifest.Id, manifest.NamesEncrypted));
105 Assert.Equal(
106 ["maps", "maps\\trenches", "maps\\trenches\\trenches.hpm", "entities\\door.ent", "empty.anim_info"],
107 manifest.Files.Select(file => file.Name));
108 Assert.Equal([false, false, true, true, true], manifest.Files.Select(file => file.IsFile));
109 Assert.Equal(Sha1("door"), Convert.ToHexStringLower(manifest.Files[3].Sha1));
110 Assert.Equal(4, manifest.Files[3].Size);
111 }
112
113 [Fact]
114 public void ReadsAZippedDepotManifestAsItsEntry()
115 {
116 Assert.Equal(DepotManifest.Read(ContentDepot().Build()).Files.Select(file => file.Name),
117 DepotManifest.Read(ContentDepot().BuildZipped()).Files.Select(file => file.Name));
118 }
119
120 [Fact]
121 public void RefusesATruncatedDepotManifest()
122 {
123 var bytes = ContentDepot().Build();
124
125 Assert.Throws<InvalidDataException>(() => DepotManifest.Read(bytes[..(bytes.Length / 2)]));
126 }
127
128 [Fact]
129 public void ClaimsEveryFileTheManifestsListWithTheirSha1()
130 {
131 var notes = new List<string>();
132
133 var claims = SteamClaims.For(Install(), Steam(), "1944430", notes);
134
135 Assert.Equal(new Dictionary<VirtualPath, string>
136 {
137 ["maps/trenches/trenches.hpm"] = Sha1("<HPLMap/>"),
138 ["entities/door.ent"] = Sha1("door"),
139 ["empty.anim_info"] = Sha1("")
140 }, claims);
141 Assert.Equal(
142 "/library/depotcache has no 1944435_1407619913197510760.manifest, so depot 1944435's files hash from their bytes.",
143 Assert.Single(notes));
144 }
145
146 [Fact]
147 public void ClaimsASharedDepotsFilesUnderTheAppsOwnAndSkipsOneInstalledElsewhere()
148 {
149 var notes = new List<string>();
150 var shared = AppManifest().Replace("\t\"InstalledDepots\"",
151 "\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\"");
152 var owner = """
153 "AppState"
154 {
155 "appid" "380"
156 "StateFlags" "68"
157 "installdir" "Amnesia The Bunker"
158 "InstalledDepots"
159 {
160 "380"
161 {
162 "manifest" "2711482073477362647"
163 }
164 }
165 }
166 """;
167 var externals = Steam(shared, more: (steamapps, depotcache) =>
168 {
169 steamapps.Add("appmanifest_380.acf", owner);
170 steamapps.Add("appmanifest_228980.acf",
171 "\"AppState\" { \"installdir\" \"Steamworks Shared\" \"InstalledDepots\" { \"228981\" { \"manifest\" \"7613356809904826842\" } } }");
172 depotcache.Add("380_2711482073477362647.manifest",
173 new DepotManifestWriter(380, 2711482073477362647).File("entities\\door.ent", "dear")
174 .File("episodic\\map.bsp", "VBSP").Build());
175 });
176
177 var claims = SteamClaims.For(Install(), externals, "1944430", notes);
178
179 Assert.Equal(Sha1("door"), claims["entities/door.ent"]);
180 Assert.Equal(Sha1("VBSP"), claims["episodic/map.bsp"]);
181 Assert.Equal(
182 [
183 "/library/steamapps/appmanifest_389.acf doesn't list depot 389, which app 1944430 shares from it, so its files hash from their bytes.",
184 "/library/depotcache has no 1944435_1407619913197510760.manifest, so depot 1944435's files hash from their bytes."
185 ],
186 notes);
187 }
188
189 [Fact]
190 public void FingerprintsASteamCopyAsACopyFromAnywhereElseWithTheSameBytes()
191 {
192 var steam = Install();
193 var elsewhere = Install("/run/media/me/Games/Amnesia The Bunker");
194 var claims = SteamClaims.For(steam, Steam(), "1944430", []);
195
196 Assert.Equal(Fingerprint.Of(elsewhere, Content, sha1Claims: true),
197 Fingerprint.Of(steam, Content, claims: claims, sha1Claims: true));
198 Assert.NotEqual(Fingerprint.Of(Install("/other", "dear"), Content, sha1Claims: true),
199 Fingerprint.Of(steam, Content, claims: claims, sha1Claims: true));
200 }
201
202 [Fact]
203 public void ClaimsNothingForACopyTheAppManifestDoesNotInstall()
204 {
205 var notes = new List<string>();
206
207 Assert.Empty(SteamClaims.For(Install(), Steam(AppManifest("Amnesia The Bunker Beta")), "1944430", notes));
208 Assert.Equal(
209 "/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.",
210 Assert.Single(notes));
211 }
212
213 [Fact]
214 public void ClaimsNothingWhileSteamIsUpdating()
215 {
216 var notes = new List<string>();
217
218 Assert.Empty(SteamClaims.For(Install(), Steam(AppManifest(state: "6")), "1944430", notes));
219 Assert.Contains("StateFlags 6", Assert.Single(notes));
220 }
221
222 [Fact]
223 public void ClaimsNothingFromAManifestWithEncryptedNames()
224 {
225 var notes = new List<string>();
226 var encrypted = new DepotManifestWriter(1944432, 7744655607509449093) { NamesEncrypted = true }
227 .File("bm9uc2Vuc2U=", "door");
228
229 Assert.Empty(SteamClaims.For(Install(), Steam(content: encrypted.Build()), "1944430", notes));
230 Assert.Contains(notes, note => note.Contains("keeps its file names encrypted"));
231 }
232
233 [Fact]
234 public void ClaimsNothingFromAnUnreadableManifest()
235 {
236 var notes = new List<string>();
237
238 Assert.Empty(SteamClaims.For(Install(), Steam(content: "not a manifest"u8.ToArray()), "1944430", notes));
239 Assert.Contains(notes, note => note.Contains("can't be read"));
240 }
241
242 [Fact]
243 public void ClaimsNothingQuietlyWithNoSteamLibraryBesideTheCopy()
244 {
245 var notes = new List<string>();
246
247 Assert.Empty(SteamClaims.For(Install(), Externals.None, "1944430", notes));
248 Assert.Empty(notes);
249 }
250
251 [Fact]
252 public void ClaimsEveryFileOfARealSteamInstallAsItsBytesHash()
253 {
254 var steam = Environment.GetEnvironmentVariable("EVIL_STEAM");
255 Assert.SkipWhen(steam is null, "Set EVIL_STEAM to a Steam folder to check its installs' depot manifests.");
256 var steamapps = Path.Combine(steam, "steamapps");
257 var checkedAny = false;
258 foreach (var (appId, changed) in RealInstalls)
259 {
260 var acf = Path.Combine(steamapps, $"appmanifest_{appId}.acf");
261 if (!File.Exists(acf))
262 continue;
263 var install = new FolderSource(
264 Path.Combine(steamapps, "common", KeyValues.Parse(File.ReadAllText(acf)).Get("installdir")!),
265 CaseRule.Insensitive);
266 var externals = new Externals(
267 [
268 new ResolvedExternal(SteamClaims.Steamapps, ExternalState.Resolved, ExternalFrom.Hint)
269 { Files = new FolderSource(steamapps, CaseRule.Insensitive, true), Location = steamapps },
270 new ResolvedExternal(SteamClaims.Depotcache, ExternalState.Resolved, ExternalFrom.Hint)
271 {
272 Files = new FolderSource(Path.Combine(steam, "depotcache"), CaseRule.Insensitive, true),
273 Location = Path.Combine(steam, "depotcache")
274 }
275 ]);
276 var notes = new List<string>();
277
278 var claims = SteamClaims.For(install, externals, appId, notes);
279
280 Assert.Empty(notes);
281 Assert.NotEmpty(claims);
282 var differ = claims
283 .Where(claim => Sha1Of(install, claim.Key) != claim.Value)
284 .Select(claim => claim.Key.Value)
285 .Where(path => !changed.Any(file => path.StartsWith(file, StringComparison.OrdinalIgnoreCase)))
286 .ToArray();
287 Assert.Empty(differ);
288 checkedAny = true;
289 }
290
291 Assert.True(checkedAny, "None of the Steam installs this test knows is installed.");
292 }
293
294 private static string? Sha1Of(IFileSource files, VirtualPath path)
295 {
296 if (!files.TryOpen(path, out var stream))
297 return null;
298 using (stream)
299 {
300 return Convert.ToHexStringLower(SHA1.HashData(stream));
301 }
302 }
303}