-
Notifications
You must be signed in to change notification settings - Fork 0
/
nonce.go
46 lines (32 loc) · 1.39 KB
/
nonce.go
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
package httpsig
import (
"context"
"crypto/rand"
"encoding/base64"
)
//go:generate mockery --name NonceGetter --structname NonceGetterMock --inpackage --testonly
// NonceGetter represents a source of random nonces to go into resulting objects.
type NonceGetter interface {
GetNonce(ctx context.Context) (string, error)
}
type NonceGetterFunc func(ctx context.Context) (string, error)
func (ng NonceGetterFunc) GetNonce(ctx context.Context) (string, error) { return ng(ctx) }
//go:generate mockery --name NonceChecker --structname NonceCheckerMock --inpackage --testonly
// NonceChecker is responsible for the verification of the nonce received in a signature,
// e.g. to prevent replay attacks, or to verify that the nonce is the expected one, like
// if requested using the Accept-Signature header.
type NonceChecker interface {
CheckNonce(ctx context.Context, nonce string) error
}
type NonceCheckerFunc func(ctx context.Context, nonce string) error
func (nc NonceCheckerFunc) GetNonce(ctx context.Context, nonce string) error { return nc(ctx, nonce) }
type noopNonceChecker struct{}
func (n noopNonceChecker) CheckNonce(_ context.Context, _ string) error { return nil }
type nonceGetter struct{}
func (n nonceGetter) GetNonce(_ context.Context) (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b), nil
}