gunk-dev/the-valley

policy.go

source9b67d021e86fmain's published tip history
21.3 KiB
1package main
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "math"
8 "os"
9 "path/filepath"
10 "slices"
11 "strconv"
12 "strings"
13 "time"
14
15 "the-valley/readaccess"
16 "the-valley/web/export"
17)
18
19// The policy path's state, beside what state.go lists:
20//
21// authorization.lock held while a policy check is read, its
22// sequence allocated and its authorization signed
23// authorization-sequence the greatest sequence an authorization was
24// signed with
25// authorization the last authorization the receiver said it
26// stored, as a signed note
27// links-delivery the greatest credential file revision signed
28// from, written under the links lock beside the
29// credential file, and the revision the last
30// stored authorization carried the links of
31// (link.go)
32const (
33 authorizationLockFile = "authorization.lock"
34 authorizationSequenceFile = "authorization-sequence"
35 authorizationFile = "authorization"
36)
37
38// authorizeAttempts is how many times the policy path signs the current
39// policy again when the receiver holds a newer authorization than this
40// publisher's counter.
41const authorizeAttempts = 3
42
43// errIncomplete is the error of a policy check that could not read every
44// project. Its authorization was still signed and sent.
45var errIncomplete = errors.New("the policy check is incomplete")
46
47// errOverflow is the error of a policy check whose authorization is too
48// large to sign in full. Its bounded fallback was signed and sent in its
49// place, and the access only the full one gives is pending.
50var errOverflow = errors.New("the authorization is too large to send")
51
52// authorize is the policy path: the only writer of authorizations. Under
53// the authorization lock it reads the policy, allocates the next sequence
54// from the durable counter, and signs the authorization. It then sends it
55// to the receiver, outside the lock. With --out it sends nothing, and the
56// signed authorization is written with the export.
57//
58// A receiver that holds a newer authorization refuses this one as
59// replayed, and one that holds another than its basis refuses it as
60// stale-basis. Either says the publisher's record of the receiver is out
61// of date, as after its state is restored from an older backup. The
62// policy path then checks the policy again, signs the current result above
63// the receiver's sequence, and keeps no access it could not check: it
64// knows nothing it can trust of what the receiver serves. It never sends
65// an authorization it signed earlier.
66//
67// Once the receiver stores an authorization, it is recorded as the last
68// one acknowledged, which the next incomplete check may keep access from.
69//
70// Growth never blocks a restriction. A check whose authorization would be
71// larger than the limit, less export.FallbackRoom, signs and sends its
72// bounded fallback instead (fallBack): the last authorization the
73// receiver acknowledged, less every access this check no longer gives,
74// and restricted further when that is over the limit too, so every
75// withdrawal and revocation still reaches the edge.
76//
77// The reply is nil with --out. An incomplete check is sent, and authorize
78// then returns an error that wraps errIncomplete. So is a fallback, with
79// an error that wraps errOverflow, and an authorization signed with no
80// bindings because the links lock could not be taken or the credential
81// file could not be read, with that error. A send that fails returns its
82// error joined with those. Every attempt that signs a fallback prints what
83// is pending and what the fallback dropped, whether or not it was sent or
84// stored. When the receiver refuses a fallback and the policy path tries
85// again, that fallback's overflow is joined into every failure a later
86// attempt returns, a check that cannot be read included, so the pass's
87// error still names the access it left pending and dropped.
88func (p *publisher) authorize(ctx context.Context) (*export.AuthorizationReply, error) {
89 var floor int64
90 trusted := true
91 // refused is the overflow of each fallback the receiver refused.
92 var refused []error
93 carry := func(err error) error {
94 if err == nil {
95 return nil
96 }
97 return errors.Join(append([]error{err}, refused...)...)
98 }
99 for attempt := 1; ; attempt++ {
100 c, err := p.signPolicy(ctx, floor, trusted)
101 if err != nil {
102 return nil, carry(err)
103 }
104 a := c.authorization
105 failed := errors.Join(c.incomplete, c.overflow, c.links.err)
106 if p.cfg.out != "" {
107 p.signedAuthorization = c.signed
108 p.sayOverflow(c)
109 return nil, failed
110 }
111 reply, err := p.sendAuthorization(ctx, a, c.signed)
112 var refusal *export.Error
113 if errors.As(err, &refusal) && (refusal.Code == export.CodeReplayed || refusal.Code == export.CodeStaleBasis) && attempt < authorizeAttempts {
114 p.sayOverflow(c)
115 if c.overflow != nil {
116 refused = append(refused, fmt.Errorf("the receiver refused authorization %d as %s: %w", a.Sequence, refusal.Code, c.overflow))
117 }
118 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",
119 refusal.HighWater, a.Sequence, refusal.Code, refusal.HighWater)
120 floor, trusted = refusal.HighWater, false
121 continue
122 }
123 if err != nil {
124 p.sayOverflow(c)
125 return nil, carry(errors.Join(err, failed))
126 }
127 if err := p.recordAuthorization(a, c.signed, c.revision); err != nil {
128 p.sayOverflow(c)
129 return nil, carry(errors.Join(err, failed))
130 }
131 p.say("the receiver stored authorization %d: %s", a.Sequence, describe(a))
132 p.sayOverflow(c)
133 return reply, carry(failed)
134 }
135}
136
137// sayOverflow prints, when the check signed its bounded fallback, the
138// access that is pending and, when the fallback was itself over the
139// limit, the access it dropped to fit.
140func (p *publisher) sayOverflow(c policyCheck) {
141 if c.overflow == nil {
142 return
143 }
144 p.say("pending: %s", c.pending)
145 if c.dropped != "" {
146 p.say("dropped: %s", c.dropped)
147 }
148}
149
150// recordAuthorization records an authorization the receiver said it
151// stored, and the credential file revision it carried the read links of,
152// under the authorization lock, unless a greater one is recorded already.
153func (p *publisher) recordAuthorization(a *export.Authorization, signed []byte, revision int64) error {
154 unlock, err := lockFile(filepath.Join(p.cfg.state, authorizationLockFile))
155 if err != nil {
156 return err
157 }
158 defer unlock()
159 last, err := p.lastAcknowledged()
160 if err != nil {
161 return err
162 }
163 if last != nil && last.Sequence >= a.Sequence {
164 return nil
165 }
166 if err := writeDurable(filepath.Join(p.cfg.state, authorizationFile), signed, 0o600); err != nil {
167 return err
168 }
169 return p.recordDelivery(a, revision)
170}
171
172// describe is who an authorization lets read each project, for messages:
173// "app to anyone, operator; site to alice".
174func describe(a *export.Authorization) string {
175 var each []string
176 for _, proj := range a.Projects {
177 each = append(each, proj.Name+" to "+strings.Join(proj.Readers, ", "))
178 }
179 s := "no project may be read"
180 if len(each) > 0 {
181 s = strings.Join(each, "; ")
182 }
183 if len(a.Bindings) > 0 {
184 s += fmt.Sprintf("; %d read links", len(a.Bindings))
185 }
186 return s
187}
188
189// policyCheck is what one check of the policy found: the projects it
190// authorizes, and, when some project's policy could not be read, an error
191// that wraps errIncomplete. A signed check also has its authorization and
192// the signed note.
193type policyCheck struct {
194 projects []export.AuthorizedProject
195 incomplete error
196 // kept names the projects whose policy the check could not read, and
197 // that keep access on the authorization's basis.
198 kept []string
199 // links is what the check read of the read links.
200 links linkRead
201 // overflow, which wraps errOverflow, is set when the authorization is
202 // the bounded fallback. pending then says what access the full one
203 // gives and the fallback, narrowed from the last acknowledged one,
204 // does not. dropped, when that fallback was over the limit too, says
205 // what access the restriction to fit took from it.
206 overflow error
207 pending string
208 dropped string
209 authorization *export.Authorization
210 signed []byte
211 // revision is the credential file revision the authorization carries
212 // the links of, or 0 for none read from the file.
213 revision int64
214}
215
216// signPolicy reads the policy and signs an authorization for it, holding
217// the authorization lock throughout, so of two authorizations the one with
218// the greater sequence always reflects the later check. The sequence is
219// greater than floor and than every sequence signed before. When trusted
220// is set, a project whose policy cannot be read may keep the access the
221// last acknowledged authorization gave it, and the authorization then
222// names that one as its basis. The read links are read last, after the
223// check, under the links lock, which is held until the authorization is
224// signed, and every authorization it signs carries them, one that keeps
225// access included. Every change to the credential file holds the links
226// lock, so none lands between that read and the signature. The lock order
227// is the authorization lock, then the links lock.
228func (p *publisher) signPolicy(ctx context.Context, floor int64, trusted bool) (policyCheck, error) {
229 unlock, err := lockFile(filepath.Join(p.cfg.state, authorizationLockFile))
230 if err != nil {
231 return policyCheck{}, err
232 }
233 defer unlock()
234 if p.key, err = p.loadKey(); err != nil {
235 return policyCheck{}, err
236 }
237 prev, err := p.lastAcknowledged()
238 if err != nil {
239 return policyCheck{}, err
240 }
241 keepFrom := prev
242 if !trusted {
243 keepFrom = nil
244 }
245 c, err := p.checkPolicy(ctx, keepFrom)
246 if err != nil {
247 return policyCheck{}, err
248 }
249 // A check that did not read every project leaves the time of the last
250 // one that did, or the epoch when none has.
251 checked := time.Unix(0, 0).UTC()
252 switch {
253 case c.incomplete == nil:
254 checked = p.now().UTC().Truncate(time.Second)
255 case prev != nil:
256 checked = prev.Checked
257 }
258 seq, err := p.nextSequence(floor)
259 if err != nil {
260 return policyCheck{}, err
261 }
262 c.authorization = &export.Authorization{Instance: p.cfg.instance, Destination: p.cfg.destination,
263 Sequence: seq, Checked: checked, Projects: c.projects}
264 if len(c.kept) > 0 {
265 c.authorization.Basis = keepFrom.Sequence
266 }
267 unlockLinks, links := p.readBindings()
268 c.links, c.revision = links, links.revision
269 c.authorization.Bindings = c.links.bindings
270 if size := c.authorization.SignedSize(p.signer); size > p.limit-export.FallbackRoom {
271 p.fallBack(&c, prev, size)
272 }
273 c.signed, err = c.authorization.Sign(p.signer, p.key)
274 unlockLinks()
275 if err != nil {
276 return policyCheck{}, err
277 }
278 return c, nil
279}
280
281// fallBack puts in place of the check's authorization, which would be
282// size bytes signed, its bounded fallback: prev, the authorization the
283// receiver last said it stored, less every access the check no longer
284// gives (export.Narrow). It keeps the authorization's sequence, which
285// nothing was signed with, its checked time and its basis, so the
286// receiver admits it as it would the full one, and what it keeps of prev
287// is within what the check gives.
288//
289// The fallback is measured, never assumed to fit. One narrowed from an
290// authorization this publisher signed in full fits, as that left
291// export.FallbackRoom. One narrowed from an authorization the receiver
292// admitted without that room, whose sequence has grown a digit or that
293// adds a basis, can be over the limit. It is then restricted further
294// until it fits (export.Fit): first the projects kept on the basis, then
295// readers, the largest project first, then read links, and at last it
296// grants nothing. Every step only removes access, so the restriction is
297// always safe, and the access it drops is reported beside what is
298// pending.
299//
300// The fallback carries only the read links prev and the check both carry.
301// Its delivery is recorded as the revision prev carried the links of, so a
302// link issued since stays pending; a revocation since is recorded pending
303// too, though the fallback delivers it. A fallback that drops a read link
304// to fit is recorded as carrying none from the file, so every link is
305// pending until an authorization fits.
306func (p *publisher) fallBack(c *policyCheck, prev *export.Authorization, size int) {
307 full := c.authorization
308 narrowed := export.Narrow(prev, full)
309 c.authorization = export.Fit(narrowed, c.kept, p.signer, p.limit)
310 c.revision = 0
311 if d := c.links.delivered; prev != nil && c.links.err == nil && d.Sequence == prev.Sequence &&
312 len(c.authorization.Bindings) == len(narrowed.Bindings) {
313 c.revision = min(d.Revision, c.links.revision)
314 }
315 c.pending = withheld(full, narrowed)
316 from := "no authorization, as the receiver has acknowledged none"
317 if prev != nil {
318 from = fmt.Sprintf("authorization %d, the last the receiver acknowledged", prev.Sequence)
319 }
320 msg := fmt.Sprintf("authorization %d would be %d bytes signed, more than the %d a pass signs in full: a receiver reads at most %d, and a pass leaves %d of room; "+
321 "its bounded fallback was signed in its place, from %s, less every access this check no longer gives, adding none",
322 full.Sequence, size, p.limit-export.FallbackRoom, p.limit, export.FallbackRoom, from)
323 if c.authorization != narrowed {
324 c.dropped = withheld(narrowed, c.authorization)
325 msg += fmt.Sprintf("; that fallback would be %d bytes signed, over the %d a receiver reads too, so to fit it also drops %s",
326 narrowed.SignedSize(p.signer), p.limit, c.dropped)
327 }
328 c.overflow = fmt.Errorf("%w: %s; pending until an authorization fits: %s", errOverflow, msg, c.pending)
329}
330
331// withheld is what full gives and sent does not, for messages: "app to
332// bob; site to 1200 readers; 3 read links".
333func withheld(full, sent *export.Authorization) string {
334 var each []string
335 for _, proj := range full.Projects {
336 var readers []string
337 for _, r := range proj.Readers {
338 if !sent.Allows(r, proj.Name, proj.Identity) {
339 readers = append(readers, r)
340 }
341 }
342 switch {
343 case len(readers) == 0:
344 case len(readers) > 4:
345 each = append(each, fmt.Sprintf("%s to %d readers", proj.Name, len(readers)))
346 default:
347 each = append(each, proj.Name+" to "+strings.Join(readers, ", "))
348 }
349 }
350 links := 0
351 for _, b := range full.Bindings {
352 if !slices.Contains(sent.Bindings, b) {
353 links++
354 }
355 }
356 if links > 0 {
357 each = append(each, fmt.Sprintf("%d read links", links))
358 }
359 if len(each) == 0 {
360 return "no access"
361 }
362 return strings.Join(each, "; ")
363}
364
365// checkPolicy reads who may read each project at the destination: the
366// instance's read grants, and each selected project's own policy/read. It
367// reads no plan, no knot and no listing of the CLI, so no project's graph
368// can fail it. It reads into caches of its own, under policy/ in the
369// publisher's cache, so a content pass running beside it is not disturbed.
370//
371// A project is authorized when a pass would export it: the host
372// declaration places it in a group, and it has an effective reader, a
373// principal its policy/read names and a read grant covers. The
374// authorization names each of its effective readers, anyone among them
375// only when both consents let anyone read it. A project whose policy
376// cannot be read keeps those of the readers prev gave it that the grants
377// still cover, under prev's publication identity, and never another; the
378// check is then incomplete. prev is the authorization the receiver last
379// said it stored, or nil when that is not known, and then nothing is
380// kept. An instance or registry that cannot be read fails the check, and
381// nothing is signed.
382func (p *publisher) checkPolicy(ctx context.Context, prev *export.Authorization) (policyCheck, error) {
383 q := *p
384 q.origin = filepath.Join(p.cache, "policy", "origin.git")
385 q.mirrors = filepath.Join(p.cache, "policy", "repos")
386 if err := q.access.CheckSchemas(ctx); err != nil {
387 return policyCheck{}, err
388 }
389 inst, err := q.fetchInstance(ctx)
390 if err != nil {
391 return policyCheck{}, err
392 }
393 grants, err := q.readGrants(ctx, inst)
394 if err != nil {
395 return policyCheck{}, err
396 }
397 var c policyCheck
398 var failed []error
399 for _, name := range inst.projects {
400 if !q.selects(grants, name) {
401 continue
402 }
403 read, err := q.readConsent(ctx, name, q.projectURL(name), grants)
404 if err != nil {
405 failed = append(failed, err)
406 if kept, ok := stillCovered(prev, grants, name); ok {
407 p.warn("%s: could not read its policy; keeping the access authorization %d gave %s, if the receiver still holds it",
408 name, prev.Sequence, strings.Join(kept.Readers, ", "))
409 c.projects = append(c.projects, kept)
410 c.kept = append(c.kept, name)
411 }
412 continue
413 }
414 if len(read.readers) > 0 {
415 c.projects = append(c.projects, export.AuthorizedProject{Name: name, Identity: read.consent.Identity, Readers: read.readers})
416 }
417 }
418 if len(failed) > 0 {
419 c.incomplete = fmt.Errorf("%w: %w", errIncomplete, errors.Join(failed...))
420 }
421 return c, nil
422}
423
424// stillCovered is what prev authorized of the project that the grants
425// still cover: the project under prev's publication identity, with those
426// of prev's readers a grant covers it for. It is false when prev does not
427// name the project, or the grants cover none of its readers.
428func stillCovered(prev *export.Authorization, grants readaccess.Grants, name string) (export.AuthorizedProject, bool) {
429 old, ok := prev.Project(name)
430 if !ok {
431 return export.AuthorizedProject{}, false
432 }
433 kept := export.AuthorizedProject{Name: name, Identity: old.Identity}
434 for _, r := range old.Readers {
435 if grants.Covers(r, name, old.Identity) {
436 kept.Readers = append(kept.Readers, r)
437 }
438 }
439 return kept, len(kept.Readers) > 0
440}
441
442// lastAcknowledged is the authorization the receiver last said it stored,
443// or nil for none.
444func (p *publisher) lastAcknowledged() (*export.Authorization, error) {
445 data, err := os.ReadFile(filepath.Join(p.cfg.state, authorizationFile))
446 if errors.Is(err, os.ErrNotExist) {
447 return nil, nil
448 }
449 if err != nil {
450 return nil, err
451 }
452 a, err := export.ReadStoredAuthorization(data)
453 if err != nil {
454 p.warn("%s is not a valid authorization; ignoring it: %v", filepath.Join(p.cfg.state, authorizationFile), err)
455 return nil, nil
456 }
457 return a, nil
458}
459
460// nextSequence allocates an authorization's sequence: one more than the
461// greater of floor and the counter in the state directory, which it writes
462// durably before it returns. The counter reads no clock, so no clock
463// stepping back can make a later authorization's sequence smaller. A
464// counter that cannot be read fails, and is never taken for zero.
465func (p *publisher) nextSequence(floor int64) (int64, error) {
466 path := filepath.Join(p.cfg.state, authorizationSequenceFile)
467 var last int64
468 data, err := os.ReadFile(path)
469 switch {
470 case errors.Is(err, os.ErrNotExist):
471 case err != nil:
472 return 0, err
473 default:
474 last, err = strconv.ParseInt(strings.TrimSuffix(string(data), "\n"), 10, 64)
475 if err != nil || last < 0 {
476 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)
477 }
478 }
479 last = max(last, floor)
480 if last == math.MaxInt64 {
481 return 0, fmt.Errorf("authorization sequence %d has reached the maximum value", last)
482 }
483 next := last + 1
484 if err := writeDurable(path, []byte(strconv.FormatInt(next, 10)+"\n"), 0o600); err != nil {
485 return 0, err
486 }
487 return next, nil
488}
489
490// writeDurable is writeFile, with the directory synced after the rename,
491// so the file survives a crash once it returns.
492func writeDurable(path string, data []byte, mode os.FileMode) error {
493 return writeDurableGroup(path, data, mode, -1)
494}
495
496// writeDurableGroup is writeDurable, with the file's group set to gid
497// unless gid is -1.
498func writeDurableGroup(path string, data []byte, mode os.FileMode, gid int) error {
499 if err := writeFileGroup(path, data, mode, gid); err != nil {
500 return err
501 }
502 d, err := os.Open(filepath.Dir(path))
503 if err != nil {
504 return err
505 }
506 defer d.Close()
507 return syncFile(d)
508}
509
510// sendAuthorization posts the signed authorization, and retries, with the
511// same authorization, a request that failed in transit, that the receiver
512// answered with a status and no refusal, or that it refused as unreadable,
513// after a pause that doubles each time. A receiver that has no
514// authorization path is older than this publisher, and the error says so.
515func (p *publisher) sendAuthorization(ctx context.Context, a *export.Authorization, signed []byte) (*export.AuthorizationReply, error) {
516 rc := receiver{base: strings.TrimSuffix(p.cfg.receiver, "/"), token: p.token, client: p.client}
517 backoff := firstBackoff
518 for attempt := 1; ; attempt++ {
519 reply, err := rc.postAuthorization(ctx, signed)
520 if err == nil && reply.Sequence != a.Sequence {
521 err = fmt.Errorf("the receiver stored authorization %d, not %d", reply.Sequence, a.Sequence)
522 }
523 if err == nil {
524 return &reply, nil
525 }
526 if ctx.Err() != nil {
527 return nil, ctx.Err()
528 }
529 var status statusError
530 if errors.As(err, &status) && status.code == 404 {
531 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)
532 }
533 var refusal *export.Error
534 if errors.As(err, &refusal) && refusal.Code != export.CodeUnreadable {
535 return nil, fmt.Errorf("the receiver refused authorization %d: %w", a.Sequence, err)
536 }
537 if attempt == uploadAttempts {
538 return nil, fmt.Errorf("sending authorization %d failed %d times: %w", a.Sequence, attempt, err)
539 }
540 p.warn("%v; trying again", err)
541 if err := p.sleep(ctx, backoff); err != nil {
542 return nil, err
543 }
544 backoff *= 2
545 }
546}