gunk-dev/the-valley

main.go

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