🐛 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
+165 -8
View File
@@ -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) {