gunk-dev/the-valley

web-receiver.nix

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