Skip to content

Commit 54b308c

Browse files
authored
Use constant time compare to check against configured api key (#61)
* Use constant time compare to check against configured api key * Rename secureCompare to secureCompareEqual
1 parent 865899a commit 54b308c

1 file changed

Lines changed: 10 additions & 1 deletion

File tree

pkg/service/auth.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package service
33
import (
44
"context"
55
"crypto/rsa"
6+
"crypto/subtle"
67
"encoding/json"
78
"errors"
89
"fmt"
@@ -53,7 +54,7 @@ func DefaultAuthMiddleware(next http.Handler, config *config.Config, enableSessi
5354
var authInfo *AuthInfo
5455
switch tokenType {
5556
case "ApiKey":
56-
if tokenString != config.ApiKey {
57+
if !secureCompareEqual(tokenString, config.ApiKey) {
5758
SendErrorResponse(w, NewUnauthorizedError("Invalid API key"))
5859
return
5960
}
@@ -176,3 +177,11 @@ func GetAuthInfoFromRequestContext(context context.Context) *AuthInfo {
176177

177178
return nil
178179
}
180+
181+
func secureCompareEqual(given string, actual string) bool {
182+
if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
183+
return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
184+
} else {
185+
return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
186+
}
187+
}

0 commit comments

Comments
 (0)