-
Notifications
You must be signed in to change notification settings - Fork 14
/
options.go
352 lines (291 loc) · 8.71 KB
/
options.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
// package rkmidauth provide auth related options
package rkmidauth
import (
"encoding/base64"
"errors"
"fmt"
"github.com/rookie-ninja/rk-common/error"
"github.com/rookie-ninja/rk-entry/middleware"
"github.com/rs/xid"
"net/http"
"strings"
)
const (
authTypeBasic = "Basic"
)
// ***************** OptionSet Interface *****************
// OptionSetInterface mainly for testing purpose
type OptionSetInterface interface {
GetEntryName() string
GetEntryType() string
Before(*BeforeCtx)
BeforeCtx(*http.Request) *BeforeCtx
}
// ***************** OptionSet Implementation *****************
// optionSet which is used for middleware implementation
type optionSet struct {
entryName string
entryType string
basicRealm string
basicAccounts map[string]bool
apiKey map[string]bool
ignorePrefix []string
mock OptionSetInterface
}
// NewOptionSet Create new optionSet with options.
func NewOptionSet(opts ...Option) OptionSetInterface {
set := &optionSet{
entryName: xid.New().String(),
entryType: "",
basicRealm: "",
basicAccounts: make(map[string]bool),
apiKey: make(map[string]bool),
ignorePrefix: []string{},
}
for i := range opts {
opts[i](set)
}
if set.mock != nil {
return set.mock
}
return set
}
// GetEntryName returns entry name
func (set *optionSet) GetEntryName() string {
return set.entryName
}
// GetEntryType returns entry type
func (set *optionSet) GetEntryType() string {
return set.entryType
}
// BeforeCtx should be created before Before()
func (set *optionSet) BeforeCtx(req *http.Request) *BeforeCtx {
ctx := NewBeforeCtx()
if req != nil && req.URL != nil && req.Header != nil {
ctx.Input.UrlPath = req.URL.Path
ctx.Input.BasicAuthHeader = req.Header.Get(rkmid.HeaderAuthorization)
ctx.Input.ApiKeyHeader = req.Header.Get(rkmid.HeaderApiKey)
}
return ctx
}
// Before should run before user handler
func (set *optionSet) Before(ctx *BeforeCtx) {
// normalize
if ctx == nil {
ctx.Output.ErrResp = rkerror.New(rkerror.WithDetails(errors.New("nil context")))
return
}
// case 0: ignore path
if set.ignore(ctx.Input.UrlPath) {
return
}
// case 1: basic auth passed
errBasic := set.isBasicAuthorized(ctx)
if errBasic == nil {
return
}
// case 2: X-API-Key passed
errApiKey := set.isApiKeyAuthorized(ctx)
if errApiKey == nil {
return
}
// case 3: basic auth provided, then return code and response related to basic auth
if len(ctx.Input.BasicAuthHeader) > 0 {
ctx.Output.ErrResp = errBasic
return
}
// case 4: X-API-Key provided, then return code and response related to X-API-Key
if len(ctx.Input.ApiKeyHeader) > 0 {
ctx.Output.ErrResp = errApiKey
return
}
// case 5: no auth provided, return bellow code and response
tmp := make([]string, 0)
// case 5.1: basic auth needed
if len(set.basicAccounts) > 0 {
ctx.Output.HeadersToReturn["WWW-Authenticate"] = fmt.Sprintf(`%s realm="%s"`, authTypeBasic, set.basicRealm)
tmp = append(tmp, "Basic Auth")
}
// case 5.2: X-API-Key needed
if len(set.apiKey) > 0 {
tmp = append(tmp, "X-API-Key")
}
ctx.Output.ErrResp = rkerror.New(
rkerror.WithHttpCode(http.StatusUnauthorized),
rkerror.WithMessage(fmt.Sprintf("missing authorization, provide one of bellow auth header:[%s]", strings.Join(tmp, ","))))
}
// Ignore determine whether auth should be ignored based on path
func (set *optionSet) ignore(path string) bool {
if len(set.basicAccounts) < 1 && len(set.apiKey) < 1 {
return true
}
for i := range set.ignorePrefix {
if strings.HasPrefix(path, set.ignorePrefix[i]) {
return true
}
}
return rkmid.IgnorePrefixGlobal(path)
}
// Validate basic auth
func (set *optionSet) isBasicAuthorized(ctx *BeforeCtx) *rkerror.ErrorResp {
// case 1: auth header is provided
if len(ctx.Input.BasicAuthHeader) > 0 {
tokens := strings.SplitN(ctx.Input.BasicAuthHeader, " ", 2)
// case 1.1: invalid basic auth
if len(tokens) != 2 {
return rkerror.New(
rkerror.WithHttpCode(http.StatusUnauthorized),
rkerror.WithMessage("Invalid Basic Auth format"))
}
// case 1.2: not authorized
_, ok := set.basicAccounts[tokens[1]]
if !ok {
if tokens[0] == authTypeBasic {
ctx.Output.HeadersToReturn["WWW-Authenticate"] = fmt.Sprintf(`%s realm="%s"`, authTypeBasic, set.basicRealm)
}
return rkerror.New(
rkerror.WithHttpCode(http.StatusUnauthorized),
rkerror.WithMessage("Invalid credential"))
}
// case 1.3: authorized
return nil
}
// case 2: auth header missing
return rkerror.New(
rkerror.WithHttpCode(http.StatusUnauthorized),
rkerror.WithMessage("missing authorization header"))
}
// Validate X-API-Key
func (set *optionSet) isApiKeyAuthorized(ctx *BeforeCtx) *rkerror.ErrorResp {
// case 1: auth header is provided
if len(ctx.Input.ApiKeyHeader) > 0 {
// case 1.1: not authorized
_, ok := set.apiKey[ctx.Input.ApiKeyHeader]
if !ok {
return rkerror.New(
rkerror.WithHttpCode(http.StatusUnauthorized),
rkerror.WithMessage("Invalid X-API-Key"))
}
// case 1.2: authorized
return nil
}
// case 2: auth header missing
return rkerror.New(
rkerror.WithHttpCode(http.StatusUnauthorized),
rkerror.WithMessage("missing authorization header"))
}
// ***************** OptionSet Mock *****************
// NewOptionSetMock for testing purpose
func NewOptionSetMock(before *BeforeCtx) OptionSetInterface {
return &optionSetMock{
before: before,
}
}
type optionSetMock struct {
before *BeforeCtx
}
// GetEntryName returns entry name
func (mock *optionSetMock) GetEntryName() string {
return "mock"
}
// GetEntryType returns entry type
func (mock *optionSetMock) GetEntryType() string {
return "mock"
}
// BeforeCtx should be created before Before()
func (mock *optionSetMock) BeforeCtx(request *http.Request) *BeforeCtx {
return mock.before
}
// Before should run before user handler
func (mock *optionSetMock) Before(ctx *BeforeCtx) {
return
}
// ***************** Context *****************
// NewBeforeCtx create new BeforeCtx with fields initialized
func NewBeforeCtx() *BeforeCtx {
ctx := &BeforeCtx{}
ctx.Output.HeadersToReturn = make(map[string]string)
return ctx
}
// BeforeCtx context for Before() function
type BeforeCtx struct {
Input struct {
BasicAuthHeader string
ApiKeyHeader string
UrlPath string
}
Output struct {
HeadersToReturn map[string]string
ErrResp *rkerror.ErrorResp
}
}
// ***************** BootConfig *****************
// BootConfig for YAML
type BootConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
IgnorePrefix []string `yaml:"ignorePrefix" json:"ignorePrefix"`
Basic []string `yaml:"basic" json:"basic"`
ApiKey []string `yaml:"apiKey" json:"apiKey"`
}
// ToOptions convert BootConfig into Option list
func ToOptions(config *BootConfig, entryName, entryType string) []Option {
opts := make([]Option, 0)
if config.Enabled {
opts = append(opts,
WithEntryNameAndType(entryName, entryType),
WithBasicAuth(entryName, config.Basic...),
WithApiKeyAuth(config.ApiKey...),
WithIgnorePrefix(config.IgnorePrefix...))
}
return opts
}
// ***************** Option *****************
// Option
type Option func(*optionSet)
// WithEntryNameAndType provide entry name and entry type.
func WithEntryNameAndType(entryName, entryType string) Option {
return func(set *optionSet) {
set.entryName = entryName
set.entryType = entryType
}
}
// WithBasicAuth provide basic auth credentials formed as user:pass.
// We will encode credential with base64 since incoming credential from client would be encoded.
func WithBasicAuth(realm string, cred ...string) Option {
return func(set *optionSet) {
for i := range cred {
set.basicAccounts[base64.StdEncoding.EncodeToString([]byte(cred[i]))] = true
}
set.basicRealm = realm
}
}
// WithApiKeyAuth provide API Key auth credentials.
// An API key is a token that a client provides when making API calls.
// With API key auth, you send a key-value pair to the API either in the request headers or query parameters.
// Some APIs use API keys for authorization.
//
// The API key was injected into incoming header with key of X-API-Key
func WithApiKeyAuth(key ...string) Option {
return func(set *optionSet) {
for i := range key {
set.apiKey[key[i]] = true
}
}
}
// WithIgnorePrefix provide paths prefix that will ignore.
// Mainly used for swagger main page and RK TV entry.
func WithIgnorePrefix(paths ...string) Option {
return func(set *optionSet) {
set.ignorePrefix = append(set.ignorePrefix, paths...)
}
}
// WithMockOptionSet provide mock OptionSetInterface
func WithMockOptionSet(mock OptionSetInterface) Option {
return func(set *optionSet) {
set.mock = mock
}
}