gunk-dev/the-valley

main.go

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