| 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). |
| 19 | # |
| 20 | # Mirror credentials are the consumer's concern: the module assumes the git |
| 21 | # user's SSH identity and known_hosts are provisioned by the host (e.g. |
| 22 | # cosmo, via its secrets). Nothing here plumbs secrets: the backup options |
| 23 | # below take *paths* to consumer-provisioned secret files; the contents |
| 24 | # never pass through this module or the store. |
| 25 | { |
| 26 | config, |
| 27 | pkgs, |
| 28 | lib, |
| 29 | ... |
| 30 | }: |
| 31 | |
| 32 | let |
| 33 | cfg = config.services.valley; |
| 34 | |
| 35 | schema = ../schema/valley.cue; |
| 36 | |
| 37 | # Build-time vet + export of the host declaration. the vet checks the |
| 38 | # declaration against the schema (whose top level applies #Host), so unknown |
| 39 | # fields and unsafe project names fail the build, with cue's error. |
| 40 | configJSON = |
| 41 | pkgs.runCommand "valley-config.json" |
| 42 | { |
| 43 | nativeBuildInputs = [ pkgs.cue ]; |
| 44 | } |
| 45 | '' |
| 46 | cue vet -c ${schema} ${cfg.config} |
| 47 | cue export ${schema} ${cfg.config} > $out |
| 48 | ''; |
| 49 | |
| 50 | host = lib.importJSON configJSON; |
| 51 | |
| 52 | # Projects whose git store is enabled get a bare repository. |
| 53 | gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects; |
| 54 | repoNames = lib.attrNames gitProjects; |
| 55 | |
| 56 | # The declared durability policy, if any. `backup` is optional in the |
| 57 | # schema: a declaration without it (or with enable = false) renders zero |
| 58 | # backup machinery, exactly as before the field existed. |
| 59 | backupPolicy = host.backup or null; |
| 60 | backupEnabled = backupPolicy != null && backupPolicy.enable; |
| 61 | |
| 62 | # The declared cadence names policy; its wall-clock rendering is this |
| 63 | # installer's choice. A lookup rather than a literal, so a cadence this |
| 64 | # module does not know fails eval loudly instead of mis-scheduling. |
| 65 | backupTimer = { |
| 66 | # Late night with a spread; Persistent runs a missed window at boot. |
| 67 | nightly = { |
| 68 | OnCalendar = "03:30"; |
| 69 | RandomizedDelaySec = "30m"; |
| 70 | Persistent = true; |
| 71 | }; |
| 72 | }; |
| 73 | |
| 74 | # The secret-path options the consumer must supply once the declaration |
| 75 | # enables backup, with what each names — for the assertion message. |
| 76 | backupSecretOptions = { |
| 77 | repositoryFile = "the restic repository URL"; |
| 78 | passwordFile = "the repository encryption password"; |
| 79 | sshKeyFile = "the SSH identity for the sftp target"; |
| 80 | knownHostsFile = "the pinned host key of the sftp target"; |
| 81 | }; |
| 82 | |
| 83 | # Managed post-receive dispatcher. Each repo's post-receive is a symlink to |
| 84 | # this script, which chains every executable dropped into the repo's |
| 85 | # hooks/post-receive.d/ directory. |
| 86 | postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" '' |
| 87 | # Managed by services.valley — do not edit. |
| 88 | # Drop executable hooks into post-receive.d/ next to this symlink. |
| 89 | set -eu |
| 90 | hook_dir="$(dirname "$0")/post-receive.d" |
| 91 | [ -d "$hook_dir" ] || exit 0 |
| 92 | updates="$(cat)" |
| 93 | [ -n "$updates" ] || exit 0 |
| 94 | for hook in "$hook_dir"/*; do |
| 95 | [ -x "$hook" ] || continue |
| 96 | printf '%s\n' "$updates" | "$hook" "$@" |
| 97 | done |
| 98 | ''; |
| 99 | |
| 100 | # Best-effort push replication. The pushes run detached (setsid) so a dead |
| 101 | # mirror can only ever cost a log line — never block or fail the primary |
| 102 | # push. Explicit refspecs with --prune force-update every branch and tag |
| 103 | # and propagate their deletions — the same deletion semantics --mirror |
| 104 | # gives for heads and tags. --mirror itself is rejected: it also tries to |
| 105 | # delete remote-only namespaces, and on GitHub the read-only refs/pull/* |
| 106 | # makes that fail every push, masking real replication failures. |
| 107 | mirrorPusher = |
| 108 | name: mirrors: |
| 109 | pkgs.writeShellScript "valley-mirror-push-${name}" '' |
| 110 | for url in ${lib.escapeShellArgs mirrors}; do |
| 111 | if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then |
| 112 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true |
| 113 | else |
| 114 | ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true |
| 115 | fi |
| 116 | done |
| 117 | ''; |
| 118 | |
| 119 | mirrorHook = |
| 120 | name: mirrors: |
| 121 | pkgs.writeShellScript "valley-mirrors-${name}" '' |
| 122 | # Managed by services.valley — best-effort push mirrors for ${name}. |
| 123 | cat >/dev/null # updated refs unused: the push replicates all heads and tags |
| 124 | ${pkgs.util-linux}/bin/setsid -f ${mirrorPusher name mirrors} </dev/null >/dev/null 2>&1 |
| 125 | exit 0 |
| 126 | ''; |
| 127 | |
| 128 | # The event bus (design/roadmap.md, Phase 1): NATS JetStream, onto which |
| 129 | # the ref-updated hook below projects this host's git activity. The bus is |
| 130 | # never load-bearing for durable state — per-repo events are durable in |
| 131 | # git itself, and `valley replay` rebuilds the stream from a repo's refs — |
| 132 | # so losing its storage costs one replay, nothing more. |
| 133 | busUrl = "nats://${cfg.bus.listen}"; |
| 134 | |
| 135 | busServerConfig = pkgs.writeText "valley-bus.conf" '' |
| 136 | listen: ${cfg.bus.listen} |
| 137 | jetstream { |
| 138 | store_dir: "${cfg.bus.storeDir}" |
| 139 | # The store directory defaults to living on the repo volume; the cap |
| 140 | # keeps a runaway or malicious local publisher from filling it. |
| 141 | max_file_store: 2GiB |
| 142 | } |
| 143 | ''; |
| 144 | |
| 145 | # One ref-updated event per updated ref, read from the post-receive stdin |
| 146 | # this script inherits. Every payload field is derivable from git alone — |
| 147 | # no wall-clock time, no hostname — so replaying a repo's refs reproduces |
| 148 | # the same events (the roadmap's determinism criterion). `valley replay` |
| 149 | # builds the identical payload; change one only with the other. |
| 150 | busPublisher = pkgs.writeShellScript "valley-bus-publish" '' |
| 151 | repo="$(basename "$PWD" .git)" |
| 152 | while read -r old new ref; do |
| 153 | [ -n "$ref" ] || continue |
| 154 | # " is the only JSON-significant character a refname can contain |
| 155 | # (git forbids \ and control characters); names and ids are safe. |
| 156 | event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \ |
| 157 | "$repo" "''${ref//\"/\\\"}" "$old" "$new")" |
| 158 | if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \ |
| 159 | "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then |
| 160 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true |
| 161 | else |
| 162 | ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true |
| 163 | fi |
| 164 | done |
| 165 | ''; |
| 166 | |
| 167 | # The post-receive.d hook, with the mirror hook's failure semantics: the |
| 168 | # publisher runs detached (setsid, inheriting the updates on stdin), so a |
| 169 | # bus problem can only ever cost a log line — never block or fail the |
| 170 | # push. git is the source of truth; the bus is the replaceable component. |
| 171 | busEventHook = pkgs.writeShellScript "valley-bus-events" '' |
| 172 | # Managed by services.valley — project ref updates onto the event bus. |
| 173 | ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1 |
| 174 | exit 0 |
| 175 | ''; |
| 176 | |
| 177 | # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks: |
| 178 | # only ever installs, updates, or removes a store symlink — a hand-written |
| 179 | # hook of the same name is left alone. |
| 180 | busHookCommands = lib.concatMapStrings ( |
| 181 | name: |
| 182 | let |
| 183 | bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus"; |
| 184 | in |
| 185 | if cfg.bus.enable then |
| 186 | '' |
| 187 | bhook=${bhook} |
| 188 | if [ -L "$bhook" ]; then |
| 189 | case "$(readlink "$bhook")" in |
| 190 | /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;; |
| 191 | esac |
| 192 | elif [ ! -e "$bhook" ]; then |
| 193 | ln -s ${busEventHook} "$bhook" |
| 194 | fi |
| 195 | '' |
| 196 | else |
| 197 | '' |
| 198 | bhook=${bhook} |
| 199 | if [ -L "$bhook" ]; then |
| 200 | case "$(readlink "$bhook")" in |
| 201 | /nix/store/*) rm -f "$bhook" ;; |
| 202 | esac |
| 203 | fi |
| 204 | '' |
| 205 | ) repoNames; |
| 206 | |
| 207 | # Per-project mirror-hook wiring. Only ever installs, updates, or removes |
| 208 | # a store symlink — a hand-written hook of the same name is left alone. |
| 209 | mirrorHookCommands = lib.concatStrings ( |
| 210 | lib.mapAttrsToList ( |
| 211 | name: p: |
| 212 | let |
| 213 | mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors"; |
| 214 | in |
| 215 | if p.mirrors != [ ] then |
| 216 | '' |
| 217 | mhook=${mhook} |
| 218 | if [ -L "$mhook" ]; then |
| 219 | case "$(readlink "$mhook")" in |
| 220 | /nix/store/*) ln -sfn ${mirrorHook name p.mirrors} "$mhook" ;; |
| 221 | esac |
| 222 | elif [ ! -e "$mhook" ]; then |
| 223 | ln -s ${mirrorHook name p.mirrors} "$mhook" |
| 224 | fi |
| 225 | '' |
| 226 | else |
| 227 | '' |
| 228 | mhook=${mhook} |
| 229 | if [ -L "$mhook" ]; then |
| 230 | case "$(readlink "$mhook")" in |
| 231 | /nix/store/*) rm -f "$mhook" ;; |
| 232 | esac |
| 233 | fi |
| 234 | '' |
| 235 | ) gitProjects |
| 236 | ); |
| 237 | in |
| 238 | { |
| 239 | options.services.valley = { |
| 240 | enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration"; |
| 241 | |
| 242 | user = lib.mkOption { |
| 243 | type = lib.types.str; |
| 244 | default = "git"; |
| 245 | description = "System user that owns the repositories and accepts SSH pushes."; |
| 246 | }; |
| 247 | |
| 248 | group = lib.mkOption { |
| 249 | type = lib.types.str; |
| 250 | default = "git"; |
| 251 | description = "Primary group of the valley git user."; |
| 252 | }; |
| 253 | |
| 254 | dataDir = lib.mkOption { |
| 255 | type = lib.types.path; |
| 256 | default = "/srv/git"; |
| 257 | example = "/mnt/git"; |
| 258 | description = '' |
| 259 | Directory holding the bare repositories, one `<name>.git` per |
| 260 | project declared in {option}`services.valley.config`. Also the git |
| 261 | user's home, so clone URLs are relative to it (`git@host:name.git`). |
| 262 | Consumers typically point it at a dedicated dataset. |
| 263 | ''; |
| 264 | }; |
| 265 | |
| 266 | authorizedKeys = lib.mkOption { |
| 267 | type = lib.types.listOf lib.types.str; |
| 268 | default = [ ]; |
| 269 | description = '' |
| 270 | SSH public keys allowed to push/fetch as the git user. Access is |
| 271 | host-level by design: every key can reach every project. |
| 272 | ''; |
| 273 | }; |
| 274 | |
| 275 | config = lib.mkOption { |
| 276 | type = lib.types.path; |
| 277 | example = lib.literalExpression "./valley.cue"; |
| 278 | description = '' |
| 279 | Path to the host's CUE declaration (`package valley`) — the |
| 280 | canonical statement of what this valley host serves, validated |
| 281 | against the shipped schema at build time. This is the single domain |
| 282 | input: projects, their push mirrors, and the backup policy are |
| 283 | declared here, never as Nix options. |
| 284 | ''; |
| 285 | }; |
| 286 | |
| 287 | # The event bus. Machine options, not domain: whether this machine runs |
| 288 | # a bus, where it listens, and where its storage lives. What gets |
| 289 | # published onto it is defined portably in ../schema/events.cue. |
| 290 | bus = { |
| 291 | enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events"; |
| 292 | |
| 293 | listen = lib.mkOption { |
| 294 | type = lib.types.str; |
| 295 | default = "127.0.0.1:4222"; |
| 296 | example = "100.100.1.7:4222"; |
| 297 | description = '' |
| 298 | Address the bus listens on, `host:port`. Localhost by default: |
| 299 | nothing off the host can reach the bus until the consumer widens |
| 300 | this deliberately — e.g. to the host's tailnet address once a |
| 301 | remote `valley tail` wants in. Local publishers (the ref-updated |
| 302 | hook) connect to this same address, so it must be reachable from |
| 303 | the host itself. |
| 304 | ''; |
| 305 | }; |
| 306 | |
| 307 | storeDir = lib.mkOption { |
| 308 | type = lib.types.path; |
| 309 | default = "${cfg.dataDir}/.bus"; |
| 310 | defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"''; |
| 311 | description = '' |
| 312 | Directory holding the JetStream file storage. The default lives |
| 313 | under {option}`services.valley.dataDir`; it can never collide |
| 314 | with a repository because project names must start with an |
| 315 | alphanumeric. The stream is a projection of git, rebuildable |
| 316 | with `valley replay` — losing this directory costs one replay. |
| 317 | ''; |
| 318 | }; |
| 319 | }; |
| 320 | |
| 321 | # Machine integration for the declared backup policy. The declaration |
| 322 | # states WHAT must hold (offsite backup, cadence, retention); these |
| 323 | # options supply HOW on this machine — where the repository is and how |
| 324 | # to authenticate. All are paths to files the consumer provisions |
| 325 | # (e.g. agenix), required when the declaration enables backup. Point |
| 326 | # them at runtime paths, never at files in the Nix store. |
| 327 | backup = { |
| 328 | repositoryFile = lib.mkOption { |
| 329 | type = lib.types.nullOr lib.types.path; |
| 330 | default = null; |
| 331 | example = "/run/agenix/valley-restic-repo"; |
| 332 | description = '' |
| 333 | File containing the restic repository URL, for the sftp target |
| 334 | e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`. |
| 335 | ''; |
| 336 | }; |
| 337 | |
| 338 | passwordFile = lib.mkOption { |
| 339 | type = lib.types.nullOr lib.types.path; |
| 340 | default = null; |
| 341 | example = "/run/agenix/valley-restic-password"; |
| 342 | description = '' |
| 343 | File containing the restic repository encryption password. |
| 344 | Losing it loses the backups — keep a copy somewhere that |
| 345 | survives this host. |
| 346 | ''; |
| 347 | }; |
| 348 | |
| 349 | sshKeyFile = lib.mkOption { |
| 350 | type = lib.types.nullOr lib.types.path; |
| 351 | default = null; |
| 352 | example = "/run/agenix/valley-git-ssh-key"; |
| 353 | description = '' |
| 354 | SSH private key that authenticates to the sftp target. The |
| 355 | backup service runs as root, so any identity the target |
| 356 | authorizes works — reusing the mirror key is fine. |
| 357 | ''; |
| 358 | }; |
| 359 | |
| 360 | knownHostsFile = lib.mkOption { |
| 361 | type = lib.types.nullOr lib.types.path; |
| 362 | default = null; |
| 363 | example = "/var/lib/valley-backup/known_hosts"; |
| 364 | description = '' |
| 365 | known_hosts file pinning the sftp target's host key. Pin from |
| 366 | the provider's published fingerprints, not a blind ssh-keyscan. |
| 367 | ''; |
| 368 | }; |
| 369 | }; |
| 370 | }; |
| 371 | |
| 372 | config = lib.mkIf cfg.enable { |
| 373 | assertions = [ |
| 374 | { |
| 375 | assertion = cfg.authorizedKeys != [ ]; |
| 376 | message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable."; |
| 377 | } |
| 378 | ] |
| 379 | ++ lib.optionals backupEnabled ( |
| 380 | lib.mapAttrsToList (name: what: { |
| 381 | assertion = cfg.backup.${name} != null; |
| 382 | 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)."; |
| 383 | }) backupSecretOptions |
| 384 | ); |
| 385 | |
| 386 | users.groups.${cfg.group} = { }; |
| 387 | |
| 388 | users.users.${cfg.user} = { |
| 389 | isSystemUser = true; |
| 390 | group = cfg.group; |
| 391 | home = cfg.dataDir; |
| 392 | # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive; |
| 393 | # interactive logins are rejected (no ~/git-shell-commands). |
| 394 | shell = "${pkgs.git}/bin/git-shell"; |
| 395 | openssh.authorizedKeys.keys = cfg.authorizedKeys; |
| 396 | }; |
| 397 | |
| 398 | services.openssh.enable = lib.mkDefault true; |
| 399 | |
| 400 | # Belt-and-braces hardening for the git user. The trailing `Match All` |
| 401 | # closes the block so it can't scope directives appended to sshd_config |
| 402 | # after this snippet. |
| 403 | services.openssh.extraConfig = '' |
| 404 | Match User ${cfg.user} |
| 405 | AllowTcpForwarding no |
| 406 | AllowAgentForwarding no |
| 407 | X11Forwarding no |
| 408 | PermitTunnel no |
| 409 | Match All |
| 410 | ''; |
| 411 | |
| 412 | # git-shell spawns git-receive-pack/git-upload-pack from PATH |
| 413 | environment.systemPackages = [ pkgs.git ]; |
| 414 | |
| 415 | systemd.tmpfiles.rules = [ |
| 416 | "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -" |
| 417 | ] |
| 418 | ++ lib.optionals cfg.bus.enable [ |
| 419 | "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -" |
| 420 | ]; |
| 421 | |
| 422 | # The bus itself. It runs as the git user — the store directory lives in |
| 423 | # that user's data — but the sandbox is what confines it: the unit can |
| 424 | # write nowhere except its store directory. |
| 425 | systemd.services.valley-bus = lib.mkIf cfg.bus.enable { |
| 426 | description = "The valley event bus (NATS JetStream)"; |
| 427 | wantedBy = [ "multi-user.target" ]; |
| 428 | after = [ |
| 429 | "network.target" |
| 430 | "systemd-tmpfiles-setup.service" |
| 431 | ]; |
| 432 | unitConfig.RequiresMountsFor = cfg.bus.storeDir; |
| 433 | serviceConfig = { |
| 434 | ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}"; |
| 435 | Restart = "on-failure"; |
| 436 | User = cfg.user; |
| 437 | Group = cfg.group; |
| 438 | LimitNOFILE = 65536; |
| 439 | NoNewPrivileges = true; |
| 440 | ProtectSystem = "strict"; |
| 441 | ReadWritePaths = [ cfg.bus.storeDir ]; |
| 442 | ProtectHome = true; |
| 443 | PrivateTmp = true; |
| 444 | PrivateDevices = true; |
| 445 | ProtectClock = true; |
| 446 | ProtectHostname = true; |
| 447 | ProtectKernelLogs = true; |
| 448 | ProtectKernelModules = true; |
| 449 | ProtectKernelTunables = true; |
| 450 | ProtectControlGroups = true; |
| 451 | ProtectProc = "invisible"; |
| 452 | RestrictAddressFamilies = [ |
| 453 | "AF_INET" |
| 454 | "AF_INET6" |
| 455 | "AF_UNIX" |
| 456 | ]; |
| 457 | RestrictNamespaces = true; |
| 458 | RestrictRealtime = true; |
| 459 | RestrictSUIDSGID = true; |
| 460 | LockPersonality = true; |
| 461 | CapabilityBoundingSet = ""; |
| 462 | SystemCallArchitectures = "native"; |
| 463 | SystemCallFilter = [ "@system-service" ]; |
| 464 | UMask = "0077"; |
| 465 | }; |
| 466 | }; |
| 467 | |
| 468 | # The stream is config, not state: (re)created idempotently on every |
| 469 | # boot, capturing everything under valley.>. An existing stream — and |
| 470 | # the events in it — is left untouched. |
| 471 | systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable { |
| 472 | description = "Create the valley event stream"; |
| 473 | wantedBy = [ "multi-user.target" ]; |
| 474 | requires = [ "valley-bus.service" ]; |
| 475 | after = [ "valley-bus.service" ]; |
| 476 | serviceConfig = { |
| 477 | Type = "oneshot"; |
| 478 | User = cfg.user; |
| 479 | Group = cfg.group; |
| 480 | }; |
| 481 | path = [ pkgs.natscli ]; |
| 482 | script = '' |
| 483 | # The server needs a moment to accept connections after startup. |
| 484 | for _ in $(seq 1 50); do |
| 485 | nats --server ${busUrl} stream ls >/dev/null 2>&1 && break |
| 486 | sleep 0.2 |
| 487 | done |
| 488 | if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then |
| 489 | nats --server ${busUrl} stream add valley \ |
| 490 | --subjects 'valley.>' --storage file --defaults |
| 491 | fi |
| 492 | ''; |
| 493 | }; |
| 494 | |
| 495 | # Create missing bare repos and (re)wire the managed hooks on every |
| 496 | # activation where the declaration changed. |
| 497 | systemd.services.valley-init = { |
| 498 | description = "Initialize the valley host's bare git repositories"; |
| 499 | wantedBy = [ "multi-user.target" ]; |
| 500 | after = [ "systemd-tmpfiles-setup.service" ]; |
| 501 | unitConfig.RequiresMountsFor = cfg.dataDir; |
| 502 | serviceConfig = { |
| 503 | Type = "oneshot"; |
| 504 | User = cfg.user; |
| 505 | Group = cfg.group; |
| 506 | }; |
| 507 | path = [ pkgs.git ]; |
| 508 | script = '' |
| 509 | repos=( ${lib.escapeShellArgs repoNames} ) |
| 510 | for name in "''${repos[@]}"; do |
| 511 | repo="${cfg.dataDir}/$name.git" |
| 512 | # Check HEAD rather than the directory itself so a pre-existing |
| 513 | # empty directory still gets initialized. |
| 514 | if [ ! -e "$repo/HEAD" ]; then |
| 515 | git init --bare --initial-branch=main "$repo" |
| 516 | fi |
| 517 | |
| 518 | # Hook scaffolding: post-receive dispatches to post-receive.d/. |
| 519 | # Only manage the hook if it is absent or already ours (a store |
| 520 | # symlink) — a hand-written hook is left alone. |
| 521 | mkdir -p "$repo/hooks/post-receive.d" |
| 522 | hook="$repo/hooks/post-receive" |
| 523 | if [ -L "$hook" ]; then |
| 524 | case "$(readlink "$hook")" in |
| 525 | /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;; |
| 526 | esac |
| 527 | elif [ ! -e "$hook" ]; then |
| 528 | ln -s ${postReceiveDispatch} "$hook" |
| 529 | fi |
| 530 | done |
| 531 | |
| 532 | # Per-project push-mirror hooks. |
| 533 | ${mirrorHookCommands} |
| 534 | |
| 535 | # The ref-updated publisher hook, on every repo when the bus is on. |
| 536 | ${busHookCommands} |
| 537 | ''; |
| 538 | }; |
| 539 | |
| 540 | # Offsite backup, rendered only when the declaration asks for it. The |
| 541 | # declaration states the policy — that backup exists, its cadence and |
| 542 | # retention; the services.valley.backup.* options supply the machine |
| 543 | # half. Declaration absent or disabled ⇒ no restic config at all. |
| 544 | services.restic.backups = lib.mkIf backupEnabled { |
| 545 | valley = { |
| 546 | initialize = true; |
| 547 | repositoryFile = cfg.backup.repositoryFile; |
| 548 | passwordFile = cfg.backup.passwordFile; |
| 549 | paths = [ cfg.dataDir ]; |
| 550 | # The schema admits only the restic-sftp target today; a second |
| 551 | # target would grow a dispatch here. The service runs as root: |
| 552 | # authenticate with the supplied identity and only the pinned |
| 553 | # host key. No prompt can be answered inside a systemd unit, so |
| 554 | # BatchMode + strict host key checking turn a would-be hang into |
| 555 | # an immediate error. |
| 556 | extraOptions = [ |
| 557 | "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'" |
| 558 | ]; |
| 559 | timerConfig = backupTimer.${backupPolicy.cadence}; |
| 560 | pruneOpts = [ |
| 561 | "--keep-daily ${toString backupPolicy.retention.daily}" |
| 562 | "--keep-weekly ${toString backupPolicy.retention.weekly}" |
| 563 | "--keep-monthly ${toString backupPolicy.retention.monthly}" |
| 564 | ]; |
| 565 | }; |
| 566 | }; |
| 567 | }; |
| 568 | } |