gunk-dev/the-valley

evidence.go

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