fix(security): remediate 2026-05-12 audit findings (Stages 2–5)
Backend CI / Test (push) Has been cancelled
Backend CI / Contract Tests (push) Has been cancelled
Backend CI / Lint (push) Has been cancelled
Backend CI / Secret Scanning (push) Has been cancelled
Backend CI / Build (push) Has been cancelled

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:
Trey t
2026-05-16 22:28:33 -05:00
parent 2004f9c5b2
commit c77ff07ce9
59 changed files with 2819 additions and 1245 deletions
+80 -45
View File
@@ -399,99 +399,135 @@ func (s *SubscriptionService) GetActivePromotions(ctx context.Context, userID ui
return result, nil
}
// ProcessApplePurchase processes an Apple IAP purchase
// Supports both StoreKit 1 (receiptData) and StoreKit 2 (transactionID)
// ProcessApplePurchase processes an Apple IAP purchase.
// Supports both StoreKit 1 (receiptData) and StoreKit 2 (transactionID).
func (s *SubscriptionService) ProcessApplePurchase(ctx context.Context, userID uint, receiptData string, transactionID string) (*SubscriptionResponse, error) {
// Store receipt/transaction data
dataToStore := receiptData
if dataToStore == "" {
dataToStore = transactionID
}
if err := s.subscriptionRepo.WithContext(ctx).UpdateReceiptData(userID, dataToStore); err != nil {
return nil, apperrors.Internal(err)
}
// Apple IAP client must be configured to validate purchases.
// Without server-side validation, we cannot trust client-provided receipts.
// Apple IAP client must be configured — without server-side validation
// we cannot trust client-provided receipts.
if s.appleClient == nil {
log.Error().Uint("user_id", userID).Msg("Apple IAP validation not configured, rejecting purchase")
return nil, apperrors.BadRequest("error.iap_validation_not_configured")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
// Validation is a network call to Apple; detach from the request context
// so a client disconnect cannot abort an in-flight grant.
vctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
var result *AppleValidationResult
var err error
// Prefer transaction ID (StoreKit 2), fall back to receipt data (StoreKit 1)
// Prefer transaction ID (StoreKit 2), fall back to receipt data (StoreKit 1).
if transactionID != "" {
result, err = s.appleClient.ValidateTransaction(ctx, transactionID)
result, err = s.appleClient.ValidateTransaction(vctx, transactionID)
} else if receiptData != "" {
result, err = s.appleClient.ValidateReceipt(ctx, receiptData)
result, err = s.appleClient.ValidateReceipt(vctx, receiptData)
}
if err != nil {
// Validation failed -- do NOT fall through to grant Pro.
log.Error().Err(err).Uint("user_id", userID).Msg("Apple validation failed")
return nil, err
}
if result == nil {
return nil, apperrors.BadRequest("error.no_receipt_or_transaction")
}
// Audit C5/C10: replay protection. A validated transaction may only ever
// be bound to one account — re-submitting a valid receipt against a
// second account must not grant Pro for free. The partial unique index
// on apple_original_transaction_id is the backstop for the check/store
// race below.
if result.OriginalTransactionID != "" {
existing, lookupErr := s.subscriptionRepo.WithContext(vctx).FindByAppleOriginalTransactionID(result.OriginalTransactionID)
switch {
case lookupErr == nil && existing != nil && existing.UserID != userID:
log.Warn().Uint("user_id", userID).Uint("bound_user_id", existing.UserID).
Msg("Apple purchase rejected — transaction already claimed by another account")
return nil, apperrors.Forbidden("error.iap_transaction_already_claimed")
case lookupErr != nil && !errors.Is(lookupErr, gorm.ErrRecordNotFound):
return nil, apperrors.Internal(lookupErr)
}
}
// Persist the receipt blob and the replay key.
dataToStore := receiptData
if dataToStore == "" {
dataToStore = transactionID
}
if err := s.subscriptionRepo.WithContext(vctx).UpdateReceiptData(userID, dataToStore); err != nil {
return nil, apperrors.Internal(err)
}
if result.OriginalTransactionID != "" {
if err := s.subscriptionRepo.WithContext(vctx).UpdateAppleOriginalTransactionID(userID, result.OriginalTransactionID); err != nil {
// The unique index rejected the bind — a concurrent request
// claimed the same transaction first.
log.Warn().Err(err).Uint("user_id", userID).Msg("Failed to bind Apple transaction ID")
return nil, apperrors.Internal(err)
}
}
expiresAt := result.ExpiresAt
log.Info().Uint("user_id", userID).Str("product", result.ProductID).Time("expires", result.ExpiresAt).Str("env", result.Environment).Msg("Apple purchase validated")
// Upgrade to Pro with the validated expiration
if err := s.subscriptionRepo.WithContext(ctx).UpgradeToPro(userID, expiresAt, "ios"); err != nil {
if err := s.subscriptionRepo.WithContext(vctx).UpgradeToPro(userID, expiresAt, "ios"); err != nil {
return nil, apperrors.Internal(err)
}
// Tier flipped — drop cached SubscriptionStatusResponse so the next call
// returns Pro immediately instead of stale Free.
if s.cache != nil {
_ = s.cache.InvalidateSubscriptionStatusForUsers(ctx, userID)
_ = s.cache.InvalidateSubscriptionStatusForUsers(vctx, userID)
}
return s.GetSubscription(ctx, userID)
return s.GetSubscription(vctx, userID)
}
// ProcessGooglePurchase processes a Google Play purchase
// productID is optional but helps validate the specific subscription
func (s *SubscriptionService) ProcessGooglePurchase(ctx context.Context, userID uint, purchaseToken string, productID string) (*SubscriptionResponse, error) {
// Store purchase token first
if err := s.subscriptionRepo.WithContext(ctx).UpdatePurchaseToken(userID, purchaseToken); err != nil {
return nil, apperrors.Internal(err)
}
// Google IAP client must be configured to validate purchases.
// Without server-side validation, we cannot trust client-provided tokens.
// Google IAP client must be configured — without server-side validation
// we cannot trust client-provided tokens.
if s.googleClient == nil {
log.Error().Uint("user_id", userID).Msg("Google IAP validation not configured, rejecting purchase")
return nil, apperrors.BadRequest("error.iap_validation_not_configured")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
// Audit C6/C10: replay protection — a purchase token may only ever be
// bound to one account. The partial unique index on google_purchase_token
// is the backstop for the check/store race.
if purchaseToken != "" {
existing, lookupErr := s.subscriptionRepo.WithContext(ctx).FindByGoogleToken(purchaseToken)
switch {
case lookupErr == nil && existing != nil && existing.UserID != userID:
log.Warn().Uint("user_id", userID).Uint("bound_user_id", existing.UserID).
Msg("Google purchase rejected — token already claimed by another account")
return nil, apperrors.Forbidden("error.iap_transaction_already_claimed")
case lookupErr != nil && !errors.Is(lookupErr, gorm.ErrRecordNotFound):
return nil, apperrors.Internal(lookupErr)
}
}
// Store the purchase token (the replay key).
if err := s.subscriptionRepo.WithContext(ctx).UpdatePurchaseToken(userID, purchaseToken); err != nil {
return nil, apperrors.Internal(err)
}
// Validation is a network call; detach from the request context.
vctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
var result *GoogleValidationResult
var err error
// If productID is provided, use it directly; otherwise try known IDs
// If productID is provided, use it directly; otherwise try known IDs.
if productID != "" {
result, err = s.googleClient.ValidateSubscription(ctx, productID, purchaseToken)
result, err = s.googleClient.ValidateSubscription(vctx, productID, purchaseToken)
} else {
result, err = s.googleClient.ValidatePurchaseToken(ctx, purchaseToken, KnownSubscriptionIDs)
result, err = s.googleClient.ValidatePurchaseToken(vctx, purchaseToken, KnownSubscriptionIDs)
}
if err != nil {
// Validation failed -- do NOT fall through to grant Pro.
log.Error().Err(err).Uint("user_id", userID).Msg("Google purchase validation failed")
return nil, err
}
if result == nil {
return nil, apperrors.BadRequest("error.no_purchase_token")
}
@@ -499,24 +535,23 @@ func (s *SubscriptionService) ProcessGooglePurchase(ctx context.Context, userID
expiresAt := result.ExpiresAt
log.Info().Uint("user_id", userID).Str("product", result.ProductID).Time("expires", result.ExpiresAt).Bool("auto_renew", result.AutoRenewing).Msg("Google purchase validated")
// Acknowledge the subscription if not already acknowledged
// Acknowledge the subscription if not already acknowledged.
if !result.AcknowledgedState {
if err := s.googleClient.AcknowledgeSubscription(ctx, result.ProductID, purchaseToken); err != nil {
if err := s.googleClient.AcknowledgeSubscription(vctx, result.ProductID, purchaseToken); err != nil {
log.Warn().Err(err).Uint("user_id", userID).Msg("Failed to acknowledge Google subscription")
// Don't fail the purchase, just log the warning
// Don't fail the purchase, just log the warning.
}
}
// Upgrade to Pro with the validated expiration
if err := s.subscriptionRepo.WithContext(ctx).UpgradeToPro(userID, expiresAt, "android"); err != nil {
if err := s.subscriptionRepo.WithContext(vctx).UpgradeToPro(userID, expiresAt, "android"); err != nil {
return nil, apperrors.Internal(err)
}
if s.cache != nil {
_ = s.cache.InvalidateSubscriptionStatusForUsers(ctx, userID)
_ = s.cache.InvalidateSubscriptionStatusForUsers(vctx, userID)
}
return s.GetSubscription(ctx, userID)
return s.GetSubscription(vctx, userID)
}
// CancelSubscription cancels a subscription (downgrades to free at end of period)