gunk-dev/the-valley

flake.nix

source55e61458f90amain's published tip history
12.3 KiB
1{
2 description = "the-valley: the CUE domain schema for a valley host, and the NixOS module that installs one";
3
4 inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
5
6 outputs =
7 { self, nixpkgs }:
8 let
9 lib = nixpkgs.lib;
10 # Checks use import-from-derivation (the module's cue export), so they
11 # are only defined for the system that can actually build them here.
12 systems = [ "x86_64-linux" ];
13
14 # The integrator's CLI (bin/valley) wrapped for `nix run`. The script
15 # itself must keep running bare from any checkout — the package is the
16 # second of its two shipping modes, never a dependency of the first.
17 valleyScriptFor =
18 pkgs:
19 pkgs.writeShellApplication {
20 name = "valley";
21 runtimeInputs = [ pkgs.git ];
22 text = builtins.readFile ./bin/valley;
23 };
24
25 # The installed package: the wrapped script plus the shell completions,
26 # at the standard paths home-manager/NixOS auto-link.
27 valleyCliFor =
28 pkgs:
29 pkgs.symlinkJoin {
30 name = "valley";
31 paths = [ (valleyScriptFor pkgs) ];
32 nativeBuildInputs = [ pkgs.installShellFiles ];
33 postBuild = ''
34 installShellCompletion --bash --name valley ${./completions/valley.bash}
35 installShellCompletion --zsh --name _valley ${./completions/_valley}
36 '';
37 };
38 in
39 {
40 nixosModules.valley-host = ./nix/valley-host.nix;
41 nixosModules.default = self.nixosModules.valley-host;
42
43 packages = lib.genAttrs systems (
44 system:
45 let
46 valley = valleyCliFor nixpkgs.legacyPackages.${system};
47 in
48 {
49 inherit valley;
50 default = valley;
51 }
52 );
53
54 checks = lib.genAttrs systems (
55 system:
56 let
57 pkgs = nixpkgs.legacyPackages.${system};
58
59 # Eval-only instantiation of the module — catches option-surface
60 # and cue-export regressions without building or booting anything.
61 # Each check host shares the machine baseline and supplies its own
62 # declaration (and, where the declaration asks for backup, the
63 # secret paths).
64 mkHost =
65 module:
66 lib.nixosSystem {
67 inherit system;
68 modules = [
69 self.nixosModules.default
70 {
71 fileSystems."/" = {
72 device = "/dev/disk/by-label/nixos";
73 fsType = "ext4";
74 };
75 boot.loader.grub.enable = false;
76 system.stateVersion = "25.11";
77 services.valley = {
78 enable = true;
79 authorizedKeys = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPlaceholderKeyForEvalOnlyCheck0 valley-check" ];
80 };
81 }
82 module
83 ];
84 };
85
86 # The example declaration enables backup, so this host supplies
87 # the four secret paths (eval-only placeholders).
88 host = mkHost {
89 services.valley = {
90 config = ./examples/host.cue;
91 backup = {
92 repositoryFile = "/run/agenix/valley-restic-repo";
93 passwordFile = "/run/agenix/valley-restic-password";
94 sshKeyFile = "/run/agenix/valley-git-ssh-key";
95 knownHostsFile = "/var/lib/valley-backup/known_hosts";
96 };
97 };
98 };
99
100 # A declaration without a backup block predates the field and must
101 # keep evaluating exactly as before: zero restic machinery.
102 noBackupHost = mkHost {
103 services.valley.config = pkgs.writeText "no-backup-host.cue" ''
104 package valley
105 projects: "the-valley": {}
106 '';
107 };
108
109 # The example declaration with the secret paths left unset: the
110 # module must refuse with assertions naming the missing options.
111 noSecretsHost = mkHost {
112 services.valley.config = ./examples/host.cue;
113 };
114
115 failedAssertions = builtins.filter (a: !a.assertion) (
116 host.config.assertions ++ noBackupHost.config.assertions
117 );
118
119 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
120
121 resticRenderedWithoutDeclaration =
122 noBackupHost.config.systemd.services ? "restic-backups-valley"
123 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
124 in
125 {
126 # The CLI must stay a lint-clean script whose help verb answers
127 # without a repo or a remote — the cheap end of its eviction clause
128 # (dcr-74c3158); anything needing more graduates instead. The
129 # completions are held to the same bar, and the installed package
130 # must carry them at the auto-linked paths.
131 valley-cli =
132 let
133 valley = valleyCliFor pkgs;
134 in
135 pkgs.runCommand "valley-cli"
136 {
137 nativeBuildInputs = [
138 pkgs.shellcheck
139 pkgs.zsh
140 valley
141 ];
142 }
143 ''
144 shellcheck ${./bin/valley}
145 shellcheck ${./completions/valley.bash}
146 # shellcheck cannot lint zsh; a bare parse is the cheap check.
147 zsh -n ${./completions/_valley}
148 valley help > help.txt
149 grep -q '^usage: valley' help.txt
150 test -f ${valley}/share/bash-completion/completions/valley
151 test -f ${valley}/share/zsh/site-functions/_valley
152 touch $out
153 '';
154
155 # The example host declaration must vet against the schema, and the
156 # schema must reject what it claims to reject: unsafe project names,
157 # unknown project fields, stray top-level fields (typos, deployment
158 # concerns), and malformed backup policy (machine concerns, targets
159 # without an implementation, non-positive retention). CUE closedness
160 # is easy to regress silently — e.g. embedding #Host instead of
161 # referencing it opens the schema — so the rejections are pinned
162 # here.
163 cue-vet =
164 let
165 invalidConfigs = {
166 unsafe-project-name = ''
167 package valley
168 projects: ".hidden": {}
169 '';
170 unknown-project-field = ''
171 package valley
172 projects: ok: dataDir: "/srv/git"
173 '';
174 top-level-typo = ''
175 package valley
176 project: oops: {}
177 '';
178 deployment-concern-in-cue = ''
179 package valley
180 user: "git"
181 projects: ok: {}
182 '';
183 machine-concern-in-backup = ''
184 package valley
185 projects: ok: {}
186 backup: repositoryFile: "/run/agenix/valley-restic-repo"
187 '';
188 unimplemented-backup-target = ''
189 package valley
190 projects: ok: {}
191 backup: target: "restic-s3"
192 '';
193 negative-retention = ''
194 package valley
195 projects: ok: {}
196 backup: retention: daily: -1
197 '';
198 };
199 in
200 pkgs.runCommand "valley-cue-vet"
201 {
202 nativeBuildInputs = [ pkgs.cue ];
203 }
204 ''
205 cue vet -c ${./schema/valley.cue} ${./examples/host.cue}
206 cue export ${./schema/valley.cue} ${./examples/host.cue} > example.json
207 grep -q 'gunk-dev/the-valley' example.json
208 grep -q 'restic-sftp' example.json
209
210 # A declaration without a backup block must stay valid —
211 # consumers written before the field existed keep vetting.
212 cue vet -c ${./schema/valley.cue} ${pkgs.writeText "no-backup.cue" ''
213 package valley
214 projects: "the-valley": {}
215 ''}
216
217 ${lib.concatStrings (
218 lib.mapAttrsToList (name: cfg: ''
219 if cue vet -c ${./schema/valley.cue} ${pkgs.writeText "${name}.cue" cfg}; then
220 echo "cue-vet: expected invalid config '${name}' to be rejected" >&2
221 exit 1
222 fi
223 '') invalidConfigs
224 )}
225 touch $out
226 '';
227
228 module-eval =
229 if failedAssertions != [ ] then
230 throw "valley module-eval: failed assertions: ${lib.concatMapStringsSep "; " (a: a.message) failedAssertions}"
231 else if resticRenderedWithoutDeclaration then
232 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
233 else if
234 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
235 then
236 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
237 else
238 pkgs.runCommand "valley-module-eval"
239 {
240 initScript = host.config.systemd.services.valley-init.script;
241 sshdConfig = host.config.services.openssh.extraConfig;
242 resticService = host.config.systemd.units."restic-backups-valley.service".text;
243 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
244 passAsFile = [
245 "initScript"
246 "sshdConfig"
247 "resticService"
248 "resticTimer"
249 ];
250 }
251 ''
252 # The repo init list and mirror hook must be generated from
253 # the CUE export, and the git user's sshd Match block must
254 # be terminated so it cannot scope later config.
255 grep -q "the-valley" "$initScriptPath"
256 grep -q "valley-mirrors" "$initScriptPath"
257 grep -q "Match All" "$sshdConfigPath"
258
259 # The mirror push must use explicit head/tag refspecs with
260 # --prune, never --mirror: --mirror also deletes remote-only
261 # refs, and GitHub's read-only refs/pull/* fails every such
262 # push. Follow the hook chain from the init script to the
263 # rendered push script and pin the invocation there.
264 mirrorHook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-[^ ]*' "$initScriptPath" | head -n1)"
265 mirrorPush="$(grep -o '/nix/store/[^ ]*-valley-mirror-push-[^ ]*' "$mirrorHook" | head -n1)"
266 grep -q -- 'push --prune' "$mirrorPush"
267 grep -qF -- '+refs/heads/*:refs/heads/*' "$mirrorPush"
268 grep -qF -- '+refs/tags/*:refs/tags/*' "$mirrorPush"
269 if grep -q -- '--mirror' "$mirrorPush"; then
270 echo "module-eval: mirror push regressed to --mirror" >&2
271 exit 1
272 fi
273
274 # The rendered restic units must back up the data directory
275 # to the consumer-supplied repository with the declared
276 # retention over a pinned host key, on the declared cadence.
277 grep -q "RESTIC_REPOSITORY_FILE=/run/agenix/valley-restic-repo" "$resticServicePath"
278 grep -q -- "--keep-daily 7 --keep-weekly 4 --keep-monthly 6" "$resticServicePath"
279 grep -q "UserKnownHostsFile=/var/lib/valley-backup/known_hosts" "$resticServicePath"
280 grep -q "BatchMode=yes" "$resticServicePath"
281 grep -q "OnCalendar=03:30" "$resticTimerPath"
282
283 # The backup paths render as a --files-from list: follow
284 # ExecStartPre to that list and pin the data directory.
285 preStart="$(sed -n 's/^ExecStartPre=//p' "$resticServicePath" | head -n1)"
286 staticPaths="$(grep -o '/nix/store/[^ ]*-staticPaths' "$preStart" | head -n1)"
287 grep -qx "/srv/git" "$staticPaths"
288 touch $out
289 '';
290 }
291 );
292 };
293}