gunk-dev/the-valley

canonical.go

source07d67d385df1main's published tip history
5.3 KiB
1package main
2
3// The canonical form of a statement: the exact bytes the signature covers.
4// Two tools that compose the same statement must produce the same bytes,
5// or a signature made by one cannot be checked by the other.
6//
7// The rules are RFC 8785's, narrowed to what a statement can hold: object
8// members sorted by key, no whitespace between tokens, and minimal string
9// escaping. A statement carries strings, objects and arrays only โ€” never a
10// number โ€” so the one genuinely hard part of RFC 8785, canonicalizing
11// floating-point, cannot arise. A number reaching this code is a statement
12// shape nobody has decided the canonical form of, so it is an error rather
13// than a guess.
14//
15// Keys are sorted by their UTF-8 bytes. RFC 8785 sorts by UTF-16 code
16// units; the two orderings agree over ASCII and part company above it. So
17// ASCII is a condition of these bytes being the same bytes anyone else
18// renders, not a fact that happens to hold: #AsciiKey in
19// schema/attestation.cue keeps a non-ASCII key out of a statement, and a
20// key that reaches here anyway is refused rather than sorted.
21//
22// attest/conformance/ holds the vectors that pin all of this against a
23// second implementation.
24
25import (
26 "bytes"
27 "encoding/json"
28 "fmt"
29 "sort"
30 "unicode/utf8"
31)
32
33// canonicalRender renders JSON bytes into their canonical form. UseNumber
34// keeps a number a number instead of a float64, so a statement carrying one
35// is refused rather than quietly rounded on the way through.
36func canonicalRender(raw []byte) ([]byte, error) {
37 var generic any
38 dec := json.NewDecoder(bytes.NewReader(raw))
39 dec.UseNumber()
40 if err := dec.Decode(&generic); err != nil {
41 return nil, err
42 }
43 return canonicalJSON(generic)
44}
45
46func canonicalJSON(v any) ([]byte, error) {
47 var b bytes.Buffer
48 if err := writeCanonical(&b, v); err != nil {
49 return nil, err
50 }
51 return b.Bytes(), nil
52}
53
54// canonicalize round-trips a value through encoding/json so that struct
55// tags, omitempty and nesting are all applied before canonical bytes are
56// rendered from the resulting generic value.
57func canonicalize(v any) ([]byte, error) {
58 raw, err := json.Marshal(v)
59 if err != nil {
60 return nil, err
61 }
62 var generic any
63 dec := json.NewDecoder(bytes.NewReader(raw))
64 dec.UseNumber()
65 if err := dec.Decode(&generic); err != nil {
66 return nil, err
67 }
68 return canonicalJSON(generic)
69}
70
71func writeCanonical(b *bytes.Buffer, v any) error {
72 switch t := v.(type) {
73 case nil:
74 b.WriteString("null")
75 case bool:
76 if t {
77 b.WriteString("true")
78 } else {
79 b.WriteString("false")
80 }
81 case string:
82 return writeCanonicalString(b, t)
83 case []any:
84 b.WriteByte('[')
85 for i, e := range t {
86 if i > 0 {
87 b.WriteByte(',')
88 }
89 if err := writeCanonical(b, e); err != nil {
90 return err
91 }
92 }
93 b.WriteByte(']')
94 case map[string]any:
95 keys := make([]string, 0, len(t))
96 for k := range t {
97 if err := asciiKey(k); err != nil {
98 return err
99 }
100 keys = append(keys, k)
101 }
102 sort.Strings(keys)
103 b.WriteByte('{')
104 for i, k := range keys {
105 if i > 0 {
106 b.WriteByte(',')
107 }
108 if err := writeCanonicalString(b, k); err != nil {
109 return err
110 }
111 b.WriteByte(':')
112 if err := writeCanonical(b, t[k]); err != nil {
113 return err
114 }
115 }
116 b.WriteByte('}')
117 default:
118 return fmt.Errorf("canonical json: a statement may not carry %T", v)
119 }
120 return nil
121}
122
123// asciiKey refuses a key this code cannot order the way RFC 8785 orders it.
124// The failure it prevents is silent: a non-ASCII key sorts one way here and
125// another way in an implementation that follows the specification exactly,
126// so the two sign different bytes over the same statement and neither
127// signature checks against the other. The schema narrows further, to
128// printable ASCII; what is unorderable is what is refused here.
129func asciiKey(k string) error {
130 for i := 0; i < len(k); i++ {
131 if k[i] >= 0x80 {
132 return fmt.Errorf("canonical json: key %q is not ASCII; member order over it would not match RFC 8785's, so two implementations would sign different bytes", k)
133 }
134 }
135 return nil
136}
137
138// writeCanonicalString escapes as RFC 8785 does: the five short escapes,
139// \u00xx with lowercase hex for the control characters that have none, and
140// every other character as itself โ€” <, > and & included, and every
141// non-ASCII character as its own UTF-8 bytes rather than an escape.
142//
143// Escaping is spelled out here rather than delegated to encoding/json,
144// which escapes U+2028 and U+2029 for JavaScript's benefit and would put
145// this signer a codepoint apart from one that follows the specification.
146// Invalid UTF-8 has no canonical form, and encoding/json would substitute
147// U+FFFD for it, so it is refused for the same reason a number is.
148func writeCanonicalString(b *bytes.Buffer, s string) error {
149 if !utf8.ValidString(s) {
150 return fmt.Errorf("canonical json: %q is not valid utf-8; it has no canonical form", s)
151 }
152 b.WriteByte('"')
153 for i := 0; i < len(s); i++ {
154 switch c := s[i]; {
155 case c == '"':
156 b.WriteString(`\"`)
157 case c == '\\':
158 b.WriteString(`\\`)
159 case c == '\b':
160 b.WriteString(`\b`)
161 case c == '\t':
162 b.WriteString(`\t`)
163 case c == '\n':
164 b.WriteString(`\n`)
165 case c == '\f':
166 b.WriteString(`\f`)
167 case c == '\r':
168 b.WriteString(`\r`)
169 case c < 0x20:
170 fmt.Fprintf(b, `\u%04x`, c)
171 default:
172 b.WriteByte(c)
173 }
174 }
175 b.WriteByte('"')
176 return nil
177}