| 1 | # The valley host installer: declarative bare-git hosting over SSH, driven |
| 2 | # by a CUE host declaration (../schema/valley.cue). |
| 3 | # |
| 4 | # Layering: the CUE file owns the domain model — which projects exist, their |
| 5 | # stores, their push mirrors, whether the host's data has offsite backup and |
| 6 | # with what cadence and retention. This module owns machine integration |
| 7 | # only: data directory, unix user, SSH keys, backup credentials. At build |
| 8 | # time the CUE config is vetted against the shipped schema and exported to |
| 9 | # JSON; an invalid config fails the system build with cue's error. Nix |
| 10 | # never redefines the schema. |
| 11 | # |
| 12 | # Repos are only ever created, never deleted or overwritten — removing a |
| 13 | # project (or disabling its git store) leaves the data on disk untouched. |
| 14 | # |
| 15 | # Identity is deliberately thin and host-level: one git user, git-shell, |
| 16 | # key-only, network ACLs in front. Per-project *access* is not honestly |
| 17 | # enforceable with this mechanism, so it is deliberately not an option |
| 18 | # (archive/.the-valley/decisions/dcr-0f5d9b1-cue-config-host-module.md). Per-project |
| 19 | # *write protection* is, because the pre-receive hook below is a real |
| 20 | # enforcement boundary and each key carries a principal name it can read |
| 21 | # (archive/.the-valley/decisions/dcr-b87f6e8-identity-is-a-governed-registry.md) — |
| 22 | # so it is declared, in the project's `protection` block, and this module |
| 23 | # only binds principal names to keys and grants, and installs the hook. |
| 24 | # Those bindings are declared by hand or compiled from the instance's |
| 25 | # identity registry, and the compiler is off until a consumer turns it on. |
| 26 | # |
| 27 | # Mirror credentials are the consumer's concern: the module assumes the git |
| 28 | # user's SSH identity and known_hosts are provisioned by the host (e.g. |
| 29 | # through its secrets). Every mirror push runs as the git user, whether |
| 30 | # a push or an integrator landing moved the ref. Nothing here plumbs |
| 31 | # secrets: the backup options below take *paths* to consumer-provisioned |
| 32 | # secret files; the contents never pass through this module or the store. |
| 33 | # |
| 34 | # Three services run under their own unix users rather than the git one: |
| 35 | # the integrator, which is the first half of the split bd-500adf7 asks |
| 36 | # for, and the check worker and the restacker, which are not in the git |
| 37 | # group at all. |
| 38 | { |
| 39 | config, |
| 40 | pkgs, |
| 41 | lib, |
| 42 | ... |
| 43 | }: |
| 44 | |
| 45 | let |
| 46 | cfg = config.services.valley; |
| 47 | |
| 48 | schema = ../schema/valley.cue; |
| 49 | |
| 50 | # Build-time vet + export of the host declaration. the vet checks the |
| 51 | # declaration against the schema (whose top level applies #Host), so unknown |
| 52 | # fields and unsafe project names fail the build, with cue's error. |
| 53 | configJSON = |
| 54 | pkgs.runCommand "valley-config.json" |
| 55 | { |
| 56 | nativeBuildInputs = [ pkgs.cue ]; |
| 57 | } |
| 58 | '' |
| 59 | cue vet -c ${schema} ${cfg.config} |
| 60 | cue export ${schema} ${cfg.config} > $out |
| 61 | ''; |
| 62 | |
| 63 | host = lib.importJSON configJSON; |
| 64 | |
| 65 | # Projects whose git store is enabled get a bare repository. |
| 66 | gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects; |
| 67 | repoNames = lib.attrNames gitProjects; |
| 68 | |
| 69 | # Where valley-init publishes repoNames in the instance repository. |
| 70 | projectsRef = "refs/the-valley/projects"; |
| 71 | |
| 72 | # The declared durability policy, if any. `backup` is optional in the |
| 73 | # schema: a declaration without it (or with enable = false) renders zero |
| 74 | # backup machinery, exactly as before the field existed. |
| 75 | backupPolicy = host.backup or null; |
| 76 | backupEnabled = backupPolicy != null && backupPolicy.enable; |
| 77 | |
| 78 | # The declared cadence names policy; its wall-clock rendering is this |
| 79 | # installer's choice. A lookup rather than a literal, so a cadence this |
| 80 | # module does not know fails eval loudly instead of mis-scheduling. |
| 81 | backupTimer = { |
| 82 | # Late night with a spread; Persistent runs a missed window at boot. |
| 83 | nightly = { |
| 84 | OnCalendar = "03:30"; |
| 85 | RandomizedDelaySec = "30m"; |
| 86 | Persistent = true; |
| 87 | }; |
| 88 | }; |
| 89 | |
| 90 | # The projects the integrator serves: exactly the ones the declaration |
| 91 | # protects. A protected ref is one only a declared writer may push, and |
| 92 | # the integrator is what lands everyone else's changes onto it. |
| 93 | integratedProjects = lib.filterAttrs (_: p: p ? protection) gitProjects; |
| 94 | |
| 95 | # The programs this flake builds (nix/packages.nix), the defaults of |
| 96 | # services.valley.packages. |
| 97 | flakePackages = import ./packages.nix { inherit pkgs lib; }; |
| 98 | |
| 99 | # The integrator this flake builds, in its shipping form: attest, the |
| 100 | # deriver, cue, git and natscli pinned inside the wrapper, so every host |
| 101 | # judges with the same tools (nix/packages.nix). |
| 102 | integratorPackage = cfg.packages.integrator; |
| 103 | |
| 104 | # The whole of a controller's configuration: which repository it serves, |
| 105 | # who it signs as, and whose evidence it accepts. No policy — the |
| 106 | # integrator reads the project layer from the target tip and the instance |
| 107 | # layer from its own side (bd-eaefe82) — and no project name, which the |
| 108 | # binary derives from the bare repo's own directory, the same way the |
| 109 | # post-receive hook does. |
| 110 | integratorCommand = lib.concatStringsSep " " ( |
| 111 | [ |
| 112 | "${integratorPackage}/bin/integrator watch" |
| 113 | "--repo ${cfg.dataDir}/%i.git" |
| 114 | "--key ${toString cfg.integrator.signingKeyFile}" |
| 115 | "--known-signers ${knownSigners}" |
| 116 | "--interval ${cfg.integrator.interval}" |
| 117 | ] |
| 118 | ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}" |
| 119 | ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}" |
| 120 | ++ ( |
| 121 | if cfg.integrator.instanceProject != null then |
| 122 | [ "--instance-repo ${instanceRepo}" ] |
| 123 | else |
| 124 | [ "--instance ${toString cfg.integrator.instancePolicy}" ] |
| 125 | ) |
| 126 | ++ lib.optional cfg.bus.enable "--bus ${busUrl}" |
| 127 | ++ [ "--publish-queue ${cfg.dataDir}/%i.git/${publishQueueName}" ] |
| 128 | # The worker's wake directory, for the projects whose landings it reads: |
| 129 | # the unit's environment file for the instance names it (integratorEnv |
| 130 | # below), and empty, which marks nothing, for every other project. |
| 131 | ++ lib.optional cfg.worker.enable "--wake=\${VALLEY_WAKE}" |
| 132 | # The controller's own wake directory, which it watches and consumes. |
| 133 | # --wake above is output, to the worker; this is the controller's input. |
| 134 | ++ [ "--woken-by ${integratorWakeRoot}/%i" ] |
| 135 | # The floor's readers, for the instance project's controller alone: its |
| 136 | # environment file names one --wake-floor-reader per other controller, |
| 137 | # and $VALLEY_FLOOR_READERS, unbraced, is split into those words. Every |
| 138 | # other controller's file names none, and the variable is no word at all. |
| 139 | ++ lib.optional (floorReaders != [ ]) "$VALLEY_FLOOR_READERS" |
| 140 | ); |
| 141 | |
| 142 | # The controllers' wake directories (integrator/wake.go), one per |
| 143 | # controller under integratorWakeRoot. A writer that moves a ref the |
| 144 | # controller reads creates the empty file due in it, and the controller |
| 145 | # starts a pass. The host makes each one, owned by the integrator's user |
| 146 | # and the writers' group: the git user, whose post-receive hook marks a |
| 147 | # push, and the integrator's user, whose instance controller marks a |
| 148 | # floor landing. Mode 0770 and no sticky bit, so the controller can |
| 149 | # remove a due whichever writer made it. They sit in /run, outside the |
| 150 | # integrator's 0700 state directory and outside the repositories: a boot |
| 151 | # loses them, and a controller's first pass reads every ref anyway. |
| 152 | integratorWakeRoot = "/run/valley-integrator-wake"; |
| 153 | integratorWakeGroup = "valley-integrator-wake"; |
| 154 | integratorWakeDir = name: "${integratorWakeRoot}/${name}"; |
| 155 | |
| 156 | # The ref the floor is read from: the integrator's default --instance-ref, |
| 157 | # which the host does not change. |
| 158 | floorRef = "refs/heads/main"; |
| 159 | |
| 160 | # The controllers that read the floor the instance project's controller |
| 161 | # lands: every other one. Empty when the host serves no instance |
| 162 | # repository, since then no landing here moves the floor. |
| 163 | floorReaders = |
| 164 | if instanceRepo == null then |
| 165 | [ ] |
| 166 | else |
| 167 | lib.filter (name: name != cfg.integrator.instanceProject) (lib.attrNames integratedProjects); |
| 168 | |
| 169 | # The one filesystem grant the integrator's user gets. It writes refs, |
| 170 | # objects, and the worktree metadata `git worktree add` keeps inside the |
| 171 | # repository, so read access is not enough: the repos it serves become |
| 172 | # group-shared, and its primary group is the git group. Re-applied on |
| 173 | # every activation, because a repo can predate the service. |
| 174 | # git creates $GIT_DIR/worktrees on the first `worktree add`, owned by |
| 175 | # whichever user got there first. Left alone that user is the integrator, |
| 176 | # and this sweep runs as the git user, which cannot chmod a directory it |
| 177 | # does not own. So init makes that directory itself, ahead of any |
| 178 | # controller: owned by the git user, group-writable, and setgid, so what a |
| 179 | # controller creates inside it lands in the git group and stays reachable. |
| 180 | integratorShareCommands = |
| 181 | '' |
| 182 | # A chmod the git user is not allowed to make is a path some other |
| 183 | # user owns; chmod -R applies what it can and then says so. Warn and |
| 184 | # carry on, and the trade is worth stating. Failing here fails |
| 185 | # valley-init, which every valley unit requires, so the alternative to |
| 186 | # a partly shared repository is no git service on the host at all: no |
| 187 | # controllers, and no ssh access to any project. A degraded share |
| 188 | # costs the integrator the paths it cannot write, is visible in the |
| 189 | # journal, and is fixed by one chown. That is the recoverable half of |
| 190 | # the trade, and it is the half to take. The warning is what keeps the |
| 191 | # degraded state from being a silent one. |
| 192 | share() { |
| 193 | "$@" || echo "valley-init: $* failed — a path the git user does not own is left as it was, and the integrator may be unable to write it" >&2 |
| 194 | } |
| 195 | '' |
| 196 | + lib.concatMapStrings (name: '' |
| 197 | repo=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"} |
| 198 | git -C "$repo" config core.sharedRepository group |
| 199 | # Before the sweep below, so the sweep never meets a root it cannot |
| 200 | # touch. On a host where a controller already made it, this is the |
| 201 | # chmod that warns, and the repository is served either way. |
| 202 | mkdir -p "$repo/worktrees" |
| 203 | share chmod g+rwxs "$repo/worktrees" |
| 204 | # The publish queue is the git user's for the same reason: the |
| 205 | # integrator writes into it and the publish unit deletes from it. |
| 206 | mkdir -p "$repo/${publishQueueName}" |
| 207 | share chmod g+rwxs "$repo/${publishQueueName}" |
| 208 | share chmod -R g+rwX "$repo" |
| 209 | share find "$repo" -type d -exec chmod g+s {} + |
| 210 | '') (lib.attrNames integratedProjects); |
| 211 | |
| 212 | # The integrator's own directory. Four unit settings have to agree about |
| 213 | # it — its state directory, its working directory, the scratch root TMPDIR |
| 214 | # names, and the read-write path that makes all three usable — so they name |
| 215 | # it once here. |
| 216 | # The bare repository the group's floor is read from: the instance |
| 217 | # project's, served by this host. Null when the host serves no instance |
| 218 | # repository and the layer is supplied as a directory instead. |
| 219 | instanceRepo = |
| 220 | if cfg.integrator.instanceProject != null then |
| 221 | "${cfg.dataDir}/${cfg.integrator.instanceProject}.git" |
| 222 | else |
| 223 | null; |
| 224 | |
| 225 | integratorStateName = "valley-integrator"; |
| 226 | integratorStateDir = "/var/lib/${integratorStateName}"; |
| 227 | |
| 228 | # The identity registry compiler this flake builds. It renders the |
| 229 | # registry at the instance repository's integrated tip into what the gates |
| 230 | # check (dcr-b87f6e8): the known-signers file the integrator and any |
| 231 | # reader of an attestation use, and a tagged authorized_keys for the git |
| 232 | # user. |
| 233 | identityPackage = cfg.packages.identity; |
| 234 | |
| 235 | identityStateName = "valley-identity"; |
| 236 | identityStateDir = "/var/lib/${identityStateName}"; |
| 237 | identityKnownSigners = "${identityStateDir}/known-signers"; |
| 238 | |
| 239 | # The grants the pre-receive hook checks, as the registry names them. |
| 240 | identityGrants = "${identityStateDir}/grants"; |
| 241 | |
| 242 | # The compiled authorized keys. sshd reads them for the git user alone: |
| 243 | # the git user's Match block below names the files its keys come from. |
| 244 | identityAuthorizedKeys = "${identityStateDir}/authorized_keys.${cfg.user}"; |
| 245 | |
| 246 | identityCommand = lib.concatStringsSep " " [ |
| 247 | "${identityPackage}/bin/identity compile" |
| 248 | "--repo ${toString instanceRepo}" |
| 249 | "--ref ${cfg.identity.ref}" |
| 250 | "--dir ${cfg.identity.directory}" |
| 251 | "--known-signers ${identityKnownSigners}" |
| 252 | "--authorized-keys ${identityAuthorizedKeys}" |
| 253 | "--grants ${identityGrants}" |
| 254 | "--declared-keys ${declaredKeysFile}" |
| 255 | ]; |
| 256 | |
| 257 | # Whose evidence a controller accepts: the compiled artifact once the |
| 258 | # registry machinery is on, and the file the consumer supplied otherwise. |
| 259 | knownSigners = |
| 260 | if cfg.identity.enable then identityKnownSigners else toString cfg.integrator.knownSignersFile; |
| 261 | |
| 262 | # Which signers count in which projects, as the integrator reads it: one |
| 263 | # line per restricted signer, its name and then its projects. Null when |
| 264 | # the consumer restricts nobody, so a host that sets nothing passes no |
| 265 | # file to anything. The file is in the store, so a changed list is a |
| 266 | # changed command line for the controllers and the publisher alike, and |
| 267 | # an activation restarts the one and runs the other again. |
| 268 | signerProjects = |
| 269 | if cfg.integrator.signerProjects == { } then |
| 270 | null |
| 271 | else |
| 272 | pkgs.writeText "valley-signer-projects" ( |
| 273 | lib.concatStrings ( |
| 274 | lib.mapAttrsToList ( |
| 275 | name: projects: lib.concatStringsSep " " ([ name ] ++ projects) + "\n" |
| 276 | ) cfg.integrator.signerProjects |
| 277 | ) |
| 278 | ); |
| 279 | |
| 280 | # What a client verifies this host's transfer statements with, published |
| 281 | # in the instance repository: the known-signers file the controllers read, |
| 282 | # whichever wrote it, and the name they sign under. Unset, the name is the |
| 283 | # integrator's own default, and the publisher computes it with the same |
| 284 | # code on the same host, so what is published is what the controllers use. |
| 285 | # A host publishes it while the integrator runs and the host serves the |
| 286 | # instance repository; any other host publishes nothing. |
| 287 | publishesSigners = cfg.integrator.enable && instanceRepo != null; |
| 288 | signersCommand = lib.concatStringsSep " " ( |
| 289 | [ |
| 290 | "${integratorPackage}/bin/integrator publish-signers" |
| 291 | "--instance-repo ${toString instanceRepo}" |
| 292 | "--known-signers ${knownSigners}" |
| 293 | ] |
| 294 | ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}" |
| 295 | ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}" |
| 296 | ++ lib.optional cfg.worker.enable "--wake ${workerWakeDir}" |
| 297 | ); |
| 298 | |
| 299 | # The check worker (status/worker.go), as this flake packages it, and the |
| 300 | # attest it signs with. |
| 301 | workerPackage = (import ./packages.nix { inherit pkgs lib; }).valley-worker; |
| 302 | attestPackage = (import ./packages.nix { inherit pkgs lib; }).attest; |
| 303 | |
| 304 | workerDir = toString cfg.worker.stateDir; |
| 305 | |
| 306 | # The worker's one key. It signs the worker's notes, and it is the ssh |
| 307 | # key the worker reaches this host's repositories with. It is made on |
| 308 | # the host the first time the service starts, and the service never |
| 309 | # copies or prints it. Anything running as the worker can read it. |
| 310 | workerKey = "${workerDir}/key"; |
| 311 | |
| 312 | # The worker's wake directory (status/wake.go): a writer that moves a |
| 313 | # ref the worker reads creates the empty file due in it, and the path |
| 314 | # unit starts a pass while due is there. The host makes it, owned by the |
| 315 | # worker, outside the worker's own directory, which is the worker's |
| 316 | # alone. Its group is the writers': the git user, whose post-receive |
| 317 | # hook and signer publisher write, and the integrator's user, which |
| 318 | # writes after a landing. Mode 0770 and no sticky bit, so the worker can |
| 319 | # rename a due whichever writer made it. Nothing in it is read as data. |
| 320 | workerWakeDir = toString cfg.worker.wakeDir; |
| 321 | workerWakeGroup = "valley-worker-wake"; |
| 322 | |
| 323 | # The integrator's environment, one file per controller. VALLEY_WAKE names |
| 324 | # the worker's wake directory to --wake for each project in wakeProjects, |
| 325 | # and is empty, which marks nothing, for every other. |
| 326 | # VALLEY_FLOOR_READERS names the floor's readers to the instance project's |
| 327 | # controller, and nothing to any other. |
| 328 | integratorEnv = pkgs.runCommand "valley-integrator-env" { } ( |
| 329 | "mkdir $out\n" |
| 330 | + lib.concatMapStrings ( |
| 331 | name: |
| 332 | let |
| 333 | lines = |
| 334 | lib.optional (cfg.worker.enable && lib.elem name wakeProjects) "VALLEY_WAKE=${workerWakeDir}" |
| 335 | ++ lib.optional (name == cfg.integrator.instanceProject && floorReaders != [ ]) ( |
| 336 | "VALLEY_FLOOR_READERS=" |
| 337 | + lib.concatMapStringsSep " " (r: "--wake-floor-reader=${integratorWakeDir r}") floorReaders |
| 338 | ); |
| 339 | in |
| 340 | "printf '%s\\n' ${lib.escapeShellArgs lines} > $out/${lib.escapeShellArg name}\n" |
| 341 | ) (lib.attrNames integratedProjects) |
| 342 | ); |
| 343 | |
| 344 | # The projects whose moves can change what the worker builds: its own, |
| 345 | # and the instance project its floor is read from, whether or not the |
| 346 | # worker builds the instance project too. |
| 347 | |
| 348 | wakeProjects = lib.unique ( |
| 349 | cfg.worker.projects ++ lib.optional (cfg.integrator.instanceProject != null) cfg.integrator.instanceProject |
| 350 | ); |
| 351 | |
| 352 | # The worker reads and pushes as an ssh client of this host, as the git |
| 353 | # user, so its pushes pass the pre-receive hook like anyone else's. It |
| 354 | # holds no grant on the repositories' files. The repository it runs in |
| 355 | # names the instance repository as origin, and the projects are found |
| 356 | # through it, the way valley pending --repo finds them. |
| 357 | workerOrigin = "${cfg.user}@localhost:${toString cfg.integrator.instanceProject}.git"; |
| 358 | |
| 359 | # Every host the worker connects to is checked against this host's own |
| 360 | # keys, under one alias. A project's policy/valley may name this host by |
| 361 | # another name, such as git@valley-host:valley.git, and that still |
| 362 | # reaches this host's sshd. A name that reaches any other host fails the |
| 363 | # check, so the worker talks to no other host. |
| 364 | workerSsh = lib.concatStringsSep " " [ |
| 365 | "${config.programs.ssh.package}/bin/ssh -F none" |
| 366 | "-i ${workerKey}" |
| 367 | "-p ${toString (lib.head config.services.openssh.ports)}" |
| 368 | "-o IdentitiesOnly=yes -o BatchMode=yes" |
| 369 | "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost" |
| 370 | "-o UserKnownHostsFile=${workerDir}/known_hosts -o GlobalKnownHostsFile=/dev/null" |
| 371 | ]; |
| 372 | |
| 373 | # The nix settings the worker's nix commands run with. The daemon applies |
| 374 | # max-jobs and cores to every connection, a client's that is not trusted |
| 375 | # included: each nix build the worker starts builds up to worker.maxJobs |
| 376 | # derivations at once, and tells each builder it may use worker.cores |
| 377 | # cores. cores is a hint the builder reads as NIX_BUILD_CORES; the build |
| 378 | # slice is what holds a build to its CPUs. The worker uses no remote |
| 379 | # builder, and no flake's nixConfig. |
| 380 | workerNixConfig = '' |
| 381 | extra-experimental-features = nix-command flakes |
| 382 | max-jobs = ${toString cfg.worker.maxJobs} |
| 383 | cores = ${toString cfg.worker.cores} |
| 384 | builders = |
| 385 | accept-flake-config = false |
| 386 | ''; |
| 387 | |
| 388 | # The build slice (services.valley.buildSlice): the one slice every |
| 389 | # build of this machine's nix daemon runs in, under the host's caps. |
| 390 | buildSlice = "valley-builds.slice"; |
| 391 | |
| 392 | # What each of the worker's capacity options says about the slice. |
| 393 | workerCapacityBound = '' |
| 394 | The build slice's {option}`services.valley.buildSlice.cpuQuota` and |
| 395 | {option}`services.valley.buildSlice.memoryMax` set aggregate CPU-time |
| 396 | and memory limits for the worker, its child processes, and the nix |
| 397 | daemon with its local builds for all users. Concurrent builds share |
| 398 | these limits, and the worker has no reserved share. Builds outside the |
| 399 | slice are not covered. |
| 400 | |
| 401 | If memory cannot be reclaimed below `memoryMax`, the kernel kills a |
| 402 | process in the slice. That may be an unrelated build, a daemon |
| 403 | process, or the worker. If `attest` returns a failure and the worker |
| 404 | survives to save it, later passes back off that batch. Killing the |
| 405 | worker before it records the failure does not establish that backoff. |
| 406 | ''; |
| 407 | |
| 408 | # What the service does each time it starts: make the key if there is |
| 409 | # none, write its public halves and this host's ssh keys, make the |
| 410 | # repository it runs in, and run one pass. |
| 411 | workerScript = '' |
| 412 | set -eu |
| 413 | state=${lib.escapeShellArg workerDir} |
| 414 | key="$state/key" |
| 415 | |
| 416 | # The key is made once, under a temporary name and renamed into place, |
| 417 | # so a start that is killed half way leaves no key, and the next start |
| 418 | # makes one. The public half is renamed first, so a key is never |
| 419 | # without it. The private half is never printed. |
| 420 | if [ ! -e "$key" ]; then |
| 421 | rm -f "$key.new" "$key.new.pub" |
| 422 | ssh-keygen -q -t ed25519 -N "" -C "valley-worker@${config.networking.hostName}" -f "$key.new" |
| 423 | chmod 0400 "$key.new" |
| 424 | mv -f "$key.new.pub" "$key.pub" |
| 425 | mv -f "$key.new" "$key" |
| 426 | fi |
| 427 | |
| 428 | # The verifier line the known-signers file holds for the key, under |
| 429 | # the worker's signing name. A changed name is a changed line, so it is |
| 430 | # written again on every start, and said whenever it changes. |
| 431 | attest key --key "$key" --name ${lib.escapeShellArg cfg.worker.signerName} > "$state/verifier.new" |
| 432 | if cmp -s "$state/verifier.new" "$state/verifier"; then |
| 433 | rm -f "$state/verifier.new" |
| 434 | else |
| 435 | mv -f "$state/verifier.new" "$state/verifier" |
| 436 | echo "valley-worker: the worker's ssh public key is $(cat "$state/key.pub")" |
| 437 | echo "valley-worker: the worker's verifier line is $(cat "$state/verifier")" |
| 438 | fi |
| 439 | |
| 440 | # This host's own ssh keys, the only ones the worker's ssh accepts. |
| 441 | : > "$state/known_hosts.new" |
| 442 | for pub in ${lib.escapeShellArgs (map (k: "${k.path}.pub") config.services.openssh.hostKeys)}; do |
| 443 | if [ -r "$pub" ]; then |
| 444 | printf 'localhost %s\n' "$(cut -d' ' -f1,2 "$pub")" >> "$state/known_hosts.new" |
| 445 | fi |
| 446 | done |
| 447 | mv -f "$state/known_hosts.new" "$state/known_hosts" |
| 448 | |
| 449 | # The repository the pass runs in. It holds no checkout, and origin is |
| 450 | # the instance repository. |
| 451 | origin="$state/origin" |
| 452 | git init --quiet "$origin" |
| 453 | if [ "$(git -C "$origin" remote get-url origin 2>/dev/null)" != ${lib.escapeShellArg workerOrigin} ]; then |
| 454 | git -C "$origin" remote remove origin 2>/dev/null || true |
| 455 | git -C "$origin" remote add origin ${lib.escapeShellArg workerOrigin} |
| 456 | fi |
| 457 | |
| 458 | cd "$origin" |
| 459 | exec valley-worker ${ |
| 460 | lib.concatMapStringsSep " " (p: "--repo ${lib.escapeShellArg p}") cfg.worker.projects |
| 461 | } --key "$key" --name ${lib.escapeShellArg cfg.worker.signerName} --state "$state" --wake ${lib.escapeShellArg workerWakeDir} --slots ${toString cfg.worker.buildSlots} --batches ${toString cfg.worker.batches} --interval ${lib.escapeShellArg cfg.worker.interval} ${ |
| 462 | if cfg.worker.evalMemoryBudget != null then |
| 463 | "--eval-budget ${cfg.worker.evalMemoryBudget}" |
| 464 | else |
| 465 | "--eval-share ${builtins.toJSON cfg.worker.evalMemoryShare}" |
| 466 | }${ |
| 467 | lib.optionalString ( |
| 468 | cfg.worker.keepOutputs != null |
| 469 | ) " --keep-outputs ${toString (cfg.worker.keepOutputs * 24)}h" |
| 470 | } |
| 471 | ''; |
| 472 | |
| 473 | # The name the controllers sign under, which the worker's must not be. |
| 474 | integratorName = |
| 475 | if cfg.integrator.signingName != null then |
| 476 | cfg.integrator.signingName |
| 477 | else |
| 478 | "${config.networking.hostName}/attestations"; |
| 479 | |
| 480 | # The restacker (restack/): one controller for each project listed, |
| 481 | # under its own Unix user. Its state for a project is a directory of its |
| 482 | # own, and it reaches the repositories as an ssh client of this host, |
| 483 | # as its own principal, so every push it makes passes the pre-receive |
| 484 | # hook like anyone else's. It is in no group that can read or write them |
| 485 | # on disk. |
| 486 | restackerPackage = cfg.packages.restacker; |
| 487 | restackerStateName = "valley-restacker"; |
| 488 | restackerState = "%S/${restackerStateName}/%i"; |
| 489 | |
| 490 | # It authenticates with the key the operator provisions, which systemd |
| 491 | # hands it as a credential, and accepts only this host's own ssh keys, |
| 492 | # under one alias, as the worker does. |
| 493 | restackerSsh = lib.concatStringsSep " " [ |
| 494 | "${config.programs.ssh.package}/bin/ssh -F none" |
| 495 | "-i %d/key" |
| 496 | "-p ${toString (lib.head config.services.openssh.ports)}" |
| 497 | "-o IdentitiesOnly=yes -o BatchMode=yes" |
| 498 | "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost" |
| 499 | "-o UserKnownHostsFile=${restackerState}/known_hosts -o GlobalKnownHostsFile=/dev/null" |
| 500 | ]; |
| 501 | |
| 502 | # This host's own ssh keys, written into the state directory before each |
| 503 | # start: the only keys the restacker's ssh accepts. |
| 504 | restackerKnownHosts = pkgs.writeShellScript "valley-restacker-known-hosts" '' |
| 505 | set -eu |
| 506 | : > "$1/known_hosts.new" |
| 507 | for pub in ${lib.escapeShellArgs (map (k: "${k.path}.pub") config.services.openssh.hostKeys)}; do |
| 508 | if [ -r "$pub" ]; then |
| 509 | printf 'localhost %s\n' "$(cut -d' ' -f1,2 "$pub")" >> "$1/known_hosts.new" |
| 510 | fi |
| 511 | done |
| 512 | mv -f "$1/known_hosts.new" "$1/known_hosts" |
| 513 | ''; |
| 514 | |
| 515 | # A pass reads landings with the verifier keys and the name the |
| 516 | # controllers read and sign under, and the floor from where the |
| 517 | # controllers read it: the instance repository, over ssh as itself, or |
| 518 | # the materialized directory. |
| 519 | restackerCommand = lib.concatStringsSep " " ( |
| 520 | [ |
| 521 | "${restackerPackage}/bin/valley-restacker run" |
| 522 | "--repo ${cfg.user}@localhost:%i.git" |
| 523 | "--state ${restackerState}" |
| 524 | "--principal ${cfg.restacker.principal}" |
| 525 | "--interval ${cfg.restacker.interval}" |
| 526 | "--integrator-name ${integratorName}" |
| 527 | ] |
| 528 | ++ lib.optional (knownSigners != "") "--known-signers ${knownSigners}" |
| 529 | ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}" |
| 530 | ++ ( |
| 531 | if cfg.integrator.instanceProject != null then |
| 532 | [ "--instance-repo ${cfg.user}@localhost:${cfg.integrator.instanceProject}.git" ] |
| 533 | else |
| 534 | [ "--instance ${toString cfg.integrator.instancePolicy}" ] |
| 535 | ) |
| 536 | ); |
| 537 | |
| 538 | # The paths the consumer must supply once the integrator is enabled, |
| 539 | # with what each names — for the assertion message. The signers file is |
| 540 | # among them only while the registry does not compile one. |
| 541 | integratorPathOptions = { |
| 542 | signingKeyFile = "the key its transfer statements are signed with"; |
| 543 | } |
| 544 | // lib.optionalAttrs (!cfg.identity.enable) { |
| 545 | knownSignersFile = "the signers whose evidence it accepts"; |
| 546 | }; |
| 547 | |
| 548 | # The secret-path options the consumer must supply once the declaration |
| 549 | # enables backup, with what each names — for the assertion message. |
| 550 | backupSecretOptions = { |
| 551 | repositoryFile = "the restic repository URL"; |
| 552 | passwordFile = "the repository encryption password"; |
| 553 | sshKeyFile = "the SSH identity for the sftp target"; |
| 554 | knownHostsFile = "the pinned host key of the sftp target"; |
| 555 | }; |
| 556 | |
| 557 | # Managed post-receive dispatcher. Each repo's post-receive is a symlink to |
| 558 | # this script, which chains every executable dropped into the repo's |
| 559 | # hooks/post-receive.d/ directory. |
| 560 | postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" '' |
| 561 | # Managed by services.valley — do not edit. |
| 562 | # Drop executable hooks into post-receive.d/ next to this symlink. |
| 563 | set -eu |
| 564 | hook_dir="$(dirname "$0")/post-receive.d" |
| 565 | [ -d "$hook_dir" ] || exit 0 |
| 566 | updates="$(cat)" |
| 567 | [ -n "$updates" ] || exit 0 |
| 568 | for hook in "$hook_dir"/*; do |
| 569 | [ -x "$hook" ] || continue |
| 570 | printf '%s\n' "$updates" | "$hook" "$@" |
| 571 | done |
| 572 | ''; |
| 573 | |
| 574 | # Push replication. A publication mirror gets main and the tags, and |
| 575 | # nothing else. Only the publish drain further down runs it, for pushes |
| 576 | # and integrator landings alike. |
| 577 | # Topic branches are review-queue state, not published: the mirror exists |
| 578 | # so consumers can fetch what has been integrated, and durability is |
| 579 | # restic's job, not the mirror's. The two refspecs are what keep every |
| 580 | # other ref of the project off the mirror. |
| 581 | # --prune propagates tag deletions through the tags glob. The heads |
| 582 | # refspec names one ref, so --prune deletes no head. |
| 583 | # The pusher deletes nothing else on a mirror. Deleting a ref that a |
| 584 | # public mirror has served unpublishes nothing, because forges keep its |
| 585 | # objects fetchable by SHA. And a mirror holds refs that other writers put |
| 586 | # there, such as a forge's own namespaces or a bot's branches; those are |
| 587 | # theirs. --mirror is refused for the same reason: it deletes every mirror |
| 588 | # ref the primary lacks, and on GitHub the read-only refs/pull/* makes |
| 589 | # that fail every push, masking real replication failures. |
| 590 | # The pusher exits non-zero when a replication push fails, and the drain |
| 591 | # retries on that. |
| 592 | mirrorPusher = |
| 593 | name: mirrors: |
| 594 | pkgs.writeShellScript "valley-mirror-push-${name}" '' |
| 595 | status=0 |
| 596 | for url in ${lib.escapeShellArgs mirrors}; do |
| 597 | if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then |
| 598 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true |
| 599 | else |
| 600 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true |
| 601 | status=1 |
| 602 | fi |
| 603 | done |
| 604 | exit "$status" |
| 605 | ''; |
| 606 | |
| 607 | # The post-receive.d hook of a project with mirrors. It does not push. It |
| 608 | # queues the push's ref moves for the publish drain, as the integrator |
| 609 | # queues a landing, and returns. So a dead mirror can only ever cost a log |
| 610 | # line and a retry, never block or fail the primary push. The file is |
| 611 | # written beside the queue and renamed into it, so the drain never reads a |
| 612 | # partial one. A push whose moves cannot be queued is logged, and stands. |
| 613 | mirrorHook = |
| 614 | name: |
| 615 | pkgs.writeShellScript "valley-mirrors-${name}" '' |
| 616 | # Managed by services.valley — queue this push for ${name}'s mirrors. |
| 617 | bin=${pkgs.coreutils}/bin |
| 618 | tmp="$($bin/mktemp .valley-publish-XXXXXXXX)" && |
| 619 | $bin/cat >"$tmp" && |
| 620 | $bin/mv -- "$tmp" "${publishQueueName}/$($bin/date +%s%N)-push-$$" || { |
| 621 | $bin/rm -f -- "$tmp" |
| 622 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: queueing a push FAILED" || true |
| 623 | } |
| 624 | exit 0 |
| 625 | ''; |
| 626 | |
| 627 | # The event bus (archive/design/roadmap.md, Phase 1): NATS JetStream, onto which |
| 628 | # the ref-updated hook below projects this host's git activity. The bus is |
| 629 | # never load-bearing for durable state — per-repo events are durable in |
| 630 | # git itself, and `valley replay` rebuilds the stream from a repo's refs — |
| 631 | # so losing its storage costs one replay, nothing more. |
| 632 | busUrl = "nats://${cfg.bus.listen}"; |
| 633 | |
| 634 | busServerConfig = pkgs.writeText "valley-bus.conf" '' |
| 635 | listen: ${cfg.bus.listen} |
| 636 | jetstream { |
| 637 | store_dir: "${cfg.bus.storeDir}" |
| 638 | # The store directory defaults to living on the repo volume; the cap |
| 639 | # keeps a runaway or malicious local publisher from filling it. |
| 640 | max_file_store: 2GiB |
| 641 | } |
| 642 | ''; |
| 643 | |
| 644 | # One ref-updated event per updated ref, read from the post-receive stdin |
| 645 | # this script inherits. Every payload field is derivable from git alone — |
| 646 | # no wall-clock time, no hostname — so replaying a repo's refs reproduces |
| 647 | # the same events (the roadmap's determinism criterion). `valley replay` |
| 648 | # builds the identical payload; change one only with the other. |
| 649 | busPublisher = pkgs.writeShellScript "valley-bus-publish" '' |
| 650 | repo="$(basename "$PWD" .git)" |
| 651 | while read -r old new ref; do |
| 652 | [ -n "$ref" ] || continue |
| 653 | # " is the only JSON-significant character a refname can contain |
| 654 | # (git forbids \ and control characters); names and ids are safe. |
| 655 | event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \ |
| 656 | "$repo" "''${ref//\"/\\\"}" "$old" "$new")" |
| 657 | if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \ |
| 658 | "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then |
| 659 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true |
| 660 | else |
| 661 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true |
| 662 | fi |
| 663 | done |
| 664 | ''; |
| 665 | |
| 666 | # How a move reaches the mirrors: the publish queue. |
| 667 | # |
| 668 | # One thing pushes a project's mirrors: the publish drain, a oneshot unit |
| 669 | # per project that runs as the git user. Whatever moves a ref writes the |
| 670 | # move into a queue directory in the repository, as the line post-receive |
| 671 | # reads: old, new, ref. A path unit watches the queue, and when it holds |
| 672 | # anything, starts the drain. A push queues its moves from post-receive, |
| 673 | # through the mirror hook above. The integrator moves refs with |
| 674 | # update-ref, which runs no post-receive hook, so it queues each landing |
| 675 | # itself (integrator/bus.go). It runs as its own user, which does not hold |
| 676 | # the git user's mirror credentials and must not. |
| 677 | # |
| 678 | # A single publisher is what keeps a mirror from being rewound. git reads |
| 679 | # the local refs before it contacts the mirror, so two pushers running at |
| 680 | # once can rewind it: one reads an old main and stalls, the other pushes a |
| 681 | # newer main, and the first then force-pushes its old main over it. |
| 682 | # systemd never runs two instances of one unit at the same time, so the |
| 683 | # drain's pushes for a project never overlap, and nothing else pushes. |
| 684 | # The drain lists the queue before git reads any ref, and deletes only what |
| 685 | # it listed, after the push succeeds. A move is queued after its ref moved, |
| 686 | # so the push covers every listed move. A move queued during the push stays |
| 687 | # for the next run, which pushes the newer main. No lock is taken: the |
| 688 | # drain runs only as the unit. To publish by hand, start the unit |
| 689 | # (systemctl start valley-publish@<project>), never the script. |
| 690 | # |
| 691 | # A run that fails leaves the queue as it was, and systemd runs it again |
| 692 | # after a delay (the unit, further down). So a failed mirror push does not |
| 693 | # wait for another move to be retried. Repeating a push is harmless: it |
| 694 | # pushes the current main, whatever the queue records. |
| 695 | # |
| 696 | # The bus is not the drain's business. A push publishes its ref-updated |
| 697 | # events from post-receive, through the bus hook below. The integrator |
| 698 | # publishes its landing's ref-updated event itself. So a mirror outage, and |
| 699 | # the drain's retries, never delay an event. |
| 700 | # |
| 701 | # The alternatives fall to the user split. Calling the post-receive |
| 702 | # dispatcher from the integrator would push as the integrator's user, and |
| 703 | # so would a reference-transaction hook, which runs as whoever ran git; it |
| 704 | # would also fire inside every push and for every bookkeeping ref the |
| 705 | # integrator writes. Starting a unit directly would take a polkit grant |
| 706 | # and carry no record of what moved. The queue costs one directory, the |
| 707 | # path unit is woken by inotify rather than a poll, and the queue is |
| 708 | # durable, so a move queued while the host goes down is published after. |
| 709 | publishQueueName = "valley-publish-queue"; |
| 710 | |
| 711 | # The projects with a publish queue and a drain: every one with mirrors, |
| 712 | # and every one the integrator serves. The integrator queues its landings |
| 713 | # whether or not the project has mirrors. A drain with no mirrors to push |
| 714 | # only empties the queue. |
| 715 | publishedProjects = lib.filterAttrs ( |
| 716 | name: p: p.mirrors != [ ] || (cfg.integrator.enable && integratedProjects ? ${name}) |
| 717 | ) gitProjects; |
| 718 | |
| 719 | # The drain, per project. Its working directory is the repository. It runs |
| 720 | # synchronously: the unit is already detached from the push or the |
| 721 | # landing, and a detached child would be killed with the oneshot's cgroup |
| 722 | # when it exits. |
| 723 | publishDrain = |
| 724 | name: p: |
| 725 | pkgs.writeShellScript "valley-publish-${name}" '' |
| 726 | # Managed by services.valley — push the moves queued on ${name} to its mirrors. |
| 727 | shopt -s nullglob |
| 728 | # Listed before the pusher reads any ref, so the push covers them all. |
| 729 | moves=( ${publishQueueName}/* ) |
| 730 | [ "''${#moves[@]}" -gt 0 ] || exit 0 |
| 731 | ${lib.optionalString (p.mirrors != [ ]) "${mirrorPusher name p.mirrors} || exit 1"} |
| 732 | # A move that cannot be deleted fails the run, so systemd retries it |
| 733 | # after a delay. A run that succeeded would leave the queue non-empty, |
| 734 | # and the path unit would start the drain again at once, over and over. |
| 735 | rm -f -- "''${moves[@]}" || exit 1 |
| 736 | ''; |
| 737 | |
| 738 | # Every drain, by project name, so the template unit runs its instance's. |
| 739 | publishDrains = pkgs.linkFarm "valley-publish-drains" ( |
| 740 | lib.mapAttrsToList (name: p: { |
| 741 | inherit name; |
| 742 | path = publishDrain name p; |
| 743 | }) publishedProjects |
| 744 | ); |
| 745 | |
| 746 | # The queue directory of every published project. The integrator's |
| 747 | # projects also get it group-shared, with the rest of the repository. |
| 748 | publishQueueCommands = lib.concatMapStrings (name: '' |
| 749 | mkdir -p ${lib.escapeShellArg "${cfg.dataDir}/${name}.git/${publishQueueName}"} |
| 750 | '') (lib.attrNames publishedProjects); |
| 751 | |
| 752 | # The post-receive.d hook that publishes a push's ref-updated events. The |
| 753 | # publisher runs detached (setsid, inheriting the updates on stdin), so a |
| 754 | # bus problem can only ever cost a log line — never block or fail the |
| 755 | # push. git is the source of truth; the bus is the replaceable component. |
| 756 | busEventHook = pkgs.writeShellScript "valley-bus-events" '' |
| 757 | # Managed by services.valley — project ref updates onto the event bus. |
| 758 | ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1 |
| 759 | exit 0 |
| 760 | ''; |
| 761 | |
| 762 | # The post-receive.d hook that marks the check worker due. It runs in the |
| 763 | # push, after the refs moved, so it does nothing slow: it reads the moves |
| 764 | # and creates one empty file, and it never fails the push. A push of |
| 765 | # nothing but knots or integration bookkeeping marks nothing, since the |
| 766 | # worker does not read those refs. Every other ref is a mark, so a ref |
| 767 | # the worker comes to read is covered without a change here. The |
| 768 | # worker's own evidence marks it too, and the pass that follows finds |
| 769 | # the evidence and builds nothing. noclobber makes the redirection |
| 770 | # O_EXCL, and a due that is there already is a mark already made. A |
| 771 | # mark that fails is logged; the worker's timer reads the push later. |
| 772 | wakeHook = pkgs.writeShellScript "valley-wake" '' |
| 773 | # Managed by services.valley — marks the check worker due. |
| 774 | due=${lib.escapeShellArg "${workerWakeDir}/due"} |
| 775 | marks= |
| 776 | while read -r old new ref; do |
| 777 | case "$ref" in |
| 778 | refs/the-valley/knots | refs/the-valley/knots/* | \ |
| 779 | refs/the-valley/integration-outcomes/* | refs/the-valley/integration-landings/*) ;; |
| 780 | *) marks=1 ;; |
| 781 | esac |
| 782 | done |
| 783 | [ -n "$marks" ] || exit 0 |
| 784 | set -C |
| 785 | { : > "$due"; } 2>/dev/null || [ -e "$due" ] || { : > "$due"; } 2>/dev/null || [ -e "$due" ] || |
| 786 | ${pkgs.util-linux}/bin/logger -t valley-wake "could not mark the check worker due in ${workerWakeDir}" || true |
| 787 | exit 0 |
| 788 | ''; |
| 789 | |
| 790 | # The post-receive.d hook that marks a project's integrator due. Like the |
| 791 | # worker's, it runs in the push after the refs moved, reads the moves, |
| 792 | # creates at most a few empty files, and exits 0 whatever happens: the |
| 793 | # dispatcher stops at the first hook that fails, and the hooks after it |
| 794 | # must still run. A push of nothing but knots, integration bookkeeping or |
| 795 | # the signers publication marks nothing, since no controller decides |
| 796 | # from those refs; the compiled signers file is what it reads, and a |
| 797 | # change to it waits for the interval. Every other ref marks the |
| 798 | # project's own controller. In the instance project, a push that moves |
| 799 | # the floor's ref also marks every controller that reads the floor, and |
| 800 | # nothing else is marked across projects. A mark that fails is logged, |
| 801 | # and the controller's interval reads the push later. |
| 802 | integratorWakeHook = |
| 803 | name: |
| 804 | pkgs.writeShellScript "valley-integrator-wake-${name}" '' |
| 805 | # Managed by services.valley — marks the integrator for ${name} due. |
| 806 | mark() { |
| 807 | { set -C; : > "$1/due"; } 2>/dev/null || [ -e "$1/due" ] || |
| 808 | ${pkgs.util-linux}/bin/logger -t valley-integrator-wake "could not mark the integrator due in $1" || true |
| 809 | } |
| 810 | own= |
| 811 | floor= |
| 812 | while read -r old new ref; do |
| 813 | case "$ref" in |
| 814 | refs/the-valley/knots | refs/the-valley/knots/* | refs/the-valley/signers | \ |
| 815 | refs/the-valley/integration-outcomes/* | refs/the-valley/integration-inputs/* | \ |
| 816 | refs/the-valley/integration-landings/*) ;; |
| 817 | ${floorRef}) own=1 floor=1 ;; |
| 818 | *) own=1 ;; |
| 819 | esac |
| 820 | done |
| 821 | [ -z "$own" ] || mark ${lib.escapeShellArg (integratorWakeDir name)} |
| 822 | ${lib.optionalString (name == cfg.integrator.instanceProject) ( |
| 823 | lib.concatMapStrings ( |
| 824 | r: "[ -z \"$floor\" ] || mark ${lib.escapeShellArg (integratorWakeDir r)}\n" |
| 825 | ) floorReaders |
| 826 | )} |
| 827 | exit 0 |
| 828 | ''; |
| 829 | |
| 830 | # Integrator-wake-hook wiring, one symlink per repo, by the bus hook's |
| 831 | # rules: every project a controller serves gets it, and every other |
| 832 | # repository loses a store symlink of the name. |
| 833 | integratorWakeHookCommands = lib.concatMapStrings ( |
| 834 | name: |
| 835 | let |
| 836 | ihook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-integrator-wake"; |
| 837 | in |
| 838 | if cfg.integrator.enable && integratedProjects ? ${name} then |
| 839 | '' |
| 840 | ihook=${ihook} |
| 841 | if [ -L "$ihook" ]; then |
| 842 | case "$(readlink "$ihook")" in |
| 843 | /nix/store/*) ln -sfn ${integratorWakeHook name} "$ihook" ;; |
| 844 | esac |
| 845 | elif [ ! -e "$ihook" ]; then |
| 846 | ln -s ${integratorWakeHook name} "$ihook" |
| 847 | fi |
| 848 | '' |
| 849 | else |
| 850 | '' |
| 851 | ihook=${ihook} |
| 852 | if [ -L "$ihook" ]; then |
| 853 | case "$(readlink "$ihook")" in |
| 854 | /nix/store/*) rm -f "$ihook" ;; |
| 855 | esac |
| 856 | fi |
| 857 | '' |
| 858 | ) repoNames; |
| 859 | |
| 860 | # Wake-hook wiring, one symlink per repo, by the bus hook's rules: the |
| 861 | # worker's projects and the instance project get it, and every other |
| 862 | # repository loses a store symlink of the name. |
| 863 | wakeHookCommands = lib.concatMapStrings ( |
| 864 | name: |
| 865 | let |
| 866 | whook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-wake"; |
| 867 | in |
| 868 | if cfg.worker.enable && lib.elem name wakeProjects then |
| 869 | '' |
| 870 | whook=${whook} |
| 871 | if [ -L "$whook" ]; then |
| 872 | case "$(readlink "$whook")" in |
| 873 | /nix/store/*) ln -sfn ${wakeHook} "$whook" ;; |
| 874 | esac |
| 875 | elif [ ! -e "$whook" ]; then |
| 876 | ln -s ${wakeHook} "$whook" |
| 877 | fi |
| 878 | '' |
| 879 | else |
| 880 | '' |
| 881 | whook=${whook} |
| 882 | if [ -L "$whook" ]; then |
| 883 | case "$(readlink "$whook")" in |
| 884 | /nix/store/*) rm -f "$whook" ;; |
| 885 | esac |
| 886 | fi |
| 887 | '' |
| 888 | ) repoNames; |
| 889 | |
| 890 | # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks: |
| 891 | # only ever installs, updates, or removes a store symlink — a hand-written |
| 892 | # hook of the same name is left alone. |
| 893 | busHookCommands = lib.concatMapStrings ( |
| 894 | name: |
| 895 | let |
| 896 | bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus"; |
| 897 | in |
| 898 | if cfg.bus.enable then |
| 899 | '' |
| 900 | bhook=${bhook} |
| 901 | if [ -L "$bhook" ]; then |
| 902 | case "$(readlink "$bhook")" in |
| 903 | /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;; |
| 904 | esac |
| 905 | elif [ ! -e "$bhook" ]; then |
| 906 | ln -s ${busEventHook} "$bhook" |
| 907 | fi |
| 908 | '' |
| 909 | else |
| 910 | '' |
| 911 | bhook=${bhook} |
| 912 | if [ -L "$bhook" ]; then |
| 913 | case "$(readlink "$bhook")" in |
| 914 | /nix/store/*) rm -f "$bhook" ;; |
| 915 | esac |
| 916 | fi |
| 917 | '' |
| 918 | ) repoNames; |
| 919 | |
| 920 | # Per-project mirror-hook wiring. Only ever installs, updates, or removes |
| 921 | # a store symlink — a hand-written hook of the same name is left alone. |
| 922 | mirrorHookCommands = lib.concatStrings ( |
| 923 | lib.mapAttrsToList ( |
| 924 | name: p: |
| 925 | let |
| 926 | mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors"; |
| 927 | in |
| 928 | if p.mirrors != [ ] then |
| 929 | '' |
| 930 | mhook=${mhook} |
| 931 | if [ -L "$mhook" ]; then |
| 932 | case "$(readlink "$mhook")" in |
| 933 | /nix/store/*) ln -sfn ${mirrorHook name} "$mhook" ;; |
| 934 | esac |
| 935 | elif [ ! -e "$mhook" ]; then |
| 936 | ln -s ${mirrorHook name} "$mhook" |
| 937 | fi |
| 938 | '' |
| 939 | else |
| 940 | '' |
| 941 | mhook=${mhook} |
| 942 | if [ -L "$mhook" ]; then |
| 943 | case "$(readlink "$mhook")" in |
| 944 | /nix/store/*) rm -f "$mhook" ;; |
| 945 | esac |
| 946 | fi |
| 947 | '' |
| 948 | ) gitProjects |
| 949 | ); |
| 950 | |
| 951 | # The environment variable carrying the pushing key's principal name. The |
| 952 | # git user's shell sets it from the tag on the authenticated key's own |
| 953 | # authorized_keys entry, and the pre-receive hook reads it. |
| 954 | principalEnv = "VALLEY_PRINCIPAL"; |
| 955 | |
| 956 | authorizedKeyLine = |
| 957 | k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}''; |
| 958 | |
| 959 | # What valley-init does to converge the host: create missing repositories |
| 960 | # and (re)wire the managed hooks. Its last step refuses to report the host |
| 961 | # converged over anything that would run instead of the push policy. |
| 962 | valleyInitBody = '' |
| 963 | conflicts=0 |
| 964 | |
| 965 | repos=( ${lib.escapeShellArgs repoNames} ) |
| 966 | for name in "''${repos[@]}"; do |
| 967 | repo="${cfg.dataDir}/$name.git" |
| 968 | # Check HEAD rather than the directory itself so a pre-existing |
| 969 | # empty directory still gets initialized. |
| 970 | if [ ! -e "$repo/HEAD" ]; then |
| 971 | git init --bare --initial-branch=main "$repo" |
| 972 | fi |
| 973 | |
| 974 | # Replacement refs make one object stand in for another wherever |
| 975 | # git looks it up. No push may write one, and every reader that |
| 976 | # makes a decision disables them, but a ref written before the |
| 977 | # hook refused them is still there. It is reported on every |
| 978 | # activation and left in place: what it is evidence of is the |
| 979 | # operator's to read before anyone deletes it. |
| 980 | replaced="$(git -C "$repo" for-each-ref --format=' %(refname) -> %(objectname)' refs/replace/)" || replaced="" |
| 981 | if [ -n "$replaced" ]; then |
| 982 | printf 'valley-init: %s holds replacement refs, which no push may write; inspect each and delete it with git update-ref -d:\n%s\n' "$repo" "$replaced" >&2 |
| 983 | fi |
| 984 | |
| 985 | # Hook scaffolding: post-receive dispatches to post-receive.d/. |
| 986 | # Only manage the hook if it is absent or already ours (a store |
| 987 | # symlink) — a hand-written hook is left alone. |
| 988 | mkdir -p "$repo/hooks/post-receive.d" |
| 989 | hook="$repo/hooks/post-receive" |
| 990 | if [ -L "$hook" ]; then |
| 991 | case "$(readlink "$hook")" in |
| 992 | /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;; |
| 993 | esac |
| 994 | elif [ ! -e "$hook" ]; then |
| 995 | ln -s ${postReceiveDispatch} "$hook" |
| 996 | fi |
| 997 | done |
| 998 | |
| 999 | # Per-project push-mirror hooks, and the queue they write. |
| 1000 | ${mirrorHookCommands} |
| 1001 | ${publishQueueCommands} |
| 1002 | |
| 1003 | # The one structural invariant, on every project the host serves. |
| 1004 | ${protectHookCommands} |
| 1005 | |
| 1006 | # The ref-updated publisher hook, on every repo when the bus is on. |
| 1007 | ${busHookCommands} |
| 1008 | ${wakeHookCommands} |
| 1009 | ${integratorWakeHookCommands} |
| 1010 | |
| 1011 | # The project list, published in the instance repository for clients to |
| 1012 | # discover this host's projects by (valley changes --all): a blob at |
| 1013 | # ${projectsRef} naming every enabled git project, one per line, |
| 1014 | # sorted, and nothing else. A host without an instance repository |
| 1015 | # publishes nothing. The name of every project is disclosed to whoever |
| 1016 | # can read the instance repository. No push may write the ref, since |
| 1017 | # the hook refuses every refs/the-valley/* it does not name, so init is |
| 1018 | # its only writer. It is written before the share sweep below, which |
| 1019 | # then gives the new object the group's permissions. A list that cannot |
| 1020 | # be written costs discovery and not the host, so it warns. |
| 1021 | ${lib.optionalString (instanceRepo != null) '' |
| 1022 | { |
| 1023 | projects="$(printf '%s\n' ${lib.escapeShellArgs (lib.sort lib.lessThan repoNames)} | |
| 1024 | git -C ${instanceRepo} hash-object -w --stdin)" && |
| 1025 | git -C ${instanceRepo} update-ref ${projectsRef} "$projects" |
| 1026 | } || echo "valley-init: could not publish the project list at ${projectsRef} in ${instanceRepo}; clients cannot discover this host's projects until it is" >&2 |
| 1027 | ''} |
| 1028 | |
| 1029 | # Group-shared repositories, on what the integrator serves. |
| 1030 | ${lib.optionalString cfg.integrator.enable integratorShareCommands} |
| 1031 | |
| 1032 | if [ "$conflicts" -ne 0 ]; then |
| 1033 | echo "valley-init: refusing to report this host converged: the push policy is not what every repository runs" >&2 |
| 1034 | exit 1 |
| 1035 | fi |
| 1036 | ''; |
| 1037 | |
| 1038 | # The configuration a convergence is of: the init script itself, which |
| 1039 | # names every hook and every policy file it wires. valley-init records it |
| 1040 | # when it converges, and the git user's shell lets a push through only |
| 1041 | # while the record names the configuration the shell was rendered with. |
| 1042 | convergenceId = builtins.substring 0 32 (builtins.hashString "sha256" valleyInitBody); |
| 1043 | |
| 1044 | # The record, in the git user's home: valley-init writes it, and nothing |
| 1045 | # a session reaches can. A dot file never collides with a repository, |
| 1046 | # because project names begin with an alphanumeric. |
| 1047 | convergedRecord = "${cfg.dataDir}/.valley-converged"; |
| 1048 | |
| 1049 | # The operator's hold on pushes: while this file exists, the git user's |
| 1050 | # shell refuses every push, whatever valley-init has recorded. valley-init |
| 1051 | # never touches it, so a hold placed before a deploy outlasts the |
| 1052 | # convergence and lasts until the operator removes it — the window a |
| 1053 | # deploy's audits need. |
| 1054 | pushHold = "${cfg.dataDir}/.valley-hold"; |
| 1055 | |
| 1056 | # The git user's login shell (valleyhook shell). sshd runs it for every |
| 1057 | # session, and it names the key files sshd authorizes the git user's keys |
| 1058 | # from, in sshd's order, so it can find the authenticated key's tag. |
| 1059 | gitShell = pkgs.writeShellScriptBin "valley-git-shell" '' |
| 1060 | exec ${valleyhookPackage}/bin/valleyhook shell \ |
| 1061 | --converged ${convergedRecord} \ |
| 1062 | --expect ${convergenceId} \ |
| 1063 | --hold ${pushHold} \ |
| 1064 | --authorized-keys /etc/ssh/authorized_keys.d/${cfg.user} ${ |
| 1065 | lib.optionalString cfg.identity.enable "--authorized-keys ${identityAuthorizedKeys}" |
| 1066 | } \ |
| 1067 | ${cfg.telemetry.shellFlags} \ |
| 1068 | -- "$@" |
| 1069 | ''; |
| 1070 | |
| 1071 | # The program every project's pre-receive hook runs: the whole of the ref |
| 1072 | # policy (valleyhook/), built by this flake. |
| 1073 | valleyhookPackage = cfg.packages.valleyhook; |
| 1074 | |
| 1075 | # The grants declared by hand, in the format the compiler writes, so the |
| 1076 | # hook reads one format whichever wrote it. The holders of the approve |
| 1077 | # grant are one set under either option, written under the name request |
| 1078 | # the way the compiler writes them, and a principal named in both is |
| 1079 | # written once. |
| 1080 | declaredGrants = pkgs.writeText "valley-grants" ( |
| 1081 | '' |
| 1082 | # Declared in services.valley.grants — do not edit. |
| 1083 | '' |
| 1084 | + lib.concatMapStrings (principal: "request ${principal}\n") ( |
| 1085 | lib.unique (cfg.grants.approve ++ cfg.grants.request) |
| 1086 | ) |
| 1087 | + lib.concatMapStrings (principal: "restack ${principal}\n") cfg.grants.restack |
| 1088 | ); |
| 1089 | |
| 1090 | # Every file the hook reads grants from. The compiled file is added to the |
| 1091 | # declared one rather than replacing it, the same way the compiled keys |
| 1092 | # are added to the declared keys: a compilation can only ever grant more. |
| 1093 | grantFiles = [ declaredGrants ] ++ lib.optional cfg.identity.enable identityGrants; |
| 1094 | |
| 1095 | # The keys a pushed attestation's signature is checked against: the ones |
| 1096 | # a controller accepts evidence from. An attestation no controller here |
| 1097 | # would accept cannot take a name in the create-only namespace, and a host |
| 1098 | # that names no such keys accepts no attestation at all. |
| 1099 | hookVerifiers = lib.optional (knownSigners != "") knownSigners; |
| 1100 | |
| 1101 | # What a project declares about pushes, as valleyhook reads it: the |
| 1102 | # protected refs and their writers, empty for a project that declares no |
| 1103 | # protection, and the project's named grants. |
| 1104 | pushPolicy = |
| 1105 | name: p: |
| 1106 | pkgs.writeText "valley-push-policy-${name}.json" ( |
| 1107 | builtins.toJSON { |
| 1108 | refs = p.protection.refs or [ ]; |
| 1109 | writers = p.protection.writers or [ ]; |
| 1110 | grants = p.grants or { }; |
| 1111 | } |
| 1112 | ); |
| 1113 | |
| 1114 | # The pre-receive hook: the one structural git invariant |
| 1115 | # (archive/design/architecture.md, archive/design/contribute.md), which is what a push may |
| 1116 | # write. It is installed on every project the host serves. Replacement |
| 1117 | # refs, notes and the valley's own namespace take no push, but for the |
| 1118 | # four namespaces below; a symbolic ref takes none; topic branches are |
| 1119 | # open; an attestation ref may only be created, and only holding what its |
| 1120 | # name says; an integration request takes the approve grant; a change |
| 1121 | # record moves only by the transitions the hook allows; the plan graph, |
| 1122 | # refs/the-valley/knots, takes any named principal's write of one commit |
| 1123 | # on its tip that keeps the graph valid; every other ref, tags included, |
| 1124 | # takes a named grant of the project; and a protected ref also takes a |
| 1125 | # declared writer. All policy beyond this lives in the integrator. |
| 1126 | # |
| 1127 | # The rules are valleyhook's, in Go, and this script is only how git |
| 1128 | # reaches it. It hands over what the policy is a function of: the pushing |
| 1129 | # principal, the project's declared push policy, the grants, the keys an |
| 1130 | # attestation is checked against, and the hook a project composes after |
| 1131 | # it, if it declares one. |
| 1132 | # |
| 1133 | # A declaration usually names no writer at all, and then the protected |
| 1134 | # refs take no push from anyone. That is the norm, not a |
| 1135 | # misconfiguration: the integrator writes the ref locally, and a local |
| 1136 | # write is not a push. |
| 1137 | # |
| 1138 | # Pushes arrive over SSH as one shared git user, so the unix account |
| 1139 | # behind a push says nothing about who pushed. The principal comes from |
| 1140 | # the key instead: services.valley.authorizedKeys tags each key's |
| 1141 | # authorized_keys entry, the git user's shell reads the tag off the entry |
| 1142 | # of the key sshd authenticated and puts it in the environment of the |
| 1143 | # receive-pack this hook runs under, and an untagged key has no principal |
| 1144 | # at all. The client cannot supply the tag itself: the shell drops any it |
| 1145 | # arrives with, and the assertions below hold sshd to offering no client |
| 1146 | # environment that could carry it. |
| 1147 | # |
| 1148 | # This governs pushes, which is every write that crosses the host |
| 1149 | # boundary. It does not govern writes made on the host: the integrator |
| 1150 | # updates refs locally, as could anyone holding the git user's shell. |
| 1151 | # Local access is the host's own boundary, not this hook's. |
| 1152 | protectHook = |
| 1153 | name: p: |
| 1154 | pkgs.writeShellScript "valley-protect-${name}" '' |
| 1155 | # Managed by services.valley — do not edit. |
| 1156 | exec ${valleyhookPackage}/bin/valleyhook pre-receive \ |
| 1157 | --project ${lib.escapeShellArg name} \ |
| 1158 | --policy ${pushPolicy name p} \ |
| 1159 | ${lib.concatMapStringsSep " " (f: "--grants ${f}") grantFiles} \ |
| 1160 | ${lib.concatMapStringsSep " " (f: "--known-signers ${f}") hookVerifiers} \ |
| 1161 | ${lib.optionalString (cfg.extraPreReceive ? ${name}) "--then ${cfg.extraPreReceive.${name}}"} \ |
| 1162 | --principal="''${${principalEnv}:-}" |
| 1163 | ''; |
| 1164 | |
| 1165 | # Per-project pre-receive wiring, on every project the host serves. A |
| 1166 | # hook that is not this module's is a hook that would run instead of the |
| 1167 | # push policy, so valley-init refuses to leave one in place: it says so, |
| 1168 | # and the activation fails once everything else is wired. The one |
| 1169 | # exception is a hook identical to the one the project composes after the |
| 1170 | # policy (services.valley.extraPreReceive), which is checked byte for byte |
| 1171 | # and then replaced, since the managed hook runs it. A store symlink is |
| 1172 | # this module's, whichever store path it names, and is re-pointed. |
| 1173 | # |
| 1174 | # core.hooksPath moves where git looks for hooks at all, from any scope |
| 1175 | # the git user reads — the repository's config, the user's, the system's, |
| 1176 | # or a file one of them includes. A repository whose hooks path is set at |
| 1177 | # all, to an empty value included, is refused the same way, with no |
| 1178 | # exception. |
| 1179 | protectHookCommands = lib.concatStrings ( |
| 1180 | lib.mapAttrsToList (name: p: '' |
| 1181 | served=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"} |
| 1182 | phook="$served/hooks/pre-receive" |
| 1183 | managed=${protectHook name p} |
| 1184 | composed=${lib.escapeShellArg (toString (cfg.extraPreReceive.${name} or ""))} |
| 1185 | if [ -L "$phook" ] && [[ "$(readlink "$phook")" == /nix/store/* ]]; then |
| 1186 | ln -sfn "$managed" "$phook" |
| 1187 | elif [ ! -e "$phook" ] && [ ! -L "$phook" ]; then |
| 1188 | ln -s "$managed" "$phook" |
| 1189 | elif [ -n "$composed" ] && [ -f "$phook" ] && cmp -s "$phook" "$composed"; then |
| 1190 | echo "valley-init: ${name}: the pre-receive hook in $served is the one services.valley.extraPreReceive.${name} composes after the push policy, so the managed hook replaces it and runs it" >&2 |
| 1191 | ln -sfn "$managed" "$phook" |
| 1192 | else |
| 1193 | echo "valley-init: ${name}: $phook is a pre-receive hook this module did not write, and git would run it instead of the push policy. Declare it as services.valley.extraPreReceive.${name} to run it after the policy, or remove it." >&2 |
| 1194 | conflicts=1 |
| 1195 | fi |
| 1196 | # Exit status 1 is the one answer that means unset. A value, an |
| 1197 | # empty one included — git then looks for hooks relative to where it |
| 1198 | # runs — and a configuration git cannot read are all refused. |
| 1199 | hooks_path="$(git -C "$served" config --get core.hooksPath)" && status=0 || status=$? |
| 1200 | if [ "$status" -ne 1 ]; then |
| 1201 | echo "valley-init: ${name}: core.hooksPath is set for $served (to '$hooks_path'), so git would look for hooks there and the push policy would not run. Remove the setting, wherever it is." >&2 |
| 1202 | conflicts=1 |
| 1203 | fi |
| 1204 | '') gitProjects |
| 1205 | ); |
| 1206 | |
| 1207 | # sshd's environment patterns, for the assertions that hold it to |
| 1208 | # accepting no client environment the push boundary reads. `*` and `?` are |
| 1209 | # the only wildcards an AcceptEnv pattern has, and a pattern is matched |
| 1210 | # as written: variable names are case-sensitive. |
| 1211 | sshPatternMatches = |
| 1212 | pattern: name: |
| 1213 | builtins.match (lib.concatMapStrings ( |
| 1214 | c: |
| 1215 | if c == "*" then |
| 1216 | ".*" |
| 1217 | else if c == "?" then |
| 1218 | "." |
| 1219 | else if builtins.match "[A-Za-z0-9_]" c != null then |
| 1220 | c |
| 1221 | else |
| 1222 | "\\${c}" |
| 1223 | ) (lib.stringToCharacters pattern)) name != null; |
| 1224 | |
| 1225 | # Whether some name beginning with prefix matches pattern: the pattern |
| 1226 | # walked over the prefix, with the rest of the name free. |
| 1227 | sshPatternMatchesSomeName = |
| 1228 | pattern: prefix: |
| 1229 | if prefix == "" then |
| 1230 | true |
| 1231 | else if pattern == "" then |
| 1232 | false |
| 1233 | else |
| 1234 | let |
| 1235 | c = builtins.substring 0 1 pattern; |
| 1236 | rest = builtins.substring 1 (-1) pattern; |
| 1237 | next = builtins.substring 1 (-1) prefix; |
| 1238 | in |
| 1239 | if c == "*" then |
| 1240 | sshPatternMatchesSomeName rest prefix || sshPatternMatchesSomeName pattern next |
| 1241 | else if c == "?" || c == builtins.substring 0 1 prefix then |
| 1242 | sshPatternMatchesSomeName rest next |
| 1243 | else |
| 1244 | false; |
| 1245 | |
| 1246 | # A variable the push boundary reads, and no client may supply: the |
| 1247 | # principal, and anything git reads its configuration, hooks or objects |
| 1248 | # from. |
| 1249 | boundaryVariable = pattern: sshPatternMatches pattern principalEnv || sshPatternMatchesSomeName pattern "GIT_"; |
| 1250 | |
| 1251 | # A refname glob as the declaration writes one, where `*` crosses path |
| 1252 | # separators (schema/valley.cue). |
| 1253 | refPatternMatches = |
| 1254 | pattern: ref: |
| 1255 | builtins.match (lib.concatMapStrings ( |
| 1256 | c: |
| 1257 | if c == "*" then |
| 1258 | ".*" |
| 1259 | else if builtins.match "[A-Za-z0-9/_-]" c != null then |
| 1260 | c |
| 1261 | else |
| 1262 | "\\${c}" |
| 1263 | ) (lib.stringToCharacters pattern)) ref != null; |
| 1264 | |
| 1265 | # Whether ref is a full ref name, which the identity registry is read at. |
| 1266 | # It opens with refs/ and holds letters, digits, dots, dashes, underscores |
| 1267 | # and slashes alone. git check-ref-format accepts it: no component is |
| 1268 | # empty, opens with a dot or ends with .lock, and it holds no ".." and |
| 1269 | # does not end with a dot. readaccess.ValidRef accepts every name this |
| 1270 | # accepts. |
| 1271 | fullRefName = |
| 1272 | ref: |
| 1273 | builtins.match "refs/[A-Za-z0-9._/-]+" ref != null |
| 1274 | && !(lib.hasInfix ".." ref) |
| 1275 | && !(lib.hasSuffix "." ref) |
| 1276 | && lib.all (part: part != "" && !(lib.hasPrefix "." part) && !(lib.hasSuffix ".lock" part)) ( |
| 1277 | lib.splitString "/" ref |
| 1278 | ); |
| 1279 | |
| 1280 | # Every value sshd is given for one keyword, from the settings and from |
| 1281 | # every line of extraConfig, inside a Match block or not. The keyword is |
| 1282 | # matched in any case, as sshd matches it, with or without `=` after it; |
| 1283 | # the values are kept as written, because sshd's patterns and variable |
| 1284 | # names are case-sensitive. Values are split on any whitespace, tabs |
| 1285 | # included, as sshd splits them. Quoting and escapes are not unpicked |
| 1286 | # here: a value holding a quote or a backslash is refused below instead, |
| 1287 | # because a reading that differed from sshd's would be a hole. |
| 1288 | sshdValues = |
| 1289 | keyword: |
| 1290 | let |
| 1291 | settings = config.services.openssh.settings; |
| 1292 | word = x: if lib.isBool x then (if x then "yes" else "no") else toString x; |
| 1293 | words = v: lib.filter (w: lib.isString w && w != "") (builtins.split "[[:space:]]+" v); |
| 1294 | fromSettings = lib.concatMap ( |
| 1295 | k: |
| 1296 | let |
| 1297 | v = settings.${k}; |
| 1298 | in |
| 1299 | if lib.isList v then lib.concatMap (x: words (word x)) v else words (word v) |
| 1300 | ) (lib.filter (k: lib.toLower k == lib.toLower keyword && settings.${k} != null) (lib.attrNames settings)); |
| 1301 | fromExtra = lib.concatMap ( |
| 1302 | line: |
| 1303 | let |
| 1304 | m = builtins.match "[[:space:]]*([A-Za-z]+)[[:space:]]*=?[[:space:]]*(.*)" line; |
| 1305 | in |
| 1306 | if m == null || lib.toLower (lib.head m) != lib.toLower keyword then |
| 1307 | [ ] |
| 1308 | else |
| 1309 | words (lib.elemAt m 1) |
| 1310 | ) (lib.splitString "\n" config.services.openssh.extraConfig); |
| 1311 | in |
| 1312 | fromSettings ++ fromExtra; |
| 1313 | |
| 1314 | # Every key line the git user's declared authorized_keys holds, from this |
| 1315 | # module and from any other, with the principal its tag names ("" for |
| 1316 | # none) and the key itself. |
| 1317 | declaredKeyEntries = lib.concatMap ( |
| 1318 | line: |
| 1319 | let |
| 1320 | key = builtins.match "(.*[[:space:]])?((ssh|ecdsa|sk)-[^[:space:]\"]+)[[:space:]]+([A-Za-z0-9+/=]+)([[:space:]].*)?" line; |
| 1321 | tag = builtins.match ".*environment=\"${principalEnv}=([^\"]*)\".*" line; |
| 1322 | in |
| 1323 | lib.optional (key != null) { |
| 1324 | key = lib.elemAt key 3; |
| 1325 | principal = if tag == null then "" else lib.head tag; |
| 1326 | } |
| 1327 | ) config.users.users.${cfg.user}.openssh.authorizedKeys.keys; |
| 1328 | |
| 1329 | # Keys declared more than once under different tags. sshd authorizes a |
| 1330 | # key by the first entry that names it, so which principal such a key |
| 1331 | # pushes as depends on file order; the assertion below refuses it. |
| 1332 | conflictingKeys = lib.filterAttrs (_: entries: lib.length (lib.unique (map (e: e.principal) entries)) > 1) ( |
| 1333 | lib.groupBy (e: e.key) declaredKeyEntries |
| 1334 | ); |
| 1335 | |
| 1336 | # The declared key lines, for the compiler: a compiled key that is also |
| 1337 | # declared under another tag is refused there, for the same reason. |
| 1338 | declaredKeysFile = pkgs.writeText "valley-declared-keys" ( |
| 1339 | lib.concatLines config.users.users.${cfg.user}.openssh.authorizedKeys.keys |
| 1340 | ); |
| 1341 | in |
| 1342 | { |
| 1343 | # Telemetry (./telemetry.nix), given what this module derives from the |
| 1344 | # declaration, so its catalog names the units this host runs. |
| 1345 | imports = [ |
| 1346 | (import ./telemetry.nix { |
| 1347 | inherit |
| 1348 | integratedProjects |
| 1349 | publishedProjects |
| 1350 | publishesSigners |
| 1351 | backupEnabled |
| 1352 | workerPackage |
| 1353 | attestPackage |
| 1354 | integratorPackage |
| 1355 | restackerPackage |
| 1356 | ; |
| 1357 | }) |
| 1358 | ]; |
| 1359 | |
| 1360 | options.services.valley = { |
| 1361 | enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration"; |
| 1362 | |
| 1363 | user = lib.mkOption { |
| 1364 | type = lib.types.str; |
| 1365 | default = "git"; |
| 1366 | description = "System user that owns the repositories and accepts SSH pushes."; |
| 1367 | }; |
| 1368 | |
| 1369 | group = lib.mkOption { |
| 1370 | type = lib.types.str; |
| 1371 | default = "git"; |
| 1372 | description = "Primary group of the valley git user."; |
| 1373 | }; |
| 1374 | |
| 1375 | dataDir = lib.mkOption { |
| 1376 | type = lib.types.path; |
| 1377 | default = "/srv/git"; |
| 1378 | example = "/mnt/git"; |
| 1379 | description = '' |
| 1380 | Directory holding the bare repositories, one `<name>.git` per |
| 1381 | project declared in {option}`services.valley.config`. Also the git |
| 1382 | user's home, so clone URLs are relative to it (`git@host:name.git`). |
| 1383 | Consumers typically point it at a dedicated dataset. |
| 1384 | ''; |
| 1385 | }; |
| 1386 | |
| 1387 | authorizedKeys = lib.mkOption { |
| 1388 | type = lib.types.listOf ( |
| 1389 | lib.types.either lib.types.str ( |
| 1390 | lib.types.submodule { |
| 1391 | options = { |
| 1392 | key = lib.mkOption { |
| 1393 | type = lib.types.str; |
| 1394 | description = "The SSH public key, as it would appear in `authorized_keys`."; |
| 1395 | }; |
| 1396 | |
| 1397 | principal = lib.mkOption { |
| 1398 | type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"; |
| 1399 | example = "integrator"; |
| 1400 | description = '' |
| 1401 | Name of the principal this key acts as. Every push made |
| 1402 | with the key carries the name, and the pre-receive hook |
| 1403 | decides what the name may write: from the project's |
| 1404 | `protection` block and named grants in |
| 1405 | {option}`services.valley.config`, and from the grants the |
| 1406 | name holds ({option}`services.valley.grants`, and the |
| 1407 | registry's when it is compiled). Nothing else uses it. |
| 1408 | A key is declared once: the same key under two tags, or |
| 1409 | tagged and untagged, is refused. |
| 1410 | ''; |
| 1411 | }; |
| 1412 | }; |
| 1413 | } |
| 1414 | ) |
| 1415 | ); |
| 1416 | default = [ ]; |
| 1417 | example = lib.literalExpression '' |
| 1418 | [ |
| 1419 | "ssh-ed25519 AAAA… someone@somewhere" |
| 1420 | { |
| 1421 | principal = "integrator"; |
| 1422 | key = "ssh-ed25519 AAAA… integrator"; |
| 1423 | } |
| 1424 | ] |
| 1425 | ''; |
| 1426 | description = '' |
| 1427 | SSH public keys allowed to push/fetch as the git user. Access is |
| 1428 | host-level by design: every key can reach every project. |
| 1429 | |
| 1430 | A key written as a plain string is anonymous — it can push, and it |
| 1431 | can write nothing protected. A key written as an attribute set |
| 1432 | names the principal it acts as, which is the only thing that can |
| 1433 | tell one pusher from another: pushes arrive as the shared git user, |
| 1434 | so identity has to ride on the key. |
| 1435 | |
| 1436 | Which refs a principal may write is declared, not an option here: |
| 1437 | it is a statement about what the host serves, and lives in the |
| 1438 | project's `protection` block in |
| 1439 | {option}`services.valley.config`. Binding a name to keys is the |
| 1440 | machine half — the hand-written form of what the identity registry |
| 1441 | compiles (dcr-b87f6e8). |
| 1442 | |
| 1443 | With {option}`services.valley.identity.enable` on, the compiled |
| 1444 | keys are added to what sshd reads and the keys here stay |
| 1445 | authorized beside them. The list is therefore the way back in when |
| 1446 | a compilation is wrong or has not happened yet, and it is never |
| 1447 | empty. |
| 1448 | ''; |
| 1449 | }; |
| 1450 | |
| 1451 | extraPreReceive = lib.mkOption { |
| 1452 | type = lib.types.attrsOf lib.types.pathInStore; |
| 1453 | default = { }; |
| 1454 | example = lib.literalExpression '' |
| 1455 | { |
| 1456 | app = pkgs.writeShellScript "app-pre-receive" ; |
| 1457 | } |
| 1458 | ''; |
| 1459 | description = '' |
| 1460 | A further pre-receive hook per project, run after the push policy |
| 1461 | accepts a push, with the same input. It can refuse what the policy |
| 1462 | accepts and never accept what the policy refuses. |
| 1463 | |
| 1464 | This is the one way to compose a hook with the managed one. A |
| 1465 | pre-receive hook the module did not write fails valley-init, |
| 1466 | because git would run it instead of the policy. A hook that is |
| 1467 | byte-for-byte the one declared here is the exception: valley-init |
| 1468 | replaces it with the managed hook, which runs it. The value is a |
| 1469 | store path, so what runs is exactly what was declared. |
| 1470 | ''; |
| 1471 | }; |
| 1472 | |
| 1473 | # Grants held by hand. The registry names who holds a grant |
| 1474 | # (dcr-b87f6e8, dcr-e544f20), and these options are the hand-written |
| 1475 | # form of what it compiles, beside it the way the declared keys sit |
| 1476 | # beside the compiled ones. |
| 1477 | grants = { |
| 1478 | approve = lib.mkOption { |
| 1479 | type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"); |
| 1480 | default = [ ]; |
| 1481 | example = [ "operator" ]; |
| 1482 | description = '' |
| 1483 | Principals holding the approve grant (also accepted as |
| 1484 | {option}`services.valley.grants.request`): the ones whose pushes |
| 1485 | may file, replace and withdraw an integration request |
| 1486 | (`refs/the-valley/integration-requests/*`) on a protected |
| 1487 | project. The pre-receive hook refuses every other write to that |
| 1488 | namespace, so a principal named neither here, nor in |
| 1489 | {option}`services.valley.grants.request`, nor in the registry |
| 1490 | cannot file an integration request. |
| 1491 | |
| 1492 | The two options are one grant. The holders are the principals |
| 1493 | named in either list, and a principal named in both holds the |
| 1494 | grant once. |
| 1495 | |
| 1496 | The grant rides on push. Only a key sshd admits reaches the hook, |
| 1497 | so a principal named here also needs a key, declared in |
| 1498 | {option}`services.valley.authorizedKeys` or compiled from the |
| 1499 | registry. |
| 1500 | |
| 1501 | With {option}`services.valley.identity.enable` on, the holders |
| 1502 | the registry names are added to these, and a compiled file can |
| 1503 | only ever add. The list is therefore how a host grants approve |
| 1504 | before its registry does — including to the operator who has to |
| 1505 | file the registry change that grants it. |
| 1506 | ''; |
| 1507 | }; |
| 1508 | |
| 1509 | request = lib.mkOption { |
| 1510 | type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"); |
| 1511 | default = [ ]; |
| 1512 | example = [ "operator" ]; |
| 1513 | description = '' |
| 1514 | Principals holding the approve grant, under the name it had |
| 1515 | first. A principal named here holds exactly what one named in |
| 1516 | {option}`services.valley.grants.approve` holds, and the holders |
| 1517 | are the principals named in either list. |
| 1518 | ''; |
| 1519 | }; |
| 1520 | |
| 1521 | restack = lib.mkOption { |
| 1522 | type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"); |
| 1523 | default = [ ]; |
| 1524 | example = [ "valley-restacker" ]; |
| 1525 | description = '' |
| 1526 | Principals holding the restack grant: the host restacker's. A |
| 1527 | holder that neither owns a change nor holds the approve grant may |
| 1528 | add exactly one version to the change's record while the change |
| 1529 | is ready, on the branch and under the title of its active version, |
| 1530 | with itself as the uploader. It may also write restack reports |
| 1531 | (`refs/the-valley/restack/main/<change-id>`). The grant permits |
| 1532 | no other record write and nothing on integration requests, and a |
| 1533 | holder keeps every ordinary power of a named principal. |
| 1534 | |
| 1535 | The grant rides on push, like approve: a principal named here also |
| 1536 | needs a key. With {option}`services.valley.identity.enable` on, |
| 1537 | the holders the registry names are added to these. The list is |
| 1538 | how a host grants restack before its registry does; remove an |
| 1539 | entry once the registry grants the same principal. |
| 1540 | ''; |
| 1541 | }; |
| 1542 | }; |
| 1543 | |
| 1544 | config = lib.mkOption { |
| 1545 | type = lib.types.path; |
| 1546 | example = lib.literalExpression "./valley.cue"; |
| 1547 | description = '' |
| 1548 | Path to the host's CUE declaration (`package valley`) — the |
| 1549 | canonical statement of what this valley host serves, validated |
| 1550 | against the shipped schema at build time. This is the single domain |
| 1551 | input: projects, their push mirrors, and the backup policy are |
| 1552 | declared here, never as Nix options. |
| 1553 | ''; |
| 1554 | }; |
| 1555 | |
| 1556 | # The event bus. Machine options, not domain: whether this machine runs |
| 1557 | # a bus, where it listens, and where its storage lives. What gets |
| 1558 | # published onto it is defined portably in ../schema/events.cue. |
| 1559 | bus = { |
| 1560 | enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events"; |
| 1561 | |
| 1562 | listen = lib.mkOption { |
| 1563 | type = lib.types.str; |
| 1564 | default = "127.0.0.1:4222"; |
| 1565 | example = "192.0.2.10:4222"; |
| 1566 | description = '' |
| 1567 | Address the bus listens on, `host:port`. Localhost by default: |
| 1568 | nothing off the host can reach the bus until the consumer widens |
| 1569 | this deliberately — e.g. to the host's private network address once a |
| 1570 | remote `valley tail` wants in. Local publishers (the ref-updated |
| 1571 | hook) connect to this same address, so it must be reachable from |
| 1572 | the host itself. |
| 1573 | ''; |
| 1574 | }; |
| 1575 | |
| 1576 | storeDir = lib.mkOption { |
| 1577 | type = lib.types.path; |
| 1578 | default = "${cfg.dataDir}/.bus"; |
| 1579 | defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"''; |
| 1580 | description = '' |
| 1581 | Directory holding the JetStream file storage. The default lives |
| 1582 | under {option}`services.valley.dataDir`; it can never collide |
| 1583 | with a repository because project names must start with an |
| 1584 | alphanumeric. The stream is a projection of git, rebuildable |
| 1585 | with `valley replay` — losing this directory costs one replay. |
| 1586 | ''; |
| 1587 | }; |
| 1588 | }; |
| 1589 | |
| 1590 | # The integrator (archive/design/roadmap.md, Phase 3): the controller that |
| 1591 | # lands a change once its evidence still transfers to the current tip. |
| 1592 | # Machine options only — whether this host runs controllers, who they |
| 1593 | # are, and how often they look. Which projects get one is not an option |
| 1594 | # either: it follows from which projects the declaration protects, |
| 1595 | # because a protected ref is exactly what a controller exists to write. |
| 1596 | integrator = { |
| 1597 | enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers"; |
| 1598 | |
| 1599 | user = lib.mkOption { |
| 1600 | type = lib.types.str; |
| 1601 | default = "valley-integrator"; |
| 1602 | description = '' |
| 1603 | System user the controllers run as. Deliberately not |
| 1604 | {option}`services.valley.user`: one unix identity per service is |
| 1605 | the split bd-500adf7 asks for, and this service begins it. |
| 1606 | |
| 1607 | The account exists only to write the repositories it serves. It |
| 1608 | gets no shell and no SSH key, and its primary group is |
| 1609 | {option}`services.valley.group`, which is the whole of its |
| 1610 | permission model: {option}`services.valley.dataDir` is already |
| 1611 | group-readable, and each served repository is made group-shared |
| 1612 | (group write, setgid directories) so a controller can write |
| 1613 | refs, objects, and git's worktree metadata. Nothing else on the |
| 1614 | host belongs to that group, and the bus's store directory (mode |
| 1615 | 0700) stays out of reach. |
| 1616 | |
| 1617 | The key and signers files are the consumer's to provision; both |
| 1618 | must be readable by this user. |
| 1619 | ''; |
| 1620 | }; |
| 1621 | |
| 1622 | signingKeyFile = lib.mkOption { |
| 1623 | type = lib.types.nullOr lib.types.path; |
| 1624 | default = null; |
| 1625 | example = "/run/agenix/valley-integrator-key"; |
| 1626 | description = '' |
| 1627 | ed25519 private key the controllers sign their transfer |
| 1628 | statements with. A runtime path the consumer provisions (e.g. |
| 1629 | agenix), never a store path — the store is world-readable. |
| 1630 | ''; |
| 1631 | }; |
| 1632 | |
| 1633 | knownSignersFile = lib.mkOption { |
| 1634 | type = lib.types.nullOr lib.types.path; |
| 1635 | default = null; |
| 1636 | example = "/var/lib/valley-instance/known_signers"; |
| 1637 | description = '' |
| 1638 | File of verifier keys whose attestations count, one per line, in |
| 1639 | `attest key` format. This is the identity registry's interim |
| 1640 | compilation (dcr-b87f6e8), supplied directly for a host that does |
| 1641 | not compile one: turning on |
| 1642 | {option}`services.valley.identity.enable` renders the same file |
| 1643 | from the registry, and then this option must be left unset. |
| 1644 | Evidence signed by nobody in it does not transfer, which a |
| 1645 | controller reports per check rather than treating as a forgery. |
| 1646 | ''; |
| 1647 | }; |
| 1648 | |
| 1649 | signerProjects = lib.mkOption { |
| 1650 | type = lib.types.attrsOf (lib.types.listOf lib.types.str); |
| 1651 | default = { }; |
| 1652 | example = { |
| 1653 | "worker/attestations" = [ "app" ]; |
| 1654 | }; |
| 1655 | description = '' |
| 1656 | Signers whose attestations count only in the projects listed for |
| 1657 | them, by the name each signs under. A signer named here counts |
| 1658 | in its listed projects alone; in any other project a controller |
| 1659 | reports its evidence as signed by no signer it holds. An empty |
| 1660 | list lets the signer count nowhere. A signer not named here |
| 1661 | counts wherever the known-signers file lets it. |
| 1662 | |
| 1663 | This is how a check worker's key, which every controller sharing |
| 1664 | the known-signers file would otherwise accept, is trusted only |
| 1665 | for the projects it builds. When |
| 1666 | {option}`services.valley.worker.enable` is on, the module lists |
| 1667 | {option}`services.valley.worker.projects` here under |
| 1668 | {option}`services.valley.worker.signerName`. A host's own entry |
| 1669 | for that name replaces the module's. The push hook still admits |
| 1670 | the worker's evidence everywhere; only the controllers restrict |
| 1671 | it. |
| 1672 | |
| 1673 | List every other controller whose key the known-signers file |
| 1674 | holds, such as another host's integrator, with an empty list. |
| 1675 | A controller countersigns the attestations a landing carried, |
| 1676 | and its own signature never counts as check evidence here; |
| 1677 | another controller's counts only until it is listed. |
| 1678 | |
| 1679 | The list is rendered into a file every controller reads at start. |
| 1680 | A host that publishes its signers publishes the file beside them, |
| 1681 | so a client can read the same restriction. Names and projects are |
| 1682 | words of printable ASCII with no space, and a name holds no plus |
| 1683 | and does not open with #. The list may not name the name the |
| 1684 | controllers sign under: a controller given such a list refuses to |
| 1685 | start. |
| 1686 | ''; |
| 1687 | }; |
| 1688 | |
| 1689 | signingName = lib.mkOption { |
| 1690 | type = lib.types.nullOr lib.types.str; |
| 1691 | default = null; |
| 1692 | example = "integrator"; |
| 1693 | description = '' |
| 1694 | The name a controller's transfer statements are signed under. |
| 1695 | Unset leaves the binary's own default, which is this host's |
| 1696 | attestations name — the machine signing as itself. |
| 1697 | |
| 1698 | Set it to the name the identity registry publishes the |
| 1699 | integrator's key under. The note format's key hash binds the name |
| 1700 | to the key (dcr-de9d996), so a controller signing under one name |
| 1701 | while the registry publishes it under another produces notes no |
| 1702 | verifier can find a key for. |
| 1703 | ''; |
| 1704 | }; |
| 1705 | |
| 1706 | instanceProject = lib.mkOption { |
| 1707 | type = lib.types.nullOr lib.types.str; |
| 1708 | default = null; |
| 1709 | example = "valley"; |
| 1710 | description = '' |
| 1711 | The project whose served repository carries the group's floor — |
| 1712 | the instance policy layer every controller on this host composes |
| 1713 | against. A controller reads it from `policy/instance/` in that |
| 1714 | bare repository's integrated tip, and nothing is materialized on |
| 1715 | disk in between. It is also where the identity registry is read |
| 1716 | from, for the same reason and at the same altitude: both are the |
| 1717 | instance's, so a host serving that repository already holds the |
| 1718 | authoritative copy. |
| 1719 | |
| 1720 | The floor is the instance repository's, read at the tip that has |
| 1721 | been integrated (dcr-f41f718); the instance repository is the |
| 1722 | group's own (dcr-b87f6e8). A host serving it is therefore already |
| 1723 | holding the authoritative copy. |
| 1724 | |
| 1725 | What follows is a property of that design, and worth knowing |
| 1726 | before editing a floor. A change to it takes effect at the first |
| 1727 | pass after it lands on that ref, and never before. An edit in a |
| 1728 | branch, in a worktree, or in an integration request that has not |
| 1729 | been integrated governs nothing. There is no refresh to trigger |
| 1730 | and no staleness to wait out: landing is the whole of publishing |
| 1731 | a floor. |
| 1732 | |
| 1733 | The project has to declare protection covering refs/heads/main, |
| 1734 | and the registry's ref when the identity compiler is on. Both |
| 1735 | are read from that tip, so a ref any push-capable key could move |
| 1736 | would hand every key the floor and the registry. |
| 1737 | |
| 1738 | Every controller on the host reads the same repository, the |
| 1739 | controller serving that repository included. Both layers are |
| 1740 | resolved from the controller's own side — this one, and the |
| 1741 | project's `policy/project/` at the target tip — so a change can |
| 1742 | never supply the policy that gates it (bd-eaefe82). |
| 1743 | |
| 1744 | Those two directories are the convention, and the module states |
| 1745 | neither: a controller takes each layer from the place the |
| 1746 | integrator defaults to, so a host declaration that says nothing |
| 1747 | about policy gets the layout the worked example lays out |
| 1748 | (dcr-f41f718). |
| 1749 | ''; |
| 1750 | }; |
| 1751 | |
| 1752 | instancePolicy = lib.mkOption { |
| 1753 | type = lib.types.nullOr lib.types.path; |
| 1754 | default = null; |
| 1755 | example = "/var/lib/valley-instance/policy/instance"; |
| 1756 | description = '' |
| 1757 | Directory of `*.cue` files holding the instance policy layer, for |
| 1758 | a host that serves no instance repository. It holds what |
| 1759 | `policy/instance/` in the instance repository holds. Set this or |
| 1760 | {option}`services.valley.integrator.instanceProject`, never both. |
| 1761 | |
| 1762 | Keeping such a directory in step with the instance repository is |
| 1763 | the consumer's to arrange, which is the reason to prefer the |
| 1764 | project option wherever the host serves the repository. |
| 1765 | ''; |
| 1766 | }; |
| 1767 | |
| 1768 | interval = lib.mkOption { |
| 1769 | type = lib.types.str; |
| 1770 | default = "15s"; |
| 1771 | example = "1m"; |
| 1772 | description = '' |
| 1773 | How long a controller waits after a pass before the next, when |
| 1774 | nothing starts one sooner. A push to the project, a floor moved |
| 1775 | in the instance project, and a landing by the controller itself |
| 1776 | each start a pass promptly. This interval is the recovery pass: it |
| 1777 | reads what a lost mark, a failed watch or a changed |
| 1778 | known-signers file left waiting, since integration requests are |
| 1779 | durable in git and the controller level-triggers over those refs. |
| 1780 | ''; |
| 1781 | }; |
| 1782 | }; |
| 1783 | |
| 1784 | # The build slice (oc-03b6f8c): caps on every build this machine's nix |
| 1785 | # daemon runs, whoever asked for it. A host decision of its own, and a |
| 1786 | # condition of the check worker, which builds through the daemon. |
| 1787 | buildSlice = { |
| 1788 | enable = lib.mkEnableOption '' |
| 1789 | capping every build the nix daemon on this host runs, for every user |
| 1790 | of it, together: the daemon runs in one slice with a CPU quota, a |
| 1791 | memory cap and no swap''; |
| 1792 | |
| 1793 | cpuQuota = lib.mkOption { |
| 1794 | type = lib.types.str; |
| 1795 | default = "400%"; |
| 1796 | example = "800%"; |
| 1797 | description = '' |
| 1798 | The CPU time every build the daemon runs gets together, as |
| 1799 | systemd's CPUQuota: 400% is four CPUs' worth. |
| 1800 | ''; |
| 1801 | }; |
| 1802 | |
| 1803 | memoryMax = lib.mkOption { |
| 1804 | type = lib.types.str; |
| 1805 | default = "8G"; |
| 1806 | example = "16G"; |
| 1807 | description = '' |
| 1808 | The memory every build the daemon runs gets together, as |
| 1809 | systemd's MemoryMax. The slice gets no swap. A build that takes |
| 1810 | the slice past it is ended by the kernel's OOM killer, which kills |
| 1811 | the process in the slice using the most memory: usually the |
| 1812 | build that went past, but any build in the slice can be the one |
| 1813 | killed. |
| 1814 | ''; |
| 1815 | }; |
| 1816 | }; |
| 1817 | |
| 1818 | # The check worker (oc-13c6bd6): a timer that runs one pass of |
| 1819 | # valley-worker over its projects, so ready changes have their |
| 1820 | # nix checks built before anyone approves them. Machine options only — |
| 1821 | # whether this host runs the worker, for which of its projects, under |
| 1822 | # which signing name, with how much build capacity, how often, and |
| 1823 | # where it keeps its state. |
| 1824 | worker = { |
| 1825 | enable = lib.mkEnableOption '' |
| 1826 | the valley check worker: a timer that builds the nix checks ready |
| 1827 | changes require and publishes the evidence, under its own key, for |
| 1828 | the projects selected by {option}`services.valley.worker.projects`, |
| 1829 | which defaults to every Git-enabled project with a protection block''; |
| 1830 | |
| 1831 | projects = lib.mkOption { |
| 1832 | type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"); |
| 1833 | default = lib.attrNames integratedProjects; |
| 1834 | defaultText = lib.literalMD "every Git-enabled project in the host declaration that has a protection block"; |
| 1835 | example = [ "app" ]; |
| 1836 | description = '' |
| 1837 | The projects the worker builds evidence for. Each is a Git |
| 1838 | repository this host serves. Unset, the list is every Git-enabled |
| 1839 | project in the host declaration that has a protection block. This |
| 1840 | includes the instance project. |
| 1841 | |
| 1842 | The worker builds evidence only for these projects. It also reads |
| 1843 | the instance repository for discovery, and any owning instance |
| 1844 | repository needed to load a project's policy floor. |
| 1845 | |
| 1846 | When the host and the worker are enabled, the module defaults |
| 1847 | {option}`services.valley.integrator.signerProjects` for |
| 1848 | {option}`services.valley.worker.signerName` to this list. An |
| 1849 | explicit entry must name the same projects, or evaluation fails. |
| 1850 | When the worker is disabled, this option does not configure signer |
| 1851 | restrictions. |
| 1852 | ''; |
| 1853 | }; |
| 1854 | |
| 1855 | signerName = lib.mkOption { |
| 1856 | type = lib.types.str; |
| 1857 | example = "worker/attestations"; |
| 1858 | description = '' |
| 1859 | The name the worker signs its notes under. It is a name of the |
| 1860 | worker's own: never the operator's, and never the name the |
| 1861 | controllers sign under, which the module refuses. |
| 1862 | |
| 1863 | Enrolled with the worker's key, it is what the known-signers file |
| 1864 | and the identity registry hold for the worker: the registry key's |
| 1865 | `signs`, and the name in the verifier line. |
| 1866 | ''; |
| 1867 | }; |
| 1868 | |
| 1869 | buildSlots = lib.mkOption { |
| 1870 | type = lib.types.ints.positive; |
| 1871 | default = 1; |
| 1872 | example = 3; |
| 1873 | description = '' |
| 1874 | The most `nix build` processes the worker runs at once for |
| 1875 | distinct check derivations in one batch, as `valley-worker |
| 1876 | --slots`. Checks with the same derivation share one process. |
| 1877 | |
| 1878 | ${workerCapacityBound} |
| 1879 | ''; |
| 1880 | }; |
| 1881 | |
| 1882 | maxJobs = lib.mkOption { |
| 1883 | type = lib.types.ints.positive; |
| 1884 | default = 1; |
| 1885 | example = 2; |
| 1886 | description = '' |
| 1887 | Each worker `nix build` may run up to this many local derivation |
| 1888 | jobs at once, including dependencies of its check, as nix's |
| 1889 | `max-jobs` setting. During the build phase, the worker's |
| 1890 | concurrent builds therefore allow up to |
| 1891 | {option}`services.valley.worker.buildSlots` times this many such |
| 1892 | jobs. Other clients' jobs are additional. |
| 1893 | |
| 1894 | ${workerCapacityBound} |
| 1895 | ''; |
| 1896 | }; |
| 1897 | |
| 1898 | cores = lib.mkOption { |
| 1899 | type = lib.types.ints.positive; |
| 1900 | default = 4; |
| 1901 | example = 2; |
| 1902 | description = '' |
| 1903 | The `cores` hint each derivation's builder gets, as nix's `cores` |
| 1904 | setting. The builder reads it as `NIX_BUILD_CORES`, and a build |
| 1905 | that honours it may use that value to limit its own parallel |
| 1906 | jobs. It caps nothing. |
| 1907 | |
| 1908 | ${workerCapacityBound} |
| 1909 | ''; |
| 1910 | }; |
| 1911 | |
| 1912 | batches = lib.mkOption { |
| 1913 | type = lib.types.ints.positive; |
| 1914 | default = 2; |
| 1915 | example = 3; |
| 1916 | description = '' |
| 1917 | The most batches a pass runs at once, as `valley-worker |
| 1918 | --batches`. A batch is one ready change's missing checks, built by |
| 1919 | one `attest run`. While a long batch runs, a pass starts the next |
| 1920 | ready change's batch in a free slot, so a short change does not |
| 1921 | wait behind a long one. |
| 1922 | |
| 1923 | At worst, the worker has this many times |
| 1924 | {option}`services.valley.worker.buildSlots` `nix build` |
| 1925 | processes at once, and each may build |
| 1926 | {option}`services.valley.worker.maxJobs` derivations at once: |
| 1927 | `batches × buildSlots × maxJobs` local derivation builds, besides |
| 1928 | the evaluations. They share {option}`services.valley.buildSlice.memoryMax` |
| 1929 | with the worker and the nix daemon. Batches overlap their builds, |
| 1930 | and their evaluations run together only while their estimated |
| 1931 | peaks fit {option}`services.valley.worker.evalMemoryBudget`, so |
| 1932 | more batches overlap more builds but no more evaluation memory. |
| 1933 | Measure the slice's peak |
| 1934 | memory under a real load before raising this: |
| 1935 | `systemctl status valley-builds.slice` shows its memory now and |
| 1936 | its peak. |
| 1937 | |
| 1938 | ${workerCapacityBound} |
| 1939 | ''; |
| 1940 | }; |
| 1941 | |
| 1942 | evalMemoryShare = lib.mkOption { |
| 1943 | type = lib.types.numbers.between 0.05 1; |
| 1944 | default = 0.6; |
| 1945 | example = 0.75; |
| 1946 | description = '' |
| 1947 | The share of the worker's memory limit that the evaluations of |
| 1948 | its batches may hold together, as `valley-worker --eval-share`. |
| 1949 | The limit is the smallest `memory.max` of the worker's cgroup and |
| 1950 | its ancestors, which is |
| 1951 | {option}`services.valley.buildSlice.memoryMax`, and never more |
| 1952 | than the host's memory. When the worker cannot find that limit, |
| 1953 | it evaluates one batch at a time and says so, and |
| 1954 | {option}`services.valley.worker.evalMemoryBudget` should be set. |
| 1955 | The rest is left to the builds of batches |
| 1956 | that are past their evaluations, to the nix daemon and to the |
| 1957 | worker. A batch's evaluation starts when its estimated peak fits |
| 1958 | this budget beside the evaluations already running; otherwise it |
| 1959 | waits. An evaluation estimated at more than the whole budget runs |
| 1960 | alone, and the worker reports it. |
| 1961 | {option}`services.valley.worker.evalMemoryBudget` overrides this. |
| 1962 | ''; |
| 1963 | }; |
| 1964 | |
| 1965 | evalMemoryBudget = lib.mkOption { |
| 1966 | type = lib.types.nullOr (lib.types.strMatching "[0-9]+[KMGT]?"); |
| 1967 | default = null; |
| 1968 | example = "12G"; |
| 1969 | description = '' |
| 1970 | The memory the evaluations of the worker's batches may hold |
| 1971 | together, as `valley-worker --eval-budget`, in bytes or with a K, |
| 1972 | M, G or T suffix for powers of 1024, as systemd's MemoryMax. |
| 1973 | `null` takes {option}`services.valley.worker.evalMemoryShare` of |
| 1974 | the worker's memory limit. Give a budget at least as large as the |
| 1975 | largest project's evaluation peak, which the `eval.end` |
| 1976 | telemetry records as `eval_max_rss_bytes`, and no more than |
| 1977 | {option}`services.valley.buildSlice.memoryMax` less what the |
| 1978 | builds of {option}`services.valley.worker.batches` batches need. |
| 1979 | ''; |
| 1980 | }; |
| 1981 | |
| 1982 | keepOutputs = lib.mkOption { |
| 1983 | type = lib.types.nullOr lib.types.ints.positive; |
| 1984 | default = 7; |
| 1985 | example = 30; |
| 1986 | description = '' |
| 1987 | How many days the worker keeps the outputs of the checks it |
| 1988 | builds, counted from the last batch that used each, as |
| 1989 | `valley-worker --keep-outputs`. The worker roots every output in |
| 1990 | `roots/` in its state directory, so the host's garbage collection |
| 1991 | keeps it, and a later change whose check has the same derivation |
| 1992 | finds it built instead of building it again. Each pass first |
| 1993 | removes the roots no batch has used for longer than this; nix's |
| 1994 | garbage collection then frees those outputs. `null` roots |
| 1995 | nothing. |
| 1996 | ''; |
| 1997 | }; |
| 1998 | |
| 1999 | interval = lib.mkOption { |
| 2000 | type = lib.types.str; |
| 2001 | default = "1m"; |
| 2002 | example = "5m"; |
| 2003 | description = '' |
| 2004 | How long the timer waits after one pass ends before it starts the |
| 2005 | next; systemd's default timer accuracy can add up to a minute. A |
| 2006 | pass that has nothing to build reads origin and ends. A move the |
| 2007 | worker reads starts a pass sooner, through the wake directory; |
| 2008 | the timer is the recovery scan, and what retries a failed batch |
| 2009 | or push once its wait is over. It is also the hold-off after a |
| 2010 | pass that could not claim its wake mark. A pass whose batches |
| 2011 | still run reads its projects again at this interval, passed as |
| 2012 | `valley-worker --interval`, since the timer starts no pass while |
| 2013 | one runs. It is a systemd time span, such as `1m` or `5min`; |
| 2014 | the worker reads every span the timer reads. |
| 2015 | ''; |
| 2016 | }; |
| 2017 | |
| 2018 | wakeDir = lib.mkOption { |
| 2019 | type = lib.types.path; |
| 2020 | default = "/var/lib/valley-worker-wake"; |
| 2021 | description = '' |
| 2022 | The worker's wake directory, mode 0770, owned by the |
| 2023 | `valley-worker` user and the `valley-worker-wake` group, whose |
| 2024 | members are the git user and the integrator's user. A push to |
| 2025 | one of the worker's projects or to the instance project, a |
| 2026 | landing in one, and a moved signer publication create the empty |
| 2027 | file `due` in it, and a path unit starts a pass while it is |
| 2028 | there. It holds no more than `due`, `claimed` and `lock`. |
| 2029 | ''; |
| 2030 | }; |
| 2031 | |
| 2032 | stateDir = lib.mkOption { |
| 2033 | type = lib.types.path; |
| 2034 | default = "/var/lib/valley-worker"; |
| 2035 | description = '' |
| 2036 | The worker's own directory, mode 0700 and owned by the |
| 2037 | `valley-worker` user. It holds the worker's key, made on the |
| 2038 | first start and readable by the worker alone; its public halves, |
| 2039 | `key.pub` and `verifier`; the lock and the record of failed |
| 2040 | batches; the clones the worker reads projects through; and |
| 2041 | `roots/`, the garbage-collector roots of the check outputs it |
| 2042 | keeps. |
| 2043 | ''; |
| 2044 | }; |
| 2045 | }; |
| 2046 | |
| 2047 | # The restacker (restack/): one controller for each project it serves, |
| 2048 | # which rebases the project's ready changes onto main when main moves, |
| 2049 | # as its own principal. Machine options only. Registering the principal |
| 2050 | # (its key and its restack grant, in services.valley.authorizedKeys and |
| 2051 | # services.valley.grants.restack or in the registry) and provisioning |
| 2052 | # its private key are the operator's, and nothing here does either. |
| 2053 | restacker = { |
| 2054 | enable = lib.mkEnableOption '' |
| 2055 | the valley restacker: one controller for each project it serves, which |
| 2056 | rebases the project's ready changes onto main when main moves, |
| 2057 | pushing over this host's sshd as its own principal''; |
| 2058 | |
| 2059 | projects = lib.mkOption { |
| 2060 | type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"); |
| 2061 | default = lib.attrNames integratedProjects; |
| 2062 | defaultText = lib.literalExpression "every Git-enabled project with a protection block"; |
| 2063 | example = [ "the-valley" ]; |
| 2064 | description = '' |
| 2065 | The projects the restacker serves, each a project this host |
| 2066 | serves. By default it serves every Git-enabled project with a |
| 2067 | protection block. Setting `projects` selects exactly the projects |
| 2068 | listed, which must be non-empty. Each gets a controller of its own, |
| 2069 | `valley-restacker@<project>.service`, with a state directory of |
| 2070 | its own under `/var/lib/valley-restacker`. |
| 2071 | ''; |
| 2072 | }; |
| 2073 | |
| 2074 | principal = lib.mkOption { |
| 2075 | type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"; |
| 2076 | default = "valley-restacker"; |
| 2077 | description = '' |
| 2078 | The principal the restacker pushes as, and names as the uploader |
| 2079 | of every version it adds. Its key must be declared under this |
| 2080 | name, and the name must hold the restack grant, for the hook to |
| 2081 | take its versions and reports. A deployment declares both; this |
| 2082 | module does neither. |
| 2083 | ''; |
| 2084 | }; |
| 2085 | |
| 2086 | sshKeyFile = lib.mkOption { |
| 2087 | type = lib.types.nullOr lib.types.str; |
| 2088 | default = null; |
| 2089 | example = "/run/agenix/valley-restacker-key"; |
| 2090 | description = '' |
| 2091 | The private ssh key the restacker authenticates with, kept |
| 2092 | outside the Nix store. systemd reads it as root and hands it to |
| 2093 | each controller as a credential, so the file may stay readable |
| 2094 | by root alone. Its public half is what the operator declares |
| 2095 | for {option}`services.valley.restacker.principal`. |
| 2096 | ''; |
| 2097 | }; |
| 2098 | |
| 2099 | interval = lib.mkOption { |
| 2100 | type = lib.types.str; |
| 2101 | default = "15s"; |
| 2102 | example = "1m"; |
| 2103 | description = '' |
| 2104 | How long a controller waits after one pass before the next. A |
| 2105 | pass reads origin whether or not main has moved, so a change |
| 2106 | readied since the last pass is found without another landing. |
| 2107 | After a pass that fails, the wait doubles, up to five minutes, |
| 2108 | until a pass succeeds. |
| 2109 | ''; |
| 2110 | }; |
| 2111 | }; |
| 2112 | |
| 2113 | # The identity registry compiler (dcr-b87f6e8): the step between the |
| 2114 | # instance's declared registry and the two gates that read what it |
| 2115 | # compiles to. Machine options only — whether this host compiles, and |
| 2116 | # from where. Who the principals are, what they hold and when their |
| 2117 | # entries end is the registry's, and the registry is a document in the |
| 2118 | # instance repository, never an option here. |
| 2119 | identity = { |
| 2120 | enable = lib.mkEnableOption '' |
| 2121 | compiling the identity registry into what the gates check: the |
| 2122 | verifier keys a controller accepts evidence from, and the git |
| 2123 | user's authorized keys, both rendered from the instance |
| 2124 | repository's integrated tip''; |
| 2125 | |
| 2126 | ref = lib.mkOption { |
| 2127 | type = lib.types.str; |
| 2128 | default = "refs/heads/main"; |
| 2129 | description = '' |
| 2130 | The ref of the instance repository whose tip carries the |
| 2131 | registry: a full ref name, opening with `refs/`, in letters, |
| 2132 | digits, dots, dashes, underscores and slashes. A short name such |
| 2133 | as `main` is refused. A registry edit takes effect at the first |
| 2134 | compilation after it lands on this ref, and never before: an edit |
| 2135 | in a branch, in a worktree, or in an integration request that has |
| 2136 | not been integrated governs nothing. The web publisher |
| 2137 | (`services.valley.webPublisher`) reads its read grants from the |
| 2138 | registry at this ref too. |
| 2139 | ''; |
| 2140 | }; |
| 2141 | |
| 2142 | directory = lib.mkOption { |
| 2143 | type = lib.types.str; |
| 2144 | default = "identity"; |
| 2145 | description = '' |
| 2146 | The registry's directory in that tip. It is a CUE package: the |
| 2147 | directory is the enumeration, and every `*.cue` document |
| 2148 | directly in it unifies into one registry. |
| 2149 | ''; |
| 2150 | }; |
| 2151 | |
| 2152 | interval = lib.mkOption { |
| 2153 | type = lib.types.str; |
| 2154 | default = "5m"; |
| 2155 | example = "1m"; |
| 2156 | description = '' |
| 2157 | How long between compilations. The compiler is level-triggered |
| 2158 | and idempotent — it renders the current tip and replaces an |
| 2159 | artifact only when its bytes changed — so a timer is the whole |
| 2160 | of the trigger, and a landed registry change takes effect within |
| 2161 | one interval. |
| 2162 | ''; |
| 2163 | }; |
| 2164 | }; |
| 2165 | |
| 2166 | # Machine integration for the declared backup policy. The declaration |
| 2167 | # states WHAT must hold (offsite backup, cadence, retention); these |
| 2168 | # options supply HOW on this machine — where the repository is and how |
| 2169 | # to authenticate. All are paths to files the consumer provisions |
| 2170 | # (e.g. agenix), required when the declaration enables backup. Point |
| 2171 | # them at runtime paths, never at files in the Nix store. |
| 2172 | backup = { |
| 2173 | repositoryFile = lib.mkOption { |
| 2174 | type = lib.types.nullOr lib.types.path; |
| 2175 | default = null; |
| 2176 | example = "/run/agenix/valley-restic-repo"; |
| 2177 | description = '' |
| 2178 | File containing the restic repository URL, for the sftp target |
| 2179 | e.g. `sftp://backup@backup.example.org:23//./backups/valley`. |
| 2180 | ''; |
| 2181 | }; |
| 2182 | |
| 2183 | passwordFile = lib.mkOption { |
| 2184 | type = lib.types.nullOr lib.types.path; |
| 2185 | default = null; |
| 2186 | example = "/run/agenix/valley-restic-password"; |
| 2187 | description = '' |
| 2188 | File containing the restic repository encryption password. |
| 2189 | Losing it loses the backups — keep a copy somewhere that |
| 2190 | survives this host. |
| 2191 | ''; |
| 2192 | }; |
| 2193 | |
| 2194 | sshKeyFile = lib.mkOption { |
| 2195 | type = lib.types.nullOr lib.types.path; |
| 2196 | default = null; |
| 2197 | example = "/run/agenix/valley-git-ssh-key"; |
| 2198 | description = '' |
| 2199 | SSH private key that authenticates to the sftp target. The |
| 2200 | backup service runs as root, so any identity the target |
| 2201 | authorizes works — reusing the mirror key is fine. |
| 2202 | ''; |
| 2203 | }; |
| 2204 | |
| 2205 | knownHostsFile = lib.mkOption { |
| 2206 | type = lib.types.nullOr lib.types.path; |
| 2207 | default = null; |
| 2208 | example = "/var/lib/valley-backup/known_hosts"; |
| 2209 | description = '' |
| 2210 | known_hosts file pinning the sftp target's host key. Pin from |
| 2211 | the provider's published fingerprints, not a blind ssh-keyscan. |
| 2212 | ''; |
| 2213 | }; |
| 2214 | }; |
| 2215 | |
| 2216 | # The programs the host runs, as this flake builds them |
| 2217 | # (nix/packages.nix). These options are internal: a host has no reason |
| 2218 | # to set them. The module checks set them to stand-ins with the same |
| 2219 | # binary names (nix/checks/hosts.nix), so a check that reads only what |
| 2220 | # the module renders does not change when one of the programs does. |
| 2221 | packages = { |
| 2222 | integrator = lib.mkOption { |
| 2223 | type = lib.types.package; |
| 2224 | internal = true; |
| 2225 | default = flakePackages.integrator; |
| 2226 | defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).integrator"; |
| 2227 | description = "The integrator, which the controllers and the signers publisher run."; |
| 2228 | }; |
| 2229 | |
| 2230 | identity = lib.mkOption { |
| 2231 | type = lib.types.package; |
| 2232 | internal = true; |
| 2233 | default = flakePackages.identity; |
| 2234 | defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).identity"; |
| 2235 | description = "The identity registry compiler, which valley-identity runs."; |
| 2236 | }; |
| 2237 | |
| 2238 | valleyhook = lib.mkOption { |
| 2239 | type = lib.types.package; |
| 2240 | internal = true; |
| 2241 | default = flakePackages.valleyhook; |
| 2242 | defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valleyhook"; |
| 2243 | description = "The push policy, which every pre-receive hook and the git user's login shell run."; |
| 2244 | }; |
| 2245 | |
| 2246 | restacker = lib.mkOption { |
| 2247 | type = lib.types.package; |
| 2248 | internal = true; |
| 2249 | default = flakePackages.valley-restacker; |
| 2250 | defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-restacker"; |
| 2251 | description = "The restacker, which each restacker controller runs."; |
| 2252 | }; |
| 2253 | }; |
| 2254 | }; |
| 2255 | |
| 2256 | config = lib.mkIf cfg.enable { |
| 2257 | assertions = [ |
| 2258 | { |
| 2259 | assertion = cfg.authorizedKeys != [ ]; |
| 2260 | message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable."; |
| 2261 | } |
| 2262 | ] |
| 2263 | ++ lib.optionals backupEnabled ( |
| 2264 | lib.mapAttrsToList (name: what: { |
| 2265 | assertion = cfg.backup.${name} != null; |
| 2266 | message = "services.valley.backup.${name} must be set: the host declaration enables backup, and ${what} is machine integration the consumer supplies (e.g. from its secrets)."; |
| 2267 | }) backupSecretOptions |
| 2268 | ) |
| 2269 | ++ lib.optionals cfg.integrator.enable ( |
| 2270 | lib.mapAttrsToList (name: what: { |
| 2271 | assertion = cfg.integrator.${name} != null; |
| 2272 | message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies."; |
| 2273 | }) integratorPathOptions |
| 2274 | ++ [ |
| 2275 | { |
| 2276 | assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null); |
| 2277 | message = "exactly one of services.valley.integrator.instanceProject and services.valley.integrator.instancePolicy must be set: the floor is read from the instance repository this host serves, or supplied as a directory for a host that serves none, and two sources for one layer is a question about which one won."; |
| 2278 | } |
| 2279 | # The rule the integrator reads the rendered file by |
| 2280 | # (note/signerprojects.go): every name and project is printable |
| 2281 | # ASCII with no space, so only the spaces this renders separate |
| 2282 | # words, and a name holds no plus and opens with no #, which |
| 2283 | # would make its line a comment. |
| 2284 | { |
| 2285 | assertion = |
| 2286 | let |
| 2287 | word = w: builtins.match "[!-~]+" w != null; |
| 2288 | name = n: word n && !lib.hasInfix "+" n && !lib.hasPrefix "#" n; |
| 2289 | in |
| 2290 | lib.all (n: name n && lib.all word cfg.integrator.signerProjects.${n}) ( |
| 2291 | lib.attrNames cfg.integrator.signerProjects |
| 2292 | ); |
| 2293 | message = "services.valley.integrator.signerProjects holds a name or project that is empty or not printable ASCII with no space, or a name with a plus or an opening #. The list is rendered one signer per line, its name and projects separated by spaces, and read back by that rule, so such a word would be read as some other signer or project, or refused. Write each as one such word."; |
| 2294 | } |
| 2295 | { |
| 2296 | assertion = |
| 2297 | cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject}; |
| 2298 | message = "services.valley.integrator.instanceProject names ${toString cfg.integrator.instanceProject}, which this host declaration does not serve: the floor is read from that repository's tip, so the host has to hold it."; |
| 2299 | } |
| 2300 | { |
| 2301 | assertion = cfg.integrator.user != cfg.user; |
| 2302 | message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7)."; |
| 2303 | } |
| 2304 | { |
| 2305 | assertion = integratedProjects != { }; |
| 2306 | message = "services.valley.integrator.enable is on and the host declaration protects no project — a controller only ever serves a protected target, so this would render no service at all."; |
| 2307 | } |
| 2308 | ] |
| 2309 | ) |
| 2310 | # The web publisher (web-publisher.nix) reads the registry at |
| 2311 | # identity.ref too, when its module is imported and on. |
| 2312 | ++ lib.optional (cfg.identity.enable || config.services.valley.webPublisher.enable or false) { |
| 2313 | assertion = fullRefName cfg.identity.ref; |
| 2314 | message = "services.valley.identity.ref is ${cfg.identity.ref}, which is not a full ref name. The identity registry is read at that ref, so name it whole, opening with refs/, as git check-ref-format accepts it: refs/heads/main, not main."; |
| 2315 | } |
| 2316 | ++ lib.optionals (cfg.integrator.instanceProject != null && gitProjects ? ${cfg.integrator.instanceProject}) ( |
| 2317 | let |
| 2318 | name = cfg.integrator.instanceProject; |
| 2319 | protected = gitProjects.${name}.protection.refs or [ ]; |
| 2320 | # The web publisher (web-publisher.nix) reads the registry at |
| 2321 | # identity.ref too, when its module is imported and on. |
| 2322 | publisher = config.services.valley.webPublisher.enable or false; |
| 2323 | read = |
| 2324 | lib.optional cfg.integrator.enable "refs/heads/main" |
| 2325 | ++ lib.optional (cfg.identity.enable || publisher) cfg.identity.ref; |
| 2326 | in |
| 2327 | map (ref: { |
| 2328 | assertion = lib.any (pattern: refPatternMatches pattern ref) protected; |
| 2329 | message = "services.valley.integrator.instanceProject names ${name}, whose ${ref} is not protected: the floor and the registry are read from it, so any key that can push could rewrite them. Declare a protection block for ${name} covering ${ref}."; |
| 2330 | }) read |
| 2331 | ) |
| 2332 | ++ [ |
| 2333 | { |
| 2334 | assertion = !(lib.any (v: builtins.match ".*[\"'\\\\].*" v != null) ( |
| 2335 | sshdValues "AcceptEnv" ++ sshdValues "SetEnv" |
| 2336 | )); |
| 2337 | message = "sshd's AcceptEnv or SetEnv here holds a quote or a backslash, which sshd unpicks and this module does not. Write each name plainly, separated by spaces, so what is checked is what sshd reads."; |
| 2338 | } |
| 2339 | { |
| 2340 | assertion = !(lib.any boundaryVariable (sshdValues "AcceptEnv")); |
| 2341 | message = "sshd accepts ${lib.concatStringsSep " " (lib.filter boundaryVariable (sshdValues "AcceptEnv"))} from the client (AcceptEnv), a pattern that admits ${principalEnv} or a GIT_ variable. The git user's shell drops them, and sshd must not offer them either. Remove the pattern."; |
| 2342 | } |
| 2343 | { |
| 2344 | assertion = !(lib.any (v: boundaryVariable (lib.head (lib.splitString "=" v))) (sshdValues "SetEnv")); |
| 2345 | message = "sshd sets ${principalEnv} or a GIT_ variable itself (SetEnv). Remove it."; |
| 2346 | } |
| 2347 | { |
| 2348 | assertion = lib.all (v: lib.toLower v == "no") (sshdValues "PermitUserEnvironment"); |
| 2349 | message = "sshd's PermitUserEnvironment must be no: the git user's shell derives the principal from the authenticated key, and nothing a key's entry or ~/.ssh/environment sets is the push boundary's to read."; |
| 2350 | } |
| 2351 | { |
| 2352 | assertion = conflictingKeys == { }; |
| 2353 | message = "the git user's authorized keys name ${lib.concatStringsSep ", " (lib.attrNames conflictingKeys)} under more than one principal tag (an untagged entry counts as one): sshd authorizes a key by the first entry naming it, so which principal it pushes as would depend on file order. Declare each key once."; |
| 2354 | } |
| 2355 | { |
| 2356 | assertion = config.users.users.${cfg.user}.openssh.authorizedKeys.keyFiles == [ ]; |
| 2357 | message = "users.users.${cfg.user}.openssh.authorizedKeys.keyFiles must be empty: the git user's keys carry the principal tag the push policy reads, so they are declared in services.valley.authorizedKeys, where their tags can be checked."; |
| 2358 | } |
| 2359 | ] |
| 2360 | ++ lib.optionals cfg.identity.enable [ |
| 2361 | { |
| 2362 | assertion = cfg.integrator.instanceProject != null; |
| 2363 | message = "services.valley.integrator.instanceProject must be set: the identity registry is read from the served instance repository's integrated tip, so the host has to hold that repository."; |
| 2364 | } |
| 2365 | { |
| 2366 | assertion = cfg.integrator.knownSignersFile == null; |
| 2367 | message = "services.valley.integrator.knownSignersFile must be unset: the registry compiles that file (${identityKnownSigners}), and two sources for one file is a question about which one won."; |
| 2368 | } |
| 2369 | ] |
| 2370 | ++ lib.optionals cfg.worker.enable ( |
| 2371 | let |
| 2372 | name = cfg.worker.signerName; |
| 2373 | listed = cfg.integrator.signerProjects.${name} or null; |
| 2374 | sorted = l: lib.sort lib.lessThan (lib.unique l); |
| 2375 | unserved = lib.filter (p: !(gitProjects ? ${p})) cfg.worker.projects; |
| 2376 | in |
| 2377 | [ |
| 2378 | { |
| 2379 | assertion = cfg.integrator.enable; |
| 2380 | message = "services.valley.worker.enable needs services.valley.integrator.enable: the worker builds evidence for this host's controllers, and they are what restrict its key to its projects."; |
| 2381 | } |
| 2382 | { |
| 2383 | assertion = cfg.integrator.instanceProject != null; |
| 2384 | message = "services.valley.worker.enable needs services.valley.integrator.instanceProject: the worker finds this host's projects through the instance repository, as valley pending --repo does."; |
| 2385 | } |
| 2386 | { |
| 2387 | assertion = cfg.worker.projects != [ ] && unserved == [ ]; |
| 2388 | message = "services.valley.worker.projects must name at least one project, and only projects this host serves${ |
| 2389 | lib.optionalString (unserved != [ ]) ", and it names ${lib.concatStringsSep ", " unserved}" |
| 2390 | }."; |
| 2391 | } |
| 2392 | # The restriction (oc-13c6bd6). Every controller that shares the |
| 2393 | # known-signers file counts a key it holds in every project, so a |
| 2394 | # worker whose key is not restricted would be trusted for projects |
| 2395 | # it never builds. The module sets the entry to the worker's |
| 2396 | # projects below; this holds a host that sets it itself. |
| 2397 | { |
| 2398 | assertion = listed != null && sorted listed == sorted cfg.worker.projects; |
| 2399 | message = "services.valley.integrator.signerProjects must restrict ${name}, the worker's signer, to exactly the worker's projects: without the restriction, every controller that holds the worker's key counts its evidence in every project. Set services.valley.integrator.signerProjects.\"${name}\" = [ ${ |
| 2400 | lib.concatMapStringsSep " " (p: "\"${p}\"") cfg.worker.projects |
| 2401 | } ], or leave the entry unset and the module sets it to the worker's projects."; |
| 2402 | } |
| 2403 | { |
| 2404 | assertion = name != integratorName; |
| 2405 | message = "services.valley.worker.signerName must differ from ${integratorName}, the name the controllers sign under: a controller's signature never counts as check evidence, and a controller refuses to start when the signer projects list names it."; |
| 2406 | } |
| 2407 | { |
| 2408 | assertion = cfg.buildSlice.enable; |
| 2409 | message = "services.valley.worker.enable needs services.valley.buildSlice.enable: the worker builds through this host's nix daemon, and only the build slice caps what it makes the daemon do. The slice caps every build the daemon runs, for every user, so turning it on is a decision about the host, made on its own."; |
| 2410 | } |
| 2411 | { |
| 2412 | assertion = config.services.openssh.enable && config.nix.enable; |
| 2413 | message = "services.valley.worker.enable needs services.openssh.enable and nix.enable: the worker reaches this host's repositories through its sshd, and builds through its nix daemon."; |
| 2414 | } |
| 2415 | ] |
| 2416 | ) |
| 2417 | ++ lib.optionals cfg.restacker.enable ( |
| 2418 | let |
| 2419 | unserved = lib.filter (p: !(gitProjects ? ${p})) cfg.restacker.projects; |
| 2420 | in |
| 2421 | [ |
| 2422 | { |
| 2423 | assertion = cfg.restacker.projects != [ ] && unserved == [ ]; |
| 2424 | message = "services.valley.restacker.projects must name at least one project, and only projects this host serves${ |
| 2425 | lib.optionalString (unserved != [ ]) ", and it names ${lib.concatStringsSep ", " unserved}" |
| 2426 | }."; |
| 2427 | } |
| 2428 | { |
| 2429 | assertion = cfg.restacker.sshKeyFile != null; |
| 2430 | message = "services.valley.restacker.sshKeyFile must be set: the restacker pushes over this host's sshd with a key the operator provisions outside the Nix store."; |
| 2431 | } |
| 2432 | { |
| 2433 | assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null); |
| 2434 | message = "services.valley.restacker.enable needs exactly one of services.valley.integrator.instanceProject and services.valley.integrator.instancePolicy: the restacker reads the cap on its versions from the policy the controllers compose, over the floor they read."; |
| 2435 | } |
| 2436 | { |
| 2437 | assertion = config.services.openssh.enable; |
| 2438 | message = "services.valley.restacker.enable needs services.openssh.enable: the restacker reaches this host's repositories through its sshd."; |
| 2439 | } |
| 2440 | ] |
| 2441 | ); |
| 2442 | |
| 2443 | # The worker's signer counts in the worker's projects and no others |
| 2444 | # (oc-e092038). On a host that sets neither list, the worker builds for |
| 2445 | # every project the controllers serve, and the controllers count its |
| 2446 | # evidence in exactly those. A host that narrows the worker's projects |
| 2447 | # narrows the signer's entry with them. The entry is a default, so a |
| 2448 | # host's own entry replaces it, and the assertion above holds that |
| 2449 | # entry to the worker's projects. |
| 2450 | services.valley.integrator.signerProjects = lib.mkIf cfg.worker.enable { |
| 2451 | ${cfg.worker.signerName} = lib.mkDefault cfg.worker.projects; |
| 2452 | }; |
| 2453 | |
| 2454 | users.groups.${cfg.group} = { }; |
| 2455 | |
| 2456 | users.users.${cfg.user} = { |
| 2457 | isSystemUser = true; |
| 2458 | group = cfg.group; |
| 2459 | home = cfg.dataDir; |
| 2460 | # The valley's shell, in front of git-shell: it derives the principal |
| 2461 | # from the authenticated key, drops the GIT_ environment, and pauses |
| 2462 | # pushes until valley-init has converged. git-shell then allows only |
| 2463 | # git-upload-pack, git-receive-pack and git-upload-archive, and rejects |
| 2464 | # interactive logins (no ~/git-shell-commands). |
| 2465 | shell = "${gitShell}/bin/valley-git-shell"; |
| 2466 | openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys; |
| 2467 | }; |
| 2468 | |
| 2469 | # The integrator's own account. No shell, no keys, no home of its own |
| 2470 | # beyond the state directory its units get; the git group is the only |
| 2471 | # thing it holds. |
| 2472 | users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable { |
| 2473 | isSystemUser = true; |
| 2474 | group = cfg.group; |
| 2475 | home = "/var/lib/valley-integrator"; |
| 2476 | description = "The valley integrator"; |
| 2477 | }; |
| 2478 | |
| 2479 | # The worker's own account. Its group is its own, not the git group, so |
| 2480 | # it can neither read nor write the repositories on disk: it reaches |
| 2481 | # them as an ssh client, as anyone else does. |
| 2482 | users.users.valley-worker = lib.mkIf cfg.worker.enable { |
| 2483 | isSystemUser = true; |
| 2484 | group = "valley-worker"; |
| 2485 | home = workerDir; |
| 2486 | description = "The valley check worker"; |
| 2487 | }; |
| 2488 | users.groups.valley-worker = lib.mkIf cfg.worker.enable { }; |
| 2489 | # The writers of the integrator's wake directories: the git user, whose |
| 2490 | # post-receive hook marks a push, and the integrator's user, whose |
| 2491 | # instance controller marks a floor landing. The worker is not in it. |
| 2492 | users.groups.${integratorWakeGroup} = lib.mkIf cfg.integrator.enable { |
| 2493 | members = [ |
| 2494 | cfg.user |
| 2495 | cfg.integrator.user |
| 2496 | ]; |
| 2497 | }; |
| 2498 | users.groups.${workerWakeGroup} = lib.mkIf cfg.worker.enable { |
| 2499 | members = [ |
| 2500 | cfg.user |
| 2501 | cfg.integrator.user |
| 2502 | ]; |
| 2503 | }; |
| 2504 | |
| 2505 | # The restacker's own account. Its group is its own, not the git group, |
| 2506 | # so it can neither read nor write the repositories on disk, and it is |
| 2507 | # in no group that reads the integrator's or the worker's keys: it |
| 2508 | # reaches the repositories as an ssh client, as its own principal. |
| 2509 | users.users.valley-restacker = lib.mkIf cfg.restacker.enable { |
| 2510 | isSystemUser = true; |
| 2511 | group = "valley-restacker"; |
| 2512 | home = "/var/lib/${restackerStateName}"; |
| 2513 | description = "The valley restacker"; |
| 2514 | }; |
| 2515 | users.groups.valley-restacker = lib.mkIf cfg.restacker.enable { }; |
| 2516 | |
| 2517 | services.openssh.enable = lib.mkDefault true; |
| 2518 | |
| 2519 | # The git user's key files, named in its Match block so no other file |
| 2520 | # can authorize a key for it. The declared keys come first, and they stay |
| 2521 | # authorized beside the compiled ones: a compiled file can only ever |
| 2522 | # add, so an empty or missing one — a first boot before the first |
| 2523 | # compilation, a registry that lost an entry, a bug here — cannot take |
| 2524 | # the git user's access away. Which is the point: the assertion above |
| 2525 | # keeps at least one key declared, and that key is the way back in. |
| 2526 | # |
| 2527 | # Nothing else authorizes a key for the git user. ~/.ssh/authorized_keys |
| 2528 | # under its home is not read, and no AuthorizedKeysCommand runs, so every |
| 2529 | # entry a pusher can arrive through carries the tag this module or the |
| 2530 | # compiler wrote, and the assertions and the compiler hold those to one |
| 2531 | # tag per key. |
| 2532 | # |
| 2533 | # Belt-and-braces hardening for the git user beside it. The trailing |
| 2534 | # `Match All` closes the block so it can't scope directives appended to |
| 2535 | # sshd_config after this snippet. |
| 2536 | services.openssh.extraConfig = '' |
| 2537 | Match User ${cfg.user} |
| 2538 | AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u${lib.optionalString cfg.identity.enable " ${identityAuthorizedKeys}"} |
| 2539 | AuthorizedKeysCommand none |
| 2540 | ExposeAuthInfo yes |
| 2541 | AllowTcpForwarding no |
| 2542 | AllowAgentForwarding no |
| 2543 | X11Forwarding no |
| 2544 | PermitTunnel no |
| 2545 | Match All |
| 2546 | ''; |
| 2547 | |
| 2548 | # git-shell spawns git-receive-pack/git-upload-pack from PATH |
| 2549 | environment.systemPackages = [ pkgs.git ]; |
| 2550 | |
| 2551 | systemd.tmpfiles.rules = [ |
| 2552 | "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -" |
| 2553 | ] |
| 2554 | ++ lib.optionals cfg.bus.enable [ |
| 2555 | "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -" |
| 2556 | ] |
| 2557 | ++ lib.optionals cfg.worker.enable [ |
| 2558 | "d ${workerDir} 0700 valley-worker valley-worker - -" |
| 2559 | "d ${workerWakeDir} 0770 valley-worker ${workerWakeGroup} - -" |
| 2560 | ] |
| 2561 | ++ lib.optionals cfg.integrator.enable ( |
| 2562 | [ "d ${integratorWakeRoot} 0755 root root - -" ] |
| 2563 | ++ map ( |
| 2564 | name: "d ${integratorWakeDir name} 0770 ${cfg.integrator.user} ${integratorWakeGroup} - -" |
| 2565 | ) (lib.attrNames integratedProjects) |
| 2566 | ); |
| 2567 | |
| 2568 | # The bus itself. It runs as the git user — the store directory lives in |
| 2569 | # that user's data — but the sandbox is what confines it: the unit can |
| 2570 | # write nowhere except its store directory. |
| 2571 | systemd.services.valley-bus = lib.mkIf cfg.bus.enable { |
| 2572 | description = "The valley event bus (NATS JetStream)"; |
| 2573 | wantedBy = [ "multi-user.target" ]; |
| 2574 | after = [ |
| 2575 | "network.target" |
| 2576 | "systemd-tmpfiles-setup.service" |
| 2577 | ]; |
| 2578 | unitConfig.RequiresMountsFor = cfg.bus.storeDir; |
| 2579 | serviceConfig = { |
| 2580 | ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}"; |
| 2581 | Restart = "on-failure"; |
| 2582 | User = cfg.user; |
| 2583 | Group = cfg.group; |
| 2584 | LimitNOFILE = 65536; |
| 2585 | NoNewPrivileges = true; |
| 2586 | ProtectSystem = "strict"; |
| 2587 | ReadWritePaths = [ cfg.bus.storeDir ]; |
| 2588 | ProtectHome = true; |
| 2589 | PrivateTmp = true; |
| 2590 | PrivateDevices = true; |
| 2591 | ProtectClock = true; |
| 2592 | ProtectHostname = true; |
| 2593 | ProtectKernelLogs = true; |
| 2594 | ProtectKernelModules = true; |
| 2595 | ProtectKernelTunables = true; |
| 2596 | ProtectControlGroups = true; |
| 2597 | ProtectProc = "invisible"; |
| 2598 | RestrictAddressFamilies = [ |
| 2599 | "AF_INET" |
| 2600 | "AF_INET6" |
| 2601 | "AF_UNIX" |
| 2602 | ]; |
| 2603 | RestrictNamespaces = true; |
| 2604 | RestrictRealtime = true; |
| 2605 | RestrictSUIDSGID = true; |
| 2606 | LockPersonality = true; |
| 2607 | CapabilityBoundingSet = ""; |
| 2608 | SystemCallArchitectures = "native"; |
| 2609 | SystemCallFilter = [ "@system-service" ]; |
| 2610 | UMask = "0077"; |
| 2611 | }; |
| 2612 | }; |
| 2613 | |
| 2614 | # The stream is config, not state: (re)created idempotently on every |
| 2615 | # boot, capturing everything under valley.>. An existing stream — and |
| 2616 | # the events in it — is left untouched. |
| 2617 | systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable { |
| 2618 | description = "Create the valley event stream"; |
| 2619 | wantedBy = [ "multi-user.target" ]; |
| 2620 | requires = [ "valley-bus.service" ]; |
| 2621 | after = [ "valley-bus.service" ]; |
| 2622 | serviceConfig = { |
| 2623 | Type = "oneshot"; |
| 2624 | User = cfg.user; |
| 2625 | Group = cfg.group; |
| 2626 | }; |
| 2627 | path = [ pkgs.natscli ]; |
| 2628 | script = '' |
| 2629 | # The server needs a moment to accept connections after startup. |
| 2630 | for _ in $(seq 1 50); do |
| 2631 | nats --server ${busUrl} stream ls >/dev/null 2>&1 && break |
| 2632 | sleep 0.2 |
| 2633 | done |
| 2634 | if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then |
| 2635 | nats --server ${busUrl} stream add valley \ |
| 2636 | --subjects 'valley.>' --storage file --defaults |
| 2637 | fi |
| 2638 | ''; |
| 2639 | }; |
| 2640 | |
| 2641 | # Create missing bare repos and (re)wire the managed hooks on every |
| 2642 | # activation where the declaration changed. |
| 2643 | systemd.services.valley-init = { |
| 2644 | description = "Initialize the valley host's bare git repositories"; |
| 2645 | wantedBy = [ "multi-user.target" ]; |
| 2646 | after = [ "systemd-tmpfiles-setup.service" ]; |
| 2647 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 2648 | serviceConfig = { |
| 2649 | Type = "oneshot"; |
| 2650 | User = cfg.user; |
| 2651 | Group = cfg.group; |
| 2652 | }; |
| 2653 | path = [ |
| 2654 | pkgs.git |
| 2655 | pkgs.diffutils |
| 2656 | ]; |
| 2657 | # Everything init can wire is wired before it fails. A conflict in one |
| 2658 | # repository is reported, the rest of the host is still converged, |
| 2659 | # and only then does the unit fail, so the activation fails loudly |
| 2660 | # without leaving another repository's hook out of date. |
| 2661 | script = '' |
| 2662 | # Pushes pause the moment a convergence starts, and resume only once |
| 2663 | # it has finished: the record is removed first and written last. |
| 2664 | rm -f ${convergedRecord} |
| 2665 | ${valleyInitBody} |
| 2666 | printf '%s\n' ${convergenceId} > ${convergedRecord}.tmp |
| 2667 | mv -f ${convergedRecord}.tmp ${convergedRecord} |
| 2668 | ''; |
| 2669 | }; |
| 2670 | |
| 2671 | # The registry compiler, on a timer. It renders the instance |
| 2672 | # repository's integrated tip into the two artifacts the gates read; |
| 2673 | # nothing else on the host writes them. |
| 2674 | # |
| 2675 | # It runs as the git user rather than under an identity of its own, |
| 2676 | # which is the one place this module steps back from the service split |
| 2677 | # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by |
| 2678 | # anyone but root or the account it authorizes, so the choice is the git |
| 2679 | # user or root, and the git user is the smaller grant. |
| 2680 | # |
| 2681 | # Level-triggered, like the rest: a compilation reads the current tip |
| 2682 | # and replaces an artifact only when its bytes changed, so re-running is |
| 2683 | # free and the timer needs no coordination with anything. |
| 2684 | systemd.services.valley-identity = lib.mkIf cfg.identity.enable { |
| 2685 | description = "Compile the valley identity registry into what the gates check"; |
| 2686 | wantedBy = [ "multi-user.target" ]; |
| 2687 | after = [ "valley-init.service" ]; |
| 2688 | requires = [ "valley-init.service" ]; |
| 2689 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 2690 | serviceConfig = { |
| 2691 | Type = "oneshot"; |
| 2692 | ExecStart = identityCommand; |
| 2693 | User = cfg.user; |
| 2694 | Group = cfg.group; |
| 2695 | StateDirectory = identityStateName; |
| 2696 | # sshd walks every directory above an authorized-keys file and |
| 2697 | # refuses a group- or world-writable one, so the state directory is |
| 2698 | # 0755 deliberately rather than the 0700 a service's state usually |
| 2699 | # takes. Nothing secret lives in it: a registry is public keys. |
| 2700 | StateDirectoryMode = "0755"; |
| 2701 | NoNewPrivileges = true; |
| 2702 | ProtectSystem = "strict"; |
| 2703 | ReadWritePaths = [ identityStateDir ]; |
| 2704 | ProtectHome = true; |
| 2705 | PrivateTmp = true; |
| 2706 | PrivateDevices = true; |
| 2707 | ProtectClock = true; |
| 2708 | ProtectHostname = true; |
| 2709 | ProtectKernelLogs = true; |
| 2710 | ProtectKernelModules = true; |
| 2711 | ProtectKernelTunables = true; |
| 2712 | ProtectControlGroups = true; |
| 2713 | ProtectProc = "invisible"; |
| 2714 | RestrictAddressFamilies = [ "AF_UNIX" ]; |
| 2715 | RestrictNamespaces = true; |
| 2716 | RestrictRealtime = true; |
| 2717 | RestrictSUIDSGID = true; |
| 2718 | LockPersonality = true; |
| 2719 | CapabilityBoundingSet = ""; |
| 2720 | SystemCallArchitectures = "native"; |
| 2721 | SystemCallFilter = [ "@system-service" ]; |
| 2722 | UMask = "0022"; |
| 2723 | }; |
| 2724 | }; |
| 2725 | |
| 2726 | systemd.timers.valley-identity = lib.mkIf cfg.identity.enable { |
| 2727 | description = "Re-compile the valley identity registry"; |
| 2728 | wantedBy = [ "timers.target" ]; |
| 2729 | timerConfig = { |
| 2730 | OnBootSec = "1m"; |
| 2731 | OnUnitActiveSec = cfg.identity.interval; |
| 2732 | }; |
| 2733 | }; |
| 2734 | |
| 2735 | # The signers publication, refs/the-valley/signers, is written by a |
| 2736 | # oneshot of its own. It runs as the git user, which owns the instance |
| 2737 | # repository, and its sandbox lets it write that repository and nothing |
| 2738 | # else. It is not part of valley-init, which runs only on activation, |
| 2739 | # nor of the registry compiler, whose sandbox writes only its state |
| 2740 | # directory. Only the host's machinery writes the ref, never a push: |
| 2741 | # the hook refuses every push to it. This unit writes it, and the |
| 2742 | # integrator can, being in the group the repository is shared with |
| 2743 | # because it lands code there. |
| 2744 | # |
| 2745 | # What starts it: every boot and every activation, after valley-init, |
| 2746 | # which covers a changed signing name, signers path or signer projects |
| 2747 | # list; and the path |
| 2748 | # unit below, whenever the known-signers file changes, which covers |
| 2749 | # each compilation that changed it and a hand-provisioned file being |
| 2750 | # replaced. A run reads the current file and name and writes the ref |
| 2751 | # only when the tree it makes differs, so a run with nothing new is |
| 2752 | # free. Both values are in one tree under one ref, so a client never |
| 2753 | # reads one value without the other. A run holds a lock in the |
| 2754 | # instance repository from reading the file to moving the ref, so two |
| 2755 | # runs take turns, and one that read an older file cannot publish it |
| 2756 | # over a newer one. The ref also moves with a compare-and-swap. |
| 2757 | # |
| 2758 | # A run that cannot read the file, or reads one that is not a list of |
| 2759 | # verifier keys, fails and leaves the last publication in place. That |
| 2760 | # is the file the controllers were given before it changed, and the |
| 2761 | # journal says why. A file with no key in it, as the compiler writes |
| 2762 | # once every signing key is revoked, is published, so clients stop |
| 2763 | # verifying with the revoked keys. |
| 2764 | systemd.services.valley-signers = lib.mkIf publishesSigners { |
| 2765 | description = "Publish what clients verify the valley integrator's transfer statements with"; |
| 2766 | wantedBy = [ "multi-user.target" ]; |
| 2767 | after = [ "valley-init.service" ] ++ lib.optional cfg.identity.enable "valley-identity.service"; |
| 2768 | requires = [ "valley-init.service" ]; |
| 2769 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 2770 | serviceConfig = { |
| 2771 | Type = "oneshot"; |
| 2772 | ExecStart = signersCommand; |
| 2773 | User = cfg.user; |
| 2774 | Group = cfg.group; |
| 2775 | NoNewPrivileges = true; |
| 2776 | ProtectSystem = "strict"; |
| 2777 | ReadWritePaths = [ instanceRepo ] ++ lib.optional cfg.worker.enable workerWakeDir; |
| 2778 | ProtectHome = true; |
| 2779 | PrivateTmp = true; |
| 2780 | PrivateDevices = true; |
| 2781 | ProtectClock = true; |
| 2782 | ProtectHostname = true; |
| 2783 | ProtectKernelLogs = true; |
| 2784 | ProtectKernelModules = true; |
| 2785 | ProtectKernelTunables = true; |
| 2786 | ProtectControlGroups = true; |
| 2787 | ProtectProc = "invisible"; |
| 2788 | RestrictAddressFamilies = [ "AF_UNIX" ]; |
| 2789 | RestrictNamespaces = true; |
| 2790 | RestrictRealtime = true; |
| 2791 | RestrictSUIDSGID = true; |
| 2792 | LockPersonality = true; |
| 2793 | CapabilityBoundingSet = ""; |
| 2794 | SystemCallArchitectures = "native"; |
| 2795 | SystemCallFilter = [ "@system-service" ]; |
| 2796 | # The instance repository is always one the integrator serves, since |
| 2797 | # it has to be protected, so it is group-shared and its directories |
| 2798 | # are setgid. With the default umask, git would chmod each directory |
| 2799 | # it makes to add group write, setgid bit included, and |
| 2800 | # RestrictSUIDSGID refuses that chmod. Group write from the start |
| 2801 | # leaves git nothing to chmod, as for the controllers. |
| 2802 | UMask = "0002"; |
| 2803 | }; |
| 2804 | }; |
| 2805 | |
| 2806 | systemd.paths.valley-signers = lib.mkIf publishesSigners { |
| 2807 | description = "Watch the known-signers file the valley integrator reads"; |
| 2808 | wantedBy = [ "multi-user.target" ]; |
| 2809 | pathConfig.PathChanged = knownSigners; |
| 2810 | }; |
| 2811 | |
| 2812 | # One controller per served project, as instances of a single template: |
| 2813 | # the units differ only in the repository they serve, which is the |
| 2814 | # instance name. One long-lived `watch` per project, rather than a timer |
| 2815 | # or a path unit starting `reconcile`: the binary watches its own wake |
| 2816 | # directory, follows a landing with another pass, and keeps its |
| 2817 | # interval as the recovery pass. A unit started for each mark would |
| 2818 | # repeat the start's sweep and could not interrupt a pass in progress |
| 2819 | # anyway, and starting a service that is already running wakes nothing. |
| 2820 | systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable { |
| 2821 | description = "The valley integrator for %i"; |
| 2822 | after = [ |
| 2823 | "network.target" |
| 2824 | "valley-init.service" |
| 2825 | "systemd-tmpfiles-setup.service" |
| 2826 | ] |
| 2827 | ++ lib.optional cfg.bus.enable "valley-bus-init.service" |
| 2828 | ++ lib.optional cfg.identity.enable "valley-identity.service"; |
| 2829 | requires = [ "valley-init.service" ]; |
| 2830 | # Wants, not requires: a controller reads the compiled signers file, |
| 2831 | # so it starts after the first compilation — but a compilation that |
| 2832 | # failed must not keep the controllers down. One that finds no file |
| 2833 | # says so and restarts, which is the same loop and a louder one. |
| 2834 | wants = lib.optional cfg.identity.enable "valley-identity.service"; |
| 2835 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 2836 | # nix is not pinned, for the reason the integrator package does not |
| 2837 | # pin it: a check's input closure must be recomputed by the nix this |
| 2838 | # machine actually runs. Everything else a controller drives is |
| 2839 | # pinned inside the wrapper. |
| 2840 | path = [ config.nix.package ]; |
| 2841 | # The repositories belong to the git user and the controller does |
| 2842 | # not, so git refuses to touch them as dubiously owned. The exception |
| 2843 | # rides in the unit's environment, for two reasons. GIT_CONFIG_* is |
| 2844 | # command-scope config, which is protected config, so safe.directory |
| 2845 | # is honoured from it — a repository-scoped setting would be ignored, |
| 2846 | # deliberately. And every git the controller drives is a child of |
| 2847 | # this unit, whether run by the integrator itself or by attest or the |
| 2848 | # deriver, so one environment covers all of them. |
| 2849 | # |
| 2850 | # One repository per instance: never a global gitconfig, never a |
| 2851 | # wildcard. Every other repository on the host stays refused. Linked |
| 2852 | # worktrees need no entry of their own — the controller creates them, |
| 2853 | # so it owns them, and git checks the worktree and its gitdir rather |
| 2854 | # than the repository they point at. |
| 2855 | # |
| 2856 | # TMPDIR is the same kind of wiring, for the same reason. A verdict |
| 2857 | # wants a checkout of the tip on disk, and the integrator asks for one |
| 2858 | # the ordinary way — a temporary directory, then a linked worktree in |
| 2859 | # it. The sandbox below leaves no writable temporary directory, so |
| 2860 | # every tick died on `could not create leading directories`. The |
| 2861 | # scratch belongs under the state directory the unit already has: |
| 2862 | # writable by construction, owned by this service, and gone when the |
| 2863 | # service's state is. Setting it in the environment rather than |
| 2864 | # teaching the binary a flag covers every process in the unit at once |
| 2865 | # — the integrator, attest, the deriver, and the git each of them runs |
| 2866 | # all read TMPDIR, and all of them want scratch in the same place. |
| 2867 | # |
| 2868 | # A second exception, for the instance repository. Every controller |
| 2869 | # reads the group's floor from that repository's tip, and it need not |
| 2870 | # be the project the controller serves — the controller for one |
| 2871 | # project reads the floor out of another project's repository, which |
| 2872 | # it likewise does not own. Without the exception git refuses it as |
| 2873 | # dubiously owned and every pass fails, exactly as it did for the |
| 2874 | # served repository. Two entries, both named; still never a wildcard. |
| 2875 | # |
| 2876 | # Reading needs no sandbox entry beside it. ProtectSystem=strict |
| 2877 | # leaves the filesystem readable and only takes write away, so the |
| 2878 | # ReadWritePaths list above stays the list of what may be written, |
| 2879 | # which is what makes it worth reading. What read does need is a |
| 2880 | # filesystem grant, and valley-init makes it: the instance repository |
| 2881 | # is group-readable whether or not it is one of the served projects. |
| 2882 | environment = { |
| 2883 | GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1"; |
| 2884 | GIT_CONFIG_KEY_0 = "safe.directory"; |
| 2885 | GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git"; |
| 2886 | TMPDIR = integratorStateDir; |
| 2887 | } |
| 2888 | // lib.optionalAttrs (instanceRepo != null) { |
| 2889 | GIT_CONFIG_KEY_1 = "safe.directory"; |
| 2890 | GIT_CONFIG_VALUE_1 = instanceRepo; |
| 2891 | }; |
| 2892 | serviceConfig = { |
| 2893 | ExecStart = integratorCommand; |
| 2894 | EnvironmentFile = "-${integratorEnv}/%i"; |
| 2895 | Restart = "on-failure"; |
| 2896 | RestartSec = "10s"; |
| 2897 | User = cfg.integrator.user; |
| 2898 | Group = cfg.group; |
| 2899 | StateDirectory = integratorStateName; |
| 2900 | StateDirectoryMode = "0700"; |
| 2901 | WorkingDirectory = integratorStateDir; |
| 2902 | NoNewPrivileges = true; |
| 2903 | ProtectSystem = "strict"; |
| 2904 | # Everything the controller may write, named where a reader of the |
| 2905 | # unit meets it. Under ProtectSystem=strict the rest of the |
| 2906 | # filesystem is read-only, so this list is the whole of what the |
| 2907 | # service can touch, and it is worth being able to read it as such |
| 2908 | # rather than as the exceptions plus whatever else is implied. |
| 2909 | # |
| 2910 | # Its own directory: its state, and the scratch root TMPDIR names. |
| 2911 | # A declaration says it here rather than relying on the state |
| 2912 | # directory being read-write by virtue of being declared, which is |
| 2913 | # not something this unit found to be true. |
| 2914 | # |
| 2915 | # The one repository it serves, and the nix daemon's socket — |
| 2916 | # recomputing a closure means asking the daemon, and connecting to |
| 2917 | # a unix socket needs write access to it. |
| 2918 | # |
| 2919 | # Its own wake directory, where it removes due. |
| 2920 | # The leading - starts the controller even when the directory is |
| 2921 | # missing; it then says so and passes on its interval. |
| 2922 | # |
| 2923 | # The worker's wake directory, where a landing marks the worker due. |
| 2924 | # |
| 2925 | # The instance project's controller also writes the floor readers' |
| 2926 | # wake directories, in the drop-in below, and no other controller |
| 2927 | # does. |
| 2928 | ReadWritePaths = [ |
| 2929 | integratorStateDir |
| 2930 | "${cfg.dataDir}/%i.git" |
| 2931 | "/nix/var/nix/daemon-socket" |
| 2932 | "-${integratorWakeRoot}/%i" |
| 2933 | ] |
| 2934 | ++ lib.optional cfg.worker.enable workerWakeDir; |
| 2935 | ProtectHome = true; |
| 2936 | PrivateTmp = true; |
| 2937 | PrivateDevices = true; |
| 2938 | ProtectClock = true; |
| 2939 | ProtectHostname = true; |
| 2940 | ProtectKernelLogs = true; |
| 2941 | ProtectKernelModules = true; |
| 2942 | ProtectKernelTunables = true; |
| 2943 | ProtectControlGroups = true; |
| 2944 | ProtectProc = "invisible"; |
| 2945 | RestrictAddressFamilies = [ |
| 2946 | "AF_INET" |
| 2947 | "AF_INET6" |
| 2948 | "AF_UNIX" |
| 2949 | ]; |
| 2950 | RestrictNamespaces = true; |
| 2951 | RestrictRealtime = true; |
| 2952 | RestrictSUIDSGID = true; |
| 2953 | LockPersonality = true; |
| 2954 | CapabilityBoundingSet = ""; |
| 2955 | SystemCallArchitectures = "native"; |
| 2956 | SystemCallFilter = [ "@system-service" ]; |
| 2957 | # Group write, not the bus unit's 0077: the git user owns these |
| 2958 | # repositories and has to stay able to write what a controller |
| 2959 | # leaves in them. |
| 2960 | UMask = "0002"; |
| 2961 | }; |
| 2962 | }; |
| 2963 | |
| 2964 | # The instance project's controller marks every floor reader after a |
| 2965 | # floor landing, so its sandbox may write their wake directories. A |
| 2966 | # drop-in on that one instance adds them to the template's list, which |
| 2967 | # it extends. It is written as text, and sets nothing else: a drop-in |
| 2968 | # declared as a service would carry the default PATH, which would |
| 2969 | # replace the template's and its nix. |
| 2970 | systemd.units."valley-integrator@${toString cfg.integrator.instanceProject}.service" = |
| 2971 | lib.mkIf (cfg.integrator.enable && floorReaders != [ ]) |
| 2972 | { |
| 2973 | overrideStrategy = "asDropin"; |
| 2974 | text = '' |
| 2975 | [Service] |
| 2976 | ${lib.concatMapStrings (r: "ReadWritePaths=-${integratorWakeDir r}\n") floorReaders}''; |
| 2977 | }; |
| 2978 | |
| 2979 | # What pushes the mirrors: a path unit per published project, watching |
| 2980 | # its publish queue, and the drain it starts. |
| 2981 | systemd.paths."valley-publish@" = lib.mkIf (publishedProjects != { }) { |
| 2982 | description = "Watch the publish queue of %i"; |
| 2983 | pathConfig.DirectoryNotEmpty = "${cfg.dataDir}/%i.git/${publishQueueName}"; |
| 2984 | }; |
| 2985 | |
| 2986 | # It runs as the git user, with ssh on its path, because the mirror |
| 2987 | # credentials are that user's. Each run drains the whole queue, so starts |
| 2988 | # are at most one per queued move, and a burst of moves must not trip |
| 2989 | # systemd's start limit and leave the queue undrained. A run is bounded |
| 2990 | # instead: one that hangs on a mirror is cut off after 15 minutes, and |
| 2991 | # systemd stops its whole cgroup, so nothing it started outlives it. A |
| 2992 | # run that fails or is cut off leaves its moves queued, and systemd |
| 2993 | # starts it again after a delay that grows from 30 seconds to 15 minutes, |
| 2994 | # until a run succeeds. While it waits to restart, the unit is not |
| 2995 | # inactive, so the path unit does not start it again sooner. |
| 2996 | systemd.services."valley-publish@" = lib.mkIf (publishedProjects != { }) { |
| 2997 | description = "Push the moves queued on %i to its mirrors"; |
| 2998 | after = [ "valley-init.service" ]; |
| 2999 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 3000 | startLimitIntervalSec = 0; |
| 3001 | path = [ config.programs.ssh.package ]; |
| 3002 | serviceConfig = { |
| 3003 | Type = "oneshot"; |
| 3004 | ExecStart = "${publishDrains}/%i"; |
| 3005 | User = cfg.user; |
| 3006 | Group = cfg.group; |
| 3007 | WorkingDirectory = "${cfg.dataDir}/%i.git"; |
| 3008 | TimeoutStartSec = "15min"; |
| 3009 | Restart = "on-failure"; |
| 3010 | RestartSec = "30s"; |
| 3011 | RestartSteps = 5; |
| 3012 | RestartMaxDelaySec = "15min"; |
| 3013 | }; |
| 3014 | }; |
| 3015 | |
| 3016 | # wantedBy on a template unit enables nothing, so the instances the |
| 3017 | # declaration asks for are pulled in by name. |
| 3018 | systemd.targets.valley-publish = lib.mkIf (publishedProjects != { }) { |
| 3019 | description = "What pushes the valley's mirrors"; |
| 3020 | wantedBy = [ "multi-user.target" ]; |
| 3021 | wants = map (name: "valley-publish@${name}.path") (lib.attrNames publishedProjects); |
| 3022 | }; |
| 3023 | |
| 3024 | systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable { |
| 3025 | description = "The valley integrator's controllers"; |
| 3026 | wantedBy = [ "multi-user.target" ]; |
| 3027 | wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects); |
| 3028 | }; |
| 3029 | |
| 3030 | # The build slice. The daemon runs every build in its own cgroup, |
| 3031 | # whoever asked for it, so a cap on a build is a cap on the daemon: the |
| 3032 | # slice holds nix-daemon.service, and the check worker when it runs, |
| 3033 | # and the kernel holds everything in it to the quota and the memory cap |
| 3034 | # together, with no swap. Every user's builds through the daemon share |
| 3035 | # the caps. A nix command that does not go through the daemon, such as |
| 3036 | # one root runs on the store directly, is outside the slice and |
| 3037 | # uncapped. |
| 3038 | # |
| 3039 | # A build that takes the slice past its memory cap is ended by the |
| 3040 | # kernel's OOM killer, which kills the process in the slice using the |
| 3041 | # most memory. That is usually the build that went past, and it can be |
| 3042 | # another build in the slice. The rest of the host goes on as it was. |
| 3043 | # When the OOM killer kills one of the daemon's processes, systemd keeps |
| 3044 | # the daemon's unit running, since the unit delegates its cgroup |
| 3045 | # (OOMPolicy=continue). Nothing exempts the daemon's own processes from |
| 3046 | # being the one chosen. |
| 3047 | # The slice sets no device policy, so a build keeps the /dev/kvm the |
| 3048 | # daemon gives NixOS tests. |
| 3049 | systemd.slices.valley-builds = lib.mkIf cfg.buildSlice.enable { |
| 3050 | description = "Every build of the nix daemon, under the host's caps"; |
| 3051 | sliceConfig = { |
| 3052 | CPUQuota = cfg.buildSlice.cpuQuota; |
| 3053 | MemoryMax = cfg.buildSlice.memoryMax; |
| 3054 | MemorySwapMax = "0"; |
| 3055 | }; |
| 3056 | }; |
| 3057 | |
| 3058 | systemd.services.nix-daemon.serviceConfig.Slice = lib.mkIf cfg.buildSlice.enable buildSlice; |
| 3059 | |
| 3060 | # One pass of the worker, as a oneshot the timer below starts. A pass |
| 3061 | # that finds nothing to build reads origin and ends. Two passes never |
| 3062 | # overlap: systemd starts the unit only while it is inactive, and the |
| 3063 | # worker's own lock in its state directory serializes any pass started |
| 3064 | # by hand. |
| 3065 | # |
| 3066 | # The unit runs in the build slice, so its evaluation shares the caps |
| 3067 | # with the builds. A pass runs worker.batches batches at once, attest |
| 3068 | # builds worker.buildSlots checks at once in each, and NIX_CONFIG lets |
| 3069 | # each of those builds build worker.maxJobs derivations at once. The |
| 3070 | # builds themselves run in the daemon, under the slice's quota and |
| 3071 | # memory cap, which they share with the worker. A stop of the unit |
| 3072 | # stops the pass and every attest it started. |
| 3073 | systemd.services.valley-worker = lib.mkIf cfg.worker.enable { |
| 3074 | description = "One pass of the valley check worker"; |
| 3075 | after = [ |
| 3076 | "network.target" |
| 3077 | "sshd.service" |
| 3078 | "valley-init.service" |
| 3079 | "systemd-tmpfiles-setup.service" |
| 3080 | ]; |
| 3081 | unitConfig.RequiresMountsFor = [ |
| 3082 | workerDir |
| 3083 | workerWakeDir |
| 3084 | ]; |
| 3085 | # A burst of marks must never leave the unit refusing to start: the |
| 3086 | # path unit starts a pass at most once per pass that ends, and a pass |
| 3087 | # that could not claim due waits out RestartSec first. |
| 3088 | unitConfig.StartLimitIntervalSec = 0; |
| 3089 | # A switch never starts, restarts or stops the worker. Restarting a |
| 3090 | # oneshot that is mid-pass makes the switch wait for the pass to end, |
| 3091 | # and a pass can run for many minutes. A pass already running ends on |
| 3092 | # the binary and configuration it started with; the next pass, from |
| 3093 | # the timer or the path unit, uses the new ones. |
| 3094 | restartIfChanged = false; |
| 3095 | stopIfChanged = false; |
| 3096 | # nix is the machine's own, for the reason the integrator's is. |
| 3097 | path = [ |
| 3098 | workerPackage |
| 3099 | attestPackage |
| 3100 | pkgs.git |
| 3101 | pkgs.diffutils |
| 3102 | config.programs.ssh.package |
| 3103 | config.nix.package |
| 3104 | ]; |
| 3105 | environment = { |
| 3106 | HOME = workerDir; |
| 3107 | XDG_CACHE_HOME = "${workerDir}/cache"; |
| 3108 | GIT_SSH_COMMAND = workerSsh; |
| 3109 | NIX_CONFIG = workerNixConfig; |
| 3110 | }; |
| 3111 | script = workerScript; |
| 3112 | serviceConfig = { |
| 3113 | Type = "oneshot"; |
| 3114 | User = "valley-worker"; |
| 3115 | Group = "valley-worker"; |
| 3116 | # A pass that could not claim its due mark exits 75 (status/wake.go), |
| 3117 | # and the due is still there. It is started again one interval |
| 3118 | # later, and the path unit, which sees the unit restarting, starts |
| 3119 | # nothing meanwhile. Any other status is left to the timer. |
| 3120 | RestartForceExitStatus = "75"; |
| 3121 | RestartSec = cfg.worker.interval; |
| 3122 | Slice = buildSlice; |
| 3123 | NoNewPrivileges = true; |
| 3124 | ProtectSystem = "strict"; |
| 3125 | # Its own directory, its wake directory, and the nix daemon's |
| 3126 | # socket, which a client writes to connect. The roots attest adds |
| 3127 | # are symlinks in its own directory, which the daemon records |
| 3128 | # through the socket. |
| 3129 | ReadWritePaths = [ |
| 3130 | workerDir |
| 3131 | workerWakeDir |
| 3132 | "/nix/var/nix/daemon-socket" |
| 3133 | ]; |
| 3134 | ProtectHome = true; |
| 3135 | PrivateTmp = true; |
| 3136 | PrivateDevices = true; |
| 3137 | ProtectClock = true; |
| 3138 | ProtectHostname = true; |
| 3139 | ProtectKernelLogs = true; |
| 3140 | ProtectKernelModules = true; |
| 3141 | ProtectKernelTunables = true; |
| 3142 | ProtectControlGroups = true; |
| 3143 | ProtectProc = "invisible"; |
| 3144 | RestrictAddressFamilies = [ |
| 3145 | "AF_INET" |
| 3146 | "AF_INET6" |
| 3147 | "AF_UNIX" |
| 3148 | ]; |
| 3149 | RestrictNamespaces = true; |
| 3150 | RestrictRealtime = true; |
| 3151 | RestrictSUIDSGID = true; |
| 3152 | LockPersonality = true; |
| 3153 | CapabilityBoundingSet = ""; |
| 3154 | SystemCallArchitectures = "native"; |
| 3155 | SystemCallFilter = [ "@system-service" ]; |
| 3156 | UMask = "0077"; |
| 3157 | }; |
| 3158 | }; |
| 3159 | |
| 3160 | # The timer is the worker's recovery scan. Its first pass starts soon |
| 3161 | # after the timer starts, at boot or at the switch that adds it, and |
| 3162 | # reads everything, so a mark lost between a ref moving and its hook |
| 3163 | # running, or a claim a killed pass left, is made good. Each later pass |
| 3164 | # starts one interval after the last one ended, and is what retries a |
| 3165 | # failed batch or push once its wait is over. A pass may start inside a |
| 3166 | # switch. Nothing waits for it: the service is wanted by no target. |
| 3167 | systemd.timers.valley-worker = lib.mkIf cfg.worker.enable { |
| 3168 | description = "Run the valley check worker"; |
| 3169 | wantedBy = [ "timers.target" ]; |
| 3170 | timerConfig = { |
| 3171 | OnActiveSec = "1s"; |
| 3172 | OnUnitInactiveSec = cfg.worker.interval; |
| 3173 | }; |
| 3174 | }; |
| 3175 | |
| 3176 | # A pass whenever the wake directory holds due. A pass claims each mark |
| 3177 | # made while it runs, and reads again. PathExists, and not PathChanged: |
| 3178 | # a mark made after a pass's last claim is seen when that pass ends, |
| 3179 | # and starts the next one then. claimed starts nothing. |
| 3180 | systemd.paths.valley-worker = lib.mkIf cfg.worker.enable { |
| 3181 | description = "Start the valley check worker when a ref it reads moves"; |
| 3182 | wantedBy = [ "multi-user.target" ]; |
| 3183 | pathConfig.PathExists = "${workerWakeDir}/due"; |
| 3184 | }; |
| 3185 | |
| 3186 | # One restacker controller for each project listed: valley-restacker |
| 3187 | # run, which reconciles at its start and then every interval. It holds |
| 3188 | # the lock on its state directory for as long as it runs, so one |
| 3189 | # controller serves a project at a time. A controller that fails is |
| 3190 | # restarted. It needs no ordering on the repositories' mounts or on |
| 3191 | # valley-init: it reads and pushes through sshd, and the git user's |
| 3192 | # shell holds a push until valley-init has converged. |
| 3193 | systemd.services."valley-restacker@" = lib.mkIf cfg.restacker.enable { |
| 3194 | description = "The valley restacker for %i"; |
| 3195 | after = [ |
| 3196 | "network.target" |
| 3197 | "sshd.service" |
| 3198 | ]; |
| 3199 | path = [ config.programs.ssh.package ]; |
| 3200 | environment = { |
| 3201 | HOME = restackerState; |
| 3202 | GIT_SSH_COMMAND = restackerSsh; |
| 3203 | }; |
| 3204 | serviceConfig = { |
| 3205 | ExecStartPre = "${restackerKnownHosts} ${restackerState}"; |
| 3206 | ExecStart = restackerCommand; |
| 3207 | Restart = "on-failure"; |
| 3208 | RestartSec = "10s"; |
| 3209 | User = "valley-restacker"; |
| 3210 | Group = "valley-restacker"; |
| 3211 | StateDirectory = "${restackerStateName}/%i"; |
| 3212 | StateDirectoryMode = "0700"; |
| 3213 | WorkingDirectory = restackerState; |
| 3214 | LoadCredential = [ "key:${toString cfg.restacker.sshKeyFile}" ]; |
| 3215 | NoNewPrivileges = true; |
| 3216 | ProtectSystem = "strict"; |
| 3217 | ProtectHome = true; |
| 3218 | PrivateTmp = true; |
| 3219 | PrivateDevices = true; |
| 3220 | ProtectClock = true; |
| 3221 | ProtectHostname = true; |
| 3222 | ProtectKernelLogs = true; |
| 3223 | ProtectKernelModules = true; |
| 3224 | ProtectKernelTunables = true; |
| 3225 | ProtectControlGroups = true; |
| 3226 | ProtectProc = "invisible"; |
| 3227 | RestrictAddressFamilies = [ |
| 3228 | "AF_INET" |
| 3229 | "AF_INET6" |
| 3230 | "AF_UNIX" |
| 3231 | ]; |
| 3232 | RestrictNamespaces = true; |
| 3233 | RestrictRealtime = true; |
| 3234 | RestrictSUIDSGID = true; |
| 3235 | LockPersonality = true; |
| 3236 | CapabilityBoundingSet = ""; |
| 3237 | SystemCallArchitectures = "native"; |
| 3238 | SystemCallFilter = [ "@system-service" ]; |
| 3239 | UMask = "0077"; |
| 3240 | }; |
| 3241 | }; |
| 3242 | |
| 3243 | # wantedBy on a template unit enables nothing, so the controllers the |
| 3244 | # declaration asks for are pulled in by name. |
| 3245 | systemd.targets.valley-restackers = lib.mkIf cfg.restacker.enable { |
| 3246 | description = "The valley restacker's controllers"; |
| 3247 | wantedBy = [ "multi-user.target" ]; |
| 3248 | wants = map (name: "valley-restacker@${name}.service") cfg.restacker.projects; |
| 3249 | }; |
| 3250 | |
| 3251 | # Offsite backup, rendered only when the declaration asks for it. The |
| 3252 | # declaration states the policy — that backup exists, its cadence and |
| 3253 | # retention; the services.valley.backup.* options supply the machine |
| 3254 | # half. Declaration absent or disabled ⇒ no restic config at all. |
| 3255 | services.restic.backups = lib.mkIf backupEnabled { |
| 3256 | valley = { |
| 3257 | initialize = true; |
| 3258 | repositoryFile = cfg.backup.repositoryFile; |
| 3259 | passwordFile = cfg.backup.passwordFile; |
| 3260 | # With the web publisher, the backup also holds the read links' |
| 3261 | # credential file's directory and the publisher's durable state: |
| 3262 | # its export key, its authorization counter and its record of what |
| 3263 | # the receiver holds. Under DynamicUser that state lives under |
| 3264 | # /var/lib/private. |
| 3265 | paths = [ |
| 3266 | cfg.dataDir |
| 3267 | ] |
| 3268 | ++ lib.optionals (config.services.valley.webPublisher.enable or false) ( |
| 3269 | let |
| 3270 | web = config.services.valley.webPublisher; |
| 3271 | in |
| 3272 | [ |
| 3273 | (dirOf (toString web.linksFile)) |
| 3274 | "/var/lib/private/${lib.removePrefix "/var/lib/" (toString web.stateDir)}" |
| 3275 | ] |
| 3276 | ); |
| 3277 | # The schema admits only the restic-sftp target today; a second |
| 3278 | # target would grow a dispatch here. The service runs as root: |
| 3279 | # authenticate with the supplied identity and only the pinned |
| 3280 | # host key. No prompt can be answered inside a systemd unit, so |
| 3281 | # BatchMode + strict host key checking turn a would-be hang into |
| 3282 | # an immediate error. |
| 3283 | extraOptions = [ |
| 3284 | "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'" |
| 3285 | ]; |
| 3286 | timerConfig = backupTimer.${backupPolicy.cadence}; |
| 3287 | pruneOpts = [ |
| 3288 | "--keep-daily ${toString backupPolicy.retention.daily}" |
| 3289 | "--keep-weekly ${toString backupPolicy.retention.weekly}" |
| 3290 | "--keep-monthly ${toString backupPolicy.retention.monthly}" |
| 3291 | ]; |
| 3292 | }; |
| 3293 | }; |
| 3294 | }; |
| 3295 | } |