gunk-dev/the-valley

text.go

source9081ff0f1d3cmain's published tip history
17.3 KiB
1package 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 the statement type,
6// which says what the document is and which revision of it this is.
7// Every line after it is a key, one space, and a value.
8//
9// the-valley/attestation/v1
10// subject.primary valley-tree-v1
11// subject.digest.git-sha1 99b5f2f7…
12// subject.digest.valley-tree-v1 73847e0b…
13// predicateType the-valley/check/pure/v1
14// predicate.check.name prose-format
15// predicate.check.runner nix
16// predicate.check.attribute prose-format
17// predicate.result passed
18// …
19//
20// A key is the path to the value from the document's root, with a dot
21// between segments. A segment that is a decimal number is an index into an
22// array, so `provenance.delegation.0.principal` is the principal of the
23// first recorded delegation.
24//
25// # Order
26//
27// Lines are written in the order a reader reads them: what the statement
28// is about, then what kind of claim it makes, then the claim, then what
29// produced the change. statementOrder is that order, written out, and it
30// is the whole of what "the written form" means for line order. A field
31// with no position in it has no written form, so a new field's position
32// arrives with the field, and the predicate type is versioned so a claim
33// shape can grow without moving what came before it.
34//
35// Within a set keyed by names a caller supplies rather than this table —
36// a digest set, and any map added later — entries sort by key. Fixed order
37// where position carries meaning, sorted order where it does not. An array
38// is positional, so its elements are written in index order.
39//
40// # No escapes
41//
42// The form has no escapes, and that is the whole reason it was chosen. A
43// value is written as its own bytes, so there is exactly one way to write
44// it and nothing for two implementations to disagree about. Everything a
45// value may not contain is refused instead of escaped: a newline or any
46// other ASCII control character, because those are what make a line a
47// line, and the empty string, because a line's value is what follows the
48// first space and an empty one leaves an invisible trailing space behind.
49//
50// The rest of what makes one document into one byte sequence:
51//
52// 1. Every leaf is a string. A number, a boolean and a null are refused,
53// because nobody has decided how a statement writes one down and a
54// guess would be a guess about signed bytes.
55// 2. An object or an array with nothing in it has no lines, so it cannot
56// be written down at all. It is refused rather than dropped, so that
57// what was validated and what was signed cannot come apart.
58// 3. An array is dense: indices run from 0 with no gaps, written in
59// decimal without leading zeros.
60// 4. A key segment starts with a letter and continues with letters,
61// digits and dashes. That keeps a segment clear of the dot that
62// separates segments, of the space that separates key from value, and
63// of the digits that mark an index.
64//
65// Text is accepted only if writing the document it says back out
66// reproduces it byte for byte, so text that parses is text this renderer
67// would have produced. attest/conformance/ pins that against a second
68// implementation.
69
70import (
71 "bytes"
72 "encoding/json"
73 "fmt"
74 "sort"
75 "strconv"
76 "strings"
77 "unicode/utf8"
78)
79
80// field is one entry in the order table: a name, and how what sits under
81// it is written.
82type field struct {
83 name string
84
85 // set marks a map whose keys come from a caller rather than from this
86 // table. Its entries carry no order of their own, so they sort by key.
87 set bool
88
89 // list marks an array. Its elements are positional, so they are
90 // written in index order, each one under the fields below.
91 list bool
92
93 // under is the order of what sits beneath this field.
94 under []field
95}
96
97func leaf(name string) field { return field{name: name} }
98func set(name string) field { return field{name: name, set: true} }
99func obj(name string, u ...field) field { return field{name: name, under: u} }
100
101// statementOrder is the order a statement's lines are written in.
102//
103// A statement is a document a reader reads in order to decide something,
104// so the reader's first question is answered first: what is this about.
105// The kind of claim comes next, because it says how to read what follows;
106// then the claim itself; then the provenance of the run that produced the
107// change, which is context for the claim rather than part of it.
108//
109// The predicate's own order is per predicate type, because the claim reads
110// differently for each. A pure claim reads as: the check, its result, and
111// then the three digests a verifier re-derives against. A notarization
112// reads as: the check, the environment it ran in, when that was, and what
113// was observed.
114func statementOrder(predicateType string) ([]field, error) {
115 var predicate field
116 switch predicateType {
117 case predicatePure:
118 predicate = obj("predicate",
119 checkOrder,
120 leaf("result"),
121 set("inputs"),
122 set("derivation"),
123 set("output"),
124 )
125 case predicateEffect:
126 predicate = obj("predicate",
127 checkOrder,
128 leaf("environment"),
129 leaf("observedAt"),
130 leaf("result"),
131 )
132 case "":
133 return nil, fmt.Errorf("the statement names no predicate type, so how its claim is written down is not decided")
134 default:
135 return nil, fmt.Errorf("predicate type %q has no written form; a claim shape is written down by the revision that publishes it", predicateType)
136 }
137 return []field{
138 obj("subject", leaf("primary"), set("digest")),
139 leaf("predicateType"),
140 predicate,
141 obj("provenance",
142 leaf("harness"),
143 leaf("model"),
144 set("prompt"),
145 set("context"),
146 field{name: "delegation", list: true, under: []field{
147 leaf("principal"),
148 leaf("grant"),
149 }},
150 ),
151 }, nil
152}
153
154// checkOrder is the check that ran: what it is called, how it was run, and
155// then whichever of the two the runner names it by.
156var checkOrder = obj("check",
157 leaf("name"),
158 leaf("runner"),
159 leaf("attribute"),
160 leaf("command"),
161)
162
163// renderText writes a document as statement text.
164func renderText(doc any) ([]byte, error) {
165 root, ok := doc.(map[string]any)
166 if !ok {
167 return nil, fmt.Errorf("a statement is an object, and this is %T", doc)
168 }
169 kind, _ := root["statementType"].(string)
170 if kind != statementType {
171 return nil, fmt.Errorf("the statement type is %q; %q is the one this writes down", root["statementType"], statementType)
172 }
173 predicateType, _ := root["predicateType"].(string)
174 order, err := statementOrder(predicateType)
175 if err != nil {
176 return nil, err
177 }
178
179 // Flatten first, which settles every value and every field name, then
180 // place the lines. A key the order table has no position for is left
181 // over, and left over is refused.
182 lines := map[string]string{}
183 if err := flatten("", root, lines); err != nil {
184 return nil, err
185 }
186 delete(lines, "statementType") // the header line carries it
187
188 var b bytes.Buffer
189 b.WriteString(kind)
190 b.WriteByte('\n')
191 placed := 0
192 for _, key := range orderedKeys(root, order, "") {
193 value, ok := lines[key]
194 if !ok {
195 continue
196 }
197 b.WriteString(key)
198 b.WriteByte(' ')
199 b.WriteString(value)
200 b.WriteByte('\n')
201 delete(lines, key)
202 placed++
203 }
204 for _, key := range sortedKeys(lines) {
205 return nil, fmt.Errorf("%s has no position in the written form of a %s", key, predicateType)
206 }
207 if placed == 0 {
208 return nil, fmt.Errorf("the statement carries nothing but its type")
209 }
210 return b.Bytes(), nil
211}
212
213// orderedKeys walks the order table over a document and returns the keys
214// it names, in order. A field the document does not carry contributes
215// nothing; what the table has no entry for is not reached at all, which is
216// how renderText finds it left over.
217func orderedKeys(doc map[string]any, order []field, prefix string) []string {
218 var out []string
219 for _, f := range order {
220 v, ok := doc[f.name]
221 if !ok {
222 continue
223 }
224 key := join(prefix, f.name)
225 switch {
226 case f.set:
227 members, ok := v.(map[string]any)
228 if !ok {
229 out = append(out, key)
230 continue
231 }
232 for _, name := range sortedAnyKeys(members) {
233 out = append(out, join(key, name))
234 }
235 case f.list:
236 elements, ok := v.([]any)
237 if !ok {
238 out = append(out, key)
239 continue
240 }
241 for i, e := range elements {
242 under, ok := e.(map[string]any)
243 if !ok {
244 out = append(out, join(key, strconv.Itoa(i)))
245 continue
246 }
247 out = append(out, orderedKeys(under, f.under, join(key, strconv.Itoa(i)))...)
248 }
249 case f.under != nil:
250 under, ok := v.(map[string]any)
251 if !ok {
252 out = append(out, key)
253 continue
254 }
255 out = append(out, orderedKeys(under, f.under, key)...)
256 default:
257 out = append(out, key)
258 }
259 }
260 return out
261}
262
263func sortedAnyKeys(m map[string]any) []string {
264 keys := make([]string, 0, len(m))
265 for k := range m {
266 keys = append(keys, k)
267 }
268 sort.Strings(keys)
269 return keys
270}
271
272// renderJSON writes a JSON document as statement text. JSON is how a
273// statement is composed and how it is handed to `cue vet`; this form is
274// how it is signed. UseNumber keeps a number a number rather than a
275// float64, so a document carrying one is refused rather than quietly
276// rounded on the way through.
277func renderJSON(raw []byte) ([]byte, error) {
278 var doc any
279 dec := json.NewDecoder(bytes.NewReader(raw))
280 dec.UseNumber()
281 if err := dec.Decode(&doc); err != nil {
282 return nil, err
283 }
284 return renderText(doc)
285}
286
287func flatten(key string, v any, out map[string]string) error {
288 where := key
289 if where == "" {
290 where = "the statement"
291 }
292 switch t := v.(type) {
293 case string:
294 if err := checkValue(t); err != nil {
295 return fmt.Errorf("%s: %w", where, err)
296 }
297 out[key] = t
298 case map[string]any:
299 if len(t) == 0 {
300 return fmt.Errorf("%s: an object with no fields has no lines, so it cannot be written down", where)
301 }
302 for k, e := range t {
303 if err := checkSegment(k); err != nil {
304 return fmt.Errorf("%s: %w", where, err)
305 }
306 if err := flatten(join(key, k), e, out); err != nil {
307 return err
308 }
309 }
310 case []any:
311 if len(t) == 0 {
312 return fmt.Errorf("%s: an array with no elements has no lines, so it cannot be written down", where)
313 }
314 for i, e := range t {
315 if err := flatten(join(key, strconv.Itoa(i)), e, out); err != nil {
316 return err
317 }
318 }
319 case json.Number:
320 return fmt.Errorf("%s: %s is a number; a statement carries none, and how one is written down has never been decided", where, t)
321 case bool:
322 return fmt.Errorf("%s: %t is a boolean; a statement carries none, and how one is written down has never been decided", where, t)
323 case nil:
324 return fmt.Errorf("%s: is null; a field a statement does not carry is left out rather than written as null", where)
325 default:
326 return fmt.Errorf("%s: a statement may not carry %T", where, v)
327 }
328 return nil
329}
330
331func join(key, segment string) string {
332 if key == "" {
333 return segment
334 }
335 return key + "." + segment
336}
337
338// checkSegment holds a key segment to what a line can carry unambiguously:
339// a letter, then letters, digits and dashes. A dot would look like the
340// separator between segments, a space like the separator between key and
341// value, and a leading digit like an array index.
342func checkSegment(s string) error {
343 switch {
344 case s == "":
345 return fmt.Errorf("a key segment may not be empty")
346 case strings.Contains(s, "."):
347 return fmt.Errorf("key segment %q contains a dot, which separates one segment from the next", s)
348 case strings.Contains(s, " "):
349 return fmt.Errorf("key segment %q contains a space, which separates the key from the value", s)
350 case s[0] >= '0' && s[0] <= '9':
351 return fmt.Errorf("key segment %q starts with a digit, which is how an array index is written", s)
352 }
353 for i, r := range s {
354 ok := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-'
355 if !ok {
356 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)
357 }
358 }
359 return nil
360}
361
362// checkValue holds a value to what one line can carry. There is no escape
363// mechanism to fall back on, so anything unwritable is an error here
364// rather than a second way of writing something.
365func checkValue(s string) error {
366 if s == "" {
367 return fmt.Errorf("the value is empty; a field a statement does not carry is left out rather than written as an empty string")
368 }
369 if !utf8.ValidString(s) {
370 return fmt.Errorf("the value is not valid utf-8, so it has no written form")
371 }
372 for i := 0; i < len(s); i++ {
373 if c := s[i]; c == '\n' {
374 return fmt.Errorf("the value holds a newline, and a line ends where its newline is; there is no escape to write one with")
375 } else if c < 0x20 || c == 0x7f {
376 return fmt.Errorf("the value holds the control character %#02x, and there is no escape to write one with", c)
377 }
378 }
379 return nil
380}
381
382// parseText reads statement text back into a document.
383//
384// It accepts text only if writing the document that text says back out
385// reproduces it byte for byte. That is the whole acceptance rule, and it
386// makes "these bytes are the written form of what they say" something a
387// verifier settles by reading rather than a claim it has to take on trust:
388// line order, a duplicated key, a set out of order and a value no line can
389// carry all fail the same way, because none of them is what a renderer
390// would have produced.
391func parseText(raw []byte) (map[string]any, error) {
392 if len(raw) == 0 || raw[len(raw)-1] != '\n' {
393 return nil, fmt.Errorf("statement text must end with a newline")
394 }
395 lines := strings.Split(string(raw[:len(raw)-1]), "\n")
396
397 root := &treeNode{children: map[string]*treeNode{}}
398 if err := root.insert([]string{"statementType"}, lines[0]); err != nil {
399 return nil, err
400 }
401 if err := checkValue(lines[0]); err != nil {
402 return nil, fmt.Errorf("line 1: %w", err)
403 }
404 for i, l := range lines[1:] {
405 n := i + 2
406 key, value, found := strings.Cut(l, " ")
407 if !found || value == "" {
408 return nil, fmt.Errorf("line %d is %q; a line is a key, one space, and a value", n, l)
409 }
410 if err := checkValue(value); err != nil {
411 return nil, fmt.Errorf("line %d: %w", n, err)
412 }
413 segments := strings.Split(key, ".")
414 for _, s := range segments {
415 if err := checkKeyOrIndex(s); err != nil {
416 return nil, fmt.Errorf("line %d: %w", n, err)
417 }
418 }
419 if err := root.insert(segments, value); err != nil {
420 return nil, fmt.Errorf("line %d: %w", n, err)
421 }
422 }
423 if len(root.children) < 2 {
424 return nil, fmt.Errorf("the text carries no lines, so it says nothing")
425 }
426 built, err := root.document("")
427 if err != nil {
428 return nil, err
429 }
430 doc := built.(map[string]any)
431
432 again, err := renderText(doc)
433 if err != nil {
434 return nil, err
435 }
436 if !bytes.Equal(again, raw) {
437 return nil, fmt.Errorf("this is not the written form of what it says:\n%s", firstDifference(raw, again))
438 }
439 return doc, nil
440}
441
442// firstDifference reports the first line the two texts disagree on, so a
443// reader is pointed at the line rather than handed two documents to
444// compare by eye.
445func firstDifference(got, want []byte) string {
446 a := strings.Split(string(got), "\n")
447 b := strings.Split(string(want), "\n")
448 for i := 0; i < len(a) || i < len(b); i++ {
449 x, y := "", ""
450 if i < len(a) {
451 x = a[i]
452 }
453 if i < len(b) {
454 y = b[i]
455 }
456 if x != y {
457 return fmt.Sprintf(" line %d is %q\n and would be %q", i+1, x, y)
458 }
459 }
460 return " the two are equal"
461}
462
463// checkKeyOrIndex admits what a rendered key segment can be: a name, or an
464// array index written in decimal with no leading zeros.
465func checkKeyOrIndex(s string) error {
466 if s != "" && s[0] >= '0' && s[0] <= '9' {
467 if s != "0" && s[0] == '0' {
468 return fmt.Errorf("index %q has a leading zero; an index is written in decimal without one", s)
469 }
470 if _, err := strconv.Atoi(s); err != nil {
471 return fmt.Errorf("key segment %q starts with a digit but is not an array index", s)
472 }
473 return nil
474 }
475 return checkSegment(s)
476}
477
478// treeNode is the document being rebuilt: either a value or the segments
479// found beneath a key.
480type treeNode struct {
481 value string
482 leaf bool
483 children map[string]*treeNode
484}
485
486func (t *treeNode) insert(segments []string, value string) error {
487 if t.leaf {
488 return fmt.Errorf("a key is both a value and a path to other values")
489 }
490 head := segments[0]
491 child, ok := t.children[head]
492 if !ok {
493 child = &treeNode{children: map[string]*treeNode{}}
494 t.children[head] = child
495 }
496 if len(segments) == 1 {
497 if child.leaf || len(child.children) > 0 {
498 return fmt.Errorf("a key is both a value and a path to other values")
499 }
500 child.leaf, child.value = true, value
501 return nil
502 }
503 return child.insert(segments[1:], value)
504}
505
506func (t *treeNode) document(key string) (any, error) {
507 if t.leaf {
508 return t.value, nil
509 }
510 where := key
511 if where == "" {
512 where = "the statement"
513 }
514 indexed := 0
515 for s := range t.children {
516 if s[0] >= '0' && s[0] <= '9' {
517 indexed++
518 }
519 }
520 if indexed > 0 && indexed != len(t.children) {
521 return nil, fmt.Errorf("%s has both array indices and named fields beneath it", where)
522 }
523 if indexed > 0 {
524 out := make([]any, len(t.children))
525 for s, child := range t.children {
526 i, _ := strconv.Atoi(s)
527 if i >= len(t.children) {
528 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))
529 }
530 v, err := child.document(join(key, s))
531 if err != nil {
532 return nil, err
533 }
534 out[i] = v
535 }
536 return out, nil
537 }
538 out := make(map[string]any, len(t.children))
539 for s, child := range t.children {
540 v, err := child.document(join(key, s))
541 if err != nil {
542 return nil, err
543 }
544 out[s] = v
545 }
546 return out, nil
547}