File size: 2,119 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package nonce

import (
	"context"
	"database/sql"
	"time"

	"github.com/target/goalert/util"
	"github.com/target/goalert/util/log"

	"github.com/google/uuid"
	"github.com/pkg/errors"
)

// Store allows generating and consuming nonce values.
type Store struct {
	logger   *log.Logger
	db       *sql.DB
	shutdown chan context.Context

	consume *sql.Stmt
	cleanup *sql.Stmt
}

// NewStore prepares a new Store.
func NewStore(ctx context.Context, logger *log.Logger, db *sql.DB) (*Store, error) {
	p := &util.Prepare{DB: db, Ctx: ctx}

	d := &Store{
		logger:   logger,
		db:       db,
		shutdown: make(chan context.Context),

		consume: p.P(`
			insert into auth_nonce (id)
			values ($1)
			on conflict do nothing
		`),
		cleanup: p.P(`
			delete from auth_nonce
			where created_at < now() - '1 week'::interval
		`),
	}
	if p.Err != nil {
		return nil, p.Err
	}
	go d.loop()

	return d, nil
}

func (s *Store) loop() {
	defer close(s.shutdown)
	t := time.NewTicker(time.Hour * 24)
	defer t.Stop()
	ctx := s.logger.BackgroundContext()
	for {
		select {
		case <-t.C:
			_, err := s.cleanup.ExecContext(ctx)
			if err != nil {
				log.Log(ctx, errors.Wrap(err, "cleanup old nonce values"))
			}
		case <-s.shutdown:
			return
		}
	}
}

// Shutdown allows gracefully shutting down the nonce store.
func (s *Store) Shutdown(ctx context.Context) error {
	if s == nil {
		return nil
	}
	s.shutdown <- ctx

	// wait for it to complete
	<-s.shutdown
	return nil
}

// New will generate a new cryptographically random nonce value.
func (s *Store) New() [16]byte { return uuid.New() }

// Consume will record the use of a nonce value.
//
// An error is returned if it is not possible to validate the nonce value.
// Otherwise true/false is returned to indicate if the id is valid.
//
// The first call to Consume for a given ID will return true, subsequent calls
// for the same ID will return false.
func (s *Store) Consume(ctx context.Context, id [16]byte) (bool, error) {
	res, err := s.consume.ExecContext(ctx, uuid.UUID(id).String())
	if err != nil {
		return false, err
	}
	n, _ := res.RowsAffected()
	return n == 1, nil
}