Merge pull request #308829 from r-ryantm/auto-update/qlog
[NixPkgs.git] / nixos / tests / installer.nix
blob7e835041eb39fd636b3d03bca1edd336032b1ec2
1 { system ? builtins.currentSystem,
2   config ? {},
3   pkgs ? import ../.. { inherit system config; },
4   systemdStage1 ? false
5 }:
7 with import ../lib/testing-python.nix { inherit system pkgs; };
8 with pkgs.lib;
10 let
12   # The configuration to install.
13   makeConfig = { bootLoader, grubDevice, grubIdentifier, grubUseEfi
14                , extraConfig, forceGrubReinstallCount ? 0, flake ? false
15                , clevisTest
16                }:
17     pkgs.writeText "configuration.nix" ''
18       { config, lib, pkgs, modulesPath, ... }:
20       { imports =
21           [ ./hardware-configuration.nix
22             ${if flake
23               then "" # Still included, but via installer/flake.nix
24               else "<nixpkgs/nixos/modules/testing/test-instrumentation.nix>"}
25           ];
27         networking.hostName = "thatworked";
29         documentation.enable = false;
31         # To ensure that we can rebuild the grub configuration on the nixos-rebuild
32         system.extraDependencies = with pkgs; [ stdenvNoCC ];
34         ${optionalString systemdStage1 "boot.initrd.systemd.enable = true;"}
36         ${optionalString (bootLoader == "grub") ''
37           boot.loader.grub.extraConfig = "serial; terminal_output serial";
38           ${if grubUseEfi then ''
39             boot.loader.grub.device = "nodev";
40             boot.loader.grub.efiSupport = true;
41             boot.loader.grub.efiInstallAsRemovable = true; # XXX: needed for OVMF?
42           '' else ''
43             boot.loader.grub.device = "${grubDevice}";
44             boot.loader.grub.fsIdentifier = "${grubIdentifier}";
45           ''}
47           boot.loader.grub.configurationLimit = 100 + ${toString forceGrubReinstallCount};
48         ''}
50         ${optionalString (bootLoader == "systemd-boot") ''
51           boot.loader.systemd-boot.enable = true;
52         ''}
54         boot.initrd.secrets."/etc/secret" = "/etc/nixos/secret";
56         ${optionalString clevisTest ''
57           boot.kernelParams = [ "console=tty0" "ip=192.168.1.1:::255.255.255.0::eth1:none" ];
58           boot.initrd = {
59             availableKernelModules = [ "tpm_tis" ];
60             clevis = { enable = true; useTang = true; };
61             network.enable = true;
62           };
63           ''}
65         users.users.alice = {
66           isNormalUser = true;
67           home = "/home/alice";
68           description = "Alice Foobar";
69         };
71         hardware.enableAllFirmware = lib.mkForce false;
73         ${replaceStrings ["\n"] ["\n  "] extraConfig}
74       }
75     '';
78   # The test script boots a NixOS VM, installs NixOS on an empty hard
79   # disk, and then reboot from the hard disk.  It's parameterized with
80   # a test script fragment `createPartitions', which must create
81   # partitions and filesystems.
82   testScriptFun = { bootLoader, createPartitions, grubDevice, grubUseEfi, grubIdentifier
83                   , postInstallCommands, postBootCommands, extraConfig
84                   , testSpecialisationConfig, testFlakeSwitch, clevisTest, clevisFallbackTest
85                   , disableFileSystems
86                   }:
87     let
88       startTarget = ''
89         ${optionalString clevisTest "tpm.start()"}
90         target.start()
91         ${postBootCommands}
92         target.wait_for_unit("multi-user.target")
93       '';
94     in ''
95       ${optionalString clevisTest ''
96       import os
97       import subprocess
99       tpm_folder = os.environ['NIX_BUILD_TOP']
101       class Tpm:
102             def __init__(self):
103                 self.start()
105             def start(self):
106                 self.proc = subprocess.Popen(["${pkgs.swtpm}/bin/swtpm",
107                     "socket",
108                     "--tpmstate", f"dir={tpm_folder}/swtpm",
109                     "--ctrl", f"type=unixio,path={tpm_folder}/swtpm-sock",
110                     "--tpm2"
111                     ])
113                 # Check whether starting swtpm failed
114                 try:
115                     exit_code = self.proc.wait(timeout=0.2)
116                     if exit_code is not None and exit_code != 0:
117                         raise Exception("failed to start swtpm")
118                 except subprocess.TimeoutExpired:
119                     pass
121             """Check whether the swtpm process exited due to an error"""
122             def check(self):
123                 exit_code = self.proc.poll()
124                 if exit_code is not None and exit_code != 0:
125                     raise Exception("swtpm process died")
128       os.mkdir(f"{tpm_folder}/swtpm")
129       tpm = Tpm()
130       tpm.check()
131       ''}
133       installer.start()
134       ${optionalString clevisTest ''
135       tang.start()
136       tang.wait_for_unit("sockets.target")
137       tang.systemctl("start network-online.target")
138       tang.wait_for_unit("network-online.target")
139       installer.systemctl("start network-online.target")
140       installer.wait_for_unit("network-online.target")
141       ''}
142       installer.wait_for_unit("multi-user.target")
144       with subtest("Assert readiness of login prompt"):
145           installer.succeed("echo hello")
147       with subtest("Wait for hard disks to appear in /dev"):
148           installer.succeed("udevadm settle")
150       ${createPartitions}
152       with subtest("Create the NixOS configuration"):
153           installer.succeed("nixos-generate-config ${optionalString disableFileSystems "--no-filesystems"} --root /mnt")
154           installer.succeed("cat /mnt/etc/nixos/hardware-configuration.nix >&2")
155           installer.copy_from_host(
156               "${ makeConfig {
157                     inherit bootLoader grubDevice grubIdentifier
158                             grubUseEfi extraConfig clevisTest;
159                   }
160               }",
161               "/mnt/etc/nixos/configuration.nix",
162           )
163           installer.copy_from_host("${pkgs.writeText "secret" "secret"}", "/mnt/etc/nixos/secret")
165       ${optionalString clevisTest ''
166         with subtest("Create the Clevis secret with Tang"):
167              installer.systemctl("start network-online.target")
168              installer.wait_for_unit("network-online.target")
169              installer.succeed('echo -n password | clevis encrypt sss \'{"t": 2, "pins": {"tpm2": {}, "tang": {"url": "http://192.168.1.2"}}}\' -y > /mnt/etc/nixos/clevis-secret.jwe')''}
171       ${optionalString clevisFallbackTest ''
172         with subtest("Shutdown Tang to check fallback to interactive prompt"):
173             tang.shutdown()
174       ''}
176       with subtest("Perform the installation"):
177           installer.succeed("nixos-install < /dev/null >&2")
179       with subtest("Do it again to make sure it's idempotent"):
180           installer.succeed("nixos-install < /dev/null >&2")
182       with subtest("Check that we can build things in nixos-enter"):
183           installer.succeed(
184               """
185               nixos-enter -- nix-build --option substitute false -E 'derivation {
186                   name = "t";
187                   builder = "/bin/sh";
188                   args = ["-c" "echo nixos-enter build > $out"];
189                   system = builtins.currentSystem;
190                   preferLocalBuild = true;
191               }'
192               """
193           )
195       ${postInstallCommands}
197       with subtest("Shutdown system after installation"):
198           installer.succeed("umount -R /mnt")
199           installer.succeed("sync")
200           installer.shutdown()
202       # We're actually the same machine, just booting differently this time.
203       target.state_dir = installer.state_dir
205       # Now see if we can boot the installation.
206       ${startTarget}
208       with subtest("Assert that /boot get mounted"):
209           target.wait_for_unit("local-fs.target")
210           ${if bootLoader == "grub"
211               then ''target.succeed("test -e /boot/grub")''
212               else ''target.succeed("test -e /boot/loader/loader.conf")''
213           }
215       with subtest("Check whether /root has correct permissions"):
216           assert "700" in target.succeed("stat -c '%a' /root")
218       with subtest("Assert swap device got activated"):
219           # uncomment once https://bugs.freedesktop.org/show_bug.cgi?id=86930 is resolved
220           target.wait_for_unit("swap.target")
221           target.succeed("cat /proc/swaps | grep -q /dev")
223       with subtest("Check that the store is in good shape"):
224           target.succeed("nix-store --verify --check-contents >&2")
226       with subtest("Check whether the channel works"):
227           target.succeed("nix-env -iA nixos.procps >&2")
228           assert ".nix-profile" in target.succeed("type -tP ps | tee /dev/stderr")
230       with subtest(
231           "Check that the daemon works, and that non-root users can run builds "
232           "(this will build a new profile generation through the daemon)"
233       ):
234           target.succeed("su alice -l -c 'nix-env -iA nixos.procps' >&2")
236       with subtest("Configure system with writable Nix store on next boot"):
237           # we're not using copy_from_host here because the installer image
238           # doesn't know about the host-guest sharing mechanism.
239           target.copy_from_host_via_shell(
240               "${ makeConfig {
241                     inherit bootLoader grubDevice grubIdentifier
242                             grubUseEfi extraConfig clevisTest;
243                     forceGrubReinstallCount = 1;
244                   }
245               }",
246               "/etc/nixos/configuration.nix",
247           )
249       with subtest("Check whether nixos-rebuild works"):
250           target.succeed("nixos-rebuild switch >&2")
252       # FIXME: Nix 2.4 broke nixos-option, someone has to fix it.
253       # with subtest("Test nixos-option"):
254       #     kernel_modules = target.succeed("nixos-option boot.initrd.kernelModules")
255       #     assert "virtio_console" in kernel_modules
256       #     assert "List of modules" in kernel_modules
257       #     assert "qemu-guest.nix" in kernel_modules
259       target.shutdown()
261       # Check whether a writable store build works
262       ${startTarget}
264       # we're not using copy_from_host here because the installer image
265       # doesn't know about the host-guest sharing mechanism.
266       target.copy_from_host_via_shell(
267           "${ makeConfig {
268                 inherit bootLoader grubDevice grubIdentifier
269                 grubUseEfi extraConfig clevisTest;
270                 forceGrubReinstallCount = 2;
271               }
272           }",
273           "/etc/nixos/configuration.nix",
274       )
275       target.succeed("nixos-rebuild boot >&2")
276       target.shutdown()
278       # And just to be sure, check that the target still boots after "nixos-rebuild switch".
279       ${startTarget}
280       target.wait_for_unit("network.target")
282       # Sanity check, is it the configuration.nix we generated?
283       hostname = target.succeed("hostname").strip()
284       assert hostname == "thatworked"
286       target.shutdown()
288       # Tests for validating clone configuration entries in grub menu
289     ''
290     + optionalString testSpecialisationConfig ''
291       # Reboot target
292       ${startTarget}
294       with subtest("Booted configuration name should be 'Home'"):
295           # This is not the name that shows in the grub menu.
296           # The default configuration is always shown as "Default"
297           target.succeed("cat /run/booted-system/configuration-name >&2")
298           assert "Home" in target.succeed("cat /run/booted-system/configuration-name")
300       with subtest("We should **not** find a file named /etc/gitconfig"):
301           target.fail("test -e /etc/gitconfig")
303       with subtest("Set grub to boot the second configuration"):
304           target.succeed("grub-reboot 1")
306       target.shutdown()
308       # Reboot target
309       ${startTarget}
311       with subtest("Booted configuration name should be Work"):
312           target.succeed("cat /run/booted-system/configuration-name >&2")
313           assert "Work" in target.succeed("cat /run/booted-system/configuration-name")
315       with subtest("We should find a file named /etc/gitconfig"):
316           target.succeed("test -e /etc/gitconfig")
318       target.shutdown()
319     ''
320     + optionalString testFlakeSwitch ''
321       ${startTarget}
323       with subtest("Configure system with flake"):
324         # TODO: evaluate as user?
325         target.succeed("""
326           mkdir /root/my-config
327           mv /etc/nixos/hardware-configuration.nix /root/my-config/
328           rm /etc/nixos/configuration.nix
329         """)
330         target.copy_from_host_via_shell(
331           "${makeConfig {
332                inherit bootLoader grubDevice grubIdentifier grubUseEfi extraConfig clevisTest;
333                forceGrubReinstallCount = 1;
334                flake = true;
335             }}",
336           "/root/my-config/configuration.nix",
337         )
338         target.copy_from_host_via_shell(
339           "${./installer/flake.nix}",
340           "/root/my-config/flake.nix",
341         )
342         target.succeed("""
343           # for some reason the image does not have `pkgs.path`, so
344           # we use readlink to find a Nixpkgs source.
345           pkgs=$(readlink -f /nix/var/nix/profiles/per-user/root/channels)/nixos
346           if ! [[ -e $pkgs/pkgs/top-level/default.nix ]]; then
347             echo 1>&2 "$pkgs does not seem to be a nixpkgs source. Please fix the test so that pkgs points to a nixpkgs source.";
348             exit 1;
349           fi
350           sed -e s^@nixpkgs@^$pkgs^ -i /root/my-config/flake.nix
351         """)
353       with subtest("Switch to flake based config"):
354         target.succeed("nixos-rebuild switch --flake /root/my-config#xyz")
356       target.shutdown()
358       ${startTarget}
360       with subtest("nix-channel command is not available anymore"):
361         target.succeed("! which nix-channel")
363       # Note that the channel profile is still present on disk, but configured
364       # not to be used.
365       with subtest("builtins.nixPath is now empty"):
366         target.succeed("""
367           [[ "[ ]" == "$(nix-instantiate builtins.nixPath --eval --expr)" ]]
368         """)
370       with subtest("<nixpkgs> does not resolve"):
371         target.succeed("""
372           ! nix-instantiate '<nixpkgs>' --eval --expr
373         """)
375       with subtest("Evaluate flake config in fresh env without nix-channel"):
376         target.succeed("nixos-rebuild switch --flake /root/my-config#xyz")
378       with subtest("Evaluate flake config in fresh env without channel profiles"):
379         target.succeed("""
380           (
381             exec 1>&2
382             rm -v /root/.nix-channels
383             rm -vrf ~/.nix-defexpr
384             rm -vrf /nix/var/nix/profiles/per-user/root/channels*
385           )
386         """)
387         target.succeed("nixos-rebuild switch --flake /root/my-config#xyz")
389       target.shutdown()
390     '';
393   makeInstallerTest = name:
394     { createPartitions
395     , postInstallCommands ? "", postBootCommands ? ""
396     , extraConfig ? ""
397     , extraInstallerConfig ? {}
398     , bootLoader ? "grub" # either "grub" or "systemd-boot"
399     , grubDevice ? "/dev/vda", grubIdentifier ? "uuid", grubUseEfi ? false
400     , enableOCR ? false, meta ? {}
401     , testSpecialisationConfig ? false
402     , testFlakeSwitch ? false
403     , clevisTest ? false
404     , clevisFallbackTest ? false
405     , disableFileSystems ? false
406     }:
407     let
408       isEfi = bootLoader == "systemd-boot" || (bootLoader == "grub" && grubUseEfi);
409     in makeTest {
410       inherit enableOCR;
411       name = "installer-" + name;
412       meta = {
413         # put global maintainers here, individuals go into makeInstallerTest fkt call
414         maintainers = (meta.maintainers or []);
415         # non-EFI tests can only run on x86
416         platforms = if isEfi then platforms.linux else [ "x86_64-linux" "i686-linux" ];
417       };
418       nodes = let
419         commonConfig = {
420           # builds stuff in the VM, needs more juice
421           virtualisation.diskSize = 8 * 1024;
422           virtualisation.cores = 8;
423           virtualisation.memorySize = 2048;
425           # both installer and target need to use the same drive
426           virtualisation.diskImage = "./target.qcow2";
428           # and the same TPM options
429           virtualisation.qemu.options = mkIf (clevisTest) [
430             "-chardev socket,id=chrtpm,path=$NIX_BUILD_TOP/swtpm-sock"
431             "-tpmdev emulator,id=tpm0,chardev=chrtpm"
432             "-device tpm-tis,tpmdev=tpm0"
433           ];
434         };
435       in {
436         # The configuration of the system used to run "nixos-install".
437         installer = {
438           imports = [
439             commonConfig
440             ../modules/profiles/installation-device.nix
441             ../modules/profiles/base.nix
442             extraInstallerConfig
443             ./common/auto-format-root-device.nix
444           ];
446           # In systemdStage1, also automatically format the device backing the
447           # root filesystem.
448           virtualisation.fileSystems."/".autoFormat = systemdStage1;
450           boot.initrd.systemd.enable = systemdStage1;
452           # Use a small /dev/vdb as the root disk for the
453           # installer. This ensures the target disk (/dev/vda) is
454           # the same during and after installation.
455           virtualisation.emptyDiskImages = [ 512 ];
456           virtualisation.rootDevice = "/dev/vdb";
458           hardware.enableAllFirmware = mkForce false;
460           # The test cannot access the network, so any packages we
461           # need must be included in the VM.
462           system.extraDependencies = with pkgs; [
463             bintools
464             brotli
465             brotli.dev
466             brotli.lib
467             desktop-file-utils
468             docbook5
469             docbook_xsl_ns
470             kbd.dev
471             kmod.dev
472             libarchive.dev
473             libxml2.bin
474             libxslt.bin
475             nixos-artwork.wallpapers.simple-dark-gray-bottom
476             ntp
477             perlPackages.ListCompare
478             perlPackages.XMLLibXML
479             # make-options-doc/default.nix
480             (python3.withPackages (p: [ p.mistune ]))
481             shared-mime-info
482             sudo
483             texinfo
484             unionfs-fuse
485             xorg.lndir
487             # add curl so that rather than seeing the test attempt to download
488             # curl's tarball, we see what it's trying to download
489             curl
490           ]
491           ++ optionals (bootLoader == "grub") (let
492             zfsSupport = extraInstallerConfig.boot.supportedFilesystems.zfs or false;
493           in [
494             (pkgs.grub2.override { inherit zfsSupport; })
495             (pkgs.grub2_efi.override { inherit zfsSupport; })
496           ])
497           ++ optionals (bootLoader == "systemd-boot") [
498             pkgs.zstd.bin
499             pkgs.mypy
500             pkgs.bootspec
501           ]
502           ++ optionals clevisTest [ pkgs.klibc ];
504           nix.settings = {
505             substituters = mkForce [];
506             hashed-mirrors = null;
507             connect-timeout = 1;
508           };
509         };
511         target = {
512           imports = [ commonConfig ];
513           virtualisation.useBootLoader = true;
514           virtualisation.useEFIBoot = isEfi;
515           virtualisation.useDefaultFilesystems = false;
516           virtualisation.efi.keepVariables = false;
518           virtualisation.fileSystems."/" = {
519             device = "/dev/disk/by-label/this-is-not-real-and-will-never-be-used";
520             fsType = "ext4";
521           };
522         };
523       } // optionalAttrs clevisTest {
524         tang = {
525           services.tang = {
526             enable = true;
527             listenStream = [ "80" ];
528             ipAddressAllow = [ "192.168.1.0/24" ];
529           };
530           networking.firewall.allowedTCPPorts = [ 80 ];
531         };
532       };
534       testScript = testScriptFun {
535         inherit bootLoader createPartitions postInstallCommands postBootCommands
536                 grubDevice grubIdentifier grubUseEfi extraConfig
537                 testSpecialisationConfig testFlakeSwitch clevisTest clevisFallbackTest
538                 disableFileSystems;
539       };
540     };
542     makeLuksRootTest = name: luksFormatOpts: makeInstallerTest name {
543       createPartitions = ''
544         installer.succeed(
545             "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
546             + " mkpart primary ext2 1M 100MB"  # /boot
547             + " mkpart primary linux-swap 100M 1024M"
548             + " mkpart primary 1024M -1s",  # LUKS
549             "udevadm settle",
550             "mkswap /dev/vda2 -L swap",
551             "swapon -L swap",
552             "modprobe dm_mod dm_crypt",
553             "echo -n supersecret | cryptsetup luksFormat ${luksFormatOpts} -q /dev/vda3 -",
554             "echo -n supersecret | cryptsetup luksOpen --key-file - /dev/vda3 cryptroot",
555             "mkfs.ext3 -L nixos /dev/mapper/cryptroot",
556             "mount LABEL=nixos /mnt",
557             "mkfs.ext3 -L boot /dev/vda1",
558             "mkdir -p /mnt/boot",
559             "mount LABEL=boot /mnt/boot",
560         )
561       '';
562       extraConfig = ''
563         boot.kernelParams = lib.mkAfter [ "console=tty0" ];
564       '';
565       enableOCR = true;
566       postBootCommands = ''
567         target.wait_for_text("[Pp]assphrase for")
568         target.send_chars("supersecret\n")
569       '';
570     };
572   # The (almost) simplest partitioning scheme: a swap partition and
573   # one big filesystem partition.
574   simple-test-config = {
575     createPartitions = ''
576       installer.succeed(
577           "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
578           + " mkpart primary linux-swap 1M 1024M"
579           + " mkpart primary ext2 1024M -1s",
580           "udevadm settle",
581           "mkswap /dev/vda1 -L swap",
582           "swapon -L swap",
583           "mkfs.ext3 -L nixos /dev/vda2",
584           "mount LABEL=nixos /mnt",
585       )
586     '';
587   };
589   simple-test-config-flake = simple-test-config // {
590     testFlakeSwitch = true;
591   };
593   simple-uefi-grub-config = {
594     createPartitions = ''
595       installer.succeed(
596           "flock /dev/vda parted --script /dev/vda -- mklabel gpt"
597           + " mkpart ESP fat32 1M 100MiB"  # /boot
598           + " set 1 boot on"
599           + " mkpart primary linux-swap 100MiB 1024MiB"
600           + " mkpart primary ext2 1024MiB -1MiB",  # /
601           "udevadm settle",
602           "mkswap /dev/vda2 -L swap",
603           "swapon -L swap",
604           "mkfs.ext3 -L nixos /dev/vda3",
605           "mount LABEL=nixos /mnt",
606           "mkfs.vfat -n BOOT /dev/vda1",
607           "mkdir -p /mnt/boot",
608           "mount LABEL=BOOT /mnt/boot",
609       )
610     '';
611     bootLoader = "grub";
612     grubUseEfi = true;
613   };
615   specialisation-test-extraconfig = {
616     extraConfig = ''
617       environment.systemPackages = [ pkgs.grub2 ];
618       boot.loader.grub.configurationName = "Home";
619       specialisation.work.configuration = {
620         boot.loader.grub.configurationName = lib.mkForce "Work";
622         environment.etc = {
623           "gitconfig".text = "
624             [core]
625               gitproxy = none for work.com
626               ";
627         };
628       };
629     '';
630     testSpecialisationConfig = true;
631   };
632   # disable zfs so we can support latest kernel if needed
633   no-zfs-module = {
634     nixpkgs.overlays = [(final: super: {
635       zfs = super.zfs.overrideAttrs(_: {meta.platforms = [];});}
636     )];
637   };
639  mkClevisBcachefsTest = { fallback ? false }: makeInstallerTest "clevis-bcachefs${optionalString fallback "-fallback"}" {
640     clevisTest = true;
641     clevisFallbackTest = fallback;
642     enableOCR = fallback;
643     extraInstallerConfig = {
644       imports = [ no-zfs-module ];
645       boot.supportedFilesystems = [ "bcachefs" ];
646       environment.systemPackages = with pkgs; [ keyutils clevis ];
647     };
648     createPartitions = ''
649       installer.succeed(
650         "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
651         + " mkpart primary ext2 1M 100MB"
652         + " mkpart primary linux-swap 100M 1024M"
653         + " mkpart primary 1024M -1s",
654         "udevadm settle",
655         "mkswap /dev/vda2 -L swap",
656         "swapon -L swap",
657         "keyctl link @u @s",
658         "echo -n password | mkfs.bcachefs -L root --encrypted /dev/vda3",
659         "echo -n password | bcachefs unlock /dev/vda3",
660         "echo -n password | mount -t bcachefs /dev/vda3 /mnt",
661         "mkfs.ext3 -L boot /dev/vda1",
662         "mkdir -p /mnt/boot",
663         "mount LABEL=boot /mnt/boot",
664         "udevadm settle")
665     '';
666     extraConfig = ''
667       boot.initrd.clevis.devices."/dev/vda3".secretFile = "/etc/nixos/clevis-secret.jwe";
669       # We override what nixos-generate-config has generated because we do
670       # not know the UUID in advance.
671       fileSystems."/" = lib.mkForce { device = "/dev/vda3"; fsType = "bcachefs"; };
672     '';
673     postBootCommands = optionalString fallback ''
674       target.wait_for_text("enter passphrase for")
675       target.send_chars("password\n")
676     '';
677   };
679   mkClevisLuksTest = { fallback ? false }: makeInstallerTest "clevis-luks${optionalString fallback "-fallback"}" {
680     clevisTest = true;
681     clevisFallbackTest = fallback;
682     enableOCR = fallback;
683     extraInstallerConfig = {
684       environment.systemPackages = with pkgs; [ clevis ];
685     };
686     createPartitions = ''
687       installer.succeed(
688         "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
689         + " mkpart primary ext2 1M 100MB"
690         + " mkpart primary linux-swap 100M 1024M"
691         + " mkpart primary 1024M -1s",
692         "udevadm settle",
693         "mkswap /dev/vda2 -L swap",
694         "swapon -L swap",
695         "modprobe dm_mod dm_crypt",
696         "echo -n password | cryptsetup luksFormat -q /dev/vda3 -",
697         "echo -n password | cryptsetup luksOpen --key-file - /dev/vda3 crypt-root",
698         "mkfs.ext3 -L nixos /dev/mapper/crypt-root",
699         "mount LABEL=nixos /mnt",
700         "mkfs.ext3 -L boot /dev/vda1",
701         "mkdir -p /mnt/boot",
702         "mount LABEL=boot /mnt/boot",
703         "udevadm settle")
704     '';
705     extraConfig = ''
706       boot.initrd.clevis.devices."crypt-root".secretFile = "/etc/nixos/clevis-secret.jwe";
707     '';
708     postBootCommands = optionalString fallback ''
709       ${if systemdStage1 then ''
710       target.wait_for_text("Please enter")
711       '' else ''
712       target.wait_for_text("Passphrase for")
713       ''}
714       target.send_chars("password\n")
715     '';
716   };
718   mkClevisZfsTest = { fallback ? false }: makeInstallerTest "clevis-zfs${optionalString fallback "-fallback"}" {
719     clevisTest = true;
720     clevisFallbackTest = fallback;
721     enableOCR = fallback;
722     extraInstallerConfig = {
723       boot.supportedFilesystems = [ "zfs" ];
724       environment.systemPackages = with pkgs; [ clevis ];
725     };
726     createPartitions = ''
727       installer.succeed(
728         "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
729         + " mkpart primary ext2 1M 100MB"
730         + " mkpart primary linux-swap 100M 1024M"
731         + " mkpart primary 1024M -1s",
732         "udevadm settle",
733         "mkswap /dev/vda2 -L swap",
734         "swapon -L swap",
735         "zpool create -O mountpoint=legacy rpool /dev/vda3",
736         "echo -n password | zfs create"
737         + " -o encryption=aes-256-gcm -o keyformat=passphrase rpool/root",
738         "mount -t zfs rpool/root /mnt",
739         "mkfs.ext3 -L boot /dev/vda1",
740         "mkdir -p /mnt/boot",
741         "mount LABEL=boot /mnt/boot",
742         "udevadm settle")
743     '';
744     extraConfig = ''
745       boot.initrd.clevis.devices."rpool/root".secretFile = "/etc/nixos/clevis-secret.jwe";
746       boot.zfs.requestEncryptionCredentials = true;
749       # Using by-uuid overrides the default of by-id, and is unique
750       # to the qemu disks, as they don't produce by-id paths for
751       # some reason.
752       boot.zfs.devNodes = "/dev/disk/by-uuid/";
753       networking.hostId = "00000000";
754     '';
755     postBootCommands = optionalString fallback ''
756       ${if systemdStage1 then ''
757       target.wait_for_text("Enter key for rpool/root")
758       '' else ''
759       target.wait_for_text("Key load error")
760       ''}
761       target.send_chars("password\n")
762     '';
763   };
765 in {
767   # !!! `parted mkpart' seems to silently create overlapping partitions.
770   # The (almost) simplest partitioning scheme: a swap partition and
771   # one big filesystem partition.
772   simple = makeInstallerTest "simple" simple-test-config;
774   switchToFlake = makeInstallerTest "switch-to-flake" simple-test-config-flake;
776   # Test cloned configurations with the simple grub configuration
777   simpleSpecialised = makeInstallerTest "simpleSpecialised" (simple-test-config // specialisation-test-extraconfig);
779   # Simple GPT/UEFI configuration using systemd-boot with 3 partitions: ESP, swap & root filesystem
780   simpleUefiSystemdBoot = makeInstallerTest "simpleUefiSystemdBoot" {
781     createPartitions = ''
782       installer.succeed(
783           "flock /dev/vda parted --script /dev/vda -- mklabel gpt"
784           + " mkpart ESP fat32 1M 100MiB"  # /boot
785           + " set 1 boot on"
786           + " mkpart primary linux-swap 100MiB 1024MiB"
787           + " mkpart primary ext2 1024MiB -1MiB",  # /
788           "udevadm settle",
789           "mkswap /dev/vda2 -L swap",
790           "swapon -L swap",
791           "mkfs.ext3 -L nixos /dev/vda3",
792           "mount LABEL=nixos /mnt",
793           "mkfs.vfat -n BOOT /dev/vda1",
794           "mkdir -p /mnt/boot",
795           "mount LABEL=BOOT /mnt/boot",
796       )
797     '';
798     bootLoader = "systemd-boot";
799   };
801   simpleUefiGrub = makeInstallerTest "simpleUefiGrub" simple-uefi-grub-config;
803   # Test cloned configurations with the uefi grub configuration
804   simpleUefiGrubSpecialisation = makeInstallerTest "simpleUefiGrubSpecialisation" (simple-uefi-grub-config // specialisation-test-extraconfig);
806   # Same as the previous, but now with a separate /boot partition.
807   separateBoot = makeInstallerTest "separateBoot" {
808     createPartitions = ''
809       installer.succeed(
810           "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
811           + " mkpart primary ext2 1M 100MB"  # /boot
812           + " mkpart primary linux-swap 100MB 1024M"
813           + " mkpart primary ext2 1024M -1s",  # /
814           "udevadm settle",
815           "mkswap /dev/vda2 -L swap",
816           "swapon -L swap",
817           "mkfs.ext3 -L nixos /dev/vda3",
818           "mount LABEL=nixos /mnt",
819           "mkfs.ext3 -L boot /dev/vda1",
820           "mkdir -p /mnt/boot",
821           "mount LABEL=boot /mnt/boot",
822       )
823     '';
824   };
826   # Same as the previous, but with fat32 /boot.
827   separateBootFat = makeInstallerTest "separateBootFat" {
828     createPartitions = ''
829       installer.succeed(
830           "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
831           + " mkpart primary ext2 1M 100MB"  # /boot
832           + " mkpart primary linux-swap 100MB 1024M"
833           + " mkpart primary ext2 1024M -1s",  # /
834           "udevadm settle",
835           "mkswap /dev/vda2 -L swap",
836           "swapon -L swap",
837           "mkfs.ext3 -L nixos /dev/vda3",
838           "mount LABEL=nixos /mnt",
839           "mkfs.vfat -n BOOT /dev/vda1",
840           "mkdir -p /mnt/boot",
841           "mount LABEL=BOOT /mnt/boot",
842       )
843     '';
844   };
846   # Same as the previous, but with ZFS /boot.
847   separateBootZfs = makeInstallerTest "separateBootZfs" {
848     extraInstallerConfig = {
849       boot.supportedFilesystems = [ "zfs" ];
850     };
852     extraConfig = ''
853       # Using by-uuid overrides the default of by-id, and is unique
854       # to the qemu disks, as they don't produce by-id paths for
855       # some reason.
856       boot.zfs.devNodes = "/dev/disk/by-uuid/";
857       networking.hostId = "00000000";
858     '';
860     createPartitions = ''
861       installer.succeed(
862           "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
863           + " mkpart primary ext2 1M 256MB"   # /boot
864           + " mkpart primary linux-swap 256MB 1280M"
865           + " mkpart primary ext2 1280M -1s", # /
866           "udevadm settle",
868           "mkswap /dev/vda2 -L swap",
869           "swapon -L swap",
871           "mkfs.ext4 -L nixos /dev/vda3",
872           "mount LABEL=nixos /mnt",
874           # Use as many ZFS features as possible to verify that GRUB can handle them
875           "zpool create"
876             " -o compatibility=grub2"
877             " -O utf8only=on"
878             " -O normalization=formD"
879             " -O compression=lz4"      # Activate the lz4_compress feature
880             " -O xattr=sa"
881             " -O acltype=posixacl"
882             " bpool /dev/vda1",
883           "zfs create"
884             " -o recordsize=1M"        # Prepare activating the large_blocks feature
885             " -o mountpoint=legacy"
886             " -o relatime=on"
887             " -o quota=1G"
888             " -o filesystem_limit=100" # Activate the filesystem_limits features
889             " bpool/boot",
891           # Snapshotting the top-level dataset would trigger a bug in GRUB2: https://github.com/openzfs/zfs/issues/13873
892           "zfs snapshot bpool/boot@snap-1",                     # Prepare activating the livelist and bookmarks features
893           "zfs clone bpool/boot@snap-1 bpool/test",             # Activate the livelist feature
894           "zfs bookmark bpool/boot@snap-1 bpool/boot#bookmark", # Activate the bookmarks feature
895           "zpool checkpoint bpool",                             # Activate the zpool_checkpoint feature
896           "mkdir -p /mnt/boot",
897           "mount -t zfs bpool/boot /mnt/boot",
898           "touch /mnt/boot/empty",                              # Activate zilsaxattr feature
899           "dd if=/dev/urandom of=/mnt/boot/test bs=1M count=1", # Activate the large_blocks feature
901           # Print out all enabled and active ZFS features (and some other stuff)
902           "sync /mnt/boot",
903           "zpool get all bpool >&2",
905           # Abort early if GRUB2 doesn't like the disks
906           "grub-probe --target=device /mnt/boot >&2",
907       )
908     '';
910     # umount & export bpool before shutdown
911     # this is a fix for "cannot import 'bpool': pool was previously in use from another system."
912     postInstallCommands = ''
913       installer.succeed("umount /mnt/boot")
914       installer.succeed("zpool export bpool")
915     '';
916   };
918   # zfs on / with swap
919   zfsroot = makeInstallerTest "zfs-root" {
920     extraInstallerConfig = {
921       boot.supportedFilesystems = [ "zfs" ];
922     };
924     extraConfig = ''
925       boot.supportedFilesystems = [ "zfs" ];
927       # Using by-uuid overrides the default of by-id, and is unique
928       # to the qemu disks, as they don't produce by-id paths for
929       # some reason.
930       boot.zfs.devNodes = "/dev/disk/by-uuid/";
931       networking.hostId = "00000000";
932     '';
934     createPartitions = ''
935       installer.succeed(
936           "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
937           + " mkpart primary 1M 100MB"  # /boot
938           + " mkpart primary linux-swap 100M 1024M"
939           + " mkpart primary 1024M -1s", # rpool
940           "udevadm settle",
941           "mkswap /dev/vda2 -L swap",
942           "swapon -L swap",
943           "zpool create rpool /dev/vda3",
944           "zfs create -o mountpoint=legacy rpool/root",
945           "mount -t zfs rpool/root /mnt",
946           "zfs create -o mountpoint=legacy rpool/root/usr",
947           "mkdir /mnt/usr",
948           "mount -t zfs rpool/root/usr /mnt/usr",
949           "mkfs.vfat -n BOOT /dev/vda1",
950           "mkdir /mnt/boot",
951           "mount LABEL=BOOT /mnt/boot",
952           "udevadm settle",
953       )
954     '';
955   };
957   # Create two physical LVM partitions combined into one volume group
958   # that contains the logical swap and root partitions.
959   lvm = makeInstallerTest "lvm" {
960     createPartitions = ''
961       installer.succeed(
962           "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
963           + " mkpart primary 1M 2048M"  # PV1
964           + " set 1 lvm on"
965           + " mkpart primary 2048M -1s"  # PV2
966           + " set 2 lvm on",
967           "udevadm settle",
968           "pvcreate /dev/vda1 /dev/vda2",
969           "vgcreate MyVolGroup /dev/vda1 /dev/vda2",
970           "lvcreate --size 1G --name swap MyVolGroup",
971           "lvcreate --size 6G --name nixos MyVolGroup",
972           "mkswap -f /dev/MyVolGroup/swap -L swap",
973           "swapon -L swap",
974           "mkfs.xfs -L nixos /dev/MyVolGroup/nixos",
975           "mount LABEL=nixos /mnt",
976       )
977     '';
978   };
980   # Boot off an encrypted root partition with the default LUKS header format
981   luksroot = makeLuksRootTest "luksroot-format1" "";
983   # Boot off an encrypted root partition with LUKS1 format
984   luksroot-format1 = makeLuksRootTest "luksroot-format1" "--type=LUKS1";
986   # Boot off an encrypted root partition with LUKS2 format
987   luksroot-format2 = makeLuksRootTest "luksroot-format2" "--type=LUKS2";
989   # Test whether opening encrypted filesystem with keyfile
990   # Checks for regression of missing cryptsetup, when no luks device without
991   # keyfile is configured
992   encryptedFSWithKeyfile = makeInstallerTest "encryptedFSWithKeyfile" {
993     createPartitions = ''
994       installer.succeed(
995           "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
996           + " mkpart primary ext2 1M 100MB"  # /boot
997           + " mkpart primary linux-swap 100M 1024M"
998           + " mkpart primary 1024M 1280M"  # LUKS with keyfile
999           + " mkpart primary 1280M -1s",
1000           "udevadm settle",
1001           "mkswap /dev/vda2 -L swap",
1002           "swapon -L swap",
1003           "mkfs.ext3 -L nixos /dev/vda4",
1004           "mount LABEL=nixos /mnt",
1005           "mkfs.ext3 -L boot /dev/vda1",
1006           "mkdir -p /mnt/boot",
1007           "mount LABEL=boot /mnt/boot",
1008           "modprobe dm_mod dm_crypt",
1009           "echo -n supersecret > /mnt/keyfile",
1010           "cryptsetup luksFormat -q /dev/vda3 --key-file /mnt/keyfile",
1011           "cryptsetup luksOpen --key-file /mnt/keyfile /dev/vda3 crypt",
1012           "mkfs.ext3 -L test /dev/mapper/crypt",
1013           "cryptsetup luksClose crypt",
1014           "mkdir -p /mnt/test",
1015       )
1016     '';
1017     extraConfig = ''
1018       fileSystems."/test" = {
1019         device = "/dev/disk/by-label/test";
1020         fsType = "ext3";
1021         encrypted.enable = true;
1022         encrypted.blkDev = "/dev/vda3";
1023         encrypted.label = "crypt";
1024         encrypted.keyFile = "/${if systemdStage1 then "sysroot" else "mnt-root"}/keyfile";
1025       };
1026     '';
1027   };
1029   # Full disk encryption (root, kernel and initrd encrypted) using GRUB, GPT/UEFI,
1030   # LVM-on-LUKS and a keyfile in initrd.secrets to enter the passphrase once
1031   fullDiskEncryption = makeInstallerTest "fullDiskEncryption" {
1032     createPartitions = ''
1033       installer.succeed(
1034           "flock /dev/vda parted --script /dev/vda -- mklabel gpt"
1035           + " mkpart ESP fat32 1M 100MiB"  # /boot/efi
1036           + " set 1 boot on"
1037           + " mkpart primary ext2 1024MiB -1MiB",  # LUKS
1038           "udevadm settle",
1039           "modprobe dm_mod dm_crypt",
1040           "dd if=/dev/random of=luks.key bs=256 count=1",
1041           "echo -n supersecret | cryptsetup luksFormat -q --pbkdf-force-iterations 1000 --type luks1 /dev/vda2 -",
1042           "echo -n supersecret | cryptsetup luksAddKey -q --pbkdf-force-iterations 1000 --key-file - /dev/vda2 luks.key",
1043           "echo -n supersecret | cryptsetup luksOpen --key-file - /dev/vda2 crypt",
1044           "pvcreate /dev/mapper/crypt",
1045           "vgcreate crypt /dev/mapper/crypt",
1046           "lvcreate -L 100M -n swap crypt",
1047           "lvcreate -l '100%FREE' -n nixos crypt",
1048           "mkfs.vfat -n efi /dev/vda1",
1049           "mkfs.ext4 -L nixos /dev/crypt/nixos",
1050           "mkswap -L swap /dev/crypt/swap",
1051           "mount LABEL=nixos /mnt",
1052           "mkdir -p /mnt/{etc/nixos,boot/efi}",
1053           "mount LABEL=efi /mnt/boot/efi",
1054           "swapon -L swap",
1055           "mv luks.key /mnt/etc/nixos/"
1056       )
1057     '';
1058     bootLoader = "grub";
1059     grubUseEfi = true;
1060     extraConfig = ''
1061       boot.loader.grub.enableCryptodisk = true;
1062       boot.loader.efi.efiSysMountPoint = "/boot/efi";
1064       boot.initrd.secrets."/luks.key" = "/etc/nixos/luks.key";
1065       boot.initrd.luks.devices.crypt =
1066         { device  = "/dev/vda2";
1067           keyFile = "/luks.key";
1068         };
1069     '';
1070     enableOCR = true;
1071     postBootCommands = ''
1072       target.wait_for_text("Enter passphrase for")
1073       target.send_chars("supersecret\n")
1074     '';
1075   };
1077   swraid = makeInstallerTest "swraid" {
1078     createPartitions = ''
1079       installer.succeed(
1080           "flock /dev/vda parted --script /dev/vda --"
1081           + " mklabel msdos"
1082           + " mkpart primary ext2 1M 100MB"  # /boot
1083           + " mkpart extended 100M -1s"
1084           + " mkpart logical 102M 3102M"  # md0 (root), first device
1085           + " mkpart logical 3103M 6103M"  # md0 (root), second device
1086           + " mkpart logical 6104M 6360M"  # md1 (swap), first device
1087           + " mkpart logical 6361M 6617M",  # md1 (swap), second device
1088           "udevadm settle",
1089           "ls -l /dev/vda* >&2",
1090           "cat /proc/partitions >&2",
1091           "udevadm control --stop-exec-queue",
1092           "mdadm --create --force /dev/md0 --metadata 1.2 --level=raid1 "
1093           + "--raid-devices=2 /dev/vda5 /dev/vda6",
1094           "mdadm --create --force /dev/md1 --metadata 1.2 --level=raid1 "
1095           + "--raid-devices=2 /dev/vda7 /dev/vda8",
1096           "udevadm control --start-exec-queue",
1097           "udevadm settle",
1098           "mkswap -f /dev/md1 -L swap",
1099           "swapon -L swap",
1100           "mkfs.ext3 -L nixos /dev/md0",
1101           "mount LABEL=nixos /mnt",
1102           "mkfs.ext3 -L boot /dev/vda1",
1103           "mkdir /mnt/boot",
1104           "mount LABEL=boot /mnt/boot",
1105           "udevadm settle",
1106       )
1107     '';
1108     postBootCommands = ''
1109       target.fail("dmesg | grep 'immediate safe mode'")
1110     '';
1111   };
1113   bcache = makeInstallerTest "bcache" {
1114     createPartitions = ''
1115       installer.succeed(
1116           "flock /dev/vda parted --script /dev/vda --"
1117           + " mklabel msdos"
1118           + " mkpart primary ext2 1M 100MB"  # /boot
1119           + " mkpart primary 100MB 512MB  "  # swap
1120           + " mkpart primary 512MB 1024MB"  # Cache (typically SSD)
1121           + " mkpart primary 1024MB -1s ",  # Backing device (typically HDD)
1122           "modprobe bcache",
1123           "udevadm settle",
1124           "make-bcache -B /dev/vda4 -C /dev/vda3",
1125           "udevadm settle",
1126           "mkfs.ext3 -L nixos /dev/bcache0",
1127           "mount LABEL=nixos /mnt",
1128           "mkfs.ext3 -L boot /dev/vda1",
1129           "mkdir /mnt/boot",
1130           "mount LABEL=boot /mnt/boot",
1131           "mkswap -f /dev/vda2 -L swap",
1132           "swapon -L swap",
1133       )
1134     '';
1135   };
1137   bcachefsSimple = makeInstallerTest "bcachefs-simple" {
1138     extraInstallerConfig = {
1139       boot.supportedFilesystems = [ "bcachefs" ];
1140       imports = [ no-zfs-module ];
1141     };
1143     createPartitions = ''
1144       installer.succeed(
1145         "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
1146         + " mkpart primary ext2 1M 100MB"          # /boot
1147         + " mkpart primary linux-swap 100M 1024M"  # swap
1148         + " mkpart primary 1024M -1s",             # /
1149         "udevadm settle",
1150         "mkswap /dev/vda2 -L swap",
1151         "swapon -L swap",
1152         "mkfs.bcachefs -L root /dev/vda3",
1153         "mount -t bcachefs /dev/vda3 /mnt",
1154         "mkfs.ext3 -L boot /dev/vda1",
1155         "mkdir -p /mnt/boot",
1156         "mount /dev/vda1 /mnt/boot",
1157       )
1158     '';
1159   };
1161   bcachefsEncrypted = makeInstallerTest "bcachefs-encrypted" {
1162     extraInstallerConfig = {
1163       boot.supportedFilesystems = [ "bcachefs" ];
1165       # disable zfs so we can support latest kernel if needed
1166       imports = [ no-zfs-module ];
1168       environment.systemPackages = with pkgs; [ keyutils ];
1169     };
1171     extraConfig = ''
1172       boot.kernelParams = lib.mkAfter [ "console=tty0" ];
1173     '';
1175     enableOCR = true;
1176     postBootCommands = ''
1177       # Enter it wrong once
1178       target.wait_for_text("enter passphrase for ")
1179       target.send_chars("wrong\n")
1180       # Then enter it right.
1181       target.wait_for_text("enter passphrase for ")
1182       target.send_chars("password\n")
1183     '';
1185     createPartitions = ''
1186       installer.succeed(
1187         "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
1188         + " mkpart primary ext2 1M 100MB"          # /boot
1189         + " mkpart primary linux-swap 100M 1024M"  # swap
1190         + " mkpart primary 1024M -1s",             # /
1191         "udevadm settle",
1192         "mkswap /dev/vda2 -L swap",
1193         "swapon -L swap",
1194         "echo password | mkfs.bcachefs -L root --encrypted /dev/vda3",
1195         "echo password | bcachefs unlock -k session /dev/vda3",
1196         "echo password | mount -t bcachefs /dev/vda3 /mnt",
1197         "mkfs.ext3 -L boot /dev/vda1",
1198         "mkdir -p /mnt/boot",
1199         "mount /dev/vda1 /mnt/boot",
1200       )
1201     '';
1202   };
1204   bcachefsMulti = makeInstallerTest "bcachefs-multi" {
1205     extraInstallerConfig = {
1206       boot.supportedFilesystems = [ "bcachefs" ];
1208       # disable zfs so we can support latest kernel if needed
1209       imports = [ no-zfs-module ];
1210     };
1212     createPartitions = ''
1213       installer.succeed(
1214         "flock /dev/vda parted --script /dev/vda -- mklabel msdos"
1215         + " mkpart primary ext2 1M 100MB"          # /boot
1216         + " mkpart primary linux-swap 100M 1024M"  # swap
1217         + " mkpart primary 1024M 4096M"            # /
1218         + " mkpart primary 4096M -1s",             # /
1219         "udevadm settle",
1220         "mkswap /dev/vda2 -L swap",
1221         "swapon -L swap",
1222         "mkfs.bcachefs -L root --metadata_replicas 2 --foreground_target ssd --promote_target ssd --background_target hdd --label ssd /dev/vda3 --label hdd /dev/vda4",
1223         "mount -t bcachefs /dev/vda3:/dev/vda4 /mnt",
1224         "mkfs.ext3 -L boot /dev/vda1",
1225         "mkdir -p /mnt/boot",
1226         "mount /dev/vda1 /mnt/boot",
1227       )
1228     '';
1229   };
1231   # Test using labels to identify volumes in grub
1232   simpleLabels = makeInstallerTest "simpleLabels" {
1233     createPartitions = ''
1234       installer.succeed(
1235           "sgdisk -Z /dev/vda",
1236           "sgdisk -n 1:0:+1M -n 2:0:+1G -N 3 -t 1:ef02 -t 2:8200 -t 3:8300 -c 3:root /dev/vda",
1237           "mkswap /dev/vda2 -L swap",
1238           "swapon -L swap",
1239           "mkfs.ext4 -L root /dev/vda3",
1240           "mount LABEL=root /mnt",
1241       )
1242     '';
1243     grubIdentifier = "label";
1244   };
1246   # Test using the provided disk name within grub
1247   # TODO: Fix udev so the symlinks are unneeded in /dev/disks
1248   simpleProvided = makeInstallerTest "simpleProvided" {
1249     createPartitions = ''
1250       uuid = "$(blkid -s UUID -o value /dev/vda2)"
1251       installer.succeed(
1252           "sgdisk -Z /dev/vda",
1253           "sgdisk -n 1:0:+1M -n 2:0:+100M -n 3:0:+1G -N 4 -t 1:ef02 -t 2:8300 "
1254           + "-t 3:8200 -t 4:8300 -c 2:boot -c 4:root /dev/vda",
1255           "mkswap /dev/vda3 -L swap",
1256           "swapon -L swap",
1257           "mkfs.ext4 -L boot /dev/vda2",
1258           "mkfs.ext4 -L root /dev/vda4",
1259       )
1260       installer.execute(f"ln -s ../../vda2 /dev/disk/by-uuid/{uuid}")
1261       installer.execute("ln -s ../../vda4 /dev/disk/by-label/root")
1262       installer.succeed(
1263           "mount /dev/disk/by-label/root /mnt",
1264           "mkdir /mnt/boot",
1265           f"mount /dev/disk/by-uuid/{uuid} /mnt/boot",
1266       )
1267     '';
1268     grubIdentifier = "provided";
1269   };
1271   # Simple btrfs grub testing
1272   btrfsSimple = makeInstallerTest "btrfsSimple" {
1273     createPartitions = ''
1274       installer.succeed(
1275           "sgdisk -Z /dev/vda",
1276           "sgdisk -n 1:0:+1M -n 2:0:+1G -N 3 -t 1:ef02 -t 2:8200 -t 3:8300 -c 3:root /dev/vda",
1277           "mkswap /dev/vda2 -L swap",
1278           "swapon -L swap",
1279           "mkfs.btrfs -L root /dev/vda3",
1280           "mount LABEL=root /mnt",
1281       )
1282     '';
1283   };
1285   # Test to see if we can detect /boot and /nix on subvolumes
1286   btrfsSubvols = makeInstallerTest "btrfsSubvols" {
1287     createPartitions = ''
1288       installer.succeed(
1289           "sgdisk -Z /dev/vda",
1290           "sgdisk -n 1:0:+1M -n 2:0:+1G -N 3 -t 1:ef02 -t 2:8200 -t 3:8300 -c 3:root /dev/vda",
1291           "mkswap /dev/vda2 -L swap",
1292           "swapon -L swap",
1293           "mkfs.btrfs -L root /dev/vda3",
1294           "btrfs device scan",
1295           "mount LABEL=root /mnt",
1296           "btrfs subvol create /mnt/boot",
1297           "btrfs subvol create /mnt/nixos",
1298           "btrfs subvol create /mnt/nixos/default",
1299           "umount /mnt",
1300           "mount -o defaults,subvol=nixos/default LABEL=root /mnt",
1301           "mkdir /mnt/boot",
1302           "mount -o defaults,subvol=boot LABEL=root /mnt/boot",
1303       )
1304     '';
1305   };
1307   # Test to see if we can detect default and aux subvolumes correctly
1308   btrfsSubvolDefault = makeInstallerTest "btrfsSubvolDefault" {
1309     createPartitions = ''
1310       installer.succeed(
1311           "sgdisk -Z /dev/vda",
1312           "sgdisk -n 1:0:+1M -n 2:0:+1G -N 3 -t 1:ef02 -t 2:8200 -t 3:8300 -c 3:root /dev/vda",
1313           "mkswap /dev/vda2 -L swap",
1314           "swapon -L swap",
1315           "mkfs.btrfs -L root /dev/vda3",
1316           "btrfs device scan",
1317           "mount LABEL=root /mnt",
1318           "btrfs subvol create /mnt/badpath",
1319           "btrfs subvol create /mnt/badpath/boot",
1320           "btrfs subvol create /mnt/nixos",
1321           "btrfs subvol set-default "
1322           + "$(btrfs subvol list /mnt | grep 'nixos' | awk '{print $2}') /mnt",
1323           "umount /mnt",
1324           "mount -o defaults LABEL=root /mnt",
1325           "mkdir -p /mnt/badpath/boot",  # Help ensure the detection mechanism
1326           # is actually looking up subvolumes
1327           "mkdir /mnt/boot",
1328           "mount -o defaults,subvol=badpath/boot LABEL=root /mnt/boot",
1329       )
1330     '';
1331   };
1333   # Test to see if we can deal with subvols that need to be escaped in fstab
1334   btrfsSubvolEscape = makeInstallerTest "btrfsSubvolEscape" {
1335     createPartitions = ''
1336       installer.succeed(
1337           "sgdisk -Z /dev/vda",
1338           "sgdisk -n 1:0:+1M -n 2:0:+1G -N 3 -t 1:ef02 -t 2:8200 -t 3:8300 -c 3:root /dev/vda",
1339           "mkswap /dev/vda2 -L swap",
1340           "swapon -L swap",
1341           "mkfs.btrfs -L root /dev/vda3",
1342           "btrfs device scan",
1343           "mount LABEL=root /mnt",
1344           "btrfs subvol create '/mnt/nixos in space'",
1345           "btrfs subvol create /mnt/boot",
1346           "umount /mnt",
1347           "mount -o 'defaults,subvol=nixos in space' LABEL=root /mnt",
1348           "mkdir /mnt/boot",
1349           "mount -o defaults,subvol=boot LABEL=root /mnt/boot",
1350       )
1351     '';
1352   };
1353 } // {
1354   clevisBcachefs = mkClevisBcachefsTest { };
1355   clevisBcachefsFallback = mkClevisBcachefsTest { fallback = true; };
1356   clevisLuks = mkClevisLuksTest { };
1357   clevisLuksFallback = mkClevisLuksTest { fallback = true; };
1358   clevisZfs = mkClevisZfsTest { };
1359   clevisZfsFallback = mkClevisZfsTest { fallback = true; };
1360 } // optionalAttrs systemdStage1 {
1361   stratisRoot = makeInstallerTest "stratisRoot" {
1362     createPartitions = ''
1363       installer.succeed(
1364         "sgdisk --zap-all /dev/vda",
1365         "sgdisk --new=1:0:+100M --typecode=0:ef00 /dev/vda", # /boot
1366         "sgdisk --new=2:0:+1G --typecode=0:8200 /dev/vda", # swap
1367         "sgdisk --new=3:0:+5G --typecode=0:8300 /dev/vda", # /
1368         "udevadm settle",
1370         "mkfs.vfat /dev/vda1",
1371         "mkswap /dev/vda2 -L swap",
1372         "swapon -L swap",
1373         "stratis pool create my-pool /dev/vda3",
1374         "stratis filesystem create my-pool nixos",
1375         "udevadm settle",
1377         "mount /dev/stratis/my-pool/nixos /mnt",
1378         "mkdir -p /mnt/boot",
1379         "mount /dev/vda1 /mnt/boot"
1380       )
1381     '';
1382     bootLoader = "systemd-boot";
1383     extraInstallerConfig = { modulesPath, ...}: {
1384       config = {
1385         services.stratis.enable = true;
1386         environment.systemPackages = [
1387           pkgs.stratis-cli
1388           pkgs.thin-provisioning-tools
1389           pkgs.lvm2.bin
1390           pkgs.stratisd.initrd
1391         ];
1392       };
1393     };
1394   };
1396   gptAutoRoot = let
1397     rootPartType = {
1398       ia32 = "44479540-F297-41B2-9AF7-D131D5F0458A";
1399       x64 = "4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709";
1400       arm = "69DAD710-2CE4-4E3C-B16C-21A1D49ABED3";
1401       aa64 = "B921B045-1DF0-41C3-AF44-4C6F280D3FAE";
1402     }.${pkgs.stdenv.hostPlatform.efiArch};
1403   in makeInstallerTest "gptAutoRoot" {
1404     disableFileSystems = true;
1405     createPartitions = ''
1406       installer.succeed(
1407         "sgdisk --zap-all /dev/vda",
1408         "sgdisk --new=1:0:+100M --typecode=0:ef00 /dev/vda", # /boot
1409         "sgdisk --new=2:0:+1G --typecode=0:8200 /dev/vda", # swap
1410         "sgdisk --new=3:0:+5G --typecode=0:${rootPartType} /dev/vda", # /
1411         "udevadm settle",
1413         "mkfs.vfat /dev/vda1",
1414         "mkswap /dev/vda2 -L swap",
1415         "swapon -L swap",
1416         "mkfs.ext4 -L root /dev/vda3",
1417         "udevadm settle",
1419         "mount /dev/vda3 /mnt",
1420         "mkdir -p /mnt/boot",
1421         "mount /dev/vda1 /mnt/boot"
1422       )
1423     '';
1424     bootLoader = "systemd-boot";
1425     extraConfig = ''
1426       boot.initrd.systemd.root = "gpt-auto";
1427       boot.initrd.supportedFilesystems = ["ext4"];
1428     '';
1429   };