fix(auth): look up API keys by id, one bcrypt compare per request

This commit is contained in:
2026-11-23 13:38:37 +00:00
parent 787c757827
commit ae5167ffa9
2 changed files with 263 additions and 31 deletions
+105 -29
View File
@@ -8,6 +8,7 @@ import (
"encoding/base64" "encoding/base64"
stderrors "errors" stderrors "errors"
"fmt" "fmt"
"strings"
"sync" "sync"
"time" "time"
@@ -154,10 +155,12 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to generate random key") return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to generate random key")
} }
rawKey := base64.URLEncoding.EncodeToString(keyBytes) secret := base64.URLEncoding.EncodeToString(keyBytes)
id := keyPrefix + generateID()
rawKey := id + keySeparator + secret
// Hash the key with the configured cost. // Hash the key with the configured cost.
hashedKey, err := bcrypt.GenerateFromPassword([]byte(rawKey), m.cfg.BcryptCost) hashedKey, err := bcrypt.GenerateFromPassword([]byte(secret), m.cfg.BcryptCost)
if err != nil { if err != nil {
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to hash key") return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to hash key")
} }
@@ -169,7 +172,7 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
} }
apiKey := &APIKey{ apiKey := &APIKey{
ID: generateID(), ID: id,
Name: name, Name: name,
HashedKey: string(hashedKey), HashedKey: string(hashedKey),
Role: role, Role: role,
@@ -198,32 +201,50 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
return apiKey, rawKey, nil return apiKey, rawKey, nil
} }
// ValidateAPIKey validates an API key and returns the associated key object. // Key format: "<id>.<secret>" with id "ghk_<random>". The id is public and selects one stored
// Hot path: snapshots candidates, runs bcrypt without holding the lock. // key; the bcrypt hash covers the secret only. Keys minted before the format
// LastUsedAt is updated in-memory under the write lock and flushed to the // existed have no id in the raw key and hash the whole raw key.
// store via a fire-and-forget goroutine. const (
func (m *Manager) ValidateAPIKey(ctx context.Context, rawKey string) (*APIKey, error) { keyPrefix = "ghk_"
// Phase 1: snapshot non-expired candidates under RLock. We hold pointers keySeparator = "."
// to APIKey; APIKey.HashedKey is an immutable string so reading it // maxLegacyCompares bounds concurrent bcrypt checks against pre-id keys,
// without a lock is safe even if the key is later removed from the map. // which can only be found by trying each one.
m.mu.RLock() maxLegacyCompares = 4
candidates := make([]*APIKey, 0, len(m.keys)) // legacyIDLen is the length of base64url(16 bytes).
now := time.Now() legacyIDLen = 24
for _, apiKey := range m.keys { )
if apiKey.ExpiresAt != nil && now.After(*apiKey.ExpiresAt) {
continue
}
candidates = append(candidates, apiKey)
}
m.mu.RUnlock()
// Phase 2: run bcrypt comparisons without holding any lock so concurrent var (
// auth checks can proceed in parallel. bcryptCompare = bcrypt.CompareHashAndPassword
for _, apiKey := range candidates { legacySlots = make(chan struct{}, maxLegacyCompares)
if err := bcrypt.CompareHashAndPassword([]byte(apiKey.HashedKey), []byte(rawKey)); err == nil { // dummyHash keeps the cost of an unknown id equal to a wrong secret.
// Phase 3: briefly take the write lock to update LastUsedAt. dummyHash = mustHash("gohoarder-dummy-secret")
// Re-check the key still exists in the map to avoid resurrecting )
// a revoked key's metadata.
func mustHash(s string) []byte {
h, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.DefaultCost)
if err != nil {
panic(fmt.Sprintf("auth: dummy hash: %v", err))
}
return h
}
// ValidateAPIKey validates an API key and returns the associated key object.
// A key with an id costs exactly one bcrypt compare, whatever the number of
// stored keys. LastUsedAt is updated in-memory under the write lock and
// flushed to the store via a fire-and-forget goroutine.
func (m *Manager) ValidateAPIKey(ctx context.Context, rawKey string) (*APIKey, error) {
var apiKey *APIKey
if id, secret, ok := splitKey(rawKey); ok {
apiKey = m.validateByID(id, secret)
} else {
apiKey = m.validateLegacy(ctx, rawKey)
}
if apiKey == nil {
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
}
// Re-check the key still exists to avoid resurrecting a revoked key's metadata.
usedAt := time.Now() usedAt := time.Now()
m.mu.Lock() m.mu.Lock()
if _, ok := m.keys[apiKey.ID]; ok { if _, ok := m.keys[apiKey.ID]; ok {
@@ -235,9 +256,64 @@ func (m *Manager) ValidateAPIKey(ctx context.Context, rawKey string) (*APIKey, e
m.persistLastUsedAsync(apiKey.ID, usedAt) m.persistLastUsedAsync(apiKey.ID, usedAt)
return apiKey, nil return apiKey, nil
} }
func splitKey(rawKey string) (id, secret string, ok bool) {
if !strings.HasPrefix(rawKey, keyPrefix) {
return "", "", false
}
return strings.Cut(rawKey, keySeparator)
} }
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key") // hasKeyID reports whether k was minted with an id embedded in its raw key.
// Legacy ids are bare generateID output, which is always legacyIDLen long.
func hasKeyID(k *APIKey) bool {
return strings.HasPrefix(k.ID, keyPrefix) && len(k.ID) > legacyIDLen
}
func (m *Manager) validateByID(id, secret string) *APIKey {
m.mu.RLock()
apiKey := m.keys[id]
m.mu.RUnlock()
hash := dummyHash
if apiKey != nil {
hash = []byte(apiKey.HashedKey)
}
err := bcryptCompare(hash, []byte(secret))
if apiKey == nil || err != nil || expired(apiKey, time.Now()) {
return nil
}
return apiKey
}
func (m *Manager) validateLegacy(ctx context.Context, rawKey string) *APIKey {
m.mu.RLock()
candidates := make([]*APIKey, 0, len(m.keys))
now := time.Now()
for _, k := range m.keys {
if !hasKeyID(k) && !expired(k, now) {
candidates = append(candidates, k)
}
}
m.mu.RUnlock()
for _, k := range candidates {
select {
case legacySlots <- struct{}{}:
case <-ctx.Done():
return nil
}
err := bcryptCompare([]byte(k.HashedKey), []byte(rawKey))
<-legacySlots
if err == nil {
return k
}
}
return nil
}
func expired(k *APIKey, now time.Time) bool {
return k.ExpiresAt != nil && now.After(*k.ExpiresAt)
} }
// persistLastUsedAsync flushes a LastUsedAt update to the store off the hot // persistLastUsedAsync flushes a LastUsedAt update to the store off the hot
+156
View File
@@ -0,0 +1,156 @@
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
)
// countBcrypt wraps bcryptCompare and returns the call counter.
func countBcrypt(t *testing.T) *atomic.Int64 {
t.Helper()
var n atomic.Int64
orig := bcryptCompare
bcryptCompare = func(h, p []byte) error {
n.Add(1)
return orig(h, p)
}
t.Cleanup(func() { bcryptCompare = orig })
return &n
}
func newTestManager() *Manager { return NewWithStore(Config{BcryptCost: bcrypt.MinCost}, nil) }
// addLegacyKey stores a key in the pre-key-id format: bcrypt of the whole raw key, no id in the key.
func addLegacyKey(t *testing.T, m *Manager) string {
t.Helper()
b := make([]byte, 32)
_, _ = rand.Read(b)
raw := base64.URLEncoding.EncodeToString(b)
h, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
k := &APIKey{ID: generateID(), Name: "legacy", HashedKey: string(h), Role: RoleReadOnly, CreatedAt: time.Now(), Permissions: getPermissionsForRole(RoleReadOnly)}
m.mu.Lock()
m.keys[k.ID] = k
m.mu.Unlock()
return raw
}
func TestValidateAPIKeyCostIndependentOfKeyCount(t *testing.T) {
m := newTestManager()
_, good, err := m.GenerateAPIKey("target", RoleReadWrite, nil)
if err != nil {
t.Fatal(err)
}
for i := 0; i < 50; i++ {
if _, _, err := m.GenerateAPIKey("filler", RoleReadOnly, nil); err != nil {
t.Fatal(err)
}
}
n := countBcrypt(t)
if _, err := m.ValidateAPIKey(context.Background(), good); err != nil {
t.Fatalf("valid key rejected: %v", err)
}
if got := n.Load(); got != 1 {
t.Errorf("valid key: %d bcrypt compares, want 1", got)
}
n.Store(0)
idPart := strings.SplitN(good, keySeparator, 2)[0]
cases := map[string]string{
"known id, wrong secret": idPart + keySeparator + "AAAA",
"unknown id": keyPrefix + "nope" + keySeparator + "AAAA",
"no secret": idPart + keySeparator,
}
for name, raw := range cases {
n.Store(0)
if _, err := m.ValidateAPIKey(context.Background(), raw); err == nil {
t.Errorf("%s: accepted", name)
}
if got := n.Load(); got != 1 {
t.Errorf("%s: %d bcrypt compares, want exactly 1", name, got)
}
}
}
func TestValidateAPIKeyRejectsSecretOfAnotherKey(t *testing.T) {
m := newTestManager()
a, _, _ := m.GenerateAPIKey("a", RoleAdmin, nil)
_, rawB, _ := m.GenerateAPIKey("b", RoleReadOnly, nil)
secretB := strings.SplitN(rawB, keySeparator, 2)[1]
if _, err := m.ValidateAPIKey(context.Background(), a.ID+keySeparator+secretB); err == nil {
t.Fatal("id of one key with the secret of another was accepted")
}
}
func TestLegacyKeysStillValidate(t *testing.T) {
m := newTestManager()
raw := addLegacyKey(t, m)
for i := 0; i < 3; i++ {
addLegacyKey(t, m)
}
k, err := m.ValidateAPIKey(context.Background(), raw)
if err != nil || k == nil || k.Name != "legacy" {
t.Fatalf("legacy key rejected: %v", err)
}
}
func TestNewFormatKeyNeverTouchesLegacyKeys(t *testing.T) {
m := newTestManager()
for i := 0; i < 20; i++ {
addLegacyKey(t, m)
}
_, raw, _ := m.GenerateAPIKey("new", RoleReadOnly, nil)
n := countBcrypt(t)
if _, err := m.ValidateAPIKey(context.Background(), raw+"x"); err == nil {
t.Fatal("bad key accepted")
}
if got := n.Load(); got != 1 {
t.Errorf("%d bcrypt compares with 20 legacy keys stored, want 1", got)
}
}
func TestLegacyComparesAreConcurrencyBounded(t *testing.T) {
m := newTestManager()
for i := 0; i < 5; i++ {
addLegacyKey(t, m)
}
var cur, peak atomic.Int64
orig := bcryptCompare
bcryptCompare = func(h, p []byte) error {
c := cur.Add(1)
for {
p := peak.Load()
if c <= p || peak.CompareAndSwap(p, c) {
break
}
}
time.Sleep(2 * time.Millisecond)
cur.Add(-1)
return orig(h, p)
}
t.Cleanup(func() { bcryptCompare = orig })
var wg sync.WaitGroup
for i := 0; i < 40; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = m.ValidateAPIKey(context.Background(), "bad-legacy-key-bad-legacy-key-bad-legacy-key-0000")
}()
}
wg.Wait()
if got := peak.Load(); got > maxLegacyCompares {
t.Errorf("peak concurrent legacy compares %d, want <= %d", got, maxLegacyCompares)
}
}