gunk-dev/the-valley

render.go

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