gunk-dev/the-valley

web-receiver.nix

source89496f97a023main's published tip history
12.6 KiB
1# The web export receiver (web/cmd/valley-web-receive) and valley-web
2# (web/cmd/valley-web) on a NixOS edge host: two long-running units
3# over one store in one state directory.
4#
5# The receiver takes the publisher's authorizations and uploads, and is
6# the store's one writer. valley-web serves the activated export to its
7# readers, as the stored authorization allows, and only reads the store.
8# With an origin set, valley-web also signs readers in with the host's
9# read links, and writes their sessions to <stateDir>/browser, its own
10# directory, mode 0700, and the one place it writes. tmpfiles makes that
11# directory, and the state directory above it as the receiver's, so the
12# receiver's StateDirectory finds its owner as it expects and changes no
13# owner beneath it. The receiver's unit cannot reach browser/. Both are given the store's descriptor, <stateDir>/store; its
14# payloads are in <stateDir>/v2 (web/export/store.go). Each runs as a user of its own, both in
15# the valley-web group. The directory is the receiver's, mode 0750, so
16# valley-web reads it through the group, and the receiver keeps its
17# staging area to itself (web/export/store.go). Each unit has its own
18# listener and its own memory cap, so an upload that saturates the
19# receiver leaves valley-web serving, and neither unit needs the other to
20# run: valley-web keeps serving while the receiver restarts.
21#
22# The receiver's token is a file outside the Nix store. systemd reads it
23# and hands it to the receiver's unit alone as a credential, so
24# valley-web's user never reads it. The verifier lines are public, and go
25# in the store.
26{
27 config,
28 pkgs,
29 lib,
30 ...
31}:
32
33let
34 cfg = config.services.valley.webReceiver;
35 stateDir = toString cfg.stateDir;
36 stateName = lib.removePrefix "/var/lib/" stateDir;
37 # The store's descriptor, which the receiver creates on its first start.
38 # Binaries of the first store layout took the directory itself, and
39 # refuse a file.
40 storeFile = "${stateDir}/store";
41
42 verifiersFile = pkgs.writeText "valley-web-verifiers" (
43 lib.concatMapStrings (line: line + "\n") cfg.verifiers
44 );
45
46 receiveCommand = lib.concatStringsSep " " [
47 (lib.getExe cfg.receiverPackage)
48 "--state ${lib.escapeShellArg storeFile}"
49 "--listen ${lib.escapeShellArg cfg.listen}"
50 "--instance ${lib.escapeShellArg cfg.instance}"
51 "--destination ${lib.escapeShellArg cfg.destination}"
52 "--verifiers ${verifiersFile}"
53 # %d is the unit's credentials directory.
54 "--token-file %d/token"
55 "--max-body ${cfg.maxBody}"
56 "--max-upload ${cfg.maxUpload}"
57 "--max-storage ${cfg.maxStorage}"
58 ];
59
60 webCommand = lib.concatStringsSep " " (
61 [
62 (lib.getExe cfg.webPackage)
63 "--state ${lib.escapeShellArg storeFile}"
64 "--listen ${lib.escapeShellArg cfg.webListen}"
65 ]
66 ++ lib.optional readers "--origin ${lib.escapeShellArg cfg.origin}"
67 );
68
69 # Whether valley-web signs readers in, and the directory it keeps their
70 # sessions in.
71 readers = cfg.origin != null;
72 browserDir = "${stateDir}/browser";
73
74 # What both units are held to. ProtectSystem=strict leaves the whole
75 # filesystem read-only but the receiver's state directory, which systemd
76 # exempts for the unit that names it, and the temporary paths below.
77 # PrivateTmp gives each unit a /tmp and a /var/tmp of its own, writable,
78 # which no other unit sees and systemd removes when the unit stops.
79 # PrivateDevices gives each unit a /dev of its own, read-only, but binds
80 # the host's /dev/shm into it, which stays writable.
81 confinement = {
82 ProtectSystem = "strict";
83 ProtectHome = true;
84 PrivateTmp = true;
85 PrivateDevices = true;
86 NoNewPrivileges = true;
87 ProtectClock = true;
88 ProtectHostname = true;
89 ProtectKernelLogs = true;
90 ProtectKernelModules = true;
91 ProtectKernelTunables = true;
92 ProtectControlGroups = true;
93 ProtectProc = "invisible";
94 RestrictAddressFamilies = [
95 "AF_INET"
96 "AF_INET6"
97 "AF_UNIX"
98 ];
99 RestrictNamespaces = true;
100 RestrictRealtime = true;
101 RestrictSUIDSGID = true;
102 LockPersonality = true;
103 CapabilityBoundingSet = "";
104 SystemCallArchitectures = "native";
105 SystemCallFilter = [ "@system-service" ];
106 UMask = "0077";
107 MemorySwapMax = "0";
108 Restart = "on-failure";
109 RestartSec = "5s";
110 };
111
112 name = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}";
113 size = lib.types.strMatching "[1-9][0-9]*[KMGT]?";
114in
115{
116 options.services.valley.webReceiver = {
117 enable = lib.mkEnableOption ''
118 the valley web export receiver and valley-web on this host: the
119 receiver takes a valley host's signed uploads into
120 {option}`services.valley.webReceiver.stateDir`, and valley-web
121 serves what it activates to anonymous readers
122 '';
123
124 instance = lib.mkOption {
125 type = name;
126 example = "valley-host";
127 description = ''
128 The instance every manifest must name: the publishing valley
129 host's {option}`networking.hostName`, which its publisher names.
130 '';
131 };
132
133 destination = lib.mkOption {
134 type = name;
135 example = "example.org";
136 description = ''
137 This receiver's name, which every manifest must name: the
138 publisher's {option}`services.valley.webPublisher.destination`.
139 '';
140 };
141
142 verifiers = lib.mkOption {
143 type = lib.types.listOf lib.types.str;
144 example = [ "valley-host/web-export+1a2b3c4d+AQ..." ];
145 description = ''
146 The publisher's verifier lines. A manifest must open under one of
147 them. The publisher writes its own to `verifier` in its state
148 directory, and prints it whenever it changes.
149 '';
150 };
151
152 tokenFile = lib.mkOption {
153 type = lib.types.strMatching "/.+";
154 example = "/run/keys/valley-web-receiver-token";
155 description = ''
156 The file that holds the token every request to the receiver must
157 carry: one line of 32 to 256 visible ASCII characters. The
158 publisher is given the same token. The path is outside the Nix
159 store, and systemd reads the file as the receiver's credential, so
160 it may be readable by root alone.
161 '';
162 };
163
164 listen = lib.mkOption {
165 type = lib.types.str;
166 example = "192.0.2.10:8081";
167 description = ''
168 The TCP address the receiver listens on, which the publisher
169 reaches. Every request to it must carry the token.
170 '';
171 };
172
173 origin = lib.mkOption {
174 type = lib.types.nullOr (lib.types.strMatching "https://[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]+)?");
175 default = null;
176 example = "https://example.org";
177 description = ''
178 The public HTTPS origin readers reach valley-web at, as a browser
179 sends it in an Origin header: a scheme and a host, with a port only
180 when it is not 443 (`--origin`). With it, readers sign in with the
181 valley host's read links, and valley-web keeps their sessions in
182 `browser/` in {option}`services.valley.webReceiver.stateDir`,
183 which the module makes as valley-web's alone, mode 0700. With
184 none, every request is read as anyone.
185 '';
186 };
187
188 webListen = lib.mkOption {
189 type = lib.types.str;
190 example = "127.0.0.1:8080";
191 description = ''
192 The TCP address valley-web listens on, which readers reach, or a
193 reverse proxy in front of it.
194 '';
195 };
196
197 stateDir = lib.mkOption {
198 type = lib.types.strMatching "/var/lib/[^/].*";
199 default = "/var/lib/valley-web";
200 description = ''
201 The state directory, under /var/lib: the receiver's, mode 0750,
202 and readable by valley-web through the valley-web group. It holds
203 the store's descriptor, `store`, and its payloads, `v2/`. On its
204 first start the receiver makes a new store there, and the
205 publisher's next pass sends everything again. The receiver writes
206 nothing else there: state of the first store layout is left for
207 the operator to delete by hand.
208 '';
209 };
210
211 maxBody = lib.mkOption {
212 type = size;
213 default = "1G";
214 description = ''
215 The most bytes one body of an upload may declare: export.json, or
216 one project's bundle (`--max-body`).
217 '';
218 };
219
220 maxUpload = lib.mkOption {
221 type = size;
222 default = "2G";
223 description = ''
224 The most bytes the bodies of one manifest may declare together
225 (`--max-upload`).
226 '';
227 };
228
229 maxStorage = lib.mkOption {
230 type = size;
231 default = "8G";
232 description = ''
233 The most bytes the state directory may take on disk: every
234 generation it holds, the staged upload's bodies, and a repository
235 for each project of the upload (`--max-storage`).
236 '';
237 };
238
239 receiverMemoryMax = lib.mkOption {
240 type = size;
241 default = "2G";
242 description = ''
243 The most memory the receiver may use, with every git it runs to
244 accept a bundle (`MemoryMax`, with no swap).
245 '';
246 };
247
248 webMemoryMax = lib.mkOption {
249 type = size;
250 default = "1G";
251 description = ''
252 The most memory valley-web may use, with every git it runs to
253 browse a repository (`MemoryMax`, with no swap).
254 '';
255 };
256
257 # The programs as this flake packages them. Internal, like the host
258 # module's packages: module-eval sets them to stand-ins.
259 receiverPackage = lib.mkOption {
260 type = lib.types.package;
261 internal = true;
262 default = (import ./packages.nix { inherit pkgs lib; }).valley-web-receive;
263 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-web-receive";
264 description = "The web export receiver.";
265 };
266 webPackage = lib.mkOption {
267 type = lib.types.package;
268 internal = true;
269 default = (import ./packages.nix { inherit pkgs lib; }).valley-web;
270 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-web";
271 description = "The web server.";
272 };
273 };
274
275 config = lib.mkIf cfg.enable {
276 assertions = [
277 {
278 assertion = cfg.verifiers != [ ];
279 message = "services.valley.webReceiver.verifiers names no verifier line, and the receiver admits no manifest without one.";
280 }
281 {
282 assertion = !(lib.hasPrefix builtins.storeDir cfg.tokenFile);
283 message = "services.valley.webReceiver.tokenFile is in the Nix store, which every user can read; give a path outside it.";
284 }
285 ];
286
287 # The state directory as the receiver's unit makes it, and browser/
288 # in it as valley-web's, before either unit starts.
289 systemd.tmpfiles.rules = lib.mkIf readers [
290 "d ${stateDir} 0750 valley-web-receive valley-web -"
291 "d ${browserDir} 0700 valley-web valley-web -"
292 ];
293
294 users.groups.valley-web = { };
295 users.users.valley-web-receive = {
296 isSystemUser = true;
297 group = "valley-web";
298 description = "valley web export receiver";
299 };
300 users.users.valley-web = {
301 isSystemUser = true;
302 group = "valley-web";
303 description = "valley-web";
304 };
305
306 systemd.services.valley-web-receive = {
307 description = "The valley web export receiver";
308 wantedBy = [ "multi-user.target" ];
309 after = [ "network.target" ];
310 serviceConfig = confinement // {
311 ExecStart = receiveCommand;
312 User = "valley-web-receive";
313 Group = "valley-web";
314 StateDirectory = stateName;
315 StateDirectoryMode = "0750";
316 WorkingDirectory = stateDir;
317 LoadCredential = [ "token:${cfg.tokenFile}" ];
318 MemoryMax = cfg.receiverMemoryMax;
319 }
320 // lib.optionalAttrs readers { InaccessiblePaths = [ "-${browserDir}" ]; };
321 };
322
323 # valley-web starts after the receiver, which makes the store, and
324 # needs nothing else of it. The state directory is read-only to it, as
325 # is everything else but browser/, which it writes when it signs
326 # readers in. A state directory not made yet is skipped (the leading
327 # -), and valley-web fails and is restarted until it is there. When it
328 # signs readers in it holds their links and session tokens in memory,
329 # so it makes itself non-dumpable, and its unit takes no core dump.
330 systemd.services.valley-web = {
331 description = "valley-web, serving the web export receiver's state directory";
332 wantedBy = [ "multi-user.target" ];
333 after = [
334 "network.target"
335 "valley-web-receive.service"
336 ];
337 serviceConfig = confinement // {
338 ExecStart = webCommand;
339 User = "valley-web";
340 Group = "valley-web";
341 ReadOnlyPaths = [ "-${stateDir}" ];
342 MemoryMax = cfg.webMemoryMax;
343 }
344 // lib.optionalAttrs readers {
345 ReadWritePaths = [ browserDir ];
346 LimitCORE = 0;
347 };
348 };
349 };
350}