gunk-dev/the-valley

telemetry.nix

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