Skip to content

Commit

Permalink
fix(redfish): avoid token store contention
Browse files Browse the repository at this point in the history
Signed-off-by: Zespre Schmidt <[email protected]>
  • Loading branch information
starbops committed Dec 19, 2024
1 parent 1c5a0f1 commit e546306
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
2 changes: 1 addition & 1 deletion pkg/redfish/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (h *handler) Authenticate(username, password *string) (string, string, erro

func (h *handler) GetSession(sessionID string) (string, string, error) {
var id, username string
tokenInfo, exists := session.GetTokenFromID(sessionID)
tokenInfo, exists := session.GetTokenFromSessionID(sessionID)
if !exists {
return id, username, fmt.Errorf("session not found")
}
Expand Down
47 changes: 38 additions & 9 deletions pkg/session/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,15 @@ import (
"encoding/hex"
"encoding/json"
"net/http"
"sync"
)

var tokenStore map[string]TokenInfo
var ts TokenStore

type TokenStore struct {
rwMutex sync.RWMutex
store map[string]TokenInfo
}

type TokenInfo struct {
ID string
Expand All @@ -22,7 +28,10 @@ func NewTokenInfo(id, username string) TokenInfo {
}

func init() {
tokenStore = make(map[string]TokenInfo, 1)
ts = TokenStore{
store: make(map[string]TokenInfo, 1),
}

}

func generateToken(tokenInfo TokenInfo) string {
Expand All @@ -33,38 +42,58 @@ func generateToken(tokenInfo TokenInfo) string {
}

func AddToken(tokenInfo TokenInfo) string {
ts.rwMutex.Lock()
defer ts.rwMutex.Unlock()

token := generateToken(tokenInfo)
tokenStore[token] = tokenInfo
ts.store[token] = tokenInfo

return token
}

func GetToken(token string) (TokenInfo, bool) {
tokenInfo, exists := tokenStore[token]
ts.rwMutex.RLock()
defer ts.rwMutex.RUnlock()

tokenInfo, exists := ts.store[token]

return tokenInfo, exists
}

func RemoveToken(token string) {
delete(tokenStore, token)
ts.rwMutex.Lock()
defer ts.rwMutex.Unlock()

delete(ts.store, token)
}

func GetTokenFromID(id string) (TokenInfo, bool) {
for _, tokenInfo := range tokenStore {
if tokenInfo.ID == id {
func GetTokenFromSessionID(sessionID string) (TokenInfo, bool) {
ts.rwMutex.RLock()
defer ts.rwMutex.RUnlock()

for _, tokenInfo := range ts.store {
if tokenInfo.ID == sessionID {
return tokenInfo, true
}
}

return TokenInfo{}, false
}

func AuthMiddleware(next http.Handler) http.Handler {

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("X-Auth-Token")
if token == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

if _, exists := tokenStore[token]; !exists {
ts.rwMutex.RLock()
_, exists := ts.store[token]
ts.rwMutex.RUnlock()

if !exists {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
Expand Down

0 comments on commit e546306

Please sign in to comment.