gunk-dev/the-valley

webui-publisher.nix

sourced03575e2a892main's published tip history
10.4 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 pass past it
170 sends nothing (`--max-bundles`).
171 '';
172 };
173
174 maxStorage = lib.mkOption {
175 type = size;
176 default = "16G";
177 description = ''
178 The most the state and cache directories may hold once a pass has
179 made its bundles. The cache holds a clone of every project the host
180 serves, and a mirror and a bundle of each public one. A pass past
181 it sends nothing (`--max-storage`).
182 '';
183 };
184
185 # The publisher as this flake packages it. Internal, like the host
186 # module's packages: module-eval sets it to a stand-in.
187 package = lib.mkOption {
188 type = lib.types.package;
189 internal = true;
190 default = (import ./packages.nix { inherit pkgs lib; }).valley-web-publish;
191 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-web-publish";
192 description = "The web publisher.";
193 };
194 };
195
196 config = lib.mkIf cfg.enable {
197 assertions = [
198 {
199 assertion = host.enable;
200 message = "services.valley.webPublisher needs services.valley: it reads the repositories that host serves.";
201 }
202 {
203 assertion = host.integrator.instanceProject != null;
204 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.";
205 }
206 ];
207
208 # One pass, as a oneshot the timer below starts. A switch never starts
209 # it: nothing wants the service, and a changed unit is not restarted.
210 # The publisher's own lock serializes a pass started by hand with the
211 # timer's.
212 systemd.services.valley-web-publish = {
213 description = "One pass of the valley web publisher";
214 after = [
215 "network-online.target"
216 "valley-init.service"
217 ];
218 wants = [ "network-online.target" ];
219 restartIfChanged = false;
220 unitConfig.RequiresMountsFor = toString host.dataDir;
221 environment = safeDirectories // {
222 HOME = toString cfg.stateDir;
223 XDG_CACHE_HOME = cacheDir;
224 };
225 serviceConfig = {
226 Type = "oneshot";
227 ExecStart = command;
228 # A pass that hangs is ended, and the timer starts the next. One
229 # that outgrows its memory is ended too.
230 TimeoutStartSec = "1h";
231 MemoryMax = cfg.memoryMax;
232 MemorySwapMax = "0";
233 DynamicUser = true;
234 SupplementaryGroups = [ host.group ];
235 StateDirectory = stateName;
236 StateDirectoryMode = "0700";
237 CacheDirectory = stateName;
238 CacheDirectoryMode = "0700";
239 WorkingDirectory = toString cfg.stateDir;
240 # ProtectSystem=strict leaves the whole filesystem read-only but
241 # the state and cache directories, which systemd exempts. So the
242 # repositories, readable through the git group, are read-only,
243 # and named here so a reader of the unit sees it. A repository
244 # valley-init has not made yet is skipped (the leading -).
245 ProtectSystem = "strict";
246 ReadOnlyPaths = map (p: "-${p}") repositories;
247 InaccessiblePaths = map (p: "-${p}") keys;
248 ProtectHome = true;
249 PrivateTmp = true;
250 PrivateDevices = true;
251 NoNewPrivileges = true;
252 ProtectClock = true;
253 ProtectHostname = true;
254 ProtectKernelLogs = true;
255 ProtectKernelModules = true;
256 ProtectKernelTunables = true;
257 ProtectControlGroups = true;
258 ProtectProc = "invisible";
259 RestrictAddressFamilies = [
260 "AF_INET"
261 "AF_INET6"
262 "AF_UNIX"
263 ];
264 RestrictNamespaces = true;
265 RestrictRealtime = true;
266 RestrictSUIDSGID = true;
267 LockPersonality = true;
268 CapabilityBoundingSet = "";
269 SystemCallArchitectures = "native";
270 SystemCallFilter = [ "@system-service" ];
271 UMask = "0077";
272 };
273 };
274
275 # Every five minutes, counted from the end of each pass. The first
276 # pass waits five minutes after the timer is started, so the first pass
277 # never runs inside the switch that starts the timer. Nothing keeps a
278 # later pass out of a later switch.
279 systemd.timers.valley-web-publish = {
280 description = "Run the valley web publisher";
281 wantedBy = [ "timers.target" ];
282 timerConfig = {
283 OnActiveSec = "5min";
284 OnUnitInactiveSec = "5min";
285 };
286 };
287 };
288}