gunk-dev/the-valley

link.go

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