aboutsummaryrefslogtreecommitdiff
path: root/lib/mk-sandbox-system.nix
blob: e9866cf0a2af5beeaf058ed84ca7390364d79634 (plain)
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
flake:
{ pkgs
, name ? "sandbox"
, user ? "dummy"
, config ? { }
, tools ? []
, envVars ? { }
, restrictNetwork ? true  # to be replaced with virtualisation.restrictNetwork
, patchQemu9p ? false  # until qemu 7.2.0 becomes available in nixpkgs
}@params:

let
  shellLib = flake.lib.shell { inherit pkgs; };

  print = rec {
    printSharedDir = name: { source, target }: ''
      echo -en ${shellLib.fmt.keyword target}": "
      echo ${pkgs.lib.escapeShellArg source}
    '';
    printSharedDirs = sharedDirs: ''
      ${shellLib.fmt.printSectionTitle "SHARED DIRECTORIES (guest: host)"}
      ${shellLib.mapAttrsToLines printSharedDir sharedDirs}
    '';

    formatAddrPort = { address, port }: "${address}:${toString port}";
    printForwardedPort = { from, proto, host, guest, }:
      if from == "host" then ''
        echo -n ${proto}' '
        echo -en ${shellLib.fmt.keyword (formatAddrPort host)}
        echo -n ' -> '
        echo ${formatAddrPort guest}
      '' else ''
        echo -n ${proto}' '
        echo -n ${formatAddrPort host}
        echo -n ' <- '
        echo -e ${shellLib.fmt.keyword (formatAddrPort guest)}
      '';
    printForwardedPorts = portForwards: ''
      ${shellLib.fmt.printSectionTitle "FORWARDED PORTS (host <-> guest)"}
      ${pkgs.lib.concatMapStringsSep "\n" printForwardedPort portForwards}
    '';
  };

in rec {

  nixosConfigurations.${name} = pkgs.nixos
  ({ modulesPath, config, lib, pkgs, ... }: {
    imports = [
      (modulesPath + "/profiles/minimal.nix")
      { environment.noXlibs = false; }  # avoid mass rebuild

      (modulesPath + "/profiles/qemu-guest.nix")
      (modulesPath + "/virtualisation/qemu-vm.nix")

      params.config
    ];

    system.stateVersion = lib.mkDefault lib.trivial.release;

    networking = {
      hostName = name;
      firewall.enable = lib.mkDefault false;
    };

    users.users.${user} = {
      isNormalUser = lib.mkDefault true;
      password = lib.mkDefault "";
      extraGroups = lib.mkDefault [ "wheel" ];
    };

    security.sudo.wheelNeedsPassword = lib.mkDefault false;

    services.getty = {
      autologinUser = lib.mkDefault user;
      helpLine = lib.mkDefault ''
        Press <CTRL-a> <x> to terminate the virtual machine.
      '';
    };

    environment = {
      variables = envVars;
      systemPackages = tools;

      interactiveShellInit = lib.mkBefore ''
        ${shellLib.ifSomeAttrs envVars shellLib.printEnvVars}
        ${shellLib.ifSomeList tools shellLib.printBins}

        ${shellLib.ifSomeAttrs config.virtualisation.sharedDirectories
          print.printSharedDirs}
        ${shellLib.ifSomeList config.virtualisation.forwardPorts
          print.printForwardedPorts}
      '';
    };

    virtualisation = {
      graphics = lib.mkDefault false;
      diskImage = lib.mkDefault "$TMP_DISK";

      sharedDirectories.host = {
        source = "$SHARED_CWD";
        target = "/mnt";
      };

      # Uncomment when this is merged:
      # https://github.com/NixOS/nixpkgs/pull/200225
      #restrictNetwork = lib.mkDefault true;

      # Patched QEMU to fix slow 9p file share.
      # https://linus.schreibt.jetzt/posts/qemu-9p-performance.html
      qemu.package = lib.mkDefault (
        if patchQemu9p then
          assert !(pkgs.lib.versionAtLeast pkgs.qemu_kvm.version "7.2.0");
          pkgs.qemu_kvm.overrideAttrs (o: {
            patches = o.patches ++ [ (pkgs.fetchpatch {
              name = "qemu-9p-performance-fix.patch";
              url = "https://github.com/qemu/qemu/commit/f5265c8.patch";
              sha256 = "sha256-PSOv0dhiEq9g6B1uIbs6vbhGr7BQWCtAoLHnk4vnvVg=";
            }) ];
          })
        else pkgs.qemu_kvm
      );

    };
  });

  packages.${name} = nixosConfigurations.${name}.config.system.build.vm;

  apps.${name} = {
    type = "app";
    program = toString (pkgs.writeShellScript "sandbox-vm" (
    (pkgs.lib.optionalString restrictNetwork ''
      # Isolate from network
      # Stopgap solution until this is merged:
      # https://github.com/NixOS/nixpkgs/pull/200225
      QEMU_NET_OPTS="restrict=yes,''${QEMU_NET_OPTS:+,$QEMU_NET_OPTS}"
      export QEMU_NET_OPTS
    '') + ''
      # Save current directory for mounting in VM
      SHARED_CWD=$PWD
      export SHARED_CWD

      TMP_DISK="$(mktemp).qcow2"
      export TMP_DISK
      trap "rm -f \"$TMP_DISK\"" EXIT

      ${packages.${name}}/bin/run-${name}-vm

      reset
      echo "Exited virtual machine."
    ''));
  };

}