gunk-dev/the-valley

main.go

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