Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 14, 05:15 UTC
basicauth: Minor internal improvements (#3861)
* nitpicks and small improvements in basicauth module 1: roll two if statements into one, since err will be nil in the second case anyhow 2: unlock cache mutex after reading the key, as this happens by-value and reduces code complexity 3: switch cache sync.Mutex to sync.RWMutex for better concurrency on cache fast track * allocate the right kind of mutex
Aurelia committed
Nov 13, 2020 at 23:28 UTC
7a3d9d81fe5836894b39d0e218193f7cffd732ff
1 file changed
+5
-9
modules/caddyhttp/caddyauth/basicauth.go
+5
-9
@@ -134,7 +134,7 @@ func (hba *HTTPBasicAuth) Provision(ctx caddy.Context) error {
134
135
if hba.HashCache != nil {
136
hba.HashCache.cache = make(map[string]bool)
137
- hba.HashCache.mu = new(sync.Mutex)
137
+ hba.HashCache.mu = new(sync.RWMutex)
138
}
139
140
return nil
@@ -156,12 +156,9 @@ func (hba HTTPBasicAuth) Authenticate(w http.ResponseWriter, req *http.Request)
156
}
157
158
same, err := hba.correctPassword(account, []byte(plaintextPasswordStr))
159
- if err != nil {
159
+ if err != nil || !same || !accountExists {
160
return hba.promptForCredentials(w, err)
161
}
162
- if !same || !accountExists {
163
- return hba.promptForCredentials(w, nil)
164
- }
162
163
return User{ID: username}, true, nil
164
}
@@ -180,13 +177,12 @@ func (hba HTTPBasicAuth) correctPassword(account Account, plaintextPassword []by
177
cacheKey := hex.EncodeToString(append(append(account.password, account.salt...), plaintextPassword...))
178
179
// fast track: if the result of the input is already cached, use it
183
- hba.HashCache.mu.Lock()
180
+ hba.HashCache.mu.RLock()
181
same, ok := hba.HashCache.cache[cacheKey]
182
+ hba.HashCache.mu.RUnlock()
183
if ok {
186
- hba.HashCache.mu.Unlock()
184
return same, nil
185
}
189
- hba.HashCache.mu.Unlock()
186
187
// slow track: do the expensive op, then add it to the cache
188
same, err := compare()
@@ -219,7 +215,7 @@ func (hba HTTPBasicAuth) promptForCredentials(w http.ResponseWriter, err error)
215
// helpful for secure password hashes which can be expensive to
216
// compute on every HTTP request.
217
type Cache struct {
222
- mu *sync.Mutex
218
+ mu *sync.RWMutex
219
220
// map of concatenated hashed password + plaintext password + salt, to result
221
cache map[string]bool