43 lines
auth/apikey.go
Validates API key format, prefix, and revocation status.
// Package auth validates inbound API keys.package authimport ( "errors" "regexp")
var ( // ErrInvalidFormat is returned when the key does not meet format requirements. ErrInvalidFormat = errors.New("invalid API key format") // ErrRevoked is returned when the key is present in the revocation list. ErrRevoked = errors.New("API key has been revoked"))
// validKeyBody matches the 32-character suffix after the 8-character prefix.var validKeyBody = regexp.MustCompile(`^[A-Za-z0-9]{32}$`)// KeyStore reports whether a key appears in the revocation list.type KeyStore interface { IsRevoked(key string) (bool, error)}
// ValidateKey checks that key meets format requirements and has not been revoked.//// A valid key must:// - be exactly 40 characters// - start with "sk_live_" (production) or "sk_test_" (sandbox)// - contain only alphanumeric characters after the 8-character prefix// - not appear in the revocation listfunc ValidateKey(key string, store KeyStore) error { if len(key) != 40 { return ErrInvalidFormat}
suffix := key[8:] if !validKeyBody.MatchString(suffix) { return ErrInvalidFormat}
if _, err := store.IsRevoked(key); err != nil { return err}
return nil}