gunk-dev/the-valley

note.go

sourcee0e2aed6532emain's published tip history
13.7 KiB
1// Package note is the envelope a valley attestation travels in: a signed
2// note, in the format golang.org/x/mod/sumdb/note defines, around statement
3// text. It is the one reading of that envelope. attest writes notes with
4// it, attest verify opens them with it, and the pre-receive hook checks
5// pushed ones with it, so a note one of them accepts is a note all of them
6// accept.
7//
8// A note is the text, a blank line, and one or more signature lines. Each
9// signature line is an em-dash, a space, the signer's name, a space, and
10// base64 of a four-byte key hash followed by the raw Ed25519 signature
11// over the text:
12//
13// the-valley/attestation/v1
14// subject.primary valley-tree-v1
15// …
16//
17// — valley-host.example.org/attestations WhFo+DGb1c/Fk6…
18//
19// The reading is strict. A note that is not valid UTF-8, or holds an ASCII
20// control character other than the newline, is refused. So is a signature
21// line that is not exactly that shape, names a signer a verifier key could
22// not name, or carries anything but an Ed25519 signature. A line by a
23// signer the reader holds no key for is well formed and carried through as
24// unknown: several parties can sign one text, and a reader need not hold
25// every party's key. A note is accepted only when at least one signature
26// verifies under a key the reader holds, and every signature by such a key
27// does.
28//
29// The package depends on the standard library alone, like everything that
30// uses it.
31package note
32
33import (
34 "bytes"
35 "crypto/ed25519"
36 "crypto/sha256"
37 "encoding/base64"
38 "encoding/binary"
39 "errors"
40 "fmt"
41 "strings"
42 "unicode"
43 "unicode/utf8"
44)
45
46const (
47 // AlgEd25519 is the algorithm byte a verifier key's public key is
48 // prefixed with. Ed25519 is the only algorithm the valley signs or
49 // verifies with.
50 AlgEd25519 = 1
51
52 // Mark opens a signature line: U+2014 EM DASH, then a space.
53 Mark = "— "
54
55 // StatementType is the first line of every statement's written form.
56 // The signature covers the text and nothing else, so the text's own
57 // first line is what says a note is an attestation.
58 StatementType = "the-valley/attestation/v1"
59
60 // signatureSize is a signature line's decoded length: the key hash
61 // and the Ed25519 signature.
62 signatureSize = 4 + ed25519.SignatureSize
63)
64
65// KeyHash is the note format's identifier for a name-and-key pair: SHA-256
66// over the name, a newline, the algorithm byte and the public key,
67// truncated to its first four bytes. The name is inside the hash and
68// outside the signature, so the same key published under two names is two
69// verifier keys.
70func KeyHash(name string, pub ed25519.PublicKey) uint32 {
71 h := sha256.New()
72 h.Write([]byte(name))
73 h.Write([]byte("\n"))
74 h.Write([]byte{AlgEd25519})
75 h.Write(pub)
76 return binary.BigEndian.Uint32(h.Sum(nil))
77}
78
79// CheckName holds a signer's name to what a signature line and a verifier
80// key can carry: valid UTF-8, no space, because a space separates the name
81// from the signature, no control character, and no plus, because a plus
82// separates the fields of a verifier key.
83func CheckName(name string) error {
84 switch {
85 case name == "":
86 return errors.New("a signer name may not be empty")
87 case !utf8.ValidString(name):
88 return fmt.Errorf("signer name %q is not valid utf-8", name)
89 case strings.ContainsFunc(name, unicode.IsSpace):
90 return fmt.Errorf("signer name %q holds a space, which separates the name from the signature", name)
91 case strings.ContainsFunc(name, unicode.IsControl):
92 return fmt.Errorf("signer name %q holds a control character", name)
93 case strings.Contains(name, "+"):
94 return fmt.Errorf("signer name %q holds a plus, which separates the fields of a verifier key", name)
95 }
96 return nil
97}
98
99// CheckBytes holds a note, or the text inside one, to valid UTF-8 with no
100// ASCII control character but the newline.
101func CheckBytes(b []byte) error {
102 if !utf8.Valid(b) {
103 return errors.New("a note is valid utf-8, and this is not")
104 }
105 for _, c := range b {
106 if c < 0x20 && c != '\n' || c == 0x7f {
107 return fmt.Errorf("a note holds no ascii control character but the newline, and this holds %#02x", c)
108 }
109 }
110 return nil
111}
112
113// CheckText holds text about to be signed, or read out of a note, to what
114// the format allows: CheckBytes, and a closing newline.
115func CheckText(text []byte) error {
116 if len(text) == 0 || text[len(text)-1] != '\n' {
117 return errors.New("a note's text must end with a newline")
118 }
119 return CheckBytes(text)
120}
121
122// VerifierKey is a key a reader accepts signatures from: a name, the key
123// hash the name and key produce, and the public key.
124type VerifierKey struct {
125 Name string
126 Hash uint32
127 Pub ed25519.PublicKey
128}
129
130// NewVerifierKey pairs a name with a public key.
131func NewVerifierKey(name string, pub ed25519.PublicKey) VerifierKey {
132 return VerifierKey{Name: name, Hash: KeyHash(name, pub), Pub: pub}
133}
134
135// String is the verifier key's line: name+hash+base64 of the algorithm
136// byte and the public key.
137func (v VerifierKey) String() string {
138 return fmt.Sprintf("%s+%08x+%s", v.Name, v.Hash,
139 base64.StdEncoding.EncodeToString(append([]byte{AlgEd25519}, v.Pub...)))
140}
141
142// ParseVerifierKey reads one verifier key line. The key hash it carries is
143// checked against the one its name and public key produce, so a line whose
144// hash was edited is refused rather than quietly matching nothing.
145func ParseVerifierKey(line string) (VerifierKey, error) {
146 // Two separators and no more: the base64 that ends the line may hold
147 // a plus of its own.
148 parts := strings.SplitN(strings.TrimSpace(line), "+", 3)
149 if len(parts) != 3 {
150 return VerifierKey{}, fmt.Errorf("%q is not a verifier key: one is name+hash+base64", line)
151 }
152 name, written, encoded := parts[0], parts[1], parts[2]
153 if err := CheckName(name); err != nil {
154 return VerifierKey{}, err
155 }
156 raw, err := base64.StdEncoding.DecodeString(encoded)
157 if err != nil {
158 return VerifierKey{}, fmt.Errorf("verifier key %s: %w", name, err)
159 }
160 if len(raw) != 1+ed25519.PublicKeySize || raw[0] != AlgEd25519 {
161 return VerifierKey{}, fmt.Errorf("verifier key %s is not an ed25519 key", name)
162 }
163 v := NewVerifierKey(name, raw[1:])
164 if fmt.Sprintf("%08x", v.Hash) != written {
165 return VerifierKey{}, fmt.Errorf("verifier key %s carries hash %s, but its name and key produce %08x", name, written, v.Hash)
166 }
167 return v, nil
168}
169
170// ParseVerifierKeys reads a known-keys file's contents: one verifier key
171// per line, with blank lines and # comments skipped. A line that is not a
172// verifier key fails the whole read, naming the line.
173func ParseVerifierKeys(data []byte) ([]VerifierKey, error) {
174 var keys []VerifierKey
175 for i, line := range strings.Split(string(data), "\n") {
176 line = strings.TrimSpace(line)
177 if line == "" || strings.HasPrefix(line, "#") {
178 continue
179 }
180 v, err := ParseVerifierKey(line)
181 if err != nil {
182 return nil, fmt.Errorf("line %d: %w", i+1, err)
183 }
184 keys = append(keys, v)
185 }
186 return keys, nil
187}
188
189// Signature is one signature line as read: who it says signed, under which
190// key hash, the signature itself, and the line as written.
191type Signature struct {
192 Name string
193 Hash uint32
194 Sig []byte
195 Line string
196}
197
198// Split separates a note into its text and its signature lines, and holds
199// both to the format. The last blank line is the separator, so text holding
200// a blank line of its own does not move the split. Every line after it must
201// be a signature line, every signature line must carry an Ed25519
202// signature, and no signer may sign twice under one key hash.
203func Split(note []byte) (text []byte, sigs []Signature, err error) {
204 if err := CheckBytes(note); err != nil {
205 return nil, nil, err
206 }
207 split := bytes.LastIndex(note, []byte("\n\n"))
208 if split < 0 {
209 return nil, nil, errors.New("this is not a note: no blank line separates the text from its signatures")
210 }
211 text, block := note[:split+1], note[split+2:]
212 if err := CheckText(text); err != nil {
213 return nil, nil, err
214 }
215 if len(block) == 0 || block[len(block)-1] != '\n' {
216 return nil, nil, errors.New("this is not a note: the signature block is empty or does not end with a newline")
217 }
218 seen := map[string]bool{}
219 for _, line := range strings.Split(strings.TrimSuffix(string(block), "\n"), "\n") {
220 sig, err := parseSignature(line)
221 if err != nil {
222 return nil, nil, err
223 }
224 id := fmt.Sprintf("%s+%08x", sig.Name, sig.Hash)
225 if seen[id] {
226 return nil, nil, fmt.Errorf("the note carries two signatures by %s", id)
227 }
228 seen[id] = true
229 sigs = append(sigs, sig)
230 }
231 return text, sigs, nil
232}
233
234func parseSignature(line string) (Signature, error) {
235 rest, ok := strings.CutPrefix(line, Mark)
236 if !ok {
237 return Signature{}, fmt.Errorf("%q is not a signature line: one opens with an em-dash and a space", line)
238 }
239 name, encoded, ok := strings.Cut(rest, " ")
240 if !ok {
241 return Signature{}, fmt.Errorf("the signature line %q carries no signature", line)
242 }
243 if err := CheckName(name); err != nil {
244 return Signature{}, fmt.Errorf("the signature line %q: %w", line, err)
245 }
246 blob, err := base64.StdEncoding.DecodeString(encoded)
247 if err != nil {
248 return Signature{}, fmt.Errorf("the signature line for %q does not decode", name)
249 }
250 if len(blob) != signatureSize {
251 return Signature{}, fmt.Errorf("the signature line for %q is not an Ed25519 signature: it holds %d bytes, not %d", name, len(blob), signatureSize)
252 }
253 return Signature{Name: name, Hash: binary.BigEndian.Uint32(blob[:4]), Sig: blob[4:], Line: line}, nil
254}
255
256// SignatureLine is the signature line a key adds under text, with its
257// closing newline.
258func SignatureLine(text []byte, name string, priv ed25519.PrivateKey) string {
259 var hb [4]byte
260 binary.BigEndian.PutUint32(hb[:], KeyHash(name, priv.Public().(ed25519.PublicKey)))
261 blob := append(hb[:], ed25519.Sign(priv, text)...)
262 return Mark + name + " " + base64.StdEncoding.EncodeToString(blob) + "\n"
263}
264
265// Sign writes a note: the text, a blank line, and one signature line. What
266// it writes is held to what Split reads, so a note this package signs is
267// one it opens.
268func Sign(text []byte, name string, priv ed25519.PrivateKey) ([]byte, error) {
269 if err := CheckText(text); err != nil {
270 return nil, err
271 }
272 if err := CheckName(name); err != nil {
273 return nil, err
274 }
275 var b bytes.Buffer
276 b.Write(text)
277 b.WriteByte('\n')
278 b.WriteString(SignatureLine(text, name, priv))
279 return b.Bytes(), nil
280}
281
282// AddSignature adds a signature line to a note that already carries one:
283// a second party signing the same text, beside the first. Signing again
284// with a key that already signed leaves the note as it was.
285func AddSignature(note []byte, name string, priv ed25519.PrivateKey) ([]byte, error) {
286 if err := CheckName(name); err != nil {
287 return nil, err
288 }
289 text, sigs, err := Split(note)
290 if err != nil {
291 return nil, err
292 }
293 line := SignatureLine(text, name, priv)
294 hash := KeyHash(name, priv.Public().(ed25519.PublicKey))
295 for _, s := range sigs {
296 if s.Name == name && s.Hash == hash {
297 return note, nil
298 }
299 }
300 return append(append([]byte{}, note...), line...), nil
301}
302
303// Checked is a signature line and what a reader made of it: whether the
304// reader holds the key it names, and whether it verified.
305type Checked struct {
306 Signature
307 Known bool
308 Verified bool
309}
310
311// Open reads a note and checks its signatures against the keys a reader
312// holds. A signature by a key the reader holds must verify, or the whole
313// note is refused: one good signature standing beside a forgery is not a
314// note anybody should read past. At least one signature must verify.
315func Open(note []byte, known []VerifierKey) (text []byte, checked []Checked, err error) {
316 text, sigs, err := Split(note)
317 if err != nil {
318 return nil, nil, err
319 }
320 verified := 0
321 for _, s := range sigs {
322 c := Checked{Signature: s}
323 for _, k := range known {
324 if k.Name != s.Name || k.Hash != s.Hash {
325 continue
326 }
327 c.Known = true
328 if !ed25519.Verify(k.Pub, text, s.Sig) {
329 return nil, nil, fmt.Errorf("the signature by %s+%08x does not check out over this text", s.Name, s.Hash)
330 }
331 c.Verified = true
332 verified++
333 break
334 }
335 checked = append(checked, c)
336 }
337 if verified == 0 {
338 return nil, nil, errors.New("no signature on this note is by a key the verifier holds")
339 }
340 return text, checked, nil
341}
342
343// Subject is the primary member of a statement's subject digest set: the
344// scheme the statement names as primary, and the digest under it.
345type Subject struct {
346 Scheme string
347 Digest string
348}
349
350// StatementSubject reads the subject a statement's text names. The text
351// must open with the statement type, and every line after it must be a
352// key, one space, and a value, with no key twice. The primary digest is
353// the subject.digest.<scheme> line for the scheme subject.primary names.
354//
355// This is the part of a statement every reader needs before anything else
356// — which tree it is about. attest reads the rest of the text, and vets it
357// against the attestation schema.
358func StatementSubject(text []byte) (Subject, error) {
359 if err := CheckText(text); err != nil {
360 return Subject{}, err
361 }
362 lines := strings.Split(strings.TrimSuffix(string(text), "\n"), "\n")
363 if lines[0] != StatementType {
364 return Subject{}, fmt.Errorf("is not a statement: its text opens with %q, not %q", lines[0], StatementType)
365 }
366 fields := map[string]string{}
367 for i, line := range lines[1:] {
368 key, value, ok := strings.Cut(line, " ")
369 if !ok || key == "" || value == "" {
370 return Subject{}, fmt.Errorf("line %d is %q; a line is a key, one space, and a value", i+2, line)
371 }
372 if _, twice := fields[key]; twice {
373 return Subject{}, fmt.Errorf("line %d sets %s a second time", i+2, key)
374 }
375 fields[key] = value
376 }
377 scheme := fields["subject.primary"]
378 if scheme == "" {
379 return Subject{}, errors.New("names no primary subject digest")
380 }
381 digest := fields["subject.digest."+scheme]
382 if digest == "" {
383 return Subject{}, fmt.Errorf("names %s as its primary digest and carries no value for it", scheme)
384 }
385 return Subject{Scheme: scheme, Digest: digest}, nil
386}