gunk-dev/the-valley

web-publisher.nix

source860de91b1a12main's published tip history
23.6 KiB
1# The web publisher (web/cmd/valley-web-publish): a oneshot on a timer
2# that reads each of this host's projects some reader may read at the
3# edge, and pushes signed exports to a web receiver, which never connects
4# back.
5#
6# A module of its own beside the host module (valley-host.nix), which it
7# needs: it reads that module's options for the repositories the host
8# serves, their group, and the instance repository. Which projects exist,
9# and the signers that verify their landings, it reads at run time from
10# what the instance repository publishes, through the valley CLI.
11#
12# The service runs as a dynamic user in the git group, so it can read the
13# repositories and own nothing on disk but its state and cache. It cannot
14# write the repositories, and the files that hold the host's mirror,
15# backup and signing keys are made inaccessible to it. The receiver's
16# token is a file outside the Nix store, which systemd reads and hands to
17# the unit as a credential. The read links' credential file is readable
18# through a group of its own, and each pass reads it live as it signs,
19# under the links lock beside it, which only root can make or replace. The unit may connect to the addresses
20# allowedAddresses lists and to no other, and it checks before each pass
21# that this filter is in force.
22{
23 config,
24 pkgs,
25 lib,
26 ...
27}:
28
29let
30 cfg = config.services.valley.webPublisher;
31 host = config.services.valley;
32
33 # The repositories this host serves, read from its declaration the way
34 # the host module reads them. The derivation is the host module's own,
35 # with the same name, schema and declaration, so it is built once. The
36 # publisher reads the same export with --host, for the groups and each
37 # project's group and short aliases, which its web URLs are made of.
38 schema = ../schema/valley.cue;
39 configJSON =
40 pkgs.runCommand "valley-config.json"
41 {
42 nativeBuildInputs = [ pkgs.cue ];
43 }
44 ''
45 cue vet -c ${schema} ${host.config}
46 cue export ${schema} ${host.config} > $out
47 '';
48 declared = lib.importJSON configJSON;
49 repositories = map (name: "${toString host.dataDir}/${name}.git") (
50 lib.attrNames (lib.filterAttrs (_: p: p.git.enable) declared.projects)
51 );
52
53 instanceRepo = "${toString host.dataDir}/${toString host.integrator.instanceProject}.git";
54
55 # The repositories belong to the git user and the service does not, so
56 # git refuses them as dubiously owned. The unit's environment carries
57 # safe.directory entries, which every git the publisher and the valley
58 # CLI run inherits. GIT_CONFIG_* is command scope, which git reads
59 # safe.directory from, after the system and global configuration. The
60 # entries add to what those set, so the first is empty, which resets the
61 # list (git-config(1)), and one exact entry per repository follows. A
62 # system configuration that trusts every directory trusts none of them
63 # here. Never a wildcard.
64 safeDirectories = {
65 GIT_CONFIG_COUNT = toString (lib.length repositories + 1);
66 }
67 // lib.listToAttrs (
68 lib.concatLists (
69 lib.imap0 (i: repo: [
70 (lib.nameValuePair "GIT_CONFIG_KEY_${toString i}" "safe.directory")
71 (lib.nameValuePair "GIT_CONFIG_VALUE_${toString i}" repo)
72 ]) ([ "" ] ++ repositories)
73 )
74 );
75
76 # What the service must never read: the git user's ssh identity, which
77 # pushes the mirrors, and the key files the host module is given. A path
78 # that does not exist is skipped (the leading -).
79 keys = [
80 "${toString host.dataDir}/.ssh"
81 "/var/lib/valley-integrator"
82 ]
83 ++ lib.optional (host.integrator.signingKeyFile != null) (toString host.integrator.signingKeyFile)
84 ++ lib.optional host.worker.enable (toString host.worker.stateDir)
85 ++ map toString (
86 lib.filter (p: p != null) [
87 host.backup.sshKeyFile
88 host.backup.passwordFile
89 host.backup.repositoryFile
90 ]
91 );
92
93 stateName = lib.removePrefix "/var/lib/" (toString cfg.stateDir);
94 cacheDir = "/var/cache/${stateName}";
95
96 principalsFile = pkgs.writeText "valley-web-principals.json" (builtins.toJSON cfg.principals);
97
98 command = lib.concatStringsSep " " [
99 (lib.getExe cfg.package)
100 "--instance-repo ${lib.escapeShellArg instanceRepo}"
101 "--instance ${lib.escapeShellArg config.networking.hostName}"
102 "--destination ${lib.escapeShellArg cfg.destination}"
103 "--host ${configJSON}"
104 "--receiver ${lib.escapeShellArg cfg.receiver}"
105 # %d is the unit's credentials directory.
106 "--receiver-token %d/receiver-token"
107 "--principals ${principalsFile}"
108 "--state ${lib.escapeShellArg (toString cfg.stateDir)}"
109 "--max-bundles ${cfg.maxBundles}"
110 "--max-storage ${cfg.maxStorage}"
111 "--registry-ref ${lib.escapeShellArg host.identity.ref}"
112 "--registry-dir ${lib.escapeShellArg host.identity.directory}"
113 "--links ${lib.escapeShellArg (toString cfg.linksFile)}"
114 ];
115
116 linksDir = dirOf (toString cfg.linksFile);
117
118 # The group the passes read the credential file through. Root alone
119 # writes the file.
120 linksGroup = "valley-web-links";
121
122 # The operator's command for read links, run as root. It runs the
123 # publisher's link command with the module's paths, and git with the
124 # unit's exact safe.directory entries, as root owns no repository. After
125 # an issue or a revoke, whether or not it changed anything, it starts a
126 # policy-only pass, then checks for a link the receiver does not yet hold
127 # the state of. A pass already running when the command started may have
128 # signed before the change, and systemctl start then returns once that
129 # pass ends. So while a link is pending, the command starts the pass and
130 # checks once more. It never repeats the change. It reports every link
131 # still pending, and exits 1 while one is. So running a revoke again
132 # retries its delivery. list and prune start no pass: prune removes only
133 # revocations a pass delivered.
134 # No core dump is written, so none holds an issued link's secret.
135 linkCommand = pkgs.writeShellApplication {
136 name = "valley-web-link";
137 runtimeInputs = [
138 cfg.package
139 pkgs.coreutils
140 pkgs.systemd
141 ];
142 text = ''
143 ulimit -c 0
144 ${lib.concatStringsSep "\n" (lib.mapAttrsToList (k: v: "export ${k}=${lib.escapeShellArg v}") safeDirectories)}
145 link() {
146 valley-web-publish link "$@" --links ${lib.escapeShellArg (toString cfg.linksFile)} \
147 --state ${lib.escapeShellArg (toString cfg.stateDir)}
148 }
149 case "''${1:-}" in
150 issue)
151 link "$@" --instance-repo ${lib.escapeShellArg instanceRepo} \
152 --destination ${lib.escapeShellArg cfg.destination} --host ${configJSON} \
153 --registry-ref ${lib.escapeShellArg host.identity.ref} \
154 --registry-dir ${lib.escapeShellArg host.identity.directory}
155 ;;
156 revoke) link "$@" ;;
157 *) link "$@"; exit ;;
158 esac
159 deliver() {
160 systemctl start valley-web-publish-policy.service ||
161 echo "valley-web-link: the policy pass failed; see journalctl -u valley-web-publish-policy" >&2
162 }
163 deliver
164 if ! link list --check > /dev/null 2>&1; then
165 deliver
166 fi
167 if link list --check > /dev/null; then
168 echo "valley-web-link: the receiver holds every link's current state" >&2
169 else
170 echo "valley-web-link: the edge does not yet hold every change; see journalctl -u valley-web-publish-policy, then run the command again to retry the delivery" >&2
171 exit 1
172 fi
173 '';
174 };
175
176 # One unit of the publisher: a pass, or its policy path alone.
177 pass =
178 { description, execStart }:
179 {
180 inherit description;
181 after = [
182 "network-online.target"
183 "valley-init.service"
184 ];
185 wants = [ "network-online.target" ];
186 restartIfChanged = false;
187 unitConfig.RequiresMountsFor = toString host.dataDir;
188 # Go's own resolver would query /etc/resolv.conf's nameserver from
189 # inside the unit, where the filter denies it. The C library's asks
190 # nscd over a Unix socket, which resolves outside the unit.
191 environment = safeDirectories // {
192 HOME = toString cfg.stateDir;
193 XDG_CACHE_HOME = cacheDir;
194 GODEBUG = "netdns=cgo";
195 };
196 serviceConfig = {
197 Type = "oneshot";
198 # Run in the unit's cgroup, under its filter, before each pass.
199 ExecStartPre = "${lib.getExe egressCheck} ${canary.address} ${canary.port}";
200 ExecStart = execStart;
201 # A pass that hangs is ended, and the timer starts the next. One
202 # that outgrows its memory is ended too.
203 TimeoutStartSec = "1h";
204 MemoryMax = cfg.memoryMax;
205 MemorySwapMax = "0";
206 # Both units share the state and cache directories, so they run as
207 # one dynamic user: systemd gives units that name the same User one
208 # UID, and never changes the directories' owner under a running
209 # pass when the other starts.
210 DynamicUser = true;
211 User = "valley-web-publish";
212 Group = "valley-web-publish";
213 SupplementaryGroups = [
214 host.group
215 linksGroup
216 ];
217 StateDirectory = stateName;
218 StateDirectoryMode = "0700";
219 CacheDirectory = stateName;
220 CacheDirectoryMode = "0700";
221 WorkingDirectory = toString cfg.stateDir;
222 LoadCredential = [ "receiver-token:${cfg.receiverTokenFile}" ];
223 # ProtectSystem=strict leaves the whole filesystem read-only but
224 # the state and cache directories, which systemd exempts. So the
225 # repositories, readable through the git group, are read-only,
226 # and named here so a reader of the unit sees it. A repository
227 # valley-init has not made yet is skipped (the leading -).
228 ProtectSystem = "strict";
229 ReadOnlyPaths = map (p: "-${p}") repositories;
230 InaccessiblePaths = map (p: "-${p}") keys;
231 ProtectHome = true;
232 PrivateTmp = true;
233 PrivateDevices = true;
234 NoNewPrivileges = true;
235 ProtectClock = true;
236 ProtectHostname = true;
237 ProtectKernelLogs = true;
238 ProtectKernelModules = true;
239 ProtectKernelTunables = true;
240 ProtectControlGroups = true;
241 ProtectProc = "invisible";
242 # A pass connects to the receiver and to nothing else.
243 IPAddressDeny = "any";
244 IPAddressAllow = cfg.allowedAddresses;
245 RestrictAddressFamilies = [
246 "AF_INET"
247 "AF_INET6"
248 "AF_UNIX"
249 ];
250 RestrictNamespaces = true;
251 RestrictRealtime = true;
252 RestrictSUIDSGID = true;
253 LockPersonality = true;
254 CapabilityBoundingSet = "";
255 SystemCallArchitectures = "native";
256 SystemCallFilter = [ "@system-service" ];
257 UMask = "0077";
258 };
259 };
260
261 size = lib.types.strMatching "[1-9][0-9]*[KMGT]?";
262
263 # The address the unit's check sends to before each pass, which the
264 # filter must deny: 198.51.100.1, in TEST-NET-2 (RFC 5737), which no
265 # receiver uses. The port is discard's.
266 canary = {
267 address = "198.51.100.1";
268 port = "9";
269 };
270
271 # The check: a UDP datagram to the canary, sent from inside the unit's
272 # cgroup. The filter makes the send fail at once with EPERM, and the pass
273 # starts only then. A datagram sent means the filter is not attached:
274 # systemd ignores IPAddressDeny, with only a warning, where the kernel or
275 # the manager lacks cgroup BPF support. Any other error, such as no route,
276 # proves nothing. A TCP connect would not do: the filter drops its SYN,
277 # and connect waits as it would for an address that never answers.
278 egressCheck = pkgs.writeShellApplication {
279 name = "valley-web-publish-egress-check";
280 runtimeInputs = [
281 pkgs.bash
282 pkgs.coreutils
283 ];
284 text = ''
285 export LC_ALL=C
286 addr=$1 port=$2
287 refuse() {
288 echo "valley-web-publish-egress-check: $*; the pass does not start" >&2
289 exit 1
290 }
291 status=0
292 # shellcheck disable=SC2016
293 out=$(timeout 5 bash -c 'printf canary > "/dev/udp/$1/$2"' check "$addr" "$port" 2>&1) || status=$?
294 case $status:$out in
295 0:*)
296 refuse "a datagram to $addr port $port was sent; the unit's IP address filter did not block it (check cgroup BPF support in systemd and the kernel, and check that allowedAddresses excludes $addr)"
297 ;;
298 124:*)
299 refuse "sending a datagram to $addr port $port timed out after 5 seconds without EPERM from the unit's IP address filter"
300 ;;
301 *"write error: Operation not permitted"*)
302 echo "valley-web-publish-egress-check: the unit's IP address filter refused a datagram to $addr port $port (EPERM)"
303 ;;
304 *"Network is unreachable"* | *"No route to host"*)
305 refuse "no route to $addr port $port ($out); add a route covering $addr, such as a default route, so the datagram reaches the unit's IP address filter"
306 ;;
307 *)
308 refuse "sending a datagram to $addr port $port failed without EPERM from the unit's IP address filter ($out)"
309 ;;
310 esac
311 '';
312 };
313
314 # An IPv4 address as a number, and whether an entry of allowedAddresses
315 # covers the canary: the address itself, or a prefix that holds it. An
316 # IPv6 entry covers no IPv4 address in the filter.
317 ipv4 = a: lib.foldl' (n: octet: n * 256 + lib.toInt octet) 0 (lib.splitString "." a);
318 coversCanary =
319 entry:
320 let
321 m = builtins.match "((0|[1-9][0-9]{0,2})(\\.(0|[1-9][0-9]{0,2})){3})(/([0-9]+))?" entry;
322 length = if lib.elemAt m 5 == null then 32 else lib.toInt (lib.elemAt m 5);
323 mask = 4294967296 - lib.foldl' (n: _: n * 2) 1 (lib.range 1 (32 - length));
324 in
325 m != null
326 && builtins.bitAnd (ipv4 (lib.head m)) mask == builtins.bitAnd (ipv4 canary.address) mask;
327in
328{
329 options.services.valley.webPublisher = {
330 enable = lib.mkEnableOption ''
331 the valley web publisher: a timer that uploads this host's
332 projects, as signed exports, to a web receiver. A project is
333 exported when it has an effective reader, a principal, anyone
334 included, that its own policy/read names and a read grant in the
335 identity registry covers it for at the destination, and when the
336 host declaration places it in a group, which its web URLs open
337 with. The
338 registry is read where the identity compiler reads it: in
339 {option}`services.valley.identity.directory` at the instance
340 repository's {option}`services.valley.identity.ref`. The host module
341 requires that ref to be protected. The manifest names
342 {option}`networking.hostName` as the instance, and is signed under
343 `<hostName>/web-export`
344 '';
345
346 destination = lib.mkOption {
347 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}";
348 example = "example.org";
349 description = ''
350 The receiver's name, which every manifest is signed for. The
351 receiver admits only manifests that name it. It is also the
352 destination of the registry's edge read boundary whose read grants
353 decide who may read each project there.
354 '';
355 };
356
357 receiver = lib.mkOption {
358 type = lib.types.strMatching "https?://[^/?#@]+(/[^?#]*)?";
359 example = "https://example.org";
360 description = ''
361 The receiver's base URL. The upload's paths are appended to it.
362 '';
363 };
364
365 allowedAddresses = lib.mkOption {
366 type = lib.types.listOf (lib.types.strMatching "[0-9a-fA-F.:]+(/[0-9]+)?");
367 default = [ ];
368 example = [
369 "192.0.2.10"
370 "2001:db8::10"
371 ];
372 description = ''
373 IPv4 or IPv6 addresses and prefixes that a pass may connect to.
374 Set this to the receiver's IP addresses. The unit allows only
375 these addresses (`IPAddressAllow`) and blocks all others
376 (`IPAddressDeny=any`), including loopback. A pass reads local
377 repositories and runs `valley` commands that use no network, so
378 it needs to reach only the receiver.
379
380 Before each pass, the unit runs an `ExecStartPre` check that
381 sends a UDP datagram to ${canary.address} and starts the pass
382 only if the cgroup filter rejects the send with `EPERM`. If
383 systemd or the kernel lacks cgroup BPF support, systemd logs a
384 warning and leaves the filter unattached, and the check stops
385 the pass from starting. Leave ${canary.address} out of this
386 list, and ensure the host has a route to it, such as a default
387 route.
388
389 The unit sets `GODEBUG=netdns=cgo`, so the cgo-built publisher
390 resolves host names through the C library. On NixOS, the C
391 library queries `nscd` ({option}`services.nscd.enable`, enabled
392 by default) over a local Unix socket, and `nscd` queries DNS
393 outside the unit. If `nscd` is disabled, DNS queries run inside
394 the unit and require the resolver address from `/etc/resolv.conf`
395 in this list.
396
397 The filter checks only the destination IP address and permits
398 every port on a listed address. When the receiver's IP addresses
399 change, passes fail until this list is updated.
400 '';
401 };
402
403 receiverTokenFile = lib.mkOption {
404 type = lib.types.strMatching "/.+";
405 example = "/run/keys/valley-web-receiver-token";
406 description = ''
407 The file that holds the receiver's token, which every request of
408 an upload carries: one line of 32 to 256 visible ASCII characters,
409 the token the receiver is given. The path is outside the Nix
410 store, and systemd reads the file as the unit's credential, so it
411 may be readable by root alone.
412 '';
413 };
414
415 principals = lib.mkOption {
416 type = lib.types.attrsOf lib.types.str;
417 default = { };
418 example = {
419 operator = "operator";
420 alice = "agent";
421 };
422 description = ''
423 The display mapping: what an export shows in place of each
424 principal's name. A principal it does not name is shown as
425 `contributor`.
426 '';
427 };
428
429 stateDir = lib.mkOption {
430 type = lib.types.strMatching "/var/lib/[^/].*";
431 default = "/var/lib/valley-web-publish";
432 description = ''
433 The publisher's state, under /var/lib: its export key, made on the
434 first start, the key's verifier line, which the receiver pins, and
435 the last acknowledgement. The cache is the directory of the same
436 name under /var/cache.
437 '';
438 };
439
440 linksFile = lib.mkOption {
441 type = lib.types.strMatching "/[^%]*[^/%]";
442 default = "/var/lib/valley-web-links/links";
443 description = ''
444 The read links' credential file, which `valley-web-link` writes as
445 root: one record per link, with its verifier and never its secret.
446 It is mode 0640, owned by root and the group `valley-web-links`,
447 in a directory of mode 0750 with the same owners, outside every
448 repository, cache and export. Each pass reads it through that
449 group as it signs an authorization, under the links lock, the file
450 `lock` in the same directory, owned by root and the same group,
451 mode 0640. It carries the active links to the edge. The verifiers are not
452 secret, as the edge holds them too: the file needs integrity, and
453 only root can write it.
454 '';
455 };
456
457 memoryMax = lib.mkOption {
458 type = size;
459 default = "1G";
460 description = ''
461 The most memory a pass may use, the publisher and every git, cue
462 and valley it runs together (`MemoryMax`, with no swap). Past it,
463 the kernel ends the pass.
464 '';
465 };
466
467 maxBundles = lib.mkOption {
468 type = size;
469 default = "1G";
470 description = ''
471 The most the bundles of one export may hold together. Each bundle
472 carries an exported project's whole history on main. A bundle is
473 written only into what this leaves, and a pass past it sends
474 nothing (`--max-bundles`).
475 '';
476 };
477
478 maxStorage = lib.mkOption {
479 type = size;
480 default = "16G";
481 description = ''
482 The most the state and cache directories may hold. The cache holds
483 a clone and a mirror of each project a read grant names, and a
484 bundle of each exported one. A pass checks it before it fetches and once it
485 has read the valley, and writes a bundle only into what it leaves.
486 A pass past it sends nothing (`--max-storage`).
487 '';
488 };
489
490 # The publisher as this flake packages it. Internal, like the host
491 # module's packages: module-eval sets it to a stand-in.
492 package = lib.mkOption {
493 type = lib.types.package;
494 internal = true;
495 default = (import ./packages.nix { inherit pkgs lib; }).valley-web-publish;
496 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-web-publish";
497 description = "The web publisher.";
498 };
499 };
500
501 config = lib.mkIf cfg.enable {
502 assertions = [
503 {
504 assertion = host.enable;
505 message = "services.valley.webPublisher needs services.valley: it reads the repositories that host serves.";
506 }
507 {
508 assertion = cfg.allowedAddresses != [ ];
509 message = "services.valley.webPublisher.allowedAddresses is empty: list the receiver's IP addresses. A pass may connect to no address the list leaves out.";
510 }
511 {
512 assertion = !(lib.any coversCanary cfg.allowedAddresses);
513 message = "services.valley.webPublisher.allowedAddresses covers ${canary.address}, which the unit sends a datagram to before each pass to check that its filter is in force. The filter must deny it: remove the address or prefix that covers it.";
514 }
515 {
516 assertion = !(lib.hasPrefix builtins.storeDir cfg.receiverTokenFile);
517 message = "services.valley.webPublisher.receiverTokenFile is in the Nix store, which every user can read; give a path outside it.";
518 }
519 {
520 assertion = host.integrator.instanceProject != null;
521 message = "services.valley.webPublisher needs services.valley.integrator.instanceProject: the publisher discovers the projects, and the signers that verify their landings, through what the instance repository publishes.";
522 }
523 ];
524
525 # One pass, as a oneshot the timer below starts. A switch never starts
526 # it: nothing wants the service, and a changed unit is not restarted.
527 # The publisher's own lock serializes a pass started by hand with the
528 # timer's.
529 systemd.services.valley-web-publish = pass {
530 description = "One pass of the valley web publisher";
531 execStart = command;
532 };
533
534 # The policy path alone, which valley-web-link starts after an issue or
535 # a revoke: it sends the authorization, with the current read links,
536 # and reads no plan and no bundle, so a stalled content pass does not
537 # hold it up.
538 systemd.services.valley-web-publish-policy = pass {
539 description = "The valley web publisher's policy path";
540 execStart = "${command} --policy-only";
541 };
542
543 # The credential file's directory, an empty file, which holds no
544 # links, and the links lock beside it, which a pass opens and locks
545 # through the group. The link command writes the file in its
546 # directory's group. Only root can make, replace or remove anything in
547 # the directory.
548 users.groups.${linksGroup} = { };
549 systemd.tmpfiles.rules = [
550 "d ${linksDir} 0750 root ${linksGroup} -"
551 "f ${toString cfg.linksFile} 0640 root ${linksGroup} -"
552 "f ${linksDir}/lock 0640 root ${linksGroup} -"
553 ];
554
555 environment.systemPackages = [ linkCommand ];
556
557 # The first pass starts five minutes after the timer starts, and each
558 # later pass five minutes after the last one ended. These are delays
559 # and nothing more: a switch that runs longer than five minutes can
560 # see the first pass start inside it, and any later switch can see a
561 # pass start inside it.
562 systemd.timers.valley-web-publish = {
563 description = "Run the valley web publisher";
564 wantedBy = [ "timers.target" ];
565 timerConfig = {
566 OnActiveSec = "5min";
567 OnUnitInactiveSec = "5min";
568 };
569 };
570 };
571}