gunk-dev/the-valley

state.go

source860de91b1a12main's published tip history
29.1 KiB
1// Package readerstate is valley-web's browser state: the read links
2// readers have redeemed at this edge, and the session each one holds.
3//
4// # The state
5//
6// valley-web keeps the state in a directory of its own, browser/ beside
7// the receiver's store descriptor. The deployment makes that directory,
8// owned by valley-web's user and mode 0700. Neither valley-web nor the
9// receiver makes it or changes its owner. Its files are:
10//
11// owner.lock held by the one valley-web that owns the directory
12// lock held for each transaction
13// state the state document
14// state.new the next state document, while a transaction writes it
15//
16// Every file is mode 0600. A symbolic link, or any file that is not a
17// regular file, is refused where a file is expected.
18//
19// The state document records every link that has been redeemed, once,
20// for good. Each record keeps the binding the link had when it was
21// redeemed: its credential ID, its principal and its verifier. It also
22// keeps the SHA-256 of the session token the redemption gave out, until
23// the reader signs out. Signing out removes the hash and keeps the
24// record, so a link is never redeemed twice. Its text is a type line,
25// then one line per record, in ID order, with "-" for no session:
26//
27// the-valley/web-reader-state/v1
28// link lk-0123456789abcdef alice <verifier> <SHA-256 of the session token>
29//
30// The document is at most MaxState bytes. A redemption that would pass
31// that is refused, and nothing is consumed. Signing out never makes the
32// document larger. No record is ever removed to make room.
33//
34// # One owner, one snapshot
35//
36// One process owns the directory: Open takes owner.lock and keeps it
37// until the process ends, and a second Open of the same directory fails.
38// The owner holds the decoded state in memory. Reads take a read lock on
39// it and touch no file but the state's directory entry. A mutation takes
40// the write lock, then the transaction lock, then the receiver's serving
41// lock shared, and reads the stored authorization again under it. It
42// writes the whole next document to state.new, syncs it, renames it over
43// state, and syncs the directory. Only then does it replace the snapshot
44// in memory.
45//
46// Every wait for a lock ends when the request's context is done. A
47// mutation checks its context again once it holds each lock, and once
48// more after it encodes the next document, just before it creates
49// state.new. One whose context is done at any of these checks stops
50// there, before it changes anything. So a request whose deadline passed
51// while it waited consumes no link and ends no session. A mutation that
52// has started writing finishes, whatever its context.
53//
54// A transaction that fails while it writes, syncs or renames leaves the
55// state unavailable until the process restarts. So does a state file
56// that is missing, replaced or changed under the process. The process
57// never goes back to a snapshot it held before: an unavailable state
58// serves no session and takes no redemption, and anonymous readers are
59// served as ever.
60//
61// # Starting empty
62//
63// An edge whose state file does not exist yet starts with no state. The
64// first state is created only under a stored authorization that was read
65// and parsed, and that carries no binding (Initialize). A missing or
66// unreadable authorization is not one with no bindings. So a link the
67// host issued before the edge's state was created is never redeemed: the
68// host revokes every link, delivers an authorization with no binding, and
69// issues new links once the state is created.
70package readerstate
71
72import (
73 "bytes"
74 "context"
75 "crypto/rand"
76 "crypto/sha256"
77 "crypto/subtle"
78 "encoding/base64"
79 "encoding/hex"
80 "errors"
81 "fmt"
82 "io"
83 "io/fs"
84 "os"
85 "path/filepath"
86 "sort"
87 "strings"
88 "sync"
89 "syscall"
90 "time"
91
92 "the-valley/web/export"
93)
94
95// Type is the first line of every state document.
96const Type = "the-valley/web-reader-state/v1"
97
98// MaxState is the most bytes a state document takes.
99const MaxState = 32 << 20
100
101// The files of a browser-state directory.
102const (
103 stateFile = "state"
104 nextFile = "state.new"
105 lockFile = "lock"
106 ownerFile = "owner.lock"
107)
108
109// The errors a transaction or a read fails with.
110var (
111 // ErrUnavailable is the error of every read and every transaction
112 // while the state is not usable: before it is created, and after a
113 // failure made it unavailable until the process restarts.
114 ErrUnavailable = errors.New("the browser state is unavailable")
115 // ErrRefused is Redeem's error for every credential it does not take:
116 // one that is malformed, unknown, revoked, redeemed already, or whose
117 // secret does not match its verifier. Its cause is never told apart.
118 ErrRefused = errors.New("this link cannot be used")
119 // ErrSignedIn is Redeem's error when the request carries a valid
120 // session already.
121 ErrSignedIn = errors.New("a reader is signed in already")
122 // ErrFull is Redeem's error when the state has no room for one more
123 // record.
124 ErrFull = errors.New("the browser state is full")
125)
126
127// Op names a kind of transaction.
128type Op int
129
130// The kinds of transaction.
131const (
132 Initializing Op = iota
133 Redeeming
134 SigningOut
135)
136
137func (o Op) String() string {
138 return [...]string{"initialize", "redeem", "logout"}[o]
139}
140
141// Step names a point in a transaction, from the encoding of the next
142// document through its durable write, each reached once the work it names
143// is done.
144type Step int
145
146// The steps of a transaction, in order.
147const (
148 // Encoded: the next document is encoded, and state.new is not made.
149 // The transaction checks its context after it.
150 Encoded Step = iota
151 // Created: state.new is made, and nothing is written to it.
152 Created
153 // Written: the next document is written to state.new.
154 Written
155 // Synced: state.new is synced.
156 Synced
157 // Renamed: state.new is renamed over state.
158 Renamed
159 // Committed: the directory is synced, so the transaction is durable.
160 Committed
161 // Published: the new snapshot is the one reads see.
162 Published
163)
164
165// Steps names each step as Step.String does.
166var Steps = []Step{Encoded, Created, Written, Synced, Renamed, Committed, Published}
167
168func (s Step) String() string {
169 return [...]string{"encoded", "created", "written", "synced", "renamed", "committed", "published"}[s]
170}
171
172// Options are what Open opens a state with. The zero value is what
173// valley-web uses.
174type Options struct {
175 // Max is the most bytes the state document takes, or 0 for MaxState.
176 Max int
177 // Fault, when set, is called at each step of each transaction. An
178 // error it returns fails the transaction at that step, as a failed
179 // write or sync would, and leaves the state unavailable. Tests set it.
180 Fault func(Op, Step) error
181}
182
183// State is one browser-state directory, owned by this process.
184type State struct {
185 dir string
186 max int
187 fault func(Op, Step) error
188 owner *os.File
189
190 // mu is the read and write lock on the snapshot. snap is nil while
191 // the state does not exist. file is the state file as this process
192 // last wrote or read it, and nil while it does not exist.
193 mu rwLock
194 snap *snapshot
195 file fs.FileInfo
196
197 // broken is why the state is unavailable until the process restarts,
198 // or nil. It is set under either lock on mu, so it has a lock of its
199 // own.
200 brokenMu sync.Mutex
201 broken error
202}
203
204// Open opens the browser-state directory dir and takes its owner lock for
205// the life of the process. It refuses a directory that is a symbolic
206// link, that is not owned by the process's user, or that other users may
207// reach, and one another process owns. It then reads the state file, if
208// there is one, and syncs it and the directory before it serves anything
209// from it. A state file that cannot be read or does not parse leaves the
210// state unavailable: Open still succeeds, and Err says why.
211func Open(dir string, o Options) (*State, error) {
212 abs, err := filepath.Abs(dir)
213 if err != nil {
214 return nil, err
215 }
216 info, err := os.Lstat(abs)
217 if err != nil {
218 return nil, err
219 }
220 switch {
221 case !info.IsDir():
222 return nil, fmt.Errorf("%s is not a directory", abs)
223 case owner(info) != os.Geteuid():
224 return nil, fmt.Errorf("%s is not owned by this process's user", abs)
225 case info.Mode().Perm()&0o077 != 0:
226 return nil, fmt.Errorf("%s is mode %04o; the browser state's directory is its owner's alone, mode 0700", abs, info.Mode().Perm())
227 }
228 f, err := openPrivate(filepath.Join(abs, ownerFile), os.O_RDWR|os.O_CREATE)
229 if err != nil {
230 return nil, err
231 }
232 if err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
233 f.Close()
234 if errors.Is(err, syscall.EWOULDBLOCK) {
235 return nil, fmt.Errorf("another process owns the browser state in %s", abs)
236 }
237 return nil, err
238 }
239 s := &State{dir: abs, max: o.Max, fault: o.Fault, owner: f}
240 if s.max <= 0 {
241 s.max = MaxState
242 }
243 if err := s.load(); err != nil {
244 s.fail(err)
245 }
246 return s, nil
247}
248
249// Close gives back the owner lock. The state is not used after.
250func (s *State) Close() error { return s.owner.Close() }
251
252// Err is why the state is unavailable until the process restarts, or nil.
253func (s *State) Err() error {
254 s.brokenMu.Lock()
255 defer s.brokenMu.Unlock()
256 return s.broken
257}
258
259// fail makes the state unavailable until the process restarts, for err,
260// unless it is so already.
261func (s *State) fail(err error) {
262 s.brokenMu.Lock()
263 defer s.brokenMu.Unlock()
264 if s.broken == nil {
265 s.broken = err
266 }
267}
268
269// Pending reports whether the state does not exist yet and may still be
270// created: Initialize may create it. It takes the read lock, waiting for
271// it until ctx is done, and fails then with ctx's error.
272func (s *State) Pending(ctx context.Context) (bool, error) {
273 if err := s.mu.rlock(ctx); err != nil {
274 return false, fmt.Errorf("waiting to read the browser state: %w", err)
275 }
276 defer s.mu.runlock()
277 return s.snap == nil && s.Err() == nil, nil
278}
279
280// load reads the state file into the snapshot, and makes it durable
281// before the snapshot is used: a document a crash left in the page cache
282// alone is synced before anything is served from it. It deletes a
283// state.new a crash left behind, which it never reads. A state file that
284// does not exist leaves no snapshot.
285func (s *State) load() error {
286 if err := os.Remove(s.path(nextFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
287 return err
288 }
289 f, err := openPrivate(s.path(stateFile), os.O_RDONLY)
290 if errors.Is(err, fs.ErrNotExist) {
291 return syncDir(s.dir)
292 }
293 if err != nil {
294 return err
295 }
296 defer f.Close()
297 data, err := io.ReadAll(io.LimitReader(f, int64(s.max)+1))
298 if err != nil {
299 return err
300 }
301 if len(data) > s.max {
302 return fmt.Errorf("%s is larger than %d bytes", s.path(stateFile), s.max)
303 }
304 snap, err := parse(data)
305 if err != nil {
306 return fmt.Errorf("%s: %w", s.path(stateFile), err)
307 }
308 if err := f.Sync(); err != nil {
309 return err
310 }
311 if err := syncDir(s.dir); err != nil {
312 return err
313 }
314 info, err := os.Lstat(s.path(stateFile))
315 if err != nil {
316 return err
317 }
318 s.snap, s.file = snap, info
319 return nil
320}
321
322// usable is nil when reads may use the snapshot, and ErrUnavailable,
323// wrapped with why, when they may not. It is called with either lock on
324// mu held. A state file that is no longer the one this process last wrote
325// or read, or that appeared while it had none, makes the state
326// unavailable.
327func (s *State) usable() error {
328 if err := s.Err(); err != nil {
329 return fmt.Errorf("%w: %v", ErrUnavailable, err)
330 }
331 if err := s.unchanged(); err != nil {
332 s.fail(err)
333 return fmt.Errorf("%w: %v", ErrUnavailable, err)
334 }
335 if s.snap == nil {
336 return fmt.Errorf("%w: it has not been created", ErrUnavailable)
337 }
338 return nil
339}
340
341// unchanged is nil when the state file is the one this process last
342// wrote or read, or still does not exist when it had none.
343func (s *State) unchanged() error {
344 info, err := os.Lstat(s.path(stateFile))
345 switch {
346 case errors.Is(err, fs.ErrNotExist) && s.file == nil:
347 return nil
348 case errors.Is(err, fs.ErrNotExist):
349 return fmt.Errorf("%s was removed", s.path(stateFile))
350 case err != nil:
351 return err
352 case s.file == nil:
353 return fmt.Errorf("%s was made by another process", s.path(stateFile))
354 case !os.SameFile(info, s.file) || info.Size() != s.file.Size() || !info.ModTime().Equal(s.file.ModTime()) || info.Mode() != s.file.Mode():
355 return fmt.Errorf("%s was replaced or changed by another process", s.path(stateFile))
356 }
357 return nil
358}
359
360// Reading is the state held under its read lock, from Read until Done.
361type Reading struct{ s *State }
362
363// Read takes the state's read lock, waiting for it until ctx is done.
364// Done gives it back.
365func (s *State) Read(ctx context.Context) (Reading, error) {
366 if err := s.mu.rlock(ctx); err != nil {
367 return Reading{}, fmt.Errorf("waiting to read the browser state: %w", err)
368 }
369 return Reading{s}, nil
370}
371
372// Done gives back the read lock Read took.
373func (r Reading) Done() { r.s.mu.runlock() }
374
375// Session is the principal whose valid session token is, under the
376// authorization a: a token whose hash the state holds for its link, while
377// a binds that link to the principal and the verifier it had when it was
378// redeemed. It is "" for a token that names no valid session: malformed,
379// unknown, signed out, or of a link a no longer binds as it was. Its
380// error is ErrUnavailable, wrapped, when the state is not usable.
381func (r Reading) Session(token string, a *export.Authorization) (string, error) {
382 if err := r.s.usable(); err != nil {
383 return "", err
384 }
385 return r.s.snap.session(token, a), nil
386}
387
388// session is the principal of token's valid session under a, or "".
389func (snap *snapshot) session(token string, a *export.Authorization) string {
390 id, ok := tokenID(token)
391 if !ok {
392 return ""
393 }
394 rec, ok := snap.records[id]
395 if !ok || rec.session == "" || !hashMatches(token, rec.session) {
396 return ""
397 }
398 b, ok := binding(a, id)
399 if !ok || b.Principal != rec.principal || b.Verifier != rec.verifier {
400 return ""
401 }
402 return rec.principal
403}
404
405// Hold takes the receiver's serving lock shared, waiting for it until ctx
406// is done, and reads the stored authorization under it. a is nil when no
407// valid authorization is stored. release gives the lock back.
408type Hold func(ctx context.Context) (a *export.Authorization, release func(), err error)
409
410// Initialize creates the empty state, when there is none yet, under an
411// authorization hold reads that carries no binding. It reports whether it
412// created it. It takes the locks a mutation takes and holds the serving
413// lock until the state is durable, so no authorization that carries a
414// binding is stored between its check and its commit. Under an
415// authorization that carries a binding, or none, it creates nothing.
416func (s *State) Initialize(ctx context.Context, hold Hold) (bool, error) {
417 created := false
418 err := s.transact(ctx, hold, Initializing, func(a *export.Authorization, snap *snapshot) (*snapshot, error) {
419 if snap != nil || a == nil || len(a.Bindings) > 0 {
420 return nil, nil
421 }
422 created = true
423 return &snapshot{records: map[string]record{}}, nil
424 })
425 return created && err == nil, err
426}
427
428// Redeem consumes the read link credential, "<credential-id>.<secret>",
429// and starts a session for its principal, under the authorization hold
430// reads. It returns the session token, which the state keeps only as a
431// hash. current is the session token the request carries, or "". A
432// current token that names a valid session fails with ErrSignedIn, before
433// anything is consumed. A link the authorization does not bind, whose
434// secret's SHA-256 is not its verifier, or that was redeemed already,
435// fails with ErrRefused. The link is consumed and its session starts in
436// one transaction, so of two redemptions of one link one alone succeeds.
437func (s *State) Redeem(ctx context.Context, hold Hold, credential, current string) (string, error) {
438 var token string
439 err := s.transact(ctx, hold, Redeeming, func(a *export.Authorization, snap *snapshot) (*snapshot, error) {
440 if snap == nil {
441 return nil, fmt.Errorf("%w: it has not been created", ErrUnavailable)
442 }
443 if current != "" && snap.session(current, a) != "" {
444 return nil, ErrSignedIn
445 }
446 id, secret, ok := parseCredential(credential)
447 if !ok {
448 return nil, ErrRefused
449 }
450 b, bound := binding(a, id)
451 sum := sha256.Sum256(secret)
452 matches := subtle.ConstantTimeCompare([]byte(hex.EncodeToString(sum[:])), []byte(b.Verifier)) == 1
453 if _, used := snap.records[id]; !bound || !matches || used {
454 return nil, ErrRefused
455 }
456 var random [32]byte
457 if _, err := rand.Read(random[:]); err != nil {
458 return nil, err
459 }
460 t := id + "." + base64.RawURLEncoding.EncodeToString(random[:])
461 next := snap.with(record{id: id, principal: b.Principal, verifier: b.Verifier, session: hashOf(t)})
462 if next.size > s.max {
463 return nil, ErrFull
464 }
465 token = t
466 return next, nil
467 })
468 if err != nil {
469 return "", err
470 }
471 return token, nil
472}
473
474// Logout ends the session token names: it removes the token's hash from
475// its link's record, and keeps the record, so the link stays consumed. A
476// token that names no session the state holds changes nothing, and
477// Logout succeeds. It takes the locks every mutation takes.
478func (s *State) Logout(ctx context.Context, hold Hold, token string) error {
479 return s.transact(ctx, hold, SigningOut, func(_ *export.Authorization, snap *snapshot) (*snapshot, error) {
480 if snap == nil {
481 return nil, fmt.Errorf("%w: it has not been created", ErrUnavailable)
482 }
483 id, ok := tokenID(token)
484 if !ok {
485 return nil, nil
486 }
487 rec, ok := snap.records[id]
488 if !ok || rec.session == "" || !hashMatches(token, rec.session) {
489 return nil, nil
490 }
491 rec.session = ""
492 return snap.with(rec), nil
493 })
494}
495
496// transact runs one transaction: it takes the write lock, the transaction
497// lock and the serving lock, in that order, reads the authorization under
498// the last, and gives change the authorization and the snapshot. change
499// returns the next snapshot, or nil for no change. A next snapshot is
500// encoded, written durably and then published. The locks are given back
501// in the reverse order, the serving lock once the next state is
502// published. Each wait ends when ctx is done. Once it holds each lock, and
503// once it has encoded the next document, it stops, with nothing changed,
504// when ctx is done.
505func (s *State) transact(ctx context.Context, hold Hold, op Op, change func(*export.Authorization, *snapshot) (*snapshot, error)) error {
506 if err := s.mu.lock(ctx); err != nil {
507 return fmt.Errorf("waiting to change the browser state: %w", err)
508 }
509 defer s.mu.unlock()
510 if err := ctx.Err(); err != nil {
511 return err
512 }
513 if err := s.Err(); err != nil {
514 return fmt.Errorf("%w: %v", ErrUnavailable, err)
515 }
516 unlock, err := s.lock(ctx)
517 if err != nil {
518 return err
519 }
520 defer unlock()
521 if err := ctx.Err(); err != nil {
522 return err
523 }
524 a, release, err := hold(ctx)
525 if err != nil {
526 return err
527 }
528 defer release()
529 if err := ctx.Err(); err != nil {
530 return err
531 }
532 if err := s.unchanged(); err != nil {
533 s.fail(err)
534 return fmt.Errorf("%w: %v", ErrUnavailable, err)
535 }
536 next, err := change(a, s.snap)
537 if err != nil || next == nil {
538 return err
539 }
540 data := next.encode()
541 err = s.step(op, Encoded)
542 if err == nil {
543 // The last check, before state.new is made. From here on the
544 // transaction finishes, whatever its context.
545 if err := ctx.Err(); err != nil {
546 return err
547 }
548 err = s.commit(op, next, data)
549 }
550 if err != nil {
551 s.fail(fmt.Errorf("a transaction to %s failed, so its outcome is uncertain: %w", op, err))
552 return fmt.Errorf("%w: %v", ErrUnavailable, err)
553 }
554 return nil
555}
556
557// step calls the fault hook, when there is one, at step st of a
558// transaction to op.
559func (s *State) step(op Op, st Step) error {
560 if s.fault != nil {
561 return s.fault(op, st)
562 }
563 return nil
564}
565
566// commit writes data, next's document, durably and publishes next,
567// calling the fault hook at each step from Created on. Its caller holds
568// the write lock and the transaction lock.
569func (s *State) commit(op Op, next *snapshot, data []byte) error {
570 step := func(st Step) error { return s.step(op, st) }
571 tmp := s.path(nextFile)
572 f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0o600)
573 if err != nil {
574 return err
575 }
576 err = f.Chmod(0o600)
577 if err == nil {
578 err = step(Created)
579 }
580 if err == nil {
581 _, err = f.Write(data)
582 }
583 if err == nil {
584 err = step(Written)
585 }
586 if err == nil {
587 err = f.Sync()
588 }
589 if err == nil {
590 err = step(Synced)
591 }
592 if cerr := f.Close(); err == nil {
593 err = cerr
594 }
595 if err == nil {
596 err = os.Rename(tmp, s.path(stateFile))
597 }
598 if err != nil {
599 os.Remove(tmp)
600 return err
601 }
602 if err := step(Renamed); err != nil {
603 return err
604 }
605 if err := syncDir(s.dir); err != nil {
606 return err
607 }
608 if err := step(Committed); err != nil {
609 return err
610 }
611 info, err := os.Lstat(s.path(stateFile))
612 if err != nil {
613 return err
614 }
615 s.snap, s.file = next, info
616 return step(Published)
617}
618
619// lock takes the transaction lock, waiting for it until ctx is done.
620func (s *State) lock(ctx context.Context) (func(), error) {
621 f, err := openPrivate(s.path(lockFile), os.O_RDWR|os.O_CREATE)
622 if err != nil {
623 return nil, err
624 }
625 for pause := time.Millisecond; ; pause = min(2*pause, 50*time.Millisecond) {
626 err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB)
627 if err == nil {
628 return func() { f.Close() }, nil
629 }
630 if !errors.Is(err, syscall.EWOULDBLOCK) {
631 f.Close()
632 return nil, err
633 }
634 select {
635 case <-time.After(pause):
636 case <-ctx.Done():
637 f.Close()
638 return nil, fmt.Errorf("waiting for %s: %w", s.path(lockFile), ctx.Err())
639 }
640 }
641}
642
643func (s *State) path(name string) string { return filepath.Join(s.dir, name) }
644
645// rwLock is the snapshot's read and write lock. Unlike sync.RWMutex, a
646// wait for it ends when its context is done. A writer that waits for it
647// holds back the readers that come after, so readers never keep a
648// transaction waiting. Its zero value is unlocked.
649type rwLock struct {
650 mu sync.Mutex
651 readers int // the readers that hold it
652 writer bool // whether a writer holds it
653 waiting int // the writers that wait for it
654 // changed is closed, and then made again, each time the lock is given
655 // back or a writer stops waiting, so every waiter looks again.
656 changed chan struct{}
657}
658
659// lock takes l to write, waiting until ctx is done. It may take l when
660// ctx is done already: its caller checks ctx once it holds l.
661func (l *rwLock) lock(ctx context.Context) error {
662 l.mu.Lock()
663 defer l.mu.Unlock()
664 l.waiting++
665 defer func() { l.waiting-- }()
666 for l.writer || l.readers > 0 {
667 if err := l.wait(ctx); err != nil {
668 l.signal()
669 return err
670 }
671 }
672 l.writer = true
673 return nil
674}
675
676func (l *rwLock) unlock() {
677 l.mu.Lock()
678 defer l.mu.Unlock()
679 l.writer = false
680 l.signal()
681}
682
683// rlock takes l to read, waiting until ctx is done, while a writer holds
684// it or waits for it.
685func (l *rwLock) rlock(ctx context.Context) error {
686 l.mu.Lock()
687 defer l.mu.Unlock()
688 for l.writer || l.waiting > 0 {
689 if err := l.wait(ctx); err != nil {
690 return err
691 }
692 }
693 l.readers++
694 return nil
695}
696
697func (l *rwLock) runlock() {
698 l.mu.Lock()
699 defer l.mu.Unlock()
700 if l.readers--; l.readers == 0 {
701 l.signal()
702 }
703}
704
705// wait gives back l.mu until the lock changes or ctx is done, and then
706// takes it again.
707func (l *rwLock) wait(ctx context.Context) error {
708 if l.changed == nil {
709 l.changed = make(chan struct{})
710 }
711 changed := l.changed
712 l.mu.Unlock()
713 defer l.mu.Lock()
714 select {
715 case <-changed:
716 return nil
717 case <-ctx.Done():
718 return ctx.Err()
719 }
720}
721
722// signal wakes every waiter. It is called with l.mu held.
723func (l *rwLock) signal() {
724 if l.changed != nil {
725 close(l.changed)
726 l.changed = nil
727 }
728}
729
730// record is one redeemed link: its binding as it was redeemed, and the
731// hex SHA-256 of its session's token, or "" once its reader signed out.
732type record struct {
733 id, principal, verifier, session string
734}
735
736// snapshot is one state document, decoded, and its encoded size. A
737// snapshot never changes once it is published: a transaction makes a new
738// one.
739type snapshot struct {
740 records map[string]record
741 size int
742}
743
744// with is a copy of snap with rec in place of the record of its ID.
745func (snap *snapshot) with(rec record) *snapshot {
746 next := &snapshot{records: make(map[string]record, len(snap.records)+1)}
747 for id, r := range snap.records {
748 next.records[id] = r
749 }
750 next.records[rec.id] = rec
751 next.size = len(next.encode())
752 return next
753}
754
755// encode is snap's document: the type line, then each record in ID order.
756func (snap *snapshot) encode() []byte {
757 ids := make([]string, 0, len(snap.records))
758 for id := range snap.records {
759 ids = append(ids, id)
760 }
761 sort.Strings(ids)
762 var b bytes.Buffer
763 b.WriteString(Type + "\n")
764 for _, id := range ids {
765 r := snap.records[id]
766 session := r.session
767 if session == "" {
768 session = "-"
769 }
770 fmt.Fprintf(&b, "link %s %s %s %s\n", r.id, r.principal, r.verifier, session)
771 }
772 return b.Bytes()
773}
774
775// parse reads a state document: the type line, then records in strictly
776// increasing ID order, each exactly a link record's five fields, and the
777// document ends with a newline.
778func parse(data []byte) (*snapshot, error) {
779 if len(data) == 0 || data[len(data)-1] != '\n' {
780 return nil, errors.New("a browser-state document ends with a newline")
781 }
782 lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
783 if lines[0] != Type {
784 return nil, fmt.Errorf("the document opens with %q, not %q", lines[0], Type)
785 }
786 snap := &snapshot{records: map[string]record{}, size: len(data)}
787 last := ""
788 for i, line := range lines[1:] {
789 f := strings.Split(line, " ")
790 if len(f) != 5 || f[0] != "link" {
791 return nil, fmt.Errorf("line %d is not a link record", i+2)
792 }
793 r := record{id: f[1], principal: f[2], verifier: f[3], session: f[4]}
794 if r.session == "-" {
795 r.session = ""
796 }
797 switch {
798 case !export.ValidLinkID(r.id) || r.id <= last:
799 return nil, fmt.Errorf("line %d names no credential ID after the one before it", i+2)
800 case !export.ValidName(r.principal) || r.principal == export.Anyone:
801 return nil, fmt.Errorf("line %d names no principal", i+2)
802 case !export.ValidVerifier(r.verifier):
803 return nil, fmt.Errorf("line %d holds no verifier", i+2)
804 case r.session != "" && !export.ValidVerifier(r.session):
805 return nil, fmt.Errorf("line %d holds no session hash", i+2)
806 }
807 last = r.id
808 snap.records[r.id] = r
809 }
810 return snap, nil
811}
812
813// binding is the binding a gives the credential id.
814func binding(a *export.Authorization, id string) (export.Binding, bool) {
815 if a == nil {
816 return export.Binding{}, false
817 }
818 i := sort.Search(len(a.Bindings), func(i int) bool { return a.Bindings[i].ID >= id })
819 if i < len(a.Bindings) && a.Bindings[i].ID == id {
820 return a.Bindings[i], true
821 }
822 return export.Binding{}, false
823}
824
825// parseCredential splits a link's credential, "<credential-id>.<secret>",
826// and decodes its secret: canonical unpadded base64url of 32 bytes.
827func parseCredential(credential string) (id string, secret []byte, ok bool) {
828 id, encoded, found := strings.Cut(credential, ".")
829 if !found || !export.ValidLinkID(id) {
830 return "", nil, false
831 }
832 secret, ok = random32(encoded)
833 return id, secret, ok
834}
835
836// tokenID is the credential ID of a session token, "<credential-id>.<random>",
837// whose random part is canonical unpadded base64url of 32 bytes.
838func tokenID(token string) (string, bool) {
839 id, _, ok := parseCredential(token)
840 return id, ok
841}
842
843// random32 decodes s, canonical unpadded base64url of 32 bytes.
844func random32(s string) ([]byte, bool) {
845 b, err := base64.RawURLEncoding.Strict().DecodeString(s)
846 if err != nil || len(b) != 32 || base64.RawURLEncoding.EncodeToString(b) != s {
847 return nil, false
848 }
849 return b, true
850}
851
852// hashOf is the lowercase hex SHA-256 of a session token.
853func hashOf(token string) string {
854 sum := sha256.Sum256([]byte(token))
855 return hex.EncodeToString(sum[:])
856}
857
858// hashMatches compares a token's hash with a stored one in constant time.
859func hashMatches(token, stored string) bool {
860 return subtle.ConstantTimeCompare([]byte(hashOf(token)), []byte(stored)) == 1
861}
862
863// openPrivate opens the file at path, refusing a symbolic link and
864// anything that is not a regular file. A file opened for writing is made
865// mode 0600, and one opened for reading alone is refused when other users
866// may read it. A file opened for reading is opened without blocking, so a
867// FIFO put in its place cannot stall it.
868func openPrivate(path string, flag int) (*os.File, error) {
869 flag |= syscall.O_NOFOLLOW | syscall.O_CLOEXEC
870 if flag&(os.O_WRONLY|os.O_RDWR) == 0 {
871 flag |= syscall.O_NONBLOCK
872 }
873 f, err := os.OpenFile(path, flag, 0o600)
874 if errors.Is(err, syscall.ELOOP) {
875 return nil, fmt.Errorf("%s is a symbolic link", path)
876 }
877 if err != nil {
878 return nil, err
879 }
880 info, err := f.Stat()
881 switch {
882 case err != nil:
883 case !info.Mode().IsRegular():
884 err = fmt.Errorf("%s is not a regular file", path)
885 case flag&os.O_RDWR != 0:
886 err = f.Chmod(0o600)
887 case info.Mode().Perm()&0o077 != 0:
888 err = fmt.Errorf("%s is mode %04o; the browser state's files are their owner's alone, mode 0600", path, info.Mode().Perm())
889 }
890 if err != nil {
891 f.Close()
892 return nil, err
893 }
894 return f, nil
895}
896
897// owner is the user ID that owns the file info describes.
898func owner(info fs.FileInfo) int {
899 if st, ok := info.Sys().(*syscall.Stat_t); ok {
900 return int(st.Uid)
901 }
902 return -1
903}
904
905// syncDir syncs the directory at path, so its entries are durable.
906func syncDir(path string) error {
907 f, err := os.Open(path)
908 if err != nil {
909 return err
910 }
911 defer f.Close()
912 return f.Sync()
913}
914
915// flock takes a lock on f's open file description, which closing f
916// releases.
917func flock(f *os.File, how int) error {
918 for {
919 err := syscall.Flock(int(f.Fd()), how)
920 if !errors.Is(err, syscall.EINTR) {
921 return err
922 }
923 }
924}