| 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 | |
| 26 | let |
| 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, though the unit's IP address filter must deny it: the filter is not in force, as when systemd lacks cgroup BPF support, or allowedAddresses covers $addr" |
| 148 | ;; |
| 149 | 124:*) |
| 150 | refuse "a datagram to $addr port $port was neither sent nor refused within 5 seconds: the unit's IP address filter is not proven in force" |
| 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), so it is in force" |
| 154 | ;; |
| 155 | *"Network is unreachable"* | *"No route to host"*) |
| 156 | refuse "a datagram to $addr port $port had no route, so it never reached the unit's IP address filter, which is not proven in force; the host needs a route to $addr, such as a default route ($out)" |
| 157 | ;; |
| 158 | *) |
| 159 | refuse "a datagram to $addr port $port failed, but not with the EPERM of the unit's IP address filter, which is not proven in force ($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; |
| 178 | in |
| 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 | The IP addresses a pass may connect to, each an address or a |
| 224 | prefix: the receiver's addresses. The unit allows these |
| 225 | (`IPAddressAllow`) and denies every other (`IPAddressDeny=any`), |
| 226 | loopback included. The repositories are local paths and the |
| 227 | valley commands a pass runs use no network, so a pass needs |
| 228 | nothing else. |
| 229 | |
| 230 | The filter is in force because the unit checks it before each |
| 231 | pass (`ExecStartPre`) and refuses to start the pass otherwise. |
| 232 | The check sends a UDP datagram to ${canary.address}, which the |
| 233 | filter must deny, and passes only when the send fails with EPERM. |
| 234 | systemd ignores the filter, with only a warning, where cgroup BPF |
| 235 | support is missing, and then no pass starts. The list may not |
| 236 | cover ${canary.address}, and the host needs a route to it, such as a |
| 237 | default route. |
| 238 | |
| 239 | Names need no resolver's address here. The unit sets |
| 240 | `GODEBUG=netdns=cgo`, so the publisher, built with cgo, looks |
| 241 | names up through the C library. On NixOS the C library asks nscd |
| 242 | ({option}`services.nscd.enable`, on by default) over a Unix |
| 243 | socket, and nscd queries DNS outside the unit. Without nscd, the |
| 244 | lookup runs inside the unit, and the filter denies the resolver |
| 245 | in /etc/resolv.conf unless its address is listed. |
| 246 | |
| 247 | The list allows addresses and nothing else: any port at a listed |
| 248 | address is reachable, and the receiver's host name is not checked |
| 249 | against it. When the receiver's addresses change, a pass fails |
| 250 | until this list follows them. |
| 251 | ''; |
| 252 | }; |
| 253 | |
| 254 | receiverTokenFile = lib.mkOption { |
| 255 | type = lib.types.strMatching "/.+"; |
| 256 | example = "/run/keys/valley-web-receiver-token"; |
| 257 | description = '' |
| 258 | The file that holds the receiver's token, which every request of |
| 259 | an upload carries: one line of 32 to 256 visible ASCII characters, |
| 260 | the token the receiver is given. The path is outside the Nix |
| 261 | store, and systemd reads the file as the unit's credential, so it |
| 262 | may be readable by root alone. |
| 263 | ''; |
| 264 | }; |
| 265 | |
| 266 | principals = lib.mkOption { |
| 267 | type = lib.types.attrsOf lib.types.str; |
| 268 | default = { }; |
| 269 | example = { |
| 270 | operator = "operator"; |
| 271 | alice = "agent"; |
| 272 | }; |
| 273 | description = '' |
| 274 | The display mapping: what an export shows in place of each |
| 275 | principal's name. A principal it does not name is shown as |
| 276 | `contributor`. |
| 277 | ''; |
| 278 | }; |
| 279 | |
| 280 | stateDir = lib.mkOption { |
| 281 | type = lib.types.strMatching "/var/lib/[^/].*"; |
| 282 | default = "/var/lib/valley-web-publish"; |
| 283 | description = '' |
| 284 | The publisher's state, under /var/lib: its export key, made on the |
| 285 | first start, the key's verifier line, which the receiver pins, and |
| 286 | the last acknowledgement. The cache is the directory of the same |
| 287 | name under /var/cache. |
| 288 | ''; |
| 289 | }; |
| 290 | |
| 291 | memoryMax = lib.mkOption { |
| 292 | type = size; |
| 293 | default = "1G"; |
| 294 | description = '' |
| 295 | The most memory a pass may use, the publisher and every git, cue |
| 296 | and valley it runs together (`MemoryMax`, with no swap). Past it, |
| 297 | the kernel ends the pass. |
| 298 | ''; |
| 299 | }; |
| 300 | |
| 301 | maxBundles = lib.mkOption { |
| 302 | type = size; |
| 303 | default = "1G"; |
| 304 | description = '' |
| 305 | The most the bundles of one export may hold together. Each bundle |
| 306 | carries a public project's whole history on main. A bundle is |
| 307 | written only into what this leaves, and a pass past it sends |
| 308 | nothing (`--max-bundles`). |
| 309 | ''; |
| 310 | }; |
| 311 | |
| 312 | maxStorage = lib.mkOption { |
| 313 | type = size; |
| 314 | default = "16G"; |
| 315 | description = '' |
| 316 | The most the state and cache directories may hold. The cache holds |
| 317 | a clone and a mirror of each project a read grant to anyone names, |
| 318 | and a bundle of each public one. A pass checks it before it fetches and once it |
| 319 | has read the valley, and writes a bundle only into what it leaves. |
| 320 | A pass past it sends nothing (`--max-storage`). |
| 321 | ''; |
| 322 | }; |
| 323 | |
| 324 | # The publisher as this flake packages it. Internal, like the host |
| 325 | # module's packages: module-eval sets it to a stand-in. |
| 326 | package = lib.mkOption { |
| 327 | type = lib.types.package; |
| 328 | internal = true; |
| 329 | default = (import ./packages.nix { inherit pkgs lib; }).valley-web-publish; |
| 330 | defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-web-publish"; |
| 331 | description = "The web publisher."; |
| 332 | }; |
| 333 | }; |
| 334 | |
| 335 | config = lib.mkIf cfg.enable { |
| 336 | assertions = [ |
| 337 | { |
| 338 | assertion = host.enable; |
| 339 | message = "services.valley.webPublisher needs services.valley: it reads the repositories that host serves."; |
| 340 | } |
| 341 | { |
| 342 | assertion = cfg.allowedAddresses != [ ]; |
| 343 | message = "services.valley.webPublisher.allowedAddresses is empty: list the receiver's IP addresses. A pass may connect to no address the list leaves out."; |
| 344 | } |
| 345 | { |
| 346 | assertion = !(lib.any coversCanary cfg.allowedAddresses); |
| 347 | 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."; |
| 348 | } |
| 349 | { |
| 350 | assertion = !(lib.hasPrefix builtins.storeDir cfg.receiverTokenFile); |
| 351 | message = "services.valley.webPublisher.receiverTokenFile is in the Nix store, which every user can read; give a path outside it."; |
| 352 | } |
| 353 | { |
| 354 | assertion = host.integrator.instanceProject != null; |
| 355 | 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."; |
| 356 | } |
| 357 | ]; |
| 358 | |
| 359 | # One pass, as a oneshot the timer below starts. A switch never starts |
| 360 | # it: nothing wants the service, and a changed unit is not restarted. |
| 361 | # The publisher's own lock serializes a pass started by hand with the |
| 362 | # timer's. |
| 363 | systemd.services.valley-web-publish = { |
| 364 | description = "One pass of the valley web publisher"; |
| 365 | after = [ |
| 366 | "network-online.target" |
| 367 | "valley-init.service" |
| 368 | ]; |
| 369 | wants = [ "network-online.target" ]; |
| 370 | restartIfChanged = false; |
| 371 | unitConfig.RequiresMountsFor = toString host.dataDir; |
| 372 | # Go's own resolver would query /etc/resolv.conf's nameserver from |
| 373 | # inside the unit, where the filter denies it. The C library's asks |
| 374 | # nscd over a Unix socket, which resolves outside the unit. |
| 375 | environment = safeDirectories // { |
| 376 | HOME = toString cfg.stateDir; |
| 377 | XDG_CACHE_HOME = cacheDir; |
| 378 | GODEBUG = "netdns=cgo"; |
| 379 | }; |
| 380 | serviceConfig = { |
| 381 | Type = "oneshot"; |
| 382 | # Run in the unit's cgroup, under its filter, before each pass. |
| 383 | ExecStartPre = "${lib.getExe egressCheck} ${canary.address} ${canary.port}"; |
| 384 | ExecStart = command; |
| 385 | # A pass that hangs is ended, and the timer starts the next. One |
| 386 | # that outgrows its memory is ended too. |
| 387 | TimeoutStartSec = "1h"; |
| 388 | MemoryMax = cfg.memoryMax; |
| 389 | MemorySwapMax = "0"; |
| 390 | DynamicUser = true; |
| 391 | SupplementaryGroups = [ host.group ]; |
| 392 | StateDirectory = stateName; |
| 393 | StateDirectoryMode = "0700"; |
| 394 | CacheDirectory = stateName; |
| 395 | CacheDirectoryMode = "0700"; |
| 396 | WorkingDirectory = toString cfg.stateDir; |
| 397 | LoadCredential = [ "receiver-token:${cfg.receiverTokenFile}" ]; |
| 398 | # ProtectSystem=strict leaves the whole filesystem read-only but |
| 399 | # the state and cache directories, which systemd exempts. So the |
| 400 | # repositories, readable through the git group, are read-only, |
| 401 | # and named here so a reader of the unit sees it. A repository |
| 402 | # valley-init has not made yet is skipped (the leading -). |
| 403 | ProtectSystem = "strict"; |
| 404 | ReadOnlyPaths = map (p: "-${p}") repositories; |
| 405 | InaccessiblePaths = map (p: "-${p}") keys; |
| 406 | ProtectHome = true; |
| 407 | PrivateTmp = true; |
| 408 | PrivateDevices = true; |
| 409 | NoNewPrivileges = true; |
| 410 | ProtectClock = true; |
| 411 | ProtectHostname = true; |
| 412 | ProtectKernelLogs = true; |
| 413 | ProtectKernelModules = true; |
| 414 | ProtectKernelTunables = true; |
| 415 | ProtectControlGroups = true; |
| 416 | ProtectProc = "invisible"; |
| 417 | # A pass connects to the receiver and to nothing else. |
| 418 | IPAddressDeny = "any"; |
| 419 | IPAddressAllow = cfg.allowedAddresses; |
| 420 | RestrictAddressFamilies = [ |
| 421 | "AF_INET" |
| 422 | "AF_INET6" |
| 423 | "AF_UNIX" |
| 424 | ]; |
| 425 | RestrictNamespaces = true; |
| 426 | RestrictRealtime = true; |
| 427 | RestrictSUIDSGID = true; |
| 428 | LockPersonality = true; |
| 429 | CapabilityBoundingSet = ""; |
| 430 | SystemCallArchitectures = "native"; |
| 431 | SystemCallFilter = [ "@system-service" ]; |
| 432 | UMask = "0077"; |
| 433 | }; |
| 434 | }; |
| 435 | |
| 436 | # The first pass starts five minutes after the timer starts, and each |
| 437 | # later pass five minutes after the last one ended. These are delays |
| 438 | # and nothing more: a switch that runs longer than five minutes can |
| 439 | # see the first pass start inside it, and any later switch can see a |
| 440 | # pass start inside it. |
| 441 | systemd.timers.valley-web-publish = { |
| 442 | description = "Run the valley web publisher"; |
| 443 | wantedBy = [ "timers.target" ]; |
| 444 | timerConfig = { |
| 445 | OnActiveSec = "5min"; |
| 446 | OnUnitInactiveSec = "5min"; |
| 447 | }; |
| 448 | }; |
| 449 | }; |
| 450 | } |