gunk-dev/the-valley

host-module.nix

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