gunk-dev/the-valley

text.go

source7a248e9dc32emain's published tip history
17.7 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 predicateTransfer:
133 // A transfer reads as: which change, onto what, from which base,
134 // under which policy, and then the per-check verdicts.
135 predicate = obj("predicate",
136 leaf("change"),
137 leaf("target"),
138 set("base"),
139 set("policy"),
140 field{name: "checks", list: true, under: []field{
141 leaf("name"),
142 leaf("rule"),
143 set("evidence"),
144 set("inputs"),
145 }},
146 )
147 case "":
148 return nil, fmt.Errorf("the statement names no predicate type, so how its claim is written down is not decided")
149 default:
150 return nil, fmt.Errorf("predicate type %q has no written form; a claim shape is written down by the revision that publishes it", predicateType)
151 }
152 return []field{
153 obj("subject", leaf("primary"), set("digest")),
154 leaf("predicateType"),
155 predicate,
156 obj("provenance",
157 leaf("harness"),
158 leaf("model"),
159 set("prompt"),
160 set("context"),
161 field{name: "delegation", list: true, under: []field{
162 leaf("principal"),
163 leaf("grant"),
164 }},
165 ),
166 }, nil
167}
168
169// checkOrder is the check that ran: what it is called, how it was run, and
170// then whichever of the two the runner names it by.
171var checkOrder = obj("check",
172 leaf("name"),
173 leaf("runner"),
174 leaf("attribute"),
175 leaf("command"),
176)
177
178// renderText writes a document as statement text.
179func renderText(doc any) ([]byte, error) {
180 root, ok := doc.(map[string]any)
181 if !ok {
182 return nil, fmt.Errorf("a statement is an object, and this is %T", doc)
183 }
184 kind, _ := root["statementType"].(string)
185 if kind != statementType {
186 return nil, fmt.Errorf("the statement type is %q; %q is the one this writes down", root["statementType"], statementType)
187 }
188 predicateType, _ := root["predicateType"].(string)
189 order, err := statementOrder(predicateType)
190 if err != nil {
191 return nil, err
192 }
193
194 // Flatten first, which settles every value and every field name, then
195 // place the lines. A key the order table has no position for is left
196 // over, and left over is refused.
197 lines := map[string]string{}
198 if err := flatten("", root, lines); err != nil {
199 return nil, err
200 }
201 delete(lines, "statementType") // the header line carries it
202
203 var b bytes.Buffer
204 b.WriteString(kind)
205 b.WriteByte('\n')
206 placed := 0
207 for _, key := range orderedKeys(root, order, "") {
208 value, ok := lines[key]
209 if !ok {
210 continue
211 }
212 b.WriteString(key)
213 b.WriteByte(' ')
214 b.WriteString(value)
215 b.WriteByte('\n')
216 delete(lines, key)
217 placed++
218 }
219 for _, key := range sortedKeys(lines) {
220 return nil, fmt.Errorf("%s has no position in the written form of a %s", key, predicateType)
221 }
222 if placed == 0 {
223 return nil, fmt.Errorf("the statement carries nothing but its type")
224 }
225 return b.Bytes(), nil
226}
227
228// orderedKeys walks the order table over a document and returns the keys
229// it names, in order. A field the document does not carry contributes
230// nothing; what the table has no entry for is not reached at all, which is
231// how renderText finds it left over.
232func orderedKeys(doc map[string]any, order []field, prefix string) []string {
233 var out []string
234 for _, f := range order {
235 v, ok := doc[f.name]
236 if !ok {
237 continue
238 }
239 key := join(prefix, f.name)
240 switch {
241 case f.set:
242 members, ok := v.(map[string]any)
243 if !ok {
244 out = append(out, key)
245 continue
246 }
247 for _, name := range sortedAnyKeys(members) {
248 out = append(out, join(key, name))
249 }
250 case f.list:
251 elements, ok := v.([]any)
252 if !ok {
253 out = append(out, key)
254 continue
255 }
256 for i, e := range elements {
257 under, ok := e.(map[string]any)
258 if !ok {
259 out = append(out, join(key, strconv.Itoa(i)))
260 continue
261 }
262 out = append(out, orderedKeys(under, f.under, join(key, strconv.Itoa(i)))...)
263 }
264 case f.under != nil:
265 under, ok := v.(map[string]any)
266 if !ok {
267 out = append(out, key)
268 continue
269 }
270 out = append(out, orderedKeys(under, f.under, key)...)
271 default:
272 out = append(out, key)
273 }
274 }
275 return out
276}
277
278func sortedAnyKeys(m map[string]any) []string {
279 keys := make([]string, 0, len(m))
280 for k := range m {
281 keys = append(keys, k)
282 }
283 sort.Strings(keys)
284 return keys
285}
286
287// renderJSON writes a JSON document as statement text. JSON is how a
288// statement is composed and how it is handed to `cue vet`; this form is
289// how it is signed. UseNumber keeps a number a number rather than a
290// float64, so a document carrying one is refused rather than quietly
291// rounded on the way through.
292func renderJSON(raw []byte) ([]byte, error) {
293 var doc any
294 dec := json.NewDecoder(bytes.NewReader(raw))
295 dec.UseNumber()
296 if err := dec.Decode(&doc); err != nil {
297 return nil, err
298 }
299 return renderText(doc)
300}
301
302func flatten(key string, v any, out map[string]string) error {
303 where := key
304 if where == "" {
305 where = "the statement"
306 }
307 switch t := v.(type) {
308 case string:
309 if err := checkValue(t); err != nil {
310 return fmt.Errorf("%s: %w", where, err)
311 }
312 out[key] = t
313 case map[string]any:
314 if len(t) == 0 {
315 return fmt.Errorf("%s: an object with no fields has no lines, so it cannot be written down", where)
316 }
317 for k, e := range t {
318 if err := checkSegment(k); err != nil {
319 return fmt.Errorf("%s: %w", where, err)
320 }
321 if err := flatten(join(key, k), e, out); err != nil {
322 return err
323 }
324 }
325 case []any:
326 if len(t) == 0 {
327 return fmt.Errorf("%s: an array with no elements has no lines, so it cannot be written down", where)
328 }
329 for i, e := range t {
330 if err := flatten(join(key, strconv.Itoa(i)), e, out); err != nil {
331 return err
332 }
333 }
334 case json.Number:
335 return fmt.Errorf("%s: %s is a number; a statement carries none, and how one is written down has never been decided", where, t)
336 case bool:
337 return fmt.Errorf("%s: %t is a boolean; a statement carries none, and how one is written down has never been decided", where, t)
338 case nil:
339 return fmt.Errorf("%s: is null; a field a statement does not carry is left out rather than written as null", where)
340 default:
341 return fmt.Errorf("%s: a statement may not carry %T", where, v)
342 }
343 return nil
344}
345
346func join(key, segment string) string {
347 if key == "" {
348 return segment
349 }
350 return key + "." + segment
351}
352
353// checkSegment holds a key segment to what a line can carry unambiguously:
354// a letter, then letters, digits and dashes. A dot would look like the
355// separator between segments, a space like the separator between key and
356// value, and a leading digit like an array index.
357func checkSegment(s string) error {
358 switch {
359 case s == "":
360 return fmt.Errorf("a key segment may not be empty")
361 case strings.Contains(s, "."):
362 return fmt.Errorf("key segment %q contains a dot, which separates one segment from the next", s)
363 case strings.Contains(s, " "):
364 return fmt.Errorf("key segment %q contains a space, which separates the key from the value", s)
365 case s[0] >= '0' && s[0] <= '9':
366 return fmt.Errorf("key segment %q starts with a digit, which is how an array index is written", s)
367 }
368 for i, r := range s {
369 ok := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-'
370 if !ok {
371 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)
372 }
373 }
374 return nil
375}
376
377// checkValue holds a value to what one line can carry. There is no escape
378// mechanism to fall back on, so anything unwritable is an error here
379// rather than a second way of writing something.
380func checkValue(s string) error {
381 if s == "" {
382 return fmt.Errorf("the value is empty; a field a statement does not carry is left out rather than written as an empty string")
383 }
384 if !utf8.ValidString(s) {
385 return fmt.Errorf("the value is not valid utf-8, so it has no written form")
386 }
387 for i := 0; i < len(s); i++ {
388 if c := s[i]; c == '\n' {
389 return fmt.Errorf("the value holds a newline, and a line ends where its newline is; there is no escape to write one with")
390 } else if c < 0x20 || c == 0x7f {
391 return fmt.Errorf("the value holds the control character %#02x, and there is no escape to write one with", c)
392 }
393 }
394 return nil
395}
396
397// parseText reads statement text back into a document.
398//
399// It accepts text only if writing the document that text says back out
400// reproduces it byte for byte. That is the whole acceptance rule, and it
401// makes "these bytes are the written form of what they say" something a
402// verifier settles by reading rather than a claim it has to take on trust:
403// line order, a duplicated key, a set out of order and a value no line can
404// carry all fail the same way, because none of them is what a renderer
405// would have produced.
406func parseText(raw []byte) (map[string]any, error) {
407 if len(raw) == 0 || raw[len(raw)-1] != '\n' {
408 return nil, fmt.Errorf("statement text must end with a newline")
409 }
410 lines := strings.Split(string(raw[:len(raw)-1]), "\n")
411
412 root := &treeNode{children: map[string]*treeNode{}}
413 if err := root.insert([]string{"statementType"}, lines[0]); err != nil {
414 return nil, err
415 }
416 if err := checkValue(lines[0]); err != nil {
417 return nil, fmt.Errorf("line 1: %w", err)
418 }
419 for i, l := range lines[1:] {
420 n := i + 2
421 key, value, found := strings.Cut(l, " ")
422 if !found || value == "" {
423 return nil, fmt.Errorf("line %d is %q; a line is a key, one space, and a value", n, l)
424 }
425 if err := checkValue(value); err != nil {
426 return nil, fmt.Errorf("line %d: %w", n, err)
427 }
428 segments := strings.Split(key, ".")
429 for _, s := range segments {
430 if err := checkKeyOrIndex(s); err != nil {
431 return nil, fmt.Errorf("line %d: %w", n, err)
432 }
433 }
434 if err := root.insert(segments, value); err != nil {
435 return nil, fmt.Errorf("line %d: %w", n, err)
436 }
437 }
438 if len(root.children) < 2 {
439 return nil, fmt.Errorf("the text carries no lines, so it says nothing")
440 }
441 built, err := root.document("")
442 if err != nil {
443 return nil, err
444 }
445 doc := built.(map[string]any)
446
447 again, err := renderText(doc)
448 if err != nil {
449 return nil, err
450 }
451 if !bytes.Equal(again, raw) {
452 return nil, fmt.Errorf("this is not the written form of what it says:\n%s", firstDifference(raw, again))
453 }
454 return doc, nil
455}
456
457// firstDifference reports the first line the two texts disagree on, so a
458// reader is pointed at the line rather than handed two documents to
459// compare by eye.
460func firstDifference(got, want []byte) string {
461 a := strings.Split(string(got), "\n")
462 b := strings.Split(string(want), "\n")
463 for i := 0; i < len(a) || i < len(b); i++ {
464 x, y := "", ""
465 if i < len(a) {
466 x = a[i]
467 }
468 if i < len(b) {
469 y = b[i]
470 }
471 if x != y {
472 return fmt.Sprintf(" line %d is %q\n and would be %q", i+1, x, y)
473 }
474 }
475 return " the two are equal"
476}
477
478// checkKeyOrIndex admits what a rendered key segment can be: a name, or an
479// array index written in decimal with no leading zeros.
480func checkKeyOrIndex(s string) error {
481 if s != "" && s[0] >= '0' && s[0] <= '9' {
482 if s != "0" && s[0] == '0' {
483 return fmt.Errorf("index %q has a leading zero; an index is written in decimal without one", s)
484 }
485 if _, err := strconv.Atoi(s); err != nil {
486 return fmt.Errorf("key segment %q starts with a digit but is not an array index", s)
487 }
488 return nil
489 }
490 return checkSegment(s)
491}
492
493// treeNode is the document being rebuilt: either a value or the segments
494// found beneath a key.
495type treeNode struct {
496 value string
497 leaf bool
498 children map[string]*treeNode
499}
500
501func (t *treeNode) insert(segments []string, value string) error {
502 if t.leaf {
503 return fmt.Errorf("a key is both a value and a path to other values")
504 }
505 head := segments[0]
506 child, ok := t.children[head]
507 if !ok {
508 child = &treeNode{children: map[string]*treeNode{}}
509 t.children[head] = child
510 }
511 if len(segments) == 1 {
512 if child.leaf || len(child.children) > 0 {
513 return fmt.Errorf("a key is both a value and a path to other values")
514 }
515 child.leaf, child.value = true, value
516 return nil
517 }
518 return child.insert(segments[1:], value)
519}
520
521func (t *treeNode) document(key string) (any, error) {
522 if t.leaf {
523 return t.value, nil
524 }
525 where := key
526 if where == "" {
527 where = "the statement"
528 }
529 indexed := 0
530 for s := range t.children {
531 if s[0] >= '0' && s[0] <= '9' {
532 indexed++
533 }
534 }
535 if indexed > 0 && indexed != len(t.children) {
536 return nil, fmt.Errorf("%s has both array indices and named fields beneath it", where)
537 }
538 if indexed > 0 {
539 out := make([]any, len(t.children))
540 for s, child := range t.children {
541 i, _ := strconv.Atoi(s)
542 if i >= len(t.children) {
543 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))
544 }
545 v, err := child.document(join(key, s))
546 if err != nil {
547 return nil, err
548 }
549 out[i] = v
550 }
551 return out, nil
552 }
553 out := make(map[string]any, len(t.children))
554 for s, child := range t.children {
555 v, err := child.document(join(key, s))
556 if err != nil {
557 return nil, err
558 }
559 out[s] = v
560 }
561 return out, nil
562}