gunk-dev/the-valley

web-publisher.nix

sourceaabc2b3ae680main's published tip history
12.3 KiB
1# The web publisher (web/cmd/valley-web-publish): a oneshot on a timer
2# that reads this host's public projects and pushes signed exports to a web
3# receiver, which never connects back.
4#
5# A module of its own beside the host module (valley-host.nix), which it
6# needs: it reads that module's options for the repositories the host
7# serves, their group, and the instance repository. Which projects exist,
8# and the signers that verify their landings, it reads at run time from
9# what the instance repository publishes, through the valley CLI.
10#
11# The service runs as a dynamic user in the git group, so it can read the
12# repositories and own nothing on disk but its state and cache. It cannot
13# write the repositories, and the files that hold the host's mirror,
14# backup and signing keys are made inaccessible to it. The receiver's
15# token is a file outside the Nix store, which systemd reads and hands to
16# the unit as a credential.
17{
18 config,
19 pkgs,
20 lib,
21 ...
22}:
23
24let
25 cfg = config.services.valley.webPublisher;
26 host = config.services.valley;
27
28 # The repositories this host serves, read from its declaration the way
29 # the host module reads them. The derivation is the host module's own,
30 # with the same name, schema and declaration, so it is built once.
31 schema = ../schema/valley.cue;
32 configJSON =
33 pkgs.runCommand "valley-config.json"
34 {
35 nativeBuildInputs = [ pkgs.cue ];
36 }
37 ''
38 cue vet -c ${schema} ${host.config}
39 cue export ${schema} ${host.config} > $out
40 '';
41 declared = lib.importJSON configJSON;
42 repositories = map (name: "${toString host.dataDir}/${name}.git") (
43 lib.attrNames (lib.filterAttrs (_: p: p.git.enable) declared.projects)
44 );
45
46 instanceRepo = "${toString host.dataDir}/${toString host.integrator.instanceProject}.git";
47
48 # The repositories belong to the git user and the service does not, so
49 # git refuses them as dubiously owned. The unit's environment carries
50 # safe.directory entries, which every git the publisher and the valley
51 # CLI run inherits. GIT_CONFIG_* is command scope, which git reads
52 # safe.directory from, after the system and global configuration. The
53 # entries add to what those set, so the first is empty, which resets the
54 # list (git-config(1)), and one exact entry per repository follows. A
55 # system configuration that trusts every directory trusts none of them
56 # here. Never a wildcard.
57 safeDirectories = {
58 GIT_CONFIG_COUNT = toString (lib.length repositories + 1);
59 }
60 // lib.listToAttrs (
61 lib.concatLists (
62 lib.imap0 (i: repo: [
63 (lib.nameValuePair "GIT_CONFIG_KEY_${toString i}" "safe.directory")
64 (lib.nameValuePair "GIT_CONFIG_VALUE_${toString i}" repo)
65 ]) ([ "" ] ++ repositories)
66 )
67 );
68
69 # What the service must never read: the git user's ssh identity, which
70 # pushes the mirrors, and the key files the host module is given. A path
71 # that does not exist is skipped (the leading -).
72 keys = [
73 "${toString host.dataDir}/.ssh"
74 "/var/lib/valley-integrator"
75 ]
76 ++ lib.optional (host.integrator.signingKeyFile != null) (toString host.integrator.signingKeyFile)
77 ++ lib.optional host.worker.enable (toString host.worker.stateDir)
78 ++ map toString (
79 lib.filter (p: p != null) [
80 host.backup.sshKeyFile
81 host.backup.passwordFile
82 host.backup.repositoryFile
83 ]
84 );
85
86 stateName = lib.removePrefix "/var/lib/" (toString cfg.stateDir);
87 cacheDir = "/var/cache/${stateName}";
88
89 principalsFile = pkgs.writeText "valley-web-principals.json" (builtins.toJSON cfg.principals);
90
91 command = lib.concatStringsSep " " [
92 (lib.getExe cfg.package)
93 "--instance-repo ${lib.escapeShellArg instanceRepo}"
94 "--instance ${lib.escapeShellArg config.networking.hostName}"
95 "--destination ${lib.escapeShellArg cfg.destination}"
96 "--receiver ${lib.escapeShellArg cfg.receiver}"
97 # %d is the unit's credentials directory.
98 "--receiver-token %d/receiver-token"
99 "--principals ${principalsFile}"
100 "--state ${lib.escapeShellArg (toString cfg.stateDir)}"
101 "--max-bundles ${cfg.maxBundles}"
102 "--max-storage ${cfg.maxStorage}"
103 "--registry-ref ${lib.escapeShellArg host.identity.ref}"
104 "--registry-dir ${lib.escapeShellArg host.identity.directory}"
105 ];
106
107 size = lib.types.strMatching "[1-9][0-9]*[KMGT]?";
108in
109{
110 options.services.valley.webPublisher = {
111 enable = lib.mkEnableOption ''
112 the valley web publisher: a timer that uploads this host's public
113 projects, as signed exports, to a web receiver. A project is public
114 when its own policy/read lets anyone read it, and a read grant to
115 anyone in the identity registry covers it at the destination. The
116 registry is read where the identity compiler reads it: in
117 {option}`services.valley.identity.directory` at the instance
118 repository's {option}`services.valley.identity.ref`. The host module
119 requires that ref to be protected. The manifest names
120 {option}`networking.hostName` as the instance, and is signed under
121 `<hostName>/web-export`
122 '';
123
124 destination = lib.mkOption {
125 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}";
126 example = "example.org";
127 description = ''
128 The receiver's name, which every manifest is signed for. The
129 receiver admits only manifests that name it. It is also the
130 destination of the registry's edge read boundary whose read grants
131 decide what anyone may read there.
132 '';
133 };
134
135 receiver = lib.mkOption {
136 type = lib.types.strMatching "https?://[^/?#@]+(/[^?#]*)?";
137 example = "https://example.org";
138 description = ''
139 The receiver's base URL. The upload's paths are appended to it.
140 '';
141 };
142
143 receiverTokenFile = lib.mkOption {
144 type = lib.types.strMatching "/.+";
145 example = "/run/keys/valley-web-receiver-token";
146 description = ''
147 The file that holds the receiver's token, which every request of
148 an upload carries: one line of 32 to 256 visible ASCII characters,
149 the token the receiver is given. The path is outside the Nix
150 store, and systemd reads the file as the unit's credential, so it
151 may be readable by root alone.
152 '';
153 };
154
155 principals = lib.mkOption {
156 type = lib.types.attrsOf lib.types.str;
157 default = { };
158 example = {
159 operator = "operator";
160 alice = "agent";
161 };
162 description = ''
163 The display mapping: what an export shows in place of each
164 principal's name. A principal it does not name is shown as
165 `contributor`.
166 '';
167 };
168
169 stateDir = lib.mkOption {
170 type = lib.types.strMatching "/var/lib/[^/].*";
171 default = "/var/lib/valley-web-publish";
172 description = ''
173 The publisher's state, under /var/lib: its export key, made on the
174 first start, the key's verifier line, which the receiver pins, and
175 the last acknowledgement. The cache is the directory of the same
176 name under /var/cache.
177 '';
178 };
179
180 memoryMax = lib.mkOption {
181 type = size;
182 default = "1G";
183 description = ''
184 The most memory a pass may use, the publisher and every git, cue
185 and valley it runs together (`MemoryMax`, with no swap). Past it,
186 the kernel ends the pass.
187 '';
188 };
189
190 maxBundles = lib.mkOption {
191 type = size;
192 default = "1G";
193 description = ''
194 The most the bundles of one export may hold together. Each bundle
195 carries a public project's whole history on main. A bundle is
196 written only into what this leaves, and a pass past it sends
197 nothing (`--max-bundles`).
198 '';
199 };
200
201 maxStorage = lib.mkOption {
202 type = size;
203 default = "16G";
204 description = ''
205 The most the state and cache directories may hold. The cache holds
206 a clone and a mirror of each project a read grant to anyone names,
207 and a bundle of each public one. A pass checks it before it fetches and once it
208 has read the valley, and writes a bundle only into what it leaves.
209 A pass past it sends nothing (`--max-storage`).
210 '';
211 };
212
213 # The publisher as this flake packages it. Internal, like the host
214 # module's packages: module-eval sets it to a stand-in.
215 package = lib.mkOption {
216 type = lib.types.package;
217 internal = true;
218 default = (import ./packages.nix { inherit pkgs lib; }).valley-web-publish;
219 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-web-publish";
220 description = "The web publisher.";
221 };
222 };
223
224 config = lib.mkIf cfg.enable {
225 assertions = [
226 {
227 assertion = host.enable;
228 message = "services.valley.webPublisher needs services.valley: it reads the repositories that host serves.";
229 }
230 {
231 assertion = !(lib.hasPrefix builtins.storeDir cfg.receiverTokenFile);
232 message = "services.valley.webPublisher.receiverTokenFile is in the Nix store, which every user can read; give a path outside it.";
233 }
234 {
235 assertion = host.integrator.instanceProject != null;
236 message = "services.valley.webPublisher needs services.valley.integrator.instanceProject: the publisher discovers the projects, and the signers that verify their landings, through what the instance repository publishes.";
237 }
238 ];
239
240 # One pass, as a oneshot the timer below starts. A switch never starts
241 # it: nothing wants the service, and a changed unit is not restarted.
242 # The publisher's own lock serializes a pass started by hand with the
243 # timer's.
244 systemd.services.valley-web-publish = {
245 description = "One pass of the valley web publisher";
246 after = [
247 "network-online.target"
248 "valley-init.service"
249 ];
250 wants = [ "network-online.target" ];
251 restartIfChanged = false;
252 unitConfig.RequiresMountsFor = toString host.dataDir;
253 environment = safeDirectories // {
254 HOME = toString cfg.stateDir;
255 XDG_CACHE_HOME = cacheDir;
256 };
257 serviceConfig = {
258 Type = "oneshot";
259 ExecStart = command;
260 # A pass that hangs is ended, and the timer starts the next. One
261 # that outgrows its memory is ended too.
262 TimeoutStartSec = "1h";
263 MemoryMax = cfg.memoryMax;
264 MemorySwapMax = "0";
265 DynamicUser = true;
266 SupplementaryGroups = [ host.group ];
267 StateDirectory = stateName;
268 StateDirectoryMode = "0700";
269 CacheDirectory = stateName;
270 CacheDirectoryMode = "0700";
271 WorkingDirectory = toString cfg.stateDir;
272 LoadCredential = [ "receiver-token:${cfg.receiverTokenFile}" ];
273 # ProtectSystem=strict leaves the whole filesystem read-only but
274 # the state and cache directories, which systemd exempts. So the
275 # repositories, readable through the git group, are read-only,
276 # and named here so a reader of the unit sees it. A repository
277 # valley-init has not made yet is skipped (the leading -).
278 ProtectSystem = "strict";
279 ReadOnlyPaths = map (p: "-${p}") repositories;
280 InaccessiblePaths = map (p: "-${p}") keys;
281 ProtectHome = true;
282 PrivateTmp = true;
283 PrivateDevices = true;
284 NoNewPrivileges = true;
285 ProtectClock = true;
286 ProtectHostname = true;
287 ProtectKernelLogs = true;
288 ProtectKernelModules = true;
289 ProtectKernelTunables = true;
290 ProtectControlGroups = true;
291 ProtectProc = "invisible";
292 RestrictAddressFamilies = [
293 "AF_INET"
294 "AF_INET6"
295 "AF_UNIX"
296 ];
297 RestrictNamespaces = true;
298 RestrictRealtime = true;
299 RestrictSUIDSGID = true;
300 LockPersonality = true;
301 CapabilityBoundingSet = "";
302 SystemCallArchitectures = "native";
303 SystemCallFilter = [ "@system-service" ];
304 UMask = "0077";
305 };
306 };
307
308 # The first pass starts five minutes after the timer starts, and each
309 # later pass five minutes after the last one ended. These are delays
310 # and nothing more: a switch that runs longer than five minutes can
311 # see the first pass start inside it, and any later switch can see a
312 # pass start inside it.
313 systemd.timers.valley-web-publish = {
314 description = "Run the valley web publisher";
315 wantedBy = [ "timers.target" ];
316 timerConfig = {
317 OnActiveSec = "5min";
318 OnUnitInactiveSec = "5min";
319 };
320 };
321 };
322}