gunk-dev/the-valley

main.go

source01aebe3a28ffmain's published tip history
18.6 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
175func main() {
176 if len(os.Args) < 2 {
177 fmt.Fprint(os.Stderr, usage)
178 os.Exit(2)
179 }
180 // Before anything runs git, so that every git this process starts — its
181 // own, and the ones attest and the deriver start — inherits the result.
182 os.Clearenv()
183 for _, kv := range gitEnvironment(environ) {
184 name, value, _ := strings.Cut(kv, "=")
185 os.Setenv(name, value)
186 }
187 var err error
188 switch os.Args[1] {
189 case "reconcile":
190 err = run(os.Args[2:], false)
191 case "watch":
192 err = run(os.Args[2:], true)
193 case "publish-signers":
194 err = publishSigners(os.Args[2:])
195 case "help", "-h", "--help":
196 fmt.Print(usage)
197 return
198 default:
199 fmt.Fprintf(os.Stderr, "integrator: unknown command %q\n\n%s", os.Args[1], usage)
200 os.Exit(2)
201 }
202 if err != nil {
203 fmt.Fprintf(os.Stderr, "integrator: %v\n", err)
204 os.Exit(1)
205 }
206}
207
208func run(args []string, loop bool) error {
209 fs := flag.NewFlagSet("integrator", flag.ExitOnError)
210 fs.Usage = func() { fmt.Fprint(os.Stderr, usage) }
211 repo := fs.String("repo", ".", "the served repository")
212 project := fs.String("project", "", "the project name events carry")
213 key := fs.String("key", "", "ed25519 private key")
214 name := fs.String("name", defaultSignerName(), "the name that key signs under")
215 known := fs.String("known-signers", "", "verifier keys whose attestations count")
216 signerProjects := fs.String("signer-projects", "", "signers whose attestations count only in the projects listed beside them")
217 instanceRepo := fs.String("instance-repo", "", "the bare repository carrying the group's floor")
218 instanceRef := fs.String("instance-ref", "refs/heads/main", "the ref whose tip carries the floor")
219 instancePolicy := fs.String("instance-policy", "policy/instance", "the floor's directory in that tip")
220 instance := fs.String("instance", "", "a materialized instance policy layer")
221 projectPolicy := fs.String("project-policy", "policy/project", "the project policy layer, relative to the target tip")
222 schema := fs.String("schema", env("VALLEY_VERIFICATION_SCHEMA"), "the verification schema")
223 attestSchema := fs.String("attest-schema", env("VALLEY_ATTEST_SCHEMA"), "the attestation schema")
224 eventSchema := fs.String("event-schema", env("VALLEY_EVENT_SCHEMA"), "the event vocabulary")
225 bus := fs.String("bus", "", "nats server to publish outcomes to")
226 publishQueue := fs.String("publish-queue", "", "the host's queue of ref moves to publish")
227 system := fs.String("system", "", "flake system")
228 interval := fs.Duration("interval", 15*time.Second, "how long to wait between passes")
229 now := fs.String("now", "", "judge as at this instant")
230 if err := fs.Parse(args); err != nil {
231 return err
232 }
233
234 in := &integrator{
235 repo: *repo,
236 project: *project,
237 out: os.Stdout,
238 timings: newDroppable(duplicate(syscall.Stdout, "stdout")),
239 attestSchema: *attestSchema,
240 eventSchema: *eventSchema,
241 key: *key,
242 signerName: *name,
243 knownSigners: *known,
244 bus: *bus,
245 publishQueue: *publishQueue,
246 system: *system,
247 }
248 for _, missing := range []struct{ flag, value string }{
249 {"--key", in.key},
250 {"--known-signers", in.knownSigners},
251 {"--schema", *schema},
252 {"--attest-schema", in.attestSchema},
253 } {
254 if missing.value == "" {
255 return fmt.Errorf("%s is required", missing.flag)
256 }
257 }
258 var err error
259 for _, tool := range []struct {
260 name string
261 into *string
262 }{{"attest", &in.attest}, {"valley", &in.valley}, {"cue", &in.cue}, {"nats", &in.nats}} {
263 if *tool.into, err = exec.LookPath(tool.name); err != nil && tool.name != "nats" {
264 return fmt.Errorf("%s is not on the path; the integrator drives it rather than reimplementing it", tool.name)
265 }
266 }
267 // The floor comes from the instance repository's integrated tip, or from
268 // a directory on disk, and never from both — two sources for one layer is
269 // a question about which one won every time the policy is read.
270 if (*instanceRepo == "") == (*instance == "") {
271 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")
272 }
273 // abs of an empty path is the working directory, and an empty field is
274 // how the layer says which of its two sources it is.
275 layer := composed.Floor{Ref: *instanceRef, Dir: *instancePolicy}
276 if *instanceRepo != "" {
277 // A full ref name is read by that exact name. Any other name,
278 // such as main, git would resolve by trying several refs in
279 // turn, and a pusher can make one of them.
280 if !strings.HasPrefix(*instanceRef, "refs/") {
281 return fmt.Errorf("--instance-ref %s is not a full ref name; name it whole, as refs/heads/main", *instanceRef)
282 }
283 layer.Repo = abs(*instanceRepo)
284 } else {
285 layer.Path = abs(*instance)
286 }
287 in.policy = policySource{
288 schema: abs(*schema),
289 layer: layer,
290 projectDir: *projectPolicy,
291 valley: in.valley,
292 cue: in.cue,
293 }
294 if *now != "" {
295 if in.clock, err = time.Parse(time.RFC3339, *now); err != nil {
296 return fmt.Errorf("--now: %w", err)
297 }
298 }
299 if in.repo, err = filepath.Abs(in.repo); err != nil {
300 return err
301 }
302 if in.project == "" {
303 in.project = projectName(in.repo)
304 }
305 if in.signerProjects, _, err = readSignerProjects(*signerProjects, in.signerName); err != nil {
306 return err
307 }
308 if in.keyHash, err = in.readKeyHash(); err != nil {
309 return err
310 }
311
312 if !loop {
313 return in.reconcile()
314 }
315 // Only the looping controller sweeps. A one-shot run may be somebody
316 // running the integrator by hand beside a controller that is already
317 // watching this repository, and sweeping from there would pull the
318 // worktree out from under a tick in progress.
319 sweepScratch(in.repo)
320 for {
321 if err := in.reconcile(); err != nil {
322 fmt.Fprintf(os.Stderr, "integrator: %v\n", err)
323 }
324 time.Sleep(*interval)
325 }
326}
327
328// readKeyHash asks attest for the verifier key this integrator signs under,
329// and keeps the key hash: it is the segment that keeps one signer's
330// attestation ref from racing another's (dcr-0de694f).
331func (in *integrator) readKeyHash() (string, error) {
332 out, err := exec.Command(in.attest, "key", "--key", in.key, "--name", in.signerName).Output()
333 if err != nil {
334 return "", fmt.Errorf("reading the signing key: %w", err)
335 }
336 // name+hash+base64, split three ways: the name holds no plus and the
337 // base64 may.
338 fields := strings.SplitN(strings.TrimSpace(string(out)), "+", 3)
339 if len(fields) != 3 {
340 return "", fmt.Errorf("attest key printed %q", strings.TrimSpace(string(out)))
341 }
342 if _, err := strconv.ParseUint(fields[1], 16, 32); err != nil {
343 return "", fmt.Errorf("attest key printed the hash %q", fields[1])
344 }
345 return fields[1], nil
346}
347
348// projectName is the name the events carry: the repository's directory,
349// with a bare repo's .git suffix removed — the same name the post-receive
350// hook derives.
351func projectName(repo string) string {
352 if bare, err := gitLine(repo, "rev-parse", "--is-bare-repository"); err == nil && bare == "true" {
353 dir, _ := gitLine(repo, "rev-parse", "--absolute-git-dir")
354 return strings.TrimSuffix(filepath.Base(dir), ".git")
355 }
356 top, err := gitLine(repo, "rev-parse", "--show-toplevel")
357 if err != nil {
358 return filepath.Base(repo)
359 }
360 return filepath.Base(top)
361}
362
363// defaultSignerName is the name this machine signs under: its own name and
364// the suffix that keeps a key signing attestations distinct from the same
365// key signing anything else (dcr-de9d996).
366func defaultSignerName() string {
367 host, err := os.Hostname()
368 if err != nil || host == "" {
369 host = "localhost"
370 }
371 return host + "/attestations"
372}
373
374func env(name string) string { return os.Getenv(name) }
375
376// environ is the environment the process started with, read before main
377// replaces it.
378var environ = os.Environ()
379
380// gitEnvironment is the environment the controller runs in: the one it
381// started with, with git's part of it fixed.
382//
383// Replacement refs are off. A replacement ref makes one object stand in for
384// another wherever git looks it up, so a refs/replace/<blob> pushed to the
385// served repository or the instance repository could swap the floor, the
386// project's policy or a change's tree for anything its author liked,
387// without moving any ref the controller watches. Every judgement here reads
388// the repository's own objects.
389//
390// No other GIT_ variable is inherited, as sigverify inherits none: a GIT_DIR
391// or GIT_OBJECT_DIRECTORY could point git at other objects, and a
392// GIT_CONFIG_PARAMETERS could change how it reads them. System and user
393// configuration are not read either. The one thing kept is command-scope
394// configuration naming safe.directory, which is how the unit tells git it
395// may read repositories the controller does not own (nix/valley-host.nix).
396// Those entries are carried over, renumbered, and no other key is.
397func gitEnvironment(inherited []string) []string {
398 vars := map[string]string{}
399 var kept []string
400 for _, kv := range inherited {
401 name, value, _ := strings.Cut(kv, "=")
402 if strings.HasPrefix(name, "GIT_") {
403 vars[name] = value
404 continue
405 }
406 kept = append(kept, kv)
407 }
408
409 var safe []string
410 count, _ := strconv.Atoi(vars["GIT_CONFIG_COUNT"])
411 for i := 0; i < count; i++ {
412 if strings.EqualFold(vars[fmt.Sprintf("GIT_CONFIG_KEY_%d", i)], "safe.directory") {
413 safe = append(safe, vars[fmt.Sprintf("GIT_CONFIG_VALUE_%d", i)])
414 }
415 }
416 if len(safe) > 0 {
417 kept = append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", len(safe)))
418 for i, dir := range safe {
419 kept = append(kept,
420 fmt.Sprintf("GIT_CONFIG_KEY_%d=safe.directory", i),
421 fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", i, dir))
422 }
423 }
424
425 return append(kept,
426 "GIT_CONFIG_NOSYSTEM=1",
427 "GIT_CONFIG_SYSTEM=/dev/null",
428 "GIT_CONFIG_GLOBAL=/dev/null",
429 "GIT_NO_REPLACE_OBJECTS=1",
430 "GIT_ATTR_NOSYSTEM=1",
431 "GIT_TERMINAL_PROMPT=0",
432 )
433}
434
435func abs(path string) string {
436 if p, err := filepath.Abs(path); err == nil {
437 return p
438 }
439 return path
440}
441
442// gitEnv runs a git command with extra environment, for the one place the
443// integrator has to state who authored and who committed.
444func (in *integrator) gitEnv(extra map[string]string, args ...string) (string, error) {
445 cmd := exec.Command("git", args...)
446 cmd.Dir = in.repo
447 cmd.Env = os.Environ()
448 for k, v := range extra {
449 cmd.Env = append(cmd.Env, k+"="+v)
450 }
451 var errb strings.Builder
452 cmd.Stderr = &errb
453 out, err := cmd.Output()
454 if err != nil {
455 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
456 }
457 return string(out), nil
458}
459
460// writeTemp writes bytes to a file cue will read as JSON — the extension is
461// how cue tells a data file from a schema.
462func writeTemp(prefix string, body []byte) (string, error) {
463 dir, err := scratch(prefix)
464 if err != nil {
465 return "", err
466 }
467 path := filepath.Join(dir, "payload.json")
468 if err := os.WriteFile(path, body, 0o644); err != nil {
469 return "", err
470 }
471 return path, nil
472}
473
474func removeTemp(path string) { _ = os.RemoveAll(filepath.Dir(path)) }