gunk-dev/the-valley

main.go

source34d12a6791c4main's published tip history
19.5 KiB
1// integrator is the Phase 3 controller that lands changes by verifying
2// evidence (archive/design/roadmap.md). It is a single writer per target stream and
3// the commit point of dcr-439b771: it applies a change's delta to the
4// current tip, checks per required check that the contributor's evidence
5// still transfers, and either fast-forwards the protected ref or says which
6// checks need new evidence.
7//
8// It runs no check. Verification happens where a change is authored, and
9// the serialized section here is digest comparison and a ref write.
10package main
11
12import (
13 "the-valley/composed"
14 "the-valley/note"
15
16 "flag"
17 "fmt"
18 "io"
19 "os"
20 "os/exec"
21 "path/filepath"
22 "strconv"
23 "strings"
24 "syscall"
25 "time"
26)
27
28const usage = `usage: integrator <command> [flags]
29
30 reconcile judge every pending integration request once, and act
31 watch reconcile on an interval until interrupted
32 publish-signers publish what clients verify transfer statements with
33 (integrator publish-signers --help)
34 help print this message
35
36The integrator polls, deliberately. Integration requests are durable in
37git — refs/the-valley/integration-requests/<target>/<change>, whose commit
38is the change's head — and the bus is a projection over them, so the
39controller level-triggers over the refs and converges. It publishes its
40outcomes to the bus and consumes nothing.
41
42The commit rule (dcr-439b771). The delta must apply cleanly to the tip; a
43conflict is new authorship, so every check is re-demanded. Then, per check
44the policy requires: a pure check transfers when its input-closure digest
45recomputed on the landed tree equals the attested one, and an effectful
46check transfers while no intervening landing has touched its requiring
47class's paths and its observation is inside the validity window the policy
48declares. Anything left standing lands; anything invalidated surfaces as
49one request-stale event naming exactly those checks, and the request stays
50for approving again.
51
52Before the commit rule, the change records can refuse a request. A request
53named c-<change ID> is that change's, and lands only while the record at
54refs/the-valley/changes/<target>/<change ID> says ready and lists the
55request's head as one of its versions'. A request of any name does not land
56while any commit it brings is a version of a change whose record is not
57ready. Both refuse with refused-not-ready. A request whose commits from the
58merge base to the head include a merge is refused-merge. A refused request
59stays where it is, and is decided again on every pass, so a change readied
60again is judged on the next one. Every record is read again just before
61the target moves, and a record never makes a request land.
62
63A withdrawn change voids its requests: each pass deletes the requests named
64for it or at one of its version heads, as voided-withdrawn, so readying it
65again needs a fresh approval. A record that does not read refuses nothing,
66and is reported with a WARNING on every pass that reads records.
67
68flags:
69 --repo DIR the served repository (default: here)
70 --project NAME the project name events carry (default: the repo's)
71 --key PATH ed25519 private key the integrator signs with
72 --name NAME the name that key signs under (default: this host's)
73 --known-signers F verifier keys whose attestations count, one per line
74 --signer-projects F signers whose attestations count only in the projects
75 listed beside them (see below); read once, at start, so a
76 changed file counts from the next start
77 --instance-repo DIR the bare repository carrying the group's floor; the
78 instance layer is read from its integrated tip
79 --instance-ref REF the ref whose tip carries it, a full ref name read by
80 that exact name (default refs/heads/main)
81 --instance-policy P the floor's directory in that tip (default
82 policy/instance); a floor that is not there is refused
83 --instance DIR a materialized instance layer, for a host that serves
84 no instance repository; one of this or --instance-repo
85 --project-policy P the project policy layer, relative to the target tip
86 (default policy/project); a target that carries none
87 is judged under the floor alone
88 --schema FILE the verification schema
89 --attest-schema F the attestation schema
90 --event-schema F the event vocabulary payloads are vetted against
91 --bus URL nats server to publish outcomes to; empty publishes
92 nothing and still prints every payload
93 --publish-queue DIR the host's queue of ref moves to publish: each landing
94 leaves its target's move there, and the host pushes it
95 to the mirrors as it does a pushed one; empty leaves
96 nothing
97 --wake DIR the host check worker's wake directory: each landing
98 creates the empty file DIR/due, before the mirror
99 queue and the bus, so the worker starts a pass;
100 empty marks nothing
101 --system SYSTEM flake system for closure recomputation
102 --interval D watch: how long to wait between passes (default 15s)
103 --now TIME judge as at this RFC 3339 instant, for the effectful
104 window; defaults to the clock
105
106Every program the controller runs reads git with replacement refs off. A
107replacement ref makes one object stand in for another wherever git looks
108it up, so a pushed refs/replace/* could swap the floor, a project's policy
109or a change's tree without moving any ref the controller watches. No GIT_
110variable is inherited except the safe.directory entries of command-scope
111configuration, and system and user configuration are not read.
112
113--known-signers is the registry's interim compilation. Identity is a
114governed registry (dcr-b87f6e8) whose entries compile into what each
115enforcement boundary checks; no compiler exists yet, so the file is
116supplied directly and is exactly what dcr-b87f6e8 calls the first
117compilation's output. An attestation signed by nobody in it does not
118transfer, and that is reported per check rather than treated as a forgery.
119
120--signer-projects restricts signers to projects. Each line names a signer,
121then the projects its attestations count in, separated by spaces:
122
123 worker/attestations the-valley app
124
125A signer the file names counts only in the projects on its line, where the
126project is the name events carry. In any other project its attestations
127are reported as signed by no signer the integrator holds. A line with a
128name and no project lets that signer count nowhere. A signer the file does
129not name counts wherever the known-signers file lets it. Blank lines and
130lines that open with # are skipped. Every name and project is a word of
131printable ASCII. A file that cannot be read, names a signer twice, holds
132a word that is not printable ASCII, names a signer no verifier key can
133carry, or names the integrator's own --name stops the integrator before
134it judges anything.
135
136The integrator's own signature never makes a check's attestation count.
137It countersigns the attestations a landing carried, and that vouches for
138the landing; a countersigned attestation counts, in any project, only
139through another signer who counts there.
140`
141
142// integrator is one controller: which repository it serves, who it signs
143// as, whose evidence it accepts, and where it finds the policy.
144type integrator struct {
145 repo string
146 project string
147 out *os.File
148 timings io.Writer // where timing lines go (timing.go); nil prints none
149
150 // The programs it drives. Every judgement about a statement or a note
151 // is attest's, and every judgement about what a policy says is the
152 // deriver's and cue's.
153 attest string
154 valley string
155 cue string
156 nats string
157
158 attestSchema string
159 eventSchema string
160 policy policySource
161
162 key string
163 signerName string
164 keyHash string
165 knownSigners string
166
167 // signerProjects restricts signers in knownSigners to projects
168 // (note/signerprojects.go). Nil restricts nobody. It is read once, at
169 // start, and signerProjectsData is the bytes it was read from, which
170 // the inputs digest covers (inputs.go).
171 signerProjects note.SignerProjects
172 signerProjectsData []byte
173
174 bus string
175 publishQueue string
176 wake string // the check worker's wake directory, or empty
177 system string
178
179 // clock, when set, is the instant the effectful window is measured
180 // against. Zero means the wall clock.
181 clock time.Time
182
183 // evidenceListed, when set, runs once collectEvidence has listed a
184 // subject's attestation refs, before it reads any of them. Tests set
185 // it to delete a ref in that window.
186 evidenceListed func()
187}
188
189func main() {
190 if len(os.Args) < 2 {
191 fmt.Fprint(os.Stderr, usage)
192 os.Exit(2)
193 }
194 // Before anything runs git, so that every git this process starts — its
195 // own, and the ones attest and the deriver start — inherits the result.
196 os.Clearenv()
197 for _, kv := range gitEnvironment(environ) {
198 name, value, _ := strings.Cut(kv, "=")
199 os.Setenv(name, value)
200 }
201 var err error
202 switch os.Args[1] {
203 case "reconcile":
204 err = run(os.Args[2:], false)
205 case "watch":
206 err = run(os.Args[2:], true)
207 case "publish-signers":
208 err = publishSigners(os.Args[2:])
209 case "help", "-h", "--help":
210 fmt.Print(usage)
211 return
212 default:
213 fmt.Fprintf(os.Stderr, "integrator: unknown command %q\n\n%s", os.Args[1], usage)
214 os.Exit(2)
215 }
216 if err != nil {
217 fmt.Fprintf(os.Stderr, "integrator: %v\n", err)
218 os.Exit(1)
219 }
220}
221
222func run(args []string, loop bool) error {
223 fs := flag.NewFlagSet("integrator", flag.ExitOnError)
224 fs.Usage = func() { fmt.Fprint(os.Stderr, usage) }
225 repo := fs.String("repo", ".", "the served repository")
226 project := fs.String("project", "", "the project name events carry")
227 key := fs.String("key", "", "ed25519 private key")
228 name := fs.String("name", defaultSignerName(), "the name that key signs under")
229 known := fs.String("known-signers", "", "verifier keys whose attestations count")
230 signerProjects := fs.String("signer-projects", "", "signers whose attestations count only in the projects listed beside them")
231 instanceRepo := fs.String("instance-repo", "", "the bare repository carrying the group's floor")
232 instanceRef := fs.String("instance-ref", "refs/heads/main", "the ref whose tip carries the floor")
233 instancePolicy := fs.String("instance-policy", "policy/instance", "the floor's directory in that tip")
234 instance := fs.String("instance", "", "a materialized instance policy layer")
235 projectPolicy := fs.String("project-policy", "policy/project", "the project policy layer, relative to the target tip")
236 schema := fs.String("schema", env("VALLEY_VERIFICATION_SCHEMA"), "the verification schema")
237 attestSchema := fs.String("attest-schema", env("VALLEY_ATTEST_SCHEMA"), "the attestation schema")
238 eventSchema := fs.String("event-schema", env("VALLEY_EVENT_SCHEMA"), "the event vocabulary")
239 bus := fs.String("bus", "", "nats server to publish outcomes to")
240 publishQueue := fs.String("publish-queue", "", "the host's queue of ref moves to publish")
241 wake := fs.String("wake", "", "the check worker's wake directory, marked due after each landing")
242 system := fs.String("system", "", "flake system")
243 interval := fs.Duration("interval", 15*time.Second, "how long to wait between passes")
244 now := fs.String("now", "", "judge as at this instant")
245 if err := fs.Parse(args); err != nil {
246 return err
247 }
248
249 in := &integrator{
250 repo: *repo,
251 project: *project,
252 out: os.Stdout,
253 timings: newDroppable(duplicate(syscall.Stdout, "stdout")),
254 attestSchema: *attestSchema,
255 eventSchema: *eventSchema,
256 key: *key,
257 signerName: *name,
258 knownSigners: *known,
259 bus: *bus,
260 publishQueue: *publishQueue,
261 wake: *wake,
262 system: *system,
263 }
264 for _, missing := range []struct{ flag, value string }{
265 {"--key", in.key},
266 {"--known-signers", in.knownSigners},
267 {"--schema", *schema},
268 {"--attest-schema", in.attestSchema},
269 } {
270 if missing.value == "" {
271 return fmt.Errorf("%s is required", missing.flag)
272 }
273 }
274 var err error
275 for _, tool := range []struct {
276 name string
277 into *string
278 }{{"attest", &in.attest}, {"valley", &in.valley}, {"cue", &in.cue}, {"nats", &in.nats}} {
279 if *tool.into, err = exec.LookPath(tool.name); err != nil && tool.name != "nats" {
280 return fmt.Errorf("%s is not on the path; the integrator drives it rather than reimplementing it", tool.name)
281 }
282 }
283 // The floor comes from the instance repository's integrated tip, or from
284 // a directory on disk, and never from both — two sources for one layer is
285 // a question about which one won every time the policy is read.
286 if (*instanceRepo == "") == (*instance == "") {
287 return fmt.Errorf("exactly one of --instance-repo and --instance is required: the floor is read from the instance repository's tip, or from a materialized directory for a host that serves none")
288 }
289 // abs of an empty path is the working directory, and an empty field is
290 // how the layer says which of its two sources it is.
291 layer := composed.Floor{Ref: *instanceRef, Dir: *instancePolicy}
292 if *instanceRepo != "" {
293 // A full ref name is read by that exact name. Any other name,
294 // such as main, git would resolve by trying several refs in
295 // turn, and a pusher can make one of them.
296 if !strings.HasPrefix(*instanceRef, "refs/") {
297 return fmt.Errorf("--instance-ref %s is not a full ref name; name it whole, as refs/heads/main", *instanceRef)
298 }
299 layer.Repo = abs(*instanceRepo)
300 } else {
301 layer.Path = abs(*instance)
302 }
303 in.policy = policySource{
304 schema: abs(*schema),
305 layer: layer,
306 projectDir: *projectPolicy,
307 valley: in.valley,
308 cue: in.cue,
309 }
310 if *now != "" {
311 if in.clock, err = time.Parse(time.RFC3339, *now); err != nil {
312 return fmt.Errorf("--now: %w", err)
313 }
314 }
315 if in.repo, err = filepath.Abs(in.repo); err != nil {
316 return err
317 }
318 if in.project == "" {
319 in.project = projectName(in.repo)
320 }
321 if in.signerProjects, in.signerProjectsData, err = readSignerProjects(*signerProjects, in.signerName); err != nil {
322 return err
323 }
324 if in.keyHash, err = in.readKeyHash(); err != nil {
325 return err
326 }
327
328 if !loop {
329 return in.reconcile()
330 }
331 // Only the looping controller sweeps. A one-shot run may be somebody
332 // running the integrator by hand beside a controller that is already
333 // watching this repository, and sweeping from there would pull the
334 // worktree out from under a tick in progress.
335 sweepScratch(in.repo)
336 for {
337 if err := in.reconcile(); err != nil {
338 fmt.Fprintf(os.Stderr, "integrator: %v\n", err)
339 }
340 time.Sleep(*interval)
341 }
342}
343
344// readKeyHash asks attest for the verifier key this integrator signs under,
345// and keeps the key hash: it is the segment that keeps one signer's
346// attestation ref from racing another's (dcr-0de694f).
347func (in *integrator) readKeyHash() (string, error) {
348 out, err := exec.Command(in.attest, "key", "--key", in.key, "--name", in.signerName).Output()
349 if err != nil {
350 return "", fmt.Errorf("reading the signing key: %w", err)
351 }
352 // name+hash+base64, split three ways: the name holds no plus and the
353 // base64 may.
354 fields := strings.SplitN(strings.TrimSpace(string(out)), "+", 3)
355 if len(fields) != 3 {
356 return "", fmt.Errorf("attest key printed %q", strings.TrimSpace(string(out)))
357 }
358 if _, err := strconv.ParseUint(fields[1], 16, 32); err != nil {
359 return "", fmt.Errorf("attest key printed the hash %q", fields[1])
360 }
361 return fields[1], nil
362}
363
364// projectName is the name the events carry: the repository's directory,
365// with a bare repo's .git suffix removed — the same name the post-receive
366// hook derives.
367func projectName(repo string) string {
368 if bare, err := gitLine(repo, "rev-parse", "--is-bare-repository"); err == nil && bare == "true" {
369 dir, _ := gitLine(repo, "rev-parse", "--absolute-git-dir")
370 return strings.TrimSuffix(filepath.Base(dir), ".git")
371 }
372 top, err := gitLine(repo, "rev-parse", "--show-toplevel")
373 if err != nil {
374 return filepath.Base(repo)
375 }
376 return filepath.Base(top)
377}
378
379// defaultSignerName is the name this machine signs under: its own name and
380// the suffix that keeps a key signing attestations distinct from the same
381// key signing anything else (dcr-de9d996).
382func defaultSignerName() string {
383 host, err := os.Hostname()
384 if err != nil || host == "" {
385 host = "localhost"
386 }
387 return host + "/attestations"
388}
389
390func env(name string) string { return os.Getenv(name) }
391
392// environ is the environment the process started with, read before main
393// replaces it.
394var environ = os.Environ()
395
396// gitEnvironment is the environment the controller runs in: the one it
397// started with, with git's part of it fixed.
398//
399// Replacement refs are off. A replacement ref makes one object stand in for
400// another wherever git looks it up, so a refs/replace/<blob> pushed to the
401// served repository or the instance repository could swap the floor, the
402// project's policy or a change's tree for anything its author liked,
403// without moving any ref the controller watches. Every judgement here reads
404// the repository's own objects.
405//
406// No other GIT_ variable is inherited, as sigverify inherits none: a GIT_DIR
407// or GIT_OBJECT_DIRECTORY could point git at other objects, and a
408// GIT_CONFIG_PARAMETERS could change how it reads them. System and user
409// configuration are not read either. The one thing kept is command-scope
410// configuration naming safe.directory, which is how the unit tells git it
411// may read repositories the controller does not own (nix/valley-host.nix).
412// Those entries are carried over, renumbered, and no other key is.
413func gitEnvironment(inherited []string) []string {
414 vars := map[string]string{}
415 var kept []string
416 for _, kv := range inherited {
417 name, value, _ := strings.Cut(kv, "=")
418 if strings.HasPrefix(name, "GIT_") {
419 vars[name] = value
420 continue
421 }
422 kept = append(kept, kv)
423 }
424
425 var safe []string
426 count, _ := strconv.Atoi(vars["GIT_CONFIG_COUNT"])
427 for i := 0; i < count; i++ {
428 if strings.EqualFold(vars[fmt.Sprintf("GIT_CONFIG_KEY_%d", i)], "safe.directory") {
429 safe = append(safe, vars[fmt.Sprintf("GIT_CONFIG_VALUE_%d", i)])
430 }
431 }
432 if len(safe) > 0 {
433 kept = append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", len(safe)))
434 for i, dir := range safe {
435 kept = append(kept,
436 fmt.Sprintf("GIT_CONFIG_KEY_%d=safe.directory", i),
437 fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", i, dir))
438 }
439 }
440
441 return append(kept,
442 "GIT_CONFIG_NOSYSTEM=1",
443 "GIT_CONFIG_SYSTEM=/dev/null",
444 "GIT_CONFIG_GLOBAL=/dev/null",
445 "GIT_NO_REPLACE_OBJECTS=1",
446 "GIT_ATTR_NOSYSTEM=1",
447 "GIT_TERMINAL_PROMPT=0",
448 )
449}
450
451func abs(path string) string {
452 if p, err := filepath.Abs(path); err == nil {
453 return p
454 }
455 return path
456}
457
458// gitEnv runs a git command with extra environment, for the one place the
459// integrator has to state who authored and who committed.
460func (in *integrator) gitEnv(extra map[string]string, args ...string) (string, error) {
461 cmd := exec.Command("git", args...)
462 cmd.Dir = in.repo
463 cmd.Env = os.Environ()
464 for k, v := range extra {
465 cmd.Env = append(cmd.Env, k+"="+v)
466 }
467 var errb strings.Builder
468 cmd.Stderr = &errb
469 out, err := cmd.Output()
470 if err != nil {
471 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
472 }
473 return string(out), nil
474}
475
476// writeTemp writes bytes to a file cue will read as JSON — the extension is
477// how cue tells a data file from a schema.
478func writeTemp(prefix string, body []byte) (string, error) {
479 dir, err := scratch(prefix)
480 if err != nil {
481 return "", err
482 }
483 path := filepath.Join(dir, "payload.json")
484 if err := os.WriteFile(path, body, 0o644); err != nil {
485 return "", err
486 }
487 return path, nil
488}
489
490func removeTemp(path string) { _ = os.RemoveAll(filepath.Dir(path)) }