gunk-dev/the-valley

evidence.go

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