gunk-dev/the-valley

render.go

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