| 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 | # |
| 23 | # Mirror credentials are the consumer's concern: the module assumes the git |
| 24 | # user's SSH identity and known_hosts are provisioned by the host (e.g. |
| 25 | # cosmo, via its secrets). Nothing here plumbs secrets: the backup options |
| 26 | # below take *paths* to consumer-provisioned secret files; the contents |
| 27 | # never pass through this module or the store. |
| 28 | { |
| 29 | config, |
| 30 | pkgs, |
| 31 | lib, |
| 32 | ... |
| 33 | }: |
| 34 | |
| 35 | let |
| 36 | cfg = config.services.valley; |
| 37 | |
| 38 | schema = ../schema/valley.cue; |
| 39 | |
| 40 | # Build-time vet + export of the host declaration. the vet checks the |
| 41 | # declaration against the schema (whose top level applies #Host), so unknown |
| 42 | # fields and unsafe project names fail the build, with cue's error. |
| 43 | configJSON = |
| 44 | pkgs.runCommand "valley-config.json" |
| 45 | { |
| 46 | nativeBuildInputs = [ pkgs.cue ]; |
| 47 | } |
| 48 | '' |
| 49 | cue vet -c ${schema} ${cfg.config} |
| 50 | cue export ${schema} ${cfg.config} > $out |
| 51 | ''; |
| 52 | |
| 53 | host = lib.importJSON configJSON; |
| 54 | |
| 55 | # Projects whose git store is enabled get a bare repository. |
| 56 | gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects; |
| 57 | repoNames = lib.attrNames gitProjects; |
| 58 | |
| 59 | # The declared durability policy, if any. `backup` is optional in the |
| 60 | # schema: a declaration without it (or with enable = false) renders zero |
| 61 | # backup machinery, exactly as before the field existed. |
| 62 | backupPolicy = host.backup or null; |
| 63 | backupEnabled = backupPolicy != null && backupPolicy.enable; |
| 64 | |
| 65 | # The declared cadence names policy; its wall-clock rendering is this |
| 66 | # installer's choice. A lookup rather than a literal, so a cadence this |
| 67 | # module does not know fails eval loudly instead of mis-scheduling. |
| 68 | backupTimer = { |
| 69 | # Late night with a spread; Persistent runs a missed window at boot. |
| 70 | nightly = { |
| 71 | OnCalendar = "03:30"; |
| 72 | RandomizedDelaySec = "30m"; |
| 73 | Persistent = true; |
| 74 | }; |
| 75 | }; |
| 76 | |
| 77 | # The secret-path options the consumer must supply once the declaration |
| 78 | # enables backup, with what each names — for the assertion message. |
| 79 | backupSecretOptions = { |
| 80 | repositoryFile = "the restic repository URL"; |
| 81 | passwordFile = "the repository encryption password"; |
| 82 | sshKeyFile = "the SSH identity for the sftp target"; |
| 83 | knownHostsFile = "the pinned host key of the sftp target"; |
| 84 | }; |
| 85 | |
| 86 | # Managed post-receive dispatcher. Each repo's post-receive is a symlink to |
| 87 | # this script, which chains every executable dropped into the repo's |
| 88 | # hooks/post-receive.d/ directory. |
| 89 | postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" '' |
| 90 | # Managed by services.valley — do not edit. |
| 91 | # Drop executable hooks into post-receive.d/ next to this symlink. |
| 92 | set -eu |
| 93 | hook_dir="$(dirname "$0")/post-receive.d" |
| 94 | [ -d "$hook_dir" ] || exit 0 |
| 95 | updates="$(cat)" |
| 96 | [ -n "$updates" ] || exit 0 |
| 97 | for hook in "$hook_dir"/*; do |
| 98 | [ -x "$hook" ] || continue |
| 99 | printf '%s\n' "$updates" | "$hook" "$@" |
| 100 | done |
| 101 | ''; |
| 102 | |
| 103 | # Best-effort push replication. Publication mirror: main and tags only. |
| 104 | # Topic branches are review-queue state, not published — the mirror exists |
| 105 | # so consumers can fetch what has been integrated; durability is restic's |
| 106 | # job, not the mirror's. Pushes run detached (setsid) so a dead mirror can |
| 107 | # only ever cost a log line — never block or fail the primary push. |
| 108 | # --prune propagates tag deletions (glob refspec); it is a no-op for heads |
| 109 | # now that the heads refspec names one ref, so a separate best-effort sweep |
| 110 | # deletes every mirror head but main — which also strips anything that |
| 111 | # appears there by other means. The sweep reads only refs/heads (ls-remote |
| 112 | # --heads), never refs/pull/*, and is logged apart from the replication |
| 113 | # push so it cannot change that push's reported outcome. --mirror is |
| 114 | # rejected outright: it also tries to delete remote-only namespaces, and on |
| 115 | # GitHub the read-only refs/pull/* makes that fail every push, masking real |
| 116 | # replication failures. |
| 117 | mirrorPusher = |
| 118 | name: mirrors: |
| 119 | pkgs.writeShellScript "valley-mirror-push-${name}" '' |
| 120 | for url in ${lib.escapeShellArgs mirrors}; do |
| 121 | if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then |
| 122 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true |
| 123 | else |
| 124 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true |
| 125 | fi |
| 126 | |
| 127 | # Unpublish anything but main. Refnames cannot contain whitespace, so |
| 128 | # accumulating them space-separated and splitting on expansion is safe. |
| 129 | stale="" |
| 130 | while read -r _ ref; do |
| 131 | [ "$ref" = refs/heads/main ] || stale="$stale $ref" |
| 132 | done < <(${pkgs.git}/bin/git ls-remote --heads "$url" 2>/dev/null) |
| 133 | if [ -n "$stale" ]; then |
| 134 | if ${pkgs.git}/bin/git push "$url" --delete $stale >/dev/null 2>&1; then |
| 135 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublished$stale from $url" || true |
| 136 | else |
| 137 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublish from $url failed (ignored)" || true |
| 138 | fi |
| 139 | fi |
| 140 | done |
| 141 | ''; |
| 142 | |
| 143 | mirrorHook = |
| 144 | name: mirrors: |
| 145 | pkgs.writeShellScript "valley-mirrors-${name}" '' |
| 146 | # Managed by services.valley — best-effort push mirrors for ${name}. |
| 147 | cat >/dev/null # updated refs unused: the push replicates main and tags |
| 148 | ${pkgs.util-linux}/bin/setsid -f ${mirrorPusher name mirrors} </dev/null >/dev/null 2>&1 |
| 149 | exit 0 |
| 150 | ''; |
| 151 | |
| 152 | # The event bus (design/roadmap.md, Phase 1): NATS JetStream, onto which |
| 153 | # the ref-updated hook below projects this host's git activity. The bus is |
| 154 | # never load-bearing for durable state — per-repo events are durable in |
| 155 | # git itself, and `valley replay` rebuilds the stream from a repo's refs — |
| 156 | # so losing its storage costs one replay, nothing more. |
| 157 | busUrl = "nats://${cfg.bus.listen}"; |
| 158 | |
| 159 | busServerConfig = pkgs.writeText "valley-bus.conf" '' |
| 160 | listen: ${cfg.bus.listen} |
| 161 | jetstream { |
| 162 | store_dir: "${cfg.bus.storeDir}" |
| 163 | # The store directory defaults to living on the repo volume; the cap |
| 164 | # keeps a runaway or malicious local publisher from filling it. |
| 165 | max_file_store: 2GiB |
| 166 | } |
| 167 | ''; |
| 168 | |
| 169 | # One ref-updated event per updated ref, read from the post-receive stdin |
| 170 | # this script inherits. Every payload field is derivable from git alone — |
| 171 | # no wall-clock time, no hostname — so replaying a repo's refs reproduces |
| 172 | # the same events (the roadmap's determinism criterion). `valley replay` |
| 173 | # builds the identical payload; change one only with the other. |
| 174 | busPublisher = pkgs.writeShellScript "valley-bus-publish" '' |
| 175 | repo="$(basename "$PWD" .git)" |
| 176 | while read -r old new ref; do |
| 177 | [ -n "$ref" ] || continue |
| 178 | # " is the only JSON-significant character a refname can contain |
| 179 | # (git forbids \ and control characters); names and ids are safe. |
| 180 | event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \ |
| 181 | "$repo" "''${ref//\"/\\\"}" "$old" "$new")" |
| 182 | if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \ |
| 183 | "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then |
| 184 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true |
| 185 | else |
| 186 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true |
| 187 | fi |
| 188 | done |
| 189 | ''; |
| 190 | |
| 191 | # The post-receive.d hook, with the mirror hook's failure semantics: the |
| 192 | # publisher runs detached (setsid, inheriting the updates on stdin), so a |
| 193 | # bus problem can only ever cost a log line — never block or fail the |
| 194 | # push. git is the source of truth; the bus is the replaceable component. |
| 195 | busEventHook = pkgs.writeShellScript "valley-bus-events" '' |
| 196 | # Managed by services.valley — project ref updates onto the event bus. |
| 197 | ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1 |
| 198 | exit 0 |
| 199 | ''; |
| 200 | |
| 201 | # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks: |
| 202 | # only ever installs, updates, or removes a store symlink — a hand-written |
| 203 | # hook of the same name is left alone. |
| 204 | busHookCommands = lib.concatMapStrings ( |
| 205 | name: |
| 206 | let |
| 207 | bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus"; |
| 208 | in |
| 209 | if cfg.bus.enable then |
| 210 | '' |
| 211 | bhook=${bhook} |
| 212 | if [ -L "$bhook" ]; then |
| 213 | case "$(readlink "$bhook")" in |
| 214 | /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;; |
| 215 | esac |
| 216 | elif [ ! -e "$bhook" ]; then |
| 217 | ln -s ${busEventHook} "$bhook" |
| 218 | fi |
| 219 | '' |
| 220 | else |
| 221 | '' |
| 222 | bhook=${bhook} |
| 223 | if [ -L "$bhook" ]; then |
| 224 | case "$(readlink "$bhook")" in |
| 225 | /nix/store/*) rm -f "$bhook" ;; |
| 226 | esac |
| 227 | fi |
| 228 | '' |
| 229 | ) repoNames; |
| 230 | |
| 231 | # Per-project mirror-hook wiring. Only ever installs, updates, or removes |
| 232 | # a store symlink — a hand-written hook of the same name is left alone. |
| 233 | mirrorHookCommands = lib.concatStrings ( |
| 234 | lib.mapAttrsToList ( |
| 235 | name: p: |
| 236 | let |
| 237 | mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors"; |
| 238 | in |
| 239 | if p.mirrors != [ ] then |
| 240 | '' |
| 241 | mhook=${mhook} |
| 242 | if [ -L "$mhook" ]; then |
| 243 | case "$(readlink "$mhook")" in |
| 244 | /nix/store/*) ln -sfn ${mirrorHook name p.mirrors} "$mhook" ;; |
| 245 | esac |
| 246 | elif [ ! -e "$mhook" ]; then |
| 247 | ln -s ${mirrorHook name p.mirrors} "$mhook" |
| 248 | fi |
| 249 | '' |
| 250 | else |
| 251 | '' |
| 252 | mhook=${mhook} |
| 253 | if [ -L "$mhook" ]; then |
| 254 | case "$(readlink "$mhook")" in |
| 255 | /nix/store/*) rm -f "$mhook" ;; |
| 256 | esac |
| 257 | fi |
| 258 | '' |
| 259 | ) gitProjects |
| 260 | ); |
| 261 | |
| 262 | # The environment variable carrying the pushing key's principal name. |
| 263 | # sshd sets it from the key's own authorized_keys entry; the pre-receive |
| 264 | # hook reads it. One name, honoured only because PermitUserEnvironment |
| 265 | # below names it. |
| 266 | principalEnv = "VALLEY_PRINCIPAL"; |
| 267 | |
| 268 | # Keys that name a principal. An entry written as a bare string names |
| 269 | # none, and renders exactly as it always did. |
| 270 | taggedKeys = lib.filter (k: !lib.isString k) cfg.authorizedKeys; |
| 271 | |
| 272 | authorizedKeyLine = |
| 273 | k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}''; |
| 274 | |
| 275 | # Where a contributor's attestations live (design/contribute.md, step 5). |
| 276 | attestationNamespace = "refs/the-valley/attestations/"; |
| 277 | |
| 278 | # The pre-receive hook: the one structural git invariant |
| 279 | # (design/architecture.md, design/contribute.md). Two clauses and nothing |
| 280 | # else — only a declared writer may update a protected ref, and an |
| 281 | # attestation ref may only be created. Every other ref is open to anyone |
| 282 | # with push access, and all policy beyond this lives in the integrator. |
| 283 | # |
| 284 | # Pushes arrive over SSH as one shared git user, so the unix account |
| 285 | # behind a push says nothing about who pushed. The principal comes from |
| 286 | # the key instead: services.valley.authorizedKeys tags each key's |
| 287 | # authorized_keys entry, sshd puts that tag in the environment of the |
| 288 | # receive-pack this hook runs under, and an untagged key has no principal |
| 289 | # at all. The client cannot supply the tag itself — sshd passes on no |
| 290 | # client environment (no AcceptEnv). |
| 291 | # |
| 292 | # This governs pushes, which is every write that crosses the host |
| 293 | # boundary. It does not govern writes made on the host: the integrator |
| 294 | # updates refs locally, as could anyone holding the git user's shell. |
| 295 | # Local access is the host's own boundary, not this hook's. |
| 296 | protectHook = |
| 297 | name: p: |
| 298 | pkgs.writeShellScript "valley-protect-${name}" '' |
| 299 | # Managed by services.valley — do not edit. |
| 300 | set -eu |
| 301 | |
| 302 | principal="''${${principalEnv}:-}" |
| 303 | [ -n "$principal" ] || principal="<untagged key>" |
| 304 | writers=( ${lib.escapeShellArgs p.writers} ) |
| 305 | protected=( ${lib.escapeShellArgs p.refs} ) |
| 306 | |
| 307 | is_writer() { |
| 308 | local w |
| 309 | for w in ''${writers[@]+"''${writers[@]}"}; do |
| 310 | if [ "$w" = "$principal" ]; then return 0; fi |
| 311 | done |
| 312 | return 1 |
| 313 | } |
| 314 | |
| 315 | rejected=0 |
| 316 | while read -r old new ref; do |
| 317 | [ -n "$ref" ] || continue |
| 318 | |
| 319 | # An attestation is a record of what was checked; a record that can |
| 320 | # be rewritten or dropped is not one. So the namespace is |
| 321 | # create-only, for everyone — an all-zero old id is a creation, at |
| 322 | # any hash length. |
| 323 | case "$ref" in |
| 324 | ${attestationNamespace}*) |
| 325 | case "$old" in |
| 326 | *[!0]*) |
| 327 | echo "valley: $principal may not update $ref — attestation refs are create-only" >&2 |
| 328 | rejected=1 |
| 329 | ;; |
| 330 | esac |
| 331 | continue |
| 332 | ;; |
| 333 | esac |
| 334 | |
| 335 | # Protected refs, matched as shell globs (so `*` crosses path |
| 336 | # separators). Unprotected refs are not the hook's business. |
| 337 | for pattern in ''${protected[@]+"''${protected[@]}"}; do |
| 338 | case "$ref" in |
| 339 | $pattern) |
| 340 | if ! is_writer; then |
| 341 | echo "valley: $principal may not write $ref — a protected ref of ${name} (writers: ${ |
| 342 | if p.writers == [ ] then "none" else lib.concatStringsSep ", " p.writers |
| 343 | })" >&2 |
| 344 | rejected=1 |
| 345 | fi |
| 346 | break |
| 347 | ;; |
| 348 | esac |
| 349 | done |
| 350 | done |
| 351 | exit "$rejected" |
| 352 | ''; |
| 353 | |
| 354 | # Per-project pre-receive wiring. Same rules as the other managed hooks: |
| 355 | # only ever installs, updates, or removes a store symlink — a |
| 356 | # hand-written hook of the same name is left alone. A project nobody |
| 357 | # declared protection for gets no hook, so a declaration written before |
| 358 | # these options installs nothing new. |
| 359 | protectHookCommands = lib.concatStrings ( |
| 360 | lib.mapAttrsToList ( |
| 361 | name: _: |
| 362 | let |
| 363 | phook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/pre-receive"; |
| 364 | in |
| 365 | if cfg.protect ? ${name} then |
| 366 | '' |
| 367 | phook=${phook} |
| 368 | if [ -L "$phook" ]; then |
| 369 | case "$(readlink "$phook")" in |
| 370 | /nix/store/*) ln -sfn ${protectHook name cfg.protect.${name}} "$phook" ;; |
| 371 | esac |
| 372 | elif [ ! -e "$phook" ]; then |
| 373 | ln -s ${protectHook name cfg.protect.${name}} "$phook" |
| 374 | fi |
| 375 | '' |
| 376 | else |
| 377 | '' |
| 378 | phook=${phook} |
| 379 | if [ -L "$phook" ]; then |
| 380 | case "$(readlink "$phook")" in |
| 381 | /nix/store/*) rm -f "$phook" ;; |
| 382 | esac |
| 383 | fi |
| 384 | '' |
| 385 | ) gitProjects |
| 386 | ); |
| 387 | in |
| 388 | { |
| 389 | options.services.valley = { |
| 390 | enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration"; |
| 391 | |
| 392 | user = lib.mkOption { |
| 393 | type = lib.types.str; |
| 394 | default = "git"; |
| 395 | description = "System user that owns the repositories and accepts SSH pushes."; |
| 396 | }; |
| 397 | |
| 398 | group = lib.mkOption { |
| 399 | type = lib.types.str; |
| 400 | default = "git"; |
| 401 | description = "Primary group of the valley git user."; |
| 402 | }; |
| 403 | |
| 404 | dataDir = lib.mkOption { |
| 405 | type = lib.types.path; |
| 406 | default = "/srv/git"; |
| 407 | example = "/mnt/git"; |
| 408 | description = '' |
| 409 | Directory holding the bare repositories, one `<name>.git` per |
| 410 | project declared in {option}`services.valley.config`. Also the git |
| 411 | user's home, so clone URLs are relative to it (`git@host:name.git`). |
| 412 | Consumers typically point it at a dedicated dataset. |
| 413 | ''; |
| 414 | }; |
| 415 | |
| 416 | authorizedKeys = lib.mkOption { |
| 417 | type = lib.types.listOf ( |
| 418 | lib.types.either lib.types.str ( |
| 419 | lib.types.submodule { |
| 420 | options = { |
| 421 | key = lib.mkOption { |
| 422 | type = lib.types.str; |
| 423 | description = "The SSH public key, as it would appear in `authorized_keys`."; |
| 424 | }; |
| 425 | |
| 426 | principal = lib.mkOption { |
| 427 | type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*"; |
| 428 | example = "integrator"; |
| 429 | description = '' |
| 430 | Name of the principal this key acts as. Every push made |
| 431 | with the key carries the name, and |
| 432 | {option}`services.valley.protect` decides what a name may |
| 433 | write. Nothing else uses it. |
| 434 | ''; |
| 435 | }; |
| 436 | }; |
| 437 | } |
| 438 | ) |
| 439 | ); |
| 440 | default = [ ]; |
| 441 | example = lib.literalExpression '' |
| 442 | [ |
| 443 | "ssh-ed25519 AAAA… someone@somewhere" |
| 444 | { |
| 445 | principal = "integrator"; |
| 446 | key = "ssh-ed25519 AAAA… integrator"; |
| 447 | } |
| 448 | ] |
| 449 | ''; |
| 450 | description = '' |
| 451 | SSH public keys allowed to push/fetch as the git user. Access is |
| 452 | host-level by design: every key can reach every project. |
| 453 | |
| 454 | A key written as a plain string is anonymous — it can push, and it |
| 455 | can write nothing protected. A key written as an attribute set |
| 456 | names the principal it acts as, which is the only thing that can |
| 457 | tell one pusher from another: pushes arrive as the shared git user, |
| 458 | so identity has to ride on the key. |
| 459 | ''; |
| 460 | }; |
| 461 | |
| 462 | protect = lib.mkOption { |
| 463 | type = lib.types.attrsOf ( |
| 464 | lib.types.submodule { |
| 465 | options = { |
| 466 | refs = lib.mkOption { |
| 467 | type = lib.types.listOf lib.types.str; |
| 468 | default = [ "refs/heads/main" ]; |
| 469 | example = [ |
| 470 | "refs/heads/main" |
| 471 | "refs/heads/release/*" |
| 472 | ]; |
| 473 | description = '' |
| 474 | Refs only a writer may create, update, or delete, as shell |
| 475 | globs against the full refname (so `*` crosses `/`). |
| 476 | ''; |
| 477 | }; |
| 478 | |
| 479 | writers = lib.mkOption { |
| 480 | type = lib.types.listOf lib.types.str; |
| 481 | default = [ ]; |
| 482 | example = [ "integrator" ]; |
| 483 | description = '' |
| 484 | Principals allowed to write this project's protected refs, |
| 485 | named as in {option}`services.valley.authorizedKeys`. The |
| 486 | empty default protects the refs from every push: the |
| 487 | integrator writes them on the host, not over SSH. |
| 488 | ''; |
| 489 | }; |
| 490 | }; |
| 491 | } |
| 492 | ); |
| 493 | default = { }; |
| 494 | example = lib.literalExpression ''{ the-valley.writers = [ "integrator" ]; }''; |
| 495 | description = '' |
| 496 | Per-project write protection, keyed by project name — the one |
| 497 | structural git invariant: only a declared writer may write a |
| 498 | protected ref, and attestation refs |
| 499 | (`refs/the-valley/attestations/*`) are create-only for everyone. |
| 500 | Topic branches, tags, and new attestation refs stay open to anyone |
| 501 | with push access; all policy beyond this lives in the integrator. |
| 502 | |
| 503 | Naming a project turns its `pre-receive` hook on. A project left |
| 504 | out of this attribute set has no hook at all, so a host declared |
| 505 | before this option serves exactly what it served before. |
| 506 | ''; |
| 507 | }; |
| 508 | |
| 509 | config = lib.mkOption { |
| 510 | type = lib.types.path; |
| 511 | example = lib.literalExpression "./valley.cue"; |
| 512 | description = '' |
| 513 | Path to the host's CUE declaration (`package valley`) — the |
| 514 | canonical statement of what this valley host serves, validated |
| 515 | against the shipped schema at build time. This is the single domain |
| 516 | input: projects, their push mirrors, and the backup policy are |
| 517 | declared here, never as Nix options. |
| 518 | ''; |
| 519 | }; |
| 520 | |
| 521 | # The event bus. Machine options, not domain: whether this machine runs |
| 522 | # a bus, where it listens, and where its storage lives. What gets |
| 523 | # published onto it is defined portably in ../schema/events.cue. |
| 524 | bus = { |
| 525 | enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events"; |
| 526 | |
| 527 | listen = lib.mkOption { |
| 528 | type = lib.types.str; |
| 529 | default = "127.0.0.1:4222"; |
| 530 | example = "100.100.1.7:4222"; |
| 531 | description = '' |
| 532 | Address the bus listens on, `host:port`. Localhost by default: |
| 533 | nothing off the host can reach the bus until the consumer widens |
| 534 | this deliberately — e.g. to the host's tailnet address once a |
| 535 | remote `valley tail` wants in. Local publishers (the ref-updated |
| 536 | hook) connect to this same address, so it must be reachable from |
| 537 | the host itself. |
| 538 | ''; |
| 539 | }; |
| 540 | |
| 541 | storeDir = lib.mkOption { |
| 542 | type = lib.types.path; |
| 543 | default = "${cfg.dataDir}/.bus"; |
| 544 | defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"''; |
| 545 | description = '' |
| 546 | Directory holding the JetStream file storage. The default lives |
| 547 | under {option}`services.valley.dataDir`; it can never collide |
| 548 | with a repository because project names must start with an |
| 549 | alphanumeric. The stream is a projection of git, rebuildable |
| 550 | with `valley replay` — losing this directory costs one replay. |
| 551 | ''; |
| 552 | }; |
| 553 | }; |
| 554 | |
| 555 | # Machine integration for the declared backup policy. The declaration |
| 556 | # states WHAT must hold (offsite backup, cadence, retention); these |
| 557 | # options supply HOW on this machine — where the repository is and how |
| 558 | # to authenticate. All are paths to files the consumer provisions |
| 559 | # (e.g. agenix), required when the declaration enables backup. Point |
| 560 | # them at runtime paths, never at files in the Nix store. |
| 561 | backup = { |
| 562 | repositoryFile = lib.mkOption { |
| 563 | type = lib.types.nullOr lib.types.path; |
| 564 | default = null; |
| 565 | example = "/run/agenix/valley-restic-repo"; |
| 566 | description = '' |
| 567 | File containing the restic repository URL, for the sftp target |
| 568 | e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`. |
| 569 | ''; |
| 570 | }; |
| 571 | |
| 572 | passwordFile = lib.mkOption { |
| 573 | type = lib.types.nullOr lib.types.path; |
| 574 | default = null; |
| 575 | example = "/run/agenix/valley-restic-password"; |
| 576 | description = '' |
| 577 | File containing the restic repository encryption password. |
| 578 | Losing it loses the backups — keep a copy somewhere that |
| 579 | survives this host. |
| 580 | ''; |
| 581 | }; |
| 582 | |
| 583 | sshKeyFile = lib.mkOption { |
| 584 | type = lib.types.nullOr lib.types.path; |
| 585 | default = null; |
| 586 | example = "/run/agenix/valley-git-ssh-key"; |
| 587 | description = '' |
| 588 | SSH private key that authenticates to the sftp target. The |
| 589 | backup service runs as root, so any identity the target |
| 590 | authorizes works — reusing the mirror key is fine. |
| 591 | ''; |
| 592 | }; |
| 593 | |
| 594 | knownHostsFile = lib.mkOption { |
| 595 | type = lib.types.nullOr lib.types.path; |
| 596 | default = null; |
| 597 | example = "/var/lib/valley-backup/known_hosts"; |
| 598 | description = '' |
| 599 | known_hosts file pinning the sftp target's host key. Pin from |
| 600 | the provider's published fingerprints, not a blind ssh-keyscan. |
| 601 | ''; |
| 602 | }; |
| 603 | }; |
| 604 | }; |
| 605 | |
| 606 | config = lib.mkIf cfg.enable { |
| 607 | assertions = [ |
| 608 | { |
| 609 | assertion = cfg.authorizedKeys != [ ]; |
| 610 | message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable."; |
| 611 | } |
| 612 | ] |
| 613 | ++ lib.mapAttrsToList (name: _: { |
| 614 | assertion = gitProjects ? ${name}; |
| 615 | message = "services.valley.protect.${name} protects refs of a project this host does not serve — the declaration has no git store named ${name}."; |
| 616 | }) cfg.protect |
| 617 | ++ lib.optionals backupEnabled ( |
| 618 | lib.mapAttrsToList (name: what: { |
| 619 | assertion = cfg.backup.${name} != null; |
| 620 | 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)."; |
| 621 | }) backupSecretOptions |
| 622 | ); |
| 623 | |
| 624 | users.groups.${cfg.group} = { }; |
| 625 | |
| 626 | users.users.${cfg.user} = { |
| 627 | isSystemUser = true; |
| 628 | group = cfg.group; |
| 629 | home = cfg.dataDir; |
| 630 | # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive; |
| 631 | # interactive logins are rejected (no ~/git-shell-commands). |
| 632 | shell = "${pkgs.git}/bin/git-shell"; |
| 633 | openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys; |
| 634 | }; |
| 635 | |
| 636 | services.openssh.enable = lib.mkDefault true; |
| 637 | |
| 638 | # Honour the principal tag on a key's entry, and nothing else: the |
| 639 | # pattern-list form admits that one variable name. Rendered only once a |
| 640 | # key names a principal, so a host with none keeps the sshd config it |
| 641 | # had. |
| 642 | services.openssh.settings = lib.optionalAttrs (taggedKeys != [ ]) { |
| 643 | PermitUserEnvironment = principalEnv; |
| 644 | }; |
| 645 | |
| 646 | # Belt-and-braces hardening for the git user. The trailing `Match All` |
| 647 | # closes the block so it can't scope directives appended to sshd_config |
| 648 | # after this snippet. |
| 649 | services.openssh.extraConfig = '' |
| 650 | Match User ${cfg.user} |
| 651 | AllowTcpForwarding no |
| 652 | AllowAgentForwarding no |
| 653 | X11Forwarding no |
| 654 | PermitTunnel no |
| 655 | Match All |
| 656 | ''; |
| 657 | |
| 658 | # git-shell spawns git-receive-pack/git-upload-pack from PATH |
| 659 | environment.systemPackages = [ pkgs.git ]; |
| 660 | |
| 661 | systemd.tmpfiles.rules = [ |
| 662 | "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -" |
| 663 | ] |
| 664 | ++ lib.optionals cfg.bus.enable [ |
| 665 | "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -" |
| 666 | ]; |
| 667 | |
| 668 | # The bus itself. It runs as the git user — the store directory lives in |
| 669 | # that user's data — but the sandbox is what confines it: the unit can |
| 670 | # write nowhere except its store directory. |
| 671 | systemd.services.valley-bus = lib.mkIf cfg.bus.enable { |
| 672 | description = "The valley event bus (NATS JetStream)"; |
| 673 | wantedBy = [ "multi-user.target" ]; |
| 674 | after = [ |
| 675 | "network.target" |
| 676 | "systemd-tmpfiles-setup.service" |
| 677 | ]; |
| 678 | unitConfig.RequiresMountsFor = cfg.bus.storeDir; |
| 679 | serviceConfig = { |
| 680 | ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}"; |
| 681 | Restart = "on-failure"; |
| 682 | User = cfg.user; |
| 683 | Group = cfg.group; |
| 684 | LimitNOFILE = 65536; |
| 685 | NoNewPrivileges = true; |
| 686 | ProtectSystem = "strict"; |
| 687 | ReadWritePaths = [ cfg.bus.storeDir ]; |
| 688 | ProtectHome = true; |
| 689 | PrivateTmp = true; |
| 690 | PrivateDevices = true; |
| 691 | ProtectClock = true; |
| 692 | ProtectHostname = true; |
| 693 | ProtectKernelLogs = true; |
| 694 | ProtectKernelModules = true; |
| 695 | ProtectKernelTunables = true; |
| 696 | ProtectControlGroups = true; |
| 697 | ProtectProc = "invisible"; |
| 698 | RestrictAddressFamilies = [ |
| 699 | "AF_INET" |
| 700 | "AF_INET6" |
| 701 | "AF_UNIX" |
| 702 | ]; |
| 703 | RestrictNamespaces = true; |
| 704 | RestrictRealtime = true; |
| 705 | RestrictSUIDSGID = true; |
| 706 | LockPersonality = true; |
| 707 | CapabilityBoundingSet = ""; |
| 708 | SystemCallArchitectures = "native"; |
| 709 | SystemCallFilter = [ "@system-service" ]; |
| 710 | UMask = "0077"; |
| 711 | }; |
| 712 | }; |
| 713 | |
| 714 | # The stream is config, not state: (re)created idempotently on every |
| 715 | # boot, capturing everything under valley.>. An existing stream — and |
| 716 | # the events in it — is left untouched. |
| 717 | systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable { |
| 718 | description = "Create the valley event stream"; |
| 719 | wantedBy = [ "multi-user.target" ]; |
| 720 | requires = [ "valley-bus.service" ]; |
| 721 | after = [ "valley-bus.service" ]; |
| 722 | serviceConfig = { |
| 723 | Type = "oneshot"; |
| 724 | User = cfg.user; |
| 725 | Group = cfg.group; |
| 726 | }; |
| 727 | path = [ pkgs.natscli ]; |
| 728 | script = '' |
| 729 | # The server needs a moment to accept connections after startup. |
| 730 | for _ in $(seq 1 50); do |
| 731 | nats --server ${busUrl} stream ls >/dev/null 2>&1 && break |
| 732 | sleep 0.2 |
| 733 | done |
| 734 | if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then |
| 735 | nats --server ${busUrl} stream add valley \ |
| 736 | --subjects 'valley.>' --storage file --defaults |
| 737 | fi |
| 738 | ''; |
| 739 | }; |
| 740 | |
| 741 | # Create missing bare repos and (re)wire the managed hooks on every |
| 742 | # activation where the declaration changed. |
| 743 | systemd.services.valley-init = { |
| 744 | description = "Initialize the valley host's bare git repositories"; |
| 745 | wantedBy = [ "multi-user.target" ]; |
| 746 | after = [ "systemd-tmpfiles-setup.service" ]; |
| 747 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 748 | serviceConfig = { |
| 749 | Type = "oneshot"; |
| 750 | User = cfg.user; |
| 751 | Group = cfg.group; |
| 752 | }; |
| 753 | path = [ pkgs.git ]; |
| 754 | script = '' |
| 755 | repos=( ${lib.escapeShellArgs repoNames} ) |
| 756 | for name in "''${repos[@]}"; do |
| 757 | repo="${cfg.dataDir}/$name.git" |
| 758 | # Check HEAD rather than the directory itself so a pre-existing |
| 759 | # empty directory still gets initialized. |
| 760 | if [ ! -e "$repo/HEAD" ]; then |
| 761 | git init --bare --initial-branch=main "$repo" |
| 762 | fi |
| 763 | |
| 764 | # Hook scaffolding: post-receive dispatches to post-receive.d/. |
| 765 | # Only manage the hook if it is absent or already ours (a store |
| 766 | # symlink) — a hand-written hook is left alone. |
| 767 | mkdir -p "$repo/hooks/post-receive.d" |
| 768 | hook="$repo/hooks/post-receive" |
| 769 | if [ -L "$hook" ]; then |
| 770 | case "$(readlink "$hook")" in |
| 771 | /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;; |
| 772 | esac |
| 773 | elif [ ! -e "$hook" ]; then |
| 774 | ln -s ${postReceiveDispatch} "$hook" |
| 775 | fi |
| 776 | done |
| 777 | |
| 778 | # Per-project push-mirror hooks. |
| 779 | ${mirrorHookCommands} |
| 780 | |
| 781 | # The one structural invariant, on every project declared protected. |
| 782 | ${protectHookCommands} |
| 783 | |
| 784 | # The ref-updated publisher hook, on every repo when the bus is on. |
| 785 | ${busHookCommands} |
| 786 | ''; |
| 787 | }; |
| 788 | |
| 789 | # Offsite backup, rendered only when the declaration asks for it. The |
| 790 | # declaration states the policy — that backup exists, its cadence and |
| 791 | # retention; the services.valley.backup.* options supply the machine |
| 792 | # half. Declaration absent or disabled ⇒ no restic config at all. |
| 793 | services.restic.backups = lib.mkIf backupEnabled { |
| 794 | valley = { |
| 795 | initialize = true; |
| 796 | repositoryFile = cfg.backup.repositoryFile; |
| 797 | passwordFile = cfg.backup.passwordFile; |
| 798 | paths = [ cfg.dataDir ]; |
| 799 | # The schema admits only the restic-sftp target today; a second |
| 800 | # target would grow a dispatch here. The service runs as root: |
| 801 | # authenticate with the supplied identity and only the pinned |
| 802 | # host key. No prompt can be answered inside a systemd unit, so |
| 803 | # BatchMode + strict host key checking turn a would-be hang into |
| 804 | # an immediate error. |
| 805 | extraOptions = [ |
| 806 | "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'" |
| 807 | ]; |
| 808 | timerConfig = backupTimer.${backupPolicy.cadence}; |
| 809 | pruneOpts = [ |
| 810 | "--keep-daily ${toString backupPolicy.retention.daily}" |
| 811 | "--keep-weekly ${toString backupPolicy.retention.weekly}" |
| 812 | "--keep-monthly ${toString backupPolicy.retention.monthly}" |
| 813 | ]; |
| 814 | }; |
| 815 | }; |
| 816 | }; |
| 817 | } |