A continuation of HomeBox the inventory and organization system built for the Home User
fix: strong API key pepper support
Matthew Kilgore90534c42c11d
diff --git a/Taskfile.yml b/Taskfile.ymlindex f7db405f..57f83b31 100644--- a/Taskfile.yml+++ b/Taskfile.yml@@ -6,6 +6,7 @@ env:HBOX_DATABASE_SQLITE_PATH: .data/homebox.db?_pragma=busy_timeout=1000&_pragma=journal_mode=WAL&_fk=1&_time_format=sqliteHBOX_OPTIONS_ALLOW_REGISTRATION: trueUNSAFE_DISABLE_PASSWORD_PROJECTION: "yes_i_am_sure"+ HBOX_AUTH_API_KEY_PEPPER: "dev-only-pepper-not-for-production-use-32b+"tasks:setup:desc: Install development dependenciesdiff --git a/backend/app/api/main.go b/backend/app/api/main.goindex fab14013..50659af7 100644--- a/backend/app/api/main.go+++ b/backend/app/api/main.go@@ -20,6 +20,7 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/sys/config""github.com/sysadminsmedia/homebox/backend/internal/sys/otel""github.com/sysadminsmedia/homebox/backend/internal/web/mid"+ "github.com/sysadminsmedia/homebox/backend/pkgs/hasher""github.com/go-chi/chi/v5""github.com/go-chi/chi/v5/middleware"@@ -108,6 +109,17 @@ func run(cfg *config.Config) error {app := new(cfg)app.setupLogger()+ // Fail fast on a missing or weak API key pepper. Without it, the HMAC keying+ // for stored API key hashes would degrade to a constant key and a DB leak+ // would expose every issued token. 32 bytes ≈ 256 bits is the cutoff.+ if len(cfg.Auth.APIKeyPepper) < 32 {+ return fmt.Errorf(+ "auth.api_key_pepper must be set to at least 32 bytes; generate with `openssl rand -base64 48` " ++ "and provide via HBOX_AUTH_API_KEY_PEPPER. Rotating it invalidates all issued API keys",+ )+ }+ hasher.SetAPIKeyPepper([]byte(cfg.Auth.APIKeyPepper))+// =========================================================================// Initialize OpenTelemetryotelProvider, err := otel.NewProvider(context.Background(), &cfg.Otel, version)diff --git a/backend/app/api/middleware.go b/backend/app/api/middleware.goindex 0570fb3c..bdcd4cb7 100644--- a/backend/app/api/middleware.go+++ b/backend/app/api/middleware.go@@ -231,7 +231,7 @@ func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {return validate.NewRequestError(errors.New("valid authorization token is required"), http.StatusUnauthorized)}- tokenHash := hasher.HashToken(requestToken)+ tokenHash := hasher.HashAPIKey(requestToken)keyUsr, keyID, keyErr := a.repos.APIKeys.GetUserFromToken(r.Context(), tokenHash)if keyErr != nil {if ent.IsNotFound(keyErr) {diff --git a/backend/internal/sys/config/conf.go b/backend/internal/sys/config/conf.goindex 53b92e49..8b75035d 100644--- a/backend/internal/sys/config/conf.go+++ b/backend/internal/sys/config/conf.go@@ -107,6 +107,11 @@ type BarcodeAPIConf struct {type AuthConfig struct {RateLimit AuthRateLimit `yaml:"rate_limit"`+ // APIKeyPepper is a server-side secret HMAC-keyed into stored API key hashes.+ // Holding it outside the database means a DB-only leak yields no usable hashes.+ // Must stay stable across restarts — rotating it invalidates every issued key.+ // Generate with `openssl rand -base64 48`.+ APIKeyPepper string `yaml:"api_key_pepper" conf:"mask"`}type AuthRateLimit struct {diff --git a/backend/pkgs/hasher/token.go b/backend/pkgs/hasher/token.goindex e11c7ad3..d5dfc52f 100644--- a/backend/pkgs/hasher/token.go+++ b/backend/pkgs/hasher/token.go@@ -2,10 +2,12 @@ package hasherimport ("context"+ "crypto/hmac""crypto/rand""crypto/sha256""encoding/base32""encoding/base64"+ "sync/atomic""go.opentelemetry.io/otel/attribute")@@ -19,6 +21,21 @@ type Token struct {Hash []byte}+// apiKeyPepper holds the HMAC key applied to API key hashes. Stored as an+// atomic.Pointer so SetAPIKeyPepper at startup is visible to verify paths+// without a lock. A nil load means the app forgot to install it.+var apiKeyPepper atomic.Pointer[[]byte]++// SetAPIKeyPepper installs the server-side pepper used for HMAC-keyed API key+// hashing. Call once at startup before any API key is hashed or verified.+// Rotating the pepper invalidates every previously issued API key, so the+// caller must persist the same value across restarts.+func SetAPIKeyPepper(pepper []byte) {+ cp := make([]byte, len(pepper))+ copy(cp, pepper)+ apiKeyPepper.Store(&cp)+}+// GenerateToken generates a cryptographically random token. The non-context variant is// kept for callers that don't have a context handy; both go through GenerateTokenCtx.func GenerateToken() Token {@@ -52,6 +69,21 @@ func HashToken(plainTextToken string) []byte {return hash[:]}+// HashAPIKey returns HMAC-SHA256(pepper, plain). Indexed equality lookups stay+// O(1) while a DB-only leak — without the pepper held in app config — yields+// no usable hashes. Panics if SetAPIKeyPepper has not been called: missing it+// would silently fall back to a constant key, which is the failure mode this+// function exists to prevent.+func HashAPIKey(plain string) []byte {+ p := apiKeyPepper.Load()+ if p == nil || len(*p) == 0 {+ panic("hasher: API key pepper not configured (call SetAPIKeyPepper at startup)")+ }+ mac := hmac.New(sha256.New, *p)+ mac.Write([]byte(plain))+ return mac.Sum(nil)+}+// GenerateAPIKey produces a static API key with 256 bits of entropy and a// recognizable prefix. The format is `hb_<base64url(32 bytes)>` — long enough// to discourage guessing, mixed-case + symbols for visual distinctness from@@ -68,7 +100,7 @@ func GenerateAPIKeyCtx(ctx context.Context) Token {_, _ = rand.Read(randomBytes)plainText := APIKeyPrefix + base64.RawURLEncoding.EncodeToString(randomBytes)- hash := HashToken(plainText)+ hash := HashAPIKey(plainText)span.SetAttributes(attribute.Int("token.raw.length", len(plainText)),diff --git a/backend/pkgs/hasher/token_test.go b/backend/pkgs/hasher/token_test.goindex d61fddfb..a48e0212 100644--- a/backend/pkgs/hasher/token_test.go+++ b/backend/pkgs/hasher/token_test.go@@ -1,13 +1,20 @@package hasherimport (+ "strings""testing""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require")const ITERATIONS = 200+func init() {+ // Tests need a pepper installed for HashAPIKey/GenerateAPIKey paths.+ SetAPIKeyPepper([]byte("test-pepper-not-for-production-use-only"))+}+func Test_NewToken(t *testing.T) {t.Parallel()tokens := make([]Token, ITERATIONS)@@ -42,3 +49,48 @@ func Test_HashToken_CheckTokenHash(t *testing.T) {assert.Equal(t, token.Hash, HashToken(token.Raw))}}++func Test_GenerateAPIKey_Format(t *testing.T) {+ t.Parallel()+ for i := 0; i < ITERATIONS; i++ {+ k := GenerateAPIKey()+ assert.True(t, strings.HasPrefix(k.Raw, APIKeyPrefix), "raw key must carry the hb_ prefix")+ assert.Len(t, k.Hash, 32, "HMAC-SHA256 output is 32 bytes")+ assert.Equal(t, k.Hash, HashAPIKey(k.Raw), "stored hash must match HashAPIKey(raw)")+ }+}++func Test_HashAPIKey_DiffersFromSHA256(t *testing.T) {+ t.Parallel()+ // The whole point of HMAC-keyed hashing is that an attacker with the DB+ // but not the pepper can't precompute or verify hashes via plain SHA-256.+ k := GenerateAPIKey()+ assert.NotEqual(t, HashToken(k.Raw), HashAPIKey(k.Raw))+}++func Test_HashAPIKey_IsKeyed(t *testing.T) {+ // Mutates the package-level pepper, so cannot run in parallel with the+ // other tests that also depend on it being stable.+ original := apiKeyPepper.Load()+ t.Cleanup(func() {+ require.NotNil(t, original)+ apiKeyPepper.Store(original)+ })++ SetAPIKeyPepper([]byte("pepper-A-pepper-A-pepper-A-pepperA"))+ a := HashAPIKey("hb_sample-token-value")+ SetAPIKeyPepper([]byte("pepper-B-pepper-B-pepper-B-pepperB"))+ b := HashAPIKey("hb_sample-token-value")+ assert.NotEqual(t, a, b)+}++func Test_HashAPIKey_PanicsWithoutPepper(t *testing.T) {+ // This test MUST NOT run in parallel — it temporarily clears global state.+ original := apiKeyPepper.Load()+ t.Cleanup(func() {+ require.NotNil(t, original)+ apiKeyPepper.Store(original)+ })+ apiKeyPepper.Store(nil)+ assert.Panics(t, func() { HashAPIKey("anything") })+}