gunk-dev/the-valley

evidence.go

source0b2daf24367fmain's published tip history
8.9 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/integrator/verdict"
17
18 "bytes"
19 "crypto/sha256"
20 "encoding/hex"
21 "fmt"
22 "os"
23 "os/exec"
24 "path"
25 "sort"
26 "strings"
27 "time"
28)
29
30const (
31 attestationPrefix = "refs/the-valley/attestations"
32 statementNote = "statement.note"
33
34 predicatePure = "the-valley/check/pure/v1"
35 predicateEffect = "the-valley/check/effectful/v1"
36 predicateTransfer = "the-valley/integration/transfer/v1"
37)
38
39// unknownSigner is the one sentence `attest verify` refuses a well-formed
40// note with when nobody who signed it is a key the verifier holds. Every
41// other refusal is a forgery as far as the integrator is concerned, so this
42// classification fails closed: an unrecognised message is a rejection.
43const unknownSigner = "no signature on this note is by a key the verifier holds"
44
45// collectEvidence finds every attestation stored for a subject digest and
46// classifies it. Attestations are stored one ref per signer
47// (dcr-0de694f), so a subject may carry several notes for one check; the
48// first admissible one is the evidence, and a note that does not verify at
49// all is reported so the verdict can reject rather than quietly look past
50// it.
51func (in *integrator) collectEvidence(wt *worktree, rev, subject string) (map[string]verdict.Evidence, map[string][]byte, error) {
52 refs, err := git(in.repo, "for-each-ref", "--format=%(refname)", attestationPrefix+"/"+subject)
53 if err != nil {
54 return nil, nil, err
55 }
56 found := map[string]verdict.Evidence{}
57 notes := map[string][]byte{}
58 for _, ref := range strings.Fields(refs) {
59 listing, err := git(in.repo, "ls-tree", "-r", "--name-only", ref)
60 if err != nil {
61 return nil, nil, err
62 }
63 for _, entry := range strings.Fields(listing) {
64 if path.Base(entry) != statementNote {
65 continue
66 }
67 note, err := git(in.repo, "cat-file", "blob", ref+":"+entry)
68 if err != nil {
69 return nil, nil, err
70 }
71 ev, err := in.classify(wt, rev, []byte(note))
72 if err != nil {
73 return nil, nil, err
74 }
75 // A check with an admissible note keeps it; otherwise the
76 // first thing found stands, so a forgery is never hidden by a
77 // good note arriving after it.
78 if old, seen := found[ev.Check]; seen && old.Admissible == verdict.Admissible {
79 continue
80 }
81 found[ev.Check], notes[ev.Check] = ev, []byte(note)
82 }
83 }
84 return found, notes, nil
85}
86
87// classify runs `attest verify` over one note and reads the statement back.
88func (in *integrator) classify(wt *worktree, rev string, note []byte) (verdict.Evidence, error) {
89 text, err := noteText(note)
90 if err != nil {
91 return verdict.Evidence{}, err
92 }
93 ev := verdict.Evidence{
94 TextDigest: sha256hex(text),
95 Check: statementValue(text, "predicate.check.name"),
96 Result: statementValue(text, "predicate.result"),
97 }
98 switch statementValue(text, "predicateType") {
99 case predicatePure:
100 ev.Kind = verdict.Pure
101 ev.Inputs = statementValue(text, "predicate.inputs.valley-inputs-v1")
102 ev.Derivation = statementValue(text, "predicate.derivation.sha256")
103 case predicateEffect:
104 ev.Kind = verdict.Effectful
105 if at := statementValue(text, "predicate.observedAt"); at != "" {
106 if t, err := time.Parse("2006-01-02T15:04:05Z", at); err == nil {
107 ev.ObservedAt = t
108 }
109 }
110 }
111 if ev.Check == "" {
112 ev.Check = "(unnamed)"
113 }
114
115 file, err := os.CreateTemp("", "valley-integrator-note")
116 if err != nil {
117 return ev, err
118 }
119 defer os.Remove(file.Name())
120 if _, err := file.Write(note); err != nil {
121 return ev, err
122 }
123 file.Close()
124
125 cmd := exec.Command(in.attest, "verify",
126 "--note", file.Name(),
127 "--known-keys", in.knownSigners,
128 "--schema", in.attestSchema,
129 "--repo", wt.dir, "--rev", rev)
130 out, err := cmd.CombinedOutput()
131 switch {
132 case err == nil:
133 ev.Admissible = verdict.Admissible
134 ev.Signer = verifiedSigner(string(out))
135 case strings.Contains(string(out), unknownSigner):
136 ev.Admissible = verdict.UnknownSigner
137 default:
138 ev.Admissible = verdict.Tampered
139 ev.Refusal = refusalLine(string(out))
140 }
141 return ev, nil
142}
143
144// verifiedSigner reads the name whose signature checked out, from the
145// verifier's own report.
146func verifiedSigner(out string) string {
147 for _, line := range strings.Split(out, "\n") {
148 if fields := strings.Fields(line); len(fields) == 3 && fields[0] == "signature" && fields[1] == "ok" {
149 return fields[2]
150 }
151 }
152 return ""
153}
154
155// noteText returns the bytes a signature covers: everything before the
156// blank line that separates the text from the signature block. The last
157// blank line wins, so text holding one of its own does not move the split
158// — the rule dcr-de9d996 fixes.
159func noteText(note []byte) ([]byte, error) {
160 split := bytes.LastIndex(note, []byte("\n\n"))
161 if split < 0 {
162 return nil, fmt.Errorf("this is not a note: no blank line separates the text from its signatures")
163 }
164 return note[:split+1], nil
165}
166
167// statementValue reads one line's value out of statement text. Sound only
168// because the form has no escapes and `attest verify` has established the
169// text is the written form of what it says: one line, one key, one value.
170func statementValue(text []byte, key string) string {
171 for _, line := range strings.Split(string(text), "\n") {
172 if k, v, ok := strings.Cut(line, " "); ok && k == key {
173 return v
174 }
175 }
176 return ""
177}
178
179func sha256hex(b []byte) string {
180 sum := sha256.Sum256(b)
181 return hex.EncodeToString(sum[:])
182}
183
184// treeDigest asks attest for a revision's valley tree digest. One
185// implementation of the content-addressing scheme, in the program that
186// defines it.
187func (in *integrator) treeDigest(wt *worktree, rev string) (string, error) {
188 out, err := exec.Command(in.attest, "digest", "--repo", wt.dir, "--rev", rev).Output()
189 if err != nil {
190 return "", fmt.Errorf("digesting %s: %w", verdict.Short(rev), err)
191 }
192 digest := strings.TrimSpace(string(out))
193 scheme, value, ok := strings.Cut(digest, ":")
194 if !ok || scheme != "valley-tree-v1" {
195 return "", fmt.Errorf("attest digest printed %q", digest)
196 }
197 return value, nil
198}
199
200// closures recomputes the input-closure digest of each pure check over the
201// tree that would land. `attest inputs` evaluates and digests; it builds
202// nothing, so this stays off the latency path the commit point serializes.
203func (in *integrator) closures(wt *worktree, rev string, required []verdict.Required) (map[string]verdict.Closure, map[string]string) {
204 got, bad := map[string]verdict.Closure{}, map[string]string{}
205 names := make([]string, 0, len(required))
206 byAttr := map[string]string{}
207 for _, r := range required {
208 if r.Runner != "nix" {
209 continue
210 }
211 names = append(names, r.Name)
212 byAttr[r.Name] = r.Attribute
213 }
214 sort.Strings(names)
215 for _, name := range names {
216 args := []string{"inputs", "--repo", wt.dir, "--rev", rev, "--check", name + "=" + byAttr[name]}
217 if in.system != "" {
218 args = append(args, "--system", in.system)
219 }
220 out, err := exec.Command(in.attest, args...).CombinedOutput()
221 if err != nil {
222 bad[name] = firstLine(string(out))
223 continue
224 }
225 // "<name> valley-inputs-v1:<closure> sha256:<derivation>". Both
226 // digests are read, because the pure rule compares the whole of
227 // what the attestation claims.
228 fields := strings.Fields(string(out))
229 if len(fields) < 3 || !strings.HasPrefix(fields[1], "valley-inputs-v1:") || !strings.HasPrefix(fields[2], "sha256:") {
230 bad[name] = "attest inputs printed " + firstLine(string(out))
231 continue
232 }
233 got[name] = verdict.Closure{
234 Inputs: strings.TrimPrefix(fields[1], "valley-inputs-v1:"),
235 Derivation: strings.TrimPrefix(fields[2], "sha256:"),
236 }
237 }
238 return got, bad
239}
240
241func firstLine(s string) string {
242 s = strings.TrimSpace(s)
243 if i := strings.IndexByte(s, '\n'); i >= 0 {
244 return s[:i]
245 }
246 return s
247}
248
249// refusalLine is the sentence a verifier refused with. `attest` reports what
250// it checked, then the refusal prefixed with its own name, then whatever
251// elaborates it; a reader of a verdict wants the sentence. This convention
252// belongs to the command being driven, so it is read here, at the boundary
253// that drives it, and the verdict is handed a result rather than a
254// transcript to parse.
255func refusalLine(out string) string {
256 var last string
257 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
258 if why, ok := strings.CutPrefix(line, "attest: "); ok {
259 return strings.TrimSpace(why)
260 }
261 if strings.TrimSpace(line) != "" {
262 last = strings.TrimSpace(line)
263 }
264 }
265 return last
266}