forked from microsoft/winget-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestCommon.cpp
More file actions
404 lines (340 loc) · 13.2 KB
/
Copy pathTestCommon.cpp
File metadata and controls
404 lines (340 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "TestCommon.h"
#include "TestHooks.h"
#include <winget/GroupPolicy.h>
#include <winget/UserSettings.h>
#include <AppInstallerMsixInfo.h>
#include <AppInstallerDownloader.h>
using namespace AppInstaller;
namespace TestCommon
{
namespace
{
int initRand()
{
srand(static_cast<unsigned int>(time(NULL)));
return rand();
};
inline int getRand()
{
static int randStart = initRand();
return randStart++;
}
inline std::filesystem::path GetFilePath(std::filesystem::path path, const std::string& baseName, const std::string& baseExt)
{
path /= baseName + std::to_string(getRand()) + baseExt;
return path;
}
inline std::filesystem::path GetTempFilePath(const std::string& baseName, const std::string& baseExt)
{
std::filesystem::path tempFilePath = std::filesystem::temp_directory_path();
return GetFilePath(tempFilePath, baseName, baseExt);
}
static TempFileDestructionBehavior s_TempFileDestructorBehavior = TempFileDestructionBehavior::Delete;
static std::vector<std::filesystem::path> s_TempFilesOnFile;
static std::filesystem::path s_TestDataFileBasePath{};
bool CleanVolatileTestRoot(HKEY root)
{
THROW_IF_WIN32_ERROR(RegDeleteTreeW(root, nullptr));
return true;
}
}
TempFile::TempFile(const std::string& baseName, const std::string& baseExt, std::optional<KeepTempFile> keepTempFile)
{
_filepath = GetTempFilePath(baseName, baseExt);
if (!keepTempFile)
{
std::filesystem::remove(_filepath);
}
}
TempFile::TempFile(const std::filesystem::path& parent, const std::string& baseName, const std::string& baseExt, std::optional<KeepTempFile> keepTempFile)
{
_filepath = GetFilePath(parent, baseName, baseExt);
if (!keepTempFile)
{
std::filesystem::remove(_filepath);
}
}
TempFile::TempFile(const std::filesystem::path& filePath, std::optional<KeepTempFile> keepTempFile)
{
if (filePath.is_relative())
{
_filepath = std::filesystem::temp_directory_path();
_filepath /= filePath;
}
else
{
_filepath = filePath;
}
if (!keepTempFile)
{
std::filesystem::remove(_filepath);
}
}
TempFile::~TempFile() try
{
if (m_destructionToken)
{
switch (s_TempFileDestructorBehavior)
{
case TempFileDestructionBehavior::Delete:
std::filesystem::remove_all(_filepath);
break;
case TempFileDestructionBehavior::Keep:
break;
case TempFileDestructionBehavior::ShellExecuteOnFailure:
s_TempFilesOnFile.emplace_back(std::move(_filepath));
break;
}
}
}
CATCH_LOG_RETURN()
void TempFile::Rename(const std::filesystem::path& newFilePath)
{
std::filesystem::rename(GetPath(), newFilePath);
_filepath = newFilePath;
}
void TempFile::Release()
{
m_destructionToken = false;
}
void TempFile::SetDestructorBehavior(TempFileDestructionBehavior behavior)
{
s_TempFileDestructorBehavior = behavior;
}
void TempFile::SetTestFailed(bool failed)
{
if (failed)
{
for (const auto& path : s_TempFilesOnFile)
{
SHELLEXECUTEINFOW seinfo{};
seinfo.cbSize = sizeof(seinfo);
seinfo.lpVerb = L"open";
seinfo.lpFile = path.c_str();
ShellExecuteExW(&seinfo);
}
}
else
{
s_TempFilesOnFile.clear();
}
}
TempDirectory::TempDirectory(const std::string& baseName, bool create)
{
_filepath = GetTempFilePath(baseName, "");
if (create)
{
if (std::filesystem::exists(_filepath))
{
std::filesystem::remove_all(_filepath);
}
std::filesystem::create_directories(_filepath);
}
}
std::filesystem::path TestDataFile::GetPath() const
{
std::filesystem::path result = s_TestDataFileBasePath;
result /= m_path;
return result;
}
void TestDataFile::SetTestDataBasePath(const std::filesystem::path& path)
{
s_TestDataFileBasePath = path;
}
void TestProgress::OnProgress(uint64_t current, uint64_t maximum, AppInstaller::ProgressType type)
{
if (m_OnProgress)
{
m_OnProgress(current, maximum, type);
}
}
void TestProgress::SetProgressMessage(std::string_view)
{
}
void TestProgress::BeginProgress()
{
}
void TestProgress::EndProgress(bool)
{
}
bool TestProgress::IsCancelledBy(AppInstaller::CancelReason)
{
return false;
}
AppInstaller::IProgressCallback::CancelFunctionRemoval TestProgress::SetCancellationFunction(std::function<void()>&&)
{
return {};
}
wil::unique_hkey RegCreateVolatileTestRoot()
{
// First create/open the real test root
wil::unique_hkey root;
THROW_IF_WIN32_ERROR(RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\WinGet\\TestRoot", 0, nullptr, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, nullptr, &root, nullptr));
static bool s_ignored = CleanVolatileTestRoot(root.get());
// Create a random name
GUID name{};
(void)CoCreateGuid(&name);
wchar_t nameBuffer[256];
(void)StringFromGUID2(name, nameBuffer, ARRAYSIZE(nameBuffer));
return RegCreateVolatileSubKey(root.get(), nameBuffer);
}
wil::unique_hkey RegCreateVolatileSubKey(HKEY parent, const std::wstring& name)
{
wil::unique_hkey result;
THROW_IF_WIN32_ERROR(RegCreateKeyExW(parent, name.c_str(), 0, nullptr, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, nullptr, &result, nullptr));
return result;
}
void SetRegistryValue(HKEY key, const std::wstring& name, const std::wstring& value, DWORD type)
{
THROW_IF_WIN32_ERROR(RegSetValueExW(key, name.c_str(), 0, type, reinterpret_cast<const BYTE*>(value.c_str()), static_cast<DWORD>(sizeof(wchar_t) * (value.size() + 1))));
}
void SetRegistryValue(HKEY key, const std::wstring& name, const std::vector<BYTE>& value, DWORD type)
{
THROW_IF_WIN32_ERROR(RegSetValueExW(key, name.c_str(), 0, type, reinterpret_cast<const BYTE*>(value.data()), static_cast<DWORD>(value.size())));
}
void SetRegistryValue(HKEY key, const std::wstring& name, DWORD value)
{
THROW_IF_WIN32_ERROR(RegSetValueExW(key, name.c_str(), 0, REG_DWORD, reinterpret_cast<const BYTE*>(&value), sizeof(DWORD)));
}
void EnableDevMode(bool enable)
{
wil::unique_hkey result;
THROW_IF_WIN32_ERROR(RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\AppModelUnlock", 0, KEY_ALL_ACCESS|KEY_WOW64_64KEY, &result));
SetRegistryValue(result.get(), L"AllowDevelopmentWithoutDevLicense", (enable ? 1 : 0));
}
TestUserSettings::TestUserSettings(bool keepFileSettings)
{
if (!keepFileSettings)
{
m_settings.clear();
}
AppInstaller::Settings::SetUserSettingsOverride(this);
}
TestUserSettings::~TestUserSettings()
{
AppInstaller::Settings::SetUserSettingsOverride(nullptr);
}
std::unique_ptr<TestUserSettings> TestUserSettings::EnableExperimentalFeature(Settings::ExperimentalFeature::Feature feature, bool keepFileSettings)
{
std::unique_ptr<TestUserSettings> result = std::make_unique<TestUserSettings>(keepFileSettings);
// Due to the template usage, this needs to be updated for any features that want to use it.
// Currently no feature is used. Uncomment below when a feature needs to be used.
// switch (feature)
// {
// default:
// THROW_HR(E_NOTIMPL);
// }
UNREFERENCED_PARAMETER(feature);
return result;
}
bool InstallCertFromSignedPackage(const std::filesystem::path& package)
{
auto [certContext, certStore] = AppInstaller::Msix::GetCertContextFromMsix(package);
wil::unique_hcertstore trustedPeopleStore;
trustedPeopleStore.reset(CertOpenStore(
CERT_STORE_PROV_SYSTEM_W,
PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
NULL,
CERT_SYSTEM_STORE_LOCAL_MACHINE,
L"TrustedPeople"));
THROW_LAST_ERROR_IF(!trustedPeopleStore.get());
wil::unique_cert_context existingCert;
existingCert.reset(CertFindCertificateInStore(
trustedPeopleStore.get(),
PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
0,
CERT_FIND_EXISTING,
certContext.get(),
nullptr));
// Add if it does not already exist in the store
if (!existingCert.get())
{
THROW_LAST_ERROR_IF(!CertAddCertificateContextToStore(
trustedPeopleStore.get(),
certContext.get(),
CERT_STORE_ADD_NEW,
nullptr));
return true;
}
return false;
}
bool UninstallCertFromSignedPackage(const std::filesystem::path& package)
{
auto [certContext, certStore] = AppInstaller::Msix::GetCertContextFromMsix(package);
wil::unique_hcertstore trustedPeopleStore;
trustedPeopleStore.reset(CertOpenStore(
CERT_STORE_PROV_SYSTEM_W,
PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
NULL,
CERT_SYSTEM_STORE_LOCAL_MACHINE,
L"TrustedPeople"));
THROW_LAST_ERROR_IF(!trustedPeopleStore.get());
wil::unique_cert_context existingCert;
existingCert.reset(CertFindCertificateInStore(
trustedPeopleStore.get(),
PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
0,
CERT_FIND_EXISTING,
certContext.get(),
nullptr));
// Remove if it exists in the store
if (existingCert.get())
{
THROW_LAST_ERROR_IF(!CertDeleteCertificateFromStore(existingCert.get()));
return true;
}
return false;
}
bool GetMsixPackageManifestReader(std::string_view testFileName, IAppxManifestReader** manifestReader)
{
// Locate test file
TestDataFile testFile(testFileName);
auto path = testFile.GetPath().u8string();
// Get the stream for the test file
auto stream = AppInstaller::Utility::GetReadOnlyStreamFromURI(path);
// Get manifest from package reader
Microsoft::WRL::ComPtr<IAppxPackageReader> packageReader;
return AppInstaller::Msix::GetPackageReader(stream.Get(), &packageReader)
&& SUCCEEDED(packageReader->GetManifest(manifestReader));
}
std::string RemoveConsoleFormat(const std::string& str)
{
// We are looking something that starts with "\x1b[0m"
if (!str.empty() && str[0] == '\x1b')
{
// Find first m
auto pos = str.find("m");
if (pos != std::string::npos)
{
return str.substr(pos + 1);
}
}
return str;
}
Json::Value ConvertToJson(const std::string& content)
{
auto contentClean = RemoveConsoleFormat(content);
Json::Value root;
Json::CharReaderBuilder builder;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
std::string error;
if (!reader->parse(contentClean.c_str(), contentClean.c_str() + contentClean.size(), &root, &error))
{
throw error;
}
return root;
}
void SetTestPathOverrides()
{
// Force all tests to run against settings inside this container.
// This prevents test runs from trashing the users actual settings.
Runtime::TestHook_SetPathOverride(Runtime::PathName::LocalState, Runtime::GetPathTo(Runtime::PathName::LocalState) / "Tests");
Runtime::TestHook_SetPathOverride(Runtime::PathName::UserFileSettings, Runtime::GetPathTo(Runtime::PathName::UserFileSettings) / "Tests");
Runtime::TestHook_SetPathOverride(Runtime::PathName::StandardSettings, Runtime::GetPathTo(Runtime::PathName::StandardSettings) / "Tests");
Runtime::TestHook_SetPathOverride(Runtime::PathName::SecureSettingsForRead, Runtime::GetPathTo(Runtime::PathName::StandardSettings) / "WinGet_SecureSettings_Tests");
Runtime::TestHook_SetPathOverride(Runtime::PathName::SecureSettingsForWrite, Runtime::GetPathDetailsFor(Runtime::PathName::SecureSettingsForRead));
}
}