🐛 Return server errors as 500 when marking a day fails

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.
This commit is contained in:
2026-12-01 16:52:30 +01:00
parent 2bcf2d69a1
commit b41f83342c
4 changed files with 196 additions and 16 deletions
+6 -2
View File
@@ -229,11 +229,15 @@ func handleMarkDay(e *core.RequestEvent) error {
} }
rec, err := MarkDay(e.App, e.Auth.Id, e.Request.PathValue("dayKey"), body.Kind, time.Now()) rec, err := MarkDay(e.App, e.Auth.Id, e.Request.PathValue("dayKey"), body.Kind, time.Now())
if err != nil { if err != nil {
if errors.Is(err, ErrInvalidDayKey) { switch {
case errors.Is(err, ErrInvalidDayKey):
return writeError(e, http.StatusBadRequest, err) 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) return e.JSON(http.StatusOK, rec)
} }
+13 -2
View File
@@ -52,13 +52,24 @@ func settingsAt(tx core.App, owner, dayKey string) (*core.Record, error) {
return rows[0], nil 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 { func location(tx core.App, owner, dayKey string) *time.Location {
set, err := settingsAt(tx, owner, dayKey) 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 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 { 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 time.UTC
} }
return loc return loc
+12 -4
View File
@@ -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 { func writeError(e *core.RequestEvent, status int, err error) error {
// The body carries the PocketBase error envelope plus the legacy "error" key so message := err.Error()
// that both the old and the new client read the unchanged message. 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{ return e.JSON(status, map[string]any{
"status": status, "status": status,
"message": err.Error(), "message": message,
"data": map[string]any{}, "data": map[string]any{},
"error": err.Error(), "error": message,
}) })
} }
+157
View File
@@ -1,9 +1,11 @@
package tracking package tracking
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest"
"strings" "strings"
"testing" "testing"
"time" "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) { func TestHealthz(t *testing.T) {
e := setup(t) e := setup(t)
(&tests.ApiScenario{ (&tests.ApiScenario{
@@ -379,6 +476,8 @@ type routeCase struct {
status int status int
// content holds the body fragments that must be in the response. // content holds the body fragments that must be in the response.
content []string content []string
// absent holds the body fragments that must not be in the response.
absent []string
after func(t testing.TB, e *env) after func(t testing.TB, e *env)
} }
@@ -401,6 +500,7 @@ func runRoutes(t *testing.T, cases []routeCase) {
Headers: headers, Headers: headers,
ExpectedStatus: c.status, ExpectedStatus: c.status,
ExpectedContent: c.content, ExpectedContent: c.content,
NotExpectedContent: c.absent,
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
} }
if c.body != "" { if c.body != "" {
@@ -480,6 +580,41 @@ func TestDayRoutes(t *testing.T) {
method: http.MethodPost, url: "/api/days/" + dayTue + "/mark", body: `{"kind":`, status: http.StatusBadRequest, method: http.MethodPost, url: "/api/days/" + dayTue + "/mark", body: `{"kind":`, status: http.StatusBadRequest,
content: []string{`"status":400`, `"error":"invalid JSON"`}, 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", name: "reopen day",
seed: func(e *env) { 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, method: http.MethodPost, url: "/api/weeks/2024-W3/close", status: http.StatusBadRequest,
content: []string{`"status":400`, `"error":"invalid week key, expected YYYY-Www"`}, 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", name: "reopen week",
seed: func(e *env) { seed: func(e *env) {