gunk-dev/the-valley

main.go

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