gunk-dev/the-valley

statement_test.go

sourced9c8073fd613main's published tip history
10.3 KiB
1package statement
2
3import (
4 "crypto/sha256"
5 "encoding/json"
6 "fmt"
7 "reflect"
8 "strings"
9 "testing"
10)
11
12// The written form and the tree digest decide which bytes get signed and
13// what a subject is, so both must agree with any other implementation.
14// attest/conformance/ holds the written form to recorded vectors through
15// attest render as well.
16
17// pureStatement is a whole statement, which is the only thing that has a
18// written form: order is defined per predicate type, so a fragment has no
19// order at all.
20func pureStatement() map[string]any {
21 return map[string]any{
22 "statementType": Type,
23 "predicateType": PredicatePure,
24 "subject": map[string]any{
25 "primary": TreeScheme,
26 "digest": map[string]any{
27 TreeScheme: strings.Repeat("a", 64),
28 "git-sha1": strings.Repeat("b", 40),
29 },
30 },
31 "predicate": map[string]any{
32 "check": map[string]any{"name": "prose-format", "runner": "nix", "attribute": "prose-format"},
33 "result": "passed",
34 "inputs": map[string]any{"valley-inputs-v1": strings.Repeat("c", 64)},
35 "derivation": map[string]any{"sha256": strings.Repeat("d", 64)},
36 "output": map[string]any{TreeScheme: strings.Repeat("e", 64)},
37 },
38 "provenance": map[string]any{
39 "harness": "a harness",
40 "model": "a model",
41 "delegation": []any{
42 map[string]any{"principal": "human:integrator", "grant": "land changes"},
43 map[string]any{"principal": "agent:run"},
44 },
45 },
46 }
47}
48
49func TestRenderTextWritesLinesInNarrativeOrder(t *testing.T) {
50 // The reader's first question — what is this about — is answered
51 // first, and what produced the change comes last. Within the digest
52 // set, whose keys are naming schemes rather than positions, entries
53 // sort by key.
54 got, err := Render(pureStatement())
55 if err != nil {
56 t.Fatal(err)
57 }
58 want := Type + "\n" +
59 "subject.primary valley-tree-v1\n" +
60 "subject.digest.git-sha1 " + strings.Repeat("b", 40) + "\n" +
61 "subject.digest.valley-tree-v1 " + strings.Repeat("a", 64) + "\n" +
62 "predicateType " + PredicatePure + "\n" +
63 "predicate.check.name prose-format\n" +
64 "predicate.check.runner nix\n" +
65 "predicate.check.attribute prose-format\n" +
66 "predicate.result passed\n" +
67 "predicate.inputs.valley-inputs-v1 " + strings.Repeat("c", 64) + "\n" +
68 "predicate.derivation.sha256 " + strings.Repeat("d", 64) + "\n" +
69 "predicate.output.valley-tree-v1 " + strings.Repeat("e", 64) + "\n" +
70 "provenance.harness a harness\n" +
71 "provenance.model a model\n" +
72 "provenance.delegation.0.principal human:integrator\n" +
73 "provenance.delegation.0.grant land changes\n" +
74 "provenance.delegation.1.principal agent:run\n"
75 if string(got) != want {
76 t.Errorf("Render =\n%s\nwant\n%s", got, want)
77 }
78}
79
80func TestRenderTextWritesArrayElementsInIndexOrder(t *testing.T) {
81 // An array is positional, so its elements are written in index order.
82 // Eleven of them is where an order taken from the key's bytes rather
83 // than from the index would put the tenth in the wrong place.
84 doc := pureStatement()
85 var steps []any
86 for i := 0; i < 11; i++ {
87 steps = append(steps, map[string]any{"principal": fmt.Sprintf("step-%d", i)})
88 }
89 doc["provenance"].(map[string]any)["delegation"] = steps
90 got, err := Render(doc)
91 if err != nil {
92 t.Fatal(err)
93 }
94 var seen []string
95 for _, l := range strings.Split(string(got), "\n") {
96 if strings.HasPrefix(l, "provenance.delegation.") {
97 seen = append(seen, strings.TrimPrefix(l, "provenance.delegation."))
98 }
99 }
100 if len(seen) != 11 || seen[1] != "1.principal step-1" || seen[10] != "10.principal step-10" {
101 t.Errorf("delegation steps are not in index order: %q", seen)
102 }
103}
104
105func TestRenderTextWritesValuesLiterally(t *testing.T) {
106 // The form has no escapes, which is what leaves two implementations
107 // nothing to disagree about. Every character below is one a JSON
108 // encoder would have had a choice about.
109 const odd = `a<b>c&d "q" \ / ü😀`
110 doc := pureStatement()
111 doc["provenance"].(map[string]any)["harness"] = odd
112 got, err := Render(doc)
113 if err != nil {
114 t.Fatal(err)
115 }
116 if !strings.Contains(string(got), "\nprovenance.harness "+odd+"\n") {
117 t.Errorf("Render did not write the value as its own bytes:\n%s", got)
118 }
119}
120
121func TestRenderTextRefusesWhatItCannotWrite(t *testing.T) {
122 // Each of these is a document with no written form. Refusing beats
123 // guessing, and beats dropping something that was validated a moment
124 // earlier and would then not be in the bytes that got signed.
125 for name, spoil := range map[string]func(map[string]any){
126 "a number": func(d map[string]any) { d["provenance"] = map[string]any{"model": json.Number("1.5")} },
127 "a boolean": func(d map[string]any) { d["provenance"] = map[string]any{"model": true} },
128 "a null": func(d map[string]any) { d["provenance"] = map[string]any{"model": nil} },
129 "an empty object": func(d map[string]any) { d["provenance"] = map[string]any{} },
130 "an empty array": func(d map[string]any) { d["provenance"] = map[string]any{"delegation": []any{}} },
131 "an empty string": func(d map[string]any) { d["provenance"] = map[string]any{"model": ""} },
132 "a newline in a value": func(d map[string]any) { d["provenance"] = map[string]any{"model": "two\nlines"} },
133 "a tab in a value": func(d map[string]any) { d["provenance"] = map[string]any{"model": "a\tb"} },
134 "invalid utf-8": func(d map[string]any) { d["provenance"] = map[string]any{"model": "\xff"} },
135 "a key with a dot": func(d map[string]any) { d["provenance"] = map[string]any{"a.b": "x"} },
136 "a key with a space": func(d map[string]any) { d["provenance"] = map[string]any{"a b": "x"} },
137 "a non-ascii key": func(d map[string]any) { d["provenance"] = map[string]any{"café": "x"} },
138 "an index-shaped key": func(d map[string]any) { d["provenance"] = map[string]any{"0": "x"} },
139
140 // A field the order table has no position for cannot be placed, so
141 // it is refused rather than written somewhere a second
142 // implementation would not look for it.
143 "a field with no position": func(d map[string]any) { d["provenance"] = map[string]any{"authority": "root"} },
144 "an unknown predicate type": func(d map[string]any) {
145 d["predicateType"] = "the-valley/check/pure/v2"
146 },
147 "an unknown statement type": func(d map[string]any) {
148 d["Type"] = "the-valley/attestation/v2"
149 },
150 } {
151 doc := pureStatement()
152 spoil(doc)
153 if _, err := Render(doc); err == nil {
154 t.Errorf("Render accepted %s", name)
155 }
156 }
157}
158
159func TestParseTextRoundTrips(t *testing.T) {
160 doc := pureStatement()
161 text, err := Render(doc)
162 if err != nil {
163 t.Fatal(err)
164 }
165 back, err := Parse(text)
166 if err != nil {
167 t.Fatalf("Parse(%q): %v", text, err)
168 }
169 if !reflect.DeepEqual(back, doc) {
170 t.Errorf("Parse(Render(doc)) =\n %#v\nwant\n %#v", back, doc)
171 }
172 // The form is a fixed point, or a statement written out again anywhere
173 // downstream stops matching what was signed.
174 again, err := Render(back)
175 if err != nil {
176 t.Fatal(err)
177 }
178 if string(again) != string(text) {
179 t.Errorf("rendering a parsed statement changed it:\n%q\n%q", again, text)
180 }
181}
182
183func TestParseTextAcceptsOnlyTheWrittenForm(t *testing.T) {
184 // Text that parses is text the renderer would have produced. That is
185 // what lets a verifier settle "these bytes are the written form of what
186 // they say" by reading, rather than trusting the sender.
187 good, err := Render(pureStatement())
188 if err != nil {
189 t.Fatal(err)
190 }
191 swap := func(a, b string) string {
192 lines := strings.Split(string(good), "\n")
193 i, j := indexOfPrefix(t, lines, a), indexOfPrefix(t, lines, b)
194 lines[i], lines[j] = lines[j], lines[i]
195 return strings.Join(lines, "\n")
196 }
197 for name, text := range map[string]string{
198 "no header": strings.TrimPrefix(string(good), Type+"\n"),
199 "another header": "the-valley/attestation/v2\n" + strings.TrimPrefix(string(good), Type+"\n"),
200 "no closing newline": strings.TrimSuffix(string(good), "\n"),
201 "a key with no value": string(good) + "provenance.model\n",
202 "a blank line": strings.Replace(string(good), "predicateType ", "\npredicateType ", 1),
203 "a repeated key": string(good) + "provenance.model twice\n",
204 "nothing at all": Type + "\n",
205
206 // The claim before what it is about, which is the order a reader
207 // does not read in.
208 "sections out of order": swap("subject.primary ", "predicateType "),
209 // A set whose entries carry no order of their own, out of the one
210 // order they have.
211 "a set out of order": swap("subject.digest.git-sha1 ", "subject.digest.valley-tree-v1 "),
212 // An array element out of its position.
213 "an array out of order": swap("provenance.delegation.0.principal ", "provenance.delegation.1.principal "),
214 // A field the order table has no position for.
215 "a field with no position": string(good) + "provenance.authority root\n",
216
217 "a sparse array": Type + "\np.0 one\np.2 three\n",
218 "index and field": Type + "\np.0 one\np.name two\n",
219 "value and path": Type + "\np one\np.q two\n",
220 "a leading zero": Type + "\np.00 one\n",
221 } {
222 if _, err := Parse([]byte(text)); err == nil {
223 t.Errorf("Parse accepted %s: %q", name, text)
224 }
225 }
226}
227
228func indexOfPrefix(t *testing.T, lines []string, prefix string) int {
229 t.Helper()
230 for i, l := range lines {
231 if strings.HasPrefix(l, prefix) {
232 return i
233 }
234 }
235 t.Fatalf("no line starting %q", prefix)
236 return -1
237}
238
239func TestTreeManifestIsUnambiguous(t *testing.T) {
240 // A path holding the manifest's own separators must not be able to
241 // forge an entry boundary: the byte length is what delimits it.
242 entries := []Entry{
243 {Mode: ModeFile, Path: "b\n100644 x 1 c", Sum: [32]byte{}},
244 {Mode: ModeExec, Path: "a", Sum: [32]byte{0xff}},
245 }
246 want := "valley-tree-v1\n" +
247 "100755 ff00000000000000000000000000000000000000000000000000000000000000 1 a\n" +
248 "100644 0000000000000000000000000000000000000000000000000000000000000000 14 b\n100644 x 1 c\n"
249 if got := string(TreeManifest(entries)); got != want {
250 t.Errorf("TreeManifest =\n%q\nwant\n%q", got, want)
251 }
252}
253
254func TestTreeDigestIsPinned(t *testing.T) {
255 // The digest of a fixed tree is a wire format: changing it invalidates
256 // every attestation ever made. This value may only change with the
257 // scheme's version.
258 entries := []Entry{{Mode: ModeFile, Path: "a.txt", Sum: sha256of("hi\n")}}
259 const want = "74781d4ba499b9896e97f2fdd38815d5723cb7b12e448ef0ce5788a1e72c2220"
260 if got := TreeDigest(entries); got != want {
261 t.Errorf("TreeDigest = %s, want %s", got, want)
262 }
263}
264
265func sha256of(s string) [32]byte { return sha256.Sum256([]byte(s)) }