Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
fix(#37): enforce settings validation + make the merge atomic (review fixes)
Cawlumm4fe6e42dbe4b
diff --git a/backend/controllers/settings_test.go b/backend/controllers/settings_test.goindex 0f74767..d7bfd36 100644--- a/backend/controllers/settings_test.go+++ b/backend/controllers/settings_test.go@@ -100,6 +100,34 @@ func TestUpdateSettings_partialUpdatePreservesCustomTargets(t *testing.T) {assertNum(t, d, "fat_target", 50)}+// Invalid values are rejected — the request tags are now actually enforced.+func TestUpdateSettings_rejectsInvalid(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ cases := []map[string]any{+ {"weight_unit": "stone"}, // not lbs/kg+ {"protein_target": -5}, // negative+ {"calorie_target": -1},+ }+ for _, body := range cases {+ c, w := newContext(uid, http.MethodPut, "/api/v1/settings", body)+ th.UpdateSettings(c)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("body %v: expected 400, got %d: %s", body, w.Code, w.Body.String())+ }+ }++ // The rejected requests must not have created/mutated a row.+ c, w := newContext(uid, http.MethodGet, "/api/v1/settings", nil)+ th.GetSettings(c)+ d := settingsData(t, w)+ assertNum(t, d, "protein_target", 150)+ if d["weight_unit"] != "lbs" {+ t.Fatalf("weight_unit = %v, want lbs (unchanged)", d["weight_unit"])+ }+}+// An explicit 0 is a real value (the pointer distinguishes it from "absent"),// so it must be stored while other omitted fields keep their values.func TestUpdateSettings_explicitZeroRespected(t *testing.T) {diff --git a/backend/controllers/user.go b/backend/controllers/user.goindex ea760b8..d80de6f 100644--- a/backend/controllers/user.go+++ b/backend/controllers/user.go@@ -43,6 +43,13 @@ func (h *Handler) UpdateSettings(c *gin.Context) {utils.BadRequest(c, err.Error())return}+ // Enforce the request tags (weight_unit oneof, targets gte=0) like every other+ // controller — binding alone doesn't run them, so without this an invalid unit+ // or a negative target would be persisted unchecked.+ if err := validate.Struct(req); err != nil {+ utils.BadRequest(c, err.Error())+ return+ }s, err := h.s.User.UpsertSettings(uid, req)if utils.DBError(c, err) {returndiff --git a/backend/stores/user.go b/backend/stores/user.goindex b7fefd6..9363d24 100644--- a/backend/stores/user.go+++ b/backend/stores/user.go@@ -38,48 +38,39 @@ func (s *UserStore) GetSettings(uid int64) (models.UserSettings, error) {return st, err}-// UpsertSettings applies a partial update and returns the stored row. It starts-// from the current row (or the defaults if none exists), overlays only the fields-// the client actually sent, then writes the merged row back — so a partial PUT-// (e.g. weight-unit only) can never zero the targets it omitted (#37).+// UpsertSettings applies a partial update and returns the merged row in a single+// atomic statement. For each field the nullable request value is COALESCEd over+// the default (on insert) or over the existing row (on conflict), so a partial PUT+// (e.g. weight-unit only) can never zero the fields it omitted (#37). Doing it in+// one INSERT…ON CONFLICT…RETURNING avoids a read-modify-write window where two+// concurrent partial updates could lose one another's change, and returns the+// stored row without a second SELECT. A nil pointer binds as SQL NULL; a non-nil+// pointer (incl. an explicit 0) binds as its value, so intentional zeros survive.func (s *UserStore) UpsertSettings(uid int64, req models.UpdateSettingsRequest) (models.UserSettings, error) {- cur, err := s.GetSettings(uid)- if err == sql.ErrNoRows {- cur = models.DefaultUserSettings(uid)- } else if err != nil {- return models.UserSettings{}, err- }-- if req.WeightUnit != nil {- cur.WeightUnit = *req.WeightUnit- }- if req.CalorieTarget != nil {- cur.CalorieTarget = *req.CalorieTarget- }- if req.ProteinTarget != nil {- cur.ProteinTarget = *req.ProteinTarget- }- if req.CarbTarget != nil {- cur.CarbTarget = *req.CarbTarget- }- if req.FatTarget != nil {- cur.FatTarget = *req.FatTarget- }-- if _, err := s.db.Exec(+ d := models.DefaultUserSettings(uid)+ var st models.UserSettings+ err := s.db.QueryRow(`INSERT INTO user_settings (user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target)- VALUES (?, ?, ?, ?, ?, ?)+ VALUES (?, COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?))ON CONFLICT(user_id) DO UPDATE SET- weight_unit = excluded.weight_unit,- calorie_target = excluded.calorie_target,- protein_target = excluded.protein_target,- carb_target = excluded.carb_target,- fat_target = excluded.fat_target`,- uid, cur.WeightUnit, cur.CalorieTarget, cur.ProteinTarget, cur.CarbTarget, cur.FatTarget,- ); err != nil {+ weight_unit = COALESCE(?, user_settings.weight_unit),+ calorie_target = COALESCE(?, user_settings.calorie_target),+ protein_target = COALESCE(?, user_settings.protein_target),+ carb_target = COALESCE(?, user_settings.carb_target),+ fat_target = COALESCE(?, user_settings.fat_target)+ RETURNING user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target`,+ uid,+ req.WeightUnit, d.WeightUnit,+ req.CalorieTarget, d.CalorieTarget,+ req.ProteinTarget, d.ProteinTarget,+ req.CarbTarget, d.CarbTarget,+ req.FatTarget, d.FatTarget,+ req.WeightUnit, req.CalorieTarget, req.ProteinTarget, req.CarbTarget, req.FatTarget,+ ).Scan(&st.UserID, &st.WeightUnit, &st.CalorieTarget, &st.ProteinTarget, &st.CarbTarget, &st.FatTarget)+ if err != nil {return models.UserSettings{}, err}- return s.GetSettings(uid)+ return st, nil}// Create inserts a user and their default settings atomically (one transaction —