gunk-dev/the-valley

compile.go

sourcecfedff357a41main's published tip history
10.9 KiB
1package main
2
3import (
4 "bytes"
5 "errors"
6 "flag"
7 "fmt"
8 "os"
9 "path/filepath"
10 "regexp"
11 "strings"
12 "time"
13
14 "the-valley/approval"
15)
16
17func compile(args []string) error {
18 fs := flag.NewFlagSet("compile", flag.ExitOnError)
19 fs.Usage = func() { fmt.Fprint(os.Stderr, usage) }
20 repo := fs.String("repo", "", "the bare instance repository carrying the registry")
21 ref := fs.String("ref", "refs/heads/main", "the ref whose tip is read")
22 dir := fs.String("dir", "identity", "the registry's directory in that tip")
23 schema := fs.String("schema", os.Getenv("VALLEY_IDENTITY_SCHEMA"), "the identity schema")
24 knownSigners := fs.String("known-signers", "", "where the verifier keys are written")
25 authorizedKeys := fs.String("authorized-keys", "", "where the tagged authorized_keys is written")
26 grantsFile := fs.String("grants", "", "where the grants the pre-receive hook checks are written")
27 approvalSignersFile := fs.String("approval-signers", "", "where the verifier keys of every approval key are written")
28 approvalHardwareFile := fs.String("approval-signers-hardware", "", "where the verifier keys of the hardware approval keys are written")
29 declaredKeys := fs.String("declared-keys", "", "the authorized_keys lines the host declares by hand")
30 now := fs.String("now", "", "the day expiry and certificate validity are judged against")
31 if err := fs.Parse(args); err != nil {
32 return err
33 }
34 for _, required := range []struct{ flag, value string }{
35 {"repo", *repo},
36 {"schema", *schema},
37 {"known-signers", *knownSigners},
38 {"authorized-keys", *authorizedKeys},
39 {"grants", *grantsFile},
40 } {
41 if required.value == "" {
42 return fmt.Errorf("--%s is required", required.flag)
43 }
44 }
45 // A full ref name is read by that exact name. Any other name, such as
46 // main, git would resolve by trying several refs in turn, and a pusher
47 // can make one of them.
48 if !strings.HasPrefix(*ref, "refs/") {
49 return fmt.Errorf("--ref %s is not a full ref name; name it whole, as refs/heads/main", *ref)
50 }
51
52 // The day expiry is judged against. A flag rather than the clock alone,
53 // so a compilation can be reproduced and a check can pin one.
54 c := compilation{
55 repo: *repo, ref: *ref, dir: *dir, schema: *schema,
56 knownSigners: *knownSigners, authorizedKeys: *authorizedKeys, grants: *grantsFile,
57 approvalSigners: *approvalSignersFile, approvalHardware: *approvalHardwareFile,
58 today: func() time.Time { return time.Now().UTC().Truncate(24 * time.Hour) },
59 }
60 // A retry budget, not a count the inputs imply: room for the ref to
61 // move once, and the day to turn once unless --now pins it, while a
62 // run compiles, with a last compilation for the reading after them.
63 rounds := 3
64 if *now != "" {
65 parsed, err := time.Parse(dateLayout, *now)
66 if err != nil {
67 return fmt.Errorf("--now %q is not a calendar day", *now)
68 }
69 c.today = func() time.Time { return parsed }
70 rounds = 2
71 }
72
73 if *declaredKeys != "" {
74 var err error
75 if c.declared, err = readDeclaredKeys(*declaredKeys); err != nil {
76 return err
77 }
78 }
79 return converge(c.ref, rounds, c.read, c.compileAt)
80}
81
82// reading is what a compilation depends on that can change while it runs:
83// the object the ref holds, and the day expiry is judged against.
84type reading struct {
85 oid string
86 day time.Time
87}
88
89func (r reading) equal(o reading) bool {
90 return r.oid == o.oid && r.day.Equal(o.day)
91}
92
93// converge compiles what read returns, reads again, and compiles again
94// until a reading matches the one compiled, so a ref moved or a day turned
95// while a run compiles is compiled by that run. What starts a run cannot
96// be relied on to start another for such a change: systemd holds no watch
97// on the ref while the compiler runs, and does not see afterwards that the
98// ref was replaced, and a start requested while the compiler runs is
99// merged into that run. A change made after the last reading waits for
100// whatever starts the next run.
101//
102// A compilation that fails ends the run only when the reading after it
103// matches what it compiled. If the ref or the day changed meanwhile, the
104// failure is said and the run compiles again, so a landing that repairs a
105// registry while the broken one compiles is compiled by that run.
106//
107// rounds is the retry budget. A run whose inputs still change after that
108// many compilations fails, so the unit shows it. Its artifacts keep what
109// its compilations wrote: each is replaced whole, but a write that fails
110// part way leaves the ones before it from the newer registry.
111func converge(ref string, rounds int, read func() (reading, error), compileAt func(reading) error) error {
112 at, err := read()
113 if err != nil {
114 return err
115 }
116 for round := 1; ; round++ {
117 failed := compileAt(at)
118 again, err := read()
119 if err != nil {
120 return errors.Join(failed, err)
121 }
122 if again.equal(at) {
123 return failed
124 }
125 if round == rounds {
126 return errors.Join(failed, fmt.Errorf("%s kept moving while the registry was compiled: after %d compilations it holds %s", ref, rounds, again.oid))
127 }
128 if failed != nil {
129 fmt.Fprintf(os.Stderr, "identity: %v\n", failed)
130 }
131 if again.oid != at.oid {
132 fmt.Fprintf(os.Stderr, "identity: %s moved to %s while %s was compiled, so the registry is compiled again\n", ref, again.oid, at.oid)
133 } else {
134 fmt.Fprintf(os.Stderr, "identity: the day turned to %s while the registry was compiled, so it is compiled again\n", again.day.Format(dateLayout))
135 }
136 at = again
137 }
138}
139
140// compilation is where one run reads the registry and writes its
141// artifacts.
142type compilation struct {
143 repo, ref, dir, schema string
144 knownSigners, authorizedKeys, grants string
145 approvalSigners, approvalHardware string
146 declared map[string]string
147 today func() time.Time
148}
149
150// read resolves the ref by its exact name, and reads the day.
151func (c compilation) read() (reading, error) {
152 oid, ok, err := resolveRef(c.repo, c.ref)
153 if err != nil {
154 return reading{}, fmt.Errorf("could not read %s in %s: %w", c.ref, c.repo, err)
155 } else if !ok {
156 return reading{}, fmt.Errorf("%s has no %s", c.repo, c.ref)
157 }
158 return reading{oid: oid, day: c.today()}, nil
159}
160
161// compileAt renders the registry the reading's object holds, as of the
162// reading's day, and writes every artifact whose bytes changed.
163func (c compilation) compileAt(at reading) error {
164 r, commit, err := readRegistry(c.repo, c.ref, at.oid, c.dir, c.schema)
165 if err != nil {
166 return err
167 }
168 a, err := render(r, at.day, c.declared)
169 if err != nil {
170 return fmt.Errorf("the registry at %s does not compile: %w", commit, err)
171 }
172
173 approvers, hardware, err := stampApproval(a, approval.Authority{Ref: c.ref, Commit: commit, Day: at.day})
174 if err != nil {
175 return err
176 }
177
178 // The omissions, before the artifacts are written: an entry that has
179 // aged out is the compiler doing its job, and it is not a silent one.
180 for _, note := range a.notes {
181 fmt.Fprintf(os.Stderr, "identity: %s\n", note)
182 }
183
184 signersWritten, err := writeArtifact(c.knownSigners, a.knownSigners)
185 if err != nil {
186 return err
187 }
188 keysWritten, err := writeArtifact(c.authorizedKeys, a.authorizedKeys)
189 if err != nil {
190 return err
191 }
192 grantsWritten, err := writeArtifact(c.grants, a.grants)
193 if err != nil {
194 return err
195 }
196
197 // The approval files are written only where the caller names them.
198 // Every render computes both, so a registry whose approval keys do not
199 // compile fails the whole compilation either way.
200 approval := ""
201 for _, f := range []struct {
202 path string
203 content []byte
204 count int
205 what string
206 }{
207 {c.approvalSigners, approvers, a.approvers, "approval signer(s)"},
208 {c.approvalHardware, hardware, a.hardware, "hardware approval signer(s)"},
209 } {
210 if f.path == "" {
211 continue
212 }
213 written, err := writeArtifact(f.path, f.content)
214 if err != nil {
215 return err
216 }
217 approval += fmt.Sprintf(", %d %s%s", f.count, f.what, changed(written))
218 }
219
220 fmt.Fprintf(os.Stderr, "identity: %s at %s: %d verifier key(s)%s, %d authorized key(s)%s, %d grant(s)%s%s\n",
221 c.ref, commit, a.signers, changed(signersWritten), a.authorized, changed(keysWritten),
222 a.granted, changed(grantsWritten), approval)
223 return nil
224}
225
226// stampApproval is the two approval signers files as they are written:
227// each opens with the authority stamp (approval.Authority), naming the ref
228// the registry was read at, the commit that ref resolved to, and the day
229// expiry was judged on, and then holds the rendered file byte for byte.
230// The commit is the one every document was read from, so the stamp names
231// exactly what the keys below it render, even when the ref has moved
232// since.
233func stampApproval(a artifacts, source approval.Authority) (approvers, hardware []byte, err error) {
234 stamp, err := source.Stamp()
235 if err != nil {
236 return nil, nil, fmt.Errorf("the approval signers files cannot be stamped: %w", err)
237 }
238 return append([]byte(stamp), a.approvalSigners...), append([]byte(stamp), a.approvalHardware...), nil
239}
240
241// readDeclaredKeys reads the authorized_keys lines the host declares by
242// hand, and maps each key to the principal its entry is tagged with.
243func readDeclaredKeys(path string) (map[string]string, error) {
244 body, err := os.ReadFile(path)
245 if err != nil {
246 return nil, err
247 }
248 declared := map[string]string{}
249 for _, line := range strings.Split(string(body), "\n") {
250 blob := keyBlob(line)
251 if blob == "" {
252 continue
253 }
254 tag := ""
255 if m := principalTag.FindStringSubmatch(line); m != nil {
256 tag = m[1]
257 }
258 declared[blob] = tag
259 }
260 return declared, nil
261}
262
263// principalTag is the option a tagged entry carries.
264var principalTag = regexp.MustCompile(`environment="` + principalEnv + `=([^"]*)"`)
265
266// keyBlob is the base64 key in an authorized_keys line: the field after the
267// first one naming a key type.
268func keyBlob(line string) string {
269 fields := strings.Fields(line)
270 for i, f := range fields[:max(len(fields)-1, 0)] {
271 if strings.HasPrefix(f, "ssh-") || strings.HasPrefix(f, "ecdsa-") || strings.HasPrefix(f, "sk-") {
272 return fields[i+1]
273 }
274 }
275 return ""
276}
277
278func changed(written bool) string {
279 if written {
280 return " written"
281 }
282 return " unchanged"
283}
284
285// writeArtifact replaces one file by rename, and only when its content
286// differs. Every artifact is rendered before any is written, so the only
287// way to see one of them newer than another is a crash between two renames
288// — and none can ever be seen half-written.
289func writeArtifact(path string, content []byte) (bool, error) {
290 if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, content) {
291 return false, nil
292 }
293 dir := filepath.Dir(path)
294 f, err := os.CreateTemp(dir, filepath.Base(path)+".tmp")
295 if err != nil {
296 return false, err
297 }
298 defer os.Remove(f.Name())
299 if _, err := f.Write(content); err != nil {
300 f.Close()
301 return false, err
302 }
303 // sshd reads the authorized_keys file and refuses one anybody but its
304 // owner can write, so the mode is stated rather than left to CreateTemp.
305 if err := f.Chmod(0o644); err != nil {
306 f.Close()
307 return false, err
308 }
309 if err := f.Close(); err != nil {
310 return false, err
311 }
312 return true, os.Rename(f.Name(), path)
313}