forked from zitadel/oidc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signer.go
88 lines (76 loc) · 1.66 KB
/
signer.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
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
package op
import (
"context"
"errors"
"sync"
"github.com/zitadel/logging"
"gopkg.in/square/go-jose.v2"
)
type Signer interface {
Health(ctx context.Context) error
Signer() jose.Signer
SignatureAlgorithm() jose.SignatureAlgorithm
}
type tokenSigner struct {
signer jose.Signer
storage AuthStorage
alg jose.SignatureAlgorithm
lock sync.RWMutex
}
func NewSigner(ctx context.Context, storage AuthStorage, keyCh <-chan jose.SigningKey) Signer {
s := &tokenSigner{
storage: storage,
}
select {
case <-ctx.Done():
return nil
case key := <-keyCh:
s.exchangeSigningKey(key)
}
go s.refreshSigningKey(ctx, keyCh)
return s
}
func (s *tokenSigner) Health(_ context.Context) error {
if s.signer == nil {
return errors.New("no signer")
}
if string(s.alg) == "" {
return errors.New("no signing algorithm")
}
return nil
}
func (s *tokenSigner) Signer() jose.Signer {
s.lock.RLock()
defer s.lock.RUnlock()
return s.signer
}
func (s *tokenSigner) refreshSigningKey(ctx context.Context, keyCh <-chan jose.SigningKey) {
for {
select {
case <-ctx.Done():
return
case key := <-keyCh:
s.exchangeSigningKey(key)
}
}
}
func (s *tokenSigner) exchangeSigningKey(key jose.SigningKey) {
s.lock.Lock()
defer s.lock.Unlock()
s.alg = key.Algorithm
if key.Algorithm == "" || key.Key == nil {
s.signer = nil
logging.Warn("signer has no key")
return
}
var err error
s.signer, err = jose.NewSigner(key, &jose.SignerOptions{})
if err != nil {
logging.New().WithError(err).Error("error creating signer")
return
}
logging.Info("signer exchanged signing key")
}
func (s *tokenSigner) SignatureAlgorithm() jose.SignatureAlgorithm {
return s.alg
}