| 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, Tailscale 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 | # cosmo, via 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 | # One service runs under its own unix user rather than the git one: the |
| 35 | # integrator. That is the first half of the split bd-500adf7 asks for. |
| 36 | { |
| 37 | config, |
| 38 | pkgs, |
| 39 | lib, |
| 40 | ... |
| 41 | }: |
| 42 | |
| 43 | let |
| 44 | cfg = config.services.valley; |
| 45 | |
| 46 | schema = ../schema/valley.cue; |
| 47 | |
| 48 | # Build-time vet + export of the host declaration. the vet checks the |
| 49 | # declaration against the schema (whose top level applies #Host), so unknown |
| 50 | # fields and unsafe project names fail the build, with cue's error. |
| 51 | configJSON = |
| 52 | pkgs.runCommand "valley-config.json" |
| 53 | { |
| 54 | nativeBuildInputs = [ pkgs.cue ]; |
| 55 | } |
| 56 | '' |
| 57 | cue vet -c ${schema} ${cfg.config} |
| 58 | cue export ${schema} ${cfg.config} > $out |
| 59 | ''; |
| 60 | |
| 61 | host = lib.importJSON configJSON; |
| 62 | |
| 63 | # Projects whose git store is enabled get a bare repository. |
| 64 | gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects; |
| 65 | repoNames = lib.attrNames gitProjects; |
| 66 | |
| 67 | # Where valley-init publishes repoNames in the instance repository. |
| 68 | projectsRef = "refs/the-valley/projects"; |
| 69 | |
| 70 | # The declared durability policy, if any. `backup` is optional in the |
| 71 | # schema: a declaration without it (or with enable = false) renders zero |
| 72 | # backup machinery, exactly as before the field existed. |
| 73 | backupPolicy = host.backup or null; |
| 74 | backupEnabled = backupPolicy != null && backupPolicy.enable; |
| 75 | |
| 76 | # The declared cadence names policy; its wall-clock rendering is this |
| 77 | # installer's choice. A lookup rather than a literal, so a cadence this |
| 78 | # module does not know fails eval loudly instead of mis-scheduling. |
| 79 | backupTimer = { |
| 80 | # Late night with a spread; Persistent runs a missed window at boot. |
| 81 | nightly = { |
| 82 | OnCalendar = "03:30"; |
| 83 | RandomizedDelaySec = "30m"; |
| 84 | Persistent = true; |
| 85 | }; |
| 86 | }; |
| 87 | |
| 88 | # The projects the integrator serves: exactly the ones the declaration |
| 89 | # protects. A protected ref is one only a declared writer may push, and |
| 90 | # the integrator is what lands everyone else's changes onto it. |
| 91 | integratedProjects = lib.filterAttrs (_: p: p ? protection) gitProjects; |
| 92 | |
| 93 | # The integrator this flake builds, in its shipping form: attest, the |
| 94 | # deriver, cue, git and natscli pinned inside the wrapper, so every host |
| 95 | # judges with the same tools (nix/packages.nix). |
| 96 | integratorPackage = (import ./packages.nix { inherit pkgs lib; }).integrator; |
| 97 | |
| 98 | # The whole of a controller's configuration: which repository it serves, |
| 99 | # who it signs as, and whose evidence it accepts. No policy — the |
| 100 | # integrator reads the project layer from the target tip and the instance |
| 101 | # layer from its own side (bd-eaefe82) — and no project name, which the |
| 102 | # binary derives from the bare repo's own directory, the same way the |
| 103 | # post-receive hook does. |
| 104 | integratorCommand = lib.concatStringsSep " " ( |
| 105 | [ |
| 106 | "${integratorPackage}/bin/integrator watch" |
| 107 | "--repo ${cfg.dataDir}/%i.git" |
| 108 | "--key ${toString cfg.integrator.signingKeyFile}" |
| 109 | "--known-signers ${knownSigners}" |
| 110 | "--interval ${cfg.integrator.interval}" |
| 111 | ] |
| 112 | ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}" |
| 113 | ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}" |
| 114 | ++ ( |
| 115 | if cfg.integrator.instanceProject != null then |
| 116 | [ "--instance-repo ${instanceRepo}" ] |
| 117 | else |
| 118 | [ "--instance ${toString cfg.integrator.instancePolicy}" ] |
| 119 | ) |
| 120 | ++ lib.optional cfg.bus.enable "--bus ${busUrl}" |
| 121 | ++ [ "--publish-queue ${cfg.dataDir}/%i.git/${publishQueueName}" ] |
| 122 | ); |
| 123 | |
| 124 | # The one filesystem grant the integrator's user gets. It writes refs, |
| 125 | # objects, and the worktree metadata `git worktree add` keeps inside the |
| 126 | # repository, so read access is not enough: the repos it serves become |
| 127 | # group-shared, and its primary group is the git group. Re-applied on |
| 128 | # every activation, because a repo can predate the service. |
| 129 | # git creates $GIT_DIR/worktrees on the first `worktree add`, owned by |
| 130 | # whichever user got there first. Left alone that user is the integrator, |
| 131 | # and this sweep runs as the git user, which cannot chmod a directory it |
| 132 | # does not own. So init makes that directory itself, ahead of any |
| 133 | # controller: owned by the git user, group-writable, and setgid, so what a |
| 134 | # controller creates inside it lands in the git group and stays reachable. |
| 135 | integratorShareCommands = |
| 136 | '' |
| 137 | # A chmod the git user is not allowed to make is a path some other |
| 138 | # user owns; chmod -R applies what it can and then says so. Warn and |
| 139 | # carry on, and the trade is worth stating. Failing here fails |
| 140 | # valley-init, which every valley unit requires, so the alternative to |
| 141 | # a partly shared repository is no git service on the host at all: no |
| 142 | # controllers, and no ssh access to any project. A degraded share |
| 143 | # costs the integrator the paths it cannot write, is visible in the |
| 144 | # journal, and is fixed by one chown. That is the recoverable half of |
| 145 | # the trade, and it is the half to take. The warning is what keeps the |
| 146 | # degraded state from being a silent one. |
| 147 | share() { |
| 148 | "$@" || 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 |
| 149 | } |
| 150 | '' |
| 151 | + lib.concatMapStrings (name: '' |
| 152 | repo=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"} |
| 153 | git -C "$repo" config core.sharedRepository group |
| 154 | # Before the sweep below, so the sweep never meets a root it cannot |
| 155 | # touch. On a host where a controller already made it, this is the |
| 156 | # chmod that warns, and the repository is served either way. |
| 157 | mkdir -p "$repo/worktrees" |
| 158 | share chmod g+rwxs "$repo/worktrees" |
| 159 | # The publish queue is the git user's for the same reason: the |
| 160 | # integrator writes into it and the publish unit deletes from it. |
| 161 | mkdir -p "$repo/${publishQueueName}" |
| 162 | share chmod g+rwxs "$repo/${publishQueueName}" |
| 163 | share chmod -R g+rwX "$repo" |
| 164 | share find "$repo" -type d -exec chmod g+s {} + |
| 165 | '') (lib.attrNames integratedProjects); |
| 166 | |
| 167 | # The integrator's own directory. Four unit settings have to agree about |
| 168 | # it — its state directory, its working directory, the scratch root TMPDIR |
| 169 | # names, and the read-write path that makes all three usable — so they name |
| 170 | # it once here. |
| 171 | # The bare repository the group's floor is read from: the instance |
| 172 | # project's, served by this host. Null when the host serves no instance |
| 173 | # repository and the layer is supplied as a directory instead. |
| 174 | instanceRepo = |
| 175 | if cfg.integrator.instanceProject != null then |
| 176 | "${cfg.dataDir}/${cfg.integrator.instanceProject}.git" |
| 177 | else |
| 178 | null; |
| 179 | |
| 180 | integratorStateName = "valley-integrator"; |
| 181 | integratorStateDir = "/var/lib/${integratorStateName}"; |
| 182 | |
| 183 | # The identity registry compiler this flake builds. It renders the |
| 184 | # registry at the instance repository's integrated tip into what the gates |
| 185 | # check (dcr-b87f6e8): the known-signers file the integrator and any |
| 186 | # reader of an attestation use, and a tagged authorized_keys for the git |
| 187 | # user. |
| 188 | identityPackage = (import ./packages.nix { inherit pkgs lib; }).identity; |
| 189 | |
| 190 | identityStateName = "valley-identity"; |
| 191 | identityStateDir = "/var/lib/${identityStateName}"; |
| 192 | identityKnownSigners = "${identityStateDir}/known-signers"; |
| 193 | |
| 194 | # The grants the pre-receive hook checks, as the registry names them. |
| 195 | identityGrants = "${identityStateDir}/grants"; |
| 196 | |
| 197 | # The compiled authorized keys. sshd reads them for the git user alone: |
| 198 | # the git user's Match block below names the files its keys come from. |
| 199 | identityAuthorizedKeys = "${identityStateDir}/authorized_keys.${cfg.user}"; |
| 200 | |
| 201 | identityCommand = lib.concatStringsSep " " [ |
| 202 | "${identityPackage}/bin/identity compile" |
| 203 | "--repo ${toString instanceRepo}" |
| 204 | "--ref ${cfg.identity.ref}" |
| 205 | "--dir ${cfg.identity.directory}" |
| 206 | "--known-signers ${identityKnownSigners}" |
| 207 | "--authorized-keys ${identityAuthorizedKeys}" |
| 208 | "--grants ${identityGrants}" |
| 209 | "--declared-keys ${declaredKeysFile}" |
| 210 | ]; |
| 211 | |
| 212 | # Whose evidence a controller accepts: the compiled artifact once the |
| 213 | # registry machinery is on, and the file the consumer supplied otherwise. |
| 214 | knownSigners = |
| 215 | if cfg.identity.enable then identityKnownSigners else toString cfg.integrator.knownSignersFile; |
| 216 | |
| 217 | # Which signers count in which projects, as the integrator reads it: one |
| 218 | # line per restricted signer, its name and then its projects. Null when |
| 219 | # the consumer restricts nobody, so a host that sets nothing passes no |
| 220 | # file to anything. The file is in the store, so a changed list is a |
| 221 | # changed command line for the controllers and the publisher alike, and |
| 222 | # an activation restarts the one and runs the other again. |
| 223 | signerProjects = |
| 224 | if cfg.integrator.signerProjects == { } then |
| 225 | null |
| 226 | else |
| 227 | pkgs.writeText "valley-signer-projects" ( |
| 228 | lib.concatStrings ( |
| 229 | lib.mapAttrsToList ( |
| 230 | name: projects: lib.concatStringsSep " " ([ name ] ++ projects) + "\n" |
| 231 | ) cfg.integrator.signerProjects |
| 232 | ) |
| 233 | ); |
| 234 | |
| 235 | # What a client verifies this host's transfer statements with, published |
| 236 | # in the instance repository: the known-signers file the controllers read, |
| 237 | # whichever wrote it, and the name they sign under. Unset, the name is the |
| 238 | # integrator's own default, and the publisher computes it with the same |
| 239 | # code on the same host, so what is published is what the controllers use. |
| 240 | # A host publishes it while the integrator runs and the host serves the |
| 241 | # instance repository; any other host publishes nothing. |
| 242 | publishesSigners = cfg.integrator.enable && instanceRepo != null; |
| 243 | signersCommand = lib.concatStringsSep " " ( |
| 244 | [ |
| 245 | "${integratorPackage}/bin/integrator publish-signers" |
| 246 | "--instance-repo ${toString instanceRepo}" |
| 247 | "--known-signers ${knownSigners}" |
| 248 | ] |
| 249 | ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}" |
| 250 | ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}" |
| 251 | ); |
| 252 | |
| 253 | # The paths the consumer must supply once the integrator is enabled, |
| 254 | # with what each names — for the assertion message. The signers file is |
| 255 | # among them only while the registry does not compile one. |
| 256 | integratorPathOptions = { |
| 257 | signingKeyFile = "the key its transfer statements are signed with"; |
| 258 | } |
| 259 | // lib.optionalAttrs (!cfg.identity.enable) { |
| 260 | knownSignersFile = "the signers whose evidence it accepts"; |
| 261 | }; |
| 262 | |
| 263 | # The secret-path options the consumer must supply once the declaration |
| 264 | # enables backup, with what each names — for the assertion message. |
| 265 | backupSecretOptions = { |
| 266 | repositoryFile = "the restic repository URL"; |
| 267 | passwordFile = "the repository encryption password"; |
| 268 | sshKeyFile = "the SSH identity for the sftp target"; |
| 269 | knownHostsFile = "the pinned host key of the sftp target"; |
| 270 | }; |
| 271 | |
| 272 | # Managed post-receive dispatcher. Each repo's post-receive is a symlink to |
| 273 | # this script, which chains every executable dropped into the repo's |
| 274 | # hooks/post-receive.d/ directory. |
| 275 | postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" '' |
| 276 | # Managed by services.valley — do not edit. |
| 277 | # Drop executable hooks into post-receive.d/ next to this symlink. |
| 278 | set -eu |
| 279 | hook_dir="$(dirname "$0")/post-receive.d" |
| 280 | [ -d "$hook_dir" ] || exit 0 |
| 281 | updates="$(cat)" |
| 282 | [ -n "$updates" ] || exit 0 |
| 283 | for hook in "$hook_dir"/*; do |
| 284 | [ -x "$hook" ] || continue |
| 285 | printf '%s\n' "$updates" | "$hook" "$@" |
| 286 | done |
| 287 | ''; |
| 288 | |
| 289 | # Push replication. A publication mirror gets main and the tags, and |
| 290 | # nothing else. Only the publish drain further down runs it, for pushes |
| 291 | # and integrator landings alike. |
| 292 | # Topic branches are review-queue state, not published: the mirror exists |
| 293 | # so consumers can fetch what has been integrated, and durability is |
| 294 | # restic's job, not the mirror's. The two refspecs are what keep every |
| 295 | # other ref of the project off the mirror. |
| 296 | # --prune propagates tag deletions through the tags glob. The heads |
| 297 | # refspec names one ref, so --prune deletes no head. |
| 298 | # The pusher deletes nothing else on a mirror. Deleting a ref that a |
| 299 | # public mirror has served unpublishes nothing, because forges keep its |
| 300 | # objects fetchable by SHA. And a mirror holds refs that other writers put |
| 301 | # there, such as a forge's own namespaces or a bot's branches; those are |
| 302 | # theirs. --mirror is refused for the same reason: it deletes every mirror |
| 303 | # ref the primary lacks, and on GitHub the read-only refs/pull/* makes |
| 304 | # that fail every push, masking real replication failures. |
| 305 | # The pusher exits non-zero when a replication push fails, and the drain |
| 306 | # retries on that. |
| 307 | mirrorPusher = |
| 308 | name: mirrors: |
| 309 | pkgs.writeShellScript "valley-mirror-push-${name}" '' |
| 310 | status=0 |
| 311 | for url in ${lib.escapeShellArgs mirrors}; do |
| 312 | if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then |
| 313 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true |
| 314 | else |
| 315 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true |
| 316 | status=1 |
| 317 | fi |
| 318 | done |
| 319 | exit "$status" |
| 320 | ''; |
| 321 | |
| 322 | # The post-receive.d hook of a project with mirrors. It does not push. It |
| 323 | # queues the push's ref moves for the publish drain, as the integrator |
| 324 | # queues a landing, and returns. So a dead mirror can only ever cost a log |
| 325 | # line and a retry, never block or fail the primary push. The file is |
| 326 | # written beside the queue and renamed into it, so the drain never reads a |
| 327 | # partial one. A push whose moves cannot be queued is logged, and stands. |
| 328 | mirrorHook = |
| 329 | name: |
| 330 | pkgs.writeShellScript "valley-mirrors-${name}" '' |
| 331 | # Managed by services.valley — queue this push for ${name}'s mirrors. |
| 332 | bin=${pkgs.coreutils}/bin |
| 333 | tmp="$($bin/mktemp .valley-publish-XXXXXXXX)" && |
| 334 | $bin/cat >"$tmp" && |
| 335 | $bin/mv -- "$tmp" "${publishQueueName}/$($bin/date +%s%N)-push-$$" || { |
| 336 | $bin/rm -f -- "$tmp" |
| 337 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: queueing a push FAILED" || true |
| 338 | } |
| 339 | exit 0 |
| 340 | ''; |
| 341 | |
| 342 | # The event bus (archive/design/roadmap.md, Phase 1): NATS JetStream, onto which |
| 343 | # the ref-updated hook below projects this host's git activity. The bus is |
| 344 | # never load-bearing for durable state — per-repo events are durable in |
| 345 | # git itself, and `valley replay` rebuilds the stream from a repo's refs — |
| 346 | # so losing its storage costs one replay, nothing more. |
| 347 | busUrl = "nats://${cfg.bus.listen}"; |
| 348 | |
| 349 | busServerConfig = pkgs.writeText "valley-bus.conf" '' |
| 350 | listen: ${cfg.bus.listen} |
| 351 | jetstream { |
| 352 | store_dir: "${cfg.bus.storeDir}" |
| 353 | # The store directory defaults to living on the repo volume; the cap |
| 354 | # keeps a runaway or malicious local publisher from filling it. |
| 355 | max_file_store: 2GiB |
| 356 | } |
| 357 | ''; |
| 358 | |
| 359 | # One ref-updated event per updated ref, read from the post-receive stdin |
| 360 | # this script inherits. Every payload field is derivable from git alone — |
| 361 | # no wall-clock time, no hostname — so replaying a repo's refs reproduces |
| 362 | # the same events (the roadmap's determinism criterion). `valley replay` |
| 363 | # builds the identical payload; change one only with the other. |
| 364 | busPublisher = pkgs.writeShellScript "valley-bus-publish" '' |
| 365 | repo="$(basename "$PWD" .git)" |
| 366 | while read -r old new ref; do |
| 367 | [ -n "$ref" ] || continue |
| 368 | # " is the only JSON-significant character a refname can contain |
| 369 | # (git forbids \ and control characters); names and ids are safe. |
| 370 | event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \ |
| 371 | "$repo" "''${ref//\"/\\\"}" "$old" "$new")" |
| 372 | if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \ |
| 373 | "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then |
| 374 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true |
| 375 | else |
| 376 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true |
| 377 | fi |
| 378 | done |
| 379 | ''; |
| 380 | |
| 381 | # How a move reaches the mirrors: the publish queue. |
| 382 | # |
| 383 | # One thing pushes a project's mirrors: the publish drain, a oneshot unit |
| 384 | # per project that runs as the git user. Whatever moves a ref writes the |
| 385 | # move into a queue directory in the repository, as the line post-receive |
| 386 | # reads: old, new, ref. A path unit watches the queue, and when it holds |
| 387 | # anything, starts the drain. A push queues its moves from post-receive, |
| 388 | # through the mirror hook above. The integrator moves refs with |
| 389 | # update-ref, which runs no post-receive hook, so it queues each landing |
| 390 | # itself (integrator/bus.go). It runs as its own user, which does not hold |
| 391 | # the git user's mirror credentials and must not. |
| 392 | # |
| 393 | # A single publisher is what keeps a mirror from being rewound. git reads |
| 394 | # the local refs before it contacts the mirror, so two pushers running at |
| 395 | # once can rewind it: one reads an old main and stalls, the other pushes a |
| 396 | # newer main, and the first then force-pushes its old main over it. |
| 397 | # systemd never runs two instances of one unit at the same time, so the |
| 398 | # drain's pushes for a project never overlap, and nothing else pushes. |
| 399 | # The drain lists the queue before git reads any ref, and deletes only what |
| 400 | # it listed, after the push succeeds. A move is queued after its ref moved, |
| 401 | # so the push covers every listed move. A move queued during the push stays |
| 402 | # for the next run, which pushes the newer main. No lock is taken: the |
| 403 | # drain runs only as the unit. To publish by hand, start the unit |
| 404 | # (systemctl start valley-publish@<project>), never the script. |
| 405 | # |
| 406 | # A run that fails leaves the queue as it was, and systemd runs it again |
| 407 | # after a delay (the unit, further down). So a failed mirror push does not |
| 408 | # wait for another move to be retried. Repeating a push is harmless: it |
| 409 | # pushes the current main, whatever the queue records. |
| 410 | # |
| 411 | # The bus is not the drain's business. A push publishes its ref-updated |
| 412 | # events from post-receive, through the bus hook below. The integrator |
| 413 | # publishes its landing's ref-updated event itself. So a mirror outage, and |
| 414 | # the drain's retries, never delay an event. |
| 415 | # |
| 416 | # The alternatives fall to the user split. Calling the post-receive |
| 417 | # dispatcher from the integrator would push as the integrator's user, and |
| 418 | # so would a reference-transaction hook, which runs as whoever ran git; it |
| 419 | # would also fire inside every push and for every bookkeeping ref the |
| 420 | # integrator writes. Starting a unit directly would take a polkit grant |
| 421 | # and carry no record of what moved. The queue costs one directory, the |
| 422 | # path unit is woken by inotify rather than a poll, and the queue is |
| 423 | # durable, so a move queued while the host goes down is published after. |
| 424 | publishQueueName = "valley-publish-queue"; |
| 425 | |
| 426 | # The projects with a publish queue and a drain: every one with mirrors, |
| 427 | # and every one the integrator serves. The integrator queues its landings |
| 428 | # whether or not the project has mirrors. A drain with no mirrors to push |
| 429 | # only empties the queue. |
| 430 | publishedProjects = lib.filterAttrs ( |
| 431 | name: p: p.mirrors != [ ] || (cfg.integrator.enable && integratedProjects ? ${name}) |
| 432 | ) gitProjects; |
| 433 | |
| 434 | # The drain, per project. Its working directory is the repository. It runs |
| 435 | # synchronously: the unit is already detached from the push or the |
| 436 | # landing, and a detached child would be killed with the oneshot's cgroup |
| 437 | # when it exits. |
| 438 | publishDrain = |
| 439 | name: p: |
| 440 | pkgs.writeShellScript "valley-publish-${name}" '' |
| 441 | # Managed by services.valley — push the moves queued on ${name} to its mirrors. |
| 442 | shopt -s nullglob |
| 443 | # Listed before the pusher reads any ref, so the push covers them all. |
| 444 | moves=( ${publishQueueName}/* ) |
| 445 | [ "''${#moves[@]}" -gt 0 ] || exit 0 |
| 446 | ${lib.optionalString (p.mirrors != [ ]) "${mirrorPusher name p.mirrors} || exit 1"} |
| 447 | # A move that cannot be deleted fails the run, so systemd retries it |
| 448 | # after a delay. A run that succeeded would leave the queue non-empty, |
| 449 | # and the path unit would start the drain again at once, over and over. |
| 450 | rm -f -- "''${moves[@]}" || exit 1 |
| 451 | ''; |
| 452 | |
| 453 | # Every drain, by project name, so the template unit runs its instance's. |
| 454 | publishDrains = pkgs.linkFarm "valley-publish-drains" ( |
| 455 | lib.mapAttrsToList (name: p: { |
| 456 | inherit name; |
| 457 | path = publishDrain name p; |
| 458 | }) publishedProjects |
| 459 | ); |
| 460 | |
| 461 | # The queue directory of every published project. The integrator's |
| 462 | # projects also get it group-shared, with the rest of the repository. |
| 463 | publishQueueCommands = lib.concatMapStrings (name: '' |
| 464 | mkdir -p ${lib.escapeShellArg "${cfg.dataDir}/${name}.git/${publishQueueName}"} |
| 465 | '') (lib.attrNames publishedProjects); |
| 466 | |
| 467 | # The post-receive.d hook that publishes a push's ref-updated events. The |
| 468 | # publisher runs detached (setsid, inheriting the updates on stdin), so a |
| 469 | # bus problem can only ever cost a log line — never block or fail the |
| 470 | # push. git is the source of truth; the bus is the replaceable component. |
| 471 | busEventHook = pkgs.writeShellScript "valley-bus-events" '' |
| 472 | # Managed by services.valley — project ref updates onto the event bus. |
| 473 | ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1 |
| 474 | exit 0 |
| 475 | ''; |
| 476 | |
| 477 | # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks: |
| 478 | # only ever installs, updates, or removes a store symlink — a hand-written |
| 479 | # hook of the same name is left alone. |
| 480 | busHookCommands = lib.concatMapStrings ( |
| 481 | name: |
| 482 | let |
| 483 | bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus"; |
| 484 | in |
| 485 | if cfg.bus.enable then |
| 486 | '' |
| 487 | bhook=${bhook} |
| 488 | if [ -L "$bhook" ]; then |
| 489 | case "$(readlink "$bhook")" in |
| 490 | /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;; |
| 491 | esac |
| 492 | elif [ ! -e "$bhook" ]; then |
| 493 | ln -s ${busEventHook} "$bhook" |
| 494 | fi |
| 495 | '' |
| 496 | else |
| 497 | '' |
| 498 | bhook=${bhook} |
| 499 | if [ -L "$bhook" ]; then |
| 500 | case "$(readlink "$bhook")" in |
| 501 | /nix/store/*) rm -f "$bhook" ;; |
| 502 | esac |
| 503 | fi |
| 504 | '' |
| 505 | ) repoNames; |
| 506 | |
| 507 | # Per-project mirror-hook wiring. Only ever installs, updates, or removes |
| 508 | # a store symlink — a hand-written hook of the same name is left alone. |
| 509 | mirrorHookCommands = lib.concatStrings ( |
| 510 | lib.mapAttrsToList ( |
| 511 | name: p: |
| 512 | let |
| 513 | mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors"; |
| 514 | in |
| 515 | if p.mirrors != [ ] then |
| 516 | '' |
| 517 | mhook=${mhook} |
| 518 | if [ -L "$mhook" ]; then |
| 519 | case "$(readlink "$mhook")" in |
| 520 | /nix/store/*) ln -sfn ${mirrorHook name} "$mhook" ;; |
| 521 | esac |
| 522 | elif [ ! -e "$mhook" ]; then |
| 523 | ln -s ${mirrorHook name} "$mhook" |
| 524 | fi |
| 525 | '' |
| 526 | else |
| 527 | '' |
| 528 | mhook=${mhook} |
| 529 | if [ -L "$mhook" ]; then |
| 530 | case "$(readlink "$mhook")" in |
| 531 | /nix/store/*) rm -f "$mhook" ;; |
| 532 | esac |
| 533 | fi |
| 534 | '' |
| 535 | ) gitProjects |
| 536 | ); |
| 537 | |
| 538 | # The environment variable carrying the pushing key's principal name. The |
| 539 | # git user's shell sets it from the tag on the authenticated key's own |
| 540 | # authorized_keys entry, and the pre-receive hook reads it. |
| 541 | principalEnv = "VALLEY_PRINCIPAL"; |
| 542 | |
| 543 | authorizedKeyLine = |
| 544 | k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}''; |
| 545 | |
| 546 | # What valley-init does to converge the host: create missing repositories |
| 547 | # and (re)wire the managed hooks. Its last step refuses to report the host |
| 548 | # converged over anything that would run instead of the push policy. |
| 549 | valleyInitBody = '' |
| 550 | conflicts=0 |
| 551 | |
| 552 | repos=( ${lib.escapeShellArgs repoNames} ) |
| 553 | for name in "''${repos[@]}"; do |
| 554 | repo="${cfg.dataDir}/$name.git" |
| 555 | # Check HEAD rather than the directory itself so a pre-existing |
| 556 | # empty directory still gets initialized. |
| 557 | if [ ! -e "$repo/HEAD" ]; then |
| 558 | git init --bare --initial-branch=main "$repo" |
| 559 | fi |
| 560 | |
| 561 | # Replacement refs make one object stand in for another wherever |
| 562 | # git looks it up. No push may write one, and every reader that |
| 563 | # makes a decision disables them, but a ref written before the |
| 564 | # hook refused them is still there. It is reported on every |
| 565 | # activation and left in place: what it is evidence of is the |
| 566 | # operator's to read before anyone deletes it. |
| 567 | replaced="$(git -C "$repo" for-each-ref --format=' %(refname) -> %(objectname)' refs/replace/)" || replaced="" |
| 568 | if [ -n "$replaced" ]; then |
| 569 | 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 |
| 570 | fi |
| 571 | |
| 572 | # Hook scaffolding: post-receive dispatches to post-receive.d/. |
| 573 | # Only manage the hook if it is absent or already ours (a store |
| 574 | # symlink) — a hand-written hook is left alone. |
| 575 | mkdir -p "$repo/hooks/post-receive.d" |
| 576 | hook="$repo/hooks/post-receive" |
| 577 | if [ -L "$hook" ]; then |
| 578 | case "$(readlink "$hook")" in |
| 579 | /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;; |
| 580 | esac |
| 581 | elif [ ! -e "$hook" ]; then |
| 582 | ln -s ${postReceiveDispatch} "$hook" |
| 583 | fi |
| 584 | done |
| 585 | |
| 586 | # Per-project push-mirror hooks, and the queue they write. |
| 587 | ${mirrorHookCommands} |
| 588 | ${publishQueueCommands} |
| 589 | |
| 590 | # The one structural invariant, on every project the host serves. |
| 591 | ${protectHookCommands} |
| 592 | |
| 593 | # The ref-updated publisher hook, on every repo when the bus is on. |
| 594 | ${busHookCommands} |
| 595 | |
| 596 | # The project list, published in the instance repository for clients to |
| 597 | # discover this host's projects by (valley changes --all): a blob at |
| 598 | # ${projectsRef} naming every enabled git project, one per line, |
| 599 | # sorted, and nothing else. A host without an instance repository |
| 600 | # publishes nothing. The name of every project is disclosed to whoever |
| 601 | # can read the instance repository. No push may write the ref, since |
| 602 | # the hook refuses every refs/the-valley/* it does not name, so init is |
| 603 | # its only writer. It is written before the share sweep below, which |
| 604 | # then gives the new object the group's permissions. A list that cannot |
| 605 | # be written costs discovery and not the host, so it warns. |
| 606 | ${lib.optionalString (instanceRepo != null) '' |
| 607 | { |
| 608 | projects="$(printf '%s\n' ${lib.escapeShellArgs (lib.sort lib.lessThan repoNames)} | |
| 609 | git -C ${instanceRepo} hash-object -w --stdin)" && |
| 610 | git -C ${instanceRepo} update-ref ${projectsRef} "$projects" |
| 611 | } || echo "valley-init: could not publish the project list at ${projectsRef} in ${instanceRepo}; clients cannot discover this host's projects until it is" >&2 |
| 612 | ''} |
| 613 | |
| 614 | # Group-shared repositories, on what the integrator serves. |
| 615 | ${lib.optionalString cfg.integrator.enable integratorShareCommands} |
| 616 | |
| 617 | if [ "$conflicts" -ne 0 ]; then |
| 618 | echo "valley-init: refusing to report this host converged: the push policy is not what every repository runs" >&2 |
| 619 | exit 1 |
| 620 | fi |
| 621 | ''; |
| 622 | |
| 623 | # The configuration a convergence is of: the init script itself, which |
| 624 | # names every hook and every policy file it wires. valley-init records it |
| 625 | # when it converges, and the git user's shell lets a push through only |
| 626 | # while the record names the configuration the shell was rendered with. |
| 627 | convergenceId = builtins.substring 0 32 (builtins.hashString "sha256" valleyInitBody); |
| 628 | |
| 629 | # The record, in the git user's home: valley-init writes it, and nothing |
| 630 | # a session reaches can. A dot file never collides with a repository, |
| 631 | # because project names begin with an alphanumeric. |
| 632 | convergedRecord = "${cfg.dataDir}/.valley-converged"; |
| 633 | |
| 634 | # The operator's hold on pushes: while this file exists, the git user's |
| 635 | # shell refuses every push, whatever valley-init has recorded. valley-init |
| 636 | # never touches it, so a hold placed before a deploy outlasts the |
| 637 | # convergence and lasts until the operator removes it — the window a |
| 638 | # deploy's audits need. |
| 639 | pushHold = "${cfg.dataDir}/.valley-hold"; |
| 640 | |
| 641 | # The git user's login shell (valleyhook shell). sshd runs it for every |
| 642 | # session, and it names the key files sshd authorizes the git user's keys |
| 643 | # from, in sshd's order, so it can find the authenticated key's tag. |
| 644 | gitShell = pkgs.writeShellScriptBin "valley-git-shell" '' |
| 645 | exec ${valleyhookPackage}/bin/valleyhook shell \ |
| 646 | --converged ${convergedRecord} \ |
| 647 | --expect ${convergenceId} \ |
| 648 | --hold ${pushHold} \ |
| 649 | --authorized-keys /etc/ssh/authorized_keys.d/${cfg.user} ${ |
| 650 | lib.optionalString cfg.identity.enable "--authorized-keys ${identityAuthorizedKeys}" |
| 651 | } \ |
| 652 | -- "$@" |
| 653 | ''; |
| 654 | |
| 655 | # The program every project's pre-receive hook runs: the whole of the ref |
| 656 | # policy (valleyhook/), built by this flake. |
| 657 | valleyhookPackage = (import ./packages.nix { inherit pkgs lib; }).valleyhook; |
| 658 | |
| 659 | # The grants declared by hand, in the format the compiler writes, so the |
| 660 | # hook reads one format whichever wrote it. The holders of the approve |
| 661 | # grant are one set under either option, written under the name request |
| 662 | # the way the compiler writes them, and a principal named in both is |
| 663 | # written once. |
| 664 | declaredGrants = pkgs.writeText "valley-grants" ( |
| 665 | '' |
| 666 | # Declared in services.valley.grants — do not edit. |
| 667 | '' |
| 668 | + lib.concatMapStrings (principal: "request ${principal}\n") ( |
| 669 | lib.unique (cfg.grants.approve ++ cfg.grants.request) |
| 670 | ) |
| 671 | + lib.concatMapStrings (principal: "restack ${principal}\n") cfg.grants.restack |
| 672 | ); |
| 673 | |
| 674 | # Every file the hook reads grants from. The compiled file is added to the |
| 675 | # declared one rather than replacing it, the same way the compiled keys |
| 676 | # are added to the declared keys: a compilation can only ever grant more. |
| 677 | grantFiles = [ declaredGrants ] ++ lib.optional cfg.identity.enable identityGrants; |
| 678 | |
| 679 | # The keys a pushed attestation's signature is checked against: the ones |
| 680 | # a controller accepts evidence from. An attestation no controller here |
| 681 | # would accept cannot take a name in the create-only namespace, and a host |
| 682 | # that names no such keys accepts no attestation at all. |
| 683 | hookVerifiers = lib.optional (knownSigners != "") knownSigners; |
| 684 | |
| 685 | # What a project declares about pushes, as valleyhook reads it: the |
| 686 | # protected refs and their writers, empty for a project that declares no |
| 687 | # protection, and the project's named grants. |
| 688 | pushPolicy = |
| 689 | name: p: |
| 690 | pkgs.writeText "valley-push-policy-${name}.json" ( |
| 691 | builtins.toJSON { |
| 692 | refs = p.protection.refs or [ ]; |
| 693 | writers = p.protection.writers or [ ]; |
| 694 | grants = p.grants or { }; |
| 695 | } |
| 696 | ); |
| 697 | |
| 698 | # The pre-receive hook: the one structural git invariant |
| 699 | # (archive/design/architecture.md, archive/design/contribute.md), which is what a push may |
| 700 | # write. It is installed on every project the host serves. Replacement |
| 701 | # refs, notes and the valley's own namespace take no push, but for the |
| 702 | # four namespaces below; a symbolic ref takes none; topic branches are |
| 703 | # open; an attestation ref may only be created, and only holding what its |
| 704 | # name says; an integration request takes the approve grant; a change |
| 705 | # record moves only by the transitions the hook allows; the plan graph, |
| 706 | # refs/the-valley/knots, takes any named principal's write of one commit |
| 707 | # on its tip that keeps the graph valid; every other ref, tags included, |
| 708 | # takes a named grant of the project; and a protected ref also takes a |
| 709 | # declared writer. All policy beyond this lives in the integrator. |
| 710 | # |
| 711 | # The rules are valleyhook's, in Go, and this script is only how git |
| 712 | # reaches it. It hands over what the policy is a function of: the pushing |
| 713 | # principal, the project's declared push policy, the grants, the keys an |
| 714 | # attestation is checked against, and the hook a project composes after |
| 715 | # it, if it declares one. |
| 716 | # |
| 717 | # A declaration usually names no writer at all, and then the protected |
| 718 | # refs take no push from anyone. That is the norm, not a |
| 719 | # misconfiguration: the integrator writes the ref locally, and a local |
| 720 | # write is not a push. |
| 721 | # |
| 722 | # Pushes arrive over SSH as one shared git user, so the unix account |
| 723 | # behind a push says nothing about who pushed. The principal comes from |
| 724 | # the key instead: services.valley.authorizedKeys tags each key's |
| 725 | # authorized_keys entry, the git user's shell reads the tag off the entry |
| 726 | # of the key sshd authenticated and puts it in the environment of the |
| 727 | # receive-pack this hook runs under, and an untagged key has no principal |
| 728 | # at all. The client cannot supply the tag itself: the shell drops any it |
| 729 | # arrives with, and the assertions below hold sshd to offering no client |
| 730 | # environment that could carry it. |
| 731 | # |
| 732 | # This governs pushes, which is every write that crosses the host |
| 733 | # boundary. It does not govern writes made on the host: the integrator |
| 734 | # updates refs locally, as could anyone holding the git user's shell. |
| 735 | # Local access is the host's own boundary, not this hook's. |
| 736 | protectHook = |
| 737 | name: p: |
| 738 | pkgs.writeShellScript "valley-protect-${name}" '' |
| 739 | # Managed by services.valley — do not edit. |
| 740 | exec ${valleyhookPackage}/bin/valleyhook pre-receive \ |
| 741 | --project ${lib.escapeShellArg name} \ |
| 742 | --policy ${pushPolicy name p} \ |
| 743 | ${lib.concatMapStringsSep " " (f: "--grants ${f}") grantFiles} \ |
| 744 | ${lib.concatMapStringsSep " " (f: "--known-signers ${f}") hookVerifiers} \ |
| 745 | ${lib.optionalString (cfg.extraPreReceive ? ${name}) "--then ${cfg.extraPreReceive.${name}}"} \ |
| 746 | --principal="''${${principalEnv}:-}" |
| 747 | ''; |
| 748 | |
| 749 | # Per-project pre-receive wiring, on every project the host serves. A |
| 750 | # hook that is not this module's is a hook that would run instead of the |
| 751 | # push policy, so valley-init refuses to leave one in place: it says so, |
| 752 | # and the activation fails once everything else is wired. The one |
| 753 | # exception is a hook identical to the one the project composes after the |
| 754 | # policy (services.valley.extraPreReceive), which is checked byte for byte |
| 755 | # and then replaced, since the managed hook runs it. A store symlink is |
| 756 | # this module's, whichever store path it names, and is re-pointed. |
| 757 | # |
| 758 | # core.hooksPath moves where git looks for hooks at all, from any scope |
| 759 | # the git user reads — the repository's config, the user's, the system's, |
| 760 | # or a file one of them includes. A repository whose hooks path is set at |
| 761 | # all, to an empty value included, is refused the same way, with no |
| 762 | # exception. |
| 763 | protectHookCommands = lib.concatStrings ( |
| 764 | lib.mapAttrsToList (name: p: '' |
| 765 | served=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"} |
| 766 | phook="$served/hooks/pre-receive" |
| 767 | managed=${protectHook name p} |
| 768 | composed=${lib.escapeShellArg (toString (cfg.extraPreReceive.${name} or ""))} |
| 769 | if [ -L "$phook" ] && [[ "$(readlink "$phook")" == /nix/store/* ]]; then |
| 770 | ln -sfn "$managed" "$phook" |
| 771 | elif [ ! -e "$phook" ] && [ ! -L "$phook" ]; then |
| 772 | ln -s "$managed" "$phook" |
| 773 | elif [ -n "$composed" ] && [ -f "$phook" ] && cmp -s "$phook" "$composed"; then |
| 774 | 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 |
| 775 | ln -sfn "$managed" "$phook" |
| 776 | else |
| 777 | 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 |
| 778 | conflicts=1 |
| 779 | fi |
| 780 | # Exit status 1 is the one answer that means unset. A value, an |
| 781 | # empty one included — git then looks for hooks relative to where it |
| 782 | # runs — and a configuration git cannot read are all refused. |
| 783 | hooks_path="$(git -C "$served" config --get core.hooksPath)" && status=0 || status=$? |
| 784 | if [ "$status" -ne 1 ]; then |
| 785 | 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 |
| 786 | conflicts=1 |
| 787 | fi |
| 788 | '') gitProjects |
| 789 | ); |
| 790 | |
| 791 | # sshd's environment patterns, for the assertions that hold it to |
| 792 | # accepting no client environment the push boundary reads. `*` and `?` are |
| 793 | # the only wildcards an AcceptEnv pattern has, and a pattern is matched |
| 794 | # as written: variable names are case-sensitive. |
| 795 | sshPatternMatches = |
| 796 | pattern: name: |
| 797 | builtins.match (lib.concatMapStrings ( |
| 798 | c: |
| 799 | if c == "*" then |
| 800 | ".*" |
| 801 | else if c == "?" then |
| 802 | "." |
| 803 | else if builtins.match "[A-Za-z0-9_]" c != null then |
| 804 | c |
| 805 | else |
| 806 | "\\${c}" |
| 807 | ) (lib.stringToCharacters pattern)) name != null; |
| 808 | |
| 809 | # Whether some name beginning with prefix matches pattern: the pattern |
| 810 | # walked over the prefix, with the rest of the name free. |
| 811 | sshPatternMatchesSomeName = |
| 812 | pattern: prefix: |
| 813 | if prefix == "" then |
| 814 | true |
| 815 | else if pattern == "" then |
| 816 | false |
| 817 | else |
| 818 | let |
| 819 | c = builtins.substring 0 1 pattern; |
| 820 | rest = builtins.substring 1 (-1) pattern; |
| 821 | next = builtins.substring 1 (-1) prefix; |
| 822 | in |
| 823 | if c == "*" then |
| 824 | sshPatternMatchesSomeName rest prefix || sshPatternMatchesSomeName pattern next |
| 825 | else if c == "?" || c == builtins.substring 0 1 prefix then |
| 826 | sshPatternMatchesSomeName rest next |
| 827 | else |
| 828 | false; |
| 829 | |
| 830 | # A variable the push boundary reads, and no client may supply: the |
| 831 | # principal, and anything git reads its configuration, hooks or objects |
| 832 | # from. |
| 833 | boundaryVariable = pattern: sshPatternMatches pattern principalEnv || sshPatternMatchesSomeName pattern "GIT_"; |
| 834 | |
| 835 | # A refname glob as the declaration writes one, where `*` crosses path |
| 836 | # separators (schema/valley.cue). |
| 837 | refPatternMatches = |
| 838 | pattern: ref: |
| 839 | builtins.match (lib.concatMapStrings ( |
| 840 | c: |
| 841 | if c == "*" then |
| 842 | ".*" |
| 843 | else if builtins.match "[A-Za-z0-9/_-]" c != null then |
| 844 | c |
| 845 | else |
| 846 | "\\${c}" |
| 847 | ) (lib.stringToCharacters pattern)) ref != null; |
| 848 | |
| 849 | # Every value sshd is given for one keyword, from the settings and from |
| 850 | # every line of extraConfig, inside a Match block or not. The keyword is |
| 851 | # matched in any case, as sshd matches it, with or without `=` after it; |
| 852 | # the values are kept as written, because sshd's patterns and variable |
| 853 | # names are case-sensitive. Values are split on any whitespace, tabs |
| 854 | # included, as sshd splits them. Quoting and escapes are not unpicked |
| 855 | # here: a value holding a quote or a backslash is refused below instead, |
| 856 | # because a reading that differed from sshd's would be a hole. |
| 857 | sshdValues = |
| 858 | keyword: |
| 859 | let |
| 860 | settings = config.services.openssh.settings; |
| 861 | word = x: if lib.isBool x then (if x then "yes" else "no") else toString x; |
| 862 | words = v: lib.filter (w: lib.isString w && w != "") (builtins.split "[[:space:]]+" v); |
| 863 | fromSettings = lib.concatMap ( |
| 864 | k: |
| 865 | let |
| 866 | v = settings.${k}; |
| 867 | in |
| 868 | if lib.isList v then lib.concatMap (x: words (word x)) v else words (word v) |
| 869 | ) (lib.filter (k: lib.toLower k == lib.toLower keyword && settings.${k} != null) (lib.attrNames settings)); |
| 870 | fromExtra = lib.concatMap ( |
| 871 | line: |
| 872 | let |
| 873 | m = builtins.match "[[:space:]]*([A-Za-z]+)[[:space:]]*=?[[:space:]]*(.*)" line; |
| 874 | in |
| 875 | if m == null || lib.toLower (lib.head m) != lib.toLower keyword then |
| 876 | [ ] |
| 877 | else |
| 878 | words (lib.elemAt m 1) |
| 879 | ) (lib.splitString "\n" config.services.openssh.extraConfig); |
| 880 | in |
| 881 | fromSettings ++ fromExtra; |
| 882 | |
| 883 | # Every key line the git user's declared authorized_keys holds, from this |
| 884 | # module and from any other, with the principal its tag names ("" for |
| 885 | # none) and the key itself. |
| 886 | declaredKeyEntries = lib.concatMap ( |
| 887 | line: |
| 888 | let |
| 889 | key = builtins.match "(.*[[:space:]])?((ssh|ecdsa|sk)-[^[:space:]\"]+)[[:space:]]+([A-Za-z0-9+/=]+)([[:space:]].*)?" line; |
| 890 | tag = builtins.match ".*environment=\"${principalEnv}=([^\"]*)\".*" line; |
| 891 | in |
| 892 | lib.optional (key != null) { |
| 893 | key = lib.elemAt key 3; |
| 894 | principal = if tag == null then "" else lib.head tag; |
| 895 | } |
| 896 | ) config.users.users.${cfg.user}.openssh.authorizedKeys.keys; |
| 897 | |
| 898 | # Keys declared more than once under different tags. sshd authorizes a |
| 899 | # key by the first entry that names it, so which principal such a key |
| 900 | # pushes as depends on file order; the assertion below refuses it. |
| 901 | conflictingKeys = lib.filterAttrs (_: entries: lib.length (lib.unique (map (e: e.principal) entries)) > 1) ( |
| 902 | lib.groupBy (e: e.key) declaredKeyEntries |
| 903 | ); |
| 904 | |
| 905 | # The declared key lines, for the compiler: a compiled key that is also |
| 906 | # declared under another tag is refused there, for the same reason. |
| 907 | declaredKeysFile = pkgs.writeText "valley-declared-keys" ( |
| 908 | lib.concatLines config.users.users.${cfg.user}.openssh.authorizedKeys.keys |
| 909 | ); |
| 910 | in |
| 911 | { |
| 912 | options.services.valley = { |
| 913 | enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration"; |
| 914 | |
| 915 | user = lib.mkOption { |
| 916 | type = lib.types.str; |
| 917 | default = "git"; |
| 918 | description = "System user that owns the repositories and accepts SSH pushes."; |
| 919 | }; |
| 920 | |
| 921 | group = lib.mkOption { |
| 922 | type = lib.types.str; |
| 923 | default = "git"; |
| 924 | description = "Primary group of the valley git user."; |
| 925 | }; |
| 926 | |
| 927 | dataDir = lib.mkOption { |
| 928 | type = lib.types.path; |
| 929 | default = "/srv/git"; |
| 930 | example = "/mnt/git"; |
| 931 | description = '' |
| 932 | Directory holding the bare repositories, one `<name>.git` per |
| 933 | project declared in {option}`services.valley.config`. Also the git |
| 934 | user's home, so clone URLs are relative to it (`git@host:name.git`). |
| 935 | Consumers typically point it at a dedicated dataset. |
| 936 | ''; |
| 937 | }; |
| 938 | |
| 939 | authorizedKeys = lib.mkOption { |
| 940 | type = lib.types.listOf ( |
| 941 | lib.types.either lib.types.str ( |
| 942 | lib.types.submodule { |
| 943 | options = { |
| 944 | key = lib.mkOption { |
| 945 | type = lib.types.str; |
| 946 | description = "The SSH public key, as it would appear in `authorized_keys`."; |
| 947 | }; |
| 948 | |
| 949 | principal = lib.mkOption { |
| 950 | type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"; |
| 951 | example = "integrator"; |
| 952 | description = '' |
| 953 | Name of the principal this key acts as. Every push made |
| 954 | with the key carries the name, and the pre-receive hook |
| 955 | decides what the name may write: from the project's |
| 956 | `protection` block and named grants in |
| 957 | {option}`services.valley.config`, and from the grants the |
| 958 | name holds ({option}`services.valley.grants`, and the |
| 959 | registry's when it is compiled). Nothing else uses it. |
| 960 | A key is declared once: the same key under two tags, or |
| 961 | tagged and untagged, is refused. |
| 962 | ''; |
| 963 | }; |
| 964 | }; |
| 965 | } |
| 966 | ) |
| 967 | ); |
| 968 | default = [ ]; |
| 969 | example = lib.literalExpression '' |
| 970 | [ |
| 971 | "ssh-ed25519 AAAA… someone@somewhere" |
| 972 | { |
| 973 | principal = "integrator"; |
| 974 | key = "ssh-ed25519 AAAA… integrator"; |
| 975 | } |
| 976 | ] |
| 977 | ''; |
| 978 | description = '' |
| 979 | SSH public keys allowed to push/fetch as the git user. Access is |
| 980 | host-level by design: every key can reach every project. |
| 981 | |
| 982 | A key written as a plain string is anonymous — it can push, and it |
| 983 | can write nothing protected. A key written as an attribute set |
| 984 | names the principal it acts as, which is the only thing that can |
| 985 | tell one pusher from another: pushes arrive as the shared git user, |
| 986 | so identity has to ride on the key. |
| 987 | |
| 988 | Which refs a principal may write is declared, not an option here: |
| 989 | it is a statement about what the host serves, and lives in the |
| 990 | project's `protection` block in |
| 991 | {option}`services.valley.config`. Binding a name to keys is the |
| 992 | machine half — the hand-written form of what the identity registry |
| 993 | compiles (dcr-b87f6e8). |
| 994 | |
| 995 | With {option}`services.valley.identity.enable` on, the compiled |
| 996 | keys are added to what sshd reads and the keys here stay |
| 997 | authorized beside them. The list is therefore the way back in when |
| 998 | a compilation is wrong or has not happened yet, and it is never |
| 999 | empty. |
| 1000 | ''; |
| 1001 | }; |
| 1002 | |
| 1003 | extraPreReceive = lib.mkOption { |
| 1004 | type = lib.types.attrsOf lib.types.pathInStore; |
| 1005 | default = { }; |
| 1006 | example = lib.literalExpression '' |
| 1007 | { |
| 1008 | cosmo = pkgs.writeShellScript "cosmo-pre-receive" ; |
| 1009 | } |
| 1010 | ''; |
| 1011 | description = '' |
| 1012 | A further pre-receive hook per project, run after the push policy |
| 1013 | accepts a push, with the same input. It can refuse what the policy |
| 1014 | accepts and never accept what the policy refuses. |
| 1015 | |
| 1016 | This is the one way to compose a hook with the managed one. A |
| 1017 | pre-receive hook the module did not write fails valley-init, |
| 1018 | because git would run it instead of the policy. A hook that is |
| 1019 | byte-for-byte the one declared here is the exception: valley-init |
| 1020 | replaces it with the managed hook, which runs it. The value is a |
| 1021 | store path, so what runs is exactly what was declared. |
| 1022 | ''; |
| 1023 | }; |
| 1024 | |
| 1025 | # Grants held by hand. The registry names who holds a grant |
| 1026 | # (dcr-b87f6e8, dcr-e544f20), and these options are the hand-written |
| 1027 | # form of what it compiles, beside it the way the declared keys sit |
| 1028 | # beside the compiled ones. |
| 1029 | grants = { |
| 1030 | approve = lib.mkOption { |
| 1031 | type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"); |
| 1032 | default = [ ]; |
| 1033 | example = [ "operator" ]; |
| 1034 | description = '' |
| 1035 | Principals holding the approve grant (also accepted as |
| 1036 | {option}`services.valley.grants.request`): the ones whose pushes |
| 1037 | may file, replace and withdraw an integration request |
| 1038 | (`refs/the-valley/integration-requests/*`) on a protected |
| 1039 | project. The pre-receive hook refuses every other write to that |
| 1040 | namespace, so a principal named neither here, nor in |
| 1041 | {option}`services.valley.grants.request`, nor in the registry |
| 1042 | cannot file an integration request. |
| 1043 | |
| 1044 | The two options are one grant. The holders are the principals |
| 1045 | named in either list, and a principal named in both holds the |
| 1046 | grant once. |
| 1047 | |
| 1048 | The grant rides on push. Only a key sshd admits reaches the hook, |
| 1049 | so a principal named here also needs a key, declared in |
| 1050 | {option}`services.valley.authorizedKeys` or compiled from the |
| 1051 | registry. |
| 1052 | |
| 1053 | With {option}`services.valley.identity.enable` on, the holders |
| 1054 | the registry names are added to these, and a compiled file can |
| 1055 | only ever add. The list is therefore how a host grants approve |
| 1056 | before its registry does — including to the operator who has to |
| 1057 | file the registry change that grants it. |
| 1058 | ''; |
| 1059 | }; |
| 1060 | |
| 1061 | request = lib.mkOption { |
| 1062 | type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"); |
| 1063 | default = [ ]; |
| 1064 | example = [ "operator" ]; |
| 1065 | description = '' |
| 1066 | Principals holding the approve grant, under the name it had |
| 1067 | first. A principal named here holds exactly what one named in |
| 1068 | {option}`services.valley.grants.approve` holds, and the holders |
| 1069 | are the principals named in either list. |
| 1070 | ''; |
| 1071 | }; |
| 1072 | |
| 1073 | restack = lib.mkOption { |
| 1074 | type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"); |
| 1075 | default = [ ]; |
| 1076 | example = [ "valley-restacker" ]; |
| 1077 | description = '' |
| 1078 | Principals holding the restack grant: the host restacker's. A |
| 1079 | holder that neither owns a change nor holds the approve grant may |
| 1080 | add exactly one version to the change's record while the change |
| 1081 | is ready, on the branch and under the title of its active version, |
| 1082 | with itself as the uploader. It may also write restack reports |
| 1083 | (`refs/the-valley/restack/main/<change-id>`). The grant permits |
| 1084 | no other record write and nothing on integration requests, and a |
| 1085 | holder keeps every ordinary power of a named principal. |
| 1086 | |
| 1087 | The grant rides on push, like approve: a principal named here also |
| 1088 | needs a key. With {option}`services.valley.identity.enable` on, |
| 1089 | the holders the registry names are added to these. The list is |
| 1090 | how a host grants restack before its registry does; remove an |
| 1091 | entry once the registry grants the same principal. |
| 1092 | ''; |
| 1093 | }; |
| 1094 | }; |
| 1095 | |
| 1096 | config = lib.mkOption { |
| 1097 | type = lib.types.path; |
| 1098 | example = lib.literalExpression "./valley.cue"; |
| 1099 | description = '' |
| 1100 | Path to the host's CUE declaration (`package valley`) — the |
| 1101 | canonical statement of what this valley host serves, validated |
| 1102 | against the shipped schema at build time. This is the single domain |
| 1103 | input: projects, their push mirrors, and the backup policy are |
| 1104 | declared here, never as Nix options. |
| 1105 | ''; |
| 1106 | }; |
| 1107 | |
| 1108 | # The event bus. Machine options, not domain: whether this machine runs |
| 1109 | # a bus, where it listens, and where its storage lives. What gets |
| 1110 | # published onto it is defined portably in ../schema/events.cue. |
| 1111 | bus = { |
| 1112 | enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events"; |
| 1113 | |
| 1114 | listen = lib.mkOption { |
| 1115 | type = lib.types.str; |
| 1116 | default = "127.0.0.1:4222"; |
| 1117 | example = "100.100.1.7:4222"; |
| 1118 | description = '' |
| 1119 | Address the bus listens on, `host:port`. Localhost by default: |
| 1120 | nothing off the host can reach the bus until the consumer widens |
| 1121 | this deliberately — e.g. to the host's tailnet address once a |
| 1122 | remote `valley tail` wants in. Local publishers (the ref-updated |
| 1123 | hook) connect to this same address, so it must be reachable from |
| 1124 | the host itself. |
| 1125 | ''; |
| 1126 | }; |
| 1127 | |
| 1128 | storeDir = lib.mkOption { |
| 1129 | type = lib.types.path; |
| 1130 | default = "${cfg.dataDir}/.bus"; |
| 1131 | defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"''; |
| 1132 | description = '' |
| 1133 | Directory holding the JetStream file storage. The default lives |
| 1134 | under {option}`services.valley.dataDir`; it can never collide |
| 1135 | with a repository because project names must start with an |
| 1136 | alphanumeric. The stream is a projection of git, rebuildable |
| 1137 | with `valley replay` — losing this directory costs one replay. |
| 1138 | ''; |
| 1139 | }; |
| 1140 | }; |
| 1141 | |
| 1142 | # The integrator (archive/design/roadmap.md, Phase 3): the controller that |
| 1143 | # lands a change once its evidence still transfers to the current tip. |
| 1144 | # Machine options only — whether this host runs controllers, who they |
| 1145 | # are, and how often they look. Which projects get one is not an option |
| 1146 | # either: it follows from which projects the declaration protects, |
| 1147 | # because a protected ref is exactly what a controller exists to write. |
| 1148 | integrator = { |
| 1149 | enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers"; |
| 1150 | |
| 1151 | user = lib.mkOption { |
| 1152 | type = lib.types.str; |
| 1153 | default = "valley-integrator"; |
| 1154 | description = '' |
| 1155 | System user the controllers run as. Deliberately not |
| 1156 | {option}`services.valley.user`: one unix identity per service is |
| 1157 | the split bd-500adf7 asks for, and this service begins it. |
| 1158 | |
| 1159 | The account exists only to write the repositories it serves. It |
| 1160 | gets no shell and no SSH key, and its primary group is |
| 1161 | {option}`services.valley.group`, which is the whole of its |
| 1162 | permission model: {option}`services.valley.dataDir` is already |
| 1163 | group-readable, and each served repository is made group-shared |
| 1164 | (group write, setgid directories) so a controller can write |
| 1165 | refs, objects, and git's worktree metadata. Nothing else on the |
| 1166 | host belongs to that group, and the bus's store directory (mode |
| 1167 | 0700) stays out of reach. |
| 1168 | |
| 1169 | The key and signers files are the consumer's to provision; both |
| 1170 | must be readable by this user. |
| 1171 | ''; |
| 1172 | }; |
| 1173 | |
| 1174 | signingKeyFile = lib.mkOption { |
| 1175 | type = lib.types.nullOr lib.types.path; |
| 1176 | default = null; |
| 1177 | example = "/run/agenix/valley-integrator-key"; |
| 1178 | description = '' |
| 1179 | ed25519 private key the controllers sign their transfer |
| 1180 | statements with. A runtime path the consumer provisions (e.g. |
| 1181 | agenix), never a store path — the store is world-readable. |
| 1182 | ''; |
| 1183 | }; |
| 1184 | |
| 1185 | knownSignersFile = lib.mkOption { |
| 1186 | type = lib.types.nullOr lib.types.path; |
| 1187 | default = null; |
| 1188 | example = "/var/lib/valley-instance/known_signers"; |
| 1189 | description = '' |
| 1190 | File of verifier keys whose attestations count, one per line, in |
| 1191 | `attest key` format. This is the identity registry's interim |
| 1192 | compilation (dcr-b87f6e8), supplied directly for a host that does |
| 1193 | not compile one: turning on |
| 1194 | {option}`services.valley.identity.enable` renders the same file |
| 1195 | from the registry, and then this option must be left unset. |
| 1196 | Evidence signed by nobody in it does not transfer, which a |
| 1197 | controller reports per check rather than treating as a forgery. |
| 1198 | ''; |
| 1199 | }; |
| 1200 | |
| 1201 | signerProjects = lib.mkOption { |
| 1202 | type = lib.types.attrsOf (lib.types.listOf lib.types.str); |
| 1203 | default = { }; |
| 1204 | example = { |
| 1205 | "laddie-worker/attestations" = [ "the-valley" ]; |
| 1206 | }; |
| 1207 | description = '' |
| 1208 | Signers whose attestations count only in the projects listed for |
| 1209 | them, by the name each signs under. A signer named here counts |
| 1210 | in its listed projects alone; in any other project a controller |
| 1211 | reports its evidence as signed by no signer it holds. An empty |
| 1212 | list lets the signer count nowhere. A signer not named here |
| 1213 | counts wherever the known-signers file lets it. |
| 1214 | |
| 1215 | This is how a check worker's key, which every controller sharing |
| 1216 | the known-signers file would otherwise accept, is trusted only |
| 1217 | for the projects it builds. The push hook still admits the |
| 1218 | worker's evidence everywhere; only the controllers restrict it. |
| 1219 | |
| 1220 | The list is rendered into a file every controller reads at start. |
| 1221 | A host that publishes its signers publishes the file beside them, |
| 1222 | so a client can read the same restriction. Names and projects are |
| 1223 | words of printable ASCII with no space, and a name holds no plus |
| 1224 | and does not open with #. The list may not name the name the |
| 1225 | controllers sign under: a controller given such a list refuses to |
| 1226 | start. |
| 1227 | ''; |
| 1228 | }; |
| 1229 | |
| 1230 | signingName = lib.mkOption { |
| 1231 | type = lib.types.nullOr lib.types.str; |
| 1232 | default = null; |
| 1233 | example = "integrator"; |
| 1234 | description = '' |
| 1235 | The name a controller's transfer statements are signed under. |
| 1236 | Unset leaves the binary's own default, which is this host's |
| 1237 | attestations name — the machine signing as itself. |
| 1238 | |
| 1239 | Set it to the name the identity registry publishes the |
| 1240 | integrator's key under. The note format's key hash binds the name |
| 1241 | to the key (dcr-de9d996), so a controller signing under one name |
| 1242 | while the registry publishes it under another produces notes no |
| 1243 | verifier can find a key for. |
| 1244 | ''; |
| 1245 | }; |
| 1246 | |
| 1247 | instanceProject = lib.mkOption { |
| 1248 | type = lib.types.nullOr lib.types.str; |
| 1249 | default = null; |
| 1250 | example = "qinling"; |
| 1251 | description = '' |
| 1252 | The project whose served repository carries the group's floor — |
| 1253 | the instance policy layer every controller on this host composes |
| 1254 | against. A controller reads it from `policy/instance/` in that |
| 1255 | bare repository's integrated tip, and nothing is materialized on |
| 1256 | disk in between. It is also where the identity registry is read |
| 1257 | from, for the same reason and at the same altitude: both are the |
| 1258 | instance's, so a host serving that repository already holds the |
| 1259 | authoritative copy. |
| 1260 | |
| 1261 | The floor is the instance repository's, read at the tip that has |
| 1262 | been integrated (dcr-f41f718); the instance repository is the |
| 1263 | group's own (dcr-b87f6e8). A host serving it is therefore already |
| 1264 | holding the authoritative copy. |
| 1265 | |
| 1266 | What follows is a property of that design, and worth knowing |
| 1267 | before editing a floor. A change to it takes effect at the first |
| 1268 | pass after it lands on that ref, and never before. An edit in a |
| 1269 | branch, in a worktree, or in an integration request that has not |
| 1270 | been integrated governs nothing. There is no refresh to trigger |
| 1271 | and no staleness to wait out: landing is the whole of publishing |
| 1272 | a floor. |
| 1273 | |
| 1274 | The project has to declare protection covering refs/heads/main, |
| 1275 | and the registry's ref when the identity compiler is on. Both |
| 1276 | are read from that tip, so a ref any push-capable key could move |
| 1277 | would hand every key the floor and the registry. |
| 1278 | |
| 1279 | Every controller on the host reads the same repository, the |
| 1280 | controller serving that repository included. Both layers are |
| 1281 | resolved from the controller's own side — this one, and the |
| 1282 | project's `policy/project/` at the target tip — so a change can |
| 1283 | never supply the policy that gates it (bd-eaefe82). |
| 1284 | |
| 1285 | Those two directories are the convention, and the module states |
| 1286 | neither: a controller takes each layer from the place the |
| 1287 | integrator defaults to, so a host declaration that says nothing |
| 1288 | about policy gets the layout the worked example lays out |
| 1289 | (dcr-f41f718). |
| 1290 | ''; |
| 1291 | }; |
| 1292 | |
| 1293 | instancePolicy = lib.mkOption { |
| 1294 | type = lib.types.nullOr lib.types.path; |
| 1295 | default = null; |
| 1296 | example = "/var/lib/valley-instance/policy/instance"; |
| 1297 | description = '' |
| 1298 | Directory of `*.cue` files holding the instance policy layer, for |
| 1299 | a host that serves no instance repository. It holds what |
| 1300 | `policy/instance/` in the instance repository holds. Set this or |
| 1301 | {option}`services.valley.integrator.instanceProject`, never both. |
| 1302 | |
| 1303 | Keeping such a directory in step with the instance repository is |
| 1304 | the consumer's to arrange, which is the reason to prefer the |
| 1305 | project option wherever the host serves the repository. |
| 1306 | ''; |
| 1307 | }; |
| 1308 | |
| 1309 | interval = lib.mkOption { |
| 1310 | type = lib.types.str; |
| 1311 | default = "15s"; |
| 1312 | example = "1m"; |
| 1313 | description = '' |
| 1314 | How long a controller waits between passes. The integrator polls |
| 1315 | deliberately: integration requests are durable in git, and the |
| 1316 | controller level-triggers over those refs, so a lost event costs |
| 1317 | one interval and nothing more. |
| 1318 | ''; |
| 1319 | }; |
| 1320 | }; |
| 1321 | |
| 1322 | # The identity registry compiler (dcr-b87f6e8): the step between the |
| 1323 | # instance's declared registry and the two gates that read what it |
| 1324 | # compiles to. Machine options only — whether this host compiles, and |
| 1325 | # from where. Who the principals are, what they hold and when their |
| 1326 | # entries end is the registry's, and the registry is a document in the |
| 1327 | # instance repository, never an option here. |
| 1328 | identity = { |
| 1329 | enable = lib.mkEnableOption '' |
| 1330 | compiling the identity registry into what the gates check: the |
| 1331 | verifier keys a controller accepts evidence from, and the git |
| 1332 | user's authorized keys, both rendered from the instance |
| 1333 | repository's integrated tip''; |
| 1334 | |
| 1335 | ref = lib.mkOption { |
| 1336 | type = lib.types.str; |
| 1337 | default = "refs/heads/main"; |
| 1338 | description = '' |
| 1339 | The ref of the instance repository whose tip carries the |
| 1340 | registry. A registry edit takes effect at the first compilation |
| 1341 | after it lands on this ref, and never before: an edit in a |
| 1342 | branch, in a worktree, or in an integration request that has not |
| 1343 | been integrated governs nothing. |
| 1344 | ''; |
| 1345 | }; |
| 1346 | |
| 1347 | directory = lib.mkOption { |
| 1348 | type = lib.types.str; |
| 1349 | default = "identity"; |
| 1350 | description = '' |
| 1351 | The registry's directory in that tip. It is a CUE package: the |
| 1352 | directory is the enumeration, and every `*.cue` document |
| 1353 | directly in it unifies into one registry. |
| 1354 | ''; |
| 1355 | }; |
| 1356 | |
| 1357 | interval = lib.mkOption { |
| 1358 | type = lib.types.str; |
| 1359 | default = "5m"; |
| 1360 | example = "1m"; |
| 1361 | description = '' |
| 1362 | How long between compilations. The compiler is level-triggered |
| 1363 | and idempotent — it renders the current tip and replaces an |
| 1364 | artifact only when its bytes changed — so a timer is the whole |
| 1365 | of the trigger, and a landed registry change takes effect within |
| 1366 | one interval. |
| 1367 | ''; |
| 1368 | }; |
| 1369 | }; |
| 1370 | |
| 1371 | # Machine integration for the declared backup policy. The declaration |
| 1372 | # states WHAT must hold (offsite backup, cadence, retention); these |
| 1373 | # options supply HOW on this machine — where the repository is and how |
| 1374 | # to authenticate. All are paths to files the consumer provisions |
| 1375 | # (e.g. agenix), required when the declaration enables backup. Point |
| 1376 | # them at runtime paths, never at files in the Nix store. |
| 1377 | backup = { |
| 1378 | repositoryFile = lib.mkOption { |
| 1379 | type = lib.types.nullOr lib.types.path; |
| 1380 | default = null; |
| 1381 | example = "/run/agenix/valley-restic-repo"; |
| 1382 | description = '' |
| 1383 | File containing the restic repository URL, for the sftp target |
| 1384 | e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`. |
| 1385 | ''; |
| 1386 | }; |
| 1387 | |
| 1388 | passwordFile = lib.mkOption { |
| 1389 | type = lib.types.nullOr lib.types.path; |
| 1390 | default = null; |
| 1391 | example = "/run/agenix/valley-restic-password"; |
| 1392 | description = '' |
| 1393 | File containing the restic repository encryption password. |
| 1394 | Losing it loses the backups — keep a copy somewhere that |
| 1395 | survives this host. |
| 1396 | ''; |
| 1397 | }; |
| 1398 | |
| 1399 | sshKeyFile = lib.mkOption { |
| 1400 | type = lib.types.nullOr lib.types.path; |
| 1401 | default = null; |
| 1402 | example = "/run/agenix/valley-git-ssh-key"; |
| 1403 | description = '' |
| 1404 | SSH private key that authenticates to the sftp target. The |
| 1405 | backup service runs as root, so any identity the target |
| 1406 | authorizes works — reusing the mirror key is fine. |
| 1407 | ''; |
| 1408 | }; |
| 1409 | |
| 1410 | knownHostsFile = lib.mkOption { |
| 1411 | type = lib.types.nullOr lib.types.path; |
| 1412 | default = null; |
| 1413 | example = "/var/lib/valley-backup/known_hosts"; |
| 1414 | description = '' |
| 1415 | known_hosts file pinning the sftp target's host key. Pin from |
| 1416 | the provider's published fingerprints, not a blind ssh-keyscan. |
| 1417 | ''; |
| 1418 | }; |
| 1419 | }; |
| 1420 | }; |
| 1421 | |
| 1422 | config = lib.mkIf cfg.enable { |
| 1423 | assertions = [ |
| 1424 | { |
| 1425 | assertion = cfg.authorizedKeys != [ ]; |
| 1426 | message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable."; |
| 1427 | } |
| 1428 | ] |
| 1429 | ++ lib.optionals backupEnabled ( |
| 1430 | lib.mapAttrsToList (name: what: { |
| 1431 | assertion = cfg.backup.${name} != null; |
| 1432 | 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)."; |
| 1433 | }) backupSecretOptions |
| 1434 | ) |
| 1435 | ++ lib.optionals cfg.integrator.enable ( |
| 1436 | lib.mapAttrsToList (name: what: { |
| 1437 | assertion = cfg.integrator.${name} != null; |
| 1438 | message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies."; |
| 1439 | }) integratorPathOptions |
| 1440 | ++ [ |
| 1441 | { |
| 1442 | assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null); |
| 1443 | 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."; |
| 1444 | } |
| 1445 | # The rule the integrator reads the rendered file by |
| 1446 | # (note/signerprojects.go): every name and project is printable |
| 1447 | # ASCII with no space, so only the spaces this renders separate |
| 1448 | # words, and a name holds no plus and opens with no #, which |
| 1449 | # would make its line a comment. |
| 1450 | { |
| 1451 | assertion = |
| 1452 | let |
| 1453 | word = w: builtins.match "[!-~]+" w != null; |
| 1454 | name = n: word n && !lib.hasInfix "+" n && !lib.hasPrefix "#" n; |
| 1455 | in |
| 1456 | lib.all (n: name n && lib.all word cfg.integrator.signerProjects.${n}) ( |
| 1457 | lib.attrNames cfg.integrator.signerProjects |
| 1458 | ); |
| 1459 | 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."; |
| 1460 | } |
| 1461 | { |
| 1462 | assertion = |
| 1463 | cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject}; |
| 1464 | 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."; |
| 1465 | } |
| 1466 | { |
| 1467 | assertion = cfg.integrator.user != cfg.user; |
| 1468 | message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7)."; |
| 1469 | } |
| 1470 | { |
| 1471 | assertion = integratedProjects != { }; |
| 1472 | 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."; |
| 1473 | } |
| 1474 | ] |
| 1475 | ) |
| 1476 | ++ lib.optionals (cfg.integrator.instanceProject != null && gitProjects ? ${cfg.integrator.instanceProject}) ( |
| 1477 | let |
| 1478 | name = cfg.integrator.instanceProject; |
| 1479 | protected = gitProjects.${name}.protection.refs or [ ]; |
| 1480 | read = |
| 1481 | lib.optional cfg.integrator.enable "refs/heads/main" ++ lib.optional cfg.identity.enable cfg.identity.ref; |
| 1482 | in |
| 1483 | map (ref: { |
| 1484 | assertion = lib.any (pattern: refPatternMatches pattern ref) protected; |
| 1485 | 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}."; |
| 1486 | }) read |
| 1487 | ) |
| 1488 | ++ [ |
| 1489 | { |
| 1490 | assertion = !(lib.any (v: builtins.match ".*[\"'\\\\].*" v != null) ( |
| 1491 | sshdValues "AcceptEnv" ++ sshdValues "SetEnv" |
| 1492 | )); |
| 1493 | 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."; |
| 1494 | } |
| 1495 | { |
| 1496 | assertion = !(lib.any boundaryVariable (sshdValues "AcceptEnv")); |
| 1497 | 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."; |
| 1498 | } |
| 1499 | { |
| 1500 | assertion = !(lib.any (v: boundaryVariable (lib.head (lib.splitString "=" v))) (sshdValues "SetEnv")); |
| 1501 | message = "sshd sets ${principalEnv} or a GIT_ variable itself (SetEnv). Remove it."; |
| 1502 | } |
| 1503 | { |
| 1504 | assertion = lib.all (v: lib.toLower v == "no") (sshdValues "PermitUserEnvironment"); |
| 1505 | 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."; |
| 1506 | } |
| 1507 | { |
| 1508 | assertion = conflictingKeys == { }; |
| 1509 | 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."; |
| 1510 | } |
| 1511 | { |
| 1512 | assertion = config.users.users.${cfg.user}.openssh.authorizedKeys.keyFiles == [ ]; |
| 1513 | 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."; |
| 1514 | } |
| 1515 | ] |
| 1516 | ++ lib.optionals cfg.identity.enable [ |
| 1517 | { |
| 1518 | assertion = cfg.integrator.instanceProject != null; |
| 1519 | 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."; |
| 1520 | } |
| 1521 | { |
| 1522 | assertion = cfg.integrator.knownSignersFile == null; |
| 1523 | 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."; |
| 1524 | } |
| 1525 | ]; |
| 1526 | |
| 1527 | users.groups.${cfg.group} = { }; |
| 1528 | |
| 1529 | users.users.${cfg.user} = { |
| 1530 | isSystemUser = true; |
| 1531 | group = cfg.group; |
| 1532 | home = cfg.dataDir; |
| 1533 | # The valley's shell, in front of git-shell: it derives the principal |
| 1534 | # from the authenticated key, drops the GIT_ environment, and pauses |
| 1535 | # pushes until valley-init has converged. git-shell then allows only |
| 1536 | # git-upload-pack, git-receive-pack and git-upload-archive, and rejects |
| 1537 | # interactive logins (no ~/git-shell-commands). |
| 1538 | shell = "${gitShell}/bin/valley-git-shell"; |
| 1539 | openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys; |
| 1540 | }; |
| 1541 | |
| 1542 | # The integrator's own account. No shell, no keys, no home of its own |
| 1543 | # beyond the state directory its units get; the git group is the only |
| 1544 | # thing it holds. |
| 1545 | users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable { |
| 1546 | isSystemUser = true; |
| 1547 | group = cfg.group; |
| 1548 | home = "/var/lib/valley-integrator"; |
| 1549 | description = "The valley integrator"; |
| 1550 | }; |
| 1551 | |
| 1552 | services.openssh.enable = lib.mkDefault true; |
| 1553 | |
| 1554 | # The git user's key files, named in its Match block so no other file |
| 1555 | # can authorize a key for it. The declared keys come first, and they stay |
| 1556 | # authorized beside the compiled ones: a compiled file can only ever |
| 1557 | # add, so an empty or missing one — a first boot before the first |
| 1558 | # compilation, a registry that lost an entry, a bug here — cannot take |
| 1559 | # the git user's access away. Which is the point: the assertion above |
| 1560 | # keeps at least one key declared, and that key is the way back in. |
| 1561 | # |
| 1562 | # Nothing else authorizes a key for the git user. ~/.ssh/authorized_keys |
| 1563 | # under its home is not read, and no AuthorizedKeysCommand runs, so every |
| 1564 | # entry a pusher can arrive through carries the tag this module or the |
| 1565 | # compiler wrote, and the assertions and the compiler hold those to one |
| 1566 | # tag per key. |
| 1567 | # |
| 1568 | # Belt-and-braces hardening for the git user beside it. The trailing |
| 1569 | # `Match All` closes the block so it can't scope directives appended to |
| 1570 | # sshd_config after this snippet. |
| 1571 | services.openssh.extraConfig = '' |
| 1572 | Match User ${cfg.user} |
| 1573 | AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u${lib.optionalString cfg.identity.enable " ${identityAuthorizedKeys}"} |
| 1574 | AuthorizedKeysCommand none |
| 1575 | ExposeAuthInfo yes |
| 1576 | AllowTcpForwarding no |
| 1577 | AllowAgentForwarding no |
| 1578 | X11Forwarding no |
| 1579 | PermitTunnel no |
| 1580 | Match All |
| 1581 | ''; |
| 1582 | |
| 1583 | # git-shell spawns git-receive-pack/git-upload-pack from PATH |
| 1584 | environment.systemPackages = [ pkgs.git ]; |
| 1585 | |
| 1586 | systemd.tmpfiles.rules = [ |
| 1587 | "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -" |
| 1588 | ] |
| 1589 | ++ lib.optionals cfg.bus.enable [ |
| 1590 | "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -" |
| 1591 | ]; |
| 1592 | |
| 1593 | # The bus itself. It runs as the git user — the store directory lives in |
| 1594 | # that user's data — but the sandbox is what confines it: the unit can |
| 1595 | # write nowhere except its store directory. |
| 1596 | systemd.services.valley-bus = lib.mkIf cfg.bus.enable { |
| 1597 | description = "The valley event bus (NATS JetStream)"; |
| 1598 | wantedBy = [ "multi-user.target" ]; |
| 1599 | after = [ |
| 1600 | "network.target" |
| 1601 | "systemd-tmpfiles-setup.service" |
| 1602 | ]; |
| 1603 | unitConfig.RequiresMountsFor = cfg.bus.storeDir; |
| 1604 | serviceConfig = { |
| 1605 | ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}"; |
| 1606 | Restart = "on-failure"; |
| 1607 | User = cfg.user; |
| 1608 | Group = cfg.group; |
| 1609 | LimitNOFILE = 65536; |
| 1610 | NoNewPrivileges = true; |
| 1611 | ProtectSystem = "strict"; |
| 1612 | ReadWritePaths = [ cfg.bus.storeDir ]; |
| 1613 | ProtectHome = true; |
| 1614 | PrivateTmp = true; |
| 1615 | PrivateDevices = true; |
| 1616 | ProtectClock = true; |
| 1617 | ProtectHostname = true; |
| 1618 | ProtectKernelLogs = true; |
| 1619 | ProtectKernelModules = true; |
| 1620 | ProtectKernelTunables = true; |
| 1621 | ProtectControlGroups = true; |
| 1622 | ProtectProc = "invisible"; |
| 1623 | RestrictAddressFamilies = [ |
| 1624 | "AF_INET" |
| 1625 | "AF_INET6" |
| 1626 | "AF_UNIX" |
| 1627 | ]; |
| 1628 | RestrictNamespaces = true; |
| 1629 | RestrictRealtime = true; |
| 1630 | RestrictSUIDSGID = true; |
| 1631 | LockPersonality = true; |
| 1632 | CapabilityBoundingSet = ""; |
| 1633 | SystemCallArchitectures = "native"; |
| 1634 | SystemCallFilter = [ "@system-service" ]; |
| 1635 | UMask = "0077"; |
| 1636 | }; |
| 1637 | }; |
| 1638 | |
| 1639 | # The stream is config, not state: (re)created idempotently on every |
| 1640 | # boot, capturing everything under valley.>. An existing stream — and |
| 1641 | # the events in it — is left untouched. |
| 1642 | systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable { |
| 1643 | description = "Create the valley event stream"; |
| 1644 | wantedBy = [ "multi-user.target" ]; |
| 1645 | requires = [ "valley-bus.service" ]; |
| 1646 | after = [ "valley-bus.service" ]; |
| 1647 | serviceConfig = { |
| 1648 | Type = "oneshot"; |
| 1649 | User = cfg.user; |
| 1650 | Group = cfg.group; |
| 1651 | }; |
| 1652 | path = [ pkgs.natscli ]; |
| 1653 | script = '' |
| 1654 | # The server needs a moment to accept connections after startup. |
| 1655 | for _ in $(seq 1 50); do |
| 1656 | nats --server ${busUrl} stream ls >/dev/null 2>&1 && break |
| 1657 | sleep 0.2 |
| 1658 | done |
| 1659 | if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then |
| 1660 | nats --server ${busUrl} stream add valley \ |
| 1661 | --subjects 'valley.>' --storage file --defaults |
| 1662 | fi |
| 1663 | ''; |
| 1664 | }; |
| 1665 | |
| 1666 | # Create missing bare repos and (re)wire the managed hooks on every |
| 1667 | # activation where the declaration changed. |
| 1668 | systemd.services.valley-init = { |
| 1669 | description = "Initialize the valley host's bare git repositories"; |
| 1670 | wantedBy = [ "multi-user.target" ]; |
| 1671 | after = [ "systemd-tmpfiles-setup.service" ]; |
| 1672 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 1673 | serviceConfig = { |
| 1674 | Type = "oneshot"; |
| 1675 | User = cfg.user; |
| 1676 | Group = cfg.group; |
| 1677 | }; |
| 1678 | path = [ |
| 1679 | pkgs.git |
| 1680 | pkgs.diffutils |
| 1681 | ]; |
| 1682 | # Everything init can wire is wired before it fails. A conflict in one |
| 1683 | # repository is reported, the rest of the host is still converged, |
| 1684 | # and only then does the unit fail, so the activation fails loudly |
| 1685 | # without leaving another repository's hook out of date. |
| 1686 | script = '' |
| 1687 | # Pushes pause the moment a convergence starts, and resume only once |
| 1688 | # it has finished: the record is removed first and written last. |
| 1689 | rm -f ${convergedRecord} |
| 1690 | ${valleyInitBody} |
| 1691 | printf '%s\n' ${convergenceId} > ${convergedRecord}.tmp |
| 1692 | mv -f ${convergedRecord}.tmp ${convergedRecord} |
| 1693 | ''; |
| 1694 | }; |
| 1695 | |
| 1696 | # The registry compiler, on a timer. It renders the instance |
| 1697 | # repository's integrated tip into the two artifacts the gates read; |
| 1698 | # nothing else on the host writes them. |
| 1699 | # |
| 1700 | # It runs as the git user rather than under an identity of its own, |
| 1701 | # which is the one place this module steps back from the service split |
| 1702 | # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by |
| 1703 | # anyone but root or the account it authorizes, so the choice is the git |
| 1704 | # user or root, and the git user is the smaller grant. |
| 1705 | # |
| 1706 | # Level-triggered, like the rest: a compilation reads the current tip |
| 1707 | # and replaces an artifact only when its bytes changed, so re-running is |
| 1708 | # free and the timer needs no coordination with anything. |
| 1709 | systemd.services.valley-identity = lib.mkIf cfg.identity.enable { |
| 1710 | description = "Compile the valley identity registry into what the gates check"; |
| 1711 | wantedBy = [ "multi-user.target" ]; |
| 1712 | after = [ "valley-init.service" ]; |
| 1713 | requires = [ "valley-init.service" ]; |
| 1714 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 1715 | serviceConfig = { |
| 1716 | Type = "oneshot"; |
| 1717 | ExecStart = identityCommand; |
| 1718 | User = cfg.user; |
| 1719 | Group = cfg.group; |
| 1720 | StateDirectory = identityStateName; |
| 1721 | # sshd walks every directory above an authorized-keys file and |
| 1722 | # refuses a group- or world-writable one, so the state directory is |
| 1723 | # 0755 deliberately rather than the 0700 a service's state usually |
| 1724 | # takes. Nothing secret lives in it: a registry is public keys. |
| 1725 | StateDirectoryMode = "0755"; |
| 1726 | NoNewPrivileges = true; |
| 1727 | ProtectSystem = "strict"; |
| 1728 | ReadWritePaths = [ identityStateDir ]; |
| 1729 | ProtectHome = true; |
| 1730 | PrivateTmp = true; |
| 1731 | PrivateDevices = true; |
| 1732 | ProtectClock = true; |
| 1733 | ProtectHostname = true; |
| 1734 | ProtectKernelLogs = true; |
| 1735 | ProtectKernelModules = true; |
| 1736 | ProtectKernelTunables = true; |
| 1737 | ProtectControlGroups = true; |
| 1738 | ProtectProc = "invisible"; |
| 1739 | RestrictAddressFamilies = [ "AF_UNIX" ]; |
| 1740 | RestrictNamespaces = true; |
| 1741 | RestrictRealtime = true; |
| 1742 | RestrictSUIDSGID = true; |
| 1743 | LockPersonality = true; |
| 1744 | CapabilityBoundingSet = ""; |
| 1745 | SystemCallArchitectures = "native"; |
| 1746 | SystemCallFilter = [ "@system-service" ]; |
| 1747 | UMask = "0022"; |
| 1748 | }; |
| 1749 | }; |
| 1750 | |
| 1751 | systemd.timers.valley-identity = lib.mkIf cfg.identity.enable { |
| 1752 | description = "Re-compile the valley identity registry"; |
| 1753 | wantedBy = [ "timers.target" ]; |
| 1754 | timerConfig = { |
| 1755 | OnBootSec = "1m"; |
| 1756 | OnUnitActiveSec = cfg.identity.interval; |
| 1757 | }; |
| 1758 | }; |
| 1759 | |
| 1760 | # The signers publication, refs/the-valley/signers, is written by a |
| 1761 | # oneshot of its own. It runs as the git user, which owns the instance |
| 1762 | # repository, and its sandbox lets it write that repository and nothing |
| 1763 | # else. It is not part of valley-init, which runs only on activation, |
| 1764 | # nor of the registry compiler, whose sandbox writes only its state |
| 1765 | # directory. Only the host's machinery writes the ref, never a push: |
| 1766 | # the hook refuses every push to it. This unit writes it, and the |
| 1767 | # integrator can, being in the group the repository is shared with |
| 1768 | # because it lands code there. |
| 1769 | # |
| 1770 | # What starts it: every boot and every activation, after valley-init, |
| 1771 | # which covers a changed signing name, signers path or signer projects |
| 1772 | # list; and the path |
| 1773 | # unit below, whenever the known-signers file changes, which covers |
| 1774 | # each compilation that changed it and a hand-provisioned file being |
| 1775 | # replaced. A run reads the current file and name and writes the ref |
| 1776 | # only when the tree it makes differs, so a run with nothing new is |
| 1777 | # free. Both values are in one tree under one ref, so a client never |
| 1778 | # reads one value without the other. A run holds a lock in the |
| 1779 | # instance repository from reading the file to moving the ref, so two |
| 1780 | # runs take turns, and one that read an older file cannot publish it |
| 1781 | # over a newer one. The ref also moves with a compare-and-swap. |
| 1782 | # |
| 1783 | # A run that cannot read the file, or reads one that is not a list of |
| 1784 | # verifier keys, fails and leaves the last publication in place. That |
| 1785 | # is the file the controllers were given before it changed, and the |
| 1786 | # journal says why. A file with no key in it, as the compiler writes |
| 1787 | # once every signing key is revoked, is published, so clients stop |
| 1788 | # verifying with the revoked keys. |
| 1789 | systemd.services.valley-signers = lib.mkIf publishesSigners { |
| 1790 | description = "Publish what clients verify the valley integrator's transfer statements with"; |
| 1791 | wantedBy = [ "multi-user.target" ]; |
| 1792 | after = [ "valley-init.service" ] ++ lib.optional cfg.identity.enable "valley-identity.service"; |
| 1793 | requires = [ "valley-init.service" ]; |
| 1794 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 1795 | serviceConfig = { |
| 1796 | Type = "oneshot"; |
| 1797 | ExecStart = signersCommand; |
| 1798 | User = cfg.user; |
| 1799 | Group = cfg.group; |
| 1800 | NoNewPrivileges = true; |
| 1801 | ProtectSystem = "strict"; |
| 1802 | ReadWritePaths = [ instanceRepo ]; |
| 1803 | ProtectHome = true; |
| 1804 | PrivateTmp = true; |
| 1805 | PrivateDevices = true; |
| 1806 | ProtectClock = true; |
| 1807 | ProtectHostname = true; |
| 1808 | ProtectKernelLogs = true; |
| 1809 | ProtectKernelModules = true; |
| 1810 | ProtectKernelTunables = true; |
| 1811 | ProtectControlGroups = true; |
| 1812 | ProtectProc = "invisible"; |
| 1813 | RestrictAddressFamilies = [ "AF_UNIX" ]; |
| 1814 | RestrictNamespaces = true; |
| 1815 | RestrictRealtime = true; |
| 1816 | RestrictSUIDSGID = true; |
| 1817 | LockPersonality = true; |
| 1818 | CapabilityBoundingSet = ""; |
| 1819 | SystemCallArchitectures = "native"; |
| 1820 | SystemCallFilter = [ "@system-service" ]; |
| 1821 | # The instance repository is always one the integrator serves, since |
| 1822 | # it has to be protected, so it is group-shared and its directories |
| 1823 | # are setgid. With the default umask, git would chmod each directory |
| 1824 | # it makes to add group write, setgid bit included, and |
| 1825 | # RestrictSUIDSGID refuses that chmod. Group write from the start |
| 1826 | # leaves git nothing to chmod, as for the controllers. |
| 1827 | UMask = "0002"; |
| 1828 | }; |
| 1829 | }; |
| 1830 | |
| 1831 | systemd.paths.valley-signers = lib.mkIf publishesSigners { |
| 1832 | description = "Watch the known-signers file the valley integrator reads"; |
| 1833 | wantedBy = [ "multi-user.target" ]; |
| 1834 | pathConfig.PathChanged = knownSigners; |
| 1835 | }; |
| 1836 | |
| 1837 | # One controller per served project, as instances of a single template: |
| 1838 | # the units differ only in the repository they serve, which is the |
| 1839 | # instance name. `watch` rather than a timer firing `reconcile`: the |
| 1840 | # binary owns its poll loop and its interval, and a timer would be a |
| 1841 | # second cadence over the same level-triggered refs. |
| 1842 | systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable { |
| 1843 | description = "The valley integrator for %i"; |
| 1844 | after = [ |
| 1845 | "network.target" |
| 1846 | "valley-init.service" |
| 1847 | ] |
| 1848 | ++ lib.optional cfg.bus.enable "valley-bus-init.service" |
| 1849 | ++ lib.optional cfg.identity.enable "valley-identity.service"; |
| 1850 | requires = [ "valley-init.service" ]; |
| 1851 | # Wants, not requires: a controller reads the compiled signers file, |
| 1852 | # so it starts after the first compilation — but a compilation that |
| 1853 | # failed must not keep the controllers down. One that finds no file |
| 1854 | # says so and restarts, which is the same loop and a louder one. |
| 1855 | wants = lib.optional cfg.identity.enable "valley-identity.service"; |
| 1856 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 1857 | # nix is not pinned, for the reason the integrator package does not |
| 1858 | # pin it: a check's input closure must be recomputed by the nix this |
| 1859 | # machine actually runs. Everything else a controller drives is |
| 1860 | # pinned inside the wrapper. |
| 1861 | path = [ config.nix.package ]; |
| 1862 | # The repositories belong to the git user and the controller does |
| 1863 | # not, so git refuses to touch them as dubiously owned. The exception |
| 1864 | # rides in the unit's environment, for two reasons. GIT_CONFIG_* is |
| 1865 | # command-scope config, which is protected config, so safe.directory |
| 1866 | # is honoured from it — a repository-scoped setting would be ignored, |
| 1867 | # deliberately. And every git the controller drives is a child of |
| 1868 | # this unit, whether run by the integrator itself or by attest or the |
| 1869 | # deriver, so one environment covers all of them. |
| 1870 | # |
| 1871 | # One repository per instance: never a global gitconfig, never a |
| 1872 | # wildcard. Every other repository on the host stays refused. Linked |
| 1873 | # worktrees need no entry of their own — the controller creates them, |
| 1874 | # so it owns them, and git checks the worktree and its gitdir rather |
| 1875 | # than the repository they point at. |
| 1876 | # |
| 1877 | # TMPDIR is the same kind of wiring, for the same reason. A verdict |
| 1878 | # wants a checkout of the tip on disk, and the integrator asks for one |
| 1879 | # the ordinary way — a temporary directory, then a linked worktree in |
| 1880 | # it. The sandbox below leaves no writable temporary directory, so |
| 1881 | # every tick died on `could not create leading directories`. The |
| 1882 | # scratch belongs under the state directory the unit already has: |
| 1883 | # writable by construction, owned by this service, and gone when the |
| 1884 | # service's state is. Setting it in the environment rather than |
| 1885 | # teaching the binary a flag covers every process in the unit at once |
| 1886 | # — the integrator, attest, the deriver, and the git each of them runs |
| 1887 | # all read TMPDIR, and all of them want scratch in the same place. |
| 1888 | # |
| 1889 | # A second exception, for the instance repository. Every controller |
| 1890 | # reads the group's floor from that repository's tip, and it need not |
| 1891 | # be the project the controller serves — the controller for one |
| 1892 | # project reads the floor out of another project's repository, which |
| 1893 | # it likewise does not own. Without the exception git refuses it as |
| 1894 | # dubiously owned and every pass fails, exactly as it did for the |
| 1895 | # served repository. Two entries, both named; still never a wildcard. |
| 1896 | # |
| 1897 | # Reading needs no sandbox entry beside it. ProtectSystem=strict |
| 1898 | # leaves the filesystem readable and only takes write away, so the |
| 1899 | # ReadWritePaths list above stays the list of what may be written, |
| 1900 | # which is what makes it worth reading. What read does need is a |
| 1901 | # filesystem grant, and valley-init makes it: the instance repository |
| 1902 | # is group-readable whether or not it is one of the served projects. |
| 1903 | environment = { |
| 1904 | GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1"; |
| 1905 | GIT_CONFIG_KEY_0 = "safe.directory"; |
| 1906 | GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git"; |
| 1907 | TMPDIR = integratorStateDir; |
| 1908 | } |
| 1909 | // lib.optionalAttrs (instanceRepo != null) { |
| 1910 | GIT_CONFIG_KEY_1 = "safe.directory"; |
| 1911 | GIT_CONFIG_VALUE_1 = instanceRepo; |
| 1912 | }; |
| 1913 | serviceConfig = { |
| 1914 | ExecStart = integratorCommand; |
| 1915 | Restart = "on-failure"; |
| 1916 | RestartSec = "10s"; |
| 1917 | User = cfg.integrator.user; |
| 1918 | Group = cfg.group; |
| 1919 | StateDirectory = integratorStateName; |
| 1920 | StateDirectoryMode = "0700"; |
| 1921 | WorkingDirectory = integratorStateDir; |
| 1922 | NoNewPrivileges = true; |
| 1923 | ProtectSystem = "strict"; |
| 1924 | # Everything the controller may write, named where a reader of the |
| 1925 | # unit meets it. Under ProtectSystem=strict the rest of the |
| 1926 | # filesystem is read-only, so this list is the whole of what the |
| 1927 | # service can touch, and it is worth being able to read it as such |
| 1928 | # rather than as the exceptions plus whatever else is implied. |
| 1929 | # |
| 1930 | # Its own directory: its state, and the scratch root TMPDIR names. |
| 1931 | # A declaration says it here rather than relying on the state |
| 1932 | # directory being read-write by virtue of being declared, which is |
| 1933 | # not something this unit found to be true. |
| 1934 | # |
| 1935 | # The one repository it serves, and the nix daemon's socket — |
| 1936 | # recomputing a closure means asking the daemon, and connecting to |
| 1937 | # a unix socket needs write access to it. |
| 1938 | ReadWritePaths = [ |
| 1939 | integratorStateDir |
| 1940 | "${cfg.dataDir}/%i.git" |
| 1941 | "/nix/var/nix/daemon-socket" |
| 1942 | ]; |
| 1943 | ProtectHome = true; |
| 1944 | PrivateTmp = true; |
| 1945 | PrivateDevices = true; |
| 1946 | ProtectClock = true; |
| 1947 | ProtectHostname = true; |
| 1948 | ProtectKernelLogs = true; |
| 1949 | ProtectKernelModules = true; |
| 1950 | ProtectKernelTunables = true; |
| 1951 | ProtectControlGroups = true; |
| 1952 | ProtectProc = "invisible"; |
| 1953 | RestrictAddressFamilies = [ |
| 1954 | "AF_INET" |
| 1955 | "AF_INET6" |
| 1956 | "AF_UNIX" |
| 1957 | ]; |
| 1958 | RestrictNamespaces = true; |
| 1959 | RestrictRealtime = true; |
| 1960 | RestrictSUIDSGID = true; |
| 1961 | LockPersonality = true; |
| 1962 | CapabilityBoundingSet = ""; |
| 1963 | SystemCallArchitectures = "native"; |
| 1964 | SystemCallFilter = [ "@system-service" ]; |
| 1965 | # Group write, not the bus unit's 0077: the git user owns these |
| 1966 | # repositories and has to stay able to write what a controller |
| 1967 | # leaves in them. |
| 1968 | UMask = "0002"; |
| 1969 | }; |
| 1970 | }; |
| 1971 | |
| 1972 | # What pushes the mirrors: a path unit per published project, watching |
| 1973 | # its publish queue, and the drain it starts. |
| 1974 | systemd.paths."valley-publish@" = lib.mkIf (publishedProjects != { }) { |
| 1975 | description = "Watch the publish queue of %i"; |
| 1976 | pathConfig.DirectoryNotEmpty = "${cfg.dataDir}/%i.git/${publishQueueName}"; |
| 1977 | }; |
| 1978 | |
| 1979 | # It runs as the git user, with ssh on its path, because the mirror |
| 1980 | # credentials are that user's. Each run drains the whole queue, so starts |
| 1981 | # are at most one per queued move, and a burst of moves must not trip |
| 1982 | # systemd's start limit and leave the queue undrained. A run is bounded |
| 1983 | # instead: one that hangs on a mirror is cut off after 15 minutes, and |
| 1984 | # systemd stops its whole cgroup, so nothing it started outlives it. A |
| 1985 | # run that fails or is cut off leaves its moves queued, and systemd |
| 1986 | # starts it again after a delay that grows from 30 seconds to 15 minutes, |
| 1987 | # until a run succeeds. While it waits to restart, the unit is not |
| 1988 | # inactive, so the path unit does not start it again sooner. |
| 1989 | systemd.services."valley-publish@" = lib.mkIf (publishedProjects != { }) { |
| 1990 | description = "Push the moves queued on %i to its mirrors"; |
| 1991 | after = [ "valley-init.service" ]; |
| 1992 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 1993 | startLimitIntervalSec = 0; |
| 1994 | path = [ config.programs.ssh.package ]; |
| 1995 | serviceConfig = { |
| 1996 | Type = "oneshot"; |
| 1997 | ExecStart = "${publishDrains}/%i"; |
| 1998 | User = cfg.user; |
| 1999 | Group = cfg.group; |
| 2000 | WorkingDirectory = "${cfg.dataDir}/%i.git"; |
| 2001 | TimeoutStartSec = "15min"; |
| 2002 | Restart = "on-failure"; |
| 2003 | RestartSec = "30s"; |
| 2004 | RestartSteps = 5; |
| 2005 | RestartMaxDelaySec = "15min"; |
| 2006 | }; |
| 2007 | }; |
| 2008 | |
| 2009 | # wantedBy on a template unit enables nothing, so the instances the |
| 2010 | # declaration asks for are pulled in by name. |
| 2011 | systemd.targets.valley-publish = lib.mkIf (publishedProjects != { }) { |
| 2012 | description = "What pushes the valley's mirrors"; |
| 2013 | wantedBy = [ "multi-user.target" ]; |
| 2014 | wants = map (name: "valley-publish@${name}.path") (lib.attrNames publishedProjects); |
| 2015 | }; |
| 2016 | |
| 2017 | systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable { |
| 2018 | description = "The valley integrator's controllers"; |
| 2019 | wantedBy = [ "multi-user.target" ]; |
| 2020 | wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects); |
| 2021 | }; |
| 2022 | |
| 2023 | # Offsite backup, rendered only when the declaration asks for it. The |
| 2024 | # declaration states the policy — that backup exists, its cadence and |
| 2025 | # retention; the services.valley.backup.* options supply the machine |
| 2026 | # half. Declaration absent or disabled ⇒ no restic config at all. |
| 2027 | services.restic.backups = lib.mkIf backupEnabled { |
| 2028 | valley = { |
| 2029 | initialize = true; |
| 2030 | repositoryFile = cfg.backup.repositoryFile; |
| 2031 | passwordFile = cfg.backup.passwordFile; |
| 2032 | paths = [ cfg.dataDir ]; |
| 2033 | # The schema admits only the restic-sftp target today; a second |
| 2034 | # target would grow a dispatch here. The service runs as root: |
| 2035 | # authenticate with the supplied identity and only the pinned |
| 2036 | # host key. No prompt can be answered inside a systemd unit, so |
| 2037 | # BatchMode + strict host key checking turn a would-be hang into |
| 2038 | # an immediate error. |
| 2039 | extraOptions = [ |
| 2040 | "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'" |
| 2041 | ]; |
| 2042 | timerConfig = backupTimer.${backupPolicy.cadence}; |
| 2043 | pruneOpts = [ |
| 2044 | "--keep-daily ${toString backupPolicy.retention.daily}" |
| 2045 | "--keep-weekly ${toString backupPolicy.retention.weekly}" |
| 2046 | "--keep-monthly ${toString backupPolicy.retention.monthly}" |
| 2047 | ]; |
| 2048 | }; |
| 2049 | }; |
| 2050 | }; |
| 2051 | } |