gunk-dev/the-valley

policy.go

sourcec66fe008501cmain's published tip history
13.9 KiB
1package main
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "math"
8 "os"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "time"
13
14 "the-valley/readaccess"
15 "the-valley/web/export"
16)
17
18// The policy path's state, beside what state.go lists:
19//
20// authorization.lock held while a policy check is read, its
21// sequence allocated and its authorization signed
22// authorization-sequence the greatest sequence an authorization was
23// signed with
24// authorization the last authorization the receiver said it
25// stored, as a signed note
26// links-delivery the greatest credential file revision signed
27// from, written under the links lock beside the
28// credential file, and the revision the last
29// stored authorization carried the links of
30// (link.go)
31const (
32 authorizationLockFile = "authorization.lock"
33 authorizationSequenceFile = "authorization-sequence"
34 authorizationFile = "authorization"
35)
36
37// authorizeAttempts is how many times the policy path signs the current
38// policy again when the receiver holds a newer authorization than this
39// publisher's counter.
40const authorizeAttempts = 3
41
42// errIncomplete is the error of a policy check that could not read every
43// project. Its authorization was still signed and sent.
44var errIncomplete = errors.New("the policy check is incomplete")
45
46// authorize is the policy path: the only writer of authorizations. Under
47// the authorization lock it reads the policy, allocates the next sequence
48// from the durable counter, and signs the authorization. It then sends it
49// to the receiver, outside the lock. With --out it sends nothing, and the
50// signed authorization is written with the export.
51//
52// A receiver that holds a newer authorization refuses this one as
53// replayed, and one that holds another than its basis refuses it as
54// stale-basis. Either says the publisher's record of the receiver is out
55// of date, as after its state is restored from an older backup. The
56// policy path then checks the policy again, signs the current result above
57// the receiver's sequence, and keeps no access it could not check: it
58// knows nothing it can trust of what the receiver serves. It never sends
59// an authorization it signed earlier.
60//
61// Once the receiver stores an authorization, it is recorded as the last
62// one acknowledged, which the next incomplete check may keep access from.
63//
64// The reply is nil with --out. An incomplete check is sent, and authorize
65// then returns an error that wraps errIncomplete. So is an authorization
66// signed with no bindings because the links lock could not be taken or the
67// credential file could not be read, and authorize then returns that error.
68func (p *publisher) authorize(ctx context.Context) (*export.AuthorizationReply, error) {
69 var floor int64
70 trusted := true
71 for attempt := 1; ; attempt++ {
72 c, err := p.signPolicy(ctx, floor, trusted)
73 if err != nil {
74 return nil, err
75 }
76 a := c.authorization
77 failed := errors.Join(c.incomplete, c.links.err)
78 if p.cfg.out != "" {
79 p.signedAuthorization = c.signed
80 return nil, failed
81 }
82 reply, err := p.sendAuthorization(ctx, a, c.signed)
83 var refusal *export.Error
84 if errors.As(err, &refusal) && (refusal.Code == export.CodeReplayed || refusal.Code == export.CodeStaleBasis) && attempt < authorizeAttempts {
85 p.warn("the receiver holds authorization %d, and refused %d as %s; rechecking the policy, keeping no access it cannot check, and signing above %d",
86 refusal.HighWater, a.Sequence, refusal.Code, refusal.HighWater)
87 floor, trusted = refusal.HighWater, false
88 continue
89 }
90 if err != nil {
91 return nil, err
92 }
93 if err := p.recordAuthorization(a, c.signed, c.links.revision); err != nil {
94 return nil, err
95 }
96 p.say("the receiver stored authorization %d: %s", a.Sequence, describe(a))
97 return reply, failed
98 }
99}
100
101// recordAuthorization records an authorization the receiver said it
102// stored, and the credential file revision it carried the read links of,
103// under the authorization lock, unless a greater one is recorded already.
104func (p *publisher) recordAuthorization(a *export.Authorization, signed []byte, revision int64) error {
105 unlock, err := lockFile(filepath.Join(p.cfg.state, authorizationLockFile))
106 if err != nil {
107 return err
108 }
109 defer unlock()
110 last, err := p.lastAcknowledged()
111 if err != nil {
112 return err
113 }
114 if last != nil && last.Sequence >= a.Sequence {
115 return nil
116 }
117 if err := writeDurable(filepath.Join(p.cfg.state, authorizationFile), signed, 0o600); err != nil {
118 return err
119 }
120 return p.recordDelivery(a, revision)
121}
122
123// describe is what an authorization lets anyone read, for messages.
124func describe(a *export.Authorization) string {
125 var names []string
126 for _, proj := range a.Projects {
127 names = append(names, proj.Name)
128 }
129 s := "anyone may read " + listNames(names)
130 if len(a.Bindings) > 0 {
131 s += fmt.Sprintf("; %d read links", len(a.Bindings))
132 }
133 return s
134}
135
136// policyCheck is what one check of the policy found: the projects it
137// authorizes, and, when some project's policy could not be read, an error
138// that wraps errIncomplete. A signed check also has its authorization and
139// the signed note.
140type policyCheck struct {
141 projects []export.AuthorizedProject
142 incomplete error
143 // kept is set when a project keeps access it could not check.
144 kept bool
145 // links is what the check read of the read links.
146 links linkRead
147 authorization *export.Authorization
148 signed []byte
149}
150
151// signPolicy reads the policy and signs an authorization for it, holding
152// the authorization lock throughout, so of two authorizations the one with
153// the greater sequence always reflects the later check. The sequence is
154// greater than floor and than every sequence signed before. When trusted
155// is set, a project whose policy cannot be read may keep the access the
156// last acknowledged authorization gave it, and the authorization then
157// names that one as its basis. The read links are read last, after the
158// check, under the links lock, which is held until the authorization is
159// signed, and every authorization it signs carries them, one that keeps
160// access included. Every change to the credential file holds the links
161// lock, so none lands between that read and the signature. The lock order
162// is the authorization lock, then the links lock.
163func (p *publisher) signPolicy(ctx context.Context, floor int64, trusted bool) (policyCheck, error) {
164 unlock, err := lockFile(filepath.Join(p.cfg.state, authorizationLockFile))
165 if err != nil {
166 return policyCheck{}, err
167 }
168 defer unlock()
169 if p.key, err = p.loadKey(); err != nil {
170 return policyCheck{}, err
171 }
172 prev, err := p.lastAcknowledged()
173 if err != nil {
174 return policyCheck{}, err
175 }
176 keepFrom := prev
177 if !trusted {
178 keepFrom = nil
179 }
180 c, err := p.checkPolicy(ctx, keepFrom)
181 if err != nil {
182 return policyCheck{}, err
183 }
184 // A check that did not read every project leaves the time of the last
185 // one that did, or the epoch when none has.
186 checked := time.Unix(0, 0).UTC()
187 switch {
188 case c.incomplete == nil:
189 checked = p.now().UTC().Truncate(time.Second)
190 case prev != nil:
191 checked = prev.Checked
192 }
193 seq, err := p.nextSequence(floor)
194 if err != nil {
195 return policyCheck{}, err
196 }
197 c.authorization = &export.Authorization{Instance: p.cfg.instance, Destination: p.cfg.destination,
198 Sequence: seq, Checked: checked, Projects: c.projects}
199 if c.kept {
200 c.authorization.Basis = keepFrom.Sequence
201 }
202 unlockLinks, links := p.readBindings()
203 c.links = links
204 c.authorization.Bindings = c.links.bindings
205 c.signed, err = c.authorization.Sign(p.signer, p.key)
206 unlockLinks()
207 if err != nil {
208 return policyCheck{}, err
209 }
210 return c, nil
211}
212
213// checkPolicy reads who may read each project at the destination: the
214// instance's read grants, and each selected project's own policy/read. It
215// reads no plan, no knot and no listing of the CLI, so no project's graph
216// can fail it. It reads into caches of its own, under policy/ in the
217// publisher's cache, so a content pass running beside it is not disturbed.
218//
219// A project is authorized for anyone when a pass would publish it: a read
220// grant to anyone covers it, the host declaration places it in a group,
221// and its policy/read lets anyone read it. A project whose policy cannot
222// be read keeps what prev gave it, as long as the grants still cover it,
223// and never more; the check is then incomplete. prev is the authorization
224// the receiver last said it stored, or nil when that is not known, and
225// then nothing is kept. An instance or registry that cannot be read fails
226// the check, and nothing is signed.
227func (p *publisher) checkPolicy(ctx context.Context, prev *export.Authorization) (policyCheck, error) {
228 q := *p
229 q.origin = filepath.Join(p.cache, "policy", "origin.git")
230 q.mirrors = filepath.Join(p.cache, "policy", "repos")
231 if err := q.access.CheckSchemas(ctx); err != nil {
232 return policyCheck{}, err
233 }
234 inst, err := q.fetchInstance(ctx)
235 if err != nil {
236 return policyCheck{}, err
237 }
238 grants, err := q.readGrants(ctx, inst)
239 if err != nil {
240 return policyCheck{}, err
241 }
242 var c policyCheck
243 var failed []error
244 for _, name := range inst.projects {
245 if !q.selects(grants, name) {
246 continue
247 }
248 read, err := q.readableByAnyone(ctx, name, q.projectURL(name), grants)
249 if err != nil {
250 failed = append(failed, err)
251 if old, ok := prev.Project(name); ok && grants.Covers(readaccess.Anyone, name, old.Identity) {
252 p.warn("%s: could not read its policy; keeping the access from authorization %d, if the receiver still holds it", name, prev.Sequence)
253 c.projects = append(c.projects, export.AuthorizedProject{Name: name, Identity: old.Identity, Readers: []string{export.Anyone}})
254 c.kept = true
255 }
256 continue
257 }
258 if read.public {
259 c.projects = append(c.projects, export.AuthorizedProject{Name: name, Identity: read.consent.Identity, Readers: []string{export.Anyone}})
260 }
261 }
262 if len(failed) > 0 {
263 c.incomplete = fmt.Errorf("%w: %w", errIncomplete, errors.Join(failed...))
264 }
265 return c, nil
266}
267
268// lastAcknowledged is the authorization the receiver last said it stored,
269// or nil for none.
270func (p *publisher) lastAcknowledged() (*export.Authorization, error) {
271 data, err := os.ReadFile(filepath.Join(p.cfg.state, authorizationFile))
272 if errors.Is(err, os.ErrNotExist) {
273 return nil, nil
274 }
275 if err != nil {
276 return nil, err
277 }
278 a, err := export.ReadStoredAuthorization(data)
279 if err != nil {
280 p.warn("%s is not a valid authorization; ignoring it: %v", filepath.Join(p.cfg.state, authorizationFile), err)
281 return nil, nil
282 }
283 return a, nil
284}
285
286// nextSequence allocates an authorization's sequence: one more than the
287// greater of floor and the counter in the state directory, which it writes
288// durably before it returns. The counter reads no clock, so no clock
289// stepping back can make a later authorization's sequence smaller. A
290// counter that cannot be read fails, and is never taken for zero.
291func (p *publisher) nextSequence(floor int64) (int64, error) {
292 path := filepath.Join(p.cfg.state, authorizationSequenceFile)
293 var last int64
294 data, err := os.ReadFile(path)
295 switch {
296 case errors.Is(err, os.ErrNotExist):
297 case err != nil:
298 return 0, err
299 default:
300 last, err = strconv.ParseInt(strings.TrimSuffix(string(data), "\n"), 10, 64)
301 if err != nil || last < 0 {
302 return 0, fmt.Errorf("%s holds %q, which is not a valid sequence; restore it from a backup, or remove it so the receiver's reply can advance the sequence", path, data)
303 }
304 }
305 last = max(last, floor)
306 if last == math.MaxInt64 {
307 return 0, fmt.Errorf("authorization sequence %d has reached the maximum value", last)
308 }
309 next := last + 1
310 if err := writeDurable(path, []byte(strconv.FormatInt(next, 10)+"\n"), 0o600); err != nil {
311 return 0, err
312 }
313 return next, nil
314}
315
316// writeDurable is writeFile, with the directory synced after the rename,
317// so the file survives a crash once it returns.
318func writeDurable(path string, data []byte, mode os.FileMode) error {
319 return writeDurableGroup(path, data, mode, -1)
320}
321
322// writeDurableGroup is writeDurable, with the file's group set to gid
323// unless gid is -1.
324func writeDurableGroup(path string, data []byte, mode os.FileMode, gid int) error {
325 if err := writeFileGroup(path, data, mode, gid); err != nil {
326 return err
327 }
328 d, err := os.Open(filepath.Dir(path))
329 if err != nil {
330 return err
331 }
332 defer d.Close()
333 return syncFile(d)
334}
335
336// sendAuthorization posts the signed authorization, and retries, with the
337// same authorization, a request that failed in transit, that the receiver
338// answered with a status and no refusal, or that it refused as unreadable,
339// after a pause that doubles each time. A receiver that has no
340// authorization path is older than this publisher, and the error says so.
341func (p *publisher) sendAuthorization(ctx context.Context, a *export.Authorization, signed []byte) (*export.AuthorizationReply, error) {
342 rc := receiver{base: strings.TrimSuffix(p.cfg.receiver, "/"), token: p.token, client: p.client}
343 backoff := firstBackoff
344 for attempt := 1; ; attempt++ {
345 reply, err := rc.postAuthorization(ctx, signed)
346 if err == nil && reply.Sequence != a.Sequence {
347 err = fmt.Errorf("the receiver stored authorization %d, not %d", reply.Sequence, a.Sequence)
348 }
349 if err == nil {
350 return &reply, nil
351 }
352 if ctx.Err() != nil {
353 return nil, ctx.Err()
354 }
355 var status statusError
356 if errors.As(err, &status) && status.code == 404 {
357 return nil, fmt.Errorf("the receiver answered 404 to %s because its valley-web-receive is older than this publisher; upgrade the edge before the valley host", export.AuthorizationPath)
358 }
359 var refusal *export.Error
360 if errors.As(err, &refusal) && refusal.Code != export.CodeUnreadable {
361 return nil, fmt.Errorf("the receiver refused authorization %d: %w", a.Sequence, err)
362 }
363 if attempt == uploadAttempts {
364 return nil, fmt.Errorf("sending authorization %d failed %d times: %w", a.Sequence, attempt, err)
365 }
366 p.warn("%v; trying again", err)
367 if err := p.sleep(ctx, backoff); err != nil {
368 return nil, err
369 }
370 backoff *= 2
371 }
372}