gunk-dev/the-valley

compile.go

sourceb40fcdedd01cmain's published tip history
7.1 KiB
1package main
2
3import (
4 "bytes"
5 "flag"
6 "fmt"
7 "os"
8 "path/filepath"
9 "regexp"
10 "strings"
11 "time"
12
13 "the-valley/approval"
14)
15
16func compile(args []string) error {
17 fs := flag.NewFlagSet("compile", flag.ExitOnError)
18 fs.Usage = func() { fmt.Fprint(os.Stderr, usage) }
19 repo := fs.String("repo", "", "the bare instance repository carrying the registry")
20 ref := fs.String("ref", "refs/heads/main", "the ref whose tip is read")
21 dir := fs.String("dir", "identity", "the registry's directory in that tip")
22 schema := fs.String("schema", os.Getenv("VALLEY_IDENTITY_SCHEMA"), "the identity schema")
23 knownSigners := fs.String("known-signers", "", "where the verifier keys are written")
24 authorizedKeys := fs.String("authorized-keys", "", "where the tagged authorized_keys is written")
25 grantsFile := fs.String("grants", "", "where the grants the pre-receive hook checks are written")
26 approvalSignersFile := fs.String("approval-signers", "", "where the verifier keys of every approval key are written")
27 approvalHardwareFile := fs.String("approval-signers-hardware", "", "where the verifier keys of the hardware approval keys are written")
28 declaredKeys := fs.String("declared-keys", "", "the authorized_keys lines the host declares by hand")
29 now := fs.String("now", "", "the day expiry and certificate validity are judged against")
30 if err := fs.Parse(args); err != nil {
31 return err
32 }
33 for _, required := range []struct{ flag, value string }{
34 {"repo", *repo},
35 {"schema", *schema},
36 {"known-signers", *knownSigners},
37 {"authorized-keys", *authorizedKeys},
38 {"grants", *grantsFile},
39 } {
40 if required.value == "" {
41 return fmt.Errorf("--%s is required", required.flag)
42 }
43 }
44 // A full ref name is read by that exact name. Any other name, such as
45 // main, git would resolve by trying several refs in turn, and a pusher
46 // can make one of them.
47 if !strings.HasPrefix(*ref, "refs/") {
48 return fmt.Errorf("--ref %s is not a full ref name; name it whole, as refs/heads/main", *ref)
49 }
50
51 // The day expiry is judged against. A flag rather than the clock alone,
52 // so a compilation can be reproduced and a check can pin one.
53 day := time.Now().UTC().Truncate(24 * time.Hour)
54 if *now != "" {
55 parsed, err := time.Parse(dateLayout, *now)
56 if err != nil {
57 return fmt.Errorf("--now %q is not a calendar day", *now)
58 }
59 day = parsed
60 }
61
62 var declared map[string]string
63 if *declaredKeys != "" {
64 var err error
65 if declared, err = readDeclaredKeys(*declaredKeys); err != nil {
66 return err
67 }
68 }
69 r, commit, err := readRegistry(*repo, *ref, *dir, *schema)
70 if err != nil {
71 return err
72 }
73 a, err := render(r, day, declared)
74 if err != nil {
75 return fmt.Errorf("the registry at %s does not compile: %w", commit, err)
76 }
77
78 approvers, hardware, err := stampApproval(a, approval.Authority{Ref: *ref, Commit: commit, Day: day})
79 if err != nil {
80 return err
81 }
82
83 // The omissions, before the artifacts are written: an entry that has
84 // aged out is the compiler doing its job, and it is not a silent one.
85 for _, note := range a.notes {
86 fmt.Fprintf(os.Stderr, "identity: %s\n", note)
87 }
88
89 signersWritten, err := writeArtifact(*knownSigners, a.knownSigners)
90 if err != nil {
91 return err
92 }
93 keysWritten, err := writeArtifact(*authorizedKeys, a.authorizedKeys)
94 if err != nil {
95 return err
96 }
97 grantsWritten, err := writeArtifact(*grantsFile, a.grants)
98 if err != nil {
99 return err
100 }
101
102 // The approval files are written only where the caller names them.
103 // Every render computes both, so a registry whose approval keys do not
104 // compile fails the whole compilation either way.
105 approval := ""
106 for _, f := range []struct {
107 path string
108 content []byte
109 count int
110 what string
111 }{
112 {*approvalSignersFile, approvers, a.approvers, "approval signer(s)"},
113 {*approvalHardwareFile, hardware, a.hardware, "hardware approval signer(s)"},
114 } {
115 if f.path == "" {
116 continue
117 }
118 written, err := writeArtifact(f.path, f.content)
119 if err != nil {
120 return err
121 }
122 approval += fmt.Sprintf(", %d %s%s", f.count, f.what, changed(written))
123 }
124
125 fmt.Fprintf(os.Stderr, "identity: %s at %s: %d verifier key(s)%s, %d authorized key(s)%s, %d grant(s)%s%s\n",
126 *ref, commit, a.signers, changed(signersWritten), a.authorized, changed(keysWritten),
127 a.granted, changed(grantsWritten), approval)
128 return nil
129}
130
131// stampApproval is the two approval signers files as they are written:
132// each opens with the authority stamp (approval.Authority), naming the ref
133// the registry was read at, the commit that ref resolved to, and the day
134// expiry was judged on, and then holds the rendered file byte for byte.
135// The commit is the one every document was read from, so the stamp names
136// exactly what the keys below it render, even when the ref has moved
137// since.
138func stampApproval(a artifacts, source approval.Authority) (approvers, hardware []byte, err error) {
139 stamp, err := source.Stamp()
140 if err != nil {
141 return nil, nil, fmt.Errorf("the approval signers files cannot be stamped: %w", err)
142 }
143 return append([]byte(stamp), a.approvalSigners...), append([]byte(stamp), a.approvalHardware...), nil
144}
145
146// readDeclaredKeys reads the authorized_keys lines the host declares by
147// hand, and maps each key to the principal its entry is tagged with.
148func readDeclaredKeys(path string) (map[string]string, error) {
149 body, err := os.ReadFile(path)
150 if err != nil {
151 return nil, err
152 }
153 declared := map[string]string{}
154 for _, line := range strings.Split(string(body), "\n") {
155 blob := keyBlob(line)
156 if blob == "" {
157 continue
158 }
159 tag := ""
160 if m := principalTag.FindStringSubmatch(line); m != nil {
161 tag = m[1]
162 }
163 declared[blob] = tag
164 }
165 return declared, nil
166}
167
168// principalTag is the option a tagged entry carries.
169var principalTag = regexp.MustCompile(`environment="` + principalEnv + `=([^"]*)"`)
170
171// keyBlob is the base64 key in an authorized_keys line: the field after the
172// first one naming a key type.
173func keyBlob(line string) string {
174 fields := strings.Fields(line)
175 for i, f := range fields[:max(len(fields)-1, 0)] {
176 if strings.HasPrefix(f, "ssh-") || strings.HasPrefix(f, "ecdsa-") || strings.HasPrefix(f, "sk-") {
177 return fields[i+1]
178 }
179 }
180 return ""
181}
182
183func changed(written bool) string {
184 if written {
185 return " written"
186 }
187 return " unchanged"
188}
189
190// writeArtifact replaces one file by rename, and only when its content
191// differs. Every artifact is rendered before any is written, so the only
192// way to see one of them newer than another is a crash between two renames
193// — and none can ever be seen half-written.
194func writeArtifact(path string, content []byte) (bool, error) {
195 if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, content) {
196 return false, nil
197 }
198 dir := filepath.Dir(path)
199 f, err := os.CreateTemp(dir, filepath.Base(path)+".tmp")
200 if err != nil {
201 return false, err
202 }
203 defer os.Remove(f.Name())
204 if _, err := f.Write(content); err != nil {
205 f.Close()
206 return false, err
207 }
208 // sshd reads the authorized_keys file and refuses one anybody but its
209 // owner can write, so the mode is stated rather than left to CreateTemp.
210 if err := f.Chmod(0o644); err != nil {
211 f.Close()
212 return false, err
213 }
214 if err := f.Close(); err != nil {
215 return false, err
216 }
217 return true, os.Rename(f.Name(), path)
218}