gunk-dev/the-valley

main.go

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