Skip to content

Commit ac516a1

Browse files
authored
Merge pull request #296 from USACE/chore/constant-time-compare
chore(api): constant time compare
2 parents 284cb23 + 3c070df commit ac516a1

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

api/internal/middleware/key.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package middleware
22

33
import (
44
"context"
5+
"crypto/subtle"
56
"errors"
67

78
"github.com/USACE/instrumentation-api/api/v4/internal/ctxkey"
@@ -13,10 +14,12 @@ import (
1314
// AppKeyAuth does a key check for ?key=<ApplicationKey>
1415
func (m *apiMw) AppKeyAuth(ctx huma.Context, next func(huma.Context)) {
1516
provided := ctx.Query("key")
16-
if provided == m.Config.ApplicationKey && provided != "" {
17-
newCtx := context.WithValue(ctx.Context(), ctxkey.AppKeyAuthSuccess, true)
18-
next(huma.WithContext(ctx, newCtx))
19-
return
17+
if provided != "" {
18+
if res := subtle.ConstantTimeCompare([]byte(provided), []byte(m.Config.ApplicationKey)); res == 1 {
19+
newCtx := context.WithValue(ctx.Context(), ctxkey.AppKeyAuthSuccess, true)
20+
next(huma.WithContext(ctx, newCtx))
21+
return
22+
}
2023
}
2124

2225
m.httperr.SetResponse(ctx, httperr.Unauthorized(errors.New("Unauthorized: invalid or missing key")))
@@ -32,7 +35,7 @@ func (m *apiMw) keyAuth(isDisabled bool, appKey string, h HashExtractorFunc) fun
3235
return
3336
}
3437

35-
if providedKey == appKey {
38+
if res := subtle.ConstantTimeCompare([]byte(providedKey), []byte(appKey)); res == 1 {
3639
newCtx := context.WithValue(ctx.Context(), ctxkey.AppKeyAuthSuccess, true)
3740
next(huma.WithContext(ctx, newCtx))
3841
return

0 commit comments

Comments
 (0)