gunk-dev/the-valley

web-publisher.nix

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