gunk-dev/the-valley

webui-publisher.nix

sourced93cce9938afmain's published tip history
10.7 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 ];
100
101 size = lib.types.strMatching "[1-9][0-9]*[KMGT]?";
102in
103{
104 options.services.valley.webPublisher = {
105 enable = lib.mkEnableOption ''
106 the valley web publisher: a timer that uploads this host's public
107 projects, as signed exports, to a web receiver. The manifest names
108 {option}`networking.hostName` as the instance, and is signed under
109 `<hostName>/web-export`
110 '';
111
112 destination = lib.mkOption {
113 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}";
114 example = "example.org";
115 description = ''
116 The receiver's name, which every manifest is signed for. The
117 receiver admits only manifests that name it.
118 '';
119 };
120
121 receiver = lib.mkOption {
122 type = lib.types.strMatching "https?://[^/?#@]+(/[^?#]*)?";
123 example = "https://example.org";
124 description = ''
125 The receiver's base URL. The upload's paths are appended to it.
126 '';
127 };
128
129 principals = lib.mkOption {
130 type = lib.types.attrsOf lib.types.str;
131 default = { };
132 example = {
133 operator = "operator";
134 alice = "agent";
135 };
136 description = ''
137 The display mapping: what an export shows in place of each
138 principal's name. A principal it does not name is shown as
139 `contributor`.
140 '';
141 };
142
143 stateDir = lib.mkOption {
144 type = lib.types.strMatching "/var/lib/[^/].*";
145 default = "/var/lib/valley-web-publish";
146 description = ''
147 The publisher's state, under /var/lib: its export key, made on the
148 first start, the key's verifier line, which the receiver pins, and
149 the last acknowledgement. The cache is the directory of the same
150 name under /var/cache.
151 '';
152 };
153
154 memoryMax = lib.mkOption {
155 type = size;
156 default = "1G";
157 description = ''
158 The most memory a pass may use, the publisher and every git, cue
159 and valley it runs together (`MemoryMax`, with no swap). Past it,
160 the kernel ends the pass.
161 '';
162 };
163
164 maxBundles = lib.mkOption {
165 type = size;
166 default = "1G";
167 description = ''
168 The most the bundles of one export may hold together. Each bundle
169 carries a public project's whole history on main. A bundle is
170 written only into what this leaves, and a pass past it sends
171 nothing (`--max-bundles`).
172 '';
173 };
174
175 maxStorage = lib.mkOption {
176 type = size;
177 default = "16G";
178 description = ''
179 The most the state and cache directories may hold. The cache holds
180 a clone of every project the host serves, and a mirror and a bundle
181 of each public one. A pass checks it before it fetches and once it
182 has read the valley, and writes a bundle only into what it leaves.
183 A pass past it sends nothing (`--max-storage`).
184 '';
185 };
186
187 # The publisher as this flake packages it. Internal, like the host
188 # module's packages: module-eval sets it to a stand-in.
189 package = lib.mkOption {
190 type = lib.types.package;
191 internal = true;
192 default = (import ./packages.nix { inherit pkgs lib; }).valley-web-publish;
193 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-web-publish";
194 description = "The web publisher.";
195 };
196 };
197
198 config = lib.mkIf cfg.enable {
199 assertions = [
200 {
201 assertion = host.enable;
202 message = "services.valley.webPublisher needs services.valley: it reads the repositories that host serves.";
203 }
204 {
205 assertion = host.integrator.instanceProject != null;
206 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.";
207 }
208 ];
209
210 # One pass, as a oneshot the timer below starts. A switch never starts
211 # it: nothing wants the service, and a changed unit is not restarted.
212 # The publisher's own lock serializes a pass started by hand with the
213 # timer's.
214 systemd.services.valley-web-publish = {
215 description = "One pass of the valley web publisher";
216 after = [
217 "network-online.target"
218 "valley-init.service"
219 ];
220 wants = [ "network-online.target" ];
221 restartIfChanged = false;
222 unitConfig.RequiresMountsFor = toString host.dataDir;
223 environment = safeDirectories // {
224 HOME = toString cfg.stateDir;
225 XDG_CACHE_HOME = cacheDir;
226 };
227 serviceConfig = {
228 Type = "oneshot";
229 ExecStart = command;
230 # A pass that hangs is ended, and the timer starts the next. One
231 # that outgrows its memory is ended too.
232 TimeoutStartSec = "1h";
233 MemoryMax = cfg.memoryMax;
234 MemorySwapMax = "0";
235 DynamicUser = true;
236 SupplementaryGroups = [ host.group ];
237 StateDirectory = stateName;
238 StateDirectoryMode = "0700";
239 CacheDirectory = stateName;
240 CacheDirectoryMode = "0700";
241 WorkingDirectory = toString cfg.stateDir;
242 # ProtectSystem=strict leaves the whole filesystem read-only but
243 # the state and cache directories, which systemd exempts. So the
244 # repositories, readable through the git group, are read-only,
245 # and named here so a reader of the unit sees it. A repository
246 # valley-init has not made yet is skipped (the leading -).
247 ProtectSystem = "strict";
248 ReadOnlyPaths = map (p: "-${p}") repositories;
249 InaccessiblePaths = map (p: "-${p}") keys;
250 ProtectHome = true;
251 PrivateTmp = true;
252 PrivateDevices = true;
253 NoNewPrivileges = true;
254 ProtectClock = true;
255 ProtectHostname = true;
256 ProtectKernelLogs = true;
257 ProtectKernelModules = true;
258 ProtectKernelTunables = true;
259 ProtectControlGroups = true;
260 ProtectProc = "invisible";
261 RestrictAddressFamilies = [
262 "AF_INET"
263 "AF_INET6"
264 "AF_UNIX"
265 ];
266 RestrictNamespaces = true;
267 RestrictRealtime = true;
268 RestrictSUIDSGID = true;
269 LockPersonality = true;
270 CapabilityBoundingSet = "";
271 SystemCallArchitectures = "native";
272 SystemCallFilter = [ "@system-service" ];
273 UMask = "0077";
274 };
275 };
276
277 # The first pass starts five minutes after the timer starts, and each
278 # later pass five minutes after the last one ended. These are delays
279 # and nothing more: a switch that runs longer than five minutes can
280 # see the first pass start inside it, and any later switch can see a
281 # pass start inside it.
282 systemd.timers.valley-web-publish = {
283 description = "Run the valley web publisher";
284 wantedBy = [ "timers.target" ];
285 timerConfig = {
286 OnActiveSec = "5min";
287 OnUnitInactiveSec = "5min";
288 };
289 };
290 };
291}