gunk-dev/the-valley

telemetry.nix

sourcedd85a8e116a8main's published tip history
33.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.
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 reporters = [
176 "alice"
177 "receiver"
178 ];
179 remoteSources = [
180 {
181 name = "remote-receiver";
182 description = "a web receiver on another machine";
183 principal = "receiver";
184 }
185 ];
186 };
187 };
188 systemd.timers.valley-worker.timerConfig.OnActiveSec = lib.mkForce "1h";
189 nix.settings.experimental-features = [
190 "nix-command"
191 "flakes"
192 ];
193 nix.settings.substituters = lib.mkForce [ ];
194 networking.useDHCP = false;
195 };
196
197 testScript = ''
198 import json
199 import shlex
200 import time
201
202 host.wait_for_unit("multi-user.target")
203 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
204
205 git = "sudo -u git git"
206 ssh_opts = "-o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
207 commit = "git -c user.name=t -c user.email=t@example.org commit --quiet"
208
209 def raw(who, command, extra=""):
210 """The telemetry command as a session sends it, with who's key."""
211 return f"ssh {ssh_opts} {extra} -i /root/keys/{who} git@localhost {shlex.quote(command)}"
212
213 def lines(out):
214 return [json.loads(l) for l in out.splitlines() if l.strip()]
215
216 def observe(args):
217 """valley telemetry as the operator, outside any checkout."""
218 return lines(host.succeed(f"cd / && valley telemetry --remote git@localhost:project.git --json {args}"))
219
220 def of(ls, kind):
221 return [l for l in ls if l.get("kind") == kind]
222
223 def records(ls, **match):
224 return [l for l in of(ls, "record") if all(l.get(k) == v for k, v in match.items())]
225
226 def source(name):
227 return [s for s in of(observe("snapshot"), "source") if s["name"] == name][0]
228
229 def as_alice(cmd, check=True):
230 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)}"
231 return host.succeed(full) if check else host.execute(full)
232
233 def registry(worker):
234 def human(who, signs):
235 s = f', signs: "{who}/attestations"' if signs else ""
236 return [
237 f'"{who}": {{',
238 ' kind: "human"',
239 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{blob[who]}"{s}}}]',
240 ' grants: {push: boundary: "push", govern: boundary: "registry"}',
241 "}",
242 ]
243 principals = human("contributor", False) + human("alice", True)
244 if worker:
245 principals += [
246 '"worker": {',
247 ' kind: "machine"',
248 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{worker}", signs: "worker/attestations"}}]',
249 ' grants: push: boundary: "push"',
250 ' expires: "2099-01-01"',
251 "}",
252 ]
253 return "\n".join(['package identity', 'boundaries: {"push": kind: "git-push", "registry": kind: "registry"}',
254 'genesis: "contributor"', "principals: {"] + principals + ["}"])
255
256 blob = {"contributor": "${pubBlob "contributor"}", "alice": "${pubBlob "alice"}"}
257
258 def land_instance(worker):
259 host.succeed(
260 "rm -rf /tmp/instance && mkdir -p /tmp/instance/policy/instance /tmp/instance/identity",
261 "cp ${floor} /tmp/instance/policy/instance/floor.cue",
262 f"cat > /tmp/instance/identity/registry.cue <<'EOF'\n{registry(worker)}\nEOF",
263 f"cd /tmp/instance && git init --quiet --initial-branch=main && git add -A && {commit} -m instance",
264 "chown -R git:git /tmp/instance",
265 f"{git} -C /srv/git/instance.git fetch --quiet --force /tmp/instance main:refs/heads/main",
266 "systemctl start valley-identity.service",
267 )
268
269 def settle():
270 """Waits out a valley-init run: a unit that requires it starts it
271 again, such as the identity timer's compile, and pushes pause
272 while it runs."""
273 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-init)\" != activating", timeout=60)
274
275 def pushing(cmd):
276 """Runs a push of alice's, again if a valley-init run paused it."""
277 for attempt in range(3):
278 settle()
279 status, out = as_alice(cmd, check=False)
280 if status == 0:
281 return out
282 time.sleep(2)
283 raise Exception(f"alice could not run {cmd}: {out}")
284
285 def ready(branch, path, script=None, rebuild=False):
286 """A change by alice: one new file, and the slow check's script
287 given, or changed so that its derivation is built again."""
288 cp = f"cp {script} slow.sh && " if script else ""
289 if rebuild:
290 cp += f"echo '# {branch}' >> slow.sh && "
291 as_alice(
292 f"git fetch --quiet origin && git checkout --quiet -B {branch} origin/main && {cp}"
293 f"mkdir -p $(dirname {path}) && echo {branch} > {path} && git add -A && {commit} -m {branch}"
294 )
295 pushing(f"git push --quiet origin {branch} && valley ready {branch}")
296 return as_alice(f"git rev-parse {branch}").strip()
297
298 with subtest("the instance and the project are seeded, and alice has a checkout"):
299 land_instance(None)
300 host.succeed(
301 "mkdir -p /tmp/project/policy",
302 "cp ${flake} /tmp/project/flake.nix",
303 "cp ${flakeLock} /tmp/project/flake.lock",
304 "cp ${slow} /tmp/project/slow.sh",
305 "cp ${fast} /tmp/project/fast.sh",
306 "echo 'git@host:instance.git' > /tmp/project/policy/valley",
307 f"cd /tmp/project && git init --quiet --initial-branch=main && git add -A && {commit} -m project",
308 "chown -R git:git /tmp/project",
309 f"{git} -C /srv/git/project.git fetch --quiet /tmp/project main:refs/heads/main",
310 "mkdir -p /root/keys /root/.ssh && cp ${keys}/* /root/keys/ && chmod 600 /root/keys/*",
311 "printf 'Host localhost host\\n IdentityFile /root/keys/operator\\n IdentitiesOnly yes\\n"
312 " StrictHostKeyChecking no\\n UserKnownHostsFile /dev/null\\n' > /root/.ssh/config",
313 "mkdir -p /home/alice/keys /home/alice/.ssh && install -m 600 ${keys}/alice /home/alice/keys/alice",
314 "printf 'Host localhost host\\n IdentityFile /home/alice/keys/alice\\n IdentitiesOnly yes\\n"
315 " StrictHostKeyChecking no\\n UserKnownHostsFile /dev/null\\n' > /home/alice/.ssh/config",
316 "chown -R alice /home/alice",
317 )
318 host.succeed("sudo -u alice -H git clone --quiet git@localhost:project.git /home/alice/project")
319 as_alice("git config valley.principal alice && git config user.name alice && git config user.email alice@example.org"
320 " && git config valley.telemetry true")
321 # The worker makes its key, and is enrolled.
322 host.fail("systemctl start valley-worker.service")
323 land_instance(" ".join(host.succeed("cat /var/lib/valley-worker/key.pub").split()[:2]))
324 host.wait_until_succeeds(
325 f"{git} -C /srv/git/instance.git cat-file blob refs/the-valley/signers:known-signers | grep -q '^alice/attestations+'",
326 timeout=60,
327 )
328
329 with subtest("an enrolled observer reads the catalog, and nobody else does"):
330 srcs = {s["name"]: s for s in of(observe("sources"), "source")}
331 for name in ["worker", "integrator", "identity", "signers", "mirrors", "convergence", "telemetry", "report.alice"]:
332 assert srcs[name]["enabled"], (name, srcs[name])
333 for name in ["bus", "backup", "web-publisher", "web-receiver", "restacker"]:
334 assert srcs[name]["state"] == "disabled", srcs[name]
335 assert srcs["remote-receiver"]["location"] == "remote" and srcs["remote-receiver"]["state"] == "unavailable", srcs["remote-receiver"]
336 assert srcs["integrator"]["not_instrumented"], srcs["integrator"]
337 assert srcs["worker"]["configured"]["attest"].startswith("/nix/store/"), srcs["worker"]
338 props = srcs["worker"]["unit_states"][0]
339 assert "Environment" not in props and props["Id"] == "valley-worker.service", props
340
341 for who, command, said in [
342 ("contributor", "valley-telemetry sources", "does not hold the telemetry observe grant"),
343 ("stranger", "valley-telemetry sources", "a key that names a principal"),
344 ("alice", "valley-telemetry sources", "does not hold the telemetry observe grant"),
345 ("operator", "valley-telemetry report", "does not hold the telemetry report grant"),
346 ("operator", "valley-telemetry sources; id", "not a telemetry operation"),
347 ("operator", "valley-telemetry sources && id", "is not a flag"),
348 ("operator", "valley-telemetry read --source=../../var/lib/valley-worker/key", "not a source name"),
349 ("operator", "valley-telemetry read --source=valley-*", "not a source name"),
350 ("operator", "valley-telemetry read --unit=sshd.service", "takes no --unit"),
351 ("operator", "valley-telemetry exec id", "not a telemetry operation"),
352 ("operator", "valley-telemetry read --source=nosuch", "no source is named nosuch"),
353 ]:
354 status, out = host.execute(raw(who, command) + " < /dev/null 2>&1")
355 assert status != 0 and said in out and "uid=" not in out, (who, command, status, out)
356 for command in ["id", "sh -c id", "systemctl restart valley-worker", "journalctl -u valley-worker"]:
357 status, out = host.execute(raw("operator", command) + " < /dev/null 2>&1")
358 assert status != 0 and "uid=" not in out and '"kind"' not in out, (command, out)
359 # A principal the client names in its environment is no principal.
360 status, out = host.execute(raw("contributor", "valley-telemetry sources", "-o SetEnv=VALLEY_PRINCIPAL=operator") + " 2>&1")
361 assert status != 0 and '"kind": "source"' not in out and '"kind":"source"' not in out, out
362 # A forced fetch-only key runs its forced command whatever it asks.
363 status, out = host.execute(raw("fetcher", "valley-telemetry sources") + " < /dev/null 2>&1")
364 assert '"kind"' not in out and "refs/heads/main" in out, out
365 # Reading is open while pushes are held.
366 host.succeed("touch /srv/git/.valley-hold")
367 assert of(observe("sources"), "end")
368 host.fail("sudo -u alice -H bash -c 'cd /home/alice/project && git push --quiet origin HEAD:refs/heads/held'")
369 host.succeed("rm /srv/git/.valley-hold")
370
371 with subtest("private keys stay private, and the diagnostics are the collector's alone to read"):
372 for user in ["git", "valley-telemetry"]:
373 host.fail(f"sudo -u {user} cat /var/lib/valley-worker/key")
374 host.fail(f"sudo -u {user} ls /var/lib/valley-worker")
375 host.fail("sudo -u git ls /var/lib/valley-telemetry/worker")
376 host.fail("sudo -u git ls /var/lib/valley-telemetry/collector")
377 assert "systemd-journal" not in host.succeed("id -nG git")
378 assert host.succeed("stat -c '%a %U %G' /var/lib/valley-telemetry/worker").strip() == "2750 valley-worker valley-telemetry"
379 assert host.succeed("stat -c '%a %U %G' /var/lib/valley-worker").strip() == "700 valley-worker valley-worker"
380 assert host.succeed("stat -c '%a %U' /run/valley-telemetry.sock").strip() == "600 git"
381
382 with subtest("a reader sees a worker's slow check build while it builds, and its interruption after a kill"):
383 good = ready("good", "good.txt")
384 host.succeed("systemctl start --no-block valley-worker.service")
385 host.wait_until_succeeds(
386 "valley telemetry --remote git@localhost:project.git read --source=worker --logs | grep -q 'slow tick 3'",
387 timeout=180,
388 )
389 ls = observe("read --source=worker --limit=1000")
390 starts = records(ls, type="check.build-start", check="slow")
391 assert starts and not records(ls, type="check.result", check="slow"), ls
392 assert starts[-1]["head"] == good and starts[-1]["tree"] and starts[-1]["change"], starts[-1]
393 shown = host.succeed("valley telemetry --remote git@localhost:project.git read --source=worker --logs")
394 assert "untrusted output" in shown and "\\x1b[31mred" in shown and "\x1b" not in shown, shown
395 assert "\x1b" not in "".join(json.dumps(l) for l in observe("read --source=worker --logs"))
396 assert not [r for r in observe("read --source=worker") if "slow tick" in json.dumps(r)]
397
398 host.succeed("systemctl kill --signal=KILL valley-worker.service")
399 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
400 worker = source("worker")
401 assert worker["state"] == "stale" and "interrupted" in worker["detail"], worker
402 assert worker["unit_states"][0]["Result"] == "signal", worker
403 lifecycle = of(observe("read --source=worker"), "lifecycle")
404 assert any("status=9/KILL" in l["message"] for l in lifecycle), lifecycle
405
406 host.succeed("systemctl start valley-worker.service")
407 state = source("worker")["exported_state"]
408 assert state["pass"] is None, state
409 kinds = [(a["kind"], a["result"]) for a in state["recent"]]
410 assert ("pass", "interrupted") in kinds and ("pass", "passed") in kinds and ("build", "passed") in kinds, kinds
411 interrupted = [a for a in state["recent"] if a["result"] == "interrupted"][0]
412 assert interrupted["inferred"] and interrupted["head"] == good, interrupted
413 ls = observe("read --source=worker --limit=1000")
414 assert records(ls, type="pass.interrupted") and records(ls, type="publish.end")
415 results = records(ls, type="check.result")
416 assert {r["check"] for r in results} >= {"slow", "fast"}, results
417 assert all(r["data"]["result"] == "passed" and r["data"]["build_ms"] >= 0 for r in results[-2:]), results
418
419 with subtest("a failed batch leaves a backoff naming the change, its head, its tree and why"):
420 broken = ready("broken", "broken.txt", "${broken}")
421 host.fail("systemctl start valley-worker.service")
422 state = source("worker")["exported_state"]
423 failure = [f for f in state["failures"] if f["head"] == broken]
424 assert failure and failure[0]["tree"] and failure[0]["change"] and failure[0]["retry"], state
425 assert "slow failed" in failure[0]["reason"], failure
426 backoff = records(observe("read --source=worker --limit=1000"), type="backoff")
427 assert backoff and backoff[-1]["head"] == broken and backoff[-1]["data"]["retry"], backoff
428 assert "broken check says why" in host.succeed("valley telemetry --remote git@localhost:project.git read --source=worker --logs")
429 # Records survive the collector's restart: each connection is a
430 # collector of its own, and its state is on disk.
431 host.succeed("systemctl restart valley-telemetry.socket")
432 assert records(observe("read --source=worker --limit=1000"), type="backoff")
433
434 with subtest("an observer watches alice's approval build a slow and a fast check side by side"):
435 fresh = ready("fresh", "fresh.txt", rebuild=True)
436 settle()
437 host.succeed(
438 "systemd-run --unit=approve-fresh --uid=alice --setenv=HOME=/home/alice"
439 " --setenv=PATH=/run/wrappers/bin:/run/current-system/sw/bin"
440 " --setenv=VALLEY_ATTEST_KEY=/home/alice/keys/alice --setenv=VALLEY_ATTEST_NAME=alice/attestations"
441 " --working-directory=/home/alice/project --remain-after-exit"
442 f" valley approve --head {fresh} fresh"
443 )
444 seen: list = []
445 for _ in range(120):
446 ls = observe("read --source=report.alice --limit=1000 --logs")
447 fast_done = [r for r in records(ls, type="check.result", check="fast") if r["head"] == fresh]
448 slow_done = [r for r in records(ls, type="check.result", check="slow") if r["head"] == fresh]
449 slow_out = [r for r in records(ls, type="check.output", check="slow") if "slow tick" in r["data"]["text"]]
450 if fast_done and slow_out and not slow_done:
451 seen = ls
452 break
453 assert not slow_done, "the slow check ended before the observer saw the fast one end"
454 assert host.succeed("systemctl show -p Result --value approve-fresh").strip() == "success", "the approval failed"
455 time.sleep(1)
456 assert seen, "never saw the fast check done while the slow one built"
457 assert all(r["data"]["untrusted"] for r in records(seen, type="check.output"))
458 assert not records(observe("read --source=report.alice --limit=1000"), type="check.output")
459 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value approve-fresh)\" = exited", timeout=300)
460 assert host.succeed("systemctl show -p ExecMainStatus --value approve-fresh").strip() == "0"
461 time.sleep(4)
462 host.succeed("sudo -u alice -H bash -c 'cd /home/alice/project && valley telemetry flush'")
463 ls = observe("read --source=report.alice --limit=1000")
464 mine = [r for r in of(ls, "record") if r.get("head") == fresh]
465 types = [r["type"] for r in mine]
466 for want in ["approve.start", "approve.policy", "approve.coverage", "approve.checks", "run.start", "check.result", "evidence.stored", "run.end", "approve.request", "approve.end"]:
467 assert want in types, (want, types)
468 start = [r for r in mine if r["type"] == "approve.start"][0]
469 assert start["principal"] == "alice" and start["received"] and start["producer"]["version"] and start["producer"]["exe"].startswith("/nix/store/"), start
470 cover = [r for r in mine if r["type"] == "approve.coverage"][0]["data"]
471 assert cover["reused"] == [] and sorted(cover["missing"]) == ["fast", "slow"], cover
472 slow_r = [r for r in mine if r["type"] == "check.result" and r["check"] == "slow"][0]["data"]
473 fast_r = [r for r in mine if r["type"] == "check.result" and r["check"] == "fast"][0]["data"]
474 assert fast_r["build_ended"] < slow_r["build_ended"] and fast_r["build_ms"] < slow_r["build_ms"], (fast_r, slow_r)
475 assert [r for r in mine if r["type"] == "approve.request"][0]["data"]["result"] == "pushed"
476 assert [r for r in mine if r["type"] == "approve.end"][0]["data"]["result"] == "filed"
477
478 with subtest("an observer watches an approval made from review, after a refused attempt in the same session"):
479 reviewed = ready("reviewed", "reviewed.txt", rebuild=True)
480 # One review session answers a, is refused for want of a key,
481 # and answers a again once the key is there. Its answers come
482 # through a FIFO a sleeping writer holds open between them.
483 review = shlex.quote(
484 "sudo -u alice -H env VALLEY_ATTEST_KEY=/home/alice/keys/later VALLEY_ATTEST_NAME=alice/attestations"
485 " bash -c 'cd /home/alice/project && exec valley review reviewed'"
486 " < /tmp/review.fifo > /tmp/review.out 2>&1"
487 )
488 host.succeed("rm -f /tmp/review.fifo /home/alice/keys/later && mkfifo -m 600 /tmp/review.fifo")
489 settle()
490 host.succeed(f"setsid -f sh -c {review} < /dev/null > /dev/null 2>&1")
491 host.succeed("setsid -f sh -c 'echo $$ > /tmp/review.holder; exec sleep 900 > /tmp/review.fifo' < /dev/null > /dev/null 2>&1")
492 host.wait_until_succeeds("grep -q 'pprove' /tmp/review.out", timeout=120)
493 host.succeed("echo a > /tmp/review.fifo")
494 refused: list = []
495 for _ in range(60):
496 ls = observe("read --source=report.alice --limit=1000")
497 refused = [r for r in records(ls, type="approve.end") if r["head"] == reviewed and r["data"]["result"] == "refused"]
498 if refused:
499 break
500 time.sleep(1)
501 assert refused, "the refused approval from review was never observed"
502 first = refused[0]["run"]
503 first_types = [r["type"] for r in of(ls, "record") if r.get("run") == first]
504 assert first_types[:3] == ["approve.start", "approve.policy", "approve.coverage"] and "approve.checks" not in first_types, first_types
505
506 host.succeed("install -m 600 -o alice ${keys}/alice /home/alice/keys/later")
507 host.wait_until_succeeds("test $(grep -o 'pprove' /tmp/review.out | wc -l) -ge 2", timeout=60)
508 host.succeed("echo a > /tmp/review.fifo")
509 live: list = []
510 for _ in range(120):
511 ls = observe("read --source=report.alice --limit=1000 --logs")
512 fast_done = [r for r in records(ls, type="check.result", check="fast") if r["head"] == reviewed]
513 if fast_done:
514 checks = fast_done[0]["run"]
515 slow_done = [r for r in records(ls, type="check.result", check="slow") if r["run"] == checks]
516 slow_out = [r for r in records(ls, type="check.output", check="slow") if r["run"] == checks and "slow tick" in r["data"]["text"]]
517 assert not slow_done, "the slow check ended before the observer saw the fast one end"
518 if slow_out:
519 live = ls
520 break
521 time.sleep(1)
522 assert live, "never saw the fast check done while the slow one built, in an approval from review"
523 host.wait_until_succeeds("grep -q '^Approved ' /tmp/review.out", timeout=300)
524 host.succeed("kill $(cat /tmp/review.holder)")
525 time.sleep(4)
526 as_alice("valley telemetry flush")
527 ls = observe("read --source=report.alice --limit=1000")
528 second = [r for r in records(ls, type="approve.end") if r["head"] == reviewed and r["data"]["result"] == "filed"]
529 assert len(second) == 1 and second[0]["run"] != first, second
530 run = second[0]["run"]
531 types = [r["type"] for r in of(ls, "record") if r.get("run") == run]
532 for want in ["approve.start", "approve.policy", "approve.coverage", "approve.checks", "approve.request", "approve.end"]:
533 assert want in types, (want, types)
534 assert [r for r in records(ls, type="approve.request") if r["run"] == run][0]["data"]["result"] == "pushed"
535 slow = [r for r in records(ls, type="check.result", check="slow") if r["run"] == run + "-checks"]
536 assert slow and slow[0]["data"]["result"] == "passed", slow
537 assert len([r for r in records(ls, type="approve.end") if r["run"] == first]) == 1
538
539 with subtest("an approval reusing the worker's evidence beside a local check, and one reusing everything, are observable"):
540 mixed = ready("mixed", "local/mixed.txt")
541 host.succeed("systemctl start valley-worker.service")
542 pushing(f"valley approve --head {mixed} mixed")
543 pushing(f"valley approve --head {good} good")
544 as_alice("valley telemetry flush")
545 ls = observe("read --source=report.alice --limit=1000")
546 cover = [r for r in records(ls, type="approve.coverage") if r["head"] == mixed][0]["data"]
547 assert sorted(cover["reused"]) == ["fast", "slow"] and cover["missing"] == ["local"], cover
548 assert len(cover["reused_by"]) == 2 and all("worker" in s for s in cover["reused_by"]), cover
549 local = [r for r in records(ls, type="check.result", check="local") if r["head"] == mixed]
550 assert local and local[0]["data"]["result"] == "passed", local
551 cover = [r for r in records(ls, type="approve.coverage") if r["head"] == good][0]["data"]
552 assert sorted(cover["reused"]) == ["fast", "slow"] and cover["missing"] == [], cover
553 good_types = [r["type"] for r in of(ls, "record") if r.get("head") == good]
554 assert "approve.checks" not in good_types and "approve.end" in good_types, good_types
555 host.wait_until_succeeds(
556 "valley telemetry --remote git@localhost:project.git --json read --source=integrator | grep -q '\"type\":\"decision\"'",
557 timeout=120,
558 )
559 decision = records(observe("read --source=integrator"), type="decision")[-1]
560 assert decision["project"] and decision["data"]["outcome"] and "duration_ms" in decision["data"], decision
561
562 with subtest("approval and pushes go on when telemetry cannot be reached, and each run's records go only where its run began"):
563 def timed_approve(branch, path):
564 head = ready(branch, path)
565 settle()
566 began = time.monotonic()
567 as_alice(f"valley approve --head {head} {branch}")
568 return time.monotonic() - began, head
569 as_alice("git config valley.telemetry false")
570 plain, _ = timed_approve("plain", "policy/plain.txt")
571 as_alice("git config valley.telemetry true")
572 host.succeed("systemctl stop valley-telemetry.socket")
573 down, head_down = timed_approve("down", "policy/down.txt")
574 as_alice("git config valley.telemetry.remote ssh://git@192.0.2.1/project.git")
575 unreachable, head_away = timed_approve("away", "policy/away.txt")
576 as_alice("git config --unset valley.telemetry.remote")
577 assert down < plain + 5 and unreachable < plain + 5, (plain, down, unreachable)
578 pushing("git push --quiet origin HEAD:refs/heads/still-pushes")
579 host.fail("sudo -u alice -H bash -c 'cd /home/alice/project && valley telemetry --remote origin flush'")
580 host.succeed("systemctl start valley-telemetry.socket")
581 time.sleep(12)
582 as_alice("valley telemetry --remote origin flush")
583 assert "0 records sent to ssh://git@localhost" in as_alice("valley telemetry --remote origin flush 2>&1")
584 # The run begun while the telemetry remote named 192.0.2.1 stays
585 # bound to it: a flush from the same checkout, back on origin,
586 # tries that destination and sends its records nowhere else.
587 status, out = as_alice("valley telemetry flush 2>&1", check=False)
588 assert status != 0 and "ssh://git@192.0.2.1" in out, out
589 ls = observe("read --source=report.alice --limit=1000")
590 ends = [r for r in records(ls, type="approve.end") if r["head"] == head_down]
591 assert len(ends) == 1 and ends[0]["data"]["result"] == "filed", ends
592 assert not [r for r in of(ls, "record") if r.get("head") == head_away], "a run bound to another destination reached this one"
593
594 with subtest("the server holds every request to its limits"):
595 big = '{"type":"approve.start","time":"2026-01-01T00:00:00.000Z","client_id":"0123456789abcdef:1","data":{"x":"' + "y" * 20000 + '"}}'
596 host.succeed(f"echo '{big}' > /tmp/big.json")
597 answer = lines(host.succeed(raw("alice", "valley-telemetry report") + " < /tmp/big.json"))
598 assert of(answer, "ack")[0]["rejected"] == 1 and of(answer, "ack")[0]["accepted"] == 0, answer
599 host.execute("timeout 5 " + raw("operator", "valley-telemetry follow --seconds=99999 --source=telemetry") + " < /dev/null > /tmp/follow.json")
600 header = of(lines(host.succeed("head -1 /tmp/follow.json")), "header")[0]
601 assert header["limits"]["follow_seconds"] == 300, header
602 header = of(observe("read --limit=999999"), "header")[0]
603 assert header["limits"]["read_limit"] == 1000, header
604 '';
605 };
606}