gunk-dev/the-valley

main.go

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