1{ config, lib, options, ... }:
2
3let
4 keysDirectory = "/var/keys";
5
6 user = "builder";
7
8 keyType = "ed25519";
9
10 cfg = config.virtualisation.darwin-builder;
11
12in
13
14{
15 imports = [
16 ../virtualisation/qemu-vm.nix
17
18 # Avoid a dependency on stateVersion
19 {
20 disabledModules = [
21 ../virtualisation/nixos-containers.nix
22 ../services/x11/desktop-managers/xterm.nix
23 ];
24 # swraid's default depends on stateVersion
25 config.boot.swraid.enable = false;
26 options.boot.isContainer = lib.mkOption { default = false; internal = true; };
27 }
28 ];
29
30 options.virtualisation.darwin-builder = with lib; {
31 diskSize = mkOption {
32 default = 20 * 1024;
33 type = types.int;
34 example = 30720;
35 description = "The maximum disk space allocated to the runner in MB";
36 };
37 memorySize = mkOption {
38 default = 3 * 1024;
39 type = types.int;
40 example = 8192;
41 description = "The runner's memory in MB";
42 };
43 min-free = mkOption {
44 default = 1024 * 1024 * 1024;
45 type = types.int;
46 example = 1073741824;
47 description = ''
48 The threshold (in bytes) of free disk space left at which to
49 start garbage collection on the runner
50 '';
51 };
52 max-free = mkOption {
53 default = 3 * 1024 * 1024 * 1024;
54 type = types.int;
55 example = 3221225472;
56 description = ''
57 The threshold (in bytes) of free disk space left at which to
58 stop garbage collection on the runner
59 '';
60 };
61 workingDirectory = mkOption {
62 default = ".";
63 type = types.str;
64 example = "/var/lib/darwin-builder";
65 description = ''
66 The working directory to use to run the script. When running
67 as part of a flake will need to be set to a non read-only filesystem.
68 '';
69 };
70 hostPort = mkOption {
71 default = 31022;
72 type = types.int;
73 example = 22;
74 description = ''
75 The localhost host port to forward TCP to the guest port.
76 '';
77 };
78 };
79
80 config = {
81 # The builder is not intended to be used interactively
82 documentation.enable = false;
83
84 environment.etc = {
85 "ssh/ssh_host_ed25519_key" = {
86 mode = "0600";
87
88 source = ./keys/ssh_host_ed25519_key;
89 };
90
91 "ssh/ssh_host_ed25519_key.pub" = {
92 mode = "0644";
93
94 source = ./keys/ssh_host_ed25519_key.pub;
95 };
96 };
97
98 # DNS fails for QEMU user networking (SLiRP) on macOS. See:
99 #
100 # https://github.com/utmapp/UTM/issues/2353
101 #
102 # This works around that by using a public DNS server other than the DNS
103 # server that QEMU provides (normally 10.0.2.3)
104 networking.nameservers = [ "8.8.8.8" ];
105
106 nix.settings = {
107 auto-optimise-store = true;
108
109 min-free = cfg.min-free;
110
111 max-free = cfg.max-free;
112
113 trusted-users = [ "root" user ];
114 };
115
116 services = {
117 getty.autologinUser = user;
118
119 openssh = {
120 enable = true;
121
122 authorizedKeysFiles = [ "${keysDirectory}/%u_${keyType}.pub" ];
123 };
124 };
125
126 system.build.macos-builder-installer =
127 let
128 privateKey = "/etc/nix/${user}_${keyType}";
129
130 publicKey = "${privateKey}.pub";
131
132 # This installCredentials script is written so that it's as easy as
133 # possible for a user to audit before confirming the `sudo`
134 installCredentials = hostPkgs.writeShellScript "install-credentials" ''
135 KEYS="''${1}"
136 INSTALL=${hostPkgs.coreutils}/bin/install
137 "''${INSTALL}" -g nixbld -m 600 "''${KEYS}/${user}_${keyType}" ${privateKey}
138 "''${INSTALL}" -g nixbld -m 644 "''${KEYS}/${user}_${keyType}.pub" ${publicKey}
139 '';
140
141 hostPkgs = config.virtualisation.host.pkgs;
142
143 script = hostPkgs.writeShellScriptBin "create-builder" (
144 # When running as non-interactively as part of a DarwinConfiguration the working directory
145 # must be set to a writeable directory.
146 (if cfg.workingDirectory != "." then ''
147 ${hostPkgs.coreutils}/bin/mkdir --parent "${cfg.workingDirectory}"
148 cd "${cfg.workingDirectory}"
149 '' else "") + ''
150 KEYS="''${KEYS:-./keys}"
151 ${hostPkgs.coreutils}/bin/mkdir --parent "''${KEYS}"
152 PRIVATE_KEY="''${KEYS}/${user}_${keyType}"
153 PUBLIC_KEY="''${PRIVATE_KEY}.pub"
154 if [ ! -e "''${PRIVATE_KEY}" ] || [ ! -e "''${PUBLIC_KEY}" ]; then
155 ${hostPkgs.coreutils}/bin/rm --force -- "''${PRIVATE_KEY}" "''${PUBLIC_KEY}"
156 ${hostPkgs.openssh}/bin/ssh-keygen -q -f "''${PRIVATE_KEY}" -t ${keyType} -N "" -C 'builder@localhost'
157 fi
158 if ! ${hostPkgs.diffutils}/bin/cmp "''${PUBLIC_KEY}" ${publicKey}; then
159 (set -x; sudo --reset-timestamp ${installCredentials} "''${KEYS}")
160 fi
161 KEYS="$(${hostPkgs.nix}/bin/nix-store --add "$KEYS")" ${lib.getExe config.system.build.vm}
162 '');
163
164 in
165 script.overrideAttrs (old: {
166 pos = __curPos; # sets meta.position to point here; see script binding above for package definition
167 meta = (old.meta or { }) // {
168 platforms = lib.platforms.darwin;
169 };
170 passthru = (old.passthru or { }) // {
171 # Let users in the repl inspect the config
172 nixosConfig = config;
173 nixosOptions = options;
174 };
175 });
176
177 system = {
178 # To prevent gratuitous rebuilds on each change to Nixpkgs
179 nixos.revision = null;
180
181 stateVersion = lib.mkDefault (throw ''
182 The macOS linux builder should not need a stateVersion to be set, but a module
183 has accessed stateVersion nonetheless.
184 Please inspect the trace of the following command to figure out which module
185 has a dependency on stateVersion.
186
187 nix-instantiate --attr darwin.linux-builder --show-trace
188 '');
189 };
190
191 users.users."${user}" = {
192 isNormalUser = true;
193 };
194
195 security.polkit.enable = true;
196
197 security.polkit.extraConfig = ''
198 polkit.addRule(function(action, subject) {
199 if (action.id === "org.freedesktop.login1.power-off" && subject.user === "${user}") {
200 return "yes";
201 } else {
202 return "no";
203 }
204 })
205 '';
206
207 virtualisation = {
208 diskSize = cfg.diskSize;
209
210 memorySize = cfg.memorySize;
211
212 forwardPorts = [
213 { from = "host"; guest.port = 22; host.port = cfg.hostPort; }
214 ];
215
216 # Disable graphics for the builder since users will likely want to run it
217 # non-interactively in the background.
218 graphics = false;
219
220 sharedDirectories.keys = {
221 source = "\"$KEYS\"";
222 target = keysDirectory;
223 };
224
225 # If we don't enable this option then the host will fail to delegate builds
226 # to the guest, because:
227 #
228 # - The host will lock the path to build
229 # - The host will delegate the build to the guest
230 # - The guest will attempt to lock the same path and fail because
231 # the lockfile on the host is visible on the guest
232 #
233 # Snapshotting the host's /nix/store as an image isolates the guest VM's
234 # /nix/store from the host's /nix/store, preventing this problem.
235 useNixStoreImage = true;
236
237 # Obviously the /nix/store needs to be writable on the guest in order for it
238 # to perform builds.
239 writableStore = true;
240
241 # This ensures that anything built on the guest isn't lost when the guest is
242 # restarted.
243 writableStoreUseTmpfs = false;
244
245 # Pass certificates from host to the guest otherwise when custom CA certificates
246 # are required we can't use the cached builder.
247 useHostCerts = true;
248 };
249 };
250}