gunk-dev/the-valley

webui-publisher.nix

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