Skip to content

Commit 49dbc33

Browse files
committed
add MaskKey check
1 parent 20fbd73 commit 49dbc33

File tree

2 files changed

+29
-9
lines changed

2 files changed

+29
-9
lines changed

packages/api/internal/auth/key.go

+19-5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package auth
33
import (
44
"crypto/rand"
55
"encoding/hex"
6+
"fmt"
67
"strings"
78
)
89

@@ -20,23 +21,36 @@ type Key struct {
2021
MaskedValue string
2122
}
2223

23-
func MaskKey(prefix string, value string) string {
24-
lastFour := value[len(value)-keySuffixLength:]
25-
stars := strings.Repeat("*", len(value)-keySuffixLength)
26-
return prefix + stars + lastFour
24+
func MaskKey(prefix string, value string) (string, error) {
25+
suffixOffset := len(value) - keySuffixLength
26+
27+
if suffixOffset < 0 {
28+
return "", fmt.Errorf("mask value length is less than key suffix length (%d)", keySuffixLength)
29+
}
30+
31+
lastFour := value[suffixOffset:]
32+
stars := strings.Repeat("*", suffixOffset)
33+
return prefix + stars + lastFour, nil
2734
}
2835

2936
func GenerateKey(prefix string) (Key, error) {
3037
keyBytes := make([]byte, keyLength)
38+
3139
_, err := rand.Read(keyBytes)
3240
if err != nil {
3341
return Key{}, err
3442
}
43+
3544
generatedToken := hex.EncodeToString(keyBytes)
3645

46+
mask, err := MaskKey(prefix, generatedToken)
47+
if err != nil {
48+
return Key{}, err
49+
}
50+
3751
return Key{
3852
PrefixedRawValue: prefix + generatedToken,
3953
HashedValue: hasher.Hash(keyBytes),
40-
MaskedValue: MaskKey(prefix, generatedToken),
54+
MaskedValue: mask,
4155
}, nil
4256
}

packages/api/internal/handlers/apikey.go

+10-4
Original file line numberDiff line numberDiff line change
@@ -80,11 +80,17 @@ func (a *APIStore) GetApikeys(c *gin.Context) {
8080

8181
keyValue := strings.Split(apiKey.APIKey, auth.ApiKeyPrefix)[1]
8282

83+
// TODO: remove this once we migrate to hashed API keys
84+
KeyMask, err := auth.MaskKey(auth.ApiKeyPrefix, keyValue)
85+
if err != nil {
86+
fmt.Printf("masking API key failed %d: %v", apiKey.ID, err)
87+
continue
88+
}
89+
8390
teamAPIKeys[i] = api.TeamAPIKey{
84-
Id: apiKey.ID,
85-
Name: apiKey.Name,
86-
// TODO: remove this once we migrate to hashed API keys
87-
KeyMask: auth.MaskKey(auth.ApiKeyPrefix, keyValue),
91+
Id: apiKey.ID,
92+
Name: apiKey.Name,
93+
KeyMask: KeyMask,
8894
CreatedAt: apiKey.CreatedAt,
8995
CreatedBy: createdBy,
9096
LastUsed: apiKey.LastUsed,

0 commit comments

Comments
 (0)