gunk-dev/the-valley

main.go

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