| 1 | package main |
| 2 | |
| 3 | // The statement's written form: the exact bytes a signature covers. |
| 4 | // |
| 5 | // A statement is written as lines. The first line is "valley-statement-v1", |
| 6 | // the name of this form. Every line after it is a key, one space, and a |
| 7 | // value, and the lines are sorted by key, ascending, comparing bytes. The |
| 8 | // text ends with a newline. |
| 9 | // |
| 10 | // valley-statement-v1 |
| 11 | // predicate.check.name prose-format |
| 12 | // predicate.result passed |
| 13 | // predicateType the-valley/check/pure/v1 |
| 14 | // subject.primary valley-tree-v1 |
| 15 | // |
| 16 | // A key is the path to the value from the document's root, with a dot |
| 17 | // between segments. A segment that is a decimal number is an index into an |
| 18 | // array, so `provenance.delegation.0.principal` is the principal of the |
| 19 | // first recorded delegation. |
| 20 | // |
| 21 | // The form has no escapes, and that is the whole reason it was chosen. A |
| 22 | // value is written as its own bytes, so there is exactly one way to write |
| 23 | // it and nothing for two implementations to disagree about. Everything a |
| 24 | // value may not contain is refused instead of escaped: a newline or any |
| 25 | // other ASCII control character, because those are what make a line a |
| 26 | // line, and the empty string, because a line's value is what follows the |
| 27 | // first space and an empty one leaves an invisible trailing space behind. |
| 28 | // |
| 29 | // The rules below are what make one document into one byte sequence. |
| 30 | // |
| 31 | // 1. Every leaf is a string. A number, a boolean and a null are refused, |
| 32 | // because nobody has decided how a statement writes one down and a |
| 33 | // guess would be a guess about signed bytes. |
| 34 | // 2. Lines are sorted by key bytes and no key repeats. Byte order is the |
| 35 | // only order because a key segment is ASCII. |
| 36 | // 3. An object or an array with nothing in it has no lines, so it cannot |
| 37 | // be written down at all. It is refused rather than dropped, so that |
| 38 | // what was validated and what was signed cannot come apart. |
| 39 | // 4. An array is dense: indices run from 0 with no gaps, written in |
| 40 | // decimal without leading zeros. Line order over indices is byte |
| 41 | // order, so `.10` sits between `.1` and `.2`; a reader rebuilds the |
| 42 | // array from the index and never from the order the lines arrive in. |
| 43 | // 5. A key segment starts with a letter and continues with letters, |
| 44 | // digits and dashes. That keeps a segment clear of the dot that |
| 45 | // separates segments, of the space that separates key from value, and |
| 46 | // of the digits that mark an index. |
| 47 | // |
| 48 | // Parsing enforces every one of these, so text that parses is text this |
| 49 | // renderer would have produced. attest/conformance/ pins that against a |
| 50 | // second implementation. |
| 51 | |
| 52 | import ( |
| 53 | "bytes" |
| 54 | "encoding/json" |
| 55 | "fmt" |
| 56 | "sort" |
| 57 | "strconv" |
| 58 | "strings" |
| 59 | "unicode/utf8" |
| 60 | ) |
| 61 | |
| 62 | // statementForm names this written form, and is the first line of every |
| 63 | // statement written in it. A signature covers the text and nothing else, |
| 64 | // so this line is what tells one kind of signed note from another: an |
| 65 | // attestation and a log checkpoint signed by the same key are different |
| 66 | // claims because their first lines differ, not because of anything in the |
| 67 | // envelope around them. |
| 68 | const statementForm = "valley-statement-v1" |
| 69 | |
| 70 | // renderText writes a document as statement text. |
| 71 | func renderText(doc any) ([]byte, error) { |
| 72 | var lines []textLine |
| 73 | if err := flatten("", doc, &lines); err != nil { |
| 74 | return nil, err |
| 75 | } |
| 76 | sort.Slice(lines, func(i, j int) bool { return lines[i].key < lines[j].key }) |
| 77 | |
| 78 | var b bytes.Buffer |
| 79 | b.WriteString(statementForm) |
| 80 | b.WriteByte('\n') |
| 81 | for _, l := range lines { |
| 82 | b.WriteString(l.key) |
| 83 | b.WriteByte(' ') |
| 84 | b.WriteString(l.value) |
| 85 | b.WriteByte('\n') |
| 86 | } |
| 87 | return b.Bytes(), nil |
| 88 | } |
| 89 | |
| 90 | // renderJSON writes a JSON document as statement text. JSON is how a |
| 91 | // statement is composed and how it is handed to `cue vet`; this form is |
| 92 | // how it is signed. UseNumber keeps a number a number rather than a |
| 93 | // float64, so a document carrying one is refused rather than quietly |
| 94 | // rounded on the way through. |
| 95 | func renderJSON(raw []byte) ([]byte, error) { |
| 96 | var doc any |
| 97 | dec := json.NewDecoder(bytes.NewReader(raw)) |
| 98 | dec.UseNumber() |
| 99 | if err := dec.Decode(&doc); err != nil { |
| 100 | return nil, err |
| 101 | } |
| 102 | return renderText(doc) |
| 103 | } |
| 104 | |
| 105 | type textLine struct{ key, value string } |
| 106 | |
| 107 | func flatten(key string, v any, out *[]textLine) error { |
| 108 | where := key |
| 109 | if where == "" { |
| 110 | where = "the statement" |
| 111 | } |
| 112 | switch t := v.(type) { |
| 113 | case string: |
| 114 | if err := checkValue(t); err != nil { |
| 115 | return fmt.Errorf("%s: %w", where, err) |
| 116 | } |
| 117 | *out = append(*out, textLine{key, t}) |
| 118 | case map[string]any: |
| 119 | if len(t) == 0 { |
| 120 | return fmt.Errorf("%s: an object with no fields has no lines, so it cannot be written down", where) |
| 121 | } |
| 122 | for k, e := range t { |
| 123 | if err := checkSegment(k); err != nil { |
| 124 | return fmt.Errorf("%s: %w", where, err) |
| 125 | } |
| 126 | if err := flatten(join(key, k), e, out); err != nil { |
| 127 | return err |
| 128 | } |
| 129 | } |
| 130 | case []any: |
| 131 | if len(t) == 0 { |
| 132 | return fmt.Errorf("%s: an array with no elements has no lines, so it cannot be written down", where) |
| 133 | } |
| 134 | for i, e := range t { |
| 135 | if err := flatten(join(key, strconv.Itoa(i)), e, out); err != nil { |
| 136 | return err |
| 137 | } |
| 138 | } |
| 139 | case json.Number: |
| 140 | return fmt.Errorf("%s: %s is a number; a statement carries none, and how one is written down has never been decided", where, t) |
| 141 | case bool: |
| 142 | return fmt.Errorf("%s: %t is a boolean; a statement carries none, and how one is written down has never been decided", where, t) |
| 143 | case nil: |
| 144 | return fmt.Errorf("%s: is null; a field a statement does not carry is left out rather than written as null", where) |
| 145 | default: |
| 146 | return fmt.Errorf("%s: a statement may not carry %T", where, v) |
| 147 | } |
| 148 | return nil |
| 149 | } |
| 150 | |
| 151 | func join(key, segment string) string { |
| 152 | if key == "" { |
| 153 | return segment |
| 154 | } |
| 155 | return key + "." + segment |
| 156 | } |
| 157 | |
| 158 | // checkSegment holds a key segment to what a line can carry unambiguously: |
| 159 | // a letter, then letters, digits and dashes. A dot would look like the |
| 160 | // separator between segments, a space like the separator between key and |
| 161 | // value, and a leading digit like an array index. |
| 162 | func checkSegment(s string) error { |
| 163 | switch { |
| 164 | case s == "": |
| 165 | return fmt.Errorf("a key segment may not be empty") |
| 166 | case strings.Contains(s, "."): |
| 167 | return fmt.Errorf("key segment %q contains a dot, which separates one segment from the next", s) |
| 168 | case strings.Contains(s, " "): |
| 169 | return fmt.Errorf("key segment %q contains a space, which separates the key from the value", s) |
| 170 | case s[0] >= '0' && s[0] <= '9': |
| 171 | return fmt.Errorf("key segment %q starts with a digit, which is how an array index is written", s) |
| 172 | } |
| 173 | for i, r := range s { |
| 174 | ok := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' |
| 175 | if !ok { |
| 176 | return fmt.Errorf("key segment %q holds %q at byte %d; a segment is a letter followed by letters, digits and dashes", s, r, i) |
| 177 | } |
| 178 | } |
| 179 | return nil |
| 180 | } |
| 181 | |
| 182 | // checkValue holds a value to what one line can carry. There is no escape |
| 183 | // mechanism to fall back on, so anything unwritable is an error here |
| 184 | // rather than a second way of writing something. |
| 185 | func checkValue(s string) error { |
| 186 | if s == "" { |
| 187 | return fmt.Errorf("the value is empty; a field a statement does not carry is left out rather than written as an empty string") |
| 188 | } |
| 189 | if !utf8.ValidString(s) { |
| 190 | return fmt.Errorf("the value is not valid utf-8, so it has no written form") |
| 191 | } |
| 192 | for i := 0; i < len(s); i++ { |
| 193 | if c := s[i]; c == '\n' { |
| 194 | return fmt.Errorf("the value holds a newline, and a line ends where its newline is; there is no escape to write one with") |
| 195 | } else if c < 0x20 || c == 0x7f { |
| 196 | return fmt.Errorf("the value holds the control character %#02x, and there is no escape to write one with", c) |
| 197 | } |
| 198 | } |
| 199 | return nil |
| 200 | } |
| 201 | |
| 202 | // parseText reads statement text back into a document. It accepts only |
| 203 | // text this renderer would have produced: lines sorted by key with none |
| 204 | // repeated, segments and values within their shapes, and arrays dense from |
| 205 | // zero. That is what makes "the text is the written form of what it |
| 206 | // says" something a parser settles rather than a claim a verifier has to |
| 207 | // re-derive. |
| 208 | func parseText(raw []byte) (map[string]any, error) { |
| 209 | if len(raw) == 0 || raw[len(raw)-1] != '\n' { |
| 210 | return nil, fmt.Errorf("statement text must end with a newline") |
| 211 | } |
| 212 | lines := strings.Split(string(raw[:len(raw)-1]), "\n") |
| 213 | if lines[0] != statementForm { |
| 214 | return nil, fmt.Errorf("line 1 is %q; statement text opens with %q", lines[0], statementForm) |
| 215 | } |
| 216 | |
| 217 | root := &treeNode{children: map[string]*treeNode{}} |
| 218 | previous := "" |
| 219 | for i, l := range lines[1:] { |
| 220 | n := i + 2 |
| 221 | key, value, found := strings.Cut(l, " ") |
| 222 | if !found || value == "" { |
| 223 | return nil, fmt.Errorf("line %d is %q; a line is a key, one space, and a value", n, l) |
| 224 | } |
| 225 | if err := checkValue(value); err != nil { |
| 226 | return nil, fmt.Errorf("line %d: %w", n, err) |
| 227 | } |
| 228 | if key <= previous { |
| 229 | return nil, fmt.Errorf("line %d: key %q does not follow %q; lines are sorted by key, ascending, and no key repeats", n, key, previous) |
| 230 | } |
| 231 | previous = key |
| 232 | segments := strings.Split(key, ".") |
| 233 | for _, s := range segments { |
| 234 | if err := checkKeyOrIndex(s); err != nil { |
| 235 | return nil, fmt.Errorf("line %d: %w", n, err) |
| 236 | } |
| 237 | } |
| 238 | if err := root.insert(segments, value); err != nil { |
| 239 | return nil, fmt.Errorf("line %d: %w", n, err) |
| 240 | } |
| 241 | } |
| 242 | if len(root.children) == 0 { |
| 243 | return nil, fmt.Errorf("the text carries no lines, so it says nothing") |
| 244 | } |
| 245 | doc, err := root.document("") |
| 246 | if err != nil { |
| 247 | return nil, err |
| 248 | } |
| 249 | return doc.(map[string]any), nil |
| 250 | } |
| 251 | |
| 252 | // checkKeyOrIndex admits what a rendered key segment can be: a name, or an |
| 253 | // array index written in decimal with no leading zeros. |
| 254 | func checkKeyOrIndex(s string) error { |
| 255 | if s != "" && s[0] >= '0' && s[0] <= '9' { |
| 256 | if s != "0" && s[0] == '0' { |
| 257 | return fmt.Errorf("index %q has a leading zero; an index is written in decimal without one", s) |
| 258 | } |
| 259 | if _, err := strconv.Atoi(s); err != nil { |
| 260 | return fmt.Errorf("key segment %q starts with a digit but is not an array index", s) |
| 261 | } |
| 262 | return nil |
| 263 | } |
| 264 | return checkSegment(s) |
| 265 | } |
| 266 | |
| 267 | // treeNode is the document being rebuilt: either a value or the segments |
| 268 | // found beneath a key. |
| 269 | type treeNode struct { |
| 270 | value string |
| 271 | leaf bool |
| 272 | children map[string]*treeNode |
| 273 | } |
| 274 | |
| 275 | func (t *treeNode) insert(segments []string, value string) error { |
| 276 | if t.leaf { |
| 277 | return fmt.Errorf("a key is both a value and a path to other values") |
| 278 | } |
| 279 | head := segments[0] |
| 280 | child, ok := t.children[head] |
| 281 | if !ok { |
| 282 | child = &treeNode{children: map[string]*treeNode{}} |
| 283 | t.children[head] = child |
| 284 | } |
| 285 | if len(segments) == 1 { |
| 286 | if child.leaf || len(child.children) > 0 { |
| 287 | return fmt.Errorf("a key is both a value and a path to other values") |
| 288 | } |
| 289 | child.leaf, child.value = true, value |
| 290 | return nil |
| 291 | } |
| 292 | return child.insert(segments[1:], value) |
| 293 | } |
| 294 | |
| 295 | func (t *treeNode) document(key string) (any, error) { |
| 296 | if t.leaf { |
| 297 | return t.value, nil |
| 298 | } |
| 299 | where := key |
| 300 | if where == "" { |
| 301 | where = "the statement" |
| 302 | } |
| 303 | indexed := 0 |
| 304 | for s := range t.children { |
| 305 | if s[0] >= '0' && s[0] <= '9' { |
| 306 | indexed++ |
| 307 | } |
| 308 | } |
| 309 | if indexed > 0 && indexed != len(t.children) { |
| 310 | return nil, fmt.Errorf("%s has both array indices and named fields beneath it", where) |
| 311 | } |
| 312 | if indexed > 0 { |
| 313 | out := make([]any, len(t.children)) |
| 314 | for s, child := range t.children { |
| 315 | i, _ := strconv.Atoi(s) |
| 316 | if i >= len(t.children) { |
| 317 | return nil, fmt.Errorf("%s runs to index %d but holds %d elements; an array's indices run from 0 with no gaps", where, i, len(t.children)) |
| 318 | } |
| 319 | v, err := child.document(join(key, s)) |
| 320 | if err != nil { |
| 321 | return nil, err |
| 322 | } |
| 323 | out[i] = v |
| 324 | } |
| 325 | return out, nil |
| 326 | } |
| 327 | out := make(map[string]any, len(t.children)) |
| 328 | for s, child := range t.children { |
| 329 | v, err := child.document(join(key, s)) |
| 330 | if err != nil { |
| 331 | return nil, err |
| 332 | } |
| 333 | out[s] = v |
| 334 | } |
| 335 | return out, nil |
| 336 | } |