gunk-dev/the-valley

verdict.go

sourcef371ed059ef8main's published tip history
19.3 KiB
1// Package verdict is what integration decides, as a function of data.
2//
3// It is a library on purpose. Nothing in it reads git, runs nix, or looks
4// at a clock: a caller gathers all of that into a Snapshot first, and this
5// package turns the Snapshot into a decision. That is what makes the rules
6// of dcr-439b771 statable once and testable without a repository, and it
7// is why the refs transport — its first caller — is the only thing that
8// has to change when a second one arrives.
9package verdict
10
11// Integration is optimistic concurrency control over content-addressed
12// evidence. A change is a transaction; its snapshot is the base tree its
13// attestations were produced over; its read set is the union of its
14// required checks' input closures; its write set is its delta. The
15// integrator is the commit point, and the commit rule has two parts: the
16// delta must apply cleanly to the current tip, and per required check the
17// evidence must transfer.
18
19import (
20 "fmt"
21 "sort"
22 "time"
23)
24
25// Outcome is what the integrator does with a change.
26type Outcome string
27
28const (
29 // Land: the delta applies and every required check's evidence stands.
30 Land Outcome = "land"
31
32 // Stale: the change is behind, not wrong. Either the delta no longer
33 // applies or some evidence no longer transfers. The request stays put
34 // and retry is partial — only the named checks need new evidence.
35 Stale Outcome = "stale"
36
37 // Reject: the evidence is not evidence. A note whose signature does
38 // not check out, text that is not the written form of what it says, or
39 // a statement about a different tree is not a staleness problem, and
40 // re-attesting would not fix it.
41 Reject Outcome = "reject"
42)
43
44// Kind is the two kinds of claim of archive/design/verification.md, which decide
45// which transfer rule applies.
46type Kind string
47
48const (
49 Pure Kind = "pure"
50 Effectful Kind = "effectful"
51)
52
53// KindOf is the kind of claim a policy runner demands. It is the whole of
54// the mapping from what the policy says about a check to which transfer
55// rule governs its evidence, and it is the only thing that decides which
56// rule runs. An unknown runner maps to no kind and gets no default: a
57// check nobody has decided how to transfer is not one to land on a guess.
58func KindOf(runner string) Kind {
59 switch runner {
60 case "nix":
61 return Pure
62 case "command":
63 return Effectful
64 }
65 return ""
66}
67
68// Admissibility is what a verifier made of an attestation before any
69// transfer rule was applied.
70type Admissibility string
71
72const (
73 // Admissible: the note verifies under a key the integrator holds, its
74 // text is the written form of what it says, and its subject is the
75 // tree the change produces.
76 Admissible Admissibility = "admissible"
77
78 // UnknownSigner: the note is well formed but nobody who signed it is
79 // in the known-signers file. Evidence from a signer the integrator
80 // does not hold does not transfer. Deciding what to do about an
81 // unknown attester — re-verification, trust measurement — belongs to
82 // the trust backstop and is deliberately not here.
83 UnknownSigner Admissibility = "unknown-signer"
84
85 // Tampered: everything else a verifier can refuse — a signature that
86 // does not check out over the text, text that is not its own written
87 // form, a statement whose subject digest is not the change's tree.
88 Tampered Admissibility = "tampered"
89)
90
91// Change is the integration primitive (ida-93e4f91): a delta targeting a
92// version stream, with the provenance and the attestations produced over
93// the tree it results in. The branch it arrived on is transport.
94type Change struct {
95 // ID names the change. The refs transport takes it from the last
96 // segment of the request ref.
97 ID string
98
99 // Target is the protected ref the delta targets, in full.
100 Target string
101
102 // Base is the commit the delta was authored against, and Head the
103 // commit whose tree the attestations name.
104 Base string
105 Head string
106
107 // Attested is the valley-tree-v1 digest of Head's tree — the snapshot
108 // the transaction read, and the subject every attestation names.
109 Attested string
110
111 // Evidence is the attestations found for this change, by check name.
112 Evidence map[string]Evidence
113
114 // Landed is the attestations found for the tree that would land, by
115 // check name, when that tree is not the attested tree. Their subject is
116 // exactly what lands, so a passing one stands for its check with no
117 // transfer rule to run.
118 Landed map[string]Evidence
119}
120
121// Evidence is one attestation as the integrator read it back.
122type Evidence struct {
123 Check string
124 Kind Kind
125 Admissible Admissibility
126
127 // Runner and Attribute are the computation the signer says ran, as
128 // the note's predicate.check.runner and predicate.check.attribute
129 // hold them. A command check has no attribute.
130 Runner string
131 Attribute string
132
133 // Result is what the statement recorded. A statement recording a
134 // failure is not evidence that a check passed.
135 Result string
136
137 // Inputs and Derivation are the two re-derivable digests a pure claim
138 // carries: the digest of the check's input closure, and the digest of
139 // the derivation that closure builds. Both are compared, because the
140 // claim a pure attestation makes is the whole of what it records, and
141 // evidence that transfers is evidence whose whole claim still holds
142 // (dcr-0de694f).
143 Inputs string
144 Derivation string
145
146 // ObservedAt is when an effectful check's result was observed.
147 ObservedAt time.Time
148
149 // TextDigest is a SHA-256 over the bytes the signature covers. The
150 // transfer statement cites the original by this digest.
151 TextDigest string
152
153 // Signer names the key whose signature the integrator accepted, for
154 // the reader of an outcome. Empty when none was accepted.
155 Signer string
156
157 // Refusal is the sentence a verifier refused this attestation with,
158 // already extracted by whoever ran the verifier. This package never
159 // parses another program's output: a caller that drives a command-line
160 // verifier owns that command's conventions, and hands the result in
161 // structured.
162 Refusal string
163}
164
165// Required is one check the policy demands of this change, as the deriver
166// named it.
167type Required struct {
168 Name string
169
170 // Classes are the path classes that made this check required. An
171 // effectful check's scope is these classes' paths: an intervening
172 // landing inside one of them is what ends the observation's validity.
173 Classes []string
174
175 // Runner and Attribute are how the check is run, from the composed
176 // policy's catalogue.
177 Runner string
178 Attribute string
179
180 // Validity is Δ: how long an effectful observation of this check stays
181 // good. Zero means the policy declares no window, and absent a
182 // declared window the check is re-demanded — a window nobody wrote
183 // down is not a window the integrator may invent.
184 Validity time.Duration
185}
186
187// Applied is what happened when the delta was applied to the current tip.
188type Applied struct {
189 // Clean says the delta applied with no conflict. A conflict means
190 // resolving it would produce a tree nobody has authored, and new
191 // authorship needs new evidence.
192 Clean bool
193
194 // Conflict is what the merge said, for the reader of the outcome.
195 Conflict string
196
197 // Tree is the valley-tree-v1 digest of the resulting tree. Equal to
198 // the change's Attested digest exactly when nothing the change reads
199 // has moved, whatever else landed in between.
200 Tree string
201}
202
203// Snapshot is everything about a change that had to be computed by
204// touching git, nix, or the clock. A transport fills it in; the verdict is
205// a function of it.
206type Snapshot struct {
207 Apply Applied
208
209 // Required is the check set derived from the diff by the policy
210 // machinery, read at the target tip and never from the submitted tree.
211 Required []Required
212
213 // Closures holds each pure check's re-derivable digests as recomputed
214 // over the tree that would land, keyed by check name. A check missing
215 // from both this map and ClosureErrors was not recomputed because it
216 // did not need to be.
217 Closures map[string]Closure
218
219 // ClosureErrors holds why a recomputation could not be done. A closure
220 // the integrator cannot compute is a check it cannot transfer.
221 ClosureErrors map[string]string
222
223 // Touched are the policy classes that intervening landed changes
224 // touched, between the change's base and the current tip.
225 Touched map[string]bool
226
227 // Now is when the judgement is being made, for the effectful window.
228 Now time.Time
229}
230
231// Closure is what evaluating a pure check over a tree named, before
232// anything was built: the digest of its input closure and the digest of
233// its derivation.
234type Closure struct {
235 Inputs string
236 Derivation string
237}
238
239// CheckVerdict is one check's outcome at the commit point.
240type CheckVerdict struct {
241 Name string
242
243 // Transferred says the evidence stands on the landed tree.
244 Transferred bool
245
246 // Rule is which transfer rule carried it: "unmoved" when the landed
247 // tree is the tree the evidence attests, the change's own or the
248 // landing tree's, "closure" when the recomputed input closure equalled
249 // the attested one, "untouched" when an effectful observation's scope
250 // was untouched and it was inside its window.
251 Rule string
252
253 // Direct says the evidence is the landing tree's own, from
254 // Change.Landed, rather than the change's.
255 Direct bool
256
257 // Reason says why it did not transfer, in words a contributor can act
258 // on. Empty when it did.
259 Reason string
260
261 // Evidence is the digest of the statement text this verdict is about,
262 // and Inputs the closure digest recomputed under the closure rule.
263 Evidence string
264 Inputs string
265
266 Signer string
267}
268
269// Verdict is what the integrator decided, and everything the outcome event
270// and the transfer statement are written from.
271type Verdict struct {
272 Outcome Outcome
273
274 // Reason is the one-line summary a reader gets. For a rejection it is
275 // what was wrong; for staleness, which rule the change fell to.
276 Reason string
277
278 // StaleReason distinguishes the two ways a change goes stale, as
279 // #RequestStale carries it: "conflict" or "evidence".
280 StaleReason string
281
282 // Checks is the per-check verdict, in the order the checks were
283 // required.
284 Checks []CheckVerdict
285
286 // Invalidated is exactly the checks that need new evidence — the
287 // event's payload, and the whole of what a contributor has to redo.
288 Invalidated []string
289}
290
291// Decide applies the commit rule of dcr-439b771 to a change.
292func Decide(ch Change, s Snapshot) Verdict {
293 required := append([]Required(nil), s.Required...)
294 sort.Slice(required, func(i, j int) bool { return required[i].Name < required[j].Name })
295
296 // First part of the commit rule: the delta must apply cleanly. A
297 // conflict is new authorship, so every check is re-demanded rather
298 // than a subset — there is no partial retry from a tree nobody wrote.
299 if !s.Apply.Clean {
300 v := Verdict{
301 Outcome: Stale,
302 StaleReason: "conflict",
303 Reason: "the delta does not apply cleanly to the tip; resolving it is new authorship, so every check needs new evidence",
304 }
305 if s.Apply.Conflict != "" {
306 v.Reason += " (" + s.Apply.Conflict + ")"
307 }
308 for _, r := range required {
309 v.Checks = append(v.Checks, CheckVerdict{Name: r.Name, Reason: "the delta conflicts, so the tree this would be evidence about does not exist yet"})
310 v.Invalidated = append(v.Invalidated, r.Name)
311 }
312 return v
313 }
314
315 unmoved := s.Apply.Tree != "" && s.Apply.Tree == ch.Attested
316
317 v := Verdict{Outcome: Land}
318 for _, r := range required {
319 cv := judge(ch, s, r, unmoved)
320 v.Checks = append(v.Checks, cv)
321 switch {
322 case cv.Rule == "rejected":
323 // A forgery ends the judgement: the change is not behind, its
324 // evidence is not evidence.
325 return Verdict{
326 Outcome: Reject,
327 Reason: fmt.Sprintf("%s: %s", r.Name, cv.Reason),
328 Checks: v.Checks,
329 }
330 case !cv.Transferred:
331 v.Invalidated = append(v.Invalidated, r.Name)
332 }
333 }
334 if len(v.Invalidated) > 0 {
335 v.Outcome = Stale
336 v.StaleReason = "evidence"
337 v.Reason = fmt.Sprintf("%d of %d required checks no longer carry evidence that transfers", len(v.Invalidated), len(required))
338 return v
339 }
340 switch {
341 // Nothing required is an outcome, not a count of zero. There are two
342 // ways to require nothing, and a reader needs to know which: the diff
343 // was covered and asked nothing of, or there was no diff to ask
344 // anything of. The second is a change already in the target's history — its base is
345 // its head, because the base is the merge base with the tip — and
346 // saying so is what keeps a request approved again from reading as a
347 // change that passed every check it had. A base nobody recorded is
348 // not that case; it is a caller that filled in neither.
349 case len(required) == 0 && ch.Base != "" && ch.Base == ch.Head:
350 v.Reason = "this change is already in the target's history, so its delta is empty and the policy requires nothing of it"
351 case len(required) == 0:
352 v.Reason = "the policy requires no check of the paths this change touches"
353 case len(required) == 1:
354 v.Reason = "the one required check carries evidence that transfers"
355 default:
356 v.Reason = fmt.Sprintf("all %d required checks carry evidence that transfers", len(required))
357 }
358 return v
359}
360
361// judge is the second part of the commit rule, for one check. On a moved
362// landing a check stands on either of two sources: the landing tree's own
363// evidence, which needs no transfer, or the change's evidence carried by a
364// transfer rule. The landing tree's is preferred when both stand. The
365// evidence from each source is the one note the caller selected for the
366// check, and a forgery in either selected note rejects the change.
367func judge(ch Change, s Snapshot, r Required, unmoved bool) CheckVerdict {
368 own := weigh(ch.Evidence, s, r, unmoved)
369 if _, ok := ch.Landed[r.Name]; unmoved || !ok || own.Rule == "rejected" {
370 return own
371 }
372 // The landing tree's evidence is about the tree that lands, so no
373 // intervening landing is outside it: its scope is untouched by
374 // construction, and only an effectful check's window applies.
375 direct := weigh(ch.Landed, Snapshot{Now: s.Now}, Required{
376 Name: r.Name, Runner: r.Runner, Attribute: r.Attribute, Validity: r.Validity,
377 }, true)
378 direct.Direct = true
379 switch {
380 case direct.Transferred:
381 // The landed tree is the tree this evidence attests, whichever
382 // kind of check it is.
383 direct.Rule = "unmoved"
384 return direct
385 case direct.Rule == "rejected":
386 return direct
387 case own.Transferred:
388 return own
389 }
390 own.Reason += fmt.Sprintf("; the attestation for the tree that would land, %s, does not stand either: %s", Short(s.Apply.Tree), direct.Reason)
391 return own
392}
393
394// weigh judges one check's evidence from one source. unmoved says the
395// landed tree is the tree that source's evidence attests.
396func weigh(evidence map[string]Evidence, s Snapshot, r Required, unmoved bool) CheckVerdict {
397 cv := CheckVerdict{Name: r.Name}
398 ev, ok := evidence[r.Name]
399 if !ok {
400 cv.Reason = "no attestation for this check accompanies the change"
401 return cv
402 }
403 cv.Evidence, cv.Signer = ev.TextDigest, ev.Signer
404
405 switch ev.Admissible {
406 case Tampered:
407 cv.Rule = "rejected"
408 cv.Reason = "the attestation does not verify as the statement it claims to be"
409 if ev.Refusal != "" {
410 cv.Reason += ": " + ev.Refusal
411 }
412 return cv
413 case UnknownSigner:
414 cv.Reason = "signed by no signer the integrator holds, so its evidence does not transfer"
415 return cv
416 }
417 if ev.Result != "passed" {
418 cv.Reason = fmt.Sprintf("the attestation records the check as %s", ev.Result)
419 return cv
420 }
421
422 // Which transfer rule applies is the policy's to say, never the
423 // attestation's. The policy names a check's runner, and the runner is
424 // what decides whether the evidence is content-addressed or a
425 // notarization. An attestation whose own kind contradicts the runner is
426 // refused rather than judged by the rule it nominated for itself:
427 // taking the claim's word for it would let an attester opt out of
428 // closure comparison by declaring a notarization.
429 want := KindOf(r.Runner)
430 if want == "" {
431 cv.Rule = "rejected"
432 cv.Reason = fmt.Sprintf("the policy runs this check with %q, and no transfer rule is defined for that runner", r.Runner)
433 return cv
434 }
435 // A verified note is evidence for a check only when it ran the
436 // computation the policy requires: the same kind, runner and flake
437 // attribute. A passing note for another computation under the same check
438 // name says nothing about this one, on an unmoved tree as much as a moved
439 // one. It is no evidence rather than a rejection, so the verdict can fall
440 // back to the other source. This is the rule approve's coverage applies
441 // before it reuses a note (status/coverage.go).
442 if ev.Kind != want {
443 cv.Reason = fmt.Sprintf("the policy requires %s and the attestation is for %s", article(want), article(ev.Kind))
444 return cv
445 }
446 if ev.Runner != r.Runner || ev.Attribute != r.Attribute {
447 cv.Reason = fmt.Sprintf("the attestation is for %s, and the policy requires %s", computation(ev.Runner, ev.Attribute), computation(r.Runner, r.Attribute))
448 return cv
449 }
450
451 if want == Pure {
452 // Content-addressed evidence does not age: a pure attestation
453 // carries no expiry, because time is not among its inputs.
454 if unmoved {
455 cv.Transferred, cv.Rule = true, "unmoved"
456 return cv
457 }
458 if why, bad := s.ClosureErrors[r.Name]; bad {
459 cv.Reason = "the input closure could not be recomputed on the landed tree: " + why
460 return cv
461 }
462 got, ok := s.Closures[r.Name]
463 if !ok {
464 cv.Reason = "the input closure was not recomputed on the landed tree"
465 return cv
466 }
467 if got.Inputs != ev.Inputs {
468 cv.Reason = fmt.Sprintf("its input closure changed: attested %s, landed tree %s", Short(ev.Inputs), Short(got.Inputs))
469 return cv
470 }
471 // The claim a pure attestation makes is the whole of what it
472 // records, so a derivation that moved under an unchanged closure
473 // is evidence about a computation this tree no longer presents.
474 if got.Derivation != ev.Derivation {
475 cv.Reason = fmt.Sprintf("its derivation changed: attested %s, landed tree %s", Short(ev.Derivation), Short(got.Derivation))
476 return cv
477 }
478 cv.Transferred, cv.Rule, cv.Inputs = true, "closure", got.Inputs
479 return cv
480 }
481
482 // An effectful observation transfers while its scope is untouched and
483 // it is recent enough. Serializable semantics against mutable world
484 // state are unattainable in principle, so the honest semantics are
485 // bounded staleness.
486 for _, class := range r.Classes {
487 if s.Touched[class] {
488 cv.Reason = fmt.Sprintf("an intervening landed change touched the %s class, which is what this check reads", class)
489 return cv
490 }
491 }
492 if r.Validity == 0 {
493 cv.Reason = "the policy declares no validity window for this effectful check, so its observation is re-demanded"
494 return cv
495 }
496 if age := s.Now.Sub(ev.ObservedAt); age >= r.Validity {
497 cv.Reason = fmt.Sprintf("the observation is %s old and the declared window is %s", age.Round(time.Second), r.Validity)
498 return cv
499 }
500 cv.Transferred, cv.Rule = true, "untouched"
501 return cv
502}
503
504// computation reads a runner and attribute as a reader would say them.
505func computation(runner, attribute string) string {
506 if attribute == "" {
507 return fmt.Sprintf("runner %q with no attribute", runner)
508 }
509 return fmt.Sprintf("runner %q, attribute %q", runner, attribute)
510}
511
512// article reads a kind as a reader would say it.
513func article(k Kind) string {
514 if k == Effectful {
515 return "an effectful check"
516 }
517 if k == "" {
518 return "no kind at all"
519 }
520 return "a " + string(k) + " check"
521}
522
523// Short abbreviates a digest for a reader. Exported because a caller
524// reporting the same verdict should abbreviate the same way.
525func Short(digest string) string {
526 if len(digest) > 12 {
527 return digest[:12]
528 }
529 return digest
530}