Fix 113 hardening issues across entire Go backend
Security: - Replace all binding: tags with validate: + c.Validate() in admin handlers - Add rate limiting to auth endpoints (login, register, password reset) - Add security headers (HSTS, XSS protection, nosniff, frame options) - Wire Google Pub/Sub token verification into webhook handler - Replace ParseUnverified with proper OIDC/JWKS key verification - Verify inner Apple JWS signatures in webhook handler - Add io.LimitReader (1MB) to all webhook body reads - Add ownership verification to file deletion - Move hardcoded admin credentials to env vars - Add uniqueIndex to User.Email - Hide ConfirmationCode from JSON serialization - Mask confirmation codes in admin responses - Use http.DetectContentType for upload validation - Fix path traversal in storage service - Replace os.Getenv with Viper in stripe service - Sanitize Redis URLs before logging - Separate DEBUG_FIXED_CODES from DEBUG flag - Reject weak SECRET_KEY in production - Add host check on /_next/* proxy routes - Use explicit localhost CORS origins in debug mode - Replace err.Error() with generic messages in all admin error responses Critical fixes: - Rewrite FCM to HTTP v1 API with OAuth 2.0 service account auth - Fix user_customuser -> auth_user table names in raw SQL - Fix dashboard verified query to use UserProfile model - Add escapeLikeWildcards() to prevent SQL wildcard injection Bug fixes: - Add bounds checks for days/expiring_soon query params (1-3650) - Add receipt_data/transaction_id empty-check to RestoreSubscription - Change Active bool -> *bool in device handler - Check all unchecked GORM/FindByIDWithProfile errors - Add validation for notification hour fields (0-23) - Add max=10000 validation on task description updates Transactions & data integrity: - Wrap registration flow in transaction - Wrap QuickComplete in transaction - Move image creation inside completion transaction - Wrap SetSpecialties in transaction - Wrap GetOrCreateToken in transaction - Wrap completion+image deletion in transaction Performance: - Batch completion summaries (2 queries vs 2N) - Reuse single http.Client in IAP validation - Cache dashboard counts (30s TTL) - Batch COUNT queries in admin user list - Add Limit(500) to document queries - Add reminder_stage+due_date filters to reminder queries - Parse AllowedTypes once at init - In-memory user cache in auth middleware (30s TTL) - Timezone change detection cache - Optimize P95 with per-endpoint sorted buffers - Replace crypto/md5 with hash/fnv for ETags Code quality: - Add sync.Once to all monitoring Stop()/Close() methods - Replace 8 fmt.Printf with zerolog in auth service - Log previously discarded errors - Standardize delete response shapes - Route hardcoded English through i18n - Remove FileURL from DocumentResponse (keep MediaURL only) - Thread user timezone through kanban board responses - Initialize empty slices to prevent null JSON - Extract shared field map for task Update/UpdateTx - Delete unused SoftDeleteModel, min(), formatCron, legacy handlers Worker & jobs: - Wire Asynq email infrastructure into worker - Register HandleReminderLogCleanup with daily 3AM cron - Use per-user timezone in HandleSmartReminder - Replace direct DB queries with repository calls - Delete legacy reminder handlers (~200 lines) - Delete unused task type constants Dependencies: - Replace archived jung-kurt/gofpdf with go-pdf/fpdf - Replace unmaintained gomail.v2 with wneessen/go-mail - Add TODO for Echo jwt v3 transitive dep removal Test infrastructure: - Fix MakeRequest/SeedLookupData error handling - Replace os.Exit(0) with t.Skip() in scope/consistency tests - Add 11 new FCM v1 tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -130,7 +130,7 @@ func (s *TaskService) ListTasks(userID uint, daysThreshold int, now time.Time) (
|
||||
return nil, apperrors.Internal(err)
|
||||
}
|
||||
|
||||
resp := responses.NewKanbanBoardResponseForAll(board)
|
||||
resp := responses.NewKanbanBoardResponseForAll(board, now)
|
||||
// NOTE: Summary statistics are calculated client-side from kanban data
|
||||
return &resp, nil
|
||||
}
|
||||
@@ -157,7 +157,7 @@ func (s *TaskService) GetTasksByResidence(residenceID, userID uint, daysThreshol
|
||||
return nil, apperrors.Internal(err)
|
||||
}
|
||||
|
||||
resp := responses.NewKanbanBoardResponse(board, residenceID)
|
||||
resp := responses.NewKanbanBoardResponse(board, residenceID, now)
|
||||
// NOTE: Summary statistics are calculated client-side from kanban data
|
||||
return &resp, nil
|
||||
}
|
||||
@@ -601,8 +601,8 @@ func (s *TaskService) CreateCompletion(req *requests.CreateTaskCompletionRequest
|
||||
task.InProgress = false
|
||||
}
|
||||
|
||||
// P1-5: Wrap completion creation and task update in a transaction.
|
||||
// If either operation fails, both are rolled back to prevent orphaned completions.
|
||||
// P1-5 + B-07: Wrap completion creation, task update, and image creation
|
||||
// in a single transaction for atomicity. If any operation fails, all are rolled back.
|
||||
txErr := s.taskRepo.DB().Transaction(func(tx *gorm.DB) error {
|
||||
if err := s.taskRepo.CreateCompletionTx(tx, completion); err != nil {
|
||||
return err
|
||||
@@ -610,6 +610,18 @@ func (s *TaskService) CreateCompletion(req *requests.CreateTaskCompletionRequest
|
||||
if err := s.taskRepo.UpdateTx(tx, task); err != nil {
|
||||
return err
|
||||
}
|
||||
// B-07: Create images inside the same transaction as completion
|
||||
for _, imageURL := range req.ImageURLs {
|
||||
if imageURL != "" {
|
||||
img := &models.TaskCompletionImage{
|
||||
CompletionID: completion.ID,
|
||||
ImageURL: imageURL,
|
||||
}
|
||||
if err := tx.Create(img).Error; err != nil {
|
||||
return fmt.Errorf("failed to create completion image: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if txErr != nil {
|
||||
@@ -621,19 +633,6 @@ func (s *TaskService) CreateCompletion(req *requests.CreateTaskCompletionRequest
|
||||
return nil, apperrors.Internal(txErr)
|
||||
}
|
||||
|
||||
// Create images if provided
|
||||
for _, imageURL := range req.ImageURLs {
|
||||
if imageURL != "" {
|
||||
img := &models.TaskCompletionImage{
|
||||
CompletionID: completion.ID,
|
||||
ImageURL: imageURL,
|
||||
}
|
||||
if err := s.taskRepo.CreateCompletionImage(img); err != nil {
|
||||
log.Error().Err(err).Uint("completion_id", completion.ID).Msg("Failed to create completion image")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reload completion with user info and images
|
||||
completion, err = s.taskRepo.FindCompletionByID(completion.ID)
|
||||
if err != nil {
|
||||
@@ -663,8 +662,10 @@ func (s *TaskService) CreateCompletion(req *requests.CreateTaskCompletionRequest
|
||||
}, nil
|
||||
}
|
||||
|
||||
// QuickComplete creates a minimal task completion (for widget use)
|
||||
// Returns only success/error, no response body
|
||||
// QuickComplete creates a minimal task completion (for widget use).
|
||||
// LE-01: The entire operation (completion creation + task update) is wrapped in a
|
||||
// transaction for atomicity.
|
||||
// Returns only success/error, no response body.
|
||||
func (s *TaskService) QuickComplete(taskID uint, userID uint) error {
|
||||
// Get the task
|
||||
task, err := s.taskRepo.FindByID(taskID)
|
||||
@@ -697,10 +698,6 @@ func (s *TaskService) QuickComplete(taskID uint, userID uint) error {
|
||||
CompletedFromColumn: completedFromColumn,
|
||||
}
|
||||
|
||||
if err := s.taskRepo.CreateCompletion(completion); err != nil {
|
||||
return apperrors.Internal(err)
|
||||
}
|
||||
|
||||
// Update next_due_date and in_progress based on frequency
|
||||
// Determine interval days: Custom frequency uses task.CustomIntervalDays, otherwise use frequency.Days
|
||||
// Note: Frequency is no longer preloaded for performance, so we load it separately if needed
|
||||
@@ -729,7 +726,6 @@ func (s *TaskService) QuickComplete(taskID uint, userID uint) error {
|
||||
} else {
|
||||
// Recurring task - calculate next due date from completion date + interval
|
||||
nextDue := completedAt.AddDate(0, 0, *quickIntervalDays)
|
||||
// frequencyName was already set when loading frequency above
|
||||
log.Info().
|
||||
Uint("task_id", task.ID).
|
||||
Str("frequency_name", frequencyName).
|
||||
@@ -742,12 +738,23 @@ func (s *TaskService) QuickComplete(taskID uint, userID uint) error {
|
||||
// Reset in_progress to false
|
||||
task.InProgress = false
|
||||
}
|
||||
if err := s.taskRepo.Update(task); err != nil {
|
||||
if errors.Is(err, repositories.ErrVersionConflict) {
|
||||
|
||||
// LE-01: Wrap completion creation and task update in a transaction for atomicity
|
||||
txErr := s.taskRepo.DB().Transaction(func(tx *gorm.DB) error {
|
||||
if err := s.taskRepo.CreateCompletionTx(tx, completion); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.taskRepo.UpdateTx(tx, task); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if txErr != nil {
|
||||
if errors.Is(txErr, repositories.ErrVersionConflict) {
|
||||
return apperrors.Conflict("error.version_conflict")
|
||||
}
|
||||
log.Error().Err(err).Uint("task_id", task.ID).Msg("Failed to update task after quick completion")
|
||||
return apperrors.Internal(err) // Return error so caller knows the update failed
|
||||
log.Error().Err(txErr).Uint("task_id", task.ID).Msg("Failed to create completion and update task in QuickComplete")
|
||||
return apperrors.Internal(txErr)
|
||||
}
|
||||
log.Info().Uint("task_id", task.ID).Msg("QuickComplete: Task updated successfully")
|
||||
|
||||
@@ -813,8 +820,16 @@ func (s *TaskService) sendTaskCompletedNotification(task *models.Task, completio
|
||||
// Send email notification (to everyone INCLUDING the person who completed it)
|
||||
// Check user's email notification preferences first
|
||||
if s.emailService != nil && user.Email != "" && s.notificationService != nil {
|
||||
prefs, err := s.notificationService.GetPreferences(user.ID)
|
||||
if err != nil || (prefs != nil && prefs.EmailTaskCompleted) {
|
||||
prefs, prefsErr := s.notificationService.GetPreferences(user.ID)
|
||||
// LE-06: Log fail-open behavior when preferences cannot be loaded
|
||||
if prefsErr != nil {
|
||||
log.Warn().
|
||||
Err(prefsErr).
|
||||
Uint("user_id", user.ID).
|
||||
Uint("task_id", task.ID).
|
||||
Msg("Failed to load notification preferences, falling back to sending email (fail-open)")
|
||||
}
|
||||
if prefsErr != nil || (prefs != nil && prefs.EmailTaskCompleted) {
|
||||
// Send email if we couldn't get prefs (fail-open) or if email notifications are enabled
|
||||
if err := s.emailService.SendTaskCompletedEmail(
|
||||
user.Email,
|
||||
|
||||
Reference in New Issue
Block a user