diff --git a/README.md b/README.md index b832592..31fa060 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr - **API documentation.** The full API is described in OpenAPI and browsable with Swagger UI, served by Sonda itself. The UI is embedded in the binary, so opening it contacts no other server. - **Listening history.** Clients report explicit `play`, `complete` and `skip` events. An event counts as a listen when it is `complete`, or when it was played for at least 20 seconds (`listening.min_listen_seconds`); the rule is applied when the history is read, so changing it re-reads the past. You can read your own history, with a `counted` flag on every event. It stays in your database and is never sent anywhere. - **Your taste.** `GET /me/taste` shows what Sonda has learned from your own listening: the artists you like and the kinds of music (tags) they have in common. A complete listen counts for more than a short one, a skip counts against the artist, and older listens weigh less (they halve every 90 days, `taste.half_life_days`; only the last ten half-lives are read). It is worked out on every request from data already in your database; nothing is sent to any provider. -- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so nothing about what you listen to can be sent to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on). +- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so this setting never sends your listening to a provider. When you turn it on, the Discover feature (coming next) may start from the artists you listen to most, and their names would be sent to Last.fm (only if an admin switched it on). - **Tags.** `GET /artists/{id}/tags` shows what Last.fm and MusicBrainz say kind of music an artist plays, each with its own weights, and the genres of the artist's own files, read offline. See [External providers](#external-providers). - **Similar artists.** With Last.fm switched on, `GET /artists/{id}/similar` lists artists similar to an artist, and says which of them you already have. See [External providers](#external-providers). Without it, Sonda makes no outbound network requests at all. diff --git a/internal/api/http/handlers_usersettings.go b/internal/api/http/handlers_usersettings.go index 8a725cb..fb5a1c4 100644 --- a/internal/api/http/handlers_usersettings.go +++ b/internal/api/http/handlers_usersettings.go @@ -3,6 +3,7 @@ package httpapi import ( "encoding/json" "errors" + "io" "net/http" "github.com/gin-gonic/gin" @@ -17,10 +18,6 @@ type userSettingsJSON struct { DiscoverFromListening bool `json:"discover_from_listening"` } -type updateUserSettingsRequest struct { - DiscoverFromListening *bool `json:"discover_from_listening"` // a pointer: absent means leave it alone -} - func writeUserSettingsError(c *gin.Context, err error) { if errors.Is(err, usersettings.ErrUserNotFound) { writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists") @@ -39,17 +36,43 @@ func (h *userSettingsHandlers) get(c *gin.Context) { c.JSON(http.StatusOK, userSettingsJSON{DiscoverFromListening: s.DiscoverFromListening}) } +// settingKeys are the settings a PATCH may name, spelt exactly like this. +var settingKeys = map[string]bool{"discover_from_listening": true} + +// parseSettingsPatch reads the body of PATCH /me/settings. It is strict because +// the settings are about privacy: one JSON object and nothing after it, only known +// settings spelt exactly, and a boolean (or null, which means "leave it alone") for each. +func parseSettingsPatch(body []byte) (usersettings.Patch, bool) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(body, &fields); err != nil || fields == nil { + return usersettings.Patch{}, false // not JSON, text after the object, or null + } + var p usersettings.Patch + for key, value := range fields { + if !settingKeys[key] { + return usersettings.Patch{}, false + } + var b *bool + if err := json.Unmarshal(value, &b); err != nil { + return usersettings.Patch{}, false + } + p.DiscoverFromListening = b + } + return p, true +} + func (h *userSettingsHandlers) update(c *gin.Context) { - // A misspelt setting must not be accepted and ignored: this is about privacy. - var req updateUserSettingsRequest - dec := json.NewDecoder(c.Request.Body) - dec.DisallowUnknownFields() - if err := dec.Decode(&req); err != nil { - writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body or unknown setting") + body, err := io.ReadAll(c.Request.Body) + if err != nil { + writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body") return } - s, err := h.svc.Update(c.Request.Context(), currentUserID(c), - usersettings.Patch{DiscoverFromListening: req.DiscoverFromListening}) + patch, ok := parseSettingsPatch(body) + if !ok { + writeError(c, http.StatusBadRequest, "invalid_input", "the body must be one JSON object with known settings, each a boolean") + return + } + s, err := h.svc.Update(c.Request.Context(), currentUserID(c), patch) if err != nil { writeUserSettingsError(c, err) return diff --git a/internal/api/http/usersettings_test.go b/internal/api/http/usersettings_test.go index 4c96f3c..28f7b50 100644 --- a/internal/api/http/usersettings_test.go +++ b/internal/api/http/usersettings_test.go @@ -1,7 +1,10 @@ package httpapi import ( + "bytes" "net/http" + "net/http/httptest" + "strconv" "testing" ) @@ -73,3 +76,66 @@ func TestSettingsRejectWhatIsNotABoolean(t *testing.T) { } } } + +// raw sends a body exactly as given, which do() cannot: it always encodes JSON. +func raw(t *testing.T, h http.Handler, token, body string) (int, string) { + t.Helper() + req := httptest.NewRequest("PATCH", "/api/v1/me/settings", bytes.NewReader([]byte(body))) + req.Header.Set("Authorization", "Bearer "+token) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec.Code, rec.Body.String() +} + +func TestSettingsAcceptOnlyOneExactObject(t *testing.T) { + h := newTestAPI(t) + alice := registerAndLogin(t, h) + for name, body := range map[string]string{ + "two objects": `{"discover_from_listening":false}{"discover_from_listening":true}`, + "trailing text": `{"discover_from_listening":true} nope`, + "null": `null`, + "empty body": ``, + "another case": `{"DISCOVER_FROM_LISTENING":true}`, + "an array": `[{"discover_from_listening":true}]`, + "a misspelt and a right": `{"discover_from_listening":true,"nope":1}`, + } { + code, out := raw(t, h, alice, body) + if code != http.StatusBadRequest { + t.Errorf("%s: %d %s, want 400", name, code, out) + } + } + // Nothing above changed anything. + if r := do(t, h, "GET", "/api/v1/me/settings", alice, nil); r.Body["discover_from_listening"] != false { + t.Errorf("a refused request changed the setting: %v", r.Body) + } + // What is accepted: an object with the setting, with a boolean or null, or with nothing. + for _, body := range []string{`{"discover_from_listening":true}`, `{"discover_from_listening":null}`, `{}`, ` { } `} { + if code, out := raw(t, h, alice, body); code != http.StatusOK { + t.Errorf("%q: %d %s, want 200", body, code, out) + } + } +} + +func TestSettingsOfADeletedAccountAreRefused(t *testing.T) { + h := newTestAPI(t) + admin := registerAndLogin(t, h) + cred := map[string]any{"username": "bob", "password": "longenough"} + created := do(t, h, "POST", "/api/v1/users", admin, cred) + if created.Code != http.StatusCreated { + t.Fatalf("create bob: %d %v", created.Code, created.Body) + } + bob, _ := do(t, h, "POST", "/api/v1/auth/login", "", cred).Body["access_token"].(string) + id := int64(created.Body["id"].(float64)) + if r := do(t, h, "DELETE", "/api/v1/users/"+itoa(id), admin, nil); r.Code != http.StatusNoContent { + t.Fatalf("delete bob: %d %v", r.Code, r.Body) + } + if r := do(t, h, "GET", "/api/v1/me/settings", bob, nil); r.Code != http.StatusUnauthorized { + t.Errorf("GET: %d %v, want 401", r.Code, r.Body) + } + on := map[string]any{"discover_from_listening": true} + if r := do(t, h, "PATCH", "/api/v1/me/settings", bob, on); r.Code != http.StatusUnauthorized { + t.Errorf("PATCH: %d %v, want 401", r.Code, r.Body) + } +} + +func itoa(n int64) string { return strconv.FormatInt(n, 10) } diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml index 9dd4d4b..62baf99 100644 --- a/internal/api/openapi/openapi.yaml +++ b/internal/api/openapi/openapi.yaml @@ -713,7 +713,9 @@ paths: summary: Change your own settings description: | Changes the settings named in the body and leaves the others alone. An empty object - changes nothing. `null` is the same as leaving a field out. + changes nothing. `null` is the same as leaving a field out. The body must be one JSON + object, with nothing after it, and the names must be spelt exactly: a setting that does + not exist is refused rather than ignored. security: [{bearerAuth: []}] requestBody: required: true @@ -1208,7 +1210,7 @@ components: application/json: schema: {$ref: '#/components/schemas/Error'} Unauthorized: - description: The access token is missing, invalid or expired (`unauthorized`). + description: The access token is missing, invalid or expired, or the account it belongs to no longer exists (`unauthorized`). content: application/json: schema: {$ref: '#/components/schemas/Error'} diff --git a/internal/storage/users.go b/internal/storage/users.go index af75aa3..28bab4a 100644 --- a/internal/storage/users.go +++ b/internal/storage/users.go @@ -144,6 +144,23 @@ func affectedOrNotFound(res sql.Result, err error, what string) error { return nil } +// SQLSTATE and SQLite extended result code of a foreign key violation. +const ( + postgresForeignKeyViolation = "23503" + sqliteConstraintForeignKey = 787 +) + +// isForeignKeyViolation says whether err is a row refused because it points at +// one that does not exist (for example settings for a user deleted a moment ago). +func isForeignKeyViolation(err error) bool { + var se *msqlite.Error + if errors.As(err, &se) { + return se.Code() == sqliteConstraintForeignKey + } + var pe *pgconn.PgError + return errors.As(err, &pe) && pe.Code == postgresForeignKeyViolation +} + func isUniqueViolation(err error) bool { var se *msqlite.Error if errors.As(err, &se) { diff --git a/internal/storage/usersettings.go b/internal/storage/usersettings.go index ebb89f8..6c47638 100644 --- a/internal/storage/usersettings.go +++ b/internal/storage/usersettings.go @@ -55,6 +55,9 @@ func (r *UserSettingsRepo) Update(ctx context.Context, userID int64, p usersetti `INSERT INTO user_settings (user_id, discover_from_listening) VALUES (?, ?) ON CONFLICT (user_id) DO UPDATE SET discover_from_listening = excluded.discover_from_listening`, userID, cur.DiscoverFromListening); err != nil { + if isForeignKeyViolation(err) { + return usersettings.ErrUserNotFound // deleted between the read and the write + } return fmt.Errorf("write user settings: %w", err) } } diff --git a/internal/storage/usersettings_test.go b/internal/storage/usersettings_test.go index c210206..7484f12 100644 --- a/internal/storage/usersettings_test.go +++ b/internal/storage/usersettings_test.go @@ -63,3 +63,18 @@ func TestUserSettingsRepo(t *testing.T) { } }) } + +func TestAForeignKeyFailureIsRecognised(t *testing.T) { + forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { + _, err := db.Exec("INSERT INTO user_settings (user_id, discover_from_listening) VALUES (424242, ?)", true) + if err == nil { + t.Fatal("expected a foreign key violation") + } + if !isForeignKeyViolation(err) { + t.Errorf("isForeignKeyViolation(%v) = false", err) + } + if isForeignKeyViolation(errors.New("something else")) { + t.Error("an unrelated error was taken for a foreign key violation") + } + }) +}