gunk-dev/the-valley

note.go

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