gunk-dev/the-valley

render.go

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