gunk-dev/the-valley

telemetry.nix

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