gunk-dev/the-valley

web-publisher.nix

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