gunk-dev/the-valley

signers.go

source937924e2f63emain's published tip history
16.3 KiB
1package main
2
3import (
4 "bytes"
5 "flag"
6 "fmt"
7 "os"
8 "path/filepath"
9 "strings"
10 "syscall"
11
12 "the-valley/approval"
13 "the-valley/note"
14)
15
16// signersRef is where the host publishes what a client verifies this
17// integrator's transfer statements with: a tree holding the known-signers
18// file the integrator reads, as signersKeys, and the name it signs under,
19// as signersName, one line. When the integrator is given a signer projects
20// file, the tree holds that file too, as signersProjects, so a client can
21// tell which signers' evidence counts in which projects.
22//
23// The tree also says who may approve, and in which instance: the two
24// approval signers files the identity compiler writes, as
25// signersApprovers and signersHardware, and the instance's identity, as
26// signersInstance, 64 lowercase hex digits and a newline, once the
27// instance repository has a main to derive it from. The publication
28// informs clients. Whatever enforces approvals reads the host's own files,
29// never this snapshot of them.
30//
31// Only the host's own machinery writes it, never a push. The push hook
32// refuses every push to a refs/the-valley/* ref it does not name. On the
33// host, this publisher writes it. The integrator can write it too: the
34// instance repository is group-writable, and the integrator is in the
35// group because it lands code there. A client already trusts the
36// integrator with what lands, so the publication is not kept from it.
37//
38// signersLock is the file in the instance repository that a run holds a
39// lock on, from reading the signers file to moving the ref.
40const (
41 signersRef = "refs/the-valley/signers"
42 signersKeys = "known-signers"
43 signersName = "integrator-name"
44 signersProjects = "signer-projects"
45 signersLock = "valley-signers.lock"
46
47 signersApprovers = "approval-signers"
48 signersHardware = "approval-signers-hardware"
49 signersInstance = "instance-id"
50
51 // instanceTip is the instance repository's integrated tip, the ref
52 // the floor and the registry are read at by default.
53 instanceTip = "refs/heads/main"
54)
55
56const signersUsage = `usage: integrator publish-signers --instance-repo DIR --known-signers F [--name NAME] [--signer-projects F]
57 [--approval-signers F] [--approval-signers-hardware F] [--wake DIR]
58
59Publishes, in the instance repository, the two values a client verifies
60this host's transfer statements with: the known-signers file a controller
61reads, and the name it signs under. Both go into one tree at
62refs/the-valley/signers, so a client reads both from one ref or neither.
63Given --signer-projects, the tree holds that file too, as signer-projects,
64so a client can tell which signers' evidence counts in which projects.
65
66The tree also holds who may approve, in which instance: approval-signers
67and approval-signers-hardware, the approval signers files the identity
68compiler writes, and instance-id, the instance's identity. The identity
69is derived from the root commits of the instance repository's
70refs/heads/main, as the approval statement defines it. A repository with
71no refs/heads/main publishes no instance-id; a shallow one, or one
72missing part of that history, publishes nothing.
73
74 --instance-repo DIR the bare repository clients read the host's
75 publications from
76 --known-signers F the file a controller is given as --known-signers
77 --name NAME the name a controller signs under, as it is given
78 to watch (default: this host's, as watch defaults)
79 --signer-projects F the file a controller is given as --signer-projects;
80 without it, the publication holds none
81 --approval-signers F
82 the verifier keys of every approval key; without
83 it, the publication's approval-signers is empty
84 --approval-signers-hardware F
85 the verifier keys of the hardware approval keys;
86 without it, the publication's
87 approval-signers-hardware is empty
88 --wake DIR the host check worker's wake directory: a run that
89 moves the ref creates the empty file DIR/due, so
90 the worker reads the new signers; empty marks nothing
91
92A publication that would not change is not written. One that would is
93written with a compare-and-swap on the ref. After each publication, the
94run reads every input again, and publishes again from that reading until
95a reading matches what it last published, so a change made up to its
96last reading is published before it ends; a later one waits for the next
97run. It makes at most one publication more than
98the inputs that can change (the known-signers file, the instance's main,
99and each other file named), and fails if the inputs are still changing
100then. Two runs at once take turns: each holds a lock in the instance
101repository from its first reading to its last, so a run that read an
102older file cannot publish it over a newer one.
103
104The file must read as verifier keys, the name must be one a verifier key
105can carry, and a signer projects file must read as watch reads one, so
106it may not name NAME. An approval signers file that is named must read
107as verifier keys too; one with no key is published as it is, so the
108publication drops revoked approval keys. One file never stands in for
109another. A file that holds no key under the name, or no key
110at all, is published all the same, because it is what the controller
111uses. So when every signing key is revoked, the publication drops the
112old keys too, and clients stop verifying with them. The run says on
113stderr that no client can verify a statement with the file. An empty
114signer projects file restricts nobody, as no file does, and is not
115published.
116`
117
118// publishSigners writes the publication, and says what it did on stdout.
119func publishSigners(args []string) error {
120 return publishSignersWith(args, nil)
121}
122
123// publishSignersWith is publishSigners with step, when it is not nil,
124// called in each round after the round's inputs are read and its tree is
125// written, and before the ref moves. Tests change an input there.
126func publishSignersWith(args []string, step func(round int)) error {
127 fs := flag.NewFlagSet("publish-signers", flag.ExitOnError)
128 fs.Usage = func() { fmt.Fprint(os.Stderr, signersUsage) }
129 repo := fs.String("instance-repo", "", "the instance repository")
130 known := fs.String("known-signers", "", "the file a controller is given as --known-signers")
131 name := fs.String("name", defaultSignerName(), "the name a controller signs under")
132 projects := fs.String("signer-projects", "", "the file a controller is given as --signer-projects")
133 approvers := fs.String("approval-signers", "", "the verifier keys of every approval key")
134 hardware := fs.String("approval-signers-hardware", "", "the verifier keys of the hardware approval keys")
135 wake := fs.String("wake", "", "the check worker's wake directory, marked due when the publication moves")
136 if err := fs.Parse(args); err != nil {
137 return err
138 }
139 if fs.NArg() > 0 {
140 return fmt.Errorf("publish-signers takes no argument, and was given %q", fs.Arg(0))
141 }
142 for _, missing := range []struct{ flag, value string }{
143 {"--instance-repo", *repo},
144 {"--known-signers", *known},
145 } {
146 if missing.value == "" {
147 return fmt.Errorf("%s is required", missing.flag)
148 }
149 }
150 in := signersInputs{repo: *repo, known: *known, name: *name, projects: *projects, approvers: *approvers, hardware: *hardware}
151 unlock, err := lockSigners(*repo)
152 if err != nil {
153 return err
154 }
155 defer unlock()
156
157 // What wakes a run misses a change made while it runs, so a run does
158 // not end on what it read at the start. After each publication it
159 // reads every input again, and publishes again from that reading until
160 // a reading matches what it last published. A change made up to its
161 // last reading is published; one made after it waits for whatever
162 // starts the next run.
163 pub, err := in.read()
164 if err != nil {
165 return err
166 }
167 moved, rounds := false, in.rounds()
168 var unsettled error
169 for round := 1; ; round++ {
170 tree, err := signersTree(*repo, pub)
171 if err != nil {
172 return err
173 }
174 if step != nil {
175 step(round)
176 }
177 // The ref is read by its exact name. With no publication yet, old
178 // is "", whatever branch is named like the ref.
179 old, _, err := resolveRef(*repo, signersRef)
180 if err != nil {
181 return err
182 }
183 if old == tree {
184 fmt.Printf("%s already publishes %s and the signers in %s\n", signersRef, *name, *known)
185 } else {
186 // The value the ref is expected to hold: the one just read, or
187 // none at all. An empty old value makes update-ref require that
188 // the ref does not exist. The lock keeps other runs out, and the
189 // compare-and-swap keeps this run from writing over anything
190 // else on the host that moved the ref since.
191 if _, err := git(*repo, "update-ref", "-m", "publish-signers", signersRef, tree, old); err != nil {
192 return err
193 }
194 moved = true
195 fmt.Printf("%s now publishes %s and the signers in %s\n", signersRef, *name, *known)
196 }
197 again, err := in.read()
198 if err != nil {
199 return err
200 }
201 if again.equal(pub) {
202 break
203 }
204 if round == rounds {
205 unsettled = fmt.Errorf("the inputs kept changing: they had changed again after each of %d publications, so %s may not hold them as they are now", rounds, signersRef)
206 break
207 }
208 fmt.Printf("the inputs changed while %s was published, so it is published again\n", signersRef)
209 pub = again
210 }
211 // The check worker reads this publication for coverage, so a moved
212 // one marks it due. A run that published nothing new marks nothing.
213 // The ref has moved either way, so a mark that fails is said and is
214 // not this run's failure.
215 if moved {
216 if err := markDue(*wake); err != nil {
217 fmt.Printf("the check worker was not marked due: %v\n", err)
218 } else if *wake != "" {
219 fmt.Println("the check worker is due")
220 }
221 }
222 return unsettled
223}
224
225// signersInputs are the files and the repository one run publishes from.
226type signersInputs struct {
227 repo, known, name, projects, approvers, hardware string
228}
229
230// read reads every input, as a publication.
231func (in signersInputs) read() (publication, error) {
232 keys, err := os.ReadFile(in.known)
233 if err != nil {
234 return publication{}, fmt.Errorf("reading the known-signers file: %w", err)
235 }
236 _, restrictions, err := readSignerProjects(in.projects, in.name)
237 if err != nil {
238 return publication{}, err
239 }
240 pub := publication{keys: keys, name: in.name, projects: restrictions}
241 if pub.approvers, err = readApprovalSigners(in.approvers); err != nil {
242 return publication{}, err
243 }
244 if pub.hardware, err = readApprovalSigners(in.hardware); err != nil {
245 return publication{}, err
246 }
247 if pub.instance, err = instanceID(in.repo); err != nil {
248 return publication{}, err
249 }
250 return pub, nil
251}
252
253// rounds is the most publications one run makes. Each input that can
254// change while a run reads and publishes may change once and be caught by
255// a round of its own: the known-signers file, the instance's main, and
256// each other file named. One round more publishes the last of them. A run
257// that still reads something new after that is reading inputs that are
258// rewritten faster than it publishes, and it fails, so the unit shows it.
259func (in signersInputs) rounds() int {
260 n := 2
261 for _, f := range []string{in.projects, in.approvers, in.hardware} {
262 if f != "" {
263 n++
264 }
265 }
266 return n + 1
267}
268
269// publication is what one run publishes: the known-signers file, the
270// signing name, the signer projects file or nothing, both approval
271// signers files, and the instance identity, "" when there is none yet.
272type publication struct {
273 keys []byte
274 name string
275 projects []byte
276 approvers, hardware []byte
277 instance string
278}
279
280// equal reports whether two readings publish the same thing.
281func (p publication) equal(q publication) bool {
282 return bytes.Equal(p.keys, q.keys) && p.name == q.name && bytes.Equal(p.projects, q.projects) &&
283 bytes.Equal(p.approvers, q.approvers) && bytes.Equal(p.hardware, q.hardware) && p.instance == q.instance
284}
285
286// readApprovalSigners reads an approval signers file and holds it to
287// verifier keys. A file that is not named is empty: nothing is configured
288// to approve, and publishing nothing is what removes the keys a run
289// published before. A file that is named and cannot be read fails the
290// run, which leaves the last publication in place.
291func readApprovalSigners(path string) ([]byte, error) {
292 if path == "" {
293 return nil, nil
294 }
295 data, err := os.ReadFile(path)
296 if err != nil {
297 return nil, fmt.Errorf("reading the approval signers file: %w", err)
298 }
299 if _, err := note.ParseVerifierKeys(data); err != nil {
300 return nil, fmt.Errorf("the approval signers file %s does not read: %w", path, err)
301 }
302 return data, nil
303}
304
305// instanceID derives the instance's identity (approval.InstanceID) from
306// the instance repository's integrated tip, read once by its exact name:
307// its root commits and the repository's object format. It is "" when the
308// repository has no tip yet. A shallow repository is refused, since the
309// roots it holds need not be its history's, and so is one missing a commit
310// of that history, which rev-list cannot walk.
311func instanceID(repo string) (string, error) {
312 tip, ok, err := resolveRef(repo, instanceTip)
313 if err != nil || !ok {
314 return "", err
315 }
316 shallow, err := gitLine(repo, "rev-parse", "--is-shallow-repository")
317 if err != nil {
318 return "", err
319 }
320 if shallow != "false" {
321 return "", fmt.Errorf("the instance repository %s is shallow, so the root commits of its %s are not known", repo, instanceTip)
322 }
323 format, err := gitLine(repo, "rev-parse", "--show-object-format")
324 if err != nil {
325 return "", err
326 }
327 roots, err := gitLine(repo, "rev-list", "--max-parents=0", tip)
328 if err != nil {
329 return "", fmt.Errorf("the history of %s in the instance repository does not read: %w", instanceTip, err)
330 }
331 id, err := approval.InstanceID(format, strings.Fields(roots))
332 if err != nil {
333 return "", fmt.Errorf("the instance identity: %w", err)
334 }
335 return id, nil
336}
337
338// signersTree writes the publication's objects into repo and returns its
339// tree. The tree holds a signer projects file when there is one, and an
340// instance identity when there is one.
341func signersTree(repo string, pub publication) (string, error) {
342 if err := note.CheckName(pub.name); err != nil {
343 return "", fmt.Errorf("--name: %w", err)
344 }
345 // A file with no key at all reads, and is published: it is what the
346 // registry compiles to once every signing key is revoked.
347 parsed, err := note.ParseVerifierKeys(pub.keys)
348 if err != nil {
349 return "", fmt.Errorf("the known-signers file does not read: %w", err)
350 }
351 signs := false
352 for _, k := range parsed {
353 signs = signs || k.Name == pub.name
354 }
355 if !signs {
356 fmt.Fprintf(os.Stderr, "integrator: the known-signers file holds no key under %s, the name the controller signs under, so no client can verify its transfer statements with it\n", pub.name)
357 }
358 type file struct {
359 name string
360 body []byte
361 }
362 files := []file{
363 {signersName, []byte(pub.name + "\n")},
364 {signersKeys, pub.keys},
365 {signersApprovers, pub.approvers},
366 {signersHardware, pub.hardware},
367 }
368 if len(pub.projects) > 0 {
369 files = append(files, file{signersProjects, pub.projects})
370 }
371 if pub.instance != "" {
372 files = append(files, file{signersInstance, []byte(pub.instance + "\n")})
373 }
374 var entries strings.Builder
375 for _, f := range files {
376 blob, err := hashObject(repo, f.body)
377 if err != nil {
378 return "", err
379 }
380 fmt.Fprintf(&entries, "100644 blob %s\t%s\n", blob, f.name)
381 }
382 out, err := gitInput(repo, []byte(entries.String()), "mktree")
383 if err != nil {
384 return "", err
385 }
386 return strings.TrimSpace(string(out)), nil
387}
388
389// lockSigners takes the publication's lock and returns what lets it go. A
390// run that asks while another holds it waits its turn. The lock is
391// flock's, on signersLock, so the kernel lets it go when the run ends
392// however it ends, and a run that dies leaves nothing to clear.
393func lockSigners(repo string) (func(), error) {
394 path := filepath.Join(repo, signersLock)
395 f, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0o644)
396 if err != nil {
397 return nil, fmt.Errorf("could not open the publication's lock: %w", err)
398 }
399 if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
400 f.Close()
401 return nil, fmt.Errorf("could not lock %s: %w", path, err)
402 }
403 return func() { f.Close() }, nil // close lets the flock go
404}
405
406func hashObject(repo string, body []byte) (string, error) {
407 out, err := gitInput(repo, body, "hash-object", "-w", "--stdin")
408 return string(bytes.TrimSpace(out)), err
409}