gunk-dev/the-valley

web-publisher-e2e.nix

source1391837a95fbmain's published tip history
22.4 KiB
1# The web publisher's sandbox, in a NixOS machine running the host module
2# and the publisher's module beside it. The unit is the one the module
3# renders, with a probe in place of the publisher, so the probe runs as the
4# unit's dynamic user under the unit's own confinement. It must read the
5# repositories the host serves and nothing more: it writes no repository,
6# reads no key outside its state, and reads no repository the host does not
7# declare, though the system's git configuration trusts every directory. The
8# unit receives the bearer token as a systemd credential while the token
9# file on disk stays readable by root alone. The unit can connect to its
10# allowed IP address while connections to disallowed IPv4 and IPv6 listeners
11# fail, even though root can reach all three listeners from outside the
12# unit. The unit's ExecStartPre egress check passes inside the unit
13# (allowing the probe to start) and fails when run by root outside the unit
14# (where root's UDP datagram reaches the canary listener). Inside the unit,
15# the C library resolves a host name through nscd from a DNS server on a
16# disallowed address, while a UDP datagram sent directly from the unit to
17# that DNS server fails with EPERM.
18#
19# The read links' wrapper, valley-web-link, runs as root against
20# repositories the git user owns, though root's git trusts none of them
21# without the wrapper's entries. tmpfiles makes the links lock beside the
22# credential file, root's, and root refuses one it does not own. The
23# wrapper issues a link for a keyless principal into a credential file only
24# root writes and the publisher's group reads, and, with no receiver
25# listening, says the link is pending and exits 1. A
26# revoke of every link fails its delivery the same way; once a receiver
27# listens, the same revoke again delivers it, and a link issued then
28# reaches the receiver, read by the policy unit through its group.
29#
30# The two publisher units run as one dynamic user. A policy pass started
31# while a content pass holds the state and cache directories they share
32# succeeds, with the content pass's UID, and the content pass still owns
33# and writes them after it.
34{
35 pkgs,
36 lib,
37 self,
38 packages,
39 ...
40}:
41let
42 declaration = pkgs.writeText "valley-web-publisher-e2e.cue" ''
43 package valley
44
45 groups: core: name: "tools"
46 projects: {
47 // The instance repository, whose main the host module requires
48 // protected.
49 "valley": protection: refs: ["refs/heads/main"]
50 "app": group: "core"
51 }
52 '';
53
54 # The instance's main: an identity registry granting alice, who holds
55 # no key, an edge read of every project at example.org, and app's
56 # policy/read, which lets alice read it.
57 registry = pkgs.writeText "registry.cue" ''
58 package identity
59
60 boundaries: {
61 registry: kind: "registry"
62 web: {kind: "edge-read", destination: "example.org"}
63 }
64 genesis: "operator"
65 principals: operator: {
66 kind: "human"
67 keys: [{class: "ssh-ed25519", bound: "hardware", public: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEDVqaZm+1Xx4noNlTYckB32kUMMUnS8eN74T/Luxo+L"}]
68 grants: govern: boundary: "registry"
69 }
70 principals: alice: {kind: "human", keys: [], grants: read: {boundary: "web", projects: "all"}}
71 anyone: grants: read: {boundary: "web", projects: {app: "9da6809f038df92138c131cd16bed76d"}}
72 '';
73 appRead = pkgs.writeText "read.cue" ''
74 package read
75
76 project: "app"
77 identity: "9da6809f038df92138c131cd16bed76d"
78 readers: {anyone: true, alice: true}
79 '';
80 # Commits the files to a repository's main as the git user, by a fetch
81 # into the bare repository, which runs no hook.
82 seed = pkgs.writeShellApplication {
83 name = "seed";
84 runtimeInputs = [
85 pkgs.git
86 pkgs.coreutils
87 ];
88 text = ''
89 work=$(mktemp -d)
90 git -C "$work" init --quiet
91 git -C "$work" config user.name operator
92 git -C "$work" config user.email operator@example.org
93 mkdir -p "$work/policy/instance" "$work/policy/read" "$work/identity"
94 echo 'package verification' > "$work/policy/instance/floor.cue"
95 cp ${registry} "$work/identity/registry.cue"
96 git -C "$work" add --all
97 git -C "$work" commit --quiet -m "the instance"
98 git -C /srv/git/valley.git fetch --quiet "$work" +HEAD:refs/heads/main
99 list=$(printf 'app\nvalley\n' | git -C /srv/git/valley.git hash-object -w --stdin)
100 git -C /srv/git/valley.git update-ref refs/the-valley/projects "$list"
101 rm -rf "$work"
102 work=$(mktemp -d)
103 git -C "$work" init --quiet
104 git -C "$work" config user.name operator
105 git -C "$work" config user.email operator@example.org
106 mkdir -p "$work/policy/read"
107 cp ${appRead} "$work/policy/read/read.cue"
108 echo /srv/git/valley.git > "$work/policy/valley"
109 git -C "$work" add --all
110 git -C "$work" commit --quiet -m "app"
111 git -C /srv/git/app.git fetch --quiet "$work" +HEAD:refs/heads/main
112 rm -rf "$work"
113 '';
114 };
115
116 # What the unit runs in place of the publisher. Each check is one claim
117 # about the sandbox, and the probe says which one failed.
118 probe = pkgs.writeShellApplication {
119 name = "valley-web-publish-probe";
120 runtimeInputs = [
121 pkgs.bash
122 pkgs.git
123 pkgs.coreutils
124 pkgs.findutils
125 pkgs.getent
126 pkgs.gnugrep
127 ];
128 text = ''
129 fail() {
130 echo "probe: $*" >&2
131 exit 1
132 }
133 # With /run/probe-hold, the probe is a content pass that holds its
134 # state and cache directories until the file is removed, then checks
135 # it still owns them and writes them.
136 if [ -e /run/probe-hold ]; then
137 touch "$STATE_DIRECTORY/holding" "$CACHE_DIRECTORY/holding"
138 for _ in $(seq 1200); do
139 [ -e /run/probe-hold ] || break
140 sleep 0.1
141 done
142 [ ! -e /run/probe-hold ] || fail "the probe was not let go"
143 owners=$(stat -L -c %u "$STATE_DIRECTORY" "$CACHE_DIRECTORY" | sort -u)
144 test "$owners" = "$(id -u)" || fail "the state or cache directory is owned by $owners, not by the probe's $(id -u)"
145 rm "$STATE_DIRECTORY/holding" "$CACHE_DIRECTORY/holding" || fail "the state or cache directory could not be written after the policy pass"
146 touch "$STATE_DIRECTORY/held" "$CACHE_DIRECTORY/held" || fail "the state or cache directory could not be written after the policy pass"
147 echo "probe: held its state"
148 exit 0
149 fi
150 git -C /srv/git/app.git rev-parse --git-dir > /dev/null ||
151 fail "a repository the host serves could not be read"
152 if git -C /srv/git/stray.git rev-parse --git-dir 2> "$STATE_DIRECTORY/stray"; then
153 fail "a repository the host does not declare was read"
154 fi
155 grep -q "dubious ownership" "$STATE_DIRECTORY/stray" ||
156 fail "the undeclared repository was refused for another reason: $(cat "$STATE_DIRECTORY/stray")"
157 if touch /srv/git/app.git/probe 2> /dev/null; then
158 fail "a repository was written"
159 fi
160 if git -C /srv/git/app.git update-ref refs/heads/probe refs/heads/main 2> /dev/null; then
161 fail "a repository's ref was written"
162 fi
163 grep -qx "edge-token-0123456789abcdef0123456789" "$CREDENTIALS_DIRECTORY/receiver-token" ||
164 fail "the receiver's token did not reach the unit as a credential"
165 for key in /srv/git/.ssh/id_ed25519 /run/keys/backup-ssh-key /run/keys/web-receiver-token; do
166 if cat "$key" > /dev/null 2>&1; then
167 fail "$key was read"
168 fi
169 done
170 # The same alternate layout the publisher writes must resolve host
171 # objects with the exact safe.directory list and read-only mounts.
172 shared="$CACHE_DIRECTORY/shared.git"
173 git init --quiet --bare --template= "$shared"
174 git -C /srv/git/app.git rev-parse --path-format=absolute --git-path objects > "$shared/objects/info/alternates"
175 tip=$(git -C /srv/git/app.git rev-parse refs/heads/main)
176 git -C "$shared" update-ref refs/heads/main "$tip"
177 git -C "$shared" cat-file -e "$tip^{commit}" || fail "shared objects could not be read"
178 test "$(find "$shared/objects" -type f | wc -l)" -eq 1 || fail "objects were copied"
179 # The CLI uses a worktree-shaped cache with the same borrowed objects.
180 repos="$CACHE_DIRECTORY/repos"
181 mkdir "$repos"
182 cli="$repos/app"
183 git init --quiet --template= "$cli"
184 cp "$shared/objects/info/alternates" "$cli/.git/objects/info/alternates"
185 git -C "$cli" config remote.origin.url /srv/git/app.git
186 git -C "$cli" config core.logallrefupdates false
187 chmod 0500 "$repos"
188 if mkdir "$repos/unlisted" 2> /dev/null; then
189 fail "an unstaged CLI cache was created"
190 fi
191 git -C "$cli" update-ref refs/remotes/origin/main "$tip"
192 git -C "$cli" cat-file -e "$tip^{commit}" || fail "CLI shared objects could not be read"
193 test "$(find "$cli/.git/objects" -type f | wc -l)" -eq 1 || fail "CLI objects were copied"
194 chmod 0700 "$repos"
195 # Egress: the unit can connect to the allowed receiver address, and
196 # connections to disallowed IPv4 and IPv6 addresses fail within the
197 # 5-second timeout (whether rejected with EPERM or dropped).
198 reach() {
199 # shellcheck disable=SC2016
200 timeout 5 bash -c 'exec 3<> "/dev/tcp/$1/8080" && head -n 1 <&3' reach "$1"
201 }
202 test "$(reach 192.0.2.1)" = "listener allowed" ||
203 fail "the allowed listener at 192.0.2.1 could not be reached"
204 for addr in 192.0.2.2 2001:db8::2; do
205 start=$SECONDS
206 if reach "$addr" > /dev/null 2>&1; then
207 fail "the unrelated listener at $addr was reached"
208 fi
209 test $((SECONDS - start)) -le 6 || fail "the connection to $addr took more than 6 seconds to fail"
210 done
211 # DNS: the C library resolves names through nscd outside the unit,
212 # while the unit itself cannot send UDP packets to the DNS server.
213 test "''${GODEBUG-}" = netdns=cgo || fail "Go's lookups are not pinned to the C library"
214 getent hosts receiver.example.org > "$STATE_DIRECTORY/getent" ||
215 fail "receiver.example.org did not resolve through the C library"
216 grep -q "^192\.0\.2\.1 " "$STATE_DIRECTORY/getent" ||
217 fail "receiver.example.org resolved to $(cat "$STATE_DIRECTORY/getent")"
218 # shellcheck disable=SC2016
219 if LC_ALL=C timeout 5 bash -c 'printf query > /dev/udp/192.0.2.53/53' 2> "$STATE_DIRECTORY/dns"; then
220 fail "a datagram reached the DNS server at 192.0.2.53"
221 fi
222 grep -q "write error: Operation not permitted" "$STATE_DIRECTORY/dns" ||
223 fail "the datagram to 192.0.2.53 failed for another reason: $(cat "$STATE_DIRECTORY/dns")"
224 touch "$STATE_DIRECTORY/written" || fail "the state directory could not be written"
225 touch "$CACHE_DIRECTORY/written" || fail "the cache directory could not be written"
226 echo "probe: confined"
227 '';
228 };
229in
230{
231 web-publisher-e2e = pkgs.testers.runNixOSTest {
232 name = "valley-web-publisher-e2e";
233 nodes.host = {
234 imports = [
235 self.nixosModules.default
236 self.nixosModules.web-publisher
237 ];
238 # The system configuration trusts every directory, so only the
239 # entries in the unit's environment can keep a repository out.
240 environment.etc.gitconfig.text = ''
241 [safe]
242 directory = *
243 '';
244 services.valley = {
245 enable = true;
246 config = declaration;
247 # The host module requires a key for the git user. Nobody holds
248 # this one's private half, and nothing in the test pushes.
249 authorizedKeys = [
250 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEDVqaZm+1Xx4noNlTYckB32kUMMUnS8eN74T/Luxo+L operator"
251 ];
252 integrator.instanceProject = "valley";
253 backup.sshKeyFile = "/run/keys/backup-ssh-key";
254 webPublisher = {
255 enable = true;
256 destination = "example.org";
257 receiver = "http://192.0.2.1";
258 receiverTokenFile = "/run/keys/web-receiver-token";
259 allowedAddresses = [ "192.0.2.1" ];
260 };
261 };
262 systemd.services.valley-web-publish.serviceConfig.ExecStart = lib.mkForce (lib.getExe probe);
263 networking.enableIPv6 = true;
264 # Local DNS server on a disallowed IP address; answers queries for
265 # receiver.example.org.
266 networking.nameservers = [ "192.0.2.53" ];
267 environment.systemPackages = [
268 pkgs.socat
269 pkgs.dnsmasq
270 pkgs.dig
271 ];
272 };
273
274 testScript =
275 { nodes, ... }:
276 let
277 check = nodes.host.systemd.services.valley-web-publish.serviceConfig.ExecStartPre;
278 in
279 ''
280 host.wait_for_unit("multi-user.target")
281 host.wait_until_succeeds("test -d /srv/git/app.git && test -d /srv/git/valley.git")
282
283 # A repository the host does not declare, as the git user would
284 # leave one, and two keys the publisher must not read. Each is
285 # readable by the git group or by anyone, so only the unit's
286 # confinement keeps the probe from it.
287 host.succeed(
288 "runuser -u git -- git init --quiet --bare /srv/git/stray.git",
289 "install -d -m 0750 -o git -g git /srv/git/.ssh",
290 "echo secret | install -m 0640 -o git -g git /dev/stdin /srv/git/.ssh/id_ed25519",
291 "install -d -m 0755 /run/keys",
292 "echo secret | install -m 0644 /dev/stdin /run/keys/backup-ssh-key",
293 "echo edge-token-0123456789abcdef0123456789 | install -m 0400 /dev/stdin /run/keys/web-receiver-token",
294 )
295
296 # Start TCP listeners on the allowed receiver address and on
297 # disallowed IPv4 and IPv6 addresses, and verify that root can
298 # reach all three.
299 host.succeed(
300 "ip addr add 192.0.2.1/32 dev lo",
301 "ip addr add 192.0.2.2/32 dev lo",
302 "ip -6 addr add 2001:db8::2/128 dev lo nodad",
303 "ip addr add 198.51.100.1/32 dev lo",
304 "ip addr add 192.0.2.53/32 dev lo",
305 )
306 # Each listener replies with its short label because socat splits
307 # option arguments on colons, which would break IPv6 literals.
308 listeners = [
309 ("allowed", "192.0.2.1", "TCP4-LISTEN:8080,bind=192.0.2.1"),
310 ("ipv4", "192.0.2.2", "TCP4-LISTEN:8080,bind=192.0.2.2"),
311 ("ipv6", "2001:db8::2", "TCP6-LISTEN:8080,bind=[2001:db8::2]"),
312 ]
313 for label, addr, bind in listeners:
314 host.succeed(f"systemd-run --unit=listener-{label} socat {bind},reuseaddr,fork SYSTEM:'echo listener {label}'")
315 for label, addr, bind in listeners:
316 host.wait_until_succeeds(f"timeout 5 bash -c 'exec 3<> /dev/tcp/{addr}/8080 && head -n 1 <&3' | grep -qx 'listener {label}'", timeout=30)
317
318 # UDP listener on the canary address (198.51.100.1:9); appends any
319 # datagram it receives to /run/canary.
320 host.succeed("systemd-run --unit=canary socat -u UDP4-RECV:9,bind=198.51.100.1 OPEN:/run/canary,creat,append")
321 host.wait_until_succeeds("ss -Hulnp | grep -q '198.51.100.1:9 '", timeout=30)
322
323 # Start the DNS server on 192.0.2.53 and verify that root can query it.
324 host.succeed("systemd-run --unit=dns dnsmasq --keep-in-foreground --no-resolv --no-hosts --bind-interfaces --listen-address=192.0.2.53 --address=/receiver.example.org/192.0.2.1")
325 host.wait_until_succeeds("dig +short +time=2 +tries=1 @192.0.2.53 receiver.example.org | grep -qx 192.0.2.1", timeout=30)
326
327 # Run the unit's egress check as root outside the unit's cgroup:
328 # the datagram reaches the canary listener, so the check fails.
329 status, refused = host.execute("${check} 2>&1")
330 print(refused)
331 assert status != 0, "the egress check passed outside the unit"
332 assert "a datagram to 198.51.100.1 port 9 was sent" in refused, "the egress check refused for another reason"
333 host.wait_until_succeeds("grep -qx canary /run/canary", timeout=30)
334
335 # Verify the systemd unit properties for the IP address filter.
336 shown = host.succeed("systemctl show -p IPAddressDeny -p IPAddressAllow valley-web-publish.service")
337 print(shown)
338 assert "IPAddressAllow=192.0.2.1/32" in shown, "the unit does not allow the receiver's address"
339 deny = [line for line in shown.splitlines() if line.startswith("IPAddressDeny=")]
340 assert deny and sorted(deny[0].removeprefix("IPAddressDeny=").split()) == ["0.0.0.0/0", "::/0"], "the unit does not deny every other address"
341
342 host.succeed("runuser -u git -- ${lib.getExe seed}")
343
344 host.succeed("systemctl start valley-web-publish.service")
345 journal = host.succeed("journalctl -u valley-web-publish.service --no-pager")
346 print(journal)
347 assert "refused a datagram to 198.51.100.1 port 9 (EPERM)" in journal, "the egress check did not pass inside the unit"
348 assert host.succeed("cat /run/canary") == "canary", "a datagram from the unit's check reached the canary"
349 assert "probe: confined" in journal, "the probe did not finish"
350 host.succeed("test -e /var/lib/valley-web-publish/written")
351 host.fail("test -e /srv/git/app.git/probe")
352
353 # Read links. Root's git refuses the git user's repositories once
354 # the system's trust is reset, as the wrapper's entries reset it.
355 refused = host.fail("GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=safe.directory GIT_CONFIG_VALUE_0= git -C /srv/git/valley.git rev-parse HEAD 2>&1")
356 assert "dubious ownership" in refused, f"root's git refused the instance for another reason: {refused}"
357 assert host.succeed("stat -c '%U:%G %a %F' /var/lib/valley-web-links /var/lib/valley-web-links/links /var/lib/valley-web-links/lock") == "root:valley-web-links 750 directory\nroot:valley-web-links 640 regular empty file\nroot:valley-web-links 640 regular empty file\n", "the credential file's or the links lock's owners, modes or types are wrong"
358
359 # Root refuses a links lock it does not own, and changes nothing.
360 host.succeed("chown nobody /var/lib/valley-web-links/lock")
361 status, refused = host.execute("valley-web-link revoke --all 2>&1")
362 print(refused)
363 assert status == 1 and "/var/lib/valley-web-links/lock is owned by UID" in refused, "root took a links lock it does not own"
364 host.succeed("test ! -s /var/lib/valley-web-links/links")
365 host.succeed("chown root /var/lib/valley-web-links/lock")
366
367 # With no receiver listening, an issue as root writes the link and
368 # prints it once, and the delivery fails: the link is pending. The
369 # test never prints the link.
370 status, _ = host.execute("valley-web-link issue --principal alice --note vm > /root/link 2> /root/issue.err")
371 issued = host.succeed("cat /root/issue.err")
372 print(issued)
373 assert status == 1, f"an undelivered issue exited {status}"
374 assert "dubious ownership" not in issued, "root's git refused a repository through the wrapper"
375 host.succeed("grep -Eqx 'https://example\\.org/-/redeem#lk-[0-9a-f]{16}\\.[A-Za-z0-9_-]{43}' /root/link")
376 assert ": issued here; the edge does not accept it until a pass delivers it" in issued, "the issue did not report the link pending"
377 assert host.succeed("stat -c '%U:%G %a' /var/lib/valley-web-links/links") == "root:valley-web-links 640\n", "the link command wrote the credential file with other owners or another mode"
378 host.fail("valley-web-link list --check")
379
380 # A revoke of every link whose delivery fails exits 1; once a
381 # receiver listens, the same revoke again delivers it.
382 status, revoked = host.execute("valley-web-link revoke --all 2>&1")
383 print(revoked)
384 assert status == 1 and "revoked here; the edge may accept it" in revoked, "an undelivered revoke --all did not report the revocation pending"
385 host.succeed(
386 "install -d -m 0700 /var/lib/receiver",
387 "systemd-run --unit=receiver ${lib.getExe' packages.valley-web-receive "valley-web-receive"} --state /var/lib/receiver/store --listen 192.0.2.1:80 --instance host --destination example.org --verifiers /var/lib/valley-web-publish/verifier --token-file /run/keys/web-receiver-token",
388 )
389 host.wait_until_succeeds("ss -Htln | grep -q '192.0.2.1:80 '", timeout=30)
390 retried = host.succeed("valley-web-link revoke --all 2>&1")
391 print(retried)
392 assert "the receiver holds every link's current state" in retried, "a repeated revoke --all did not deliver"
393 host.fail("grep -q '^binding ' /var/lib/receiver/v2/authorization")
394
395 # A link issued now reaches the receiver: the policy unit reads the
396 # credential file through its group as it signs.
397 host.succeed("valley-web-link issue --principal alice > /root/link")
398 lk = host.succeed("sed 's/.*#\\(lk-[0-9a-f]*\\)\\..*/\\1/' /root/link").strip()
399 host.succeed(f"grep -Eq '^binding {lk} alice [0-9a-f]{{64}}$' /var/lib/receiver/v2/authorization")
400
401 # Both units run as one dynamic user. A policy pass while a content
402 # pass holds the state and cache directories succeeds, with the
403 # content pass's UID, and the content pass then finds them its own,
404 # as the unit sees them, writes them, and ends.
405 users = host.succeed("systemctl show -p User --value valley-web-publish.service valley-web-publish-policy.service")
406 assert users.split() == ["valley-web-publish", "valley-web-publish"], f"the units run as {users.split()}"
407 host.succeed("touch /run/probe-hold")
408 host.succeed("systemctl start --no-block valley-web-publish.service")
409 host.wait_until_succeeds("test -e /var/lib/private/valley-web-publish/holding", timeout=60)
410 probe_uid = host.succeed("stat -c %u /proc/$(systemctl show -p MainPID --value valley-web-publish.service)").strip()
411 since = host.succeed("date +%s").strip()
412 host.succeed("valley-web-link revoke --all")
413 host.fail(f"grep -q '^binding {lk} ' /var/lib/receiver/v2/authorization")
414 policy_uids = host.succeed(f"journalctl _SYSTEMD_UNIT=valley-web-publish-policy.service --since=@{since} -o export | sed -n 's/^_UID=//p' | sort -u").split()
415 assert policy_uids == [probe_uid], f"the policy pass ran as UID {policy_uids}, and the content pass as {probe_uid}"
416 host.succeed("systemctl show -p ActiveState --value valley-web-publish.service | grep -qx activating")
417 host.succeed("rm /run/probe-hold")
418 host.wait_until_succeeds("systemctl show -p ActiveState --value valley-web-publish.service | grep -Eqx 'inactive|failed'", timeout=60)
419 journal = host.succeed("journalctl -u valley-web-publish.service --no-pager")
420 print(journal)
421 result = host.succeed("systemctl show -p Result --value valley-web-publish.service").strip()
422 assert result == "success" and "probe: held its state" in journal, f"the content pass that held its state ended with {result}"
423 host.succeed("test -e /var/lib/private/valley-web-publish/held -a -e /var/cache/private/valley-web-publish/held")
424 '';
425 };
426}