gunk-dev/the-valley

main.go

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