gunk-dev/the-valley

policy.go

sourcec4c1671e1d82main's published tip history
8.9 KiB
1package main
2
3// The policy bridge. The integrator derives required checks in-process:
4// cue composes the two layers under the schema into one model, as the
5// composed-policy reader (../composed) reads it, and the deriver
6// (../derive) matches a diff's paths against that model. Composition is
7// cue's alone, so the integrator holds no second copy of it.
8//
9// Both layers are resolved from the integrator's own side and never from
10// the submitted tree (bd-eaefe82): the project layer from the target tip,
11// the instance layer from where the integrator is configured to find it. A change therefore never supplies the policy that gates it.
12//
13// Each layer is a directory of its own under `policy/`, which is the layout
14// dcr-f41f718's worked example lays out and the layout the defaults name:
15// the floor at `policy/instance` in the instance repository's tip, the
16// project's own layer at `policy/project` in the target tip. A repository
17// that keeps either somewhere else says so with --instance-policy or
18// --project-policy.
19//
20// A layer that is not there defaults in the safe direction of that layer's
21// job (dcr-f41f718), and the two directions are opposite: an absent project
22// layer composes the floor alone, and an absent floor is refused.
23
24import (
25 "the-valley/composed"
26 "the-valley/derive"
27 "the-valley/integrator/verdict"
28
29 "context"
30 "fmt"
31 "time"
32)
33
34// The floor is the instance repository's, read at the tip that has been
35// integrated (dcr-f41f718), and the instance repository is the group's own
36// (dcr-b87f6e8). A host that serves that repository is therefore already
37// holding the authoritative copy, and reading it there is reading it where
38// it is authoritative: no checkout to keep in step, no refresh to schedule,
39// and no way for the floor a controller composes against to differ from the
40// floor the group last landed. composed.Floor reads it with ls-tree and
41// show rather than a worktree, because a worktree would write into the
42// instance repository, and a controller has no business writing a
43// repository it does not serve.
44//
45// The consequence is worth stating, because it is a property and not a
46// limitation. A change to the floor takes effect at the first pass after it
47// lands on that ref, and never before — an edit sitting in a branch, a
48// worktree, or a request that has not been integrated governs nothing.
49//
50// A host that serves no instance repository is given a materialized
51// directory of `*.cue` instead.
52
53// policySource is where the two layers are read from, and the schema they
54// are composed under.
55type policySource struct {
56 schema string // the verification schema
57 layer composed.Floor
58 projectDir string // the project layer's directory in the target tip's tree
59 cue string // the composer
60
61 // diff reads every side of a diff in a repository; derive.Diff when
62 // nil.
63 diff func(ctx context.Context, dir string, env []string, base, head string) ([]string, error)
64
65 // Both layers as directories of *.cue on disk, and the policy they
66 // compose, resolved and read by open and good for one request.
67 instance string
68 project string
69 model *composed.Model
70
71 // note is the one thing a pass has to say about how the layers
72 // resolved, when that is not what the configuration reads as. Empty
73 // when both were where they are configured to be.
74 note string
75}
76
77// open resolves both layers, reads the policy they compose, and returns a
78// source that derives under it, together with what ends the request's use
79// of it. The policy is read once per request, so the request's candidate
80// derivation, its intervening derivation, the check definitions and the
81// digest its landing records are all of one model.
82func (p policySource) open(tip *worktree) (policySource, func(), error) {
83 dir, done, err := p.layer.Open(context.Background(), "valley-integrator-floor")
84 if err != nil {
85 return p, done, err
86 }
87 p.instance = dir
88 endProject, err := p.openProject(tip)
89 if err != nil {
90 done()
91 return p, func() {}, err
92 }
93 if err := p.read(); err != nil {
94 endProject()
95 done()
96 return p, func() {}, err
97 }
98 return p, func() { endProject(); done() }, nil
99}
100
101// read composes the resolved layers under the schema into the model. The
102// integrator never reads whether a requirement is mandatory, so it reads
103// the model without asking cue that of every requirement.
104func (p *policySource) read() error {
105 m, err := composed.ReadUnpinned(context.Background(), p.cue, p.schema, p.instance, p.project)
106 if err != nil {
107 return err
108 }
109 p.model = m
110 return nil
111}
112
113// openProject resolves the project's own layer at the target tip, read
114// from git as composed.Project reads it, and returns what ends it. The
115// layer is read from the tip's commit and not from the checkout's files,
116// so presence is decided as approve decides it: a directory with a *.cue
117// entry is there, one with none is not, and one that cannot be read is
118// refused.
119//
120// A target that carries no layer of its own is judged under the floor
121// alone. The project layer only ever adds (dcr-f41f718), and the identity
122// of "adds" is "adds nothing", so that is what absence means. Refusing the
123// target instead would make a repository unlandable until its first policy
124// commit, which cannot land either: a change never supplies the policy that
125// gates it.
126func (p *policySource) openProject(tip *worktree) (func(), error) {
127 dir, note, done, err := composed.Project(context.Background(), tip.repo, tip.rev, p.projectDir, "valley-integrator-project")
128 if err != nil {
129 return done, err
130 }
131 p.project, p.note = dir, note
132 return done, nil
133}
134
135// derived is one derivation over a diff: how many changed paths it read,
136// which classes the diff matched, which checks that made required, and the
137// change's carry mode.
138//
139// A path no class covers puts the name `unclassified` in classes, and a
140// check the policy's `unclassified` set requires names it among the classes
141// requiring it. A class the policy itself names `unclassified` folds into
142// that one name. That only widens what an intervening change reads as
143// touching, so it can stop an observation transferring and never let one
144// through.
145type derived struct {
146 paths int
147 classes map[string]bool
148 requires map[string][]string // check name -> the classes requiring it
149 carry string // how far an approval carries across a rebase
150}
151
152// derive derives the checks a diff requires under the request's model, in
153// a checkout of the target tip. The checkout supplies the commits the diff
154// names; the policy comes from outside it.
155func (p policySource) derive(tip *worktree, from, to string) (derived, error) {
156 fail := func(err error) (derived, error) {
157 return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w", verdict.Short(from), verdict.Short(to), err)
158 }
159 diff := p.diff
160 if diff == nil {
161 diff = derive.Diff
162 }
163 paths, err := diff(context.Background(), tip.dir, nil, from, to)
164 if err != nil {
165 return fail(err)
166 }
167 r, err := derive.Derive(p.model, paths)
168 if err != nil {
169 return fail(err)
170 }
171 d := derived{paths: len(r.Paths), classes: map[string]bool{}, requires: map[string][]string{}, carry: r.Carry}
172 for _, c := range r.Classes {
173 d.classes[c] = true
174 }
175 if len(r.Unclassified) > 0 {
176 d.classes["unclassified"] = true
177 }
178 for _, q := range r.Required {
179 by := append([]string{}, q.Classes...)
180 if q.Unclassified {
181 by = append(by, "unclassified")
182 }
183 d.requires[q.Name] = by
184 }
185 // A diff misread as empty requires nothing, so no changed paths are
186 // believed only when git agrees that the two trees are the same.
187 if d.paths == 0 {
188 if _, err := git(tip.dir, "diff-tree", "--quiet", from, to); err != nil {
189 return derived{}, fmt.Errorf("the deriver read no changed paths in %s..%s, and git does not agree: %w", verdict.Short(from), verdict.Short(to), err)
190 }
191 }
192 return d, nil
193}
194
195// required turns a derivation into the check set the verdict is computed
196// over, with each check as the model defines it: a pure check's attribute
197// is what the integrator evaluates a closure over, and an effectful
198// check's window is Δ.
199func (p policySource) required(d derived) ([]verdict.Required, error) {
200 var out []verdict.Required
201 for name, classes := range d.requires {
202 entry, ok := p.model.Checks[name]
203 if !ok {
204 return nil, fmt.Errorf("the policy requires %q and defines no check by that name", name)
205 }
206 window, err := parseWindow(entry.Validity)
207 if err != nil {
208 return nil, fmt.Errorf("check %s: %w", name, err)
209 }
210 out = append(out, verdict.Required{
211 Name: name,
212 Classes: classes,
213 Runner: entry.Runner,
214 Attribute: entry.Attribute,
215 Validity: window,
216 })
217 }
218 return out, nil
219}
220
221// parseWindow reads a #Duration from the policy. The schema admits whole
222// seconds, minutes, hours and days; an empty window is no window, which is
223// what makes the integrator re-demand the check.
224func parseWindow(s string) (time.Duration, error) {
225 if s == "" {
226 return 0, nil
227 }
228 unit := s[len(s)-1]
229 if unit == 'd' {
230 d, err := time.ParseDuration(s[:len(s)-1] + "h")
231 return d * 24, err
232 }
233 return time.ParseDuration(s)
234}