gunk-dev/the-valley

signers.go

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