gunk-dev/the-valley

evidence.go

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