| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "flag" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "os" |
| 15 | "path/filepath" |
| 16 | "slices" |
| 17 | "strings" |
| 18 | "syscall" |
| 19 | "text/tabwriter" |
| 20 | "time" |
| 21 | "unicode" |
| 22 | "unicode/utf8" |
| 23 | |
| 24 | "the-valley/exactjson" |
| 25 | "the-valley/readaccess" |
| 26 | "the-valley/web/export" |
| 27 | "the-valley/web/nodump" |
| 28 | ) |
| 29 | |
| 30 | const linkUsage = `usage: valley-web-publish link issue --principal NAME [--note TEXT] FLAGS |
| 31 | valley-web-publish link list [--check] [CREDENTIAL_ID...] FLAGS |
| 32 | valley-web-publish link revoke (CREDENTIAL_ID | --principal NAME | --all) FLAGS |
| 33 | valley-web-publish link prune FLAGS |
| 34 | |
| 35 | Issue, list and revoke read links: bearer credentials, each bound to one |
| 36 | registry principal, that let their holder read what that principal may |
| 37 | read at the destination, and nothing more. The host keeps each link's |
| 38 | verifier in the credential file and never its secret. Each policy pass |
| 39 | reads the file as it signs, and carries the active links to the edge in |
| 40 | the authorization. issue, revoke and prune hold the links lock, the file |
| 41 | lock in the credential file's directory, while they read and write the |
| 42 | file; a pass holds it from its read of the file until it has signed. So |
| 43 | a change waits for a pass that is signing, and a pass for a change, each |
| 44 | for at most a minute; a change then fails having changed nothing. The |
| 45 | lock must be a regular file owned by root, or by the user who runs the |
| 46 | command, and is made when it is missing. |
| 47 | |
| 48 | issue make a link for the principal, and print it once on |
| 49 | stdout: https://DESTINATION/-/redeem#ID.SECRET; refused |
| 50 | unless the principal may read at least one project at |
| 51 | the destination, by the registry and the projects' |
| 52 | policy/read, as a policy pass reads them; refused too |
| 53 | when the file would come within 64 KiB of the 1 MiB it |
| 54 | may hold: prune it first |
| 55 | list show each link's ID, principal, state (active or |
| 56 | revoked), delivery, issue time and note; delivery is |
| 57 | enforced once the receiver acknowledged an authorization |
| 58 | signed from the credential file's revision that set the |
| 59 | link's state, or a later one, and pending before; it is |
| 60 | read from the publisher's state, never from the edge, |
| 61 | and says nothing of whether a link was redeemed |
| 62 | revoke revoke one link, every link of a principal, or every |
| 63 | link, for good; revoked IDs stay in the file until |
| 64 | prune removes them; a revoke is never refused for the |
| 65 | file's size |
| 66 | prune remove from the file every revoked link whose |
| 67 | revocation is enforced; the edge accepts only a link an |
| 68 | authorization binds, so a link absent from the file is |
| 69 | as revoked as one recorded revoked |
| 70 | |
| 71 | FLAGS: |
| 72 | --links FILE the credential file (required), not named lock |
| 73 | --state DIR the publisher's state directory, whose delivery |
| 74 | record every verb reads (default as a pass) |
| 75 | --principal NAME issue: the principal the link identifies; revoke: |
| 76 | revoke every link of the principal |
| 77 | --note TEXT issue: a label list shows, at most 100 characters |
| 78 | and no control characters |
| 79 | --all revoke: revoke every link |
| 80 | --check list: exit 1, and say why, when a link shown is |
| 81 | pending |
| 82 | --instance-repo, --destination, --host, --read-schema, |
| 83 | --identity-schema, --registry-ref, --registry-dir |
| 84 | issue alone: as for a pass; issue needs |
| 85 | --instance-repo, --destination and --host` |
| 86 | |
| 87 | // The credential file's limits. Reads and writes hold it to maxLinksFile |
| 88 | // bytes. Issue refuses to write it larger than maxLinksFile less |
| 89 | // linksHeadroom, which always fits a revocation of every active link: each |
| 90 | // adds a revoked time, at most 41 bytes with its indentation, and at most |
| 91 | // 18 more digits to its changed revision, so 1,000 links add at most |
| 92 | // 59,018 bytes with the file's own revision. |
| 93 | const ( |
| 94 | maxNote = 100 |
| 95 | maxLinksFile = 1 << 20 |
| 96 | linksHeadroom = 64 << 10 |
| 97 | ) |
| 98 | |
| 99 | // linksFile is the credential file: one record per read link the host |
| 100 | // issued, revoked ones included, and the file's revision. Each change |
| 101 | // writes a revision greater than the file's and than every revision a |
| 102 | // pass signed from, so the revision only moves forward. The file never |
| 103 | // holds a secret. A missing or empty file holds no links, at revision 0. |
| 104 | type linksFile struct { |
| 105 | Revision int64 `json:"revision"` |
| 106 | Links []linkRecord `json:"links"` |
| 107 | } |
| 108 | |
| 109 | // linkRecord is one read link. Revoked is "" while it is active. Changed |
| 110 | // is the revision of the credential file that set the link's current |
| 111 | // state: the one its issue wrote, or its revocation. |
| 112 | type linkRecord struct { |
| 113 | ID string `json:"id"` |
| 114 | Principal string `json:"principal"` |
| 115 | Note string `json:"note"` |
| 116 | Verifier string `json:"verifier"` |
| 117 | Issued string `json:"issued"` |
| 118 | Revoked string `json:"revoked,omitempty"` |
| 119 | Changed int64 `json:"changed"` |
| 120 | } |
| 121 | |
| 122 | // readLinks reads the credential file. A missing or empty file holds no |
| 123 | // links. Anything else that is not a valid credential file is an error: |
| 124 | // unknown or misspelled keys, a repeated ID, a malformed field, or more |
| 125 | // active links than an authorization carries. |
| 126 | func readLinks(path string) (linksFile, error) { |
| 127 | var f linksFile |
| 128 | file, err := os.Open(path) |
| 129 | if errors.Is(err, os.ErrNotExist) { |
| 130 | return f, nil |
| 131 | } |
| 132 | if err != nil { |
| 133 | return f, err |
| 134 | } |
| 135 | defer file.Close() |
| 136 | data, err := io.ReadAll(io.LimitReader(file, maxLinksFile+1)) |
| 137 | if err != nil { |
| 138 | return f, err |
| 139 | } |
| 140 | if len(data) == 0 { |
| 141 | return f, nil |
| 142 | } |
| 143 | if len(data) > maxLinksFile { |
| 144 | return f, fmt.Errorf("%s is larger than %d bytes", path, maxLinksFile) |
| 145 | } |
| 146 | if err := exactjson.Decode(data, &f); err != nil { |
| 147 | return f, fmt.Errorf("%s is not a credential file: %w", path, err) |
| 148 | } |
| 149 | if err := f.check(); err != nil { |
| 150 | return f, fmt.Errorf("%s is not a valid credential file: %w", path, err) |
| 151 | } |
| 152 | return f, nil |
| 153 | } |
| 154 | |
| 155 | func (f *linksFile) check() error { |
| 156 | if f.Revision < 0 { |
| 157 | return fmt.Errorf("its revision %d is negative", f.Revision) |
| 158 | } |
| 159 | seen := map[string]bool{} |
| 160 | active := 0 |
| 161 | for i, l := range f.Links { |
| 162 | switch { |
| 163 | case !export.ValidLinkID(l.ID): |
| 164 | return fmt.Errorf("link %d has the ID %q, which is not lk- and 16 lowercase hex digits", i, l.ID) |
| 165 | case seen[l.ID]: |
| 166 | return fmt.Errorf("the ID %s is in it twice", l.ID) |
| 167 | case !export.ValidName(l.Principal) || l.Principal == readaccess.Anyone: |
| 168 | return fmt.Errorf("%s names %q, which is not a principal", l.ID, l.Principal) |
| 169 | case checkNote(l.Note) != nil: |
| 170 | return fmt.Errorf("%s: %w", l.ID, checkNote(l.Note)) |
| 171 | case !export.ValidVerifier(l.Verifier): |
| 172 | return fmt.Errorf("%s has a verifier that is not 64 lowercase hex digits", l.ID) |
| 173 | case !validInstant(l.Issued): |
| 174 | return fmt.Errorf("%s was issued at %q, which is not a time in RFC 3339, in UTC, to the second", l.ID, l.Issued) |
| 175 | case l.Revoked != "" && !validInstant(l.Revoked): |
| 176 | return fmt.Errorf("%s was revoked at %q, which is not a time in RFC 3339, in UTC, to the second", l.ID, l.Revoked) |
| 177 | case l.Changed < 1 || l.Changed > f.Revision: |
| 178 | return fmt.Errorf("%s was changed at revision %d, which is not from 1 to the file's revision, %d", l.ID, l.Changed, f.Revision) |
| 179 | } |
| 180 | seen[l.ID] = true |
| 181 | if l.Revoked == "" { |
| 182 | active++ |
| 183 | } |
| 184 | } |
| 185 | if active > export.MaxBindings { |
| 186 | return fmt.Errorf("it holds %d active links, more than the %d an authorization carries", active, export.MaxBindings) |
| 187 | } |
| 188 | return nil |
| 189 | } |
| 190 | |
| 191 | func checkNote(note string) error { |
| 192 | if !utf8.ValidString(note) || utf8.RuneCountInString(note) > maxNote || strings.ContainsFunc(note, unicode.IsControl) { |
| 193 | return fmt.Errorf("a note is at most %d characters of UTF-8, with no control characters", maxNote) |
| 194 | } |
| 195 | return nil |
| 196 | } |
| 197 | |
| 198 | func validInstant(s string) bool { |
| 199 | t, err := time.Parse(time.RFC3339, s) |
| 200 | return err == nil && t.UTC().Format(time.RFC3339) == s |
| 201 | } |
| 202 | |
| 203 | // active are the links not revoked. |
| 204 | func (f *linksFile) active() []linkRecord { |
| 205 | var out []linkRecord |
| 206 | for _, l := range f.Links { |
| 207 | if l.Revoked == "" { |
| 208 | out = append(out, l) |
| 209 | } |
| 210 | } |
| 211 | return out |
| 212 | } |
| 213 | |
| 214 | // nextRevision is the revision a change to the file writes: one more than |
| 215 | // the greater of the file's and the greatest a pass signed from. A change |
| 216 | // to a file restored from an older copy so still moves past every revision |
| 217 | // already published. |
| 218 | func nextRevision(f linksFile, d linkDelivery) int64 { |
| 219 | return max(f.Revision, d.Signed) + 1 |
| 220 | } |
| 221 | |
| 222 | // encode is the credential file as writeLinks writes it. One larger than |
| 223 | // maxLinksFile bytes, which readLinks would refuse, is an error. |
| 224 | func (f linksFile) encode() ([]byte, error) { |
| 225 | if err := f.check(); err != nil { |
| 226 | return nil, err |
| 227 | } |
| 228 | data, err := json.MarshalIndent(f, "", " ") |
| 229 | if err != nil { |
| 230 | return nil, err |
| 231 | } |
| 232 | data = append(data, '\n') |
| 233 | if len(data) > maxLinksFile { |
| 234 | return nil, fmt.Errorf("the credential file would be %d bytes, more than the %d it may hold; run valley-web-link prune", len(data), maxLinksFile) |
| 235 | } |
| 236 | return data, nil |
| 237 | } |
| 238 | |
| 239 | // writeLinks writes the credential file durably, mode 0640, in the group |
| 240 | // of its directory, which the publisher reads it through. |
| 241 | func writeLinks(path string, f linksFile) error { |
| 242 | data, err := f.encode() |
| 243 | if err != nil { |
| 244 | return err |
| 245 | } |
| 246 | info, err := os.Stat(filepath.Dir(path)) |
| 247 | if err != nil { |
| 248 | return err |
| 249 | } |
| 250 | st, ok := info.Sys().(*syscall.Stat_t) |
| 251 | if !ok { |
| 252 | return fmt.Errorf("could not read the group of %s", filepath.Dir(path)) |
| 253 | } |
| 254 | return writeDurableGroup(path, data, 0o640, int(st.Gid)) |
| 255 | } |
| 256 | |
| 257 | // linksLockFile is the links lock's name in the credential file's |
| 258 | // directory. |
| 259 | const linksLockFile = "lock" |
| 260 | |
| 261 | // linksWait is how long a change to the credential file, and a pass about |
| 262 | // to read it, wait for the links lock. A test shortens it. |
| 263 | var linksWait = time.Minute |
| 264 | |
| 265 | // errLinksBusy is lockLinks's error when the links lock stayed held for |
| 266 | // linksWait. |
| 267 | var errLinksBusy = errors.New("the links lock stayed held") |
| 268 | |
| 269 | // lockLinks takes the links lock: the file named lock in the credential |
| 270 | // file's directory. It serializes every change to the credential file with |
| 271 | // the read of it a pass signs. A change (issue, revoke, prune) holds it |
| 272 | // alone while it reads and writes the file. A pass takes it inside the |
| 273 | // authorization lock, just before it reads the file, and holds it until it |
| 274 | // has signed. So a pass signs the file as it is when it signs, and once a |
| 275 | // change has finished, every pass that signs after it reads it. A change |
| 276 | // takes no other lock, so neither waits for the other in a cycle. |
| 277 | // |
| 278 | // Under the module the directory is root's, mode 0750, and tmpfiles makes |
| 279 | // the lock a regular file owned by root and the group valley-web-links, |
| 280 | // mode 0640. The publisher opens and locks it through that group, and can |
| 281 | // make, replace or remove nothing in the directory. The lock is opened |
| 282 | // without following a symbolic link or waiting on a FIFO, made when it is |
| 283 | // missing, and refused unless it is a regular file owned by root or by the |
| 284 | // user who runs the command. A missing directory is an error that wraps |
| 285 | // os.ErrNotExist. |
| 286 | // |
| 287 | // lockLinks waits at most linksWait, calls waiting once if it has to |
| 288 | // wait, and then fails with errLinksBusy. |
| 289 | func lockLinks(links string, waiting func(lock string)) (func(), error) { |
| 290 | path := filepath.Join(filepath.Dir(links), linksLockFile) |
| 291 | f, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0o640) |
| 292 | if errors.Is(err, syscall.ELOOP) { |
| 293 | return nil, fmt.Errorf("the links lock %s is a symbolic link; it must be a regular file owned by root", path) |
| 294 | } |
| 295 | if err != nil { |
| 296 | return nil, err |
| 297 | } |
| 298 | info, err := f.Stat() |
| 299 | if err != nil { |
| 300 | f.Close() |
| 301 | return nil, err |
| 302 | } |
| 303 | st, ok := info.Sys().(*syscall.Stat_t) |
| 304 | switch { |
| 305 | case !info.Mode().IsRegular(): |
| 306 | f.Close() |
| 307 | return nil, fmt.Errorf("the links lock %s is a %s, not a regular file owned by root", path, fileKind(info.Mode())) |
| 308 | case !ok: |
| 309 | f.Close() |
| 310 | return nil, fmt.Errorf("could not read the owner of the links lock %s", path) |
| 311 | case st.Uid != 0 && int(st.Uid) != os.Geteuid(): |
| 312 | f.Close() |
| 313 | return nil, fmt.Errorf("the links lock %s is owned by UID %d, not by root", path, st.Uid) |
| 314 | } |
| 315 | deadline := time.Now().Add(linksWait) |
| 316 | for waited := false; ; waited = true { |
| 317 | err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) |
| 318 | switch { |
| 319 | case err == nil: |
| 320 | return func() { f.Close() }, nil |
| 321 | case !errors.Is(err, syscall.EWOULDBLOCK) && !errors.Is(err, syscall.EINTR): |
| 322 | f.Close() |
| 323 | return nil, fmt.Errorf("could not lock %s: %w", path, err) |
| 324 | case time.Now().After(deadline): |
| 325 | f.Close() |
| 326 | return nil, fmt.Errorf("%w: %s was held for longer than %s", errLinksBusy, path, linksWait) |
| 327 | case !waited: |
| 328 | waiting(path) |
| 329 | } |
| 330 | time.Sleep(100 * time.Millisecond) |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | // fileKind names a file type that is not a regular file, for messages. |
| 335 | func fileKind(m os.FileMode) string { |
| 336 | switch { |
| 337 | case m&os.ModeNamedPipe != 0: |
| 338 | return "FIFO" |
| 339 | case m.IsDir(): |
| 340 | return "directory" |
| 341 | case m&os.ModeSocket != 0: |
| 342 | return "socket" |
| 343 | case m&os.ModeDevice != 0: |
| 344 | return "device" |
| 345 | } |
| 346 | return "file of another kind" |
| 347 | } |
| 348 | |
| 349 | // lockChange takes the links lock for a change to the credential file, as |
| 350 | // lockLinks says, making the file's directory when it is missing. It says |
| 351 | // on stderr when it waits, and fails having changed nothing when the wait |
| 352 | // runs out. |
| 353 | func lockChange(c linkConfig, stderr io.Writer) (func(), error) { |
| 354 | if err := os.MkdirAll(filepath.Dir(c.links), 0o750); err != nil { |
| 355 | return nil, err |
| 356 | } |
| 357 | unlock, err := lockLinks(c.links, func(lock string) { |
| 358 | fmt.Fprintf(stderr, "valley-web-publish link: waiting up to %s for the policy pass or the change that holds the links lock %s\n", linksWait, lock) |
| 359 | }) |
| 360 | if errors.Is(err, errLinksBusy) { |
| 361 | return nil, fmt.Errorf("%w; the credential file is unchanged: run the command again", err) |
| 362 | } |
| 363 | return unlock, err |
| 364 | } |
| 365 | |
| 366 | // linkDeliveryFile is the publisher's state for the read links, in the |
| 367 | // state directory: the greatest credential file revision a pass signed |
| 368 | // from, and the last authorization the receiver acknowledged, with the |
| 369 | // revision it was signed from. |
| 370 | const linkDeliveryFile = "links-delivery" |
| 371 | |
| 372 | // linkDelivery is the delivery record. Signed is the greatest credential |
| 373 | // file revision a pass read to sign an authorization from; it is written |
| 374 | // under the links lock, before that authorization is signed. Sequence is the last authorization |
| 375 | // the receiver acknowledged, and Revision the credential file revision it |
| 376 | // carried the links of, or 0 when it carried none read from a file. |
| 377 | type linkDelivery struct { |
| 378 | Signed int64 `json:"signed"` |
| 379 | Sequence int64 `json:"sequence"` |
| 380 | Revision int64 `json:"revision"` |
| 381 | } |
| 382 | |
| 383 | // maxDelivery is the most bytes the delivery record may hold. |
| 384 | const maxDelivery = 4 << 10 |
| 385 | |
| 386 | // readDelivery reads the delivery record from the state directory. A |
| 387 | // missing one records nothing signed or delivered. A change runs as root, |
| 388 | // and the state directory is the publisher's, so the record is opened |
| 389 | // without following a symbolic link or waiting on a FIFO, and must be a |
| 390 | // regular file of at most maxDelivery bytes. |
| 391 | func readDelivery(state string) (linkDelivery, error) { |
| 392 | var d linkDelivery |
| 393 | path := filepath.Join(state, linkDeliveryFile) |
| 394 | f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0) |
| 395 | switch { |
| 396 | case errors.Is(err, os.ErrNotExist): |
| 397 | return d, nil |
| 398 | case errors.Is(err, syscall.ELOOP): |
| 399 | return d, fmt.Errorf("%s is a symbolic link, not a delivery record", path) |
| 400 | case err != nil: |
| 401 | return d, err |
| 402 | } |
| 403 | defer f.Close() |
| 404 | info, err := f.Stat() |
| 405 | if err != nil { |
| 406 | return d, err |
| 407 | } |
| 408 | if !info.Mode().IsRegular() { |
| 409 | return d, fmt.Errorf("%s is a %s, not a delivery record", path, fileKind(info.Mode())) |
| 410 | } |
| 411 | data, err := io.ReadAll(io.LimitReader(f, maxDelivery+1)) |
| 412 | if err != nil { |
| 413 | return d, err |
| 414 | } |
| 415 | if len(data) > maxDelivery { |
| 416 | return d, fmt.Errorf("%s is larger than %d bytes, so not a delivery record", path, maxDelivery) |
| 417 | } |
| 418 | if err := exactjson.Decode(data, &d); err != nil { |
| 419 | return d, fmt.Errorf("%s is not a delivery record: %w", path, err) |
| 420 | } |
| 421 | return d, nil |
| 422 | } |
| 423 | |
| 424 | func writeDelivery(state string, d linkDelivery) error { |
| 425 | data, err := json.Marshal(d) |
| 426 | if err != nil { |
| 427 | return err |
| 428 | } |
| 429 | return writeDurable(filepath.Join(state, linkDeliveryFile), append(data, '\n'), 0o600) |
| 430 | } |
| 431 | |
| 432 | // linkRead is what a policy pass read of the read links: the bindings |
| 433 | // its authorization carries, the credential file revision they were read |
| 434 | // from, or 0 when they reflect no file, and, when the pass is to fail, |
| 435 | // why. |
| 436 | type linkRead struct { |
| 437 | bindings []export.Binding |
| 438 | revision int64 |
| 439 | err error |
| 440 | } |
| 441 | |
| 442 | // readBindings reads the read links an authorization carries, under the |
| 443 | // links lock, and returns the lock held: the pass releases it once it has |
| 444 | // signed. It runs under the authorization lock, after the policy check, |
| 445 | // every time the pass signs. Every change to the credential file holds the |
| 446 | // links lock, so an authorization carries the links as the file holds them |
| 447 | // when it is signed, and a pass signs no link revoked before then. |
| 448 | // |
| 449 | // A pass with no --links carries none, and so does one whose credential |
| 450 | // file's directory does not exist, as it holds no file. A links lock the |
| 451 | // pass cannot take within linksWait, or a credential file it cannot read, |
| 452 | // gives none and an error. The pass then signs and sends an authorization |
| 453 | // with no binding, so no link is active at the edge and a withdrawal still |
| 454 | // reaches it, and fails. Otherwise the file's |
| 455 | // revision is recorded as signed from, durably, under the links lock and |
| 456 | // before the authorization is signed, so a change reads it consistently. |
| 457 | func (p *publisher) readBindings() (func(), linkRead) { |
| 458 | none := func() {} |
| 459 | if p.cfg.links == "" { |
| 460 | return none, linkRead{} |
| 461 | } |
| 462 | unlock, err := lockLinks(p.cfg.links, func(lock string) { |
| 463 | p.warn("waiting up to %s for the change to the credential file that holds the links lock %s", linksWait, lock) |
| 464 | }) |
| 465 | if errors.Is(err, os.ErrNotExist) { |
| 466 | return none, linkRead{} |
| 467 | } |
| 468 | if err != nil { |
| 469 | return none, p.noLinks(err) |
| 470 | } |
| 471 | f, err := readLinks(p.cfg.links) |
| 472 | if err != nil { |
| 473 | return unlock, p.noLinks(err) |
| 474 | } |
| 475 | d, err := readDelivery(p.cfg.state) |
| 476 | if err != nil { |
| 477 | return unlock, p.noLinks(err) |
| 478 | } |
| 479 | if f.Revision > d.Signed { |
| 480 | d.Signed = f.Revision |
| 481 | if err := writeDelivery(p.cfg.state, d); err != nil { |
| 482 | return unlock, p.noLinks(err) |
| 483 | } |
| 484 | } |
| 485 | r := linkRead{revision: f.Revision} |
| 486 | for _, l := range f.active() { |
| 487 | r.bindings = append(r.bindings, export.Binding{ID: l.ID, Principal: l.Principal, Verifier: l.Verifier}) |
| 488 | } |
| 489 | return unlock, r |
| 490 | } |
| 491 | |
| 492 | // noLinks is the read of a pass whose authorization carries no read |
| 493 | // links, and fails, for err. |
| 494 | func (p *publisher) noLinks(err error) linkRead { |
| 495 | p.warn("%v; the authorization carries no read links", err) |
| 496 | return linkRead{err: err} |
| 497 | } |
| 498 | |
| 499 | // recordDelivery records that the receiver stored a, which carried the |
| 500 | // links of the credential file's revision, under the authorization lock. |
| 501 | func (p *publisher) recordDelivery(a *export.Authorization, revision int64) error { |
| 502 | d, err := readDelivery(p.cfg.state) |
| 503 | if err != nil { |
| 504 | return err |
| 505 | } |
| 506 | d.Sequence, d.Revision = a.Sequence, revision |
| 507 | return writeDelivery(p.cfg.state, d) |
| 508 | } |
| 509 | |
| 510 | // linkConfig is the link command's flags. |
| 511 | type linkConfig struct { |
| 512 | config |
| 513 | verb string |
| 514 | ids []string |
| 515 | principal string |
| 516 | note string |
| 517 | all bool |
| 518 | check bool |
| 519 | } |
| 520 | |
| 521 | // issueFlags are the flags only issue reads: what it needs to read the |
| 522 | // registry and the projects' policy/read as a pass does. |
| 523 | var issueFlags = []string{"instance-repo", "destination", "host", "read-schema", "identity-schema", "registry-ref", "registry-dir"} |
| 524 | |
| 525 | func parseLinkArgs(args []string) (linkConfig, error) { |
| 526 | c := linkConfig{config: config{maxBundles: 1 << 30, maxStorage: 16 << 30}} |
| 527 | fs := flag.NewFlagSet("valley-web-publish link", flag.ContinueOnError) |
| 528 | fs.SetOutput(io.Discard) |
| 529 | fs.StringVar(&c.links, "links", "", "") |
| 530 | fs.StringVar(&c.state, "state", "", "") |
| 531 | fs.StringVar(&c.instanceRepo, "instance-repo", "", "") |
| 532 | fs.StringVar(&c.destination, "destination", "", "") |
| 533 | fs.StringVar(&c.host, "host", "", "") |
| 534 | fs.StringVar(&c.readSchema, "read-schema", os.Getenv("VALLEY_READ_SCHEMA"), "") |
| 535 | fs.StringVar(&c.idSchema, "identity-schema", os.Getenv("VALLEY_IDENTITY_SCHEMA"), "") |
| 536 | fs.StringVar(&c.registryRef, "registry-ref", "refs/heads/main", "") |
| 537 | fs.StringVar(&c.registryDir, "registry-dir", "identity", "") |
| 538 | fs.StringVar(&c.principal, "principal", "", "") |
| 539 | fs.StringVar(&c.note, "note", "", "") |
| 540 | fs.BoolVar(&c.all, "all", false, "") |
| 541 | fs.BoolVar(&c.check, "check", false, "") |
| 542 | // Flags may follow the verb and the IDs, as the wrapper appends the |
| 543 | // module's. |
| 544 | var words []string |
| 545 | for rest := args; ; { |
| 546 | if err := fs.Parse(rest); err != nil { |
| 547 | return c, err |
| 548 | } |
| 549 | if fs.NArg() == 0 { |
| 550 | break |
| 551 | } |
| 552 | words = append(words, fs.Arg(0)) |
| 553 | rest = fs.Args()[1:] |
| 554 | } |
| 555 | if len(words) == 0 { |
| 556 | return c, errors.New("give a verb: issue, list, revoke or prune") |
| 557 | } |
| 558 | c.verb, c.ids = words[0], words[1:] |
| 559 | for _, id := range c.ids { |
| 560 | if !export.ValidLinkID(id) { |
| 561 | return c, fmt.Errorf("%q is not a credential ID: lk- and 16 lowercase hex digits", id) |
| 562 | } |
| 563 | } |
| 564 | var given []string |
| 565 | fs.Visit(func(f *flag.Flag) { |
| 566 | if slices.Contains(issueFlags, f.Name) { |
| 567 | given = append(given, "--"+f.Name) |
| 568 | } |
| 569 | }) |
| 570 | bad := func(format string, args ...any) (linkConfig, error) { return c, fmt.Errorf(format, args...) } |
| 571 | switch { |
| 572 | case c.links == "": |
| 573 | return bad("--links is required") |
| 574 | case filepath.Base(c.links) == linksLockFile: |
| 575 | return bad("--links may not name a file %s: the links lock has that name", linksLockFile) |
| 576 | case !slices.Contains([]string{"issue", "list", "revoke", "prune"}, c.verb): |
| 577 | return bad("%q is not a verb: give issue, list, revoke or prune", c.verb) |
| 578 | case c.note != "" && c.verb != "issue": |
| 579 | return bad("--note goes with issue") |
| 580 | case len(given) > 0 && c.verb != "issue": |
| 581 | return bad("%s goes with issue", strings.Join(given, ", ")) |
| 582 | case c.all && c.verb != "revoke": |
| 583 | return bad("--all goes with revoke") |
| 584 | case c.check && c.verb != "list": |
| 585 | return bad("--check goes with list") |
| 586 | case c.principal != "" && c.verb != "issue" && c.verb != "revoke": |
| 587 | return bad("--principal goes with issue and revoke") |
| 588 | case len(c.ids) > 0 && c.verb == "prune": |
| 589 | return bad("prune takes no credential ID") |
| 590 | } |
| 591 | switch c.verb { |
| 592 | case "issue": |
| 593 | switch { |
| 594 | case len(c.ids) > 0: |
| 595 | return bad("issue takes no credential ID") |
| 596 | case !export.ValidName(c.principal) || c.principal == readaccess.Anyone: |
| 597 | return bad("--principal %q is not a principal; issue needs one", c.principal) |
| 598 | case checkNote(c.note) != nil: |
| 599 | return bad("--note: %v", checkNote(c.note)) |
| 600 | case c.instanceRepo == "" || !filepath.IsAbs(c.instanceRepo): |
| 601 | return bad("issue needs --instance-repo, an absolute local path") |
| 602 | case !export.ValidName(c.destination): |
| 603 | return bad("issue needs --destination, a name") |
| 604 | case c.host == "": |
| 605 | return bad("issue needs --host") |
| 606 | case !readaccess.ValidRef(c.registryRef): |
| 607 | return bad("--registry-ref %q is not a full ref name", c.registryRef) |
| 608 | case c.readSchema == "" || c.idSchema == "": |
| 609 | return bad("no schema: give --read-schema and --identity-schema, or set VALLEY_READ_SCHEMA and VALLEY_IDENTITY_SCHEMA") |
| 610 | } |
| 611 | case "revoke": |
| 612 | given := 0 |
| 613 | for _, b := range []bool{len(c.ids) > 0, c.principal != "", c.all} { |
| 614 | if b { |
| 615 | given++ |
| 616 | } |
| 617 | } |
| 618 | switch { |
| 619 | case given != 1 || len(c.ids) > 1: |
| 620 | return bad("revoke takes one of a credential ID, --principal or --all") |
| 621 | case c.principal != "" && !export.ValidName(c.principal): |
| 622 | return bad("--principal %q is not a principal", c.principal) |
| 623 | } |
| 624 | } |
| 625 | if c.state == "" { |
| 626 | base := os.Getenv("XDG_STATE_HOME") |
| 627 | if base == "" { |
| 628 | home, err := os.UserHomeDir() |
| 629 | if err != nil { |
| 630 | return bad("no state directory: give --state, or set XDG_STATE_HOME or HOME") |
| 631 | } |
| 632 | base = filepath.Join(home, ".local", "state") |
| 633 | } |
| 634 | c.state = filepath.Join(base, "valley", "web-publish") |
| 635 | } |
| 636 | return c, nil |
| 637 | } |
| 638 | |
| 639 | // runLink is the link command. |
| 640 | func runLink(ctx context.Context, args []string, stdout, stderr io.Writer) int { |
| 641 | c, err := parseLinkArgs(args) |
| 642 | if errors.Is(err, flag.ErrHelp) { |
| 643 | fmt.Fprintln(stdout, linkUsage) |
| 644 | return 0 |
| 645 | } |
| 646 | if err != nil { |
| 647 | fmt.Fprintf(stderr, "valley-web-publish link: %v\n%s\n", err, linkUsage) |
| 648 | return 2 |
| 649 | } |
| 650 | switch c.verb { |
| 651 | case "issue": |
| 652 | err = issueLink(ctx, c, stdout, stderr) |
| 653 | case "revoke": |
| 654 | err = revokeLinks(c, stdout, stderr) |
| 655 | case "prune": |
| 656 | err = pruneLinks(c, stdout, stderr) |
| 657 | case "list": |
| 658 | err = listLinks(c, stdout, stderr) |
| 659 | } |
| 660 | if errors.Is(err, errPending) { |
| 661 | return 1 |
| 662 | } |
| 663 | if err != nil { |
| 664 | fmt.Fprintf(stderr, "valley-web-publish link: %v\n", err) |
| 665 | return 1 |
| 666 | } |
| 667 | return 0 |
| 668 | } |
| 669 | |
| 670 | // issueLink checks that the principal may read a project at the |
| 671 | // destination, then adds a link for it to the credential file and prints |
| 672 | // the link. It refuses to write the file within linksHeadroom of its |
| 673 | // limit, which it keeps for revocations. |
| 674 | func issueLink(ctx context.Context, c linkConfig, stdout, stderr io.Writer) error { |
| 675 | readable, err := readableBy(ctx, c.config, c.principal, stderr) |
| 676 | if err != nil { |
| 677 | return err |
| 678 | } |
| 679 | if len(readable) == 0 { |
| 680 | return fmt.Errorf("%s may read no project at %s: the registry grants it no edge read there that a project's policy/read consents to; no link is issued", c.principal, c.destination) |
| 681 | } |
| 682 | unlock, err := lockChange(c, stderr) |
| 683 | if err != nil { |
| 684 | return err |
| 685 | } |
| 686 | defer unlock() |
| 687 | f, err := readLinks(c.links) |
| 688 | if err != nil { |
| 689 | return err |
| 690 | } |
| 691 | d, err := readDelivery(c.state) |
| 692 | switch { |
| 693 | case err != nil: |
| 694 | return err |
| 695 | case len(f.active()) >= export.MaxBindings: |
| 696 | return fmt.Errorf("%d links are active, the most an authorization carries; revoke one first", export.MaxBindings) |
| 697 | } |
| 698 | if err := nodump.Set(); err != nil { |
| 699 | return fmt.Errorf("could not keep the secret out of a core dump: %w", err) |
| 700 | } |
| 701 | var id string |
| 702 | for id == "" || slices.ContainsFunc(f.Links, func(l linkRecord) bool { return l.ID == id }) { |
| 703 | var b [8]byte |
| 704 | if _, err := rand.Read(b[:]); err != nil { |
| 705 | return err |
| 706 | } |
| 707 | id = "lk-" + hex.EncodeToString(b[:]) |
| 708 | } |
| 709 | var secret [32]byte |
| 710 | if _, err := rand.Read(secret[:]); err != nil { |
| 711 | return err |
| 712 | } |
| 713 | verifier := sha256.Sum256(secret[:]) |
| 714 | f.Revision = nextRevision(f, d) |
| 715 | f.Links = append(f.Links, linkRecord{ID: id, Principal: c.principal, Note: c.note, |
| 716 | Verifier: hex.EncodeToString(verifier[:]), Issued: time.Now().UTC().Format(time.RFC3339), Changed: f.Revision}) |
| 717 | data, err := f.encode() |
| 718 | if err != nil { |
| 719 | return err |
| 720 | } |
| 721 | if len(data) > maxLinksFile-linksHeadroom { |
| 722 | return fmt.Errorf("the credential file would be %d bytes, within %d KiB of the %d it may hold, which is kept for revocations; run valley-web-link prune to remove the revocations the edge enforces, then issue again", len(data), linksHeadroom>>10, maxLinksFile) |
| 723 | } |
| 724 | if err := writeLinks(c.links, f); err != nil { |
| 725 | return err |
| 726 | } |
| 727 | fmt.Fprintf(stderr, "valley-web-publish link: issued %s for %s, who may read %s; the link is shown once, and the edge accepts it once a policy pass delivers it\n", |
| 728 | id, c.principal, listNames(readable)) |
| 729 | fmt.Fprintf(stdout, "https://%s/-/redeem#%s.%s\n", c.destination, id, base64.RawURLEncoding.EncodeToString(secret[:])) |
| 730 | return nil |
| 731 | } |
| 732 | |
| 733 | // readableBy are the projects the principal may read at the destination, |
| 734 | // read as a policy pass reads them: the read grants at the destination in |
| 735 | // the registry, and the policy/read on main of each project a grant |
| 736 | // selects and the host declaration places in a group. It fetches into a |
| 737 | // cache of its own, which it removes, so it writes nothing of the |
| 738 | // publisher's. |
| 739 | func readableBy(ctx context.Context, cfg config, principal string, stderr io.Writer) ([]string, error) { |
| 740 | p, err := newPublisher(cfg, io.Discard, stderr) |
| 741 | if err != nil { |
| 742 | return nil, err |
| 743 | } |
| 744 | tmp, err := os.MkdirTemp("", "valley-web-link-") |
| 745 | if err != nil { |
| 746 | return nil, err |
| 747 | } |
| 748 | defer os.RemoveAll(tmp) |
| 749 | p.cache = tmp |
| 750 | p.origin = filepath.Join(tmp, "origin.git") |
| 751 | p.mirrors = filepath.Join(tmp, "repos") |
| 752 | if err := p.access.CheckSchemas(ctx); err != nil { |
| 753 | return nil, err |
| 754 | } |
| 755 | inst, err := p.fetchInstance(ctx) |
| 756 | if err != nil { |
| 757 | return nil, err |
| 758 | } |
| 759 | grants, err := p.readGrants(ctx, inst) |
| 760 | if err != nil { |
| 761 | return nil, err |
| 762 | } |
| 763 | if len(grants[principal]) == 0 { |
| 764 | return nil, fmt.Errorf("the registry grants %s no edge read at %s, or does not name %s; no link is issued", principal, cfg.destination, principal) |
| 765 | } |
| 766 | var readable []string |
| 767 | for _, name := range inst.projects { |
| 768 | if !grants.Selects(principal, name) || p.places.placements[name].Group == "" || !export.ValidName(name) { |
| 769 | continue |
| 770 | } |
| 771 | mirror, tip, err := p.fetchMain(ctx, name, p.projectURL(name)) |
| 772 | if errors.Is(err, errNoMain) { |
| 773 | continue |
| 774 | } |
| 775 | if err != nil { |
| 776 | return nil, fmt.Errorf("%s: could not read main: %w", name, err) |
| 777 | } |
| 778 | consent, err := p.access.Consent(ctx, mirror, tip, name) |
| 779 | var bad *readaccess.InvalidError |
| 780 | switch { |
| 781 | case errors.Is(err, readaccess.ErrMissing), errors.As(err, &bad): |
| 782 | continue |
| 783 | case err != nil: |
| 784 | return nil, fmt.Errorf("%s: could not read its policy/read at %s: %w", name, short(tip), err) |
| 785 | } |
| 786 | if grants.May(principal, consent) { |
| 787 | readable = append(readable, name) |
| 788 | } |
| 789 | } |
| 790 | return readable, nil |
| 791 | } |
| 792 | |
| 793 | // revokeLinks revokes the link with the ID given, every active link of |
| 794 | // the principal, or every active link, and prints each it revoked. Each |
| 795 | // link it revokes records the revision it writes. It writes the file only |
| 796 | // when it revoked a link. |
| 797 | func revokeLinks(c linkConfig, stdout, stderr io.Writer) error { |
| 798 | unlock, err := lockChange(c, stderr) |
| 799 | if err != nil { |
| 800 | return err |
| 801 | } |
| 802 | defer unlock() |
| 803 | f, err := readLinks(c.links) |
| 804 | if err != nil { |
| 805 | return err |
| 806 | } |
| 807 | d, err := readDelivery(c.state) |
| 808 | if err != nil { |
| 809 | return err |
| 810 | } |
| 811 | next := nextRevision(f, d) |
| 812 | now := time.Now().UTC().Format(time.RFC3339) |
| 813 | found, changed := false, false |
| 814 | for i, l := range f.Links { |
| 815 | switch { |
| 816 | case len(c.ids) > 0 && l.ID != c.ids[0], c.principal != "" && l.Principal != c.principal: |
| 817 | continue |
| 818 | } |
| 819 | found = true |
| 820 | if l.Revoked != "" { |
| 821 | if len(c.ids) > 0 { |
| 822 | fmt.Fprintf(stdout, "%s (%s) was revoked at %s\n", l.ID, l.Principal, l.Revoked) |
| 823 | } |
| 824 | continue |
| 825 | } |
| 826 | f.Links[i].Revoked, f.Links[i].Changed = now, next |
| 827 | changed = true |
| 828 | fmt.Fprintf(stdout, "revoked %s (%s)\n", l.ID, l.Principal) |
| 829 | } |
| 830 | switch { |
| 831 | case len(c.ids) > 0 && !found: |
| 832 | return fmt.Errorf("%s holds no link %s", c.links, c.ids[0]) |
| 833 | case !changed && len(c.ids) == 0: |
| 834 | fmt.Fprintln(stdout, "no active link to revoke") |
| 835 | } |
| 836 | if !changed { |
| 837 | return nil |
| 838 | } |
| 839 | f.Revision = next |
| 840 | return writeLinks(c.links, f) |
| 841 | } |
| 842 | |
| 843 | // pruneLinks removes the revoked links whose revocation is enforced: the |
| 844 | // receiver acknowledged an authorization that carried the links of the |
| 845 | // revision that revoked them, or of a later one. It prints each it |
| 846 | // removed, and writes the file at the next revision when it removed any. |
| 847 | // |
| 848 | // Pruning loses nothing. The edge accepts a link only while the stored |
| 849 | // authorization binds it, so a link absent from the file is as revoked as |
| 850 | // one recorded revoked, and no pass carries either. A pending revocation |
| 851 | // is kept until a pass delivers it. |
| 852 | func pruneLinks(c linkConfig, stdout, stderr io.Writer) error { |
| 853 | unlock, err := lockChange(c, stderr) |
| 854 | if err != nil { |
| 855 | return err |
| 856 | } |
| 857 | defer unlock() |
| 858 | f, err := readLinks(c.links) |
| 859 | if err != nil { |
| 860 | return err |
| 861 | } |
| 862 | d, err := readDelivery(c.state) |
| 863 | if err != nil { |
| 864 | return err |
| 865 | } |
| 866 | kept, pending := []linkRecord{}, 0 |
| 867 | for _, l := range f.Links { |
| 868 | switch { |
| 869 | case l.Revoked == "": |
| 870 | kept = append(kept, l) |
| 871 | case d.Revision < l.Changed: |
| 872 | kept = append(kept, l) |
| 873 | pending++ |
| 874 | default: |
| 875 | fmt.Fprintf(stdout, "pruned %s (%s), revoked at %s\n", l.ID, l.Principal, l.Revoked) |
| 876 | } |
| 877 | } |
| 878 | if pending > 0 { |
| 879 | fmt.Fprintf(stdout, "kept %d revoked links whose revocation is pending until a pass delivers it\n", pending) |
| 880 | } |
| 881 | if len(kept) == len(f.Links) { |
| 882 | fmt.Fprintln(stdout, "no enforced revocation to prune") |
| 883 | return nil |
| 884 | } |
| 885 | f.Revision, f.Links = nextRevision(f, d), kept |
| 886 | return writeLinks(c.links, f) |
| 887 | } |
| 888 | |
| 889 | // errPending is list --check's error when a link it shows is pending; it |
| 890 | // has said why. |
| 891 | var errPending = errors.New("pending") |
| 892 | |
| 893 | // listLinks prints the links, or those with the IDs given, and how far |
| 894 | // each has reached the edge, from the publisher's delivery record. A link |
| 895 | // is enforced once the receiver acknowledged an authorization that |
| 896 | // carried the links of the revision that set its state, or of a later |
| 897 | // one: every authorization signed after that one carries the links of a |
| 898 | // revision at least as late, or none, unless the file is restored from an |
| 899 | // older copy. |
| 900 | func listLinks(c linkConfig, stdout, stderr io.Writer) error { |
| 901 | f, err := readLinks(c.links) |
| 902 | if err != nil { |
| 903 | return err |
| 904 | } |
| 905 | d, err := readDelivery(c.state) |
| 906 | if err != nil { |
| 907 | return err |
| 908 | } |
| 909 | shown := f.Links |
| 910 | if len(c.ids) > 0 { |
| 911 | shown = nil |
| 912 | for _, id := range c.ids { |
| 913 | i := slices.IndexFunc(f.Links, func(l linkRecord) bool { return l.ID == id }) |
| 914 | if i < 0 { |
| 915 | return fmt.Errorf("%s holds no link %s", c.links, id) |
| 916 | } |
| 917 | shown = append(shown, f.Links[i]) |
| 918 | } |
| 919 | } |
| 920 | switch { |
| 921 | case d.Sequence == 0: |
| 922 | fmt.Fprintf(stdout, "the receiver has acknowledged no authorization from this publisher's state; the credential file is at revision %d\n", f.Revision) |
| 923 | case d.Revision == 0: |
| 924 | fmt.Fprintf(stdout, "the receiver last acknowledged authorization %d, which carried no read links from the credential file, now at revision %d\n", d.Sequence, f.Revision) |
| 925 | default: |
| 926 | fmt.Fprintf(stdout, "the receiver last acknowledged authorization %d, which carried the links of revision %d of the credential file, now at revision %d\n", |
| 927 | d.Sequence, d.Revision, f.Revision) |
| 928 | } |
| 929 | var problems []string |
| 930 | w := tabwriter.NewWriter(stdout, 0, 0, 2, ' ', 0) |
| 931 | fmt.Fprintln(w, "ID\tPRINCIPAL\tSTATE\tDELIVERY\tISSUED\tNOTE") |
| 932 | for _, l := range shown { |
| 933 | state, delivery := "active", "enforced" |
| 934 | if l.Revoked != "" { |
| 935 | state = "revoked" |
| 936 | } |
| 937 | switch { |
| 938 | case d.Revision < l.Changed && l.Revoked == "": |
| 939 | delivery = "pending" |
| 940 | problems = append(problems, fmt.Sprintf("%s: issued here; the edge does not accept it until a pass delivers it", l.ID)) |
| 941 | case d.Revision < l.Changed: |
| 942 | delivery = "pending" |
| 943 | problems = append(problems, fmt.Sprintf("%s: revoked here; the edge may accept it until a pass delivers the revocation", l.ID)) |
| 944 | } |
| 945 | fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", l.ID, l.Principal, state, delivery, l.Issued, l.Note) |
| 946 | } |
| 947 | if err := w.Flush(); err != nil { |
| 948 | return err |
| 949 | } |
| 950 | if c.check && len(problems) > 0 { |
| 951 | for _, line := range problems { |
| 952 | fmt.Fprintln(stderr, line) |
| 953 | } |
| 954 | return errPending |
| 955 | } |
| 956 | return nil |
| 957 | } |