package syncapi_test import ( "database/sql" "errors" "fmt" "net/http" "strings" "testing" "github.com/pocketbase/pocketbase/core" "github.com/pocketbase/pocketbase/tests" _ "github.com/wotra/wotra/internal/migrations" "github.com/wotra/wotra/internal/syncapi" ) const ( recA = "aaaaaaaaaaaaaaa" recB = "bbbbbbbbbbbbbbb" recC = "ccccccccccccccc" recD = "ddddddddddddddd" ) const ( entryData = `"data":{"start_time":1000,"end_time":2000,"auto_stopped":false,"note":"%s","day_key":"2026-01-05"}` settingsData = `"data":{"effective_from":"2026-01-01","hours_per_week":40,"workdays_mask":31,"timezone":"Europe/Berlin"}` closedDay = `{"collection":"closed_days","id":"` + recB + `","data":{"day_key":"2026-01-05","worked_ms":1000,"kind":"work","closed_at":1},"client_updated_at":5,"deleted":false}` ) type env struct { app *tests.TestApp tokenA string tokenB string userA string userB string } func setup(t testing.TB) *env { app, err := tests.NewTestApp() if err != nil { t.Fatal(err) } syncapi.Register(app) users, err := app.FindCollectionByNameOrId("users") if err != nil { t.Fatal(err) } mk := func(email string) (*core.Record, string) { u := core.NewRecord(users) u.SetEmail(email) u.SetPassword("password123456") if err := app.Save(u); err != nil { t.Fatal(err) } token, _ := u.NewAuthToken() return u, token } ua, ta := mk("sync_a@example.com") ub, tb := mk("sync_b@example.com") seed(t, app, "entries", recA, ua.Id, map[string]any{ "start_time": 1000, "end_time": 2000, "auto_stopped": false, "note": "orig", "day_key": "2026-01-05", }) return &env{app: app, tokenA: ta, tokenB: tb, userA: ua.Id, userB: ub.Id} } func seed(t testing.TB, app *tests.TestApp, collection, id, owner string, data map[string]any) { col, err := app.FindCollectionByNameOrId(collection) if err != nil { t.Fatal(err) } r := core.NewRecord(col) r.Id = id r.Set("owner", owner) for field, value := range data { r.Set(field, value) } r.Set("client_updated_at", 1000) r.Set("rev", 1) if err := app.Save(r); err != nil { t.Fatal(err) } } func entry(id, note string, updatedAt int64, deleted bool) string { return fmt.Sprintf(`{"collection":"entries","id":%q,`+entryData+`,"client_updated_at":%d,"deleted":%t}`, id, note, updatedAt, deleted) } func settingsDelete(id string, updatedAt int64) string { return fmt.Sprintf(`{"collection":"settings_history","id":%q,`+settingsData+`,"client_updated_at":%d,"deleted":true}`, id, updatedAt) } func body(changes ...string) *strings.Reader { return strings.NewReader(`{"changes":[` + strings.Join(changes, ",") + `]}`) } func checkRecord(collection, id string, want map[string]any) func(testing.TB, *tests.TestApp, *http.Response) { return func(t testing.TB, app *tests.TestApp, _ *http.Response) { r, err := app.FindRecordById(collection, id) if err != nil { t.Fatal(err) } for field, expected := range want { var got any switch expected.(type) { case string: got = r.GetString(field) case int: got = r.GetInt(field) case bool: got = r.GetBool(field) } if got != expected { t.Fatalf("%s/%s %s: got %v, want %v", collection, id, field, got, expected) } } } } func checkNoRecord(collection, id string) func(testing.TB, *tests.TestApp, *http.Response) { return func(t testing.TB, app *tests.TestApp, _ *http.Response) { if _, err := app.FindRecordById(collection, id); !errors.Is(err, sql.ErrNoRows) { t.Fatalf("expected no %s record %s, got err=%v", collection, id, err) } } } func TestPush(t *testing.T) { cases := []struct { name string auth func(*env) string body string status int content []string after func(testing.TB, *tests.TestApp, *http.Response) }{ { name: "create entry", auth: func(e *env) string { return e.tokenA }, body: entry(recB, "new", 5, false), status: 200, content: []string{`"status":"ok"`, `"id":"` + recB + `"`, `"rev":1`, `"note":"new"`}, after: checkRecord("entries", recB, map[string]any{"note": "new", "day_key": "2026-01-05", "start_time": 1000, "end_time": 2000, "auto_stopped": false, "deleted": false, "rev": 1}), }, { name: "update entry bumps rev", auth: func(e *env) string { return e.tokenA }, body: entry(recA, "upd", 2000, false), status: 200, content: []string{`"status":"ok"`, `"rev":2`, `"note":"upd"`}, after: checkRecord("entries", recA, map[string]any{"note": "upd", "rev": 2, "deleted": false}), }, { name: "stale is rejected and returns the server record", auth: func(e *env) string { return e.tokenA }, body: entry(recA, "old", 500, true), status: 200, content: []string{`"status":"stale"`, `"note":"orig"`, `"rev":1`, `"deleted":false`}, after: checkRecord("entries", recA, map[string]any{"note": "orig", "rev": 1, "deleted": false}), }, { name: "another owner gets forbidden", auth: func(e *env) string { return e.tokenB }, body: entry(recA, "hack", 9999, false), status: 200, content: []string{`"status":"forbidden"`}, after: checkRecord("entries", recA, map[string]any{"note": "orig", "rev": 1}), }, { name: "closed_days change is readonly", auth: func(e *env) string { return e.tokenA }, body: closedDay, status: 200, content: []string{`"status":"readonly"`, `"collection":"closed_days"`}, after: checkNoRecord("closed_days", recB), }, { name: "unknown data field", auth: func(e *env) string { return e.tokenA }, body: `{"collection":"entries","id":"` + recB + `","data":{"evil":1},"client_updated_at":1,"deleted":false}`, status: 400, content: []string{`Changes[0]: unknown field \"evil\".`}, }, { name: "bad collection", auth: func(e *env) string { return e.tokenA }, body: `{"collection":"users","id":"` + recB + `","data":{},"client_updated_at":1,"deleted":false}`, status: 400, content: []string{`Changes[0]: invalid collection \"users\".`}, }, { name: "bad id", auth: func(e *env) string { return e.tokenA }, body: `{"collection":"entries","id":"BAD","data":{},"client_updated_at":1,"deleted":false}`, status: 400, content: []string{`Changes[0]: invalid id.`}, }, { name: "negative client_updated_at", auth: func(e *env) string { return e.tokenA }, body: entry(recB, "new", -1, false), status: 400, content: []string{`Changes[0]: invalid client_updated_at.`}, }, { name: "unauthenticated", auth: func(e *env) string { return "" }, body: entry(recB, "new", 1, false), status: 401, content: []string{`"data":{}`}, }, } for _, c := range cases { e := setup(t) headers := map[string]string{} if tok := c.auth(e); tok != "" { headers["Authorization"] = tok } s := tests.ApiScenario{ Name: c.name, Method: http.MethodPost, URL: "/api/sync/push", Body: body(c.body), Headers: headers, ExpectedStatus: c.status, ExpectedContent: c.content, TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, AfterTestFunc: c.after, } s.Test(t) } } func TestPushCreatedRecordIsOwnedByCaller(t *testing.T) { e := setup(t) (&tests.ApiScenario{ Name: "created entry belongs to the authenticated user", Method: http.MethodPost, URL: "/api/sync/push", Body: body(entry(recB, "new", 5, false)), Headers: map[string]string{"Authorization": e.tokenA}, ExpectedStatus: 200, ExpectedContent: []string{ `"status":"ok"`, `"owner":"` + e.userA + `"`, }, TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, AfterTestFunc: checkRecord("entries", recB, map[string]any{"owner": e.userA, "rev": 1}), }).Test(t) } func TestPushBatchIsAtomic(t *testing.T) { e := setup(t) // The second change fails validation (malformed day_key), so the first one must be rolled back too. batch := body(entry(recB, "new", 5, false), `{"collection":"entries","id":"`+recA+`","data":{"start_time":1000,"end_time":2000,"note":"upd","day_key":"2026-1-5"},"client_updated_at":2000,"deleted":false}`) (&tests.ApiScenario{ Name: "a failing change rolls back the whole batch", Method: http.MethodPost, URL: "/api/sync/push", Body: batch, Headers: map[string]string{"Authorization": e.tokenA}, ExpectedStatus: 400, ExpectedContent: []string{`"Failed to apply changes.`}, TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) { checkNoRecord("entries", recB)(t, app, res) checkRecord("entries", recA, map[string]any{"note": "orig", "rev": 1})(t, app, res) }, }).Test(t) } func TestPushSettingsDelete(t *testing.T) { seedSettings := func(e *env, ids ...string) { for _, id := range ids { seed(t, e.app, "settings_history", id, e.userA, map[string]any{ "effective_from": "2026-01-01", "hours_per_week": 40.0, "workdays_mask": 31, "timezone": "Europe/Berlin", }) } } e := setup(t) seedSettings(e, recC) (&tests.ApiScenario{ Name: "deleting the only settings row is stale", Method: http.MethodPost, URL: "/api/sync/push", Body: body(settingsDelete(recC, 2000)), Headers: map[string]string{"Authorization": e.tokenA}, ExpectedStatus: 200, ExpectedContent: []string{ `"status":"stale"`, `"id":"` + recC + `"`, `"rev":1`, `"deleted":false`, }, TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, AfterTestFunc: checkRecord("settings_history", recC, map[string]any{"deleted": false, "rev": 1}), }).Test(t) e = setup(t) seedSettings(e, recC, recD) (&tests.ApiScenario{ Name: "deleting one of two settings rows is ok", Method: http.MethodPost, URL: "/api/sync/push", Body: body(settingsDelete(recC, 2000)), Headers: map[string]string{"Authorization": e.tokenA}, ExpectedStatus: 200, ExpectedContent: []string{ `"status":"ok"`, `"id":"` + recC + `"`, `"rev":2`, `"deleted":true`, }, TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) { checkRecord("settings_history", recC, map[string]any{"deleted": true, "rev": 2})(t, app, res) checkRecord("settings_history", recD, map[string]any{"deleted": false, "rev": 1})(t, app, res) }, }).Test(t) } func superuserToken(t testing.TB, app *tests.TestApp) string { col, err := app.FindCollectionByNameOrId("_superusers") if err != nil { t.Fatal(err) } su := core.NewRecord(col) su.SetEmail("superuser@example.com") su.SetPassword("password123456") if err := app.Save(su); err != nil { t.Fatal(err) } token, _ := su.NewAuthToken() return token } func TestRestWrites(t *testing.T) { e := setup(t) (&tests.ApiScenario{ Name: "users cannot write synced collections over REST", Method: http.MethodPost, URL: "/api/collections/entries/records", Body: strings.NewReader(`{"id":"` + recB + `","owner":"` + e.userA + `","day_key":"2026-01-06","rev":42}`), Headers: map[string]string{"Authorization": e.tokenA}, ExpectedStatus: 403, ExpectedContent: []string{`"data":{}`}, TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, AfterTestFunc: checkNoRecord("entries", recB), }).Test(t) e = setup(t) (&tests.ApiScenario{ Name: "superuser REST create forces rev=1", Method: http.MethodPost, URL: "/api/collections/entries/records", Body: strings.NewReader(`{"id":"` + recB + `","owner":"` + e.userA + `","day_key":"2026-01-06","rev":42,"client_updated_at":1}`), Headers: map[string]string{"Authorization": superuserToken(t, e.app)}, ExpectedStatus: 200, ExpectedContent: []string{`"rev":1`, `"owner":"` + e.userA + `"`}, TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, }).Test(t) e = setup(t) (&tests.ApiScenario{ Name: "superuser REST update keeps owner and increments rev", Method: http.MethodPatch, URL: "/api/collections/entries/records/" + recA, Body: strings.NewReader(`{"owner":"` + e.userB + `","note":"p2","rev":42}`), Headers: map[string]string{"Authorization": superuserToken(t, e.app)}, ExpectedStatus: 200, ExpectedContent: []string{`"rev":2`, `"note":"p2"`, `"owner":"` + e.userA + `"`}, NotExpectedContent: []string{`"rev":42`, `"owner":"` + e.userB + `"`}, TestAppFactory: func(testing.TB) *tests.TestApp { return e.app }, AfterTestFunc: checkRecord("entries", recA, map[string]any{"owner": e.userA, "rev": 2, "note": "p2"}), }).Test(t) }