gunk-dev/the-valley

main.go

source9ee0a5aa589dmain's published tip history
11.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 policy)
55 --instance DIR a materialized instance layer, for a host that serves
56 no instance repository; one of this or --instance-repo
57 --project-policy P the project policy layer, relative to the target tip
58 --schema FILE the verification schema
59 --attest-schema F the attestation schema
60 --event-schema F the event vocabulary payloads are vetted against
61 --bus URL nats server to publish outcomes to; empty publishes
62 nothing and still prints every payload
63 --system SYSTEM flake system for closure recomputation
64 --interval D watch: how long to wait between passes (default 15s)
65 --now TIME judge as at this RFC 3339 instant, for the effectful
66 window; defaults to the clock
67
68--known-signers is the registry's interim compilation. Identity is a
69governed registry (dcr-b87f6e8) whose entries compile into what each
70enforcement boundary checks; no compiler exists yet, so the file is
71supplied directly and is exactly what dcr-b87f6e8 calls the first
72compilation's output. An attestation signed by nobody in it does not
73transfer, and that is reported per check rather than treated as a forgery.
74`
75
76// integrator is one controller: which repository it serves, who it signs
77// as, whose evidence it accepts, and where it finds the policy.
78type integrator struct {
79 repo string
80 project string
81 out *os.File
82
83 // The programs it drives. Every judgement about a statement or a note
84 // is attest's, and every judgement about what a policy says is the
85 // deriver's and cue's.
86 attest string
87 valley string
88 cue string
89 nats string
90
91 attestSchema string
92 eventSchema string
93 policy policySource
94
95 key string
96 signerName string
97 keyHash string
98 knownSigners string
99
100 bus string
101 system string
102
103 // clock, when set, is the instant the effectful window is measured
104 // against. Zero means the wall clock.
105 clock time.Time
106}
107
108func main() {
109 if len(os.Args) < 2 {
110 fmt.Fprint(os.Stderr, usage)
111 os.Exit(2)
112 }
113 var err error
114 switch os.Args[1] {
115 case "reconcile":
116 err = run(os.Args[2:], false)
117 case "watch":
118 err = run(os.Args[2:], true)
119 case "help", "-h", "--help":
120 fmt.Print(usage)
121 return
122 default:
123 fmt.Fprintf(os.Stderr, "integrator: unknown command %q\n\n%s", os.Args[1], usage)
124 os.Exit(2)
125 }
126 if err != nil {
127 fmt.Fprintf(os.Stderr, "integrator: %v\n", err)
128 os.Exit(1)
129 }
130}
131
132func run(args []string, loop bool) error {
133 fs := flag.NewFlagSet("integrator", flag.ExitOnError)
134 fs.Usage = func() { fmt.Fprint(os.Stderr, usage) }
135 repo := fs.String("repo", ".", "the served repository")
136 project := fs.String("project", "", "the project name events carry")
137 key := fs.String("key", "", "ed25519 private key")
138 name := fs.String("name", defaultSignerName(), "the name that key signs under")
139 known := fs.String("known-signers", "", "verifier keys whose attestations count")
140 instanceRepo := fs.String("instance-repo", "", "the bare repository carrying the group's floor")
141 instanceRef := fs.String("instance-ref", "refs/heads/main", "the ref whose tip carries the floor")
142 instancePolicy := fs.String("instance-policy", "policy", "the floor's directory in that tip")
143 instance := fs.String("instance", "", "a materialized instance policy layer")
144 projectPolicy := fs.String("project-policy", "policy", "the project policy layer, relative to the target tip")
145 schema := fs.String("schema", env("VALLEY_VERIFICATION_SCHEMA"), "the verification schema")
146 attestSchema := fs.String("attest-schema", env("VALLEY_ATTEST_SCHEMA"), "the attestation schema")
147 eventSchema := fs.String("event-schema", env("VALLEY_EVENT_SCHEMA"), "the event vocabulary")
148 bus := fs.String("bus", "", "nats server to publish outcomes to")
149 system := fs.String("system", "", "flake system")
150 interval := fs.Duration("interval", 15*time.Second, "how long to wait between passes")
151 now := fs.String("now", "", "judge as at this instant")
152 if err := fs.Parse(args); err != nil {
153 return err
154 }
155
156 in := &integrator{
157 repo: *repo,
158 project: *project,
159 out: os.Stdout,
160 attestSchema: *attestSchema,
161 eventSchema: *eventSchema,
162 key: *key,
163 signerName: *name,
164 knownSigners: *known,
165 bus: *bus,
166 system: *system,
167 }
168 for _, missing := range []struct{ flag, value string }{
169 {"--key", in.key},
170 {"--known-signers", in.knownSigners},
171 {"--schema", *schema},
172 {"--attest-schema", in.attestSchema},
173 } {
174 if missing.value == "" {
175 return fmt.Errorf("%s is required", missing.flag)
176 }
177 }
178 var err error
179 for _, tool := range []struct {
180 name string
181 into *string
182 }{{"attest", &in.attest}, {"valley", &in.valley}, {"cue", &in.cue}, {"nats", &in.nats}} {
183 if *tool.into, err = exec.LookPath(tool.name); err != nil && tool.name != "nats" {
184 return fmt.Errorf("%s is not on the path; the integrator drives it rather than reimplementing it", tool.name)
185 }
186 }
187 // The floor comes from the instance repository's integrated tip, or from
188 // a directory on disk, and never from both — two sources for one layer is
189 // a question about which one won every time the policy is read.
190 if (*instanceRepo == "") == (*instance == "") {
191 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")
192 }
193 // abs of an empty path is the working directory, and an empty field is
194 // how the layer says which of its two sources it is.
195 layer := instanceLayer{ref: *instanceRef, dir: *instancePolicy}
196 if *instanceRepo != "" {
197 layer.repo = abs(*instanceRepo)
198 } else {
199 layer.path = abs(*instance)
200 }
201 in.policy = policySource{
202 schema: abs(*schema),
203 layer: layer,
204 project: *projectPolicy,
205 valley: in.valley,
206 cue: in.cue,
207 }
208 if *now != "" {
209 if in.clock, err = time.Parse(time.RFC3339, *now); err != nil {
210 return fmt.Errorf("--now: %w", err)
211 }
212 }
213 if in.repo, err = filepath.Abs(in.repo); err != nil {
214 return err
215 }
216 if in.project == "" {
217 in.project = projectName(in.repo)
218 }
219 if in.keyHash, err = in.readKeyHash(); err != nil {
220 return err
221 }
222
223 if !loop {
224 return in.reconcile()
225 }
226 // Only the looping controller sweeps. A one-shot run may be somebody
227 // running the integrator by hand beside a controller that is already
228 // watching this repository, and sweeping from there would pull the
229 // worktree out from under a tick in progress.
230 sweepScratch(in.repo)
231 for {
232 if err := in.reconcile(); err != nil {
233 fmt.Fprintf(os.Stderr, "integrator: %v\n", err)
234 }
235 time.Sleep(*interval)
236 }
237}
238
239// readKeyHash asks attest for the verifier key this integrator signs under,
240// and keeps the key hash: it is the segment that keeps one signer's
241// attestation ref from racing another's (dcr-0de694f).
242func (in *integrator) readKeyHash() (string, error) {
243 out, err := exec.Command(in.attest, "key", "--key", in.key, "--name", in.signerName).Output()
244 if err != nil {
245 return "", fmt.Errorf("reading the signing key: %w", err)
246 }
247 // name+hash+base64, split three ways: the name holds no plus and the
248 // base64 may.
249 fields := strings.SplitN(strings.TrimSpace(string(out)), "+", 3)
250 if len(fields) != 3 {
251 return "", fmt.Errorf("attest key printed %q", strings.TrimSpace(string(out)))
252 }
253 if _, err := strconv.ParseUint(fields[1], 16, 32); err != nil {
254 return "", fmt.Errorf("attest key printed the hash %q", fields[1])
255 }
256 return fields[1], nil
257}
258
259// projectName is the name the events carry: the repository's directory,
260// with a bare repo's .git suffix removed — the same name the post-receive
261// hook derives.
262func projectName(repo string) string {
263 if bare, err := gitLine(repo, "rev-parse", "--is-bare-repository"); err == nil && bare == "true" {
264 dir, _ := gitLine(repo, "rev-parse", "--absolute-git-dir")
265 return strings.TrimSuffix(filepath.Base(dir), ".git")
266 }
267 top, err := gitLine(repo, "rev-parse", "--show-toplevel")
268 if err != nil {
269 return filepath.Base(repo)
270 }
271 return filepath.Base(top)
272}
273
274// defaultSignerName is the name this machine signs under: its own name and
275// the suffix that keeps a key signing attestations distinct from the same
276// key signing anything else (dcr-de9d996).
277func defaultSignerName() string {
278 host, err := os.Hostname()
279 if err != nil || host == "" {
280 host = "localhost"
281 }
282 return host + "/attestations"
283}
284
285func env(name string) string { return os.Getenv(name) }
286
287func abs(path string) string {
288 if p, err := filepath.Abs(path); err == nil {
289 return p
290 }
291 return path
292}
293
294// gitEnv runs a git command with extra environment, for the one place the
295// integrator has to set authorship.
296func (in *integrator) gitEnv(extra map[string]string, args ...string) (string, error) {
297 cmd := exec.Command("git", args...)
298 cmd.Dir = in.repo
299 cmd.Env = os.Environ()
300 for k, v := range extra {
301 cmd.Env = append(cmd.Env, k+"="+v)
302 }
303 var errb strings.Builder
304 cmd.Stderr = &errb
305 out, err := cmd.Output()
306 if err != nil {
307 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
308 }
309 return string(out), nil
310}
311
312// writeTemp writes bytes to a file cue will read as JSON — the extension is
313// how cue tells a data file from a schema.
314func writeTemp(prefix string, body []byte) (string, error) {
315 dir, err := scratch(prefix)
316 if err != nil {
317 return "", err
318 }
319 path := filepath.Join(dir, "payload.json")
320 if err := os.WriteFile(path, body, 0o644); err != nil {
321 return "", err
322 }
323 return path, nil
324}
325
326func removeTemp(path string) { _ = os.RemoveAll(filepath.Dir(path)) }