gunk-dev/the-valley

host-module.nix

source6063990989b7main's published tip history
20.6 KiB
1# What the NixOS module renders from a declaration, and what it must refuse.
2# The refusals are eval-time: a host that must not evaluate is caught by a
3# throw here, since there is nothing to build once it has. What a host does
4# render is pinned by module-eval.sh over the rendered scripts.
5{
6 pkgs,
7 lib,
8 hosts,
9 ...
10}:
11let
12 inherit (hosts)
13 unprotectedInstanceHost
14 acceptEnvHost
15 matchAcceptEnvHost
16 wildcardAcceptEnvHost
17 setEnvHost
18 permitUserEnvironmentHost
19 conflictingKeysHost
20 host
21 noBackupHost
22 noSecretsHost
23 protectedHost
24 busHost
25 mirrorHost
26 integratorHost
27 integratorSelfHost
28 identityHost
29 ;
30
31 failedAssertions = builtins.filter (a: !a.assertion) (
32 host.config.assertions
33 ++ noBackupHost.config.assertions
34 ++ busHost.config.assertions
35 ++ mirrorHost.config.assertions
36 ++ protectedHost.config.assertions
37 ++ integratorHost.config.assertions
38 ++ integratorSelfHost.config.assertions
39 ++ identityHost.config.assertions
40 );
41
42 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
43
44 # The hosts the module must refuse, each with the words its refusal must
45 # say. An assertion that stopped firing would leave the push policy
46 # quietly wrong, so each is held to naming what is wrong.
47 refusedHosts = [
48 {
49 host = unprotectedInstanceHost;
50 says = "whose refs/heads/main is not protected";
51 why = "an instance repository without protection would let any key that can push rewrite the floor and the registry";
52 }
53 {
54 host = acceptEnvHost;
55 says = "AcceptEnv";
56 why = "sshd accepting the principal variable from the client would let any key name any principal";
57 }
58 {
59 host = matchAcceptEnvHost;
60 says = "GIT_CONFIG_*";
61 why = "sshd accepting GIT_ variables in the git user's Match block, in whatever case the keyword is written, would let a client set git's configuration";
62 }
63 {
64 host = wildcardAcceptEnvHost;
65 says = "G?T_*";
66 why = "a wildcard that admits GIT_ variables admits them however it is spelled";
67 }
68 {
69 host = setEnvHost;
70 says = "SetEnv";
71 why = "sshd setting the principal itself would make every key push as it";
72 }
73 {
74 host = permitUserEnvironmentHost;
75 says = "PermitUserEnvironment";
76 why = "a PermitUserEnvironment wider than the principal variable would let a key's entry or ~/.ssh/environment set what the push policy does not expect";
77 }
78 {
79 host = conflictingKeysHost;
80 says = "more than one principal tag";
81 why = "a key declared under two tags would push as whichever entry sshd reads first";
82 }
83 ];
84
85 unrefusedHosts = builtins.filter (
86 r: !(lib.any (a: !a.assertion && lib.hasInfix r.says a.message) r.host.config.assertions)
87 ) refusedHosts;
88
89 protectedKeyLines = protectedHost.config.users.users.git.openssh.authorizedKeys.keys;
90
91 resticRenderedWithoutDeclaration =
92 noBackupHost.config.systemd.services ? "restic-backups-valley"
93 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
94
95 # The bus defaults off; a host that never asked for one must
96 # render zero bus machinery.
97 busRenderedWithoutEnable =
98 noBackupHost.config.systemd.services ? valley-bus
99 || noBackupHost.config.systemd.services ? valley-bus-init;
100
101 # A declaration with no protection block and no tagged key still gets
102 # the push policy on every project — the policy is the host's, and a
103 # protection block only adds protected refs to it — and nothing of the
104 # principal machinery: no tag on a key, no sshd change.
105 protectionRenderedWithoutDeclaration =
106 noBackupHost.config.services.openssh.settings ? PermitUserEnvironment
107 || lib.any (lib.hasInfix "environment=") (
108 noBackupHost.config.users.users.git.openssh.authorizedKeys.keys
109 );
110
111 policyMissingWithoutDeclaration =
112 !(lib.hasInfix "valley-protect-the-valley" noBackupHost.config.systemd.services.valley-init.script);
113
114 # The integrator's units. What a controller *does* is not checked here
115 # and no VM is booted: that is integrator-e2e's job (the real binaries
116 # over real repositories) and, past it, live exercise on a host. These
117 # assertions cover the wiring — that a controller is rendered for what
118 # the declaration protects and for nothing else, under an identity that
119 # is not the git user's, pointed at the key and the signers the consumer
120 # supplied.
121 #
122 # There is a seam between those two halves that neither reaches, and in a
123 # single day it produced five deployment failures. Every assertion below is
124 # an eval of the unit's text; integrator-e2e runs the binaries with no unit
125 # around them at all. What sits between is the unit's sandbox and identity
126 # meeting the filesystem the binaries actually use at runtime:
127 #
128 # - git refusing a repository the service does not own (bd-500adf7)
129 # - a push authenticating as the operator rather than as the run
130 # (bd-353c59d)
131 # - no writable temporary directory, so no worktree could be made
132 # - the worktree metadata root, created by whichever service reached it
133 # first and then unchmodable by the other, which failed valley-init and
134 # took every valley unit down with it
135 # - the state directory not writable under ProtectSystem=strict unless
136 # the unit names it, which the previous fix had made the scratch root
137 #
138 # Each was found by a host, minutes of a live service after a deploy that
139 # every check here passed. They compose: the third's fix set up the fourth,
140 # and the fourth's fix set up the fifth. That is the argument. A seam whose
141 # failures feed each other is not one to pin an assertion at a time, and
142 # each assertion here that marks a piece of it — the git ownership
143 # exception, TMPDIR, the worktrees root, ReadWritePaths — marks a place a
144 # smoke boot would have spoken first.
145 #
146 # A nixosTest that boots one host, starts the units and reconciles one
147 # change end to end is the next check this module needs. Nothing else
148 # closes the seam, and five incidents is enough evidence of what it costs
149 # to leave open. Not built here.
150 #
151 # Protection and integration are separable declarations: protectedHost
152 # declares the same protected projects with the service off, and must
153 # evaluate to no controller at all.
154 integratorRenderedWithoutEnable =
155 protectedHost.config.systemd.services ? "valley-integrator@"
156 || protectedHost.config.systemd.targets ? valley-integrators
157 || lib.hasInfix "sharedRepository" protectedHost.config.systemd.services.valley-init.script;
158
159 controllers = integratorHost.config.systemd.targets.valley-integrators.wants;
160
161 integratorUser = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.User;
162
163 # The controller is not the repositories' owner, which is the whole point
164 # of running it as itself — so git needs an ownership exception, and
165 # where that exception lives is load-bearing. GIT_CONFIG_* is command
166 # scope, the only scope besides system and global that safe.directory is
167 # read from, and the unit's environment is inherited by every git the
168 # controller drives. It names one repository: a wildcard here would hand
169 # a compromised controller every repository on the host.
170 integratorGitEnv = integratorHost.config.systemd.services."valley-integrator@".environment;
171
172 # The count is what git reads; an entry past it is an entry git ignores,
173 # silently. So it is checked against the entries actually rendered rather
174 # than against a number written here, which would have to be edited every
175 # time a grant is added and would go on passing if it were not.
176 integratorSafeDirectory =
177 integratorGitEnv.GIT_CONFIG_KEY_0 or null != "safe.directory"
178 || integratorGitEnv.GIT_CONFIG_VALUE_0 or null != "/srv/git/%i.git"
179 || integratorGitEnv.GIT_CONFIG_COUNT or null
180 != toString (
181 lib.length (lib.filter (lib.hasPrefix "GIT_CONFIG_KEY_") (lib.attrNames integratorGitEnv))
182 );
183
184 integratorService = integratorHost.config.systemd.services."valley-integrator@".serviceConfig;
185
186 # Scratch goes under the state directory, because the sandbox leaves no
187 # writable temporary directory and a verdict needs a checkout on disk. Two
188 # halves, and each was a live failure on its own. TMPDIR naming a path
189 # outside the state directory is the first; the state directory not being
190 # named in ReadWritePaths is the second, which failed even though
191 # ProtectSystem=strict is documented to leave a declared state directory
192 # writable. Everything the unit may write is enumerated, so what a reader
193 # of the unit sees is the whole of it.
194 # The floor is read from the instance repository's integrated tip
195 # (dcr-f41f718, dcr-b87f6e8), so a controller is told which repository
196 # carries it and reads it there. Three things have to be true of that, and
197 # each was a way for it to be silently wrong.
198 #
199 # The controller has to be told at all — the failure this replaced was a
200 # binary looking for a materialized directory nothing populated.
201 #
202 # It has to work when the repository carrying the floor is not the one the
203 # controller serves, which is the ordinary case: on integratorHost every
204 # controller serves a protected project and reads the floor out of
205 # "open", which no controller serves. git refuses a repository the caller
206 # does not own, so that read needs its own safe.directory entry, named and
207 # not wildcarded — the same failure as the served repository's, one
208 # repository over.
209 #
210 # And it has to keep working when the two coincide, which is what an
211 # instance's own host looks like: integratorSelfHost's controller for
212 # "guarded" reads the floor from "guarded".
213 integratorFloor =
214 let
215 command = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
216 selfCommand = integratorSelfHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
217 env = integratorHost.config.systemd.services."valley-integrator@".environment;
218 in
219 !(lib.hasInfix "--instance-repo /srv/git/sealed.git" command)
220 || !(lib.hasInfix "--instance-repo /srv/git/guarded.git" selfCommand)
221 || env.GIT_CONFIG_COUNT or null != "2"
222 || env.GIT_CONFIG_KEY_1 or null != "safe.directory"
223 || env.GIT_CONFIG_VALUE_1 or null != "/srv/git/sealed.git";
224
225 integratorScratch =
226 integratorGitEnv.TMPDIR or null != "/var/lib/${integratorService.StateDirectory}"
227 || !(builtins.elem "/var/lib/${integratorService.StateDirectory}" integratorService.ReadWritePaths);
228
229 # The registry compiler. It is off by default and must stay inert: a
230 # consumer that has not asked for it renders the system it always did.
231 # integratorHost is the strongest witness available — the integrator on,
232 # the signers file supplied by hand, and every option of the identity
233 # block left alone.
234 identityRenderedWithoutEnable =
235 integratorHost.config.systemd.services ? valley-identity
236 || integratorHost.config.systemd.timers ? valley-identity
237 || integratorHost.config.services.openssh.settings ? PermitUserEnvironment
238 || lib.any (lib.hasInfix "valley-identity") integratorHost.config.services.openssh.authorizedKeysFiles
239 || lib.hasInfix "valley-identity" integratorHost.config.services.openssh.extraConfig
240 || lib.hasInfix "valley-identity" (
241 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
242 )
243 || lib.hasInfix "--name " (
244 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
245 );
246
247 identityService = identityHost.config.systemd.services.valley-identity.serviceConfig;
248
249 identityStateDir = "/var/lib/${identityService.StateDirectory or ""}";
250
251 # What the compiled artifacts have to be true of, and each was a way for
252 # the machinery to be quietly wrong.
253 #
254 # The compiler writes into its state directory and nowhere else, so that
255 # directory has to be the one path the unit may write.
256 #
257 # sshd walks every directory above an authorized-keys file and refuses a
258 # group- or world-writable one, so the state directory is 0755 rather than
259 # the 0700 a service's state usually takes — and the unit runs as the git
260 # user, because sshd equally refuses a file owned by anyone but root or
261 # the account it authorizes.
262 #
263 # The compiled file is added to what sshd reads for the git user rather
264 # than replacing it, and for the git user alone: the user's Match block
265 # names the declared keys and the compiled ones, and nothing else — no
266 # ~/.ssh/authorized_keys, no AuthorizedKeysCommand — so every key the git
267 # user accepts carries a tag this module or the compiler wrote. The
268 # compiler is handed the declared keys, so it can refuse a registry key
269 # declared under another tag.
270 identityCompiler =
271 identityService.User or null != identityHost.config.services.valley.user
272 || identityService.StateDirectoryMode or null != "0755"
273 || identityService.ReadWritePaths or [ ] != [ identityStateDir ]
274 || !(lib.hasInfix "--repo /srv/git/sealed.git" identityService.ExecStart)
275 || !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" identityService.ExecStart)
276 || !(lib.hasInfix "--authorized-keys ${identityStateDir}/authorized_keys.git" identityService.ExecStart)
277 || !(lib.hasInfix "--grants ${identityStateDir}/grants" identityService.ExecStart)
278 || !(lib.hasInfix "-valley-declared-keys" identityService.ExecStart)
279 || !(lib.hasInfix "AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u ${identityStateDir}/authorized_keys.git\n" identityHost.config.services.openssh.extraConfig)
280 || !(lib.hasInfix "AuthorizedKeysCommand none" identityHost.config.services.openssh.extraConfig);
281
282 # A controller under a compiled registry reads the compiled signers file
283 # and signs under the name the registry publishes its key under. The key
284 # hash binds name to key, so a controller signing under the host's default
285 # name while the registry publishes it as "integrator" would produce notes
286 # no verifier can find a key for.
287 identityIntegrator =
288 let
289 command = identityHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
290 in
291 !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" command)
292 || !(lib.hasInfix "--name integrator" command)
293 || !(builtins.elem "valley-identity.service"
294 identityHost.config.systemd.services."valley-integrator@".after
295 );
296
297 # The declared keys stay authorized beside the compiled ones. A compiled
298 # file that replaced them would make a bad compilation — or a first boot
299 # before the first one — a locked-out git user, which is the one failure
300 # this machinery must never have.
301 identityKeepsDeclaredKeys =
302 identityHost.config.users.users.git.openssh.authorizedKeys.keys == [ ];
303in
304{
305 module-eval =
306 if failedAssertions != [ ] then
307 throw "valley module-eval: failed assertions: ${
308 lib.concatMapStringsSep "; " (a: a.message) failedAssertions
309 }"
310 else if resticRenderedWithoutDeclaration then
311 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
312 else if busRenderedWithoutEnable then
313 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
314 else if
315 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
316 then
317 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
318 else if unrefusedHosts != [ ] then
319 throw "valley module-eval: ${lib.concatMapStringsSep "; " (r: "a host was not refused although ${r.why}") unrefusedHosts}"
320 else if protectionRenderedWithoutDeclaration then
321 throw "valley module-eval: principal machinery rendered for a declaration with no protection block and no tagged key"
322 else if policyMissingWithoutDeclaration then
323 throw "valley module-eval: a project with no protection block got no pre-receive hook — the push policy is installed on every project a host serves"
324 else if protectedHost.config.services.openssh.settings ? PermitUserEnvironment then
325 throw "valley module-eval: sshd must pass no key's environment on: the git user's shell derives the principal from the authenticated key"
326 else if
327 !(lib.hasInfix "valley-git-shell" protectedHost.config.users.users.git.shell)
328 then
329 throw "valley module-eval: the git user's login shell must be the valley's, which derives the principal and pauses pushes until init converges"
330 else if integratorRenderedWithoutEnable then
331 throw "valley module-eval: integrator machinery rendered for a protected declaration that never enabled the service"
332 else if !(integratorHost.config.systemd.services ? "valley-integrator@") then
333 throw "valley module-eval: the integrator is enabled and no controller unit was rendered"
334 else if
335 controllers != [
336 "valley-integrator@guarded.service"
337 "valley-integrator@released.service"
338 "valley-integrator@sealed.service"
339 ]
340 then
341 throw "valley module-eval: a controller runs for each protected project and no other, not ${lib.concatStringsSep ", " controllers}"
342 else if integratorUser == integratorHost.config.services.valley.user then
343 throw "valley module-eval: the integrator must not run as the git user — it has its own (bd-500adf7)"
344 else if !(integratorHost.config.users.users ? ${integratorUser}) then
345 throw "valley module-eval: the integrator runs as ${integratorUser}, which the module never declares"
346 else if integratorHost.config.users.users.${integratorUser}.group != "git" then
347 throw "valley module-eval: the integrator reaches the repositories through the git group, and holds no other grant"
348 else if integratorSafeDirectory then
349 throw "valley module-eval: a controller must carry safe.directory for the one repository it serves in its own environment — it does not own the repositories, and git refuses what it does not own"
350 else if integratorFloor then
351 throw "valley module-eval: a controller must be told which repository carries the floor, and must carry a safe.directory exception for it — the floor is read from that repository's integrated tip, and git refuses a repository its caller does not own"
352 else if integratorScratch then
353 throw "valley module-eval: a controller's TMPDIR must be its state directory and that directory must be named in ReadWritePaths — under ProtectSystem=strict a path the unit does not enumerate is one it cannot write, and a verdict needs a worktree on disk"
354 else if identityRenderedWithoutEnable then
355 throw "valley module-eval: registry-compilation machinery rendered for a host that never enabled it — nothing may change until a consumer opts in"
356 else if identityCompiler then
357 throw "valley module-eval: the compiler must run as the git user, write only its own 0755 state directory, read the registry from the instance repository, write the grants the pre-receive hook reads, and have its authorized_keys added to what sshd reads under the %u token — sshd refuses a keys file owned by anyone but root or the account it authorizes, and a fixed path in that global list would authorize every registry key for every account on the host"
358 else if identityIntegrator then
359 throw "valley module-eval: a controller under a compiled registry must read the compiled signers file, start after the compilation, and sign under the name the registry publishes its key under"
360 else if identityKeepsDeclaredKeys then
361 throw "valley module-eval: the declared authorized keys must stay authorized beside the compiled ones — a compiled file that replaced them would make a bad compilation a locked-out git user"
362 else
363 pkgs.runCommand "valley-module-eval" {
364 initScript = host.config.systemd.services.valley-init.script;
365 sshdConfig = host.config.services.openssh.extraConfig;
366 resticService = host.config.systemd.units."restic-backups-valley.service".text;
367 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
368 protectedInit = protectedHost.config.systemd.services.valley-init.script;
369 protectedKeys = lib.concatStringsSep "\n" protectedKeyLines;
370 protectedShell = protectedHost.config.users.users.git.shell;
371 integratorUnit = integratorHost.config.systemd.units."valley-integrator@.service".text;
372 integratorInit = integratorHost.config.systemd.services.valley-init.script;
373 identityInit = identityHost.config.systemd.services.valley-init.script;
374 passAsFile = [
375 "initScript"
376 "sshdConfig"
377 "resticService"
378 "resticTimer"
379 "protectedInit"
380 "protectedKeys"
381 "integratorUnit"
382 "integratorInit"
383 "identityInit"
384 ];
385 } (builtins.readFile ./module-eval.sh);
386}