gunk-dev/the-valley

text.go

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