gunk-dev/the-valley

web-publisher.nix

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