gunk-dev/the-valley

main.go

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