gunk-dev/the-valley

render.go

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