fix(security): remediate 2026-05-12 audit findings (Stages 2–5)
Remediation of the 2026-05-12/13 audits (78 findings + cluster gaps), tracked in deploy-k3s/SECURITY.md, plus fixes from two independent post-remediation reviews. Auth & sessions: - SHA-256 hashed auth-token storage (C1); prior-token cache eviction on re-login (MEDIUM-1) - local Google JWKS verification, iss/aud/exp checks (C2/C3) - constant-time login + generic errors (L1/LIVE-L11/LIVE-L13) - per-account login lockout keyed on distinct source IPs (M5/MEDIUM-3) - verified-email gating, login rate limiting (LIVE-L19, H1-H3) IAP & webhooks: - Apple/Google cross-account replay protection (C5/C6/C10/C13, H5/H6) - migrations 000003-000006 (token hashing, IAP replay, audit_log + webhook_event_log table creation, append-only audit log) Authorization & races: - file-ownership owner-OR-member fix (C7), atomic share-code join (C9/H9), device-token reassignment (C8/LOW-3) Secrets & deploy: - secrets file-mounted at /etc/honeydue/secrets, not env (F8); Redis password out of the ConfigMap (HIGH-1); B2 keys reconciled - digest-pinned images, admin ingress hardening, CSP/HSTS, /metrics lockdown; kubeconfig 0600, etcd secrets-encryption, fail2ban + unattended-upgrades at provision; secret-rotation runbook Build, vet, and the full test suite (incl. -race) pass; the goose migration chain is verified against PostgreSQL 16. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"github.com/treytartt/honeydue-api/internal/models"
|
||||
)
|
||||
@@ -194,6 +195,60 @@ func (r *ResidenceRepository) HasAccess(residenceID, userID uint) (bool, error)
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// JoinWithShareCode atomically redeems a one-time share code (audit C9/H9):
|
||||
// it locks the share-code row, re-checks validity under the lock, adds the
|
||||
// user to the residence, and deactivates the code — all in one transaction.
|
||||
// Concurrent redemptions of the same code serialize on the row lock; the
|
||||
// loser sees is_active=false and is rejected. A failure to deactivate aborts
|
||||
// the whole join. Returns gorm.ErrRecordNotFound for an unknown, inactive, or
|
||||
// expired code so the caller can map every case to one generic error.
|
||||
func (r *ResidenceRepository) JoinWithShareCode(code string, userID uint) (residenceID uint, alreadyMember bool, err error) {
|
||||
err = r.db.Transaction(func(tx *gorm.DB) error {
|
||||
var sc models.ResidenceShareCode
|
||||
if e := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("code = ?", code).First(&sc).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
if !sc.IsActive || (sc.ExpiresAt != nil && time.Now().UTC().After(*sc.ExpiresAt)) {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
residenceID = sc.ResidenceID
|
||||
|
||||
// Already a member (owner or shared user)?
|
||||
var accessCount int64
|
||||
if e := tx.Raw(`
|
||||
SELECT COUNT(*) FROM (
|
||||
SELECT 1 FROM residence_residence
|
||||
WHERE id = ? AND owner_id = ? AND is_active = true
|
||||
UNION
|
||||
SELECT 1 FROM residence_residence_users
|
||||
WHERE residence_id = ? AND user_id = ?
|
||||
) ac
|
||||
`, sc.ResidenceID, userID, sc.ResidenceID, userID).Scan(&accessCount).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
if accessCount > 0 {
|
||||
alreadyMember = true
|
||||
return nil
|
||||
}
|
||||
|
||||
if e := tx.Exec(
|
||||
"INSERT INTO residence_residence_users (residence_id, user_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
|
||||
sc.ResidenceID, userID,
|
||||
).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
// One-time use: deactivate the code. A failure here aborts the join.
|
||||
if e := tx.Model(&models.ResidenceShareCode{}).
|
||||
Where("id = ?", sc.ID).Update("is_active", false).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return residenceID, alreadyMember, err
|
||||
}
|
||||
|
||||
// IsOwner checks if a user is the owner of a residence
|
||||
func (r *ResidenceRepository) IsOwner(residenceID, userID uint) (bool, error) {
|
||||
var count int64
|
||||
|
||||
@@ -151,6 +151,28 @@ func (r *SubscriptionRepository) FindByAppleReceiptContains(transactionID string
|
||||
return &sub, nil
|
||||
}
|
||||
|
||||
// FindByAppleOriginalTransactionID finds a subscription by the Apple original
|
||||
// transaction ID (audit C5/C13). Exact match on an indexed column — replaces
|
||||
// the LIKE scan in FindByAppleReceiptContains for both replay detection and
|
||||
// webhook user lookup.
|
||||
func (r *SubscriptionRepository) FindByAppleOriginalTransactionID(originalTransactionID string) (*models.UserSubscription, error) {
|
||||
var sub models.UserSubscription
|
||||
err := r.db.Where("apple_original_transaction_id = ?", originalTransactionID).First(&sub).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &sub, nil
|
||||
}
|
||||
|
||||
// UpdateAppleOriginalTransactionID binds an Apple original transaction ID to a
|
||||
// user's subscription. A partial unique index enforces one account per
|
||||
// transaction (audit C5) — a second account claiming the same ID fails here.
|
||||
func (r *SubscriptionRepository) UpdateAppleOriginalTransactionID(userID uint, originalTransactionID string) error {
|
||||
return r.db.Model(&models.UserSubscription{}).
|
||||
Where("user_id = ?", userID).
|
||||
Update("apple_original_transaction_id", originalTransactionID).Error
|
||||
}
|
||||
|
||||
// FindByGoogleToken finds a subscription by Google purchase token
|
||||
// Used by webhooks to find the user associated with a purchase
|
||||
func (r *SubscriptionRepository) FindByGoogleToken(purchaseToken string) (*models.UserSubscription, error) {
|
||||
|
||||
@@ -226,3 +226,48 @@ func TestUpdateExpiresAt(t *testing.T) {
|
||||
require.NotNil(t, updated.ExpiresAt)
|
||||
assert.WithinDuration(t, newExpiry, *updated.ExpiresAt, time.Second, "expires_at should be updated")
|
||||
}
|
||||
|
||||
// TestSubscriptionRepo_IAPTransactionReplayRejected is the regression test for
|
||||
// audit C5/C6: an in-app-purchase transaction (an Apple original transaction
|
||||
// ID or a Google purchase token) may be bound to exactly one account. Without
|
||||
// that guarantee a valid receipt could be replayed against a second account
|
||||
// to grant Pro for free. The guarantee is the pair of partial unique indexes
|
||||
// added by migration 000004; AutoMigrate does not create them, so this test
|
||||
// recreates them verbatim to exercise the same DB-level enforcement.
|
||||
func TestSubscriptionRepo_IAPTransactionReplayRejected(t *testing.T) {
|
||||
db := testutil.SetupTestDB(t)
|
||||
require.NoError(t, db.Exec(`CREATE UNIQUE INDEX uq_subscription_apple_original_txn `+
|
||||
`ON subscription_usersubscription (apple_original_transaction_id) `+
|
||||
`WHERE apple_original_transaction_id IS NOT NULL AND apple_original_transaction_id <> ''`).Error)
|
||||
require.NoError(t, db.Exec(`CREATE UNIQUE INDEX uq_subscription_google_purchase_token `+
|
||||
`ON subscription_usersubscription (google_purchase_token) `+
|
||||
`WHERE google_purchase_token IS NOT NULL AND google_purchase_token <> ''`).Error)
|
||||
|
||||
repo := NewSubscriptionRepository(db)
|
||||
userA := testutil.CreateTestUser(t, db, "iapusera", "iapa@test.com", "password")
|
||||
userB := testutil.CreateTestUser(t, db, "iapuserb", "iapb@test.com", "password")
|
||||
require.NoError(t, db.Create(&models.UserSubscription{UserID: userA.ID, Tier: models.TierFree}).Error)
|
||||
require.NoError(t, db.Create(&models.UserSubscription{UserID: userB.ID, Tier: models.TierFree}).Error)
|
||||
|
||||
t.Run("apple transaction cannot be claimed by a second account", func(t *testing.T) {
|
||||
require.NoError(t, repo.UpdateAppleOriginalTransactionID(userA.ID, "apple-original-txn-1"),
|
||||
"the first account binding the transaction must succeed")
|
||||
err := repo.UpdateAppleOriginalTransactionID(userB.ID, "apple-original-txn-1")
|
||||
require.Error(t, err,
|
||||
"replaying account A's Apple transaction onto account B must be rejected (C5)")
|
||||
})
|
||||
|
||||
t.Run("google purchase token cannot be claimed by a second account", func(t *testing.T) {
|
||||
require.NoError(t, repo.UpdatePurchaseToken(userA.ID, "google-purchase-token-1"),
|
||||
"the first account binding the token must succeed")
|
||||
err := repo.UpdatePurchaseToken(userB.ID, "google-purchase-token-1")
|
||||
require.Error(t, err,
|
||||
"replaying account A's Google purchase token onto account B must be rejected (C6)")
|
||||
})
|
||||
|
||||
t.Run("re-binding the same transaction to the same account is allowed", func(t *testing.T) {
|
||||
// A renewal re-submitting the same transaction for its owner must not
|
||||
// be rejected — the partial unique index excludes the row's own value.
|
||||
require.NoError(t, repo.UpdateAppleOriginalTransactionID(userA.ID, "apple-original-txn-1"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -174,10 +174,12 @@ func (r *UserRepository) GetOrCreateToken(userID uint) (*models.AuthToken, error
|
||||
return &token, nil
|
||||
}
|
||||
|
||||
// FindTokenByKey looks up an auth token by its key value.
|
||||
func (r *UserRepository) FindTokenByKey(key string) (*models.AuthToken, error) {
|
||||
// FindTokenByKey looks up an auth token by its raw key value. The raw token
|
||||
// is hashed (audit C1) before the indexed lookup, since only the hash is
|
||||
// stored.
|
||||
func (r *UserRepository) FindTokenByKey(rawKey string) (*models.AuthToken, error) {
|
||||
var token models.AuthToken
|
||||
if err := r.db.Where("key = ?", key).First(&token).Error; err != nil {
|
||||
if err := r.db.Where("key = ?", models.HashToken(rawKey)).First(&token).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrTokenNotFound
|
||||
}
|
||||
@@ -195,9 +197,46 @@ func (r *UserRepository) CreateToken(userID uint) (*models.AuthToken, error) {
|
||||
return &token, nil
|
||||
}
|
||||
|
||||
// DeleteToken deletes an auth token
|
||||
// CreateFreshToken issues a new auth token for the user, replacing any
|
||||
// existing one. Because tokens are stored hashed (audit C1) the server
|
||||
// cannot re-issue a previously-minted token's plaintext, so every login
|
||||
// mints a fresh token. The returned token's Plaintext field carries the
|
||||
// raw value to hand to the client; it is never persisted.
|
||||
//
|
||||
// It also returns the stored hashes of the token rows it deleted, so the
|
||||
// caller can evict those entries from the Redis token cache (audit MEDIUM-1).
|
||||
// Without that, a prior (e.g. stolen) token keeps authenticating via a cache
|
||||
// hit for up to the cache TTL even though its DB row is gone.
|
||||
func (r *UserRepository) CreateFreshToken(userID uint) (*models.AuthToken, []string, error) {
|
||||
var token models.AuthToken
|
||||
var oldHashes []string
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
var old []models.AuthToken
|
||||
if err := tx.Where("user_id = ?", userID).Find(&old).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
oldHashes = make([]string, 0, len(old))
|
||||
for i := range old {
|
||||
if old[i].Key != "" {
|
||||
oldHashes = append(oldHashes, old[i].Key)
|
||||
}
|
||||
}
|
||||
if err := tx.Where("user_id = ?", userID).Delete(&models.AuthToken{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
token = models.AuthToken{UserID: userID}
|
||||
return tx.Create(&token).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return &token, oldHashes, nil
|
||||
}
|
||||
|
||||
// DeleteToken deletes an auth token by its raw key value. The raw token is
|
||||
// hashed (audit C1) before the lookup, since only the hash is stored.
|
||||
func (r *UserRepository) DeleteToken(token string) error {
|
||||
result := r.db.Where("key = ?", token).Delete(&models.AuthToken{})
|
||||
result := r.db.Where("key = ?", models.HashToken(token)).Delete(&models.AuthToken{})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ func TestUserRepository_FindTokenByKey(t *testing.T) {
|
||||
token, err := repo.GetOrCreateToken(user.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
found, err := repo.FindTokenByKey(token.Key)
|
||||
found, err := repo.FindTokenByKey(token.Plaintext)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, token.Key, found.Key)
|
||||
assert.Equal(t, user.ID, found.UserID)
|
||||
@@ -128,10 +128,10 @@ func TestUserRepository_DeleteToken(t *testing.T) {
|
||||
token, err := repo.GetOrCreateToken(user.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = repo.DeleteToken(token.Key)
|
||||
err = repo.DeleteToken(token.Plaintext)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = repo.FindTokenByKey(token.Key)
|
||||
_, err = repo.FindTokenByKey(token.Plaintext)
|
||||
assert.ErrorIs(t, err, ErrTokenNotFound)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user