-
Notifications
You must be signed in to change notification settings - Fork 2
/
keyset.go
198 lines (162 loc) · 4.73 KB
/
keyset.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package xkeyset
import (
"context"
"encoding/json"
"net/http"
"sync/atomic"
"time"
"fmt"
"io/ioutil"
opentracing "github.com/opentracing/opentracing-go"
otext "github.com/opentracing/opentracing-go/ext"
"github.com/pquerna/cachecontrol"
"golang.org/x/net/context/ctxhttp"
jose "gopkg.in/square/go-jose.v2"
)
const (
xjwtOpenTracingTag = "com.scaleft.xjwt"
)
type Options struct {
UserAgent string
URL string
Client *http.Client
MinCacheDuration time.Duration
MaxCacheDuration time.Duration
RefreshWarning func(err error)
// RefreshContext is used during background refreshing of the Keyset. If unset, context.Background() is used.
RefreshContext context.Context
}
// New creates a JSON Keyset that is cached in memory.
//
// On creation, it will do a block HTTP request to load the initial keyset.
//
// After initial load, it will refresh the cached keyset, any consumers may see
// older versions of the cache until the refresh is complete.
//
// New emits opentracing spans on the supplied context when fetching the keyset.
func New(initCtx context.Context, opts Options) (*RemoteKeyset, error) {
rctx := opts.RefreshContext
if rctx == nil {
rctx = context.Background()
}
rctx, cfunc := context.WithCancel(rctx)
rk := &RemoteKeyset{
ctx: rctx,
cfunc: cfunc,
opts: opts,
client: opts.Client,
}
if rk.client == nil {
rk.client = &http.Client{
Timeout: time.Second * 30,
}
}
if rk.opts.MinCacheDuration == 0 {
rk.opts.MinCacheDuration = time.Minute * 5
}
if rk.opts.MaxCacheDuration == 0 {
rk.opts.MaxCacheDuration = time.Hour * 12
}
if rk.opts.RefreshWarning == nil {
rk.opts.RefreshWarning = func(err error) {}
}
err := rk.init(initCtx)
if err != nil {
return nil, err
}
return rk, nil
}
type RemoteKeyset struct {
opts Options
ctx context.Context
cfunc context.CancelFunc
client *http.Client
now func() time.Time
current atomic.Value
}
func (rk *RemoteKeyset) init(ctx context.Context) error {
rk.current.Store(&jose.JSONWebKeySet{})
rv, refresh, err := rk.fetchKeyset(ctx)
if err != nil {
return err
}
rk.current.Store(rv)
go rk.refreshKeySet(refresh)
return nil
}
func (rk *RemoteKeyset) refreshKeySet(refresh time.Duration) {
select {
case <-rk.ctx.Done():
return
case <-time.After(refresh):
rv, d, err := rk.fetchKeyset(rk.ctx)
if err != nil {
rk.opts.RefreshWarning(err)
go rk.refreshKeySet(refresh)
return
}
rk.current.Store(rv)
go rk.refreshKeySet(d)
return
}
}
func (rk *RemoteKeyset) fetchKeyset(ctx context.Context) (*jose.JSONWebKeySet, time.Duration, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30)
defer cancel()
req, err := http.NewRequest("GET", rk.opts.URL, nil)
if err != nil {
return nil, time.Duration(0), err
}
req.Header.Set("Accept", "application/json")
if rk.opts.UserAgent != "" {
req.Header.Set("User-Agent", rk.opts.UserAgent)
} else {
req.Header.Set("User-Agent", "xjwt-keyset.go/0.1.0")
}
sp, ctx := opentracing.StartSpanFromContext(ctx, "xjwt.keyset.fetch")
otext.Component.Set(sp, xjwtOpenTracingTag)
otext.SpanKind.Set(sp, otext.SpanKindRPCClientEnum)
otext.HTTPUrl.Set(sp, req.URL.String())
otext.HTTPMethod.Set(sp, req.Method)
defer sp.Finish()
resp, err := ctxhttp.Do(ctx, rk.client, req)
if err != nil {
otext.Error.Set(sp, true)
return nil, time.Duration(0), err
}
otext.HTTPStatusCode.Set(sp, uint16(resp.StatusCode))
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return rk.parseResponse(req, resp)
}
return nil, time.Duration(0), fmt.Errorf("xjwt.keyset: Fetch returned HTTP Status Code '%d' for '%s'", resp.StatusCode, rk.opts.URL)
}
func (rk *RemoteKeyset) parseResponse(req *http.Request, resp *http.Response) (*jose.JSONWebKeySet, time.Duration, error) {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, time.Duration(0), fmt.Errorf("xjwt.keyset: Error reading response '%s': %v", rk.opts.URL, err)
}
rv := &jose.JSONWebKeySet{}
err = json.Unmarshal(data, rv)
if err != nil {
return nil, time.Duration(0), fmt.Errorf("xjwt.keyset: Error parsing response '%s': %v", rk.opts.URL, err)
}
_, cacheExpires, err := cachecontrol.CachableResponse(req, resp, cachecontrol.Options{})
if err != nil {
return nil, time.Duration(0), fmt.Errorf("xjwt.keyset: Error parsing cache control header '%s': %v", rk.opts.URL, err)
}
n := time.Now()
exp := cacheExpires.Sub(n)
if exp > rk.opts.MaxCacheDuration {
return rv, rk.opts.MaxCacheDuration, nil
} else if exp < rk.opts.MinCacheDuration {
return rv, rk.opts.MinCacheDuration, nil
}
return rv, exp, nil
}
func (rk *RemoteKeyset) Get() (*jose.JSONWebKeySet, error) {
return rk.current.Load().(*jose.JSONWebKeySet), nil
}
func (rk *RemoteKeyset) Close() {
rk.cfunc()
}