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