gunk-dev/the-valley

main.go

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