gunk-dev/the-valley

evidence.go

sourcebabe14e6c71cmain's published tip history
10.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.
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.
153 ev.Admissible = verdict.UnknownSigner
154 for _, signer := range verifiedSigners(string(out)) {
155 name, _, _ := strings.Cut(signer, "+")
156 if name != in.signerName && in.signerProjects.Counts(name, in.project) {
157 ev.Admissible, ev.Signer = verdict.Admissible, signer
158 break
159 }
160 }
161 case strings.Contains(string(out), unknownSigner):
162 ev.Admissible = verdict.UnknownSigner
163 default:
164 ev.Admissible = verdict.Tampered
165 ev.Refusal = refusalLine(string(out))
166 }
167 return ev, nil
168}
169
170// verifiedSigners reads the signers whose signatures checked out, as
171// name+hash, in the order of the verifier's own report.
172func verifiedSigners(out string) []string {
173 var signers []string
174 for _, line := range strings.Split(out, "\n") {
175 if fields := strings.Fields(line); len(fields) == 3 && fields[0] == "signature" && fields[1] == "ok" {
176 signers = append(signers, fields[2])
177 }
178 }
179 return signers
180}
181
182// noteText returns the bytes a signature covers: everything before the
183// blank line that separates the text from the signature block. The last
184// blank line wins, so text holding one of its own does not move the split
185// — the rule dcr-de9d996 fixes.
186func noteText(note []byte) ([]byte, error) {
187 split := bytes.LastIndex(note, []byte("\n\n"))
188 if split < 0 {
189 return nil, fmt.Errorf("this is not a note: no blank line separates the text from its signatures")
190 }
191 return note[:split+1], nil
192}
193
194// statementValue reads one line's value out of statement text. Sound only
195// because the form has no escapes and `attest verify` has established the
196// text is the written form of what it says: one line, one key, one value.
197func statementValue(text []byte, key string) string {
198 for _, line := range strings.Split(string(text), "\n") {
199 if k, v, ok := strings.Cut(line, " "); ok && k == key {
200 return v
201 }
202 }
203 return ""
204}
205
206func sha256hex(b []byte) string {
207 sum := sha256.Sum256(b)
208 return hex.EncodeToString(sum[:])
209}
210
211// treeDigest asks attest for a revision's valley tree digest. One
212// implementation of the content-addressing scheme, in the program that
213// defines it.
214func (in *integrator) treeDigest(wt *worktree, rev string) (string, error) {
215 out, err := exec.Command(in.attest, "digest", "--repo", wt.dir, "--rev", rev).Output()
216 if err != nil {
217 return "", fmt.Errorf("digesting %s: %w", verdict.Short(rev), err)
218 }
219 digest := strings.TrimSpace(string(out))
220 scheme, value, ok := strings.Cut(digest, ":")
221 if !ok || scheme != "valley-tree-v1" {
222 return "", fmt.Errorf("attest digest printed %q", digest)
223 }
224 return value, nil
225}
226
227// closures recomputes the input-closure digest of each pure check over the
228// tree that would land. `attest inputs` evaluates and digests; it builds
229// nothing, so this stays off the latency path the commit point serializes.
230func (in *integrator) closures(wt *worktree, rev string, required []verdict.Required) (map[string]verdict.Closure, map[string]string) {
231 got, bad := map[string]verdict.Closure{}, map[string]string{}
232 names := make([]string, 0, len(required))
233 byAttr := map[string]string{}
234 for _, r := range required {
235 if r.Runner != "nix" {
236 continue
237 }
238 names = append(names, r.Name)
239 byAttr[r.Name] = r.Attribute
240 }
241 sort.Strings(names)
242 for _, name := range names {
243 args := []string{"inputs", "--repo", wt.dir, "--rev", rev, "--check", name + "=" + byAttr[name]}
244 if in.system != "" {
245 args = append(args, "--system", in.system)
246 }
247 out, err := exec.Command(in.attest, args...).CombinedOutput()
248 if err != nil {
249 bad[name] = firstLine(string(out))
250 continue
251 }
252 // "<name> valley-inputs-v1:<closure> sha256:<derivation>". Both
253 // digests are read, because the pure rule compares the whole of
254 // what the attestation claims.
255 fields := strings.Fields(string(out))
256 if len(fields) < 3 || !strings.HasPrefix(fields[1], "valley-inputs-v1:") || !strings.HasPrefix(fields[2], "sha256:") {
257 bad[name] = "attest inputs printed " + firstLine(string(out))
258 continue
259 }
260 got[name] = verdict.Closure{
261 Inputs: strings.TrimPrefix(fields[1], "valley-inputs-v1:"),
262 Derivation: strings.TrimPrefix(fields[2], "sha256:"),
263 }
264 }
265 return got, bad
266}
267
268func firstLine(s string) string {
269 s = strings.TrimSpace(s)
270 if i := strings.IndexByte(s, '\n'); i >= 0 {
271 return s[:i]
272 }
273 return s
274}
275
276// refusalLine is the sentence a verifier refused with. `attest` reports what
277// it checked, then the refusal prefixed with its own name, then whatever
278// elaborates it; a reader of a verdict wants the sentence. This convention
279// belongs to the command being driven, so it is read here, at the boundary
280// that drives it, and the verdict is handed a result rather than a
281// transcript to parse.
282func refusalLine(out string) string {
283 var last string
284 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
285 if why, ok := strings.CutPrefix(line, "attest: "); ok {
286 return strings.TrimSpace(why)
287 }
288 if strings.TrimSpace(line) != "" {
289 last = strings.TrimSpace(line)
290 }
291 }
292 return last
293}