gunk-dev/the-valley

evidence.go

source2b2256ecc7a4main's published tip history
9.1 KiB
1package main
2
3// Reading a change's evidence. Every judgement about whether an attestation
4// is what it claims to be is `attest verify`'s: the note's signatures, the
5// text being the one written form of what it says, the statement satisfying
6// the schema, and its subject digest being the tree in front of the
7// verifier. This file runs that verifier and classifies what it said.
8//
9// Nothing here re-implements the envelope or the written form. What it does
10// do is read values out of text that `attest verify` has already established
11// is the written form of what it says — where a line is a key, one space,
12// and a value, with no escapes. That is a lookup, not a parser, and it is
13// sound only in that order: verify first, read second.
14
15import (
16 "the-valley/change"
17 "the-valley/integrator/verdict"
18
19 "bytes"
20 "crypto/sha256"
21 "encoding/hex"
22 "fmt"
23 "os"
24 "os/exec"
25 "path"
26 "sort"
27 "strings"
28 "time"
29)
30
31const (
32 attestationPrefix = "refs/the-valley/attestations"
33 statementNote = "statement.note"
34
35 predicatePure = "the-valley/check/pure/v1"
36 predicateEffect = "the-valley/check/effectful/v1"
37 predicateTransfer = "the-valley/integration/transfer/v1"
38)
39
40// unknownSigner is the one sentence `attest verify` refuses a well-formed
41// note with when nobody who signed it is a key the verifier holds. Every
42// other refusal is a forgery as far as the integrator is concerned, so this
43// classification fails closed: an unrecognised message is a rejection.
44const unknownSigner = "no signature on this note is by a key the verifier holds"
45
46// collectEvidence finds every attestation stored for a subject digest and
47// classifies it. Attestations are stored one ref per signer
48// (dcr-0de694f), so a subject may carry several notes for one check.
49// Which one a check is judged by is change.SelectNotes's choice, the one
50// approve makes too: the first admissible note, whatever it records, or
51// else the last note read, so a note that does not verify is reported and
52// the verdict can reject rather than quietly look past it.
53func (in *integrator) collectEvidence(wt *worktree, rev, subject string) (map[string]verdict.Evidence, map[string][]byte, error) {
54 refs, err := git(in.repo, "for-each-ref", "--format=%(refname)", attestationPrefix+"/"+subject)
55 if err != nil {
56 return nil, nil, err
57 }
58 type read struct {
59 ev verdict.Evidence
60 note []byte
61 }
62 var all []read
63 for _, ref := range strings.Fields(refs) {
64 listing, err := git(in.repo, "ls-tree", "-r", "--name-only", ref)
65 if err != nil {
66 return nil, nil, err
67 }
68 for _, entry := range strings.Fields(listing) {
69 if path.Base(entry) != statementNote {
70 continue
71 }
72 note, err := git(in.repo, "cat-file", "blob", ref+":"+entry)
73 if err != nil {
74 return nil, nil, err
75 }
76 ev, err := in.classify(wt, rev, []byte(note))
77 if err != nil {
78 return nil, nil, err
79 }
80 all = append(all, read{ev, []byte(note)})
81 }
82 }
83 picked := change.SelectNotes(all,
84 func(r read) string { return r.ev.Check },
85 func(r read) bool { return r.ev.Admissible == verdict.Admissible })
86 found := map[string]verdict.Evidence{}
87 notes := map[string][]byte{}
88 for check, r := range picked {
89 found[check], notes[check] = r.ev, r.note
90 }
91 return found, notes, nil
92}
93
94// classify runs `attest verify` over one note and reads the statement back.
95func (in *integrator) classify(wt *worktree, rev string, note []byte) (verdict.Evidence, error) {
96 text, err := noteText(note)
97 if err != nil {
98 return verdict.Evidence{}, err
99 }
100 ev := verdict.Evidence{
101 TextDigest: sha256hex(text),
102 Check: statementValue(text, "predicate.check.name"),
103 Result: statementValue(text, "predicate.result"),
104 }
105 switch statementValue(text, "predicateType") {
106 case predicatePure:
107 ev.Kind = verdict.Pure
108 ev.Inputs = statementValue(text, "predicate.inputs.valley-inputs-v1")
109 ev.Derivation = statementValue(text, "predicate.derivation.sha256")
110 case predicateEffect:
111 ev.Kind = verdict.Effectful
112 if at := statementValue(text, "predicate.observedAt"); at != "" {
113 if t, err := time.Parse("2006-01-02T15:04:05Z", at); err == nil {
114 ev.ObservedAt = t
115 }
116 }
117 }
118 if ev.Check == "" {
119 ev.Check = "(unnamed)"
120 }
121
122 file, err := os.CreateTemp("", "valley-integrator-note")
123 if err != nil {
124 return ev, err
125 }
126 defer os.Remove(file.Name())
127 if _, err := file.Write(note); err != nil {
128 return ev, err
129 }
130 file.Close()
131
132 cmd := exec.Command(in.attest, "verify",
133 "--note", file.Name(),
134 "--known-keys", in.knownSigners,
135 "--schema", in.attestSchema,
136 "--repo", wt.dir, "--rev", rev)
137 out, err := cmd.CombinedOutput()
138 switch {
139 case err == nil:
140 ev.Admissible = verdict.Admissible
141 ev.Signer = verifiedSigner(string(out))
142 case strings.Contains(string(out), unknownSigner):
143 ev.Admissible = verdict.UnknownSigner
144 default:
145 ev.Admissible = verdict.Tampered
146 ev.Refusal = refusalLine(string(out))
147 }
148 return ev, nil
149}
150
151// verifiedSigner reads the name whose signature checked out, from the
152// verifier's own report.
153func verifiedSigner(out string) string {
154 for _, line := range strings.Split(out, "\n") {
155 if fields := strings.Fields(line); len(fields) == 3 && fields[0] == "signature" && fields[1] == "ok" {
156 return fields[2]
157 }
158 }
159 return ""
160}
161
162// noteText returns the bytes a signature covers: everything before the
163// blank line that separates the text from the signature block. The last
164// blank line wins, so text holding one of its own does not move the split
165// — the rule dcr-de9d996 fixes.
166func noteText(note []byte) ([]byte, error) {
167 split := bytes.LastIndex(note, []byte("\n\n"))
168 if split < 0 {
169 return nil, fmt.Errorf("this is not a note: no blank line separates the text from its signatures")
170 }
171 return note[:split+1], nil
172}
173
174// statementValue reads one line's value out of statement text. Sound only
175// because the form has no escapes and `attest verify` has established the
176// text is the written form of what it says: one line, one key, one value.
177func statementValue(text []byte, key string) string {
178 for _, line := range strings.Split(string(text), "\n") {
179 if k, v, ok := strings.Cut(line, " "); ok && k == key {
180 return v
181 }
182 }
183 return ""
184}
185
186func sha256hex(b []byte) string {
187 sum := sha256.Sum256(b)
188 return hex.EncodeToString(sum[:])
189}
190
191// treeDigest asks attest for a revision's valley tree digest. One
192// implementation of the content-addressing scheme, in the program that
193// defines it.
194func (in *integrator) treeDigest(wt *worktree, rev string) (string, error) {
195 out, err := exec.Command(in.attest, "digest", "--repo", wt.dir, "--rev", rev).Output()
196 if err != nil {
197 return "", fmt.Errorf("digesting %s: %w", verdict.Short(rev), err)
198 }
199 digest := strings.TrimSpace(string(out))
200 scheme, value, ok := strings.Cut(digest, ":")
201 if !ok || scheme != "valley-tree-v1" {
202 return "", fmt.Errorf("attest digest printed %q", digest)
203 }
204 return value, nil
205}
206
207// closures recomputes the input-closure digest of each pure check over the
208// tree that would land. `attest inputs` evaluates and digests; it builds
209// nothing, so this stays off the latency path the commit point serializes.
210func (in *integrator) closures(wt *worktree, rev string, required []verdict.Required) (map[string]verdict.Closure, map[string]string) {
211 got, bad := map[string]verdict.Closure{}, map[string]string{}
212 names := make([]string, 0, len(required))
213 byAttr := map[string]string{}
214 for _, r := range required {
215 if r.Runner != "nix" {
216 continue
217 }
218 names = append(names, r.Name)
219 byAttr[r.Name] = r.Attribute
220 }
221 sort.Strings(names)
222 for _, name := range names {
223 args := []string{"inputs", "--repo", wt.dir, "--rev", rev, "--check", name + "=" + byAttr[name]}
224 if in.system != "" {
225 args = append(args, "--system", in.system)
226 }
227 out, err := exec.Command(in.attest, args...).CombinedOutput()
228 if err != nil {
229 bad[name] = firstLine(string(out))
230 continue
231 }
232 // "<name> valley-inputs-v1:<closure> sha256:<derivation>". Both
233 // digests are read, because the pure rule compares the whole of
234 // what the attestation claims.
235 fields := strings.Fields(string(out))
236 if len(fields) < 3 || !strings.HasPrefix(fields[1], "valley-inputs-v1:") || !strings.HasPrefix(fields[2], "sha256:") {
237 bad[name] = "attest inputs printed " + firstLine(string(out))
238 continue
239 }
240 got[name] = verdict.Closure{
241 Inputs: strings.TrimPrefix(fields[1], "valley-inputs-v1:"),
242 Derivation: strings.TrimPrefix(fields[2], "sha256:"),
243 }
244 }
245 return got, bad
246}
247
248func firstLine(s string) string {
249 s = strings.TrimSpace(s)
250 if i := strings.IndexByte(s, '\n'); i >= 0 {
251 return s[:i]
252 }
253 return s
254}
255
256// refusalLine is the sentence a verifier refused with. `attest` reports what
257// it checked, then the refusal prefixed with its own name, then whatever
258// elaborates it; a reader of a verdict wants the sentence. This convention
259// belongs to the command being driven, so it is read here, at the boundary
260// that drives it, and the verdict is handed a result rather than a
261// transcript to parse.
262func refusalLine(out string) string {
263 var last string
264 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
265 if why, ok := strings.CutPrefix(line, "attest: "); ok {
266 return strings.TrimSpace(why)
267 }
268 if strings.TrimSpace(line) != "" {
269 last = strings.TrimSpace(line)
270 }
271 }
272 return last
273}