gunk-dev/the-valley

web-publisher.nix

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