gunk-dev/the-valley

web-publisher-e2e.nix

source30fe2c053de0main's published tip history
12.5 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 pkgs,
20 lib,
21 self,
22 ...
23}:
24let
25 declaration = pkgs.writeText "valley-web-publisher-e2e.cue" ''
26 package valley
27
28 projects: {
29 // The instance repository, whose main the host module requires
30 // protected.
31 "valley": protection: refs: ["refs/heads/main"]
32 "app": {}
33 }
34 '';
35
36 # What the unit runs in place of the publisher. Each check is one claim
37 # about the sandbox, and the probe says which one failed.
38 probe = pkgs.writeShellApplication {
39 name = "valley-web-publish-probe";
40 runtimeInputs = [
41 pkgs.bash
42 pkgs.git
43 pkgs.coreutils
44 pkgs.findutils
45 pkgs.getent
46 pkgs.gnugrep
47 ];
48 text = ''
49 fail() {
50 echo "probe: $*" >&2
51 exit 1
52 }
53 git -C /srv/git/app.git rev-parse --git-dir > /dev/null ||
54 fail "a repository the host serves could not be read"
55 if git -C /srv/git/stray.git rev-parse --git-dir 2> "$STATE_DIRECTORY/stray"; then
56 fail "a repository the host does not declare was read"
57 fi
58 grep -q "dubious ownership" "$STATE_DIRECTORY/stray" ||
59 fail "the undeclared repository was refused for another reason: $(cat "$STATE_DIRECTORY/stray")"
60 if touch /srv/git/app.git/probe 2> /dev/null; then
61 fail "a repository was written"
62 fi
63 if git -C /srv/git/app.git update-ref refs/heads/probe refs/heads/main 2> /dev/null; then
64 fail "a repository's ref was written"
65 fi
66 grep -qx "edge-token-0123456789abcdef0123456789" "$CREDENTIALS_DIRECTORY/receiver-token" ||
67 fail "the receiver's token did not reach the unit as a credential"
68 for key in /srv/git/.ssh/id_ed25519 /run/keys/backup-ssh-key /run/keys/web-receiver-token; do
69 if cat "$key" > /dev/null 2>&1; then
70 fail "$key was read"
71 fi
72 done
73 # The same alternate layout the publisher writes must resolve host
74 # objects with the exact safe.directory list and read-only mounts.
75 shared="$CACHE_DIRECTORY/shared.git"
76 git init --quiet --bare --template= "$shared"
77 git -C /srv/git/app.git rev-parse --path-format=absolute --git-path objects > "$shared/objects/info/alternates"
78 tip=$(git -C /srv/git/app.git rev-parse refs/heads/main)
79 git -C "$shared" update-ref refs/heads/main "$tip"
80 git -C "$shared" cat-file -e "$tip^{commit}" || fail "shared objects could not be read"
81 test "$(find "$shared/objects" -type f | wc -l)" -eq 1 || fail "objects were copied"
82 # The CLI uses a worktree-shaped cache with the same borrowed objects.
83 repos="$CACHE_DIRECTORY/repos"
84 mkdir "$repos"
85 cli="$repos/app"
86 git init --quiet --template= "$cli"
87 cp "$shared/objects/info/alternates" "$cli/.git/objects/info/alternates"
88 git -C "$cli" config remote.origin.url /srv/git/app.git
89 git -C "$cli" config core.logallrefupdates false
90 chmod 0500 "$repos"
91 if mkdir "$repos/unlisted" 2> /dev/null; then
92 fail "an unstaged CLI cache was created"
93 fi
94 git -C "$cli" update-ref refs/remotes/origin/main "$tip"
95 git -C "$cli" cat-file -e "$tip^{commit}" || fail "CLI shared objects could not be read"
96 test "$(find "$cli/.git/objects" -type f | wc -l)" -eq 1 || fail "CLI objects were copied"
97 chmod 0700 "$repos"
98 # Egress: the unit can connect to the allowed receiver address, and
99 # connections to disallowed IPv4 and IPv6 addresses fail within the
100 # 5-second timeout (whether rejected with EPERM or dropped).
101 reach() {
102 # shellcheck disable=SC2016
103 timeout 5 bash -c 'exec 3<> "/dev/tcp/$1/8080" && head -n 1 <&3' reach "$1"
104 }
105 test "$(reach 192.0.2.1)" = "listener allowed" ||
106 fail "the allowed listener at 192.0.2.1 could not be reached"
107 for addr in 192.0.2.2 2001:db8::2; do
108 start=$SECONDS
109 if reach "$addr" > /dev/null 2>&1; then
110 fail "the unrelated listener at $addr was reached"
111 fi
112 test $((SECONDS - start)) -le 6 || fail "the connection to $addr took more than 6 seconds to fail"
113 done
114 # DNS: the C library resolves names through nscd outside the unit,
115 # while the unit itself cannot send UDP packets to the DNS server.
116 test "''${GODEBUG-}" = netdns=cgo || fail "Go's lookups are not pinned to the C library"
117 getent hosts receiver.example.org > "$STATE_DIRECTORY/getent" ||
118 fail "receiver.example.org did not resolve through the C library"
119 grep -q "^192\.0\.2\.1 " "$STATE_DIRECTORY/getent" ||
120 fail "receiver.example.org resolved to $(cat "$STATE_DIRECTORY/getent")"
121 # shellcheck disable=SC2016
122 if LC_ALL=C timeout 5 bash -c 'printf query > /dev/udp/192.0.2.53/53' 2> "$STATE_DIRECTORY/dns"; then
123 fail "a datagram reached the DNS server at 192.0.2.53"
124 fi
125 grep -q "write error: Operation not permitted" "$STATE_DIRECTORY/dns" ||
126 fail "the datagram to 192.0.2.53 failed for another reason: $(cat "$STATE_DIRECTORY/dns")"
127 touch "$STATE_DIRECTORY/written" || fail "the state directory could not be written"
128 touch "$CACHE_DIRECTORY/written" || fail "the cache directory could not be written"
129 echo "probe: confined"
130 '';
131 };
132in
133{
134 web-publisher-e2e = pkgs.testers.runNixOSTest {
135 name = "valley-web-publisher-e2e";
136 nodes.host = {
137 imports = [
138 self.nixosModules.default
139 self.nixosModules.web-publisher
140 ];
141 # The system configuration trusts every directory, so only the
142 # entries in the unit's environment can keep a repository out.
143 environment.etc.gitconfig.text = ''
144 [safe]
145 directory = *
146 '';
147 services.valley = {
148 enable = true;
149 config = declaration;
150 # The host module requires a key for the git user. Nobody holds
151 # this one's private half, and nothing in the test pushes.
152 authorizedKeys = [
153 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEDVqaZm+1Xx4noNlTYckB32kUMMUnS8eN74T/Luxo+L operator"
154 ];
155 integrator.instanceProject = "valley";
156 backup.sshKeyFile = "/run/keys/backup-ssh-key";
157 webPublisher = {
158 enable = true;
159 destination = "example.org";
160 receiver = "http://192.0.2.1";
161 receiverTokenFile = "/run/keys/web-receiver-token";
162 allowedAddresses = [ "192.0.2.1" ];
163 };
164 };
165 systemd.services.valley-web-publish.serviceConfig.ExecStart = lib.mkForce (lib.getExe probe);
166 networking.enableIPv6 = true;
167 # Local DNS server on a disallowed IP address; answers queries for
168 # receiver.example.org.
169 networking.nameservers = [ "192.0.2.53" ];
170 environment.systemPackages = [
171 pkgs.socat
172 pkgs.dnsmasq
173 pkgs.dig
174 ];
175 };
176
177 testScript =
178 { nodes, ... }:
179 let
180 check = nodes.host.systemd.services.valley-web-publish.serviceConfig.ExecStartPre;
181 in
182 ''
183 host.wait_for_unit("multi-user.target")
184 host.wait_until_succeeds("test -d /srv/git/app.git && test -d /srv/git/valley.git")
185
186 # A repository the host does not declare, as the git user would
187 # leave one, and two keys the publisher must not read. Each is
188 # readable by the git group or by anyone, so only the unit's
189 # confinement keeps the probe from it.
190 host.succeed(
191 "runuser -u git -- git init --quiet --bare /srv/git/stray.git",
192 "install -d -m 0750 -o git -g git /srv/git/.ssh",
193 "echo secret | install -m 0640 -o git -g git /dev/stdin /srv/git/.ssh/id_ed25519",
194 "install -d -m 0755 /run/keys",
195 "echo secret | install -m 0644 /dev/stdin /run/keys/backup-ssh-key",
196 "echo edge-token-0123456789abcdef0123456789 | install -m 0400 /dev/stdin /run/keys/web-receiver-token",
197 )
198
199 # Start TCP listeners on the allowed receiver address and on
200 # disallowed IPv4 and IPv6 addresses, and verify that root can
201 # reach all three.
202 host.succeed(
203 "ip addr add 192.0.2.1/32 dev lo",
204 "ip addr add 192.0.2.2/32 dev lo",
205 "ip -6 addr add 2001:db8::2/128 dev lo nodad",
206 "ip addr add 198.51.100.1/32 dev lo",
207 "ip addr add 192.0.2.53/32 dev lo",
208 )
209 # Each listener replies with its short label because socat splits
210 # option arguments on colons, which would break IPv6 literals.
211 listeners = [
212 ("allowed", "192.0.2.1", "TCP4-LISTEN:8080,bind=192.0.2.1"),
213 ("ipv4", "192.0.2.2", "TCP4-LISTEN:8080,bind=192.0.2.2"),
214 ("ipv6", "2001:db8::2", "TCP6-LISTEN:8080,bind=[2001:db8::2]"),
215 ]
216 for label, addr, bind in listeners:
217 host.succeed(f"systemd-run --unit=listener-{label} socat {bind},reuseaddr,fork SYSTEM:'echo listener {label}'")
218 for label, addr, bind in listeners:
219 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)
220
221 # UDP listener on the canary address (198.51.100.1:9); appends any
222 # datagram it receives to /run/canary.
223 host.succeed("systemd-run --unit=canary socat -u UDP4-RECV:9,bind=198.51.100.1 OPEN:/run/canary,creat,append")
224 host.wait_until_succeeds("ss -Hulnp | grep -q '198.51.100.1:9 '", timeout=30)
225
226 # Start the DNS server on 192.0.2.53 and verify that root can query it.
227 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")
228 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)
229
230 # Run the unit's egress check as root outside the unit's cgroup:
231 # the datagram reaches the canary listener, so the check fails.
232 status, refused = host.execute("${check} 2>&1")
233 print(refused)
234 assert status != 0, "the egress check passed outside the unit"
235 assert "a datagram to 198.51.100.1 port 9 was sent" in refused, "the egress check refused for another reason"
236 host.wait_until_succeeds("grep -qx canary /run/canary", timeout=30)
237
238 # Verify the systemd unit properties for the IP address filter.
239 shown = host.succeed("systemctl show -p IPAddressDeny -p IPAddressAllow valley-web-publish.service")
240 print(shown)
241 assert "IPAddressAllow=192.0.2.1/32" in shown, "the unit does not allow the receiver's address"
242 deny = [line for line in shown.splitlines() if line.startswith("IPAddressDeny=")]
243 assert deny and sorted(deny[0].removeprefix("IPAddressDeny=").split()) == ["0.0.0.0/0", "::/0"], "the unit does not deny every other address"
244
245 host.succeed("runuser -u git -- sh -c 'tree=$(git -C /srv/git/app.git mktree < /dev/null); tip=$(echo initial | git -C /srv/git/app.git -c user.name=operator -c user.email=operator@example.org commit-tree \"$tree\"); git -C /srv/git/app.git update-ref refs/heads/main \"$tip\"'")
246
247 host.succeed("systemctl start valley-web-publish.service")
248 journal = host.succeed("journalctl -u valley-web-publish.service --no-pager")
249 print(journal)
250 assert "refused a datagram to 198.51.100.1 port 9 (EPERM)" in journal, "the egress check did not pass inside the unit"
251 assert host.succeed("cat /run/canary") == "canary", "a datagram from the unit's check reached the canary"
252 assert "probe: confined" in journal, "the probe did not finish"
253 host.succeed("test -e /var/lib/valley-web-publish/written")
254 host.fail("test -e /srv/git/app.git/probe")
255 '';
256 };
257}