gunk-dev/the-valley

evidence.go

source01aebe3a28ffmain's published tip history
10.5 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 // Each ref is read through the object it held when listed, never by its
55 // name again: a ref deleted since would have git try other names for it.
56 refs, err := git(in.repo, "for-each-ref", "--format=%(objectname)", attestationPrefix+"/"+subject)
57 if err != nil {
58 return nil, nil, err
59 }
60 type read struct {
61 ev verdict.Evidence
62 note []byte
63 }
64 var all []read
65 for _, oid := range strings.Fields(refs) {
66 listing, err := git(in.repo, "ls-tree", "-r", "--name-only", oid)
67 if err != nil {
68 return nil, nil, err
69 }
70 for _, entry := range strings.Fields(listing) {
71 if path.Base(entry) != statementNote {
72 continue
73 }
74 note, err := git(in.repo, "cat-file", "blob", oid+":"+entry)
75 if err != nil {
76 return nil, nil, err
77 }
78 ev, err := in.classify(wt, rev, []byte(note))
79 if err != nil {
80 return nil, nil, err
81 }
82 all = append(all, read{ev, []byte(note)})
83 }
84 }
85 picked := change.SelectNotes(all,
86 func(r read) string { return r.ev.Check },
87 func(r read) bool { return r.ev.Admissible == verdict.Admissible })
88 found := map[string]verdict.Evidence{}
89 notes := map[string][]byte{}
90 for check, r := range picked {
91 found[check], notes[check] = r.ev, r.note
92 }
93 return found, notes, nil
94}
95
96// classify runs `attest verify` over one note and reads the statement back.
97// A note with no verified signer who counts in this project
98// (note/signerprojects.go) is classified as signed by an unknown signer.
99// The integrator's own signature never counts here.
100func (in *integrator) classify(wt *worktree, rev string, note []byte) (verdict.Evidence, error) {
101 text, err := noteText(note)
102 if err != nil {
103 return verdict.Evidence{}, err
104 }
105 ev := verdict.Evidence{
106 TextDigest: sha256hex(text),
107 Check: statementValue(text, "predicate.check.name"),
108 Result: statementValue(text, "predicate.result"),
109 }
110 switch statementValue(text, "predicateType") {
111 case predicatePure:
112 ev.Kind = verdict.Pure
113 ev.Inputs = statementValue(text, "predicate.inputs.valley-inputs-v1")
114 ev.Derivation = statementValue(text, "predicate.derivation.sha256")
115 case predicateEffect:
116 ev.Kind = verdict.Effectful
117 if at := statementValue(text, "predicate.observedAt"); at != "" {
118 if t, err := time.Parse("2006-01-02T15:04:05Z", at); err == nil {
119 ev.ObservedAt = t
120 }
121 }
122 }
123 if ev.Check == "" {
124 ev.Check = "(unnamed)"
125 }
126
127 file, err := os.CreateTemp("", "valley-integrator-note")
128 if err != nil {
129 return ev, err
130 }
131 defer os.Remove(file.Name())
132 if _, err := file.Write(note); err != nil {
133 return ev, err
134 }
135 file.Close()
136
137 cmd := exec.Command(in.attest, "verify",
138 "--note", file.Name(),
139 "--known-keys", in.knownSigners,
140 "--schema", in.attestSchema,
141 "--repo", wt.dir, "--rev", rev)
142 out, err := cmd.CombinedOutput()
143 switch {
144 case err == nil:
145 // A key in the known-signers file signed the note. Its signer
146 // counts here only if the signer projects file lets it count in
147 // this project; a note no such signer signed is a stranger's.
148 //
149 // A signature under the integrator's own name is its
150 // countersignature, added when the note landed (transfer.go). It
151 // vouches for that landing, in the project it landed in, and is
152 // never the check's own signer: a countersigned note copied into
153 // another project counts there only through the signer who made
154 // the claim. Nothing in a note marks another controller's
155 // signature as a countersignature, so the host declares each
156 // other controller whose key it holds: the signer projects file
157 // names it with no project, and it counts nowhere.
158 ev.Admissible = verdict.UnknownSigner
159 for _, signer := range verifiedSigners(string(out)) {
160 name, _, _ := strings.Cut(signer, "+")
161 if name != in.signerName && in.signerProjects.Counts(name, in.project) {
162 ev.Admissible, ev.Signer = verdict.Admissible, signer
163 break
164 }
165 }
166 case strings.Contains(string(out), unknownSigner):
167 ev.Admissible = verdict.UnknownSigner
168 default:
169 ev.Admissible = verdict.Tampered
170 ev.Refusal = refusalLine(string(out))
171 }
172 return ev, nil
173}
174
175// verifiedSigners reads the signers whose signatures checked out, as
176// name+hash, in the order of the verifier's own report.
177func verifiedSigners(out string) []string {
178 var signers []string
179 for _, line := range strings.Split(out, "\n") {
180 if fields := strings.Fields(line); len(fields) == 3 && fields[0] == "signature" && fields[1] == "ok" {
181 signers = append(signers, fields[2])
182 }
183 }
184 return signers
185}
186
187// noteText returns the bytes a signature covers: everything before the
188// blank line that separates the text from the signature block. The last
189// blank line wins, so text holding one of its own does not move the split
190// — the rule dcr-de9d996 fixes.
191func noteText(note []byte) ([]byte, error) {
192 split := bytes.LastIndex(note, []byte("\n\n"))
193 if split < 0 {
194 return nil, fmt.Errorf("this is not a note: no blank line separates the text from its signatures")
195 }
196 return note[:split+1], nil
197}
198
199// statementValue reads one line's value out of statement text. Sound only
200// because the form has no escapes and `attest verify` has established the
201// text is the written form of what it says: one line, one key, one value.
202func statementValue(text []byte, key string) string {
203 for _, line := range strings.Split(string(text), "\n") {
204 if k, v, ok := strings.Cut(line, " "); ok && k == key {
205 return v
206 }
207 }
208 return ""
209}
210
211func sha256hex(b []byte) string {
212 sum := sha256.Sum256(b)
213 return hex.EncodeToString(sum[:])
214}
215
216// treeDigest asks attest for a revision's valley tree digest. One
217// implementation of the content-addressing scheme, in the program that
218// defines it.
219func (in *integrator) treeDigest(wt *worktree, rev string) (string, error) {
220 out, err := exec.Command(in.attest, "digest", "--repo", wt.dir, "--rev", rev).Output()
221 if err != nil {
222 return "", fmt.Errorf("digesting %s: %w", verdict.Short(rev), err)
223 }
224 digest := strings.TrimSpace(string(out))
225 scheme, value, ok := strings.Cut(digest, ":")
226 if !ok || scheme != "valley-tree-v1" {
227 return "", fmt.Errorf("attest digest printed %q", digest)
228 }
229 return value, nil
230}
231
232// closures recomputes the input-closure digest of each pure check over the
233// tree that would land. `attest inputs` evaluates and digests; it builds
234// nothing, so this stays off the latency path the commit point serializes.
235func (in *integrator) closures(wt *worktree, rev string, required []verdict.Required) (map[string]verdict.Closure, map[string]string) {
236 got, bad := map[string]verdict.Closure{}, map[string]string{}
237 names := make([]string, 0, len(required))
238 byAttr := map[string]string{}
239 for _, r := range required {
240 if r.Runner != "nix" {
241 continue
242 }
243 names = append(names, r.Name)
244 byAttr[r.Name] = r.Attribute
245 }
246 sort.Strings(names)
247 for _, name := range names {
248 args := []string{"inputs", "--repo", wt.dir, "--rev", rev, "--check", name + "=" + byAttr[name]}
249 if in.system != "" {
250 args = append(args, "--system", in.system)
251 }
252 out, err := exec.Command(in.attest, args...).CombinedOutput()
253 if err != nil {
254 bad[name] = firstLine(string(out))
255 continue
256 }
257 // "<name> valley-inputs-v1:<closure> sha256:<derivation>". Both
258 // digests are read, because the pure rule compares the whole of
259 // what the attestation claims.
260 fields := strings.Fields(string(out))
261 if len(fields) < 3 || !strings.HasPrefix(fields[1], "valley-inputs-v1:") || !strings.HasPrefix(fields[2], "sha256:") {
262 bad[name] = "attest inputs printed " + firstLine(string(out))
263 continue
264 }
265 got[name] = verdict.Closure{
266 Inputs: strings.TrimPrefix(fields[1], "valley-inputs-v1:"),
267 Derivation: strings.TrimPrefix(fields[2], "sha256:"),
268 }
269 }
270 return got, bad
271}
272
273func firstLine(s string) string {
274 s = strings.TrimSpace(s)
275 if i := strings.IndexByte(s, '\n'); i >= 0 {
276 return s[:i]
277 }
278 return s
279}
280
281// refusalLine is the sentence a verifier refused with. `attest` reports what
282// it checked, then the refusal prefixed with its own name, then whatever
283// elaborates it; a reader of a verdict wants the sentence. This convention
284// belongs to the command being driven, so it is read here, at the boundary
285// that drives it, and the verdict is handed a result rather than a
286// transcript to parse.
287func refusalLine(out string) string {
288 var last string
289 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
290 if why, ok := strings.CutPrefix(line, "attest: "); ok {
291 return strings.TrimSpace(why)
292 }
293 if strings.TrimSpace(line) != "" {
294 last = strings.TrimSpace(line)
295 }
296 }
297 return last
298}