-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokens.go
263 lines (220 loc) · 6.25 KB
/
tokens.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Copyright (c) 2023 The Go-Enjin Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tokens
import (
"time"
"github.com/urfave/cli/v2"
sha "github.com/go-corelibs/shasum"
"github.com/go-enjin/be/pkg/crypto"
"github.com/go-enjin/be/pkg/feature"
uses_kvc "github.com/go-enjin/be/pkg/feature/uses-kvc"
"github.com/go-enjin/be/pkg/kvs"
"github.com/go-enjin/be/pkg/log"
"github.com/go-enjin/be/pkg/maps"
)
var (
DefaultNumRandomBytes int = 128
DefaultDuration time.Duration = time.Minute * 10
)
var (
_ Feature = (*CFeature)(nil)
_ MakeFeature = (*CFeature)(nil)
)
const Tag feature.Tag = "srv-factory-tokens"
type Feature interface {
feature.Feature
feature.TokenFactoryFeature
}
type MakeFeature interface {
uses_kvc.MakeFeature[MakeFeature]
SetDuration(duration time.Duration) MakeFeature
SetNumRandomBytes(size int) MakeFeature
Make() Feature
}
type CFeature struct {
feature.CFeature
uses_kvc.CUsesKVC[MakeFeature]
numRandomBytes int
duration time.Duration
tokens map[string]map[string]time.Time
}
func New() MakeFeature {
return NewTagged(Tag)
}
func NewTagged(tag feature.Tag) MakeFeature {
f := new(CFeature)
f.Init(f)
f.PackageTag = Tag
f.FeatureTag = tag
f.CFeature.Construct(f)
return f
}
func (f *CFeature) Init(this interface{}) {
f.CFeature.Init(this)
f.CUsesKVC.InitUsesKVC(this)
f.tokens = make(map[string]map[string]time.Time)
f.numRandomBytes = DefaultNumRandomBytes
f.duration = DefaultDuration
return
}
func (f *CFeature) SetDuration(duration time.Duration) MakeFeature {
if duration.Seconds() < 60 {
log.FatalDF(1, "minimum duration required is 1m, default is %v", DefaultDuration)
}
f.duration = duration
return f
}
func (f *CFeature) SetNumRandomBytes(size int) MakeFeature {
if size <= 7 {
log.FatalDF(1, "minimum bytes required is 8, default is %d", DefaultNumRandomBytes)
}
f.numRandomBytes = size
return f
}
func (f *CFeature) Make() (feat Feature) {
return f
}
func (f *CFeature) Build(b feature.Buildable) (err error) {
if err = f.CFeature.Build(b); err != nil {
return
} else if err = f.CUsesKVC.BuildUsesKVC(); err != nil {
return
}
return
}
func (f *CFeature) Startup(ctx *cli.Context) (err error) {
if err = f.CFeature.Startup(ctx); err != nil {
return
} else if err = f.CUsesKVC.StartupUsesKVC(f.Enjin.Features()); err != nil {
return
}
return
}
func (f *CFeature) makeKey(k string) (key string) {
key = f.KebabTag + "__" + k
return
}
func (f *CFeature) randomValue() (value string) {
var err error
if value, err = crypto.RandomValue(f.numRandomBytes); err != nil {
log.ErrorF("crypto.RandomValue error: %v", err)
}
return
}
func (f *CFeature) expire() {
f.Lock()
defer f.Unlock()
now := time.Now()
prune := make(map[string][]string)
for key, values := range f.tokens {
for value, expiration := range values {
if now.After(expiration) {
prune[key] = append(prune[key], value)
}
}
}
for key, values := range prune {
for _, value := range values {
delete(f.tokens[key], value)
if bucket, err := f.KVC().Bucket(key); err == nil {
_ = bucket.Delete(value)
}
}
}
}
func (f *CFeature) verify(key, value string) (valid bool) {
f.expire()
f.Lock()
defer f.Unlock()
var err error
var expiration time.Time
var tokenBucket, aliasBucket feature.KeyValueStore
aliasKey := sha.MustBriefSum(key)
if tokenBucket, err = f.KVC().Bucket(key); err != nil {
// TODO: is this a case to panic or just trace ignore?
//panic(err)
//log.TraceF("error getting token bucket for key: %q - %v", key, err)
return
} else if aliasBucket, err = f.KVC().Bucket(aliasKey); err != nil {
// TODO: is this a case to panic or just trace ignore?
//panic(err)
//log.TraceF("error getting alias bucket for key: %q - %v", key, err)
return
}
var shasum string
if sha.Valid(value) {
// use the value as the shasum and get the value from the kvs
shasum = value
if err = kvs.GetUnmarshal(aliasBucket, shasum, &value); err != nil {
// not a valid token alias and nothing to clean up
return
} else if value == "" {
// shasum exists but it's empty
_ = aliasBucket.Delete(shasum)
return
}
} else {
shasum = sha.MustBriefSum(value)
}
defer func() {
delete(f.tokens[key], value)
_ = tokenBucket.Delete(value)
_ = aliasBucket.Delete(shasum)
}()
if err = kvs.GetUnmarshal(tokenBucket, value, &expiration); err == nil {
valid = time.Now().Before(expiration)
}
return
}
func (f *CFeature) get(key string, duration time.Duration) (value, shasum string) {
f.expire()
f.Lock()
defer f.Unlock()
if duration < 1 {
duration = f.duration
}
aliasKey := sha.MustBriefSum(key)
var err error
var tokenBucket, aliasBucket feature.KeyValueStore
if tokenBucket, err = f.KVC().Bucket(key); err != nil {
panic(err)
} else if aliasBucket, err = f.KVC().Bucket(aliasKey); err != nil {
panic(err)
}
value = f.randomValue()
shasum = sha.MustBriefSum(value)
maps.MakeTypedKey(key, f.tokens)
f.tokens[key][value] = time.Now().Add(duration)
if err = kvs.SetMarshal(tokenBucket, value, f.tokens[key][value]); err != nil {
panic(err)
} else if err = kvs.SetMarshal(aliasBucket, shasum, value); err != nil {
panic(err)
}
return
}
// VerifyToken will validate and evict the given nonce value
func (f *CFeature) VerifyToken(key, value string) (valid bool) {
valid = f.verify(f.makeKey(key), value)
return
}
// CreateToken will add a new nonce associated with the given key
func (f *CFeature) CreateToken(key string) (value, shasum string) {
value, shasum = f.get(f.makeKey(key), f.duration)
return
}
// CreateTokenWith will add a new token with the given duration, associated with the given key
func (f *CFeature) CreateTokenWith(key string, duration time.Duration) (value, shasum string) {
value, shasum = f.get(f.makeKey(key), duration)
return
}