gunk-dev/the-valley

evidence.go

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