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