From b41f83342c0b112dad7ccfbe6ac6de1df1f2fb71 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Tue, 1 Dec 2026 16:52:30 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Return=20server=20errors=20as=20?= =?UTF-8?q?500=20when=20marking=20a=20day=20fails?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Marking a day answered every error except an invalid day key with 422, including database errors. Only an invalid kind is a 422 now. Server errors are logged with their cause and answered with a generic message instead of the error text, which can contain SQL, and the timezone lookup logs at warn before it falls back to UTC. --- internal/tracking/days.go | 8 +- internal/tracking/settings.go | 15 ++- internal/tracking/tracking.go | 16 ++- internal/tracking/tracking_test.go | 173 +++++++++++++++++++++++++++-- 4 files changed, 196 insertions(+), 16 deletions(-) diff --git a/internal/tracking/days.go b/internal/tracking/days.go index 4cc4621..7b693ed 100644 --- a/internal/tracking/days.go +++ b/internal/tracking/days.go @@ -229,10 +229,14 @@ func handleMarkDay(e *core.RequestEvent) error { } rec, err := MarkDay(e.App, e.Auth.Id, e.Request.PathValue("dayKey"), body.Kind, time.Now()) if err != nil { - if errors.Is(err, ErrInvalidDayKey) { + switch { + case errors.Is(err, ErrInvalidDayKey): return writeError(e, http.StatusBadRequest, err) + case errors.Is(err, ErrInvalidKind): + return writeError(e, http.StatusUnprocessableEntity, err) } - return writeError(e, http.StatusUnprocessableEntity, err) + // Everything else is a server failure, for example a database error. + return writeError(e, http.StatusInternalServerError, err) } return e.JSON(http.StatusOK, rec) } diff --git a/internal/tracking/settings.go b/internal/tracking/settings.go index 357fec7..c59c736 100644 --- a/internal/tracking/settings.go +++ b/internal/tracking/settings.go @@ -52,13 +52,24 @@ func settingsAt(tx core.App, owner, dayKey string) (*core.Record, error) { return rows[0], nil } +// location returns the timezone of the settings effective on dayKey, or UTC when +// there are none or they cannot be read. A failed lookup is logged because UTC +// is only a guess at what the owner meant. func location(tx core.App, owner, dayKey string) *time.Location { set, err := settingsAt(tx, owner, dayKey) - if err != nil || set == nil { + if err != nil { + tx.Logger().Warn("cannot read the settings for the timezone, using UTC", + "owner", owner, "dayKey", dayKey, "error", err) return time.UTC } - loc, err := time.LoadLocation(set.GetString("timezone")) + if set == nil { + return time.UTC + } + timezone := set.GetString("timezone") + loc, err := time.LoadLocation(timezone) if err != nil { + tx.Logger().Warn("unknown timezone in the settings, using UTC", + "owner", owner, "dayKey", dayKey, "timezone", timezone, "error", err) return time.UTC } return loc diff --git a/internal/tracking/tracking.go b/internal/tracking/tracking.go index 3d6a49d..e95e2ca 100644 --- a/internal/tracking/tracking.go +++ b/internal/tracking/tracking.go @@ -52,13 +52,21 @@ func Register(app core.App) { }) } +// writeError answers err in the PocketBase error envelope plus the legacy "error" +// key, so that the old and the new client read the same message. A server error +// is logged with its cause and answered with a generic message, because the +// error text can contain SQL and other internals. func writeError(e *core.RequestEvent, status int, err error) error { - // The body carries the PocketBase error envelope plus the legacy "error" key so - // that both the old and the new client read the unchanged message. + message := err.Error() + if status >= http.StatusInternalServerError { + e.App.Logger().Error("tracking request failed", + "method", e.Request.Method, "path", e.Request.URL.Path, "status", status, "error", err) + message = "internal server error" + } return e.JSON(status, map[string]any{ "status": status, - "message": err.Error(), + "message": message, "data": map[string]any{}, - "error": err.Error(), + "error": message, }) } diff --git a/internal/tracking/tracking_test.go b/internal/tracking/tracking_test.go index 6efe96f..2bd79ca 100644 --- a/internal/tracking/tracking_test.go +++ b/internal/tracking/tracking_test.go @@ -1,9 +1,11 @@ package tracking import ( + "bytes" "errors" "fmt" "net/http" + "net/http/httptest" "strings" "testing" "time" @@ -357,6 +359,101 @@ func TestWeekDayKeysRejectsWeeksTheYearDoesNotHave(t *testing.T) { } } +// requestEvent builds the event of a request without running it through the router. +func requestEvent(app core.App, method, path string) (*core.RequestEvent, *httptest.ResponseRecorder) { + rec := httptest.NewRecorder() + e := &core.RequestEvent{App: app} + e.Response = rec + e.Request = httptest.NewRequest(method, path, nil) + return e, rec +} + +func TestWriteErrorHidesServerErrors(t *testing.T) { + e := setup(t) + app := loggedApp{App: e.app, logs: &bytes.Buffer{}} + + // A domain error is answered with its message and is not logged. + req, rec := requestEvent(app, http.MethodPost, "/api/days/"+dayMon+"/close") + if err := writeError(req, http.StatusConflict, ErrDayAlreadyClosed); err != nil { + t.Fatal(err) + } + for _, want := range []string{`"status":409`, `"message":"day is already closed"`, `"error":"day is already closed"`, `"data":{}`} { + if body := rec.Body.String(); !strings.Contains(body, want) { + t.Errorf("body lacks %s: %s", want, body) + } + } + if logs := app.logs.String(); strings.Contains(logs, "level=ERROR") { + t.Errorf("a domain error was logged as an error:\n%s", logs) + } + + // A server error is logged with its cause and answered with a generic message. + cause := errors.New("SELECT owner FROM entries: no such table: entries") + req, rec = requestEvent(app, http.MethodPost, "/api/days/"+dayMon+"/mark") + if err := writeError(req, http.StatusInternalServerError, cause); err != nil { + t.Fatal(err) + } + body := rec.Body.String() + for _, want := range []string{`"status":500`, `"message":"internal server error"`, `"error":"internal server error"`, `"data":{}`} { + if !strings.Contains(body, want) { + t.Errorf("body lacks %s: %s", want, body) + } + } + if strings.Contains(body, "SELECT") || strings.Contains(body, "no such table") { + t.Errorf("body leaks the cause: %s", body) + } + logs := app.logs.String() + for _, want := range []string{"level=ERROR", cause.Error(), "/api/days/" + dayMon + "/mark"} { + if !strings.Contains(logs, want) { + t.Errorf("logs lack %s:\n%s", want, logs) + } + } +} + +func TestLocationLogsTheFallback(t *testing.T) { + e := setup(t) + app := loggedApp{App: e.app, logs: &bytes.Buffer{}} + tokyo := e.settings("2026-06-01", 40, 31, "Asia/Tokyo") + + // Without a settings row there is nothing to look up, so nothing is logged. + if got := location(app, "someone-else", "2026-07-01"); got != time.UTC { + t.Errorf("owner without settings: got %s, want UTC", got) + } + if logs := app.logs.String(); logs != "" { + t.Errorf("logs without a failure:\n%s", logs) + } + + // An unknown timezone is logged together with the settings row it comes from. + tokyo.Set("timezone", "Mars/Olympus") + if err := e.app.Save(tokyo); err != nil { + t.Fatal(err) + } + if got := location(app, e.owner.Id, "2026-07-01"); got != time.UTC { + t.Errorf("invalid timezone: got %s, want UTC", got) + } + logs := app.logs.String() + for _, want := range []string{"level=WARN", "Mars/Olympus", "2026-07-01"} { + if !strings.Contains(logs, want) { + t.Errorf("logs lack %s:\n%s", want, logs) + } + } + + // A settings lookup that fails is logged with the error. + app.logs.Reset() + if _, err := e.app.DB().NewQuery("DROP TABLE settings_history").Execute(); err != nil { + t.Fatal(err) + } + if got := location(app, e.owner.Id, "2026-07-01"); got != time.UTC { + t.Errorf("failed lookup: got %s, want UTC", got) + } + logs = app.logs.String() + for _, want := range []string{"level=WARN", "no such table"} { + if !strings.Contains(logs, want) { + t.Errorf("logs lack %s:\n%s", want, logs) + } + } + +} + func TestHealthz(t *testing.T) { e := setup(t) (&tests.ApiScenario{ @@ -379,7 +476,9 @@ type routeCase struct { status int // content holds the body fragments that must be in the response. content []string - after func(t testing.TB, e *env) + // absent holds the body fragments that must not be in the response. + absent []string + after func(t testing.TB, e *env) } func runRoutes(t *testing.T, cases []routeCase) { @@ -395,13 +494,14 @@ func runRoutes(t *testing.T, cases []routeCase) { headers = c.as(e) } s := tests.ApiScenario{ - Name: c.name, - Method: c.method, - URL: c.url, - Headers: headers, - ExpectedStatus: c.status, - ExpectedContent: c.content, - TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, + Name: c.name, + Method: c.method, + URL: c.url, + Headers: headers, + ExpectedStatus: c.status, + ExpectedContent: c.content, + NotExpectedContent: c.absent, + TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, } if c.body != "" { s.Body = strings.NewReader(c.body) @@ -480,6 +580,41 @@ func TestDayRoutes(t *testing.T) { method: http.MethodPost, url: "/api/days/" + dayTue + "/mark", body: `{"kind":`, status: http.StatusBadRequest, content: []string{`"status":400`, `"error":"invalid JSON"`}, }, + { + // The settings cannot be read, so this is a server failure and not a + // validation problem: 500 with a generic message instead of 422 with SQL. + name: "mark day when the server fails", + seed: func(e *env) { + if _, err := e.app.DB().NewQuery("DROP TABLE settings_history").Execute(); err != nil { + t.Fatal(err) + } + }, + method: http.MethodPost, url: "/api/days/" + dayTue + "/mark", body: `{"kind":"holiday"}`, status: http.StatusInternalServerError, + content: []string{`"status":500`, `"message":"internal server error"`, `"error":"internal server error"`, `"data":{}`}, + absent: []string{"no such table", "settings_history"}, + }, + { + name: "close day when the server fails", + seed: func(e *env) { + if _, err := e.app.DB().NewQuery("DROP TABLE closed_days").Execute(); err != nil { + t.Fatal(err) + } + }, + method: http.MethodPost, url: closed, status: http.StatusInternalServerError, + content: []string{`"status":500`, `"error":"internal server error"`}, + absent: []string{"no such table", "closed_days"}, + }, + { + name: "reopen day when the server fails", + seed: func(e *env) { + if _, err := e.app.DB().NewQuery("DROP TABLE closed_days").Execute(); err != nil { + t.Fatal(err) + } + }, + method: http.MethodDelete, url: closed, status: http.StatusInternalServerError, + content: []string{`"status":500`, `"error":"internal server error"`}, + absent: []string{"no such table", "closed_days"}, + }, { name: "reopen day", seed: func(e *env) { @@ -596,6 +731,28 @@ func TestWeekRoutes(t *testing.T) { method: http.MethodPost, url: "/api/weeks/2024-W3/close", status: http.StatusBadRequest, content: []string{`"status":400`, `"error":"invalid week key, expected YYYY-Www"`}, }, + { + name: "close week when the server fails", + seed: func(e *env) { + if _, err := e.app.DB().NewQuery("DROP TABLE closed_weeks").Execute(); err != nil { + t.Fatal(err) + } + }, + method: http.MethodPost, url: closed, status: http.StatusInternalServerError, + content: []string{`"status":500`, `"error":"internal server error"`}, + absent: []string{"no such table", "closed_weeks"}, + }, + { + name: "reopen week when the server fails", + seed: func(e *env) { + if _, err := e.app.DB().NewQuery("DROP TABLE closed_weeks").Execute(); err != nil { + t.Fatal(err) + } + }, + method: http.MethodDelete, url: closed, status: http.StatusInternalServerError, + content: []string{`"status":500`, `"error":"internal server error"`}, + absent: []string{"no such table", "closed_weeks"}, + }, { name: "reopen week", seed: func(e *env) {