gunk-dev/the-valley

main.go

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