gunk-dev/the-valley

text.go

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