v0.3.0 security and edge case improvement all around
This commit is contained in:
@@ -1,50 +1,44 @@
|
||||
// FILE: auth/token.go
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"crypto/sha256"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// SimpleTokenValidator implements in-memory token validation
|
||||
type SimpleTokenValidator struct {
|
||||
tokens map[string]struct{}
|
||||
tokens map[[32]byte]struct{} // keyed by SHA-256(token)
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewSimpleTokenValidator creates token validator
|
||||
func NewSimpleTokenValidator() *SimpleTokenValidator {
|
||||
return &SimpleTokenValidator{
|
||||
tokens: make(map[string]struct{}),
|
||||
tokens: make(map[[32]byte]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateToken checks if token is valid
|
||||
func (v *SimpleTokenValidator) ValidateToken(token string) bool {
|
||||
h := sha256.Sum256([]byte(token))
|
||||
v.mu.RLock()
|
||||
defer v.mu.RUnlock()
|
||||
|
||||
// Constant-time comparison for each stored token
|
||||
for storedToken := range v.tokens {
|
||||
if subtle.ConstantTimeEq(int32(len(token)), int32(len(storedToken))) == 1 {
|
||||
if subtle.ConstantTimeCompare([]byte(token), []byte(storedToken)) == 1 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
_, ok := v.tokens[h]
|
||||
return ok
|
||||
}
|
||||
|
||||
// AddToken adds token to validator
|
||||
func (v *SimpleTokenValidator) AddToken(token string) {
|
||||
h := sha256.Sum256([]byte(token))
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
v.tokens[token] = struct{}{}
|
||||
v.tokens[h] = struct{}{}
|
||||
}
|
||||
|
||||
// RemoveToken removes token from validator
|
||||
func (v *SimpleTokenValidator) RemoveToken(token string) {
|
||||
h := sha256.Sum256([]byte(token))
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
delete(v.tokens, token)
|
||||
}
|
||||
delete(v.tokens, h)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user