gunk-dev/the-valley

policy.go

sourceed42f27353e2main's published tip history
10.6 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 signed, as a signed note
25const (
26 authorizationLockFile = "authorization.lock"
27 authorizationSequenceFile = "authorization-sequence"
28 authorizationFile = "authorization"
29)
30
31// authorizeAttempts is how many times the policy path signs the current
32// policy again when the receiver holds a newer authorization than this
33// publisher's counter.
34const authorizeAttempts = 3
35
36// errIncomplete is the error of a policy check that could not read every
37// project. Its authorization was still signed and sent.
38var errIncomplete = errors.New("the policy check is incomplete")
39
40// authorize is the policy path: the only writer of authorizations. Under
41// the authorization lock it reads the policy, allocates the next sequence
42// from the durable counter, and signs the authorization. It then sends it
43// to the receiver, outside the lock. With --out it sends nothing, and the
44// signed authorization is written with the export.
45//
46// A receiver that holds a newer authorization refuses this one as
47// replayed. The policy path then checks the policy again, and signs the
48// current result above the receiver's sequence. It never sends an
49// authorization it signed earlier.
50//
51// The reply is nil with --out. An incomplete check is sent, and authorize
52// then returns an error that wraps errIncomplete.
53func (p *publisher) authorize(ctx context.Context) (*export.AuthorizationReply, error) {
54 var floor int64
55 for attempt := 1; ; attempt++ {
56 c, err := p.signPolicy(ctx, floor)
57 if err != nil {
58 return nil, err
59 }
60 a := c.authorization
61 if p.cfg.out != "" {
62 p.signedAuthorization = c.signed
63 return nil, c.incomplete
64 }
65 reply, err := p.sendAuthorization(ctx, a, c.signed)
66 var refusal *export.Error
67 if errors.As(err, &refusal) && refusal.Code == export.CodeReplayed && attempt < authorizeAttempts {
68 p.warn("the receiver already holds authorization %d (this pass signed %d); rechecking the policy and signing above %d", refusal.HighWater, a.Sequence, refusal.HighWater)
69 floor = refusal.HighWater
70 continue
71 }
72 if err != nil {
73 return nil, err
74 }
75 p.say("the receiver stored authorization %d: %s", a.Sequence, describe(a))
76 return reply, c.incomplete
77 }
78}
79
80// describe is what an authorization lets anyone read, for messages.
81func describe(a *export.Authorization) string {
82 var names []string
83 for _, proj := range a.Projects {
84 names = append(names, proj.Name)
85 }
86 return "anyone may read " + listNames(names)
87}
88
89// policyCheck is what one check of the policy found: the projects it
90// authorizes, and, when some project's policy could not be read, an error
91// that wraps errIncomplete. A signed check also has its authorization and
92// the signed note.
93type policyCheck struct {
94 projects []export.AuthorizedProject
95 incomplete error
96 authorization *export.Authorization
97 signed []byte
98}
99
100// signPolicy reads the policy and signs an authorization for it, holding
101// the authorization lock throughout, so of two authorizations the one with
102// the greater sequence always reflects the later check. The sequence is
103// greater than floor and than every sequence signed before.
104func (p *publisher) signPolicy(ctx context.Context, floor int64) (policyCheck, error) {
105 unlock, err := lockFile(filepath.Join(p.cfg.state, authorizationLockFile))
106 if err != nil {
107 return policyCheck{}, err
108 }
109 defer unlock()
110 if p.key, err = p.loadKey(); err != nil {
111 return policyCheck{}, err
112 }
113 prev, err := p.lastAuthorization()
114 if err != nil {
115 return policyCheck{}, err
116 }
117 c, err := p.checkPolicy(ctx, prev)
118 if err != nil {
119 return policyCheck{}, err
120 }
121 // A check that did not read every project leaves the time of the last
122 // one that did, or the epoch when none has.
123 checked := time.Unix(0, 0).UTC()
124 switch {
125 case c.incomplete == nil:
126 checked = p.now().UTC().Truncate(time.Second)
127 case prev != nil:
128 checked = prev.Checked
129 }
130 seq, err := p.nextSequence(floor)
131 if err != nil {
132 return policyCheck{}, err
133 }
134 c.authorization = &export.Authorization{Instance: p.cfg.instance, Destination: p.cfg.destination,
135 Sequence: seq, Checked: checked, Projects: c.projects}
136 if c.signed, err = c.authorization.Sign(p.signer, p.key); err != nil {
137 return policyCheck{}, err
138 }
139 if err := writeDurable(filepath.Join(p.cfg.state, authorizationFile), c.signed, 0o600); err != nil {
140 return policyCheck{}, err
141 }
142 return c, nil
143}
144
145// checkPolicy reads who may read each project at the destination: the
146// instance's read grants, and each selected project's own policy/read. It
147// reads no plan, no knot and no listing of the CLI, so no project's graph
148// can fail it. It reads into caches of its own, under policy/ in the
149// publisher's cache, so a content pass running beside it is not disturbed.
150//
151// A project is authorized for anyone when a pass would publish it: a read
152// grant to anyone covers it, the host declaration places it in a group,
153// and its policy/read lets anyone read it. A project whose policy cannot
154// be read keeps what the previous authorization gave it, as long as the
155// grants still cover it, and never more; the check is then incomplete. An
156// instance or registry that cannot be read fails the check, and nothing is
157// signed.
158func (p *publisher) checkPolicy(ctx context.Context, prev *export.Authorization) (policyCheck, error) {
159 q := *p
160 q.origin = filepath.Join(p.cache, "policy", "origin.git")
161 q.mirrors = filepath.Join(p.cache, "policy", "repos")
162 if err := q.access.CheckSchemas(ctx); err != nil {
163 return policyCheck{}, err
164 }
165 inst, err := q.fetchInstance(ctx)
166 if err != nil {
167 return policyCheck{}, err
168 }
169 grants, err := q.readGrants(ctx, inst)
170 if err != nil {
171 return policyCheck{}, err
172 }
173 var c policyCheck
174 var failed []error
175 for _, name := range inst.projects {
176 if !q.selects(grants, name) {
177 continue
178 }
179 read, err := q.readableByAnyone(ctx, name, q.projectURL(name), grants)
180 if err != nil {
181 failed = append(failed, err)
182 if old, ok := prev.Project(name); ok && grants.Covers(readaccess.Anyone, name, old.Identity) {
183 p.warn("%s: could not read its policy; keeping the access from authorization %d", name, prev.Sequence)
184 c.projects = append(c.projects, export.AuthorizedProject{Name: name, Identity: old.Identity, Readers: []string{export.Anyone}})
185 }
186 continue
187 }
188 if read.public {
189 c.projects = append(c.projects, export.AuthorizedProject{Name: name, Identity: read.consent.Identity, Readers: []string{export.Anyone}})
190 }
191 }
192 if len(failed) > 0 {
193 c.incomplete = fmt.Errorf("%w: %w", errIncomplete, errors.Join(failed...))
194 }
195 return c, nil
196}
197
198// lastAuthorization is the authorization the policy path signed last, or
199// nil for none.
200func (p *publisher) lastAuthorization() (*export.Authorization, error) {
201 data, err := os.ReadFile(filepath.Join(p.cfg.state, authorizationFile))
202 if errors.Is(err, os.ErrNotExist) {
203 return nil, nil
204 }
205 if err != nil {
206 return nil, err
207 }
208 a, err := export.ReadStoredAuthorization(data)
209 if err != nil {
210 p.warn("%s is not a valid authorization; ignoring it: %v", filepath.Join(p.cfg.state, authorizationFile), err)
211 return nil, nil
212 }
213 return a, nil
214}
215
216// nextSequence allocates an authorization's sequence: one more than the
217// greater of floor and the counter in the state directory, which it writes
218// durably before it returns. The counter reads no clock, so no clock
219// stepping back can make a later authorization's sequence smaller. A
220// counter that cannot be read fails, and is never taken for zero.
221func (p *publisher) nextSequence(floor int64) (int64, error) {
222 path := filepath.Join(p.cfg.state, authorizationSequenceFile)
223 var last int64
224 data, err := os.ReadFile(path)
225 switch {
226 case errors.Is(err, os.ErrNotExist):
227 case err != nil:
228 return 0, err
229 default:
230 last, err = strconv.ParseInt(strings.TrimSuffix(string(data), "\n"), 10, 64)
231 if err != nil || last < 0 {
232 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)
233 }
234 }
235 last = max(last, floor)
236 if last == math.MaxInt64 {
237 return 0, fmt.Errorf("authorization sequence %d has reached the maximum value", last)
238 }
239 next := last + 1
240 if err := writeDurable(path, []byte(strconv.FormatInt(next, 10)+"\n"), 0o600); err != nil {
241 return 0, err
242 }
243 return next, nil
244}
245
246// writeDurable is writeFile, with the directory synced after the rename,
247// so the file survives a crash once it returns.
248func writeDurable(path string, data []byte, mode os.FileMode) error {
249 if err := writeFile(path, data, mode); err != nil {
250 return err
251 }
252 d, err := os.Open(filepath.Dir(path))
253 if err != nil {
254 return err
255 }
256 defer d.Close()
257 return d.Sync()
258}
259
260// sendAuthorization posts the signed authorization, and retries, with the
261// same authorization, a request that failed in transit, that the receiver
262// answered with a status and no refusal, or that it refused as unreadable,
263// after a pause that doubles each time. A receiver that has no
264// authorization path is older than this publisher, and the error says so.
265func (p *publisher) sendAuthorization(ctx context.Context, a *export.Authorization, signed []byte) (*export.AuthorizationReply, error) {
266 rc := receiver{base: strings.TrimSuffix(p.cfg.receiver, "/"), token: p.token, client: p.client}
267 backoff := firstBackoff
268 for attempt := 1; ; attempt++ {
269 reply, err := rc.postAuthorization(ctx, signed)
270 if err == nil && reply.Sequence != a.Sequence {
271 err = fmt.Errorf("the receiver stored authorization %d, not %d", reply.Sequence, a.Sequence)
272 }
273 if err == nil {
274 return &reply, nil
275 }
276 if ctx.Err() != nil {
277 return nil, ctx.Err()
278 }
279 var status statusError
280 if errors.As(err, &status) && status.code == 404 {
281 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)
282 }
283 var refusal *export.Error
284 if errors.As(err, &refusal) && refusal.Code != export.CodeUnreadable {
285 return nil, fmt.Errorf("the receiver refused authorization %d: %w", a.Sequence, err)
286 }
287 if attempt == uploadAttempts {
288 return nil, fmt.Errorf("sending authorization %d failed %d times: %w", a.Sequence, attempt, err)
289 }
290 p.warn("%v; trying again", err)
291 if err := p.sleep(ctx, backoff); err != nil {
292 return nil, err
293 }
294 backoff *= 2
295 }
296}