gunk-dev/the-valley

render.go

sourceef747ea0f748main's published tip history
9.3 KiB
1package main
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "crypto/sha256"
7 "encoding/base64"
8 "encoding/binary"
9 "fmt"
10 "sort"
11 "strings"
12 "time"
13)
14
15const (
16 // The algorithm identifier the note format prefixes a public key with,
17 // and the only algorithm this program renders (attest/sign.go).
18 algEd25519 = 1
19 sshEd25519 = "ssh-ed25519"
20
21 // The environment variable carrying the pushing key's principal name.
22 // One name, shared with nix/valley-host.nix — change it in both.
23 principalEnv = "VALLEY_PRINCIPAL"
24
25 dateLayout = "2006-01-02"
26)
27
28const knownSignersHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8).
29# Verifier keys whose attestations count, one per line: the name a key
30# signs under, the note format's key hash over that name and key, and
31# base64 of the algorithm byte and the raw ed25519 public key.
32`
33
34const authorizedKeysHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8).
35# Keys that may push, each tagged with the principal it acts as. The git
36# user's shell reads the tag off the entry of the key sshd authenticated,
37# which is what tells one pusher from another over a shared user.
38`
39
40const grantsHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8).
41# Grants the pre-receive hook checks, one per line: the grant, then the
42# principal holding it. A principal not named here holds none.
43`
44
45// The lines a holder of a grant at a hook boundary is written under: the
46// grant the hook checks. grantRequest is the approve grant, the verb of
47// dcr-e544f20. A holder at a boundary of kind approve or of kind request
48// is written under the name request, which every deployed hook reads, and
49// the hook takes a line naming either name as the approve grant.
50// grantRestack is the host restacker's.
51const (
52 grantRequest = "request"
53 grantRestack = "restack"
54)
55
56// artifacts is a whole compilation: every file, what was left out, and the
57// counts the journal line reports. Nothing is written until every part of
58// this exists, so a failure anywhere leaves the last good set intact.
59type artifacts struct {
60 knownSigners []byte
61 authorizedKeys []byte
62 grants []byte
63 notes []string
64 signers int
65 authorized int
66 granted int
67}
68
69// render turns a registry into every artifact as of one day. declared maps
70// each key the host authorizes by hand to the principal its entry is
71// tagged with, "" for an untagged one; nil when the caller names none.
72//
73// One key authorized as two principals is refused, whether both entries
74// are the registry's or one is the host's. sshd authorizes a key by the
75// first entry that names it, so which principal such a key pushed as would
76// depend on the order of lines and files, and a grant could silently stop
77// applying to the principal that holds it.
78func render(r registry, day time.Time, declared map[string]string) (artifacts, error) {
79 var a artifacts
80 var signers, authorized, granted []string
81 governed := false
82 authorizedAs := map[string]string{}
83
84 names := make([]string, 0, len(r.Principals))
85 for name := range r.Principals {
86 names = append(names, name)
87 }
88 sort.Strings(names)
89
90 for _, name := range names {
91 p := r.Principals[name]
92
93 expired, err := hasExpired(p.Expires, day)
94 if err != nil {
95 return a, fmt.Errorf("%s: %w", name, err)
96 }
97 if expired {
98 a.notes = append(a.notes, fmt.Sprintf(
99 "%s expired %s: %d key(s) and every grant omitted from all artifacts", name, p.Expires, len(p.Keys)))
100 continue
101 }
102
103 held, err := heldKinds(r, p)
104 if err != nil {
105 return a, fmt.Errorf("%s: %w", name, err)
106 }
107 governed = governed || held[boundaryRegistry]
108 pushes := held[boundaryGitPush]
109 if held[boundaryApprove] || held[boundaryRequest] {
110 granted = append(granted, grantRequest+" "+name)
111 }
112 if held[boundaryRestack] {
113 granted = append(granted, grantRestack+" "+name)
114 }
115
116 for i, k := range p.Keys {
117 pub, err := sshEd25519Public(k.Public)
118 if err != nil {
119 return a, fmt.Errorf("%s: key %d: %w", name, i, err)
120 }
121 if k.Signs != "" {
122 signers = append(signers, verifierKey(k.Signs, pub))
123 }
124 if pushes {
125 blob := strings.Fields(k.Public)[1]
126 if other, ok := authorizedAs[blob]; ok && other != name {
127 return a, fmt.Errorf("%s: key %d is also %s's, and one key authorizes one principal", name, i, other)
128 }
129 authorizedAs[blob] = name
130 if tag, ok := declared[blob]; ok && tag != name {
131 if tag == "" {
132 tag = "an untagged entry"
133 }
134 return a, fmt.Errorf("%s: key %d is also declared on this host as %s, and sshd reads the declared entry first, so the key would never push as %s; tag the declared key as %s or remove it", name, i, tag, name, name)
135 }
136 authorized = append(authorized, fmt.Sprintf("environment=%q %s", principalEnv+"="+name, k.Public))
137 }
138 }
139 }
140
141 // The state the whole render is refused for: after the expiry cut,
142 // nobody governs the registry's own stream (dcr-2f03be3).
143 if !governed {
144 return a, fmt.Errorf("governanceOrphaned: on %s no unexpired principal holds a grant at a boundary of kind %q",
145 day.Format(dateLayout), boundaryRegistry)
146 }
147
148 a.knownSigners, a.signers = artifact(knownSignersHeader, signers)
149 a.authorizedKeys, a.authorized = artifact(authorizedKeysHeader, authorized)
150 a.grants, a.granted = artifact(grantsHeader, granted)
151 return a, nil
152}
153
154// hasExpired reads an entry's expiry. The declared day is the first day the
155// entry no longer counts, so a compilation on it already omits the entry.
156func hasExpired(expires string, day time.Time) (bool, error) {
157 if expires == "" {
158 return false, nil
159 }
160 end, err := time.Parse(dateLayout, expires)
161 if err != nil {
162 return false, fmt.Errorf("expires %q is not a calendar day", expires)
163 }
164 return !day.Before(end), nil
165}
166
167// heldKinds answers which boundary kinds the entry holds a grant at. A
168// grant naming a boundary the registry does not declare fails the render:
169// the schema already refuses one, and a compiler that silently dropped it
170// would turn a typo into a quiet loss of access.
171func heldKinds(r registry, p principal) (map[string]bool, error) {
172 held := map[string]bool{}
173 for _, name := range sortedGrants(p.Grants) {
174 b, ok := r.Boundaries[p.Grants[name].Boundary]
175 if !ok {
176 return nil, fmt.Errorf("grant %s names boundary %q, which the registry does not declare",
177 name, p.Grants[name].Boundary)
178 }
179 held[b.Kind] = true
180 }
181 return held, nil
182}
183
184func sortedGrants(g map[string]grant) []string {
185 names := make([]string, 0, len(g))
186 for name := range g {
187 names = append(names, name)
188 }
189 sort.Strings(names)
190 return names
191}
192
193// artifact writes one file's bytes: the header, then the lines sorted and
194// deduplicated. Sorting is what makes a compilation reproducible, so a
195// registry that did not change re-renders byte for byte and the atomic
196// replace below has nothing to do.
197func artifact(header string, lines []string) ([]byte, int) {
198 sort.Strings(lines)
199 out := bytes.NewBufferString(header)
200 previous := ""
201 count := 0
202 for i, line := range lines {
203 if i > 0 && line == previous {
204 continue
205 }
206 previous = line
207 count++
208 out.WriteString(line)
209 out.WriteByte('\n')
210 }
211 return out.Bytes(), count
212}
213
214// keyHash is the note format's identifier for a name-and-key pair, byte for
215// byte what attest computes (attest/sign.go): sha256 over the name, a
216// newline, the algorithm byte and the public key, truncated to four bytes.
217// The name is inside the hash, which is why a key's signing name is
218// recorded per key and getting it wrong compiles a line no verifier
219// matches.
220func keyHash(name string, pub ed25519.PublicKey) uint32 {
221 h := sha256.New()
222 h.Write([]byte(name))
223 h.Write([]byte("\n"))
224 h.Write([]byte{algEd25519})
225 h.Write(pub)
226 return binary.BigEndian.Uint32(h.Sum(nil))
227}
228
229// verifierKey is one line of the known-signers file.
230func verifierKey(name string, pub ed25519.PublicKey) string {
231 return fmt.Sprintf("%s+%08x+%s", name, keyHash(name, pub),
232 base64.StdEncoding.EncodeToString(append([]byte{algEd25519}, pub...)))
233}
234
235// sshEd25519Public takes the raw 32-byte public key out of an
236// authorized_keys line: base64 of the SSH wire format, which is the
237// algorithm name and the key, each length-prefixed.
238func sshEd25519Public(line string) (ed25519.PublicKey, error) {
239 fields := strings.Fields(line)
240 if len(fields) < 2 || fields[0] != sshEd25519 {
241 return nil, fmt.Errorf("%q is not an %s public key", line, sshEd25519)
242 }
243 blob, err := base64.StdEncoding.DecodeString(fields[1])
244 if err != nil {
245 return nil, fmt.Errorf("%s key: %w", sshEd25519, err)
246 }
247 algorithm, rest, err := sshString(blob)
248 if err != nil {
249 return nil, err
250 }
251 pub, rest, err := sshString(rest)
252 if err != nil {
253 return nil, err
254 }
255 switch {
256 case string(algorithm) != sshEd25519:
257 return nil, fmt.Errorf("key names algorithm %q, not %s", algorithm, sshEd25519)
258 case len(pub) != ed25519.PublicKeySize:
259 return nil, fmt.Errorf("key holds %d bytes, not the %d an ed25519 key has", len(pub), ed25519.PublicKeySize)
260 case len(rest) != 0:
261 return nil, fmt.Errorf("key carries %d trailing bytes", len(rest))
262 }
263 return ed25519.PublicKey(pub), nil
264}
265
266// sshString reads one length-prefixed field of the SSH wire format.
267func sshString(b []byte) (value, rest []byte, err error) {
268 if len(b) < 4 {
269 return nil, nil, fmt.Errorf("truncated key blob")
270 }
271 n := binary.BigEndian.Uint32(b[:4])
272 if uint64(n) > uint64(len(b)-4) {
273 return nil, nil, fmt.Errorf("key blob claims a %d-byte field it does not hold", n)
274 }
275 return b[4 : 4+n], b[4+n:], nil
276}