gunk-dev/the-valley

flake.nix

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