gunk-dev/the-valley

main.go

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