-
Notifications
You must be signed in to change notification settings - Fork 25
/
options.go
272 lines (253 loc) · 8.92 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
// Copyright 2015-present, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// 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 auth
import (
"net/http"
"regexp"
"strings"
"github.com/corestoreio/errors"
"github.com/corestoreio/pkg/net/mw"
"github.com/corestoreio/pkg/store/scope"
)
// WithDefaultConfig applies the default configuration settings for
// a specific scope.
//
// Default values are:
// - authentication returns always access denied
// - all resources protected
func WithDefaultConfig(scopeIDs ...scope.TypeID) Option {
return withDefaultConfig(scopeIDs...)
}
// WithUnauthorizedHandler sets the handler which calls the interface to request
// data from a user after the authentication failed.
func WithUnauthorizedHandler(uah mw.ErrorHandler, scopeIDs ...scope.TypeID) Option {
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
sc.UnauthorizedHandler = uah
return s.updateScopedConfig(sc)
}
}
// WithUnauthorizedRedirect redirects if the authorization fails.
func WithUnauthorizedRedirect(url string, code int, scopeIDs ...scope.TypeID) Option {
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
sc.UnauthorizedHandler = func(_ error) http.Handler {
return http.RedirectHandler(url, code)
}
return s.updateScopedConfig(sc)
}
}
func matchPath(caseSensitivePath bool, r *http.Request, other string) bool {
if caseSensitivePath {
return strings.HasPrefix(r.URL.Path, other)
}
return strings.HasPrefix(strings.ToLower(r.URL.Path), strings.ToLower(other))
}
// WithResourceACLs enables to define specific URL paths to be black- and/or
// white listed. Matching for black- and white lists checks if the URL path has
// the provided string of a list as a prefix.
// auth.WithResources(nil,nil) // blocks everything
// auth.WithResources([]string{"/"}, []string{}) // blocks everything
// auth.WithResources([]string{"/"}, []string{"/catalog"}) // blocks everything except the routes starting with /catalog.
// Providing no scopeIDs applies the resource ACL to the default scope ID. The
// string based ACL checks will always be executed before REGEX based ACL
// checks, if both functional options have been provided.
func WithResourceACLs(blockList, allowList []string, scopeIDs ...scope.TypeID) Option {
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
isCaseSensitive := sc.caseSensitivePath // copy the value to avoid races
sc.triggers = append(sc.triggers, authTrigger{
prio: -10,
TriggerFunc: func(r *http.Request) bool {
blocked := len(blockList) == 0
for _, b := range blockList {
if matchPath(isCaseSensitive, r, b) {
blocked = true
}
}
if blocked {
for _, w := range allowList {
if matchPath(isCaseSensitive, r, w) {
return false
}
}
}
return blocked
},
})
sc.triggers.sort()
return s.updateScopedConfig(sc)
}
}
func strSliceToRegexSlice(sl []string) ([]*regexp.Regexp, error) {
rs := make([]*regexp.Regexp, 0, len(sl))
for i, b := range sl {
if b == "" {
continue
}
r, err := regexp.Compile(b)
if err != nil {
return nil, errors.Fatal.Newf("[auth] Failed to compile regex %q at index %d", b, i)
}
rs = append(rs, r)
}
return rs, nil
}
// WithResourceRegexpACLs same as WithResourceACLs but uses the slow
// pre-compiled and more powerful regexes.
func WithResourceRegexpACLs(blockList, allowList []string, scopeIDs ...scope.TypeID) Option {
br, err := strSliceToRegexSlice(blockList)
if err != nil {
return func(s *Service) error {
return errors.Wrap(err, "[auth] WithResourcesRegexp block list")
}
}
wlr, err := strSliceToRegexSlice(allowList)
if err != nil {
return func(s *Service) error {
return errors.Wrap(err, "[auth] WithResourcesRegexp allow list")
}
}
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
sc.triggers = append(sc.triggers, authTrigger{
prio: -5,
TriggerFunc: func(r *http.Request) bool {
block := len(br) == 0
for _, blockr := range br {
if blockr.MatchString(r.URL.Path) {
block = true
}
}
if block {
for _, whiter := range wlr {
if whiter.MatchString(r.URL.Path) {
return false
}
}
}
return block
},
})
sc.triggers.sort()
return s.updateScopedConfig(sc)
}
}
// WithCombineTriggers setting to true forces all authentication triggers to
// return true. Otherwise the first trigger which returns true, triggers the
// authentication providers. Default value: false.
func WithCombineTriggers(combine bool, scopeIDs ...scope.TypeID) Option {
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
sc.combineTrigger = combine
return s.updateScopedConfig(sc)
}
}
// WithTrigger sets the authentication trigger function which implements a
// condition to check if the list of authentication providers should be called.
// Subsequent calls of this functional option will add more TriggerFuncs to the
// internal list. If not trigger has been applied the authentication providers
// will always be called.
func WithTrigger(tf TriggerFunc, priority int, scopeIDs ...scope.TypeID) Option {
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
sc.triggers = append(sc.triggers, authTrigger{
prio: priority,
TriggerFunc: tf,
})
return s.updateScopedConfig(sc)
}
}
// WithProvider sets the authentication provider function which checks if a
// request should be considered valid to call the next HTTP handler on err ==
// nil or even call the next provider. Subsequent calls of this functions will
// add more ProviderFuncs to the internal list. This internal list cannot yet be
// cleared or reset.
func WithProvider(pf ProviderFunc, priority int, scopeIDs ...scope.TypeID) Option {
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
sc.providers = append(sc.providers, authProvider{
prio: priority,
ProviderFunc: pf,
})
return s.updateScopedConfig(sc)
}
}
// WithSimpleBasicAuth sets a single username/password for a scope. Username and
// password must be provided as "plain text" arguments. This basic auth handler
// calls the next authentication provider if the authentication fails. Username
// and password will be compared in constant time.
func WithSimpleBasicAuth(username, password, realm string, scopeIDs ...scope.TypeID) Option {
ba256, err := basicAuthValidator("sha256", username, password)
if err != nil {
return func(s *Service) error {
return errors.Wrap(err, "[auth] WithSimpleBasicAuth basicAuthHashed")
}
}
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
sc.providers = append(sc.providers, authProvider{
prio: 10,
ProviderFunc: basicAuth(ba256),
})
sc.UnauthorizedHandler = basicAuthHandler(realm)
return s.updateScopedConfig(sc)
}
}
// WithBasicAuth provides the basic authentication header but allows to set a
// custom function to compare the input data of username and password.
func WithBasicAuth(baf BasicAuthFunc, realm string, scopeIDs ...scope.TypeID) Option {
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
sc.providers = append(sc.providers, authProvider{
prio: 1,
ProviderFunc: basicAuth(baf),
})
sc.UnauthorizedHandler = basicAuthHandler(realm)
return s.updateScopedConfig(sc)
}
}
// prioIncrement only used for testing to trigger the sorting. This variable
// should not trigger any race conditions.
var prioIncrement = 1000
// WithInvalidAuth authentication will always fail. Mainly used for testing ;-)
func WithInvalidAuth(callNext bool, scopeIDs ...scope.TypeID) Option {
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
prioIncrement++
sc.providers = append(sc.providers, authProvider{
prio: prioIncrement,
ProviderFunc: func(scopeID scope.TypeID, r *http.Request) (bool, error) {
return callNext, errors.Unauthorized.Newf("[auth] Access denied in Scope %s for path %q", scopeID, r.URL.Path)
},
})
sc.providers.sort()
return s.updateScopedConfig(sc)
}
}
// WithValidAuth authentication will always succeed. Mainly used for testing ;-)
func WithValidAuth(scopeIDs ...scope.TypeID) Option {
return func(s *Service) error {
sc := s.findScopedConfig(scopeIDs...)
prioIncrement++
sc.providers = append(sc.providers, authProvider{
prio: prioIncrement,
ProviderFunc: func(_ scope.TypeID, _ *http.Request) (bool, error) {
return false, nil
},
})
sc.providers.sort()
return s.updateScopedConfig(sc)
}
}