| 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 | # (.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 | # (.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 renders the hook. |
| 24 | # |
| 25 | # Mirror credentials are the consumer's concern: the module assumes the git |
| 26 | # user's SSH identity and known_hosts are provisioned by the host (e.g. |
| 27 | # cosmo, via its secrets). Nothing here plumbs secrets: the backup options |
| 28 | # below take *paths* to consumer-provisioned secret files; the contents |
| 29 | # never pass through this module or the store. |
| 30 | # |
| 31 | # One service runs under its own unix user rather than the git one: the |
| 32 | # integrator. That is the first half of the split bd-500adf7 asks for. |
| 33 | { |
| 34 | config, |
| 35 | pkgs, |
| 36 | lib, |
| 37 | ... |
| 38 | }: |
| 39 | |
| 40 | let |
| 41 | cfg = config.services.valley; |
| 42 | |
| 43 | schema = ../schema/valley.cue; |
| 44 | |
| 45 | # Build-time vet + export of the host declaration. the vet checks the |
| 46 | # declaration against the schema (whose top level applies #Host), so unknown |
| 47 | # fields and unsafe project names fail the build, with cue's error. |
| 48 | configJSON = |
| 49 | pkgs.runCommand "valley-config.json" |
| 50 | { |
| 51 | nativeBuildInputs = [ pkgs.cue ]; |
| 52 | } |
| 53 | '' |
| 54 | cue vet -c ${schema} ${cfg.config} |
| 55 | cue export ${schema} ${cfg.config} > $out |
| 56 | ''; |
| 57 | |
| 58 | host = lib.importJSON configJSON; |
| 59 | |
| 60 | # Projects whose git store is enabled get a bare repository. |
| 61 | gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects; |
| 62 | repoNames = lib.attrNames gitProjects; |
| 63 | |
| 64 | # The declared durability policy, if any. `backup` is optional in the |
| 65 | # schema: a declaration without it (or with enable = false) renders zero |
| 66 | # backup machinery, exactly as before the field existed. |
| 67 | backupPolicy = host.backup or null; |
| 68 | backupEnabled = backupPolicy != null && backupPolicy.enable; |
| 69 | |
| 70 | # The declared cadence names policy; its wall-clock rendering is this |
| 71 | # installer's choice. A lookup rather than a literal, so a cadence this |
| 72 | # module does not know fails eval loudly instead of mis-scheduling. |
| 73 | backupTimer = { |
| 74 | # Late night with a spread; Persistent runs a missed window at boot. |
| 75 | nightly = { |
| 76 | OnCalendar = "03:30"; |
| 77 | RandomizedDelaySec = "30m"; |
| 78 | Persistent = true; |
| 79 | }; |
| 80 | }; |
| 81 | |
| 82 | # The projects the integrator serves: exactly the ones the declaration |
| 83 | # protects. A protected ref is one only a declared writer may push, and |
| 84 | # the integrator is what lands everyone else's changes onto it. |
| 85 | integratedProjects = lib.filterAttrs (_: p: p ? protection) gitProjects; |
| 86 | |
| 87 | # The integrator this flake builds, in its shipping form: attest, the |
| 88 | # deriver, cue, git and natscli pinned inside the wrapper, so every host |
| 89 | # judges with the same tools (nix/packages.nix). |
| 90 | integratorPackage = (import ./packages.nix { inherit pkgs lib; }).integrator; |
| 91 | |
| 92 | # The whole of a controller's configuration: which repository it serves, |
| 93 | # who it signs as, and whose evidence it accepts. No policy — the |
| 94 | # integrator reads the project layer from the target tip and the instance |
| 95 | # layer from its own side (bd-eaefe82) — and no project name, which the |
| 96 | # binary derives from the bare repo's own directory, the same way the |
| 97 | # post-receive hook does. |
| 98 | integratorCommand = lib.concatStringsSep " " ( |
| 99 | [ |
| 100 | "${integratorPackage}/bin/integrator watch" |
| 101 | "--repo ${cfg.dataDir}/%i.git" |
| 102 | "--key ${toString cfg.integrator.signingKeyFile}" |
| 103 | "--known-signers ${toString cfg.integrator.knownSignersFile}" |
| 104 | "--interval ${cfg.integrator.interval}" |
| 105 | ] |
| 106 | ++ ( |
| 107 | if cfg.integrator.instanceProject != null then |
| 108 | [ "--instance-repo ${instanceRepo}" ] |
| 109 | else |
| 110 | [ "--instance ${toString cfg.integrator.instancePolicy}" ] |
| 111 | ) |
| 112 | ++ lib.optional cfg.bus.enable "--bus ${busUrl}" |
| 113 | ); |
| 114 | |
| 115 | # The one filesystem grant the integrator's user gets. It writes refs, |
| 116 | # objects, and the worktree metadata `git worktree add` keeps inside the |
| 117 | # repository, so read access is not enough: the repos it serves become |
| 118 | # group-shared, and its primary group is the git group. Re-applied on |
| 119 | # every activation, because a repo can predate the service. |
| 120 | # git creates $GIT_DIR/worktrees on the first `worktree add`, owned by |
| 121 | # whichever user got there first. Left alone that user is the integrator, |
| 122 | # and this sweep runs as the git user, which cannot chmod a directory it |
| 123 | # does not own. So init makes that directory itself, ahead of any |
| 124 | # controller: owned by the git user, group-writable, and setgid, so what a |
| 125 | # controller creates inside it lands in the git group and stays reachable. |
| 126 | integratorShareCommands = |
| 127 | '' |
| 128 | # A chmod the git user is not allowed to make is a path some other |
| 129 | # user owns; chmod -R applies what it can and then says so. Warn and |
| 130 | # carry on, and the trade is worth stating. Failing here fails |
| 131 | # valley-init, which every valley unit requires, so the alternative to |
| 132 | # a partly shared repository is no git service on the host at all: no |
| 133 | # controllers, and no ssh access to any project. A degraded share |
| 134 | # costs the integrator the paths it cannot write, is visible in the |
| 135 | # journal, and is fixed by one chown. That is the recoverable half of |
| 136 | # the trade, and it is the half to take. The warning is what keeps the |
| 137 | # degraded state from being a silent one. |
| 138 | share() { |
| 139 | "$@" || 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 |
| 140 | } |
| 141 | '' |
| 142 | + lib.concatMapStrings (name: '' |
| 143 | repo=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"} |
| 144 | git -C "$repo" config core.sharedRepository group |
| 145 | # Before the sweep below, so the sweep never meets a root it cannot |
| 146 | # touch. On a host where a controller already made it, this is the |
| 147 | # chmod that warns, and the repository is served either way. |
| 148 | mkdir -p "$repo/worktrees" |
| 149 | share chmod g+rwxs "$repo/worktrees" |
| 150 | share chmod -R g+rwX "$repo" |
| 151 | share find "$repo" -type d -exec chmod g+s {} + |
| 152 | '') (lib.attrNames integratedProjects) |
| 153 | # The instance repository, when it is not one of the served projects. |
| 154 | # Every controller reads the floor from it and none of them writes it, |
| 155 | # so read is the whole of the grant — no group write, and no |
| 156 | # core.sharedRepository, which is a statement about who writes. |
| 157 | + lib.optionalString |
| 158 | ( |
| 159 | cfg.integrator.instanceProject != null |
| 160 | && !(integratedProjects ? ${cfg.integrator.instanceProject}) |
| 161 | ) |
| 162 | '' |
| 163 | repo=${lib.escapeShellArg (toString instanceRepo)} |
| 164 | share chmod -R g+rX "$repo" |
| 165 | share find "$repo" -type d -exec chmod g+s {} + |
| 166 | ''; |
| 167 | |
| 168 | # The integrator's own directory. Four unit settings have to agree about |
| 169 | # it — its state directory, its working directory, the scratch root TMPDIR |
| 170 | # names, and the read-write path that makes all three usable — so they name |
| 171 | # it once here. |
| 172 | # The bare repository the group's floor is read from: the instance |
| 173 | # project's, served by this host. Null when the host serves no instance |
| 174 | # repository and the layer is supplied as a directory instead. |
| 175 | instanceRepo = |
| 176 | if cfg.integrator.instanceProject != null then |
| 177 | "${cfg.dataDir}/${cfg.integrator.instanceProject}.git" |
| 178 | else |
| 179 | null; |
| 180 | |
| 181 | integratorStateName = "valley-integrator"; |
| 182 | integratorStateDir = "/var/lib/${integratorStateName}"; |
| 183 | |
| 184 | # The paths the consumer must supply once the integrator is enabled, |
| 185 | # with what each names — for the assertion message. |
| 186 | integratorPathOptions = { |
| 187 | signingKeyFile = "the key its transfer statements are signed with"; |
| 188 | knownSignersFile = "the signers whose evidence it accepts"; |
| 189 | }; |
| 190 | |
| 191 | # The secret-path options the consumer must supply once the declaration |
| 192 | # enables backup, with what each names — for the assertion message. |
| 193 | backupSecretOptions = { |
| 194 | repositoryFile = "the restic repository URL"; |
| 195 | passwordFile = "the repository encryption password"; |
| 196 | sshKeyFile = "the SSH identity for the sftp target"; |
| 197 | knownHostsFile = "the pinned host key of the sftp target"; |
| 198 | }; |
| 199 | |
| 200 | # Managed post-receive dispatcher. Each repo's post-receive is a symlink to |
| 201 | # this script, which chains every executable dropped into the repo's |
| 202 | # hooks/post-receive.d/ directory. |
| 203 | postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" '' |
| 204 | # Managed by services.valley — do not edit. |
| 205 | # Drop executable hooks into post-receive.d/ next to this symlink. |
| 206 | set -eu |
| 207 | hook_dir="$(dirname "$0")/post-receive.d" |
| 208 | [ -d "$hook_dir" ] || exit 0 |
| 209 | updates="$(cat)" |
| 210 | [ -n "$updates" ] || exit 0 |
| 211 | for hook in "$hook_dir"/*; do |
| 212 | [ -x "$hook" ] || continue |
| 213 | printf '%s\n' "$updates" | "$hook" "$@" |
| 214 | done |
| 215 | ''; |
| 216 | |
| 217 | # Best-effort push replication. Publication mirror: main and tags only. |
| 218 | # Topic branches are review-queue state, not published — the mirror exists |
| 219 | # so consumers can fetch what has been integrated; durability is restic's |
| 220 | # job, not the mirror's. Pushes run detached (setsid) so a dead mirror can |
| 221 | # only ever cost a log line — never block or fail the primary push. |
| 222 | # --prune propagates tag deletions (glob refspec); it is a no-op for heads |
| 223 | # now that the heads refspec names one ref, so a separate best-effort sweep |
| 224 | # deletes every mirror head but main — which also strips anything that |
| 225 | # appears there by other means. The sweep reads only refs/heads (ls-remote |
| 226 | # --heads), never refs/pull/*, and is logged apart from the replication |
| 227 | # push so it cannot change that push's reported outcome. --mirror is |
| 228 | # rejected outright: it also tries to delete remote-only namespaces, and on |
| 229 | # GitHub the read-only refs/pull/* makes that fail every push, masking real |
| 230 | # replication failures. |
| 231 | mirrorPusher = |
| 232 | name: mirrors: |
| 233 | pkgs.writeShellScript "valley-mirror-push-${name}" '' |
| 234 | for url in ${lib.escapeShellArgs mirrors}; do |
| 235 | if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then |
| 236 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true |
| 237 | else |
| 238 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true |
| 239 | fi |
| 240 | |
| 241 | # Unpublish anything but main. Refnames cannot contain whitespace, so |
| 242 | # accumulating them space-separated and splitting on expansion is safe. |
| 243 | stale="" |
| 244 | while read -r _ ref; do |
| 245 | [ "$ref" = refs/heads/main ] || stale="$stale $ref" |
| 246 | done < <(${pkgs.git}/bin/git ls-remote --heads "$url" 2>/dev/null) |
| 247 | if [ -n "$stale" ]; then |
| 248 | if ${pkgs.git}/bin/git push "$url" --delete $stale >/dev/null 2>&1; then |
| 249 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublished$stale from $url" || true |
| 250 | else |
| 251 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublish from $url failed (ignored)" || true |
| 252 | fi |
| 253 | fi |
| 254 | done |
| 255 | ''; |
| 256 | |
| 257 | mirrorHook = |
| 258 | name: mirrors: |
| 259 | pkgs.writeShellScript "valley-mirrors-${name}" '' |
| 260 | # Managed by services.valley — best-effort push mirrors for ${name}. |
| 261 | cat >/dev/null # updated refs unused: the push replicates main and tags |
| 262 | ${pkgs.util-linux}/bin/setsid -f ${mirrorPusher name mirrors} </dev/null >/dev/null 2>&1 |
| 263 | exit 0 |
| 264 | ''; |
| 265 | |
| 266 | # The event bus (design/roadmap.md, Phase 1): NATS JetStream, onto which |
| 267 | # the ref-updated hook below projects this host's git activity. The bus is |
| 268 | # never load-bearing for durable state — per-repo events are durable in |
| 269 | # git itself, and `valley replay` rebuilds the stream from a repo's refs — |
| 270 | # so losing its storage costs one replay, nothing more. |
| 271 | busUrl = "nats://${cfg.bus.listen}"; |
| 272 | |
| 273 | busServerConfig = pkgs.writeText "valley-bus.conf" '' |
| 274 | listen: ${cfg.bus.listen} |
| 275 | jetstream { |
| 276 | store_dir: "${cfg.bus.storeDir}" |
| 277 | # The store directory defaults to living on the repo volume; the cap |
| 278 | # keeps a runaway or malicious local publisher from filling it. |
| 279 | max_file_store: 2GiB |
| 280 | } |
| 281 | ''; |
| 282 | |
| 283 | # One ref-updated event per updated ref, read from the post-receive stdin |
| 284 | # this script inherits. Every payload field is derivable from git alone — |
| 285 | # no wall-clock time, no hostname — so replaying a repo's refs reproduces |
| 286 | # the same events (the roadmap's determinism criterion). `valley replay` |
| 287 | # builds the identical payload; change one only with the other. |
| 288 | busPublisher = pkgs.writeShellScript "valley-bus-publish" '' |
| 289 | repo="$(basename "$PWD" .git)" |
| 290 | while read -r old new ref; do |
| 291 | [ -n "$ref" ] || continue |
| 292 | # " is the only JSON-significant character a refname can contain |
| 293 | # (git forbids \ and control characters); names and ids are safe. |
| 294 | event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \ |
| 295 | "$repo" "''${ref//\"/\\\"}" "$old" "$new")" |
| 296 | if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \ |
| 297 | "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then |
| 298 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true |
| 299 | else |
| 300 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true |
| 301 | fi |
| 302 | done |
| 303 | ''; |
| 304 | |
| 305 | # The post-receive.d hook, with the mirror hook's failure semantics: the |
| 306 | # publisher runs detached (setsid, inheriting the updates on stdin), so a |
| 307 | # bus problem can only ever cost a log line — never block or fail the |
| 308 | # push. git is the source of truth; the bus is the replaceable component. |
| 309 | busEventHook = pkgs.writeShellScript "valley-bus-events" '' |
| 310 | # Managed by services.valley — project ref updates onto the event bus. |
| 311 | ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1 |
| 312 | exit 0 |
| 313 | ''; |
| 314 | |
| 315 | # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks: |
| 316 | # only ever installs, updates, or removes a store symlink — a hand-written |
| 317 | # hook of the same name is left alone. |
| 318 | busHookCommands = lib.concatMapStrings ( |
| 319 | name: |
| 320 | let |
| 321 | bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus"; |
| 322 | in |
| 323 | if cfg.bus.enable then |
| 324 | '' |
| 325 | bhook=${bhook} |
| 326 | if [ -L "$bhook" ]; then |
| 327 | case "$(readlink "$bhook")" in |
| 328 | /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;; |
| 329 | esac |
| 330 | elif [ ! -e "$bhook" ]; then |
| 331 | ln -s ${busEventHook} "$bhook" |
| 332 | fi |
| 333 | '' |
| 334 | else |
| 335 | '' |
| 336 | bhook=${bhook} |
| 337 | if [ -L "$bhook" ]; then |
| 338 | case "$(readlink "$bhook")" in |
| 339 | /nix/store/*) rm -f "$bhook" ;; |
| 340 | esac |
| 341 | fi |
| 342 | '' |
| 343 | ) repoNames; |
| 344 | |
| 345 | # Per-project mirror-hook wiring. Only ever installs, updates, or removes |
| 346 | # a store symlink — a hand-written hook of the same name is left alone. |
| 347 | mirrorHookCommands = lib.concatStrings ( |
| 348 | lib.mapAttrsToList ( |
| 349 | name: p: |
| 350 | let |
| 351 | mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors"; |
| 352 | in |
| 353 | if p.mirrors != [ ] then |
| 354 | '' |
| 355 | mhook=${mhook} |
| 356 | if [ -L "$mhook" ]; then |
| 357 | case "$(readlink "$mhook")" in |
| 358 | /nix/store/*) ln -sfn ${mirrorHook name p.mirrors} "$mhook" ;; |
| 359 | esac |
| 360 | elif [ ! -e "$mhook" ]; then |
| 361 | ln -s ${mirrorHook name p.mirrors} "$mhook" |
| 362 | fi |
| 363 | '' |
| 364 | else |
| 365 | '' |
| 366 | mhook=${mhook} |
| 367 | if [ -L "$mhook" ]; then |
| 368 | case "$(readlink "$mhook")" in |
| 369 | /nix/store/*) rm -f "$mhook" ;; |
| 370 | esac |
| 371 | fi |
| 372 | '' |
| 373 | ) gitProjects |
| 374 | ); |
| 375 | |
| 376 | # The environment variable carrying the pushing key's principal name. |
| 377 | # sshd sets it from the key's own authorized_keys entry; the pre-receive |
| 378 | # hook reads it. One name, honoured only because PermitUserEnvironment |
| 379 | # below names it. |
| 380 | principalEnv = "VALLEY_PRINCIPAL"; |
| 381 | |
| 382 | # Keys that name a principal. An entry written as a bare string names |
| 383 | # none, and renders exactly as it always did. |
| 384 | taggedKeys = lib.filter (k: !lib.isString k) cfg.authorizedKeys; |
| 385 | |
| 386 | authorizedKeyLine = |
| 387 | k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}''; |
| 388 | |
| 389 | # Where a contributor's attestations live (design/contribute.md, step 5). |
| 390 | attestationNamespace = "refs/the-valley/attestations/"; |
| 391 | |
| 392 | # The pre-receive hook: the one structural git invariant |
| 393 | # (design/architecture.md, design/contribute.md). Two clauses and nothing |
| 394 | # else — only a declared writer may update a protected ref, and an |
| 395 | # attestation ref may only be created. Every other ref is open to anyone |
| 396 | # with push access, and all policy beyond this lives in the integrator. |
| 397 | # |
| 398 | # What is protected and who may write it comes from the declaration's |
| 399 | # `protection` block, like every other domain fact here. This renders it. |
| 400 | # |
| 401 | # Pushes arrive over SSH as one shared git user, so the unix account |
| 402 | # behind a push says nothing about who pushed. The principal comes from |
| 403 | # the key instead: services.valley.authorizedKeys tags each key's |
| 404 | # authorized_keys entry, sshd puts that tag in the environment of the |
| 405 | # receive-pack this hook runs under, and an untagged key has no principal |
| 406 | # at all. The client cannot supply the tag itself — sshd passes on no |
| 407 | # client environment (no AcceptEnv). |
| 408 | # |
| 409 | # This governs pushes, which is every write that crosses the host |
| 410 | # boundary. It does not govern writes made on the host: the integrator |
| 411 | # updates refs locally, as could anyone holding the git user's shell. |
| 412 | # Local access is the host's own boundary, not this hook's. |
| 413 | protectHook = |
| 414 | name: p: |
| 415 | pkgs.writeShellScript "valley-protect-${name}" '' |
| 416 | # Managed by services.valley — do not edit. |
| 417 | set -eu |
| 418 | |
| 419 | principal="''${${principalEnv}:-}" |
| 420 | [ -n "$principal" ] || principal="<untagged key>" |
| 421 | writers=( ${lib.escapeShellArgs p.writers} ) |
| 422 | protected=( ${lib.escapeShellArgs p.refs} ) |
| 423 | |
| 424 | is_writer() { |
| 425 | local w |
| 426 | for w in ''${writers[@]+"''${writers[@]}"}; do |
| 427 | if [ "$w" = "$principal" ]; then return 0; fi |
| 428 | done |
| 429 | return 1 |
| 430 | } |
| 431 | |
| 432 | rejected=0 |
| 433 | while read -r old new ref; do |
| 434 | [ -n "$ref" ] || continue |
| 435 | |
| 436 | # An attestation is a record of what was checked; a record that can |
| 437 | # be rewritten or dropped is not one. So the namespace is |
| 438 | # create-only, for everyone — an all-zero old id is a creation, at |
| 439 | # any hash length. |
| 440 | case "$ref" in |
| 441 | ${attestationNamespace}*) |
| 442 | case "$old" in |
| 443 | *[!0]*) |
| 444 | echo "valley: $principal may not update $ref — attestation refs are create-only" >&2 |
| 445 | rejected=1 |
| 446 | ;; |
| 447 | esac |
| 448 | continue |
| 449 | ;; |
| 450 | esac |
| 451 | |
| 452 | # Protected refs, matched as shell globs (so `*` crosses path |
| 453 | # separators). Unprotected refs are not the hook's business. |
| 454 | for pattern in ''${protected[@]+"''${protected[@]}"}; do |
| 455 | case "$ref" in |
| 456 | $pattern) |
| 457 | if ! is_writer; then |
| 458 | echo "valley: $principal may not write $ref — a protected ref of ${name} (writers: ${ |
| 459 | lib.concatStringsSep ", " p.writers |
| 460 | })" >&2 |
| 461 | rejected=1 |
| 462 | fi |
| 463 | break |
| 464 | ;; |
| 465 | esac |
| 466 | done |
| 467 | done |
| 468 | exit "$rejected" |
| 469 | ''; |
| 470 | |
| 471 | # Per-project pre-receive wiring, from the declaration's protection |
| 472 | # blocks. Same rules as the other managed hooks: only ever installs, |
| 473 | # updates, or removes a store symlink — a hand-written hook of the same |
| 474 | # name is left alone. A project that declares no protection gets no hook, |
| 475 | # so a declaration written before the field installs nothing new. |
| 476 | protectHookCommands = lib.concatStrings ( |
| 477 | lib.mapAttrsToList ( |
| 478 | name: p: |
| 479 | let |
| 480 | phook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/pre-receive"; |
| 481 | in |
| 482 | if p ? protection then |
| 483 | '' |
| 484 | phook=${phook} |
| 485 | if [ -L "$phook" ]; then |
| 486 | case "$(readlink "$phook")" in |
| 487 | /nix/store/*) ln -sfn ${protectHook name p.protection} "$phook" ;; |
| 488 | esac |
| 489 | elif [ ! -e "$phook" ]; then |
| 490 | ln -s ${protectHook name p.protection} "$phook" |
| 491 | fi |
| 492 | '' |
| 493 | else |
| 494 | '' |
| 495 | phook=${phook} |
| 496 | if [ -L "$phook" ]; then |
| 497 | case "$(readlink "$phook")" in |
| 498 | /nix/store/*) rm -f "$phook" ;; |
| 499 | esac |
| 500 | fi |
| 501 | '' |
| 502 | ) gitProjects |
| 503 | ); |
| 504 | in |
| 505 | { |
| 506 | options.services.valley = { |
| 507 | enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration"; |
| 508 | |
| 509 | user = lib.mkOption { |
| 510 | type = lib.types.str; |
| 511 | default = "git"; |
| 512 | description = "System user that owns the repositories and accepts SSH pushes."; |
| 513 | }; |
| 514 | |
| 515 | group = lib.mkOption { |
| 516 | type = lib.types.str; |
| 517 | default = "git"; |
| 518 | description = "Primary group of the valley git user."; |
| 519 | }; |
| 520 | |
| 521 | dataDir = lib.mkOption { |
| 522 | type = lib.types.path; |
| 523 | default = "/srv/git"; |
| 524 | example = "/mnt/git"; |
| 525 | description = '' |
| 526 | Directory holding the bare repositories, one `<name>.git` per |
| 527 | project declared in {option}`services.valley.config`. Also the git |
| 528 | user's home, so clone URLs are relative to it (`git@host:name.git`). |
| 529 | Consumers typically point it at a dedicated dataset. |
| 530 | ''; |
| 531 | }; |
| 532 | |
| 533 | authorizedKeys = lib.mkOption { |
| 534 | type = lib.types.listOf ( |
| 535 | lib.types.either lib.types.str ( |
| 536 | lib.types.submodule { |
| 537 | options = { |
| 538 | key = lib.mkOption { |
| 539 | type = lib.types.str; |
| 540 | description = "The SSH public key, as it would appear in `authorized_keys`."; |
| 541 | }; |
| 542 | |
| 543 | principal = lib.mkOption { |
| 544 | type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"; |
| 545 | example = "integrator"; |
| 546 | description = '' |
| 547 | Name of the principal this key acts as. Every push made |
| 548 | with the key carries the name, and |
| 549 | {option}`services.valley.protect` decides what a name may |
| 550 | write. Nothing else uses it. |
| 551 | ''; |
| 552 | }; |
| 553 | }; |
| 554 | } |
| 555 | ) |
| 556 | ); |
| 557 | default = [ ]; |
| 558 | example = lib.literalExpression '' |
| 559 | [ |
| 560 | "ssh-ed25519 AAAA… someone@somewhere" |
| 561 | { |
| 562 | principal = "integrator"; |
| 563 | key = "ssh-ed25519 AAAA… integrator"; |
| 564 | } |
| 565 | ] |
| 566 | ''; |
| 567 | description = '' |
| 568 | SSH public keys allowed to push/fetch as the git user. Access is |
| 569 | host-level by design: every key can reach every project. |
| 570 | |
| 571 | A key written as a plain string is anonymous — it can push, and it |
| 572 | can write nothing protected. A key written as an attribute set |
| 573 | names the principal it acts as, which is the only thing that can |
| 574 | tell one pusher from another: pushes arrive as the shared git user, |
| 575 | so identity has to ride on the key. |
| 576 | |
| 577 | Which refs a principal may write is declared, not an option here: |
| 578 | it is a statement about what the host serves, and lives in the |
| 579 | project's `protection` block in |
| 580 | {option}`services.valley.config`. Binding a name to keys is the |
| 581 | machine half — the interim form of the identity registry's |
| 582 | compilation (dcr-b87f6e8). |
| 583 | ''; |
| 584 | }; |
| 585 | |
| 586 | config = lib.mkOption { |
| 587 | type = lib.types.path; |
| 588 | example = lib.literalExpression "./valley.cue"; |
| 589 | description = '' |
| 590 | Path to the host's CUE declaration (`package valley`) — the |
| 591 | canonical statement of what this valley host serves, validated |
| 592 | against the shipped schema at build time. This is the single domain |
| 593 | input: projects, their push mirrors, and the backup policy are |
| 594 | declared here, never as Nix options. |
| 595 | ''; |
| 596 | }; |
| 597 | |
| 598 | # The event bus. Machine options, not domain: whether this machine runs |
| 599 | # a bus, where it listens, and where its storage lives. What gets |
| 600 | # published onto it is defined portably in ../schema/events.cue. |
| 601 | bus = { |
| 602 | enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events"; |
| 603 | |
| 604 | listen = lib.mkOption { |
| 605 | type = lib.types.str; |
| 606 | default = "127.0.0.1:4222"; |
| 607 | example = "100.100.1.7:4222"; |
| 608 | description = '' |
| 609 | Address the bus listens on, `host:port`. Localhost by default: |
| 610 | nothing off the host can reach the bus until the consumer widens |
| 611 | this deliberately — e.g. to the host's tailnet address once a |
| 612 | remote `valley tail` wants in. Local publishers (the ref-updated |
| 613 | hook) connect to this same address, so it must be reachable from |
| 614 | the host itself. |
| 615 | ''; |
| 616 | }; |
| 617 | |
| 618 | storeDir = lib.mkOption { |
| 619 | type = lib.types.path; |
| 620 | default = "${cfg.dataDir}/.bus"; |
| 621 | defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"''; |
| 622 | description = '' |
| 623 | Directory holding the JetStream file storage. The default lives |
| 624 | under {option}`services.valley.dataDir`; it can never collide |
| 625 | with a repository because project names must start with an |
| 626 | alphanumeric. The stream is a projection of git, rebuildable |
| 627 | with `valley replay` — losing this directory costs one replay. |
| 628 | ''; |
| 629 | }; |
| 630 | }; |
| 631 | |
| 632 | # The integrator (design/roadmap.md, Phase 3): the controller that |
| 633 | # lands a change once its evidence still transfers to the current tip. |
| 634 | # Machine options only — whether this host runs controllers, who they |
| 635 | # are, and how often they look. Which projects get one is not an option |
| 636 | # either: it follows from which projects the declaration protects, |
| 637 | # because a protected ref is exactly what a controller exists to write. |
| 638 | integrator = { |
| 639 | enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers"; |
| 640 | |
| 641 | user = lib.mkOption { |
| 642 | type = lib.types.str; |
| 643 | default = "valley-integrator"; |
| 644 | description = '' |
| 645 | System user the controllers run as. Deliberately not |
| 646 | {option}`services.valley.user`: one unix identity per service is |
| 647 | the split bd-500adf7 asks for, and this service begins it. |
| 648 | |
| 649 | The account exists only to write the repositories it serves. It |
| 650 | gets no shell and no SSH key, and its primary group is |
| 651 | {option}`services.valley.group`, which is the whole of its |
| 652 | permission model: {option}`services.valley.dataDir` is already |
| 653 | group-readable, and each served repository is made group-shared |
| 654 | (group write, setgid directories) so a controller can write |
| 655 | refs, objects, and git's worktree metadata. Nothing else on the |
| 656 | host belongs to that group, and the bus's store directory (mode |
| 657 | 0700) stays out of reach. |
| 658 | |
| 659 | The key and signers files are the consumer's to provision; both |
| 660 | must be readable by this user. |
| 661 | ''; |
| 662 | }; |
| 663 | |
| 664 | signingKeyFile = lib.mkOption { |
| 665 | type = lib.types.nullOr lib.types.path; |
| 666 | default = null; |
| 667 | example = "/run/agenix/valley-integrator-key"; |
| 668 | description = '' |
| 669 | ed25519 private key the controllers sign their transfer |
| 670 | statements with. A runtime path the consumer provisions (e.g. |
| 671 | agenix), never a store path — the store is world-readable. |
| 672 | ''; |
| 673 | }; |
| 674 | |
| 675 | knownSignersFile = lib.mkOption { |
| 676 | type = lib.types.nullOr lib.types.path; |
| 677 | default = null; |
| 678 | example = "/var/lib/valley-instance/known_signers"; |
| 679 | description = '' |
| 680 | File of verifier keys whose attestations count, one per line, in |
| 681 | `attest key` format. This is the identity registry's interim |
| 682 | compilation (dcr-b87f6e8): no compiler exists yet, so the file |
| 683 | is supplied directly. Evidence signed by nobody in it does not |
| 684 | transfer, which a controller reports per check rather than |
| 685 | treating as a forgery. |
| 686 | ''; |
| 687 | }; |
| 688 | |
| 689 | instanceProject = lib.mkOption { |
| 690 | type = lib.types.nullOr lib.types.str; |
| 691 | default = null; |
| 692 | example = "qinling"; |
| 693 | description = '' |
| 694 | The project whose served repository carries the group's floor — |
| 695 | the instance policy layer every controller on this host composes |
| 696 | against. A controller reads it from `policy/instance/` in that |
| 697 | bare repository's integrated tip, and nothing is materialized on |
| 698 | disk in between. |
| 699 | |
| 700 | The floor is the instance repository's, read at the tip that has |
| 701 | been integrated (dcr-f41f718); the instance repository is the |
| 702 | group's own (dcr-b87f6e8). A host serving it is therefore already |
| 703 | holding the authoritative copy. |
| 704 | |
| 705 | What follows is a property of that design, and worth knowing |
| 706 | before editing a floor. A change to it takes effect at the first |
| 707 | pass after it lands on that ref, and never before. An edit in a |
| 708 | branch, in a worktree, or in an integration request that has not |
| 709 | been integrated governs nothing. There is no refresh to trigger |
| 710 | and no staleness to wait out: landing is the whole of publishing |
| 711 | a floor. |
| 712 | |
| 713 | Every controller on the host reads the same repository, the |
| 714 | controller serving that repository included. Both layers are |
| 715 | resolved from the controller's own side — this one, and the |
| 716 | project's `policy/project/` at the target tip — so a change can |
| 717 | never supply the policy that gates it (bd-eaefe82). |
| 718 | |
| 719 | Those two directories are the convention, and the module states |
| 720 | neither: a controller takes each layer from the place the |
| 721 | integrator defaults to, so a host declaration that says nothing |
| 722 | about policy gets the layout the worked example lays out |
| 723 | (dcr-f41f718). |
| 724 | ''; |
| 725 | }; |
| 726 | |
| 727 | instancePolicy = lib.mkOption { |
| 728 | type = lib.types.nullOr lib.types.path; |
| 729 | default = null; |
| 730 | example = "/var/lib/valley-instance/policy/instance"; |
| 731 | description = '' |
| 732 | Directory of `*.cue` files holding the instance policy layer, for |
| 733 | a host that serves no instance repository. It holds what |
| 734 | `policy/instance/` in the instance repository holds. Set this or |
| 735 | {option}`services.valley.integrator.instanceProject`, never both. |
| 736 | |
| 737 | Keeping such a directory in step with the instance repository is |
| 738 | the consumer's to arrange, which is the reason to prefer the |
| 739 | project option wherever the host serves the repository. |
| 740 | ''; |
| 741 | }; |
| 742 | |
| 743 | interval = lib.mkOption { |
| 744 | type = lib.types.str; |
| 745 | default = "15s"; |
| 746 | example = "1m"; |
| 747 | description = '' |
| 748 | How long a controller waits between passes. The integrator polls |
| 749 | deliberately: integration requests are durable in git, and the |
| 750 | controller level-triggers over those refs, so a lost event costs |
| 751 | one interval and nothing more. |
| 752 | ''; |
| 753 | }; |
| 754 | }; |
| 755 | |
| 756 | # Machine integration for the declared backup policy. The declaration |
| 757 | # states WHAT must hold (offsite backup, cadence, retention); these |
| 758 | # options supply HOW on this machine — where the repository is and how |
| 759 | # to authenticate. All are paths to files the consumer provisions |
| 760 | # (e.g. agenix), required when the declaration enables backup. Point |
| 761 | # them at runtime paths, never at files in the Nix store. |
| 762 | backup = { |
| 763 | repositoryFile = lib.mkOption { |
| 764 | type = lib.types.nullOr lib.types.path; |
| 765 | default = null; |
| 766 | example = "/run/agenix/valley-restic-repo"; |
| 767 | description = '' |
| 768 | File containing the restic repository URL, for the sftp target |
| 769 | e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`. |
| 770 | ''; |
| 771 | }; |
| 772 | |
| 773 | passwordFile = lib.mkOption { |
| 774 | type = lib.types.nullOr lib.types.path; |
| 775 | default = null; |
| 776 | example = "/run/agenix/valley-restic-password"; |
| 777 | description = '' |
| 778 | File containing the restic repository encryption password. |
| 779 | Losing it loses the backups — keep a copy somewhere that |
| 780 | survives this host. |
| 781 | ''; |
| 782 | }; |
| 783 | |
| 784 | sshKeyFile = lib.mkOption { |
| 785 | type = lib.types.nullOr lib.types.path; |
| 786 | default = null; |
| 787 | example = "/run/agenix/valley-git-ssh-key"; |
| 788 | description = '' |
| 789 | SSH private key that authenticates to the sftp target. The |
| 790 | backup service runs as root, so any identity the target |
| 791 | authorizes works — reusing the mirror key is fine. |
| 792 | ''; |
| 793 | }; |
| 794 | |
| 795 | knownHostsFile = lib.mkOption { |
| 796 | type = lib.types.nullOr lib.types.path; |
| 797 | default = null; |
| 798 | example = "/var/lib/valley-backup/known_hosts"; |
| 799 | description = '' |
| 800 | known_hosts file pinning the sftp target's host key. Pin from |
| 801 | the provider's published fingerprints, not a blind ssh-keyscan. |
| 802 | ''; |
| 803 | }; |
| 804 | }; |
| 805 | }; |
| 806 | |
| 807 | config = lib.mkIf cfg.enable { |
| 808 | assertions = [ |
| 809 | { |
| 810 | assertion = cfg.authorizedKeys != [ ]; |
| 811 | message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable."; |
| 812 | } |
| 813 | ] |
| 814 | ++ lib.optionals backupEnabled ( |
| 815 | lib.mapAttrsToList (name: what: { |
| 816 | assertion = cfg.backup.${name} != null; |
| 817 | 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)."; |
| 818 | }) backupSecretOptions |
| 819 | ) |
| 820 | ++ lib.optionals cfg.integrator.enable ( |
| 821 | lib.mapAttrsToList (name: what: { |
| 822 | assertion = cfg.integrator.${name} != null; |
| 823 | message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies."; |
| 824 | }) integratorPathOptions |
| 825 | ++ [ |
| 826 | { |
| 827 | assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null); |
| 828 | 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."; |
| 829 | } |
| 830 | { |
| 831 | assertion = |
| 832 | cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject}; |
| 833 | 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."; |
| 834 | } |
| 835 | { |
| 836 | assertion = cfg.integrator.user != cfg.user; |
| 837 | message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7)."; |
| 838 | } |
| 839 | { |
| 840 | assertion = integratedProjects != { }; |
| 841 | 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."; |
| 842 | } |
| 843 | ] |
| 844 | ); |
| 845 | |
| 846 | users.groups.${cfg.group} = { }; |
| 847 | |
| 848 | users.users.${cfg.user} = { |
| 849 | isSystemUser = true; |
| 850 | group = cfg.group; |
| 851 | home = cfg.dataDir; |
| 852 | # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive; |
| 853 | # interactive logins are rejected (no ~/git-shell-commands). |
| 854 | shell = "${pkgs.git}/bin/git-shell"; |
| 855 | openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys; |
| 856 | }; |
| 857 | |
| 858 | # The integrator's own account. No shell, no keys, no home of its own |
| 859 | # beyond the state directory its units get; the git group is the only |
| 860 | # thing it holds. |
| 861 | users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable { |
| 862 | isSystemUser = true; |
| 863 | group = cfg.group; |
| 864 | home = "/var/lib/valley-integrator"; |
| 865 | description = "The valley integrator"; |
| 866 | }; |
| 867 | |
| 868 | services.openssh.enable = lib.mkDefault true; |
| 869 | |
| 870 | # Honour the principal tag on a key's entry, and nothing else: the |
| 871 | # pattern-list form admits that one variable name. Rendered only once a |
| 872 | # key names a principal, so a host with none keeps the sshd config it |
| 873 | # had. |
| 874 | services.openssh.settings = lib.optionalAttrs (taggedKeys != [ ]) { |
| 875 | PermitUserEnvironment = principalEnv; |
| 876 | }; |
| 877 | |
| 878 | # Belt-and-braces hardening for the git user. The trailing `Match All` |
| 879 | # closes the block so it can't scope directives appended to sshd_config |
| 880 | # after this snippet. |
| 881 | services.openssh.extraConfig = '' |
| 882 | Match User ${cfg.user} |
| 883 | AllowTcpForwarding no |
| 884 | AllowAgentForwarding no |
| 885 | X11Forwarding no |
| 886 | PermitTunnel no |
| 887 | Match All |
| 888 | ''; |
| 889 | |
| 890 | # git-shell spawns git-receive-pack/git-upload-pack from PATH |
| 891 | environment.systemPackages = [ pkgs.git ]; |
| 892 | |
| 893 | systemd.tmpfiles.rules = [ |
| 894 | "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -" |
| 895 | ] |
| 896 | ++ lib.optionals cfg.bus.enable [ |
| 897 | "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -" |
| 898 | ]; |
| 899 | |
| 900 | # The bus itself. It runs as the git user — the store directory lives in |
| 901 | # that user's data — but the sandbox is what confines it: the unit can |
| 902 | # write nowhere except its store directory. |
| 903 | systemd.services.valley-bus = lib.mkIf cfg.bus.enable { |
| 904 | description = "The valley event bus (NATS JetStream)"; |
| 905 | wantedBy = [ "multi-user.target" ]; |
| 906 | after = [ |
| 907 | "network.target" |
| 908 | "systemd-tmpfiles-setup.service" |
| 909 | ]; |
| 910 | unitConfig.RequiresMountsFor = cfg.bus.storeDir; |
| 911 | serviceConfig = { |
| 912 | ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}"; |
| 913 | Restart = "on-failure"; |
| 914 | User = cfg.user; |
| 915 | Group = cfg.group; |
| 916 | LimitNOFILE = 65536; |
| 917 | NoNewPrivileges = true; |
| 918 | ProtectSystem = "strict"; |
| 919 | ReadWritePaths = [ cfg.bus.storeDir ]; |
| 920 | ProtectHome = true; |
| 921 | PrivateTmp = true; |
| 922 | PrivateDevices = true; |
| 923 | ProtectClock = true; |
| 924 | ProtectHostname = true; |
| 925 | ProtectKernelLogs = true; |
| 926 | ProtectKernelModules = true; |
| 927 | ProtectKernelTunables = true; |
| 928 | ProtectControlGroups = true; |
| 929 | ProtectProc = "invisible"; |
| 930 | RestrictAddressFamilies = [ |
| 931 | "AF_INET" |
| 932 | "AF_INET6" |
| 933 | "AF_UNIX" |
| 934 | ]; |
| 935 | RestrictNamespaces = true; |
| 936 | RestrictRealtime = true; |
| 937 | RestrictSUIDSGID = true; |
| 938 | LockPersonality = true; |
| 939 | CapabilityBoundingSet = ""; |
| 940 | SystemCallArchitectures = "native"; |
| 941 | SystemCallFilter = [ "@system-service" ]; |
| 942 | UMask = "0077"; |
| 943 | }; |
| 944 | }; |
| 945 | |
| 946 | # The stream is config, not state: (re)created idempotently on every |
| 947 | # boot, capturing everything under valley.>. An existing stream — and |
| 948 | # the events in it — is left untouched. |
| 949 | systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable { |
| 950 | description = "Create the valley event stream"; |
| 951 | wantedBy = [ "multi-user.target" ]; |
| 952 | requires = [ "valley-bus.service" ]; |
| 953 | after = [ "valley-bus.service" ]; |
| 954 | serviceConfig = { |
| 955 | Type = "oneshot"; |
| 956 | User = cfg.user; |
| 957 | Group = cfg.group; |
| 958 | }; |
| 959 | path = [ pkgs.natscli ]; |
| 960 | script = '' |
| 961 | # The server needs a moment to accept connections after startup. |
| 962 | for _ in $(seq 1 50); do |
| 963 | nats --server ${busUrl} stream ls >/dev/null 2>&1 && break |
| 964 | sleep 0.2 |
| 965 | done |
| 966 | if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then |
| 967 | nats --server ${busUrl} stream add valley \ |
| 968 | --subjects 'valley.>' --storage file --defaults |
| 969 | fi |
| 970 | ''; |
| 971 | }; |
| 972 | |
| 973 | # Create missing bare repos and (re)wire the managed hooks on every |
| 974 | # activation where the declaration changed. |
| 975 | systemd.services.valley-init = { |
| 976 | description = "Initialize the valley host's bare git repositories"; |
| 977 | wantedBy = [ "multi-user.target" ]; |
| 978 | after = [ "systemd-tmpfiles-setup.service" ]; |
| 979 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 980 | serviceConfig = { |
| 981 | Type = "oneshot"; |
| 982 | User = cfg.user; |
| 983 | Group = cfg.group; |
| 984 | }; |
| 985 | path = [ pkgs.git ]; |
| 986 | script = '' |
| 987 | repos=( ${lib.escapeShellArgs repoNames} ) |
| 988 | for name in "''${repos[@]}"; do |
| 989 | repo="${cfg.dataDir}/$name.git" |
| 990 | # Check HEAD rather than the directory itself so a pre-existing |
| 991 | # empty directory still gets initialized. |
| 992 | if [ ! -e "$repo/HEAD" ]; then |
| 993 | git init --bare --initial-branch=main "$repo" |
| 994 | fi |
| 995 | |
| 996 | # Hook scaffolding: post-receive dispatches to post-receive.d/. |
| 997 | # Only manage the hook if it is absent or already ours (a store |
| 998 | # symlink) — a hand-written hook is left alone. |
| 999 | mkdir -p "$repo/hooks/post-receive.d" |
| 1000 | hook="$repo/hooks/post-receive" |
| 1001 | if [ -L "$hook" ]; then |
| 1002 | case "$(readlink "$hook")" in |
| 1003 | /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;; |
| 1004 | esac |
| 1005 | elif [ ! -e "$hook" ]; then |
| 1006 | ln -s ${postReceiveDispatch} "$hook" |
| 1007 | fi |
| 1008 | done |
| 1009 | |
| 1010 | # Per-project push-mirror hooks. |
| 1011 | ${mirrorHookCommands} |
| 1012 | |
| 1013 | # The one structural invariant, on every project declared protected. |
| 1014 | ${protectHookCommands} |
| 1015 | |
| 1016 | # The ref-updated publisher hook, on every repo when the bus is on. |
| 1017 | ${busHookCommands} |
| 1018 | |
| 1019 | # Group-shared repositories, on what the integrator serves. |
| 1020 | ${lib.optionalString cfg.integrator.enable integratorShareCommands} |
| 1021 | ''; |
| 1022 | }; |
| 1023 | |
| 1024 | # One controller per served project, as instances of a single template: |
| 1025 | # the units differ only in the repository they serve, which is the |
| 1026 | # instance name. `watch` rather than a timer firing `reconcile`: the |
| 1027 | # binary owns its poll loop and its interval, and a timer would be a |
| 1028 | # second cadence over the same level-triggered refs. |
| 1029 | systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable { |
| 1030 | description = "The valley integrator for %i"; |
| 1031 | after = [ |
| 1032 | "network.target" |
| 1033 | "valley-init.service" |
| 1034 | ] |
| 1035 | ++ lib.optional cfg.bus.enable "valley-bus-init.service"; |
| 1036 | requires = [ "valley-init.service" ]; |
| 1037 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 1038 | # nix is not pinned, for the reason the integrator package does not |
| 1039 | # pin it: a check's input closure must be recomputed by the nix this |
| 1040 | # machine actually runs. Everything else a controller drives is |
| 1041 | # pinned inside the wrapper. |
| 1042 | path = [ config.nix.package ]; |
| 1043 | # The repositories belong to the git user and the controller does |
| 1044 | # not, so git refuses to touch them as dubiously owned. The exception |
| 1045 | # rides in the unit's environment, for two reasons. GIT_CONFIG_* is |
| 1046 | # command-scope config, which is protected config, so safe.directory |
| 1047 | # is honoured from it — a repository-scoped setting would be ignored, |
| 1048 | # deliberately. And every git the controller drives is a child of |
| 1049 | # this unit, whether run by the integrator itself or by attest or the |
| 1050 | # deriver, so one environment covers all of them. |
| 1051 | # |
| 1052 | # One repository per instance: never a global gitconfig, never a |
| 1053 | # wildcard. Every other repository on the host stays refused. Linked |
| 1054 | # worktrees need no entry of their own — the controller creates them, |
| 1055 | # so it owns them, and git checks the worktree and its gitdir rather |
| 1056 | # than the repository they point at. |
| 1057 | # |
| 1058 | # TMPDIR is the same kind of wiring, for the same reason. A verdict |
| 1059 | # wants a checkout of the tip on disk, and the integrator asks for one |
| 1060 | # the ordinary way — a temporary directory, then a linked worktree in |
| 1061 | # it. The sandbox below leaves no writable temporary directory, so |
| 1062 | # every tick died on `could not create leading directories`. The |
| 1063 | # scratch belongs under the state directory the unit already has: |
| 1064 | # writable by construction, owned by this service, and gone when the |
| 1065 | # service's state is. Setting it in the environment rather than |
| 1066 | # teaching the binary a flag covers every process in the unit at once |
| 1067 | # — the integrator, attest, the deriver, and the git each of them runs |
| 1068 | # all read TMPDIR, and all of them want scratch in the same place. |
| 1069 | # |
| 1070 | # A second exception, for the instance repository. Every controller |
| 1071 | # reads the group's floor from that repository's tip, and it need not |
| 1072 | # be the project the controller serves — the controller for one |
| 1073 | # project reads the floor out of another project's repository, which |
| 1074 | # it likewise does not own. Without the exception git refuses it as |
| 1075 | # dubiously owned and every pass fails, exactly as it did for the |
| 1076 | # served repository. Two entries, both named; still never a wildcard. |
| 1077 | # |
| 1078 | # Reading needs no sandbox entry beside it. ProtectSystem=strict |
| 1079 | # leaves the filesystem readable and only takes write away, so the |
| 1080 | # ReadWritePaths list above stays the list of what may be written, |
| 1081 | # which is what makes it worth reading. What read does need is a |
| 1082 | # filesystem grant, and valley-init makes it: the instance repository |
| 1083 | # is group-readable whether or not it is one of the served projects. |
| 1084 | environment = { |
| 1085 | GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1"; |
| 1086 | GIT_CONFIG_KEY_0 = "safe.directory"; |
| 1087 | GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git"; |
| 1088 | TMPDIR = integratorStateDir; |
| 1089 | } |
| 1090 | // lib.optionalAttrs (instanceRepo != null) { |
| 1091 | GIT_CONFIG_KEY_1 = "safe.directory"; |
| 1092 | GIT_CONFIG_VALUE_1 = instanceRepo; |
| 1093 | }; |
| 1094 | serviceConfig = { |
| 1095 | ExecStart = integratorCommand; |
| 1096 | Restart = "on-failure"; |
| 1097 | RestartSec = "10s"; |
| 1098 | User = cfg.integrator.user; |
| 1099 | Group = cfg.group; |
| 1100 | StateDirectory = integratorStateName; |
| 1101 | StateDirectoryMode = "0700"; |
| 1102 | WorkingDirectory = integratorStateDir; |
| 1103 | NoNewPrivileges = true; |
| 1104 | ProtectSystem = "strict"; |
| 1105 | # Everything the controller may write, named where a reader of the |
| 1106 | # unit meets it. Under ProtectSystem=strict the rest of the |
| 1107 | # filesystem is read-only, so this list is the whole of what the |
| 1108 | # service can touch, and it is worth being able to read it as such |
| 1109 | # rather than as the exceptions plus whatever else is implied. |
| 1110 | # |
| 1111 | # Its own directory: its state, and the scratch root TMPDIR names. |
| 1112 | # A declaration says it here rather than relying on the state |
| 1113 | # directory being read-write by virtue of being declared, which is |
| 1114 | # not something this unit found to be true. |
| 1115 | # |
| 1116 | # The one repository it serves, and the nix daemon's socket — |
| 1117 | # recomputing a closure means asking the daemon, and connecting to |
| 1118 | # a unix socket needs write access to it. |
| 1119 | ReadWritePaths = [ |
| 1120 | integratorStateDir |
| 1121 | "${cfg.dataDir}/%i.git" |
| 1122 | "/nix/var/nix/daemon-socket" |
| 1123 | ]; |
| 1124 | ProtectHome = true; |
| 1125 | PrivateTmp = true; |
| 1126 | PrivateDevices = true; |
| 1127 | ProtectClock = true; |
| 1128 | ProtectHostname = true; |
| 1129 | ProtectKernelLogs = true; |
| 1130 | ProtectKernelModules = true; |
| 1131 | ProtectKernelTunables = true; |
| 1132 | ProtectControlGroups = true; |
| 1133 | ProtectProc = "invisible"; |
| 1134 | RestrictAddressFamilies = [ |
| 1135 | "AF_INET" |
| 1136 | "AF_INET6" |
| 1137 | "AF_UNIX" |
| 1138 | ]; |
| 1139 | RestrictNamespaces = true; |
| 1140 | RestrictRealtime = true; |
| 1141 | RestrictSUIDSGID = true; |
| 1142 | LockPersonality = true; |
| 1143 | CapabilityBoundingSet = ""; |
| 1144 | SystemCallArchitectures = "native"; |
| 1145 | SystemCallFilter = [ "@system-service" ]; |
| 1146 | # Group write, not the bus unit's 0077: the git user owns these |
| 1147 | # repositories and has to stay able to write what a controller |
| 1148 | # leaves in them. |
| 1149 | UMask = "0002"; |
| 1150 | }; |
| 1151 | }; |
| 1152 | |
| 1153 | # wantedBy on a template unit enables nothing, so the instances the |
| 1154 | # declaration asks for are pulled in by name. |
| 1155 | systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable { |
| 1156 | description = "The valley integrator's controllers"; |
| 1157 | wantedBy = [ "multi-user.target" ]; |
| 1158 | wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects); |
| 1159 | }; |
| 1160 | |
| 1161 | # Offsite backup, rendered only when the declaration asks for it. The |
| 1162 | # declaration states the policy — that backup exists, its cadence and |
| 1163 | # retention; the services.valley.backup.* options supply the machine |
| 1164 | # half. Declaration absent or disabled ⇒ no restic config at all. |
| 1165 | services.restic.backups = lib.mkIf backupEnabled { |
| 1166 | valley = { |
| 1167 | initialize = true; |
| 1168 | repositoryFile = cfg.backup.repositoryFile; |
| 1169 | passwordFile = cfg.backup.passwordFile; |
| 1170 | paths = [ cfg.dataDir ]; |
| 1171 | # The schema admits only the restic-sftp target today; a second |
| 1172 | # target would grow a dispatch here. The service runs as root: |
| 1173 | # authenticate with the supplied identity and only the pinned |
| 1174 | # host key. No prompt can be answered inside a systemd unit, so |
| 1175 | # BatchMode + strict host key checking turn a would-be hang into |
| 1176 | # an immediate error. |
| 1177 | extraOptions = [ |
| 1178 | "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'" |
| 1179 | ]; |
| 1180 | timerConfig = backupTimer.${backupPolicy.cadence}; |
| 1181 | pruneOpts = [ |
| 1182 | "--keep-daily ${toString backupPolicy.retention.daily}" |
| 1183 | "--keep-weekly ${toString backupPolicy.retention.weekly}" |
| 1184 | "--keep-monthly ${toString backupPolicy.retention.monthly}" |
| 1185 | ]; |
| 1186 | }; |
| 1187 | }; |
| 1188 | }; |
| 1189 | } |