-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathInstallerTests.cpp
More file actions
1051 lines (833 loc) · 38.8 KB
/
InstallerTests.cpp
File metadata and controls
1051 lines (833 loc) · 38.8 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*++
Copyright (c) Microsoft. All rights reserved.
Module Name:
InstallerTests.cpp
Abstract:
This file contains test cases for the installation process.
--*/
#include "precomp.h"
#include <Sfc.h>
#include "Common.h"
#include "registry.hpp"
#include "PluginTests.h"
using namespace wsl::windows::common::registry;
extern std::wstring g_dumpFolder;
static std::wstring g_pipelineBuildId;
class InstallerTests
{
std::wstring m_msixPackagePath;
std::wstring m_msiPath;
std::wstring m_msixInstalledPath;
std::filesystem::path m_installedPath;
bool m_initialized = false;
winrt::Windows::Management::Deployment::PackageManager m_packageManager;
wil::unique_hkey m_lxssKey = wsl::windows::common::registry::OpenLxssMachineKey(KEY_ALL_ACCESS);
wil::unique_schandle m_scm{OpenSCManagerW(nullptr, SERVICES_ACTIVE_DATABASE, GENERIC_READ | GENERIC_EXECUTE)};
wil::unique_hfile nulDevice{CreateFileW(
L"nul", GENERIC_READ, (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)};
WSL_TEST_CLASS(InstallerTests)
TEST_CLASS_SETUP(TestClassSetup)
{
VERIFY_ARE_EQUAL(LxsstuInitialize(FALSE), TRUE);
m_initialized = true;
WEX::Common::String MsixPackagePath;
WEX::TestExecution::RuntimeParameters::TryGetValue(L"Package", MsixPackagePath);
m_msixPackagePath = std::filesystem::weakly_canonical(static_cast<std::wstring>(MsixPackagePath)).wstring();
VERIFY_IS_FALSE(m_msixPackagePath.empty());
for (const auto& e : m_packageManager.FindPackages(wsl::windows::common::wslutil::c_msixPackageFamilyName))
{
VERIFY_IS_TRUE(m_msixInstalledPath.empty());
m_msixInstalledPath = std::wstring(e.InstalledLocation().Path().c_str());
}
#ifdef WSL_DEV_THIN_MSI_PACKAGE
m_msiPath = std::filesystem::weakly_canonical(WSL_DEV_THIN_MSI_PACKAGE).wstring();
#else
VERIFY_IS_TRUE(IsInstallerMsixInstalled(), L"Installer MSIX absent, can't run the tests");
m_msiPath = (std::filesystem::temp_directory_path() / L"wsl.msi").wstring();
VERIFY_IS_TRUE(std::filesystem::copy_file(m_msixInstalledPath + L"\\wsl.msi", m_msiPath, std::filesystem::copy_options::overwrite_existing));
#endif
auto installPath = wsl::windows::common::wslutil::GetMsiPackagePath();
VERIFY_IS_TRUE(installPath.has_value());
m_installedPath = std::move(installPath.value());
wsl::windows::common::helpers::SetHandleInheritable(nulDevice.get());
return true;
}
TEST_CLASS_CLEANUP(TestClassCleanup)
{
#ifndef WSL_DEV_THIN_MSI_PACKAGE
if (!m_msiPath.empty())
{
std::filesystem::remove(m_msiPath);
}
#endif
if (m_initialized)
{
LxsstuUninitialize(FALSE);
}
return true;
}
DWORD GetWslInstallerServiceState() const
{
const wil::unique_schandle service{OpenServiceW(m_scm.get(), L"Wslinstaller", SERVICE_QUERY_STATUS)};
VERIFY_IS_NOT_NULL(service);
SERVICE_STATUS status{};
VERIFY_IS_TRUE(QueryServiceStatus(service.get(), &status));
return status.dwCurrentState;
}
void WaitForInstallerServiceStop()
{
DWORD lastState = -1;
auto pred = [&]() {
lastState = GetWslInstallerServiceState();
THROW_HR_IF(E_FAIL, lastState != SERVICE_STOPPED);
};
try
{
wsl::shared::retry::RetryWithTimeout<void>(pred, std::chrono::hours(3), std::chrono::minutes(2));
}
catch (...)
{
LogError("InstallerService state: %lu", lastState);
VERIFY_FAIL("Timed out waiting for the installer service to stop");
}
}
static std::wstring GenerateMsiLogPath()
{
// Note: canonical is required because msiexec seems to be unable to deal with symlinks.
static int counter = 0;
return std::format(L"{}\\msi-install-{}.txt", std::filesystem::canonical(g_dumpFolder).c_str(), counter++);
}
bool IsInstallerMsixInstalled() const
{
return std::filesystem::exists(m_msixInstalledPath + L"\\wslinstaller.exe");
}
bool IsMsixInstalled() const
{
return m_packageManager.FindPackagesForUser(L"", wsl::windows::common::wslutil::c_msixPackageFamilyName).First().HasCurrent();
}
static void CallMsiExec(const std::wstring& Args)
{
std::wstring commandLine;
THROW_IF_FAILED(wil::GetSystemDirectoryW(commandLine));
commandLine += L"\\msiexec.exe " + Args;
LogInfo("Calling msiexec: %ls", commandLine.c_str());
// There is a potential race condition given that we have no easy way to know when the msiexec process
// created by the installer service will release the MSI mutex.
// If the mutex is still held when we call msiexec, it will fails with ERROR_INSTALL_ALREADY_RUNNING
// so retry for up to two minutes if we get that error back.
DWORD exitCode = -1;
wsl::shared::retry::RetryWithTimeout<void>(
[&]() {
exitCode = LxsstuRunCommand(commandLine.data());
THROW_HR_IF(E_ABORT, exitCode == ERROR_INSTALL_ALREADY_RUNNING);
},
std::chrono::seconds(1),
std::chrono::minutes(2),
[]() { return wil::ResultFromCaughtException() == E_ABORT; });
VERIFY_ARE_EQUAL(0L, exitCode);
}
std::wstring GetMsiProductCode() const
{
return wsl::windows::common::registry::ReadString(m_lxssKey.get(), L"MSI", L"ProductCode", L"");
}
// Release any in-process COM DLLs (e.g. wslserviceproxystub.dll loaded by prior tests)
// so the Restart Manager doesn't detect the test process as holding files.
// This avoids install failures on older Server SKUs where the RM has stricter silent-mode behavior.
static void PrepareForMsiOperation()
{
CoFreeUnusedLibrariesEx(0, 0);
}
void UninstallMsi()
{
PrepareForMsiOperation();
auto productCode = GetMsiProductCode();
VERIFY_IS_FALSE(productCode.empty());
CallMsiExec(std::format(L"/qn /norestart /x {} /L*V {}", productCode, GenerateMsiLogPath()));
}
void InstallMsi()
{
PrepareForMsiOperation();
CallMsiExec(std::format(L"/qn /norestart /i {} /L*V {}", m_msiPath, GenerateMsiLogPath()));
}
void InstallMsix() const
{
const auto result =
m_packageManager
.AddPackageAsync(winrt::Windows::Foundation::Uri{m_msixPackagePath}, nullptr, winrt::Windows::Management::Deployment::DeploymentOptions::None)
.get();
VERIFY_ARE_EQUAL(result.ExtendedErrorCode(), S_OK);
}
void UninstallMsix() const
{
auto result = m_packageManager.DeprovisionPackageForAllUsersAsync(wsl::windows::common::wslutil::c_msixPackageFamilyName).get();
auto errorCode = result.ExtendedErrorCode();
if (FAILED(errorCode) && errorCode != HRESULT_FROM_WIN32(ERROR_NOT_FOUND))
{
LogError("Error deprovisioning the package: 0x%x, %ls", errorCode, result.ErrorText().c_str());
VERIFY_FAIL();
}
for (const auto& e : m_packageManager.FindPackages(wsl::windows::common::wslutil::c_msixPackageFamilyName))
{
// Remove the package for the current user first.
result = m_packageManager.RemovePackageAsync(e.Id().FullName()).get();
errorCode = result.ExtendedErrorCode();
if (FAILED(errorCode) && errorCode != HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND))
{
LogError("Error deprovisioning the package: 0x%x, %ls", errorCode, result.ErrorText().c_str());
VERIFY_FAIL();
}
// then remove the package for all users.
result = m_packageManager
.RemovePackageAsync(e.Id().FullName(), winrt::Windows::Management::Deployment::RemovalOptions::RemoveForAllUsers)
.get();
errorCode = result.ExtendedErrorCode();
if (FAILED(errorCode) && errorCode != HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND))
{
LogError("Error deprovisioning the package: 0x%x, %ls", errorCode, result.ErrorText().c_str());
VERIFY_FAIL();
}
}
}
bool IsMsiPackageInstalled()
{
// Check for wslservice to be installed because MSI installs registry keys before installing services
return !GetMsiProductCode().empty() && wsl::windows::common::helpers::IsServicePresent(L"wslservice");
}
static bool IsMsixInstallerInstalled()
{
return wsl::windows::common::helpers::IsServicePresent(L"wslinstaller");
}
void WaitForMsiPackageInstall()
{
auto pred = [this]() { THROW_HR_IF(E_FAIL, !IsMsiPackageInstalled()); };
try
{
// It is possible for the 'DeprovisionMsix' stage of the MSI installation to take a long time.
// On vb_release, up to 7 minutes have been observed. Wait for up to 20 minutes to be safe.
wsl::shared::retry::RetryWithTimeout<void>(pred, std::chrono::seconds(1), std::chrono::minutes(20));
}
catch (...)
{
VERIFY_FAIL("Timed out waiting for MSI package installation");
}
}
static void ValidateInstalledVersion(LPCWSTR expectedVersion)
{
auto pred = [expectedVersion]() {
// Validate that we're not using inbox WSL
auto [output, _] = LxsstuLaunchWslAndCaptureOutput(L"--version");
if (output.find(expectedVersion) == std::string::npos)
{
LogInfo("Package is not installed yet. Output: %ls", output.c_str());
THROW_HR(E_FAIL);
}
LogInfo("Package is properly installed. Output: %ls", output.c_str());
};
// Sadly the provisioning of MSIX packages for user accounts isn't synchronous so we need to wait until the package
// becomes visible.
try
{
wsl::shared::retry::RetryWithTimeout<void>(pred, std::chrono::seconds(1), std::chrono::minutes(2));
}
catch (...)
{
VERIFY_FAIL("Timed out waiting for MSIX package to be available");
}
}
void ValidatePackageInstalledProperly(LPCWSTR expectedVersion = WIDEN(WSL_PACKAGE_VERSION))
{
ValidateInstalledVersion(expectedVersion);
auto checkInstalled = []() {
auto commandLine = LxssGenerateWslCommandLine(L"echo OK");
auto [output, _, exitCode] = LxsstuLaunchCommandAndCaptureOutputWithResult(commandLine.data());
if (exitCode != 0 && output.find(L"Wsl/ERROR_SHARING_VIOLATION") != std::wstring::npos)
{
THROW_HR(HRESULT_FROM_WIN32(ERROR_RETRY));
}
return std::make_pair(exitCode, output);
};
// When upgrading from MSIX, wsl.exe might not be available right away. Retry if we get Wsl/ERROR_SHARING_VIOLATION back.
std::wstring output;
int exitCode = -1;
try
{
std::tie(exitCode, output) = wsl::shared::retry::RetryWithTimeout<std::pair<int, std::wstring>>(
checkInstalled, std::chrono::seconds(1), std::chrono::minutes(2), []() {
return wil::ResultFromCaughtException() == HRESULT_FROM_WIN32(ERROR_RETRY);
});
}
catch (...)
{
VERIFY_FAIL("Timed out waiting for WSL to be installed.");
}
VERIFY_ARE_EQUAL(exitCode, 0);
VERIFY_ARE_EQUAL(output, L"OK\n");
// Check that the installed version is the one we expect
const auto key = wsl::windows::common::registry::OpenLxssMachineKey();
const auto version = wsl::windows::common::registry::ReadString(key.get(), L"MSI", L"Version", L"");
VERIFY_ARE_EQUAL(version, expectedVersion);
VERIFY_IS_FALSE(GetMsiProductCode().empty());
// TODO: check wslsupport, wslapi and p9rdr
}
void DeleteProductCode() const
{
const auto msiKey = wsl::windows::common::registry::OpenKey(m_lxssKey.get(), L"MSI", KEY_ALL_ACCESS);
wsl::windows::common::registry::DeleteKeyValue(msiKey.get(), L"ProductCode");
}
void InstallGitHubRelease(const std::wstring& version)
{
auto arch = wsl::shared::Arm64 ? L".0.arm64" : L".0.x64";
std::wstring installerFile;
auto cleanup = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, [&installerFile]() { DeleteFile(installerFile.c_str()); });
if (auto found = L"wsl." + version + arch + L".msi"; PathFileExists(found.c_str()))
{
installerFile = std::filesystem::weakly_canonical(found);
cleanup.release();
}
else if (auto found = L"Microsoft.WSL_" + version + L".0_x64_ARM64.msixbundle"; PathFileExists(found.c_str()))
{
installerFile = std::filesystem::weakly_canonical(found);
cleanup.release();
}
else
{
LogInfo("Downloading: %ls", version.c_str());
VERIFY_IS_TRUE(g_pipelineBuildId.empty()); // Pipeline builds should have the installers already available
auto release = wsl::windows::common::wslutil::GetGitHubReleaseByTag(version);
auto asset = wsl::windows::common::wslutil::GetGitHubAssetFromRelease(release);
VERIFY_IS_TRUE(asset.has_value());
auto downloadPath = wsl::windows::common::wslutil::DownloadFile(asset->second.url, asset->second.name);
installerFile = std::move(downloadPath);
}
LogInfo("Installing: %ls", installerFile.c_str());
if (wsl::shared::string::EndsWith<wchar_t>(installerFile, L".msi"))
{
PrepareForMsiOperation();
CallMsiExec(std::format(L"/qn /norestart /i {} /L*V {}", installerFile, GenerateMsiLogPath()));
}
else
{
auto result =
m_packageManager
.AddPackageAsync(winrt::Windows::Foundation::Uri{installerFile}, nullptr, winrt::Windows::Management::Deployment::DeploymentOptions::None)
.get();
VERIFY_SUCCEEDED(result.ExtendedErrorCode());
}
ValidateInstalledVersion(version.c_str());
}
TEST_METHOD(UpgradeFromWsl130)
{
UninstallMsi();
InstallGitHubRelease(L"1.3.17");
// Note: we can't use wsl --update here because GitHubUrlOverride was introduced in 2.0.0
InstallMsi();
ValidatePackageInstalledProperly();
}
TEST_METHOD(UpgradeFromWsl200)
{
UninstallMsi();
// Note: we can't use wsl --update here because wsl 2.0.0 passes REINSTALL=ALL to msiexec
InstallGitHubRelease(L"2.0.0");
InstallMsi();
ValidatePackageInstalledProperly();
}
TEST_METHOD(UpgradeFromWsl202)
{
UninstallMsi();
InstallGitHubRelease(L"2.0.2");
CallWslUpdateViaMsi();
}
TEST_METHOD(MsrdcPluginKey)
{
// Remove the MSI package.
UninstallMsi();
// Create a volatile registry key to emulate what the old MSIX would do.
const auto key = wsl::windows::common::registry::CreateKey(
HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Terminal Server Client\\Default", KEY_ALL_ACCESS);
VERIFY_IS_TRUE(!!key);
wsl::windows::common::registry::DeleteKey(key.get(), L"OptionalAddIns\\WSLDVC_PACKAGE");
const auto volatileKey =
wsl::windows::common::registry::CreateKey(key.get(), L"OptionalAddIns\\WSLDVC_PACKAGE", KEY_READ, nullptr, REG_OPTION_VOLATILE);
VERIFY_IS_TRUE(wsl::windows::common::registry::IsKeyVolatile(volatileKey.get()));
// Install the MSI.
InstallMsi();
// Validate that the key is correctly written to and isn't volatile anymore.
auto pluginPath = wsl::windows::common::wslutil::GetMsiPackagePath().value_or(L"");
VERIFY_IS_FALSE(pluginPath.empty());
pluginPath += L"WSLDVCPlugin.dll";
const auto pluginKey = wsl::windows::common::registry::OpenKey(
HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Terminal Server Client\\Default\\OptionalAddIns\\WSLDVC_PACKAGE", KEY_READ);
const auto value = wsl::windows::common::registry::ReadString(pluginKey.get(), nullptr, L"Name", L"");
VERIFY_ARE_EQUAL(value, pluginPath);
VERIFY_IS_FALSE(wsl::windows::common::registry::IsKeyVolatile(pluginKey.get()));
}
TEST_METHOD(UninstallingMsiRemovesInstallerMsix)
{
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
InstallMsix();
WaitForMsiPackageInstall();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_TRUE(IsMsixInstallerInstalled());
ValidatePackageInstalledProperly();
}
TEST_METHOD(InstallingMsiInstallsGluePackage)
{
// Remove the MSI package
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
// Installing it again and validate that the glue package was added
InstallMsi();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_FALSE(IsMsixInstallerInstalled());
ValidatePackageInstalledProperly();
// Validate that removing it removes the glue package
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
// Validate that installing the installer gets the MSI installed properly again
InstallMsix();
WaitForMsiPackageInstall();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_TRUE(IsMsixInstallerInstalled());
ValidatePackageInstalledProperly();
}
TEST_METHOD(UpgradeInstallsTheMsiPackage)
{
// Remove the MSIX package
UninstallMsix();
VERIFY_IS_FALSE(IsMsixInstalled());
// Validate that upgrading the MSI installs the MSIX again
InstallMsi();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_FALSE(IsMsixInstallerInstalled());
ValidatePackageInstalledProperly();
}
TEST_METHOD(MsixInstallerUpgrades)
{
// Remove the MSIX package
UninstallMsix();
VERIFY_IS_FALSE(IsMsixInstalled());
// Remove the MSI package
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
RegistryKeyChange<std::wstring> change(
HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Lxss\\MSI", L"Version", L"1.0.0");
DeleteProductCode();
VERIFY_IS_TRUE(GetMsiProductCode().empty());
// Validate that upgrading the MSIX upgrades the MSI
InstallMsix();
WaitForMsiPackageInstall();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_TRUE(IsMsixInstallerInstalled());
// Validate that the version got upgraded
const auto key = wsl::windows::common::registry::OpenLxssMachineKey();
const auto versionValue = wsl::windows::common::registry::ReadString(key.get(), L"MSI", L"Version");
VERIFY_ARE_EQUAL(versionValue, WIDEN(WSL_PACKAGE_VERSION));
}
TEST_METHOD(MsixInstallerUpgradesWithLogFile)
{
// Remove the MSIX package
UninstallMsix();
VERIFY_IS_FALSE(IsMsixInstalled());
// Remove the MSI package
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
RegistryKeyChange<std::wstring> version(
HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Lxss\\MSI", L"Version", L"1.0.0");
auto logFilePath = std::filesystem::current_path() / "msi-install-logs.txt";
RegistryKeyChange<std::wstring> logFile(
HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Lxss\\MSI", L"UpgradeLogFile", logFilePath.c_str());
auto cleanup =
wil::scope_exit_log(WI_DIAGNOSTICS_INFO, [&logFilePath]() { LOG_IF_WIN32_BOOL_FALSE(DeleteFile(logFilePath.c_str())); });
DeleteProductCode();
VERIFY_IS_TRUE(GetMsiProductCode().empty());
// Validate that upgrading the MSIX upgrades the MSI
InstallMsix();
WaitForMsiPackageInstall();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_TRUE(IsMsixInstallerInstalled());
// Validate that the version got upgraded
const auto key = wsl::windows::common::registry::OpenLxssMachineKey();
const auto versionValue = wsl::windows::common::registry::ReadString(key.get(), L"MSI", L"Version");
VERIFY_ARE_EQUAL(versionValue, WIDEN(WSL_PACKAGE_VERSION));
// Validate that the log file exists and is not empty
VERIFY_IS_TRUE(std::filesystem::exists(logFilePath));
VERIFY_ARE_NOT_EQUAL(std::filesystem::file_size(logFilePath), 0);
}
TEST_METHOD(MsixInstallerDoesntDowngrade)
{
// Remove the MSIX package
UninstallMsix();
VERIFY_IS_FALSE(IsMsixInstalled());
RegistryKeyChange<std::wstring> change(
HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Lxss\\MSI", L"Version", L"999.0.0");
// Validate that upgrading the MSIX doesn't downgrade the MSI
InstallMsix();
WaitForInstallerServiceStop();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_TRUE(IsMsixInstallerInstalled());
// Validate that the version dit not get upgrade
const auto key = wsl::windows::common::registry::OpenLxssMachineKey();
const auto versionValue = wsl::windows::common::registry::ReadString(key.get(), L"MSI", L"Version");
VERIFY_ARE_EQUAL(versionValue, L"999.0.0");
}
TEST_METHOD(MsixUpgradeManual)
{
// Registry key to disable auto upgrade on service start
RegistryKeyChange<DWORD> change(
HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Lxss\\MSI", L"AutoUpgradeViaMsix", static_cast<DWORD>(0));
// Remove the MSI package
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
// Install the installer MSIX
InstallMsix();
// Validate that calling wsl.exe triggers the install
auto [output, warnings] = LxsstuLaunchWslAndCaptureOutput(L"echo ok");
VERIFY_ARE_EQUAL(L"ok\n", output);
VERIFY_ARE_EQUAL(L"WSL is finishing an upgrade...\r\n", warnings);
ValidatePackageInstalledProperly();
}
TEST_METHOD(MsixUpgradeFails)
{
// Remove the MSI package
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
auto cleanup = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, [&]() { InstallMsi(); });
// Open a handle to wsl.exe in the install directory which will cause the installation to fail.
//
// N.B. The file handle will be closed before the cleanup lambda runs.
std::filesystem::create_directories(m_installedPath);
wil::unique_hfile fileHandle(::CreateFileW(
(m_installedPath / WSL_BINARY_NAME).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr));
// Install the installer MSIX
InstallMsix();
// Validate that calling wsl.exe triggers the install.
auto [output, warnings] = LxsstuLaunchWslAndCaptureOutput(L"echo ok", -1, nulDevice.get());
VERIFY_ARE_EQUAL(
L"\r\nAnother application has exclusive access to the file 'C:\\Program Files\\WSL\\wsl.exe'. Please shut down all "
L"other applications, then click Retry.\r\n"
L"Update failed (exit code: 1603).\r\n"
L"Error code: Wsl/CallMsi/Install/ERROR_INSTALL_FAILURE\r\n",
output);
}
TEST_METHOD(WslUpdateNoNewVersion)
{
constexpr auto endpoint = L"http://127.0.0.1:12345/";
RegistryKeyChange<std::wstring> change(
HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Lxss", wsl::windows::common::wslutil::c_githubUrlOverrideRegistryValue, endpoint);
constexpr auto GitHubApiResponse =
LR"({
\"name\": \"1.0.0\",
\"created_at\": \"2023-06-14T16:56:30Z\",
\"assets\": [
{
\"url\": \"https://api.github.com/repos/microsoft/WSL/releases/assets/112754644\",
\"id\": 112754644,
\"name\": \"Microsoft.WSL_1.0.0.0_x64_ARM64.msixbundle\"
}
]
})";
UniqueWebServer server(endpoint, GitHubApiResponse);
auto [out, _] = LxsstuLaunchWslAndCaptureOutput(L"--update");
VERIFY_ARE_EQUAL(
out, L"Checking for updates.\r\nThe most recent version of Windows Subsystem for Linux is already installed.\r\n");
}
TEST_METHOD(InstallRemovesStaleComRegistration)
{
constexpr auto clsid = L"{A9B7A1B9-0671-405C-95F1-E0612CB4CE7E}";
// Remove the MSI package
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
// Emulate a leaked packaged COM registration
auto packagedComClassIndex{wsl::windows::common::registry::OpenKey(
HKEY_LOCAL_MACHINE, L"SOFTWARE\\Classes\\PackagedCom\\ClassIndex", KEY_CREATE_SUB_KEY | KEY_READ)};
auto keyExists = [&packagedComClassIndex]() {
wil::unique_hkey subKey;
const auto result = RegOpenKeyEx(packagedComClassIndex.get(), clsid, 0, KEY_READ, &subKey);
return result == NO_ERROR;
};
wsl::windows::common::registry::CreateKey(packagedComClassIndex.get(), clsid);
VERIFY_IS_TRUE(keyExists());
// Install the package and validate that the registry key was removed.
InstallMsi();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_FALSE(IsMsixInstallerInstalled());
VERIFY_IS_FALSE(keyExists());
ValidatePackageInstalledProperly();
}
TEST_METHOD(InstallremovesStaleServiceRegistration)
{
// Remove the MSI package.
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
// Emulate a leaked packaged service registration.
const wil::unique_schandle manager{OpenSCManager(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE)};
wil::unique_schandle service{CreateService(
manager.get(),
L"wslservice",
L"WSL test service",
GENERIC_ALL,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DISABLED,
SERVICE_ERROR_IGNORE,
L"C:\\windows\\system32\\cmd.exe",
nullptr,
nullptr,
nullptr,
nullptr,
nullptr)};
service.reset();
wil::unique_hkey key = wsl::windows::common::registry::OpenKey(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services", KEY_WRITE);
THROW_LAST_ERROR_IF(!key);
wsl::windows::common::registry::WriteString(key.get(), L"wslservice", L"AppUserModelId", L"Dummy");
key.reset();
auto cleanup = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, [&]() {
service.reset(OpenService(manager.get(), L"wslservice", DELETE));
THROW_LAST_ERROR_IF(!service);
LOG_IF_WIN32_BOOL_FALSE(DeleteService(service.get()));
});
// Install the MSI package. It should delete the wslservice.
InstallMsi();
cleanup.release();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
ValidatePackageInstalledProperly();
// Validate that the AppUserModelId registry value is gone.
VERIFY_ARE_EQUAL(wsl::windows::common::registry::ReadString(key.get(), L"wslservice", L"AppUserModelId", L""), L"");
}
TEST_METHOD(InstallSetsLspRegistration)
{
auto installPath = wsl::windows::common::wslutil::GetMsiPackagePath();
VERIFY_IS_TRUE(installPath.has_value());
// Remove the MSI package.
UninstallMsi();
VERIFY_IS_FALSE(IsMsiPackageInstalled());
VERIFY_IS_FALSE(IsMsixInstalled());
// Validate that LSP flags are not set
auto getLspFlags = [&installPath](const auto* path) -> std::optional<DWORD> {
DWORD flags{};
INT error{};
if (WSCGetApplicationCategory(path, static_cast<DWORD>(wcslen(path)), nullptr, 0, &flags, &error) == SOCKET_ERROR)
{
if (error != WSASERVICE_NOT_FOUND)
{
LogError("WSCGetApplicationCategory failed for: %ls, error: %i", path, error);
}
return {};
}
return flags;
};
const std::vector<LPCWSTR> executables = {L"wsl.exe", L"wslhost.exe", L"wslrelay.exe", L"wslg.exe"};
for (const auto& e : executables)
{
auto fullPath = installPath.value() + e;
VERIFY_ARE_EQUAL(getLspFlags(fullPath.c_str()).value_or(0), 0);
}
// Install the package
InstallMsi();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
ValidatePackageInstalledProperly();
// Validate that the LSP flags were correctly set
for (const auto& e : executables)
{
auto fullPath = installPath.value() + e;
VERIFY_ARE_EQUAL(getLspFlags(fullPath.c_str()).value_or(0), LSP_SYSTEM);
}
}
TEST_METHOD(InstallClearsExplorerState)
{
constexpr auto valueName = L"Attributes";
// Put the explorer in a state where the WSL shortcut is hidden.
const auto key = wsl::windows::common::registry::CreateKey(
HKEY_CURRENT_USER,
LR"(Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID\{B2B4A4D1-2754-4140-A2EB-9A76D9D7CDC6}\ShellFolder)",
KEY_READ | KEY_WRITE);
wsl::windows::common::registry::WriteDword(key.get(), nullptr, valueName, SFGAO_NONENUMERATED);
// Install the package
InstallMsi();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
ValidatePackageInstalledProperly();
// Validate that the installer removed the problematic flag
VERIFY_ARE_EQUAL(wsl::windows::common::registry::ReadDword(key.get(), nullptr, valueName, 0), 0);
}
TEST_METHOD(InstallUnprotectsKeys)
{
const auto installPath = wsl::windows::common::wslutil::GetMsiPackagePath();
VERIFY_IS_TRUE(installPath.has_value());
constexpr auto keyPath = LR"(SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\IdListAliasTranslations\WSL)";
// Create a protected key that the installer will write to
{
auto [localAdministratorsSid, adminSidBuffer] =
wsl::windows::common::security::CreateSid(SECURITY_NT_AUTHORITY, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS);
EXPLICIT_ACCESS aces[2];
aces[0].grfAccessMode = SET_ACCESS;
aces[0].grfAccessPermissions = KEY_READ;
aces[0].grfInheritance = NO_INHERITANCE;
BuildTrusteeWithSid(&aces[0].Trustee, localAdministratorsSid);
aces[1].grfAccessMode = GRANT_ACCESS;
aces[1].grfAccessPermissions = KEY_ALL_ACCESS;
aces[1].grfInheritance = NO_INHERITANCE;
std::wstring trustedInstaller = L"NT Service\\TrustedInstaller";
BuildTrusteeWithName(&aces[1].Trustee, trustedInstaller.data());
wsl::windows::common::security::unique_acl newAcl{};
THROW_IF_WIN32_ERROR(SetEntriesInAcl(2, aces, nullptr, &newAcl));
SECURITY_DESCRIPTOR newDescriptor{};
THROW_IF_WIN32_BOOL_FALSE(InitializeSecurityDescriptor(&newDescriptor, SECURITY_DESCRIPTOR_REVISION));
THROW_IF_WIN32_BOOL_FALSE(SetSecurityDescriptorDacl(&newDescriptor, true, newAcl.get(), false));
auto restore = wsl::windows::common::security::AcquirePrivileges({SE_BACKUP_NAME, SE_RESTORE_NAME});
const auto key =
wsl::windows::common::registry::CreateKey(HKEY_LOCAL_MACHINE, keyPath, KEY_ALL_ACCESS, nullptr, REG_OPTION_BACKUP_RESTORE);
THROW_IF_WIN32_ERROR(RegSetKeySecurity(key.get(), DACL_SECURITY_INFORMATION, &newDescriptor));
}
VERIFY_IS_TRUE(SfcIsKeyProtected(HKEY_LOCAL_MACHINE, keyPath, KEY_WOW64_64KEY));
// Install the package
InstallMsi();
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
ValidatePackageInstalledProperly();
// Verify that key was unprotected.
VERIFY_IS_FALSE(SfcIsKeyProtected(HKEY_LOCAL_MACHINE, keyPath, KEY_WOW64_64KEY));
}
void CallWslUpdateViaMsi()
{
#ifdef WSL_DEV_THIN_MSI_PACKAGE
LogSkipped("This test case cannot run with a thin MSI package");
return;
#endif
constexpr auto endpoint = L"http://127.0.0.1:12345/";
RegistryKeyChange<std::wstring> change(
HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Lxss", wsl::windows::common::wslutil::c_githubUrlOverrideRegistryValue, endpoint);
constexpr auto GitHubApiResponse =
LR"({
\"name\": \"999.0.0\",
\"created_at\": \"2023-06-14T16:56:30Z\",
\"assets\": [
{
\"url\": \"http://127.0.0.1:12346/wsl.testpackage.x64.msi\",
\"id\": 0,
\"name\": \"wsl.testpackage.x64.msi\"
}
]
})";
UniqueWebServer apiServer(endpoint, GitHubApiResponse);
UniqueWebServer fileServer(L"http://127.0.0.1:12346/", std::filesystem::path(m_msiPath));
// DeleteProductCode();
// TODO: It would be good to remove something to validate that the MSI actually gets installed,
// but this doesn't work during the tests because the ProductCode is the same so the components
// don't actually get reinstalled and we can't use REINSTALLMODE because this would skip component removal
// during upgrade.
// The MSI upgrade can send a ctrl-c to wsl.exe, so create a new console so the test process doesn't receive the ctrl-c.
const auto commandLine = LxssGenerateWslCommandLine(L"--update");
wsl::windows::common::SubProcess process(nullptr, commandLine.data(), CREATE_NEW_CONSOLE);
process.SetShowWindow(SW_HIDE);
LogInfo("wsl --update exited with: %lu", process.Run());
// wsl --update isn't synchronous since wsl.exe will be killed during the installation.
WaitForMsiPackageInstall();
ValidatePackageInstalledProperly();
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_TRUE(!GetMsiProductCode().empty());
}
TEST_METHOD(WslUpdateViaMsi)
{
CallWslUpdateViaMsi();
}
TEST_METHOD(WslUpdateViaMsix)
{
constexpr auto endpoint = L"http://127.0.0.1:12345/";
RegistryKeyChange<std::wstring> change(
HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Lxss", wsl::windows::common::wslutil::c_githubUrlOverrideRegistryValue, endpoint);
constexpr auto GitHubApiResponse =
LR"({
\"name\": \"999.0.0\",
\"created_at\": \"2023-06-14T16:56:30Z\",
\"assets\": [
{
\"url\": \"http://127.0.0.1:12346/wsl.testpackage.msixbundle\",
\"id\": 0,
\"name\": \"wsl.testpackage.x64.msixbundle\"
}
]
})";
UniqueWebServer apiServer(endpoint, GitHubApiResponse);
UniqueWebServer fileServer(L"http://127.0.0.1:12346/", std::filesystem::path(m_msixPackagePath));
UninstallMsix();
VERIFY_IS_FALSE(IsMsixInstalled());
const auto installLocation = wsl::windows::common::wslutil::GetMsiPackagePath();
VERIFY_IS_TRUE(installLocation.has_value());
auto cmd = installLocation.value() + L"\\wsl.exe --update";
LxsstuRunCommand(cmd.data()); // Ignore the error code since wsl.exe will be killed by msiexec
VERIFY_IS_TRUE(IsMsiPackageInstalled());
VERIFY_IS_TRUE(IsMsixInstalled());
VERIFY_IS_TRUE(IsMsixInstallerInstalled());
ValidatePackageInstalledProperly();
}
static bool WslSettingsProtocolAssociationExists()
{
wil::com_ptr<IEnumAssocHandlers> enumAssocHandlers;
if (FAILED(SHAssocEnumHandlersForProtocolByApplication(L"wsl-settings", IID_PPV_ARGS(&enumAssocHandlers))))
{
return false;
}
ULONG elementsReturned;