gunk-dev/the-valley

telemetry.nix

source58e68be0d151main's published tip history
39.4 KiB
1# Telemetry: the collector's unit tests, and telemetry on a host end to end.
2#
3# telemetry-e2e is one NixOS machine running the module with the worker,
4# the controllers, the registry compiler and the collector. Every read and
5# report goes over its real sshd, through the git user's shell.
6#
7# First the boundary: an enrolled observer reads, and nobody else does. A
8# contributor without the grant, an untagged key, a key claiming another
9# principal through its environment, a reporter, and every malformed or
10# hostile command are refused, and none reaches a shell. A forced
11# fetch-only key stays fetch-only. Reads work while pushes are held. The
12# git user and the collector cannot read the worker's key, and the git
13# user cannot read the diagnostics on disk.
14#
15# Then the worker: a pass's slow check prints its output while it builds,
16# and a reader sees it then. The pass is killed during the build; the
17# source reads as stale, the journal shows the kill, and the next pass
18# records the interruption, inferred, and finishes. A change whose check
19# fails leaves a backoff naming the change, its head, its tree and why.
20#
21# Then the workstation, alice, a second user reaching the host over ssh
22# as its own principal. Her approval of a fresh change builds a slow and a
23# fast check side by side; the observer sees the fast one finish, and the
24# slow one's output, while the slow one still builds, and then the request
25# published, with alice's CLI version and her own timestamps. An approval
26# reusing the worker's evidence beside a local command check, and one
27# reusing everything, are observable too, and so is the integrator's
28# decision. The operator, who observes the worker, asks it for two
29# commits' checks with valley checks --build: one passes, and one whose
30# check fails is not established, with the worker's output for its tree.
31# Every command alice runs records its verb, its flag names, its exit
32# status, its time and, for pending, its phases, and never an argument's
33# value; with telemetry off it records nothing and writes no spool, and
34# with the host unreachable it prints and exits as it does off.
35#
36# Last, outage: with the collector stopped, and with the telemetry remote
37# unreachable, approvals and pushes still complete, within a bounded
38# overhead; once the collector is back, one flush sends what was spooled,
39# and a second sends nothing again. Report and read limits hold on the
40# server whatever is asked.
41{
42 pkgs,
43 lib,
44 self,
45 packages,
46 machineValley,
47 ...
48}:
49let
50 keys = pkgs.runCommand "valley-telemetry-e2e-keys" { nativeBuildInputs = [ pkgs.openssh ]; } ''
51 mkdir $out
52 for who in integrator contributor operator alice stranger fetcher; do
53 ssh-keygen -q -t ed25519 -N "" -C "$who" -f "$out/$who"
54 done
55 '';
56 pub = who: lib.fileContents "${keys}/${who}.pub";
57 pubBlob = who: lib.concatStringsSep " " (lib.take 2 (lib.splitString " " (pub who)));
58
59 declaration = pkgs.writeText "valley-telemetry-e2e.cue" ''
60 package valley
61
62 projects: {
63 "instance": protection: refs: ["refs/heads/main"]
64 "project": protection: {}
65 }
66 '';
67
68 # Every change requires a slow and a fast nix check; one that touches
69 # local/ also requires a command check, which the worker leaves to
70 # approve.
71 floor = pkgs.writeText "floor.cue" ''
72 package verification
73
74 floor: {
75 checks: {
76 slow: {runner: "nix", attribute: "slow"}
77 fast: {runner: "nix", attribute: "fast"}
78 local: {runner: "command", command: "echo local check ran"}
79 }
80 classes: {
81 policy: {paths: {"policy/**": true}, requires: {}}
82 local: {paths: {"local/**": true}, requires: {slow: true, fast: true, local: true}}
83 }
84 unclassified: {slow: true, fast: true}
85 }
86 '';
87
88 flake = pkgs.writeText "flake.nix" ''
89 {
90 outputs =
91 { self }:
92 let
93 check = name: script: derivation {
94 inherit name;
95 system = "x86_64-linux";
96 builder = "/bin/sh";
97 args = [ script ];
98 };
99 in
100 {
101 checks.x86_64-linux = {
102 slow = check "telemetry-slow" ./slow.sh;
103 fast = check "telemetry-fast" ./fast.sh;
104 };
105 };
106 }
107 '';
108 flakeLock = pkgs.writeText "flake.lock" ''{"nodes":{"root":{}},"root":"root","version":7}'';
109 # About half a second a tick, a line of output each, and a terminal
110 # escape in the first, which a reader must see escaped.
111 slow = pkgs.writeText "slow.sh" ''
112 printf 'slow start \033[31mred\033[0m\n'
113 n=0
114 while [ $n -lt 40 ]; do
115 i=0
116 while [ $i -lt 250000 ]; do i=$((i+1)); done
117 n=$((n+1))
118 echo "slow tick $n"
119 done
120 echo slow > $out
121 '';
122 fast = pkgs.writeText "fast.sh" "echo fast > $out";
123 broken = pkgs.writeText "broken.sh" ''
124 echo "broken check says why"
125 exit 1
126 '';
127in
128{
129 telemetry-unit = packages.telemetry.unit;
130
131 telemetry-e2e = pkgs.testers.runNixOSTest {
132 name = "valley-telemetry-e2e";
133 nodes.host =
134 { lib, ... }:
135 {
136 imports = [ self.nixosModules.default ];
137 virtualisation.cores = 4;
138 virtualisation.memorySize = 3072;
139 environment.systemPackages = [
140 pkgs.git
141 machineValley
142 ];
143 users.users.alice.isNormalUser = true;
144 services.valley = {
145 enable = true;
146 config = declaration;
147 authorizedKeys = [
148 {
149 principal = "contributor";
150 key = pub "contributor";
151 }
152 {
153 principal = "operator";
154 key = pub "operator";
155 }
156 {
157 principal = "alice";
158 key = pub "alice";
159 }
160 (pub "stranger")
161 ''command="git-upload-pack 'project.git'" ${pub "fetcher"}''
162 ];
163 grants.request = [ "alice" ];
164 identity.enable = true;
165 buildSlice.enable = true;
166 integrator = {
167 enable = true;
168 interval = "5s";
169 signingKeyFile = "${keys}/integrator";
170 instanceProject = "instance";
171 signerProjects."worker/attestations" = [ "project" ];
172 };
173 worker = {
174 enable = true;
175 projects = [ "project" ];
176 signerName = "worker/attestations";
177 };
178 telemetry = {
179 enable = true;
180 observers = [ "operator" ];
181 localSources = [
182 {
183 name = "host-probe";
184 description = "a service of the host's own, which fails";
185 units = [ "host-probe.service" ];
186 }
187 ];
188 reporters = [
189 "alice"
190 "receiver"
191 ];
192 remoteSources = [
193 {
194 name = "remote-receiver";
195 description = "a web receiver on another machine";
196 principal = "receiver";
197 }
198 ];
199 };
200 };
201 # A unit of the host's own, which nothing starts and which fails.
202 systemd.services.host-probe = {
203 serviceConfig.Type = "oneshot";
204 script = "echo host-probe says why; exit 3";
205 };
206 systemd.timers.valley-worker.timerConfig.OnActiveSec = lib.mkForce "1h";
207 nix.settings.experimental-features = [
208 "nix-command"
209 "flakes"
210 ];
211 nix.settings.substituters = lib.mkForce [ ];
212 networking.useDHCP = false;
213 };
214
215 testScript = ''
216 import json
217 import shlex
218 import time
219
220 host.wait_for_unit("multi-user.target")
221 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
222
223 git = "sudo -u git git"
224 ssh_opts = "-o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
225 commit = "git -c user.name=t -c user.email=t@example.org commit --quiet"
226
227 def raw(who, command, extra=""):
228 """The telemetry command as a session sends it, with who's key."""
229 return f"ssh {ssh_opts} {extra} -i /root/keys/{who} git@localhost {shlex.quote(command)}"
230
231 def lines(out):
232 return [json.loads(l) for l in out.splitlines() if l.strip()]
233
234 def observe(args):
235 """valley telemetry as the operator, outside any checkout."""
236 return lines(host.succeed(f"cd / && valley telemetry --remote git@localhost:project.git --json {args}"))
237
238 def of(ls, kind):
239 return [l for l in ls if l.get("kind") == kind]
240
241 def records(ls, **match):
242 return [l for l in of(ls, "record") if all(l.get(k) == v for k, v in match.items())]
243
244 def source(name):
245 return [s for s in of(observe("snapshot"), "source") if s["name"] == name][0]
246
247 def as_alice(cmd, check=True):
248 full = f"sudo -u alice -H env VALLEY_ATTEST_KEY=/home/alice/keys/alice VALLEY_ATTEST_NAME=alice/attestations bash -c {shlex.quote('cd /home/alice/project && ' + cmd)}"
249 return host.succeed(full) if check else host.execute(full)
250
251 def registry(worker):
252 def human(who, signs):
253 s = f', signs: "{who}/attestations"' if signs else ""
254 return [
255 f'"{who}": {{',
256 ' kind: "human"',
257 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{blob[who]}"{s}}}]',
258 ' grants: {push: boundary: "push", govern: boundary: "registry"}',
259 "}",
260 ]
261 principals = human("contributor", False) + human("alice", True)
262 if worker:
263 principals += [
264 '"worker": {',
265 ' kind: "machine"',
266 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{worker}", signs: "worker/attestations"}}]',
267 ' grants: push: boundary: "push"',
268 ' expires: "2099-01-01"',
269 "}",
270 ]
271 return "\n".join(['package identity', 'boundaries: {"push": kind: "git-push", "registry": kind: "registry"}',
272 'genesis: "contributor"', "principals: {"] + principals + ["}"])
273
274 blob = {"contributor": "${pubBlob "contributor"}", "alice": "${pubBlob "alice"}"}
275
276 def land_instance(worker):
277 host.succeed(
278 "rm -rf /tmp/instance && mkdir -p /tmp/instance/policy/instance /tmp/instance/identity",
279 "cp ${floor} /tmp/instance/policy/instance/floor.cue",
280 f"cat > /tmp/instance/identity/registry.cue <<'EOF'\n{registry(worker)}\nEOF",
281 f"cd /tmp/instance && git init --quiet --initial-branch=main && git add -A && {commit} -m instance",
282 "chown -R git:git /tmp/instance",
283 f"{git} -C /srv/git/instance.git fetch --quiet --force /tmp/instance main:refs/heads/main",
284 "systemctl start valley-identity.service",
285 )
286
287 def settle():
288 """Waits out a valley-init run: a unit that requires it starts it
289 again, such as the identity timer's compile, and pushes pause
290 while it runs."""
291 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-init)\" != activating", timeout=60)
292
293 def pushing(cmd):
294 """Runs a push of alice's, again if a valley-init run paused it."""
295 for attempt in range(3):
296 settle()
297 status, out = as_alice(cmd, check=False)
298 if status == 0:
299 return out
300 time.sleep(2)
301 raise Exception(f"alice could not run {cmd}: {out}")
302
303 def side_by_side(head, ended):
304 """Reads alice's records until the observer sees the fast check of
305 her approval at head done while the slow one still prints, and
306 returns that read. It reads for as long as the approval runs, and
307 fails if the slow check ends first."""
308 deadline = time.monotonic() + 300
309 while time.monotonic() < deadline and not ended():
310 ls = observe("read --source=report.alice --limit=1000 --logs")
311 fast_done = [r for r in records(ls, type="check.result", check="fast") if r["head"] == head]
312 if fast_done:
313 run = fast_done[0]["run"]
314 assert not [r for r in records(ls, type="check.result", check="slow") if r["run"] == run], "the slow check ended before the observer saw the fast one end"
315 if [r for r in records(ls, type="check.output", check="slow") if r["run"] == run and "slow tick" in r["data"]["text"]]:
316 return ls
317 time.sleep(1)
318 raise Exception(f"never saw the fast check done while the slow one built, at {head}")
319
320 def filed(head):
321 """Flushes alice's records until the observer reads her approval at
322 head filed, and returns that read and those approve.end records."""
323 for _ in range(60):
324 as_alice("valley telemetry flush")
325 ls = observe("read --source=report.alice --limit=1000")
326 ends = [r for r in records(ls, type="approve.end") if r["head"] == head and r["data"]["result"] == "filed"]
327 if ends:
328 return ls, ends
329 time.sleep(1)
330 raise Exception(f"the approval at {head} was never observed filed")
331
332 def ready(branch, path, script=None, rebuild=False):
333 """A change by alice: one new file, and the slow check's script
334 given, or changed so that its derivation is built again."""
335 cp = f"cp {script} slow.sh && " if script else ""
336 if rebuild:
337 cp += f"echo '# {branch}' >> slow.sh && "
338 as_alice(
339 f"git fetch --quiet origin && git checkout --quiet -B {branch} origin/main && {cp}"
340 f"mkdir -p $(dirname {path}) && echo {branch} > {path} && git add -A && {commit} -m {branch}"
341 )
342 pushing(f"git push --quiet origin {branch} && valley ready {branch}")
343 return as_alice(f"git rev-parse {branch}").strip()
344
345 with subtest("the instance and the project are seeded, and alice has a checkout"):
346 land_instance(None)
347 host.succeed(
348 "mkdir -p /tmp/project/policy",
349 "cp ${flake} /tmp/project/flake.nix",
350 "cp ${flakeLock} /tmp/project/flake.lock",
351 "cp ${slow} /tmp/project/slow.sh",
352 "cp ${fast} /tmp/project/fast.sh",
353 "echo 'git@host:instance.git' > /tmp/project/policy/valley",
354 f"cd /tmp/project && git init --quiet --initial-branch=main && git add -A && {commit} -m project",
355 "chown -R git:git /tmp/project",
356 f"{git} -C /srv/git/project.git fetch --quiet /tmp/project main:refs/heads/main",
357 "mkdir -p /root/keys /root/.ssh && cp ${keys}/* /root/keys/ && chmod 600 /root/keys/*",
358 "printf 'Host localhost host\\n IdentityFile /root/keys/operator\\n IdentitiesOnly yes\\n"
359 " StrictHostKeyChecking no\\n UserKnownHostsFile /dev/null\\n' > /root/.ssh/config",
360 "mkdir -p /home/alice/keys /home/alice/.ssh && install -m 600 ${keys}/alice /home/alice/keys/alice",
361 "printf 'Host localhost host\\n IdentityFile /home/alice/keys/alice\\n IdentitiesOnly yes\\n"
362 " StrictHostKeyChecking no\\n UserKnownHostsFile /dev/null\\n' > /home/alice/.ssh/config",
363 "chown -R alice /home/alice",
364 )
365 host.succeed("sudo -u alice -H git clone --quiet git@localhost:project.git /home/alice/project")
366 as_alice("git config valley.principal alice && git config user.name alice && git config user.email alice@example.org"
367 " && git config valley.telemetry true")
368 # The worker makes its key, and is enrolled.
369 host.fail("systemctl start valley-worker.service")
370 land_instance(" ".join(host.succeed("cat /var/lib/valley-worker/key.pub").split()[:2]))
371 host.wait_until_succeeds(
372 f"{git} -C /srv/git/instance.git cat-file blob refs/the-valley/signers:known-signers | grep -q '^alice/attestations+'",
373 timeout=60,
374 )
375
376 with subtest("an enrolled observer reads the catalog, and nobody else does"):
377 srcs = {s["name"]: s for s in of(observe("sources"), "source")}
378 for name in ["worker", "integrator", "identity", "signers", "mirrors", "convergence", "telemetry", "report.alice"]:
379 assert srcs[name]["enabled"], (name, srcs[name])
380 for name in ["bus", "backup", "web-publisher", "web-receiver", "restacker"]:
381 assert srcs[name]["state"] == "disabled", srcs[name]
382 assert srcs["remote-receiver"]["location"] == "remote" and srcs["remote-receiver"]["state"] == "unavailable", srcs["remote-receiver"]
383 assert srcs["integrator"]["not_instrumented"], srcs["integrator"]
384 assert srcs["worker"]["configured"]["attest"].startswith("/nix/store/"), srcs["worker"]
385 props = srcs["worker"]["unit_states"][0]
386 assert "Environment" not in props and props["Id"] == "valley-worker.service", props
387
388 for who, command, said in [
389 ("contributor", "valley-telemetry sources", "does not hold the telemetry observe grant"),
390 ("stranger", "valley-telemetry sources", "a key that names a principal"),
391 ("alice", "valley-telemetry sources", "does not hold the telemetry observe grant"),
392 ("operator", "valley-telemetry report", "does not hold the telemetry report grant"),
393 ("operator", "valley-telemetry sources; id", "not a telemetry operation"),
394 ("operator", "valley-telemetry sources && id", "is not a flag"),
395 ("operator", "valley-telemetry read --source=../../var/lib/valley-worker/key", "not a source name"),
396 ("operator", "valley-telemetry read --source=valley-*", "not a source name"),
397 ("operator", "valley-telemetry read --unit=sshd.service", "takes no --unit"),
398 ("operator", "valley-telemetry exec id", "not a telemetry operation"),
399 ("operator", "valley-telemetry read --source=nosuch", "no source is named nosuch"),
400 ]:
401 status, out = host.execute(raw(who, command) + " < /dev/null 2>&1")
402 assert status != 0 and said in out and "uid=" not in out, (who, command, status, out)
403 for command in ["id", "sh -c id", "systemctl restart valley-worker", "journalctl -u valley-worker"]:
404 status, out = host.execute(raw("operator", command) + " < /dev/null 2>&1")
405 assert status != 0 and "uid=" not in out and '"kind"' not in out, (command, out)
406 # A principal the client names in its environment is no principal.
407 status, out = host.execute(raw("contributor", "valley-telemetry sources", "-o SetEnv=VALLEY_PRINCIPAL=operator") + " 2>&1")
408 assert status != 0 and '"kind": "source"' not in out and '"kind":"source"' not in out, out
409 # A forced fetch-only key runs its forced command whatever it asks.
410 status, out = host.execute(raw("fetcher", "valley-telemetry sources") + " < /dev/null 2>&1")
411 assert '"kind"' not in out and "refs/heads/main" in out, out
412 # Reading is open while pushes are held.
413 host.succeed("touch /srv/git/.valley-hold")
414 assert of(observe("sources"), "end")
415 host.fail("sudo -u alice -H bash -c 'cd /home/alice/project && git push --quiet origin HEAD:refs/heads/held'")
416 host.succeed("rm /srv/git/.valley-hold")
417
418 with subtest("private keys stay private, and the diagnostics are the collector's alone to read"):
419 for user in ["git", "valley-telemetry"]:
420 host.fail(f"sudo -u {user} cat /var/lib/valley-worker/key")
421 host.fail(f"sudo -u {user} ls /var/lib/valley-worker")
422 host.fail("sudo -u git ls /var/lib/valley-telemetry/worker")
423 host.fail("sudo -u git ls /var/lib/valley-telemetry/collector")
424 assert "systemd-journal" not in host.succeed("id -nG git")
425 assert host.succeed("stat -c '%a %U %G' /var/lib/valley-telemetry/worker").strip() == "2750 valley-worker valley-telemetry"
426 assert host.succeed("stat -c '%a %U %G' /var/lib/valley-worker").strip() == "700 valley-worker valley-worker"
427 assert host.succeed("stat -c '%a %U' /run/valley-telemetry.sock").strip() == "600 git"
428
429 with subtest("a unit the host declares is a source, failed and logged as the module's own are"):
430 host.fail("systemctl start host-probe.service")
431 probe = source("host-probe")
432 assert probe["location"] == "local" and probe["state"] == "failed", probe
433 assert "host-probe.service" in probe["detail"] and probe["unit_states"][0]["ExecMainStatus"] == "3", probe
434 assert probe["unit_states"][0]["Id"] == "host-probe.service" and "Environment" not in probe["unit_states"][0], probe
435 assert [s for s in of(observe("sources"), "source") if s["name"] == "host-probe"][0]["state"] == "failed"
436 shown = host.succeed("valley telemetry --remote git@localhost:project.git read --source=host-probe --logs")
437 assert "host-probe says why" in shown and "untrusted output" in shown, shown
438 assert "host-probe says why" not in json.dumps(observe("read --source=host-probe")), "lifecycle only without --logs"
439
440 with subtest("a reader sees a worker's slow check build while it builds, and its interruption after a kill"):
441 good = ready("good", "good.txt")
442 host.succeed("systemctl start --no-block valley-worker.service")
443 host.wait_until_succeeds(
444 "valley telemetry --remote git@localhost:project.git read --source=worker --logs | grep -q 'slow tick 3'",
445 timeout=180,
446 )
447 ls = observe("read --source=worker --limit=1000")
448 starts = records(ls, type="check.build-start", check="slow")
449 assert starts and not records(ls, type="check.result", check="slow"), ls
450 assert starts[-1]["head"] == good and starts[-1]["tree"] and starts[-1]["change"], starts[-1]
451 shown = host.succeed("valley telemetry --remote git@localhost:project.git read --source=worker --logs")
452 assert "untrusted output" in shown and "\\x1b[31mred" in shown and "\x1b" not in shown, shown
453 assert "\x1b" not in "".join(json.dumps(l) for l in observe("read --source=worker --logs"))
454 assert not [r for r in observe("read --source=worker") if "slow tick" in json.dumps(r)]
455
456 host.succeed("systemctl kill --signal=KILL valley-worker.service")
457 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
458 worker = source("worker")
459 assert worker["state"] == "stale" and "interrupted" in worker["detail"], worker
460 assert worker["unit_states"][0]["Result"] == "signal", worker
461 lifecycle = of(observe("read --source=worker"), "lifecycle")
462 assert any("status=9/KILL" in l["message"] for l in lifecycle), lifecycle
463
464 host.succeed("systemctl start valley-worker.service")
465 state = source("worker")["exported_state"]
466 assert state["pass"] is None, state
467 kinds = [(a["kind"], a["result"]) for a in state["recent"]]
468 assert ("pass", "interrupted") in kinds and ("pass", "passed") in kinds and ("build", "passed") in kinds, kinds
469 interrupted = [a for a in state["recent"] if a["result"] == "interrupted"][0]
470 assert interrupted["inferred"] and interrupted["head"] == good, interrupted
471 ls = observe("read --source=worker --limit=1000")
472 assert records(ls, type="pass.interrupted") and records(ls, type="publish.end")
473 results = records(ls, type="check.result")
474 assert {r["check"] for r in results} >= {"slow", "fast"}, results
475 assert all(r["data"]["result"] == "passed" and r["data"]["build_ms"] >= 0 for r in results[-2:]), results
476
477 with subtest("a failed batch leaves a backoff naming the change, its head, its tree and why"):
478 broken = ready("broken", "broken.txt", "${broken}")
479 host.fail("systemctl start valley-worker.service")
480 state = source("worker")["exported_state"]
481 failure = [f for f in state["failures"] if f["head"] == broken]
482 assert failure and failure[0]["tree"] and failure[0]["change"] and failure[0]["retry"], state
483 assert "slow failed" in failure[0]["reason"], failure
484 backoff = records(observe("read --source=worker --limit=1000"), type="backoff")
485 assert backoff and backoff[-1]["head"] == broken and backoff[-1]["data"]["retry"], backoff
486 assert "broken check says why" in host.succeed("valley telemetry --remote git@localhost:project.git read --source=worker --logs")
487 # Records survive the collector's restart: each connection is a
488 # collector of its own, and its state is on disk.
489 host.succeed("systemctl restart valley-telemetry.socket")
490 assert records(observe("read --source=worker --limit=1000"), type="backoff")
491
492 with subtest("an observer watches alice's approval build a slow and a fast check side by side"):
493 fresh = ready("fresh", "fresh.txt", rebuild=True)
494 settle()
495 host.succeed(
496 "systemd-run --unit=approve-fresh --uid=alice --setenv=HOME=/home/alice"
497 " --setenv=PATH=/run/wrappers/bin:/run/current-system/sw/bin"
498 " --setenv=VALLEY_ATTEST_KEY=/home/alice/keys/alice --setenv=VALLEY_ATTEST_NAME=alice/attestations"
499 " --working-directory=/home/alice/project --remain-after-exit"
500 f" valley approve --build-here --head {fresh} fresh"
501 )
502 def fresh_ended():
503 assert host.succeed("systemctl show -p Result --value approve-fresh").strip() == "success", "the approval failed"
504 return host.succeed("systemctl show -p SubState --value approve-fresh").strip() == "exited"
505 seen = side_by_side(fresh, fresh_ended)
506 assert all(r["data"]["untrusted"] for r in records(seen, type="check.output"))
507 assert not records(observe("read --source=report.alice --limit=1000"), type="check.output")
508 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value approve-fresh)\" = exited", timeout=300)
509 assert host.succeed("systemctl show -p ExecMainStatus --value approve-fresh").strip() == "0"
510 ls, _ = filed(fresh)
511 mine = [r for r in of(ls, "record") if r.get("head") == fresh]
512 types = [r["type"] for r in mine]
513 for want in ["approve.start", "approve.policy", "approve.coverage", "approve.checks", "run.start", "check.result", "evidence.stored", "run.end", "approve.request", "approve.end"]:
514 assert want in types, (want, types)
515 start = [r for r in mine if r["type"] == "approve.start"][0]
516 assert start["principal"] == "alice" and start["received"] and start["producer"]["version"] and start["producer"]["exe"].startswith("/nix/store/"), start
517 cover = [r for r in mine if r["type"] == "approve.coverage"][0]["data"]
518 assert cover["reused"] == [] and sorted(cover["missing"]) == ["fast", "slow"], cover
519 slow_r = [r for r in mine if r["type"] == "check.result" and r["check"] == "slow"][0]["data"]
520 fast_r = [r for r in mine if r["type"] == "check.result" and r["check"] == "fast"][0]["data"]
521 assert fast_r["build_ended"] < slow_r["build_ended"] and fast_r["build_ms"] < slow_r["build_ms"], (fast_r, slow_r)
522 assert [r for r in mine if r["type"] == "approve.request"][0]["data"]["result"] == "pushed"
523 assert [r for r in mine if r["type"] == "approve.end"][0]["data"]["result"] == "filed"
524
525 with subtest("an observer watches an approval made from review, after a refused attempt in the same session"):
526 reviewed = ready("reviewed", "reviewed.txt", rebuild=True)
527 # One review session answers a, is refused for want of a key,
528 # and answers a again once the key is there. Its answers come
529 # through a FIFO a sleeping writer holds open between them.
530 review = shlex.quote(
531 "sudo -u alice -H env VALLEY_ATTEST_KEY=/home/alice/keys/later VALLEY_ATTEST_NAME=alice/attestations"
532 " bash -c 'cd /home/alice/project && exec valley review --build-here reviewed'"
533 " < /tmp/review.fifo > /tmp/review.out 2>&1"
534 )
535 host.succeed("rm -f /tmp/review.fifo /home/alice/keys/later && mkfifo -m 600 /tmp/review.fifo")
536 settle()
537 host.succeed(f"setsid -f sh -c {review} < /dev/null > /dev/null 2>&1")
538 host.succeed("setsid -f sh -c 'echo $$ > /tmp/review.holder; exec sleep 900 > /tmp/review.fifo' < /dev/null > /dev/null 2>&1")
539 host.wait_until_succeeds("grep -q 'pprove' /tmp/review.out", timeout=120)
540 host.succeed("echo a > /tmp/review.fifo")
541 refused: list = []
542 for _ in range(60):
543 ls = observe("read --source=report.alice --limit=1000")
544 refused = [r for r in records(ls, type="approve.end") if r["head"] == reviewed and r["data"]["result"] == "refused"]
545 if refused:
546 break
547 time.sleep(1)
548 assert refused, "the refused approval from review was never observed"
549 first = refused[0]["run"]
550 first_types = [r["type"] for r in of(ls, "record") if r.get("run") == first]
551 assert first_types[:3] == ["approve.start", "approve.policy", "approve.coverage"] and "approve.checks" not in first_types, first_types
552
553 host.succeed("install -m 600 -o alice ${keys}/alice /home/alice/keys/later")
554 host.wait_until_succeeds("test $(grep -o 'pprove' /tmp/review.out | wc -l) -ge 2", timeout=60)
555 host.succeed("echo a > /tmp/review.fifo")
556 side_by_side(reviewed, lambda: host.execute("grep -q ' approved' /tmp/review.out")[0] == 0)
557 host.wait_until_succeeds("grep -q ' approved' /tmp/review.out", timeout=300)
558 host.succeed("kill $(cat /tmp/review.holder)")
559 ls, second = filed(reviewed)
560 assert len(second) == 1 and second[0]["run"] != first, second
561 run = second[0]["run"]
562 types = [r["type"] for r in of(ls, "record") if r.get("run") == run]
563 for want in ["approve.start", "approve.policy", "approve.coverage", "approve.checks", "approve.request", "approve.end"]:
564 assert want in types, (want, types)
565 assert [r for r in records(ls, type="approve.request") if r["run"] == run][0]["data"]["result"] == "pushed"
566 slow = [r for r in records(ls, type="check.result", check="slow") if r["run"] == run + "-checks"]
567 assert slow and slow[0]["data"]["result"] == "passed", slow
568 assert len([r for r in records(ls, type="approve.end") if r["run"] == first]) == 1
569
570 with subtest("an approval reusing the worker's evidence beside a local check, and one reusing everything, are observable"):
571 mixed = ready("mixed", "local/mixed.txt")
572 host.succeed("systemctl start valley-worker.service")
573 pushing(f"valley approve --head {mixed} mixed")
574 pushing(f"valley approve --head {good} good")
575 as_alice("valley telemetry flush")
576 ls = observe("read --source=report.alice --limit=1000")
577 cover = [r for r in records(ls, type="approve.coverage") if r["head"] == mixed][0]["data"]
578 assert sorted(cover["reused"]) == ["fast", "slow"] and cover["missing"] == ["local"], cover
579 assert len(cover["reused_by"]) == 2 and all("worker" in s for s in cover["reused_by"]), cover
580 local = [r for r in records(ls, type="check.result", check="local") if r["head"] == mixed]
581 assert local and local[0]["data"]["result"] == "passed", local
582 cover = [r for r in records(ls, type="approve.coverage") if r["head"] == good][0]["data"]
583 assert sorted(cover["reused"]) == ["fast", "slow"] and cover["missing"] == [], cover
584 good_types = [r["type"] for r in of(ls, "record") if r.get("head") == good]
585 assert "approve.checks" not in good_types and "approve.end" in good_types, good_types
586 host.wait_until_succeeds(
587 "valley telemetry --remote git@localhost:project.git --json read --source=integrator | grep -q '\"type\":\"decision\"'",
588 timeout=120,
589 )
590 decision = records(observe("read --source=integrator"), type="decision")[-1]
591 assert decision["project"] and decision["data"]["outcome"] and "duration_ms" in decision["data"], decision
592
593 with subtest("checks --build passes once origin holds every check's evidence, and otherwise says why not"):
594 # Two commits ask at once, from two worktrees, and one worker pass
595 # builds both. The first passes. The second's slow check fails, so
596 # its outcome is not established, with the worker's records and
597 # build output for its tree.
598 requests = f"{git} -C /srv/git/project.git for-each-ref refs/the-valley/check-requests/"
599 host.succeed("git clone --quiet git@localhost:project.git /root/project && git -C /root/project config valley.principal operator")
600 for branch, cp in [("asked", ""), ("asked-broken", "cp ${broken} slow.sh && ")]:
601 host.succeed(f"git -C /root/project worktree add --quiet -b {branch} /root/{branch} origin/main && cd /root/{branch} && {cp}"
602 f"echo {branch} > {branch}.txt && git add -A && {commit} -m {branch}")
603 asking = shlex.quote(f"cd /root/{branch} && valley checks --build > /tmp/{branch}.out 2>&1; echo $? > /tmp/{branch}.status")
604 host.succeed(f"setsid -f sh -c {asking} < /dev/null > /dev/null 2>&1")
605 host.wait_until_succeeds(f"test $({requests}operator/ | wc -l) = 2", timeout=120)
606 host.execute("systemctl start valley-worker.service")
607 host.wait_until_succeeds("test -s /tmp/asked.status && test -s /tmp/asked-broken.status", timeout=300)
608 passed, failed = host.succeed("cat /tmp/asked.out"), host.succeed("cat /tmp/asked-broken.out")
609 assert host.succeed("cat /tmp/asked.status").strip() == "0" and "2 checks passed" in passed, passed
610 assert host.succeed("cat /tmp/asked-broken.status").strip() == "1", failed
611 assert "not established" in failed and "slow failed" in failed and "| broken check says why" in failed, failed
612 assert not host.succeed(requests), "a request was left on origin"
613
614 with subtest("approval and pushes go on when telemetry cannot be reached, and each run's records go only where its run began"):
615 def timed_approve(branch, path):
616 head = ready(branch, path)
617 settle()
618 began = time.monotonic()
619 as_alice(f"valley approve --head {head} {branch}")
620 return time.monotonic() - began, head
621 as_alice("git config valley.telemetry false")
622 plain, _ = timed_approve("plain", "policy/plain.txt")
623 as_alice("git config valley.telemetry true")
624 host.succeed("systemctl stop valley-telemetry.socket")
625 down, head_down = timed_approve("down", "policy/down.txt")
626 as_alice("git config valley.telemetry.remote ssh://git@192.0.2.1/project.git")
627 unreachable, head_away = timed_approve("away", "policy/away.txt")
628 as_alice("git config --unset valley.telemetry.remote")
629 print(f"approve took {plain:.1f}s plain, {down:.1f}s with the collector down, {unreachable:.1f}s with it unreachable")
630 # A guest under load varies one approval by seconds; a wait on
631 # telemetry would be its 20-second flush deadline.
632 assert down < plain + 15 and unreachable < plain + 15, (plain, down, unreachable)
633 pushing("git push --quiet origin HEAD:refs/heads/still-pushes")
634 host.fail("sudo -u alice -H bash -c 'cd /home/alice/project && valley telemetry --remote origin flush'")
635 host.succeed("systemctl start valley-telemetry.socket")
636 time.sleep(12)
637 as_alice("valley telemetry --remote origin flush")
638 assert "0 records sent to ssh://git@localhost" in as_alice("valley telemetry --remote origin flush 2>&1")
639 # The run begun while the telemetry remote named 192.0.2.1 stays
640 # bound to it: a flush from the same checkout, back on origin,
641 # tries that destination and sends its records nowhere else.
642 status, out = as_alice("valley telemetry flush 2>&1", check=False)
643 assert status != 0 and "ssh://git@192.0.2.1" in out, out
644 ls = observe("read --source=report.alice --limit=1000")
645 ends = [r for r in records(ls, type="approve.end") if r["head"] == head_down]
646 assert len(ends) == 1 and ends[0]["data"]["result"] == "filed", ends
647 assert not [r for r in of(ls, "record") if r.get("head") == head_away], "a run bound to another destination reached this one"
648
649 with subtest("every command records its verb, flags, status, time and phases, never a value, and only with telemetry on"):
650 def commands(verb):
651 # Only origin's spool: the outage left one bound to 192.0.2.1.
652 as_alice("valley telemetry --remote origin flush")
653 ls = observe("read --source=report.alice --limit=1000")
654 return ls, [r for r in records(ls, type="command") if r["data"]["verb"] == verb]
655 as_alice("valley pending --json > /tmp/on.json")
656 as_alice("valley status --json zx81q-secret", check=False)
657 ls, pending = commands("pending")
658 d = pending[-1]["data"]
659 assert d["status"] == 0 and d["flags"] == ["--json"] and pending[-1].get("project"), pending[-1]
660 assert d["elapsed_ms"] >= d["fetch_ms"] > 0 and d["fetch_procs"] > 0 and "records_ms" in d, d
661 named = [r for r in records(ls, type="command") if r["data"]["verb"] == "status"]
662 assert named and named[-1]["data"]["status"] == 1 and named[-1]["data"]["flags"] == ["--json"], named
663 assert "zx81q" not in json.dumps(ls), "an argument's value reached the report stream"
664 # Off: no record, and no spool file, under a state home of its own.
665 as_alice("git config --unset valley.telemetry")
666 off = as_alice("XDG_STATE_HOME=/tmp/alice-off valley pending --json > /tmp/off.json"
667 " && XDG_STATE_HOME=/tmp/alice-off valley status --json zx81q-secret; echo $?")
668 host.fail("test -e /tmp/alice-off")
669 assert len(commands("pending")[1]) == len(pending)
670 # Unreachable: the same output and exit status as off.
671 as_alice("git config valley.telemetry true && git config valley.telemetry.remote ssh://git@192.0.2.1/project.git")
672 away = as_alice("valley pending --json > /tmp/away.json && valley status --json zx81q-secret; echo $?")
673 as_alice("git config --unset valley.telemetry.remote")
674 assert away == off and host.succeed("cat /tmp/away.json") == host.succeed("cat /tmp/off.json"), (away, off)
675
676 with subtest("the server holds every request to its limits"):
677 big = '{"type":"approve.start","time":"2026-01-01T00:00:00.000Z","client_id":"0123456789abcdef:1","data":{"x":"' + "y" * 20000 + '"}}'
678 host.succeed(f"echo '{big}' > /tmp/big.json")
679 answer = lines(host.succeed(raw("alice", "valley-telemetry report") + " < /tmp/big.json"))
680 assert of(answer, "ack")[0]["rejected"] == 1 and of(answer, "ack")[0]["accepted"] == 0, answer
681 host.execute("timeout 5 " + raw("operator", "valley-telemetry follow --seconds=99999 --source=telemetry") + " < /dev/null > /tmp/follow.json")
682 header = of(lines(host.succeed("head -1 /tmp/follow.json")), "header")[0]
683 assert header["limits"]["follow_seconds"] == 300, header
684 header = of(observe("read --limit=999999"), "header")[0]
685 assert header["limits"]["read_limit"] == 1000, header
686 '';
687 };
688}