gunk-dev/the-valley

main.go

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