gunk-dev/the-valley

link.go

sourcee2dd787b4f4fmain's published tip history
34.0 KiB
1package main
2
3import (
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
30const 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
35Issue, list and revoke read links: bearer credentials, each bound to one
36registry principal, that let their holder read what that principal may
37read at the destination, and nothing more. The host keeps each link's
38verifier in the credential file and never its secret. Each policy pass
39reads the file as it signs, and carries the active links to the edge in
40the authorization. issue, revoke and prune hold the links lock, the file
41lock in the credential file's directory, while they read and write the
42file; a pass holds it from its read of the file until it has signed. So
43a change waits for a pass that is signing, and a pass for a change, each
44for at most a minute; a change then fails having changed nothing. The
45lock must be a regular file owned by root, or by the user who runs the
46command, 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
71FLAGS:
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.
93const (
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.
104type 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.
112type 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.
126func 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
155func (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
191func 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
198func 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.
204func (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.
218func 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.
224func (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.
241func 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.
259const 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.
263var linksWait = time.Minute
264
265// errLinksBusy is lockLinks's error when the links lock stayed held for
266// linksWait.
267var 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.
289func 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.
335func 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.
353func 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.
370const 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.
377type 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.
384const 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.
391func 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
424func 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, the delivery record as it read
435// it, and, when the pass is to fail, why.
436type linkRead struct {
437 bindings []export.Binding
438 revision int64
439 delivered linkDelivery
440 err error
441}
442
443// readBindings reads the read links an authorization carries, under the
444// links lock, and returns the lock held: the pass releases it once it has
445// signed. It runs under the authorization lock, after the policy check,
446// every time the pass signs. Every change to the credential file holds the
447// links lock, so an authorization carries the links as the file holds them
448// when it is signed, and a pass signs no link revoked before then.
449//
450// A pass with no --links carries none, and so does one whose credential
451// file's directory does not exist, as it holds no file. A links lock the
452// pass cannot take within linksWait, or a credential file it cannot read,
453// gives none and an error. The pass then signs and sends an authorization
454// with no binding, so no link is active at the edge and a withdrawal still
455// reaches it, and fails. Otherwise the file's
456// revision is recorded as signed from, durably, under the links lock and
457// before the authorization is signed, so a change reads it consistently.
458func (p *publisher) readBindings() (func(), linkRead) {
459 none := func() {}
460 if p.cfg.links == "" {
461 return none, linkRead{}
462 }
463 unlock, err := lockLinks(p.cfg.links, func(lock string) {
464 p.warn("waiting up to %s for the change to the credential file that holds the links lock %s", linksWait, lock)
465 })
466 if errors.Is(err, os.ErrNotExist) {
467 return none, linkRead{}
468 }
469 if err != nil {
470 return none, p.noLinks(err)
471 }
472 f, err := readLinks(p.cfg.links)
473 if err != nil {
474 return unlock, p.noLinks(err)
475 }
476 d, err := readDelivery(p.cfg.state)
477 if err != nil {
478 return unlock, p.noLinks(err)
479 }
480 if f.Revision > d.Signed {
481 d.Signed = f.Revision
482 if err := writeDelivery(p.cfg.state, d); err != nil {
483 return unlock, p.noLinks(err)
484 }
485 }
486 r := linkRead{revision: f.Revision, delivered: d}
487 for _, l := range f.active() {
488 r.bindings = append(r.bindings, export.Binding{ID: l.ID, Principal: l.Principal, Verifier: l.Verifier})
489 }
490 return unlock, r
491}
492
493// noLinks is the read of a pass whose authorization carries no read
494// links, and fails, for err.
495func (p *publisher) noLinks(err error) linkRead {
496 p.warn("%v; the authorization carries no read links", err)
497 return linkRead{err: err}
498}
499
500// recordDelivery records that the receiver stored a, which carried the
501// links of the credential file's revision, under the authorization lock.
502func (p *publisher) recordDelivery(a *export.Authorization, revision int64) error {
503 d, err := readDelivery(p.cfg.state)
504 if err != nil {
505 return err
506 }
507 d.Sequence, d.Revision = a.Sequence, revision
508 return writeDelivery(p.cfg.state, d)
509}
510
511// linkConfig is the link command's flags.
512type linkConfig struct {
513 config
514 verb string
515 ids []string
516 principal string
517 note string
518 all bool
519 check bool
520}
521
522// issueFlags are the flags only issue reads: what it needs to read the
523// registry and the projects' policy/read as a pass does.
524var issueFlags = []string{"instance-repo", "destination", "host", "read-schema", "identity-schema", "registry-ref", "registry-dir"}
525
526func parseLinkArgs(args []string) (linkConfig, error) {
527 c := linkConfig{config: config{maxBundles: 1 << 30, maxStorage: 16 << 30}}
528 fs := flag.NewFlagSet("valley-web-publish link", flag.ContinueOnError)
529 fs.SetOutput(io.Discard)
530 fs.StringVar(&c.links, "links", "", "")
531 fs.StringVar(&c.state, "state", "", "")
532 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
533 fs.StringVar(&c.destination, "destination", "", "")
534 fs.StringVar(&c.host, "host", "", "")
535 fs.StringVar(&c.readSchema, "read-schema", os.Getenv("VALLEY_READ_SCHEMA"), "")
536 fs.StringVar(&c.idSchema, "identity-schema", os.Getenv("VALLEY_IDENTITY_SCHEMA"), "")
537 fs.StringVar(&c.registryRef, "registry-ref", "refs/heads/main", "")
538 fs.StringVar(&c.registryDir, "registry-dir", "identity", "")
539 fs.StringVar(&c.principal, "principal", "", "")
540 fs.StringVar(&c.note, "note", "", "")
541 fs.BoolVar(&c.all, "all", false, "")
542 fs.BoolVar(&c.check, "check", false, "")
543 // Flags may follow the verb and the IDs, as the wrapper appends the
544 // module's.
545 var words []string
546 for rest := args; ; {
547 if err := fs.Parse(rest); err != nil {
548 return c, err
549 }
550 if fs.NArg() == 0 {
551 break
552 }
553 words = append(words, fs.Arg(0))
554 rest = fs.Args()[1:]
555 }
556 if len(words) == 0 {
557 return c, errors.New("give a verb: issue, list, revoke or prune")
558 }
559 c.verb, c.ids = words[0], words[1:]
560 for _, id := range c.ids {
561 if !export.ValidLinkID(id) {
562 return c, fmt.Errorf("%q is not a credential ID: lk- and 16 lowercase hex digits", id)
563 }
564 }
565 var given []string
566 fs.Visit(func(f *flag.Flag) {
567 if slices.Contains(issueFlags, f.Name) {
568 given = append(given, "--"+f.Name)
569 }
570 })
571 bad := func(format string, args ...any) (linkConfig, error) { return c, fmt.Errorf(format, args...) }
572 switch {
573 case c.links == "":
574 return bad("--links is required")
575 case filepath.Base(c.links) == linksLockFile:
576 return bad("--links may not name a file %s: the links lock has that name", linksLockFile)
577 case !slices.Contains([]string{"issue", "list", "revoke", "prune"}, c.verb):
578 return bad("%q is not a verb: give issue, list, revoke or prune", c.verb)
579 case c.note != "" && c.verb != "issue":
580 return bad("--note goes with issue")
581 case len(given) > 0 && c.verb != "issue":
582 return bad("%s goes with issue", strings.Join(given, ", "))
583 case c.all && c.verb != "revoke":
584 return bad("--all goes with revoke")
585 case c.check && c.verb != "list":
586 return bad("--check goes with list")
587 case c.principal != "" && c.verb != "issue" && c.verb != "revoke":
588 return bad("--principal goes with issue and revoke")
589 case len(c.ids) > 0 && c.verb == "prune":
590 return bad("prune takes no credential ID")
591 }
592 switch c.verb {
593 case "issue":
594 switch {
595 case len(c.ids) > 0:
596 return bad("issue takes no credential ID")
597 case !export.ValidName(c.principal) || c.principal == readaccess.Anyone:
598 return bad("--principal %q is not a principal; issue needs one", c.principal)
599 case checkNote(c.note) != nil:
600 return bad("--note: %v", checkNote(c.note))
601 case c.instanceRepo == "" || !filepath.IsAbs(c.instanceRepo):
602 return bad("issue needs --instance-repo, an absolute local path")
603 case !export.ValidName(c.destination):
604 return bad("issue needs --destination, a name")
605 case c.host == "":
606 return bad("issue needs --host")
607 case !readaccess.ValidRef(c.registryRef):
608 return bad("--registry-ref %q is not a full ref name", c.registryRef)
609 case c.readSchema == "" || c.idSchema == "":
610 return bad("no schema: give --read-schema and --identity-schema, or set VALLEY_READ_SCHEMA and VALLEY_IDENTITY_SCHEMA")
611 }
612 case "revoke":
613 given := 0
614 for _, b := range []bool{len(c.ids) > 0, c.principal != "", c.all} {
615 if b {
616 given++
617 }
618 }
619 switch {
620 case given != 1 || len(c.ids) > 1:
621 return bad("revoke takes one of a credential ID, --principal or --all")
622 case c.principal != "" && !export.ValidName(c.principal):
623 return bad("--principal %q is not a principal", c.principal)
624 }
625 }
626 if c.state == "" {
627 base := os.Getenv("XDG_STATE_HOME")
628 if base == "" {
629 home, err := os.UserHomeDir()
630 if err != nil {
631 return bad("no state directory: give --state, or set XDG_STATE_HOME or HOME")
632 }
633 base = filepath.Join(home, ".local", "state")
634 }
635 c.state = filepath.Join(base, "valley", "web-publish")
636 }
637 return c, nil
638}
639
640// runLink is the link command.
641func runLink(ctx context.Context, args []string, stdout, stderr io.Writer) int {
642 c, err := parseLinkArgs(args)
643 if errors.Is(err, flag.ErrHelp) {
644 fmt.Fprintln(stdout, linkUsage)
645 return 0
646 }
647 if err != nil {
648 fmt.Fprintf(stderr, "valley-web-publish link: %v\n%s\n", err, linkUsage)
649 return 2
650 }
651 switch c.verb {
652 case "issue":
653 err = issueLink(ctx, c, stdout, stderr)
654 case "revoke":
655 err = revokeLinks(c, stdout, stderr)
656 case "prune":
657 err = pruneLinks(c, stdout, stderr)
658 case "list":
659 err = listLinks(c, stdout, stderr)
660 }
661 if errors.Is(err, errPending) {
662 return 1
663 }
664 if err != nil {
665 fmt.Fprintf(stderr, "valley-web-publish link: %v\n", err)
666 return 1
667 }
668 return 0
669}
670
671// issueLink checks that the principal may read a project at the
672// destination, then adds a link for it to the credential file and prints
673// the link. It refuses to write the file within linksHeadroom of its
674// limit, which it keeps for revocations.
675func issueLink(ctx context.Context, c linkConfig, stdout, stderr io.Writer) error {
676 readable, err := readableBy(ctx, c.config, c.principal, stderr)
677 if err != nil {
678 return err
679 }
680 if len(readable) == 0 {
681 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)
682 }
683 unlock, err := lockChange(c, stderr)
684 if err != nil {
685 return err
686 }
687 defer unlock()
688 f, err := readLinks(c.links)
689 if err != nil {
690 return err
691 }
692 d, err := readDelivery(c.state)
693 switch {
694 case err != nil:
695 return err
696 case len(f.active()) >= export.MaxBindings:
697 return fmt.Errorf("%d links are active, the most an authorization carries; revoke one first", export.MaxBindings)
698 }
699 if err := nodump.Set(); err != nil {
700 return fmt.Errorf("could not keep the secret out of a core dump: %w", err)
701 }
702 var id string
703 for id == "" || slices.ContainsFunc(f.Links, func(l linkRecord) bool { return l.ID == id }) {
704 var b [8]byte
705 if _, err := rand.Read(b[:]); err != nil {
706 return err
707 }
708 id = "lk-" + hex.EncodeToString(b[:])
709 }
710 var secret [32]byte
711 if _, err := rand.Read(secret[:]); err != nil {
712 return err
713 }
714 verifier := sha256.Sum256(secret[:])
715 f.Revision = nextRevision(f, d)
716 f.Links = append(f.Links, linkRecord{ID: id, Principal: c.principal, Note: c.note,
717 Verifier: hex.EncodeToString(verifier[:]), Issued: time.Now().UTC().Format(time.RFC3339), Changed: f.Revision})
718 data, err := f.encode()
719 if err != nil {
720 return err
721 }
722 if len(data) > maxLinksFile-linksHeadroom {
723 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)
724 }
725 if err := writeLinks(c.links, f); err != nil {
726 return err
727 }
728 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",
729 id, c.principal, listNames(readable))
730 fmt.Fprintf(stdout, "https://%s/-/redeem#%s.%s\n", c.destination, id, base64.RawURLEncoding.EncodeToString(secret[:]))
731 return nil
732}
733
734// readableBy are the projects the principal may read at the destination,
735// read as a policy pass reads them: the read grants at the destination in
736// the registry, and the policy/read on main of each project a grant
737// selects and the host declaration places in a group. It fetches into a
738// cache of its own, which it removes, so it writes nothing of the
739// publisher's.
740func readableBy(ctx context.Context, cfg config, principal string, stderr io.Writer) ([]string, error) {
741 p, err := newPublisher(cfg, io.Discard, stderr)
742 if err != nil {
743 return nil, err
744 }
745 tmp, err := os.MkdirTemp("", "valley-web-link-")
746 if err != nil {
747 return nil, err
748 }
749 defer os.RemoveAll(tmp)
750 p.cache = tmp
751 p.origin = filepath.Join(tmp, "origin.git")
752 p.mirrors = filepath.Join(tmp, "repos")
753 if err := p.access.CheckSchemas(ctx); err != nil {
754 return nil, err
755 }
756 inst, err := p.fetchInstance(ctx)
757 if err != nil {
758 return nil, err
759 }
760 grants, err := p.readGrants(ctx, inst)
761 if err != nil {
762 return nil, err
763 }
764 if len(grants[principal]) == 0 {
765 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)
766 }
767 var readable []string
768 for _, name := range inst.projects {
769 if !grants.Selects(principal, name) || p.places.placements[name].Group == "" || !export.ValidName(name) {
770 continue
771 }
772 mirror, tip, err := p.fetchMain(ctx, name, p.projectURL(name))
773 if errors.Is(err, errNoMain) {
774 continue
775 }
776 if err != nil {
777 return nil, fmt.Errorf("%s: could not read main: %w", name, err)
778 }
779 consent, err := p.access.Consent(ctx, mirror, tip, name)
780 var bad *readaccess.InvalidError
781 switch {
782 case errors.Is(err, readaccess.ErrMissing), errors.As(err, &bad):
783 continue
784 case err != nil:
785 return nil, fmt.Errorf("%s: could not read its policy/read at %s: %w", name, short(tip), err)
786 }
787 if grants.May(principal, consent) {
788 readable = append(readable, name)
789 }
790 }
791 return readable, nil
792}
793
794// revokeLinks revokes the link with the ID given, every active link of
795// the principal, or every active link, and prints each it revoked. Each
796// link it revokes records the revision it writes. It writes the file only
797// when it revoked a link.
798func revokeLinks(c linkConfig, stdout, stderr io.Writer) error {
799 unlock, err := lockChange(c, stderr)
800 if err != nil {
801 return err
802 }
803 defer unlock()
804 f, err := readLinks(c.links)
805 if err != nil {
806 return err
807 }
808 d, err := readDelivery(c.state)
809 if err != nil {
810 return err
811 }
812 next := nextRevision(f, d)
813 now := time.Now().UTC().Format(time.RFC3339)
814 found, changed := false, false
815 for i, l := range f.Links {
816 switch {
817 case len(c.ids) > 0 && l.ID != c.ids[0], c.principal != "" && l.Principal != c.principal:
818 continue
819 }
820 found = true
821 if l.Revoked != "" {
822 if len(c.ids) > 0 {
823 fmt.Fprintf(stdout, "%s (%s) was revoked at %s\n", l.ID, l.Principal, l.Revoked)
824 }
825 continue
826 }
827 f.Links[i].Revoked, f.Links[i].Changed = now, next
828 changed = true
829 fmt.Fprintf(stdout, "revoked %s (%s)\n", l.ID, l.Principal)
830 }
831 switch {
832 case len(c.ids) > 0 && !found:
833 return fmt.Errorf("%s holds no link %s", c.links, c.ids[0])
834 case !changed && len(c.ids) == 0:
835 fmt.Fprintln(stdout, "no active link to revoke")
836 }
837 if !changed {
838 return nil
839 }
840 f.Revision = next
841 return writeLinks(c.links, f)
842}
843
844// pruneLinks removes the revoked links whose revocation is enforced: the
845// receiver acknowledged an authorization that carried the links of the
846// revision that revoked them, or of a later one. It prints each it
847// removed, and writes the file at the next revision when it removed any.
848//
849// Pruning loses nothing. The edge accepts a link only while the stored
850// authorization binds it, so a link absent from the file is as revoked as
851// one recorded revoked, and no pass carries either. A pending revocation
852// is kept until a pass delivers it.
853func pruneLinks(c linkConfig, stdout, stderr io.Writer) error {
854 unlock, err := lockChange(c, stderr)
855 if err != nil {
856 return err
857 }
858 defer unlock()
859 f, err := readLinks(c.links)
860 if err != nil {
861 return err
862 }
863 d, err := readDelivery(c.state)
864 if err != nil {
865 return err
866 }
867 kept, pending := []linkRecord{}, 0
868 for _, l := range f.Links {
869 switch {
870 case l.Revoked == "":
871 kept = append(kept, l)
872 case d.Revision < l.Changed:
873 kept = append(kept, l)
874 pending++
875 default:
876 fmt.Fprintf(stdout, "pruned %s (%s), revoked at %s\n", l.ID, l.Principal, l.Revoked)
877 }
878 }
879 if pending > 0 {
880 fmt.Fprintf(stdout, "kept %d revoked links whose revocation is pending until a pass delivers it\n", pending)
881 }
882 if len(kept) == len(f.Links) {
883 fmt.Fprintln(stdout, "no enforced revocation to prune")
884 return nil
885 }
886 f.Revision, f.Links = nextRevision(f, d), kept
887 return writeLinks(c.links, f)
888}
889
890// errPending is list --check's error when a link it shows is pending; it
891// has said why.
892var errPending = errors.New("pending")
893
894// listLinks prints the links, or those with the IDs given, and how far
895// each has reached the edge, from the publisher's delivery record. A link
896// is enforced once the receiver acknowledged an authorization that
897// carried the links of the revision that set its state, or of a later
898// one: every authorization signed after that one carries the links of a
899// revision at least as late, or none, unless the file is restored from an
900// older copy.
901func listLinks(c linkConfig, stdout, stderr io.Writer) error {
902 f, err := readLinks(c.links)
903 if err != nil {
904 return err
905 }
906 d, err := readDelivery(c.state)
907 if err != nil {
908 return err
909 }
910 shown := f.Links
911 if len(c.ids) > 0 {
912 shown = nil
913 for _, id := range c.ids {
914 i := slices.IndexFunc(f.Links, func(l linkRecord) bool { return l.ID == id })
915 if i < 0 {
916 return fmt.Errorf("%s holds no link %s", c.links, id)
917 }
918 shown = append(shown, f.Links[i])
919 }
920 }
921 switch {
922 case d.Sequence == 0:
923 fmt.Fprintf(stdout, "the receiver has acknowledged no authorization from this publisher's state; the credential file is at revision %d\n", f.Revision)
924 case d.Revision == 0:
925 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)
926 default:
927 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",
928 d.Sequence, d.Revision, f.Revision)
929 }
930 var problems []string
931 w := tabwriter.NewWriter(stdout, 0, 0, 2, ' ', 0)
932 fmt.Fprintln(w, "ID\tPRINCIPAL\tSTATE\tDELIVERY\tISSUED\tNOTE")
933 for _, l := range shown {
934 state, delivery := "active", "enforced"
935 if l.Revoked != "" {
936 state = "revoked"
937 }
938 switch {
939 case d.Revision < l.Changed && l.Revoked == "":
940 delivery = "pending"
941 problems = append(problems, fmt.Sprintf("%s: issued here; the edge does not accept it until a pass delivers it", l.ID))
942 case d.Revision < l.Changed:
943 delivery = "pending"
944 problems = append(problems, fmt.Sprintf("%s: revoked here; the edge may accept it until a pass delivers the revocation", l.ID))
945 }
946 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)
947 }
948 if err := w.Flush(); err != nil {
949 return err
950 }
951 if c.check && len(problems) > 0 {
952 for _, line := range problems {
953 fmt.Fprintln(stderr, line)
954 }
955 return errPending
956 }
957 return nil
958}