package main import ( "bytes" "context" "crypto/rand" "encoding/hex" "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "os" "strings" "testing" "time" "github.com/jackc/pgx/v5" ) // These tests run the handlers against a real PostgreSQL. Set TEST_DATABASE_URL // to a postgres:// URL of a database the tests may write to; without it they are // skipped. Each test works in its own schema, which it drops afterwards, so the // database can be shared. TEST_DATABASE_URL must not be the service's own // DATABASE_URL. const ( testBearer = "test-device-token" // Realistic millisecond timestamps in the past, so normalizeTimestamp leaves // them alone. Later writes use t0 plus an offset. t0 = int64(1_700_000_000_000) ) // testDB returns a DB on a fresh schema of TEST_DATABASE_URL, with the tables // created by initSchema. func testDB(t *testing.T) *DB { t.Helper() base := strings.TrimSpace(os.Getenv("TEST_DATABASE_URL")) if base == "" { t.Skip("TEST_DATABASE_URL is not set; database-backed tests need a PostgreSQL they may write to") } if base == strings.TrimSpace(os.Getenv("DATABASE_URL")) { t.Fatal("TEST_DATABASE_URL must not be the same database as DATABASE_URL") } parsed, err := url.Parse(base) if err != nil { t.Fatalf("TEST_DATABASE_URL is not a URL: %v", err) } suffix := make([]byte, 6) if _, err := rand.Read(suffix); err != nil { t.Fatal(err) } schema := "collabtable_test_" + hex.EncodeToString(suffix) ctx := context.Background() admin, err := pgx.Connect(ctx, base) if err != nil { t.Fatalf("connect to TEST_DATABASE_URL: %v", err) } if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil { _ = admin.Close(ctx) t.Fatalf("create schema: %v", err) } query := parsed.Query() query.Set("search_path", schema) parsed.RawQuery = query.Encode() db, err := connectDB(ctx, parsed.String()) if err != nil { t.Fatalf("connectDB: %v", err) } t.Cleanup(func() { db.close() _, _ = admin.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE") _ = admin.Close(ctx) }) if err := db.initSchema(ctx); err != nil { t.Fatalf("initSchema: %v", err) } return db } // testUserID owns testBearer. It is not 0: identity 0 is the placeholder used // when login is off, and the sync API never accepts it. const testUserID = 1 // testAPI serves the real routes over a test database. Auth is disabled, and the // sync API accepts testBearer. type testAPI struct { t *testing.T db *DB mux *http.ServeMux } func newTestAPI(t *testing.T) *testAPI { t.Helper() db := testDB(t) server := &Server{ db: db, auth: newAuthService(db, "", false, true), syncSlots: make(chan struct{}, maxConcurrentSyncs), } mux := http.NewServeMux() server.registerRoutes(mux, webFS) if err := db.regenerateAPIToken(context.Background(), testUserID, hashToken(testBearer)); err != nil { t.Fatalf("seed API token: %v", err) } return &testAPI{t: t, db: db, mux: mux} } func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRecorder { a.t.Helper() var reader *bytes.Reader if body == nil { reader = bytes.NewReader(nil) } else { encoded, err := json.Marshal(body) if err != nil { a.t.Fatalf("encode request: %v", err) } reader = bytes.NewReader(encoded) } request := httptest.NewRequest(method, path, reader) request.Header.Set("Authorization", "Bearer "+testBearer) if device != "" { request.Header.Set("X-Device-Id", device) } recorder := httptest.NewRecorder() a.mux.ServeHTTP(recorder, request) return recorder } func (a *testAPI) mustDo(method, path, device string, body any, wantStatus int) *httptest.ResponseRecorder { a.t.Helper() recorder := a.do(method, path, device, body) if recorder.Code != wantStatus { a.t.Fatalf("%s %s status = %d, want %d; body %s", method, path, recorder.Code, wantStatus, recorder.Body.String()) } return recorder } func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T { t.Helper() var value T if err := json.Unmarshal(recorder.Body.Bytes(), &value); err != nil { t.Fatalf("decode %q: %v", recorder.Body.String(), err) } return value } func (a *testAPI) sync(device string, request SyncRequest) SyncResponse { a.t.Helper() request.DeviceID = device return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK)) } func (a *testAPI) count(query string, args ...any) int { a.t.Helper() var n int if err := a.db.pool.QueryRow(context.Background(), query, args...).Scan(&n); err != nil { a.t.Fatalf("%s: %v", query, err) } return n } func (a *testAPI) notifications(eventType, entityType, entityID string) int { a.t.Helper() return a.count(`SELECT count(*) FROM notifications WHERE eventtype = $1 AND entitytype = $2 AND entityid = $3`, eventType, entityType, entityID) } // cascadeState summarizes a list and its children, so two delete paths can be // compared: the list's isdeleted flag, deleted/total fields and items, and the // number of values left on the list's items. func (a *testAPI) cascadeState(listID string) string { a.t.Helper() return fmt.Sprintf("list=%d fields=%d/%d items=%d/%d values=%d", a.count(`SELECT isdeleted FROM lists WHERE id = $1`, listID), a.count(`SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 1`, listID), a.count(`SELECT count(*) FROM fields WHERE listid = $1`, listID), a.count(`SELECT count(*) FROM items WHERE listid = $1 AND isdeleted = 1`, listID), a.count(`SELECT count(*) FROM items WHERE listid = $1`, listID), a.count(`SELECT count(*) FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID), ) } func testList(id, name string, updatedAt int64, deleted bool) List { return List{ID: id, Name: name, CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted} } func testField(id, listID, name string, updatedAt int64, deleted bool) Field { return Field{ID: id, ListID: listID, Name: name, FieldType: "TEXT", Alignment: "start", CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted} } func testItem(id, listID string, updatedAt int64, deleted bool) Item { return Item{ID: id, ListID: listID, CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted} } func testValue(id, itemID, fieldID, value string, updatedAt int64) ItemValue { return ItemValue{ID: id, ItemID: itemID, FieldID: fieldID, Value: value, UpdatedAt: Timestamp(updatedAt)} } // seedList pushes a list with two fields, one item and a value in each field, all // stamped t0+10, as one device's first sync. Its IDs are prefix-list, prefix-f1, // prefix-f2, prefix-item, prefix-v1 and prefix-v2. func (a *testAPI) seedList(device, prefix string) { a.t.Helper() at := t0 + 10 a.sync(device, SyncRequest{ Lists: []List{testList(prefix+"-list", "Groceries", at, false)}, Fields: []Field{testField(prefix+"-f1", prefix+"-list", "Name", at, false), testField(prefix+"-f2", prefix+"-list", "Qty", at, false)}, Items: []Item{testItem(prefix+"-item", prefix+"-list", at, false)}, ItemValues: []ItemValue{ testValue(prefix+"-v1", prefix+"-item", prefix+"-f1", "milk", at), testValue(prefix+"-v2", prefix+"-item", prefix+"-f2", "2", at), }, }) } func TestInitSchemaCanRunAgainstAnExistingDatabase(t *testing.T) { db := testDB(t) if err := db.initSchema(context.Background()); err != nil { t.Fatalf("second initSchema() error = %v", err) } } func TestSyncRoundTripBetweenTwoDevices(t *testing.T) { api := newTestAPI(t) api.seedList("phone", "g") // A device that has never synced gets everything. full := api.sync("tablet", SyncRequest{}) if len(full.Lists) != 1 || len(full.Fields) != 2 || len(full.Items) != 1 || len(full.ItemValues) != 2 { t.Fatalf("first sync returned lists=%d fields=%d items=%d values=%d, want 1/2/1/2", len(full.Lists), len(full.Fields), len(full.Items), len(full.ItemValues)) } if full.ServerTimestamp <= 0 { t.Fatalf("serverTimestamp = %d, want a positive time", full.ServerTimestamp) } if len(full.OrphanItemValues) != 0 { t.Fatalf("orphanItemValues = %v, want none", full.OrphanItemValues) } // The delta filter is "updated at or after the cursor". if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 11)}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 { t.Fatalf("sync after the last change returned %+v, want nothing", got) } if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 10)}); len(got.Lists) != 1 || len(got.ItemValues) != 2 { t.Fatalf("sync at the change time returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues)) } // The REST reads see the same data. lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)) if len(lists) != 1 || lists[0].Name != "Groceries" { t.Fatalf("GET /api/lists = %+v, want the pushed list", lists) } values := decodeBody[[]ItemValue](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK)) if len(values) != 2 { t.Fatalf("GET item values = %+v, want 2", values) } // The first push is announced to the other device, and not back to its sender. toTablet := decodeBody[PollResponse](t, api.mustDo(http.MethodGet, "/api/notifications/poll?since=0", "tablet", nil, http.StatusOK)) if len(toTablet.Notifications) == 0 { t.Fatal("tablet got no notifications for the phone's push") } for _, event := range toTablet.Notifications { if event.DeviceIDOrigin != "phone" { t.Fatalf("notification origin = %q, want phone", event.DeviceIDOrigin) } } toPhone := decodeBody[PollResponse](t, api.mustDo(http.MethodGet, "/api/notifications/poll?since=0", "phone", nil, http.StatusOK)) if len(toPhone.Notifications) != 0 { t.Fatalf("phone got its own notifications back: %+v", toPhone.Notifications) } } func TestSyncLastWriterWinsByTimestamp(t *testing.T) { api := newTestAPI(t) push := func(name string, updatedAt int64) { api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("l1", name, updatedAt, false)}}) } name := func() string { return decodeBody[List](t, api.mustDo(http.MethodGet, "/api/lists/l1", "", nil, http.StatusOK)).Name } push("v2", t0+2000) events := api.notifications("updated", "list", "l1") push("v1", t0+1000) if got := name(); got != "v2" { t.Fatalf("name after an older write = %q, want v2", got) } if got := api.notifications("updated", "list", "l1"); got != events { t.Fatalf("an ignored write added %d notification(s)", got-events) } push("v3", t0+3000) if got := name(); got != "v3" { t.Fatalf("name after a newer write = %q, want v3", got) } push("v3b", t0+3000) if got := name(); got != "v3b" { t.Fatalf("name after a write with the same timestamp = %q, want v3b", got) } } func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) { api := newTestAPI(t) api.seedList("phone", "g") const kept = "list=0 fields=0/2 items=0/1 values=2" api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+5, true)}}) if got := api.cascadeState("g-list"); got != kept { t.Fatalf("state after a stale delete = %s, want %s", got, kept) } if got := api.notifications("deleted", "list", "g-list"); got != 0 { t.Fatalf("a stale delete produced %d deleted notification(s)", got) } api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+20, true)}}) if got, want := api.cascadeState("g-list"), "list=1 fields=2/2 items=1/1 values=0"; got != want { t.Fatalf("state after a newer delete = %s, want %s (fields and items soft-deleted, values removed)", got, want) } if got := api.notifications("deleted", "list", "g-list"); got != 1 { t.Fatalf("deleted notifications = %d, want 1", got) } // The tombstone travels to other devices, but the REST list read hides it. delta := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 15)}) if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted { t.Fatalf("delta after the delete = %+v, want the tombstone", delta.Lists) } if lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists) != 0 { t.Fatalf("GET /api/lists = %+v, want the deleted list hidden", lists) } } func TestDeletingTheLastFieldDeletesTheItems(t *testing.T) { api := newTestAPI(t) api.seedList("phone", "g") api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Fields: []Field{testField("g-f1", "g-list", "Name", t0+20, true)}}) if got, want := api.cascadeState("g-list"), "list=0 fields=1/2 items=0/1 values=1"; got != want { t.Fatalf("state after deleting one of two fields = %s, want %s", got, want) } // Through REST this time. The response says the items went with it. answer := decodeBody[map[string]any](t, api.mustDo(http.MethodDelete, "/api/fields/g-f2", "phone", nil, http.StatusOK)) if answer["cascadeItemsDeleted"] != true { t.Fatalf("DELETE last field answer = %v, want cascadeItemsDeleted true", answer) } if got, want := api.cascadeState("g-list"), "list=0 fields=2/2 items=1/1 values=0"; got != want { t.Fatalf("state after deleting the last field = %s, want %s", got, want) } } func TestRESTAndSyncDeletesLeaveTheSameState(t *testing.T) { api := newTestAPI(t) api.seedList("phone", "rest") api.seedList("phone", "sync") api.mustDo(http.MethodDelete, "/api/lists/rest-list", "phone", nil, http.StatusOK) api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("sync-list", "Groceries", time.Now().UnixMilli(), true)}}) const want = "list=1 fields=2/2 items=1/1 values=0" if got := api.cascadeState("rest-list"); got != want { t.Fatalf("REST delete left %s, want %s", got, want) } if got := api.cascadeState("sync-list"); got != want { t.Fatalf("sync delete left %s, want %s", got, want) } // Item deletes agree as well. api.seedList("phone", "ri") api.seedList("phone", "si") api.mustDo(http.MethodDelete, "/api/items/ri-item", "phone", nil, http.StatusOK) api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Items: []Item{testItem("si-item", "si-list", time.Now().UnixMilli(), true)}}) const wantItem = "list=0 fields=0/2 items=1/1 values=0" if got := api.cascadeState("ri-list"); got != wantItem { t.Fatalf("REST item delete left %s, want %s", got, wantItem) } if got := api.cascadeState("si-list"); got != wantItem { t.Fatalf("sync item delete left %s, want %s", got, wantItem) } } func TestSyncCannotMoveAValueOntoAnotherCell(t *testing.T) { api := newTestAPI(t) api.seedList("phone", "g") api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Items: []Item{testItem("g-item2", "g-list", t0+10, false)}}) // Same value id, newer timestamp, but naming another item and another field. api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{testValue("g-v1", "g-item2", "g-f2", "hijacked", t0+50)}}) var itemID, fieldID, value string if err := api.db.pool.QueryRow(context.Background(), `SELECT itemid, fieldid, value FROM item_values WHERE id = 'g-v1'`).Scan(&itemID, &fieldID, &value); err != nil { t.Fatal(err) } if itemID != "g-item" || fieldID != "g-f1" || value != "milk" { t.Fatalf("stored value = (%s, %s, %q), want it unchanged at (g-item, g-f1, milk)", itemID, fieldID, value) } if got := api.notifications("listContentUpdated", "value", "g-v1"); got != 1 { t.Fatalf("notifications for the value = %d, want only the original push", got) } } func TestSyncReportsValuesItCannotPlaceAndStubsMissingItems(t *testing.T) { api := newTestAPI(t) api.seedList("phone", "g") answer := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{ testValue("lost", "g-item", "no-such-field", "x", t0+20), testValue("late", "item-not-pushed-yet", "g-f1", "y", t0+20), }}) if len(answer.OrphanItemValues) != 1 || answer.OrphanItemValues[0].ID != "lost" || answer.OrphanItemValues[0].Reason != "missingField" { t.Fatalf("orphanItemValues = %+v, want only lost with reason missingField", answer.OrphanItemValues) } if got := api.count(`SELECT count(*) FROM item_values WHERE id = 'lost'`); got != 0 { t.Fatal("a value for a missing field was stored") } // A value for an item the server has not seen yet creates the item in the // field's list, so the value is kept. if got := api.count(`SELECT count(*) FROM items WHERE id = 'item-not-pushed-yet' AND listid = 'g-list' AND isdeleted = 0`); got != 1 { t.Fatalf("stub item rows = %d, want 1", got) } if got := api.count(`SELECT count(*) FROM item_values WHERE id = 'late'`); got != 1 { t.Fatalf("value rows for the stubbed item = %d, want 1", got) } } func TestFailedNotificationDoesNotAbortTheMutation(t *testing.T) { api := newTestAPI(t) if _, err := api.db.pool.Exec(context.Background(), `DROP TABLE notifications`); err != nil { t.Fatal(err) } // Every notification insert now fails. The sync still commits its data. api.sync("phone", SyncRequest{Lists: []List{testList("l1", "Kept", t0+10, false)}}) if got := api.count(`SELECT count(*) FROM lists WHERE id = 'l1'`); got != 1 { t.Fatal("the list was rolled back because its notification failed") } // So does a REST delete, which runs in a transaction. api.mustDo(http.MethodDelete, "/api/lists/l1", "phone", nil, http.StatusOK) if got := api.count(`SELECT isdeleted FROM lists WHERE id = 'l1'`); got != 1 { t.Fatal("the REST delete was rolled back because its notification failed") } } func TestRESTValueWriteIgnoresAnOlderTimestamp(t *testing.T) { api := newTestAPI(t) api.seedList("phone", "g") write := func(value string, updatedAt int64) ItemValue { return decodeBody[ItemValue](t, api.mustDo(http.MethodPost, "/api/items/values", "phone", testValue("g-v1", "g-item", "g-f1", value, updatedAt), http.StatusOK)) } if got := write("oat milk", t0+30); got.Value != "oat milk" { t.Fatalf("newer write answered %q, want oat milk", got.Value) } if got := write("stale", t0+20); got.Value != "oat milk" || int64(got.UpdatedAt) != t0+30 { t.Fatalf("older write answered %+v, want the stored oat milk at t0+30", got) } } func TestWebDataSupportsConditionalRequests(t *testing.T) { api := newTestAPI(t) api.seedList("phone", "g") get := func(etag string) *httptest.ResponseRecorder { request := httptest.NewRequest(http.MethodGet, "/web/data", nil) if etag != "" { request.Header.Set("If-None-Match", etag) } recorder := httptest.NewRecorder() api.mux.ServeHTTP(recorder, request) return recorder } first := get("") if first.Code != http.StatusOK { t.Fatalf("GET /web/data status = %d, want 200; body %s", first.Code, first.Body.String()) } var payload struct { Lists []struct { ID string `json:"id"` EffectiveUpdatedAt int64 `json:"effectiveUpdatedAt"` } `json:"lists"` Stats map[string]int `json:"stats"` } if err := json.Unmarshal(first.Body.Bytes(), &payload); err != nil { t.Fatal(err) } if len(payload.Lists) != 1 || payload.Lists[0].EffectiveUpdatedAt != t0+10 || payload.Stats["values"] != 2 { t.Fatalf("payload = %+v, want one list effective at t0+10 and two values", payload) } etag := first.Header().Get("ETag") if etag == "" { t.Fatal("GET /web/data sent no ETag") } if again := get(etag); again.Code != http.StatusNotModified { t.Fatalf("unchanged data status = %d, want 304", again.Code) } api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{testValue("g-v1", "g-item", "g-f1", "oat milk", t0+40)}}) if changed := get(etag); changed.Code != http.StatusOK { t.Fatalf("changed data status = %d, want 200", changed.Code) } } func TestRegeneratingAnAccountsTokenReplacesTheOldOne(t *testing.T) { api := newTestAPI(t) const fresh = "replacement-device-token" if err := api.db.regenerateAPIToken(context.Background(), testUserID, hashToken(fresh)); err != nil { t.Fatal(err) } if old := api.do(http.MethodGet, "/api/lists", "", nil); old.Code != http.StatusUnauthorized { t.Fatalf("old token status = %d, want 401", old.Code) } request := httptest.NewRequest(http.MethodGet, "/api/lists", nil) request.Header.Set("Authorization", "Bearer "+fresh) recorder := httptest.NewRecorder() api.mux.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Fatalf("new token status = %d, want 200", recorder.Code) } } // With login off (AUTH_DISABLED, or the login-required override) a caller with no // session can reach token regeneration, but only as the placeholder identity 0. // A token minted that way must not open the sync API. func TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI(t *testing.T) { api := newTestAPI(t) answer := decodeBody[map[string]string](t, api.mustDo(http.MethodPost, "/api/auth/token/regenerate", "", nil, http.StatusOK)) minted := answer["token"] if minted == "" { t.Fatalf("regenerate answer = %v, want a token", answer) } if got := api.count(`SELECT count(*) FROM api_tokens WHERE user_id = 0`); got != 1 { t.Fatalf("tokens stored for identity 0 = %d, want 1", got) } for _, probe := range []struct{ method, path string }{ {http.MethodGet, "/api/lists"}, {http.MethodPost, "/api/sync"}, } { request := httptest.NewRequest(probe.method, probe.path, strings.NewReader("{}")) request.Header.Set("Authorization", "Bearer "+minted) recorder := httptest.NewRecorder() api.mux.ServeHTTP(recorder, request) if recorder.Code != http.StatusUnauthorized { t.Fatalf("%s %s with a session-less token status = %d, want 401", probe.method, probe.path, recorder.Code) } } // And it did not disturb the real account's token. api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK) } func TestSetupClaimCanBeTakenOnceAndReopened(t *testing.T) { db := testDB(t) ctx := context.Background() claimed, err := db.IsSetupClaimed(ctx) if err != nil || claimed { t.Fatalf("IsSetupClaimed() on a new database = %v, %v, want false", claimed, err) } if won, err := db.TryClaimSetup(ctx); err != nil || !won { t.Fatalf("first TryClaimSetup() = %v, %v, want true", won, err) } if won, err := db.TryClaimSetup(ctx); err != nil || won { t.Fatalf("second TryClaimSetup() = %v, %v, want false", won, err) } if err := db.UnclaimSetup(ctx); err != nil { t.Fatal(err) } if won, err := db.TryClaimSetup(ctx); err != nil || !won { t.Fatalf("TryClaimSetup() after UnclaimSetup() = %v, %v, want true", won, err) } }