Files
CollabTable/backend/db_test.go
T

866 lines
34 KiB
Go
Raw Normal View History

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 {
return a.doAs(method, path, device, testBearer, body)
}
func (a *testAPI) doAs(method, path, device, token 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 "+token)
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 (a *testAPI) mustDoAs(method, path, device, token string, body any, wantStatus int) *httptest.ResponseRecorder {
a.t.Helper()
recorder := a.doAs(method, path, device, token, 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()
if request.LastSyncToken == nil {
initialToken := int64(0)
request.LastSyncToken = &initialToken
}
request.DeviceID = device
return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK))
}
func (a *testAPI) currentSyncToken() int64 {
a.t.Helper()
var token int64
if err := a.db.pool.QueryRow(context.Background(), `SELECT token FROM collabtable_sync_clock WHERE id = 1`).Scan(&token); err != nil {
a.t.Fatalf("read sync token: %v", err)
}
return token
}
func ptrInt64(value int64) *int64 { return &value }
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.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('backfill', 'Backfill', $1, $1)`, t0); err != nil {
t.Fatal(err)
}
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists DISABLE TRIGGER lists_change_token`); err != nil {
t.Fatal(err)
}
if _, err := db.pool.Exec(context.Background(), `UPDATE lists SET change_token = 0 WHERE id = 'backfill'`); err != nil {
t.Fatal(err)
}
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists ENABLE TRIGGER lists_change_token`); err != nil {
t.Fatal(err)
}
if err := db.initSchema(context.Background()); err != nil {
t.Fatalf("second initSchema() error = %v", err)
}
var firstToken int64
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&firstToken); err != nil {
t.Fatal(err)
}
if firstToken == 0 {
t.Fatal("initSchema left an existing list without a change token")
}
if err := db.initSchema(context.Background()); err != nil {
t.Fatalf("third initSchema() error = %v", err)
}
var secondToken int64
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&secondToken); err != nil {
t.Fatal(err)
}
if secondToken != firstToken {
t.Fatalf("re-running initSchema changed backfilled token from %d to %d", firstToken, secondToken)
}
}
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 server returns a cursor from the same snapshot as its data page.
if got := api.sync("tablet", SyncRequest{LastSyncToken: &full.NextSyncToken}); 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{LastSyncToken: ptrInt64(0)}); len(got.Lists) != 1 || len(got.ItemValues) != 2 {
t.Fatalf("initial page returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues))
}
// The REST reads see the same data.
lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
if len(lists.Items) != 1 || lists.Items[0].Name != "Groceries" || lists.HasMore {
t.Fatalf("GET /api/lists = %+v, want the pushed list", lists)
}
values := decodeBody[PageResponse[ItemValue]](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK))
if len(values.Items) != 2 || values.HasMore {
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 TestCollectionEndpointsPageWithStableCursors(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
api.sync("phone", SyncRequest{
Lists: []List{testList("a-list", "A", t0+10, false)},
Items: []Item{testItem("a-item", "g-list", t0+10, false)},
})
tests := []struct {
name string
endpoint string
decode func(*testing.T, *httptest.ResponseRecorder) (string, string, bool)
}{
{
name: "lists",
endpoint: "/api/lists",
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
page := decodeBody[PageResponse[List]](t, recorder)
if len(page.Items) != 1 {
t.Fatalf("first list page has %d items, want 1", len(page.Items))
}
return page.Items[0].ID, page.NextCursor, page.HasMore
},
},
{
name: "fields",
endpoint: "/api/fields/list/g-list",
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
page := decodeBody[PageResponse[Field]](t, recorder)
if len(page.Items) != 1 {
t.Fatalf("first field page has %d items, want 1", len(page.Items))
}
return page.Items[0].ID, page.NextCursor, page.HasMore
},
},
{
name: "items",
endpoint: "/api/items/list/g-list",
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
page := decodeBody[PageResponse[Item]](t, recorder)
if len(page.Items) != 1 {
t.Fatalf("first item page has %d items, want 1", len(page.Items))
}
return page.Items[0].ID, page.NextCursor, page.HasMore
},
},
{
name: "values",
endpoint: "/api/items/g-item/values",
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
page := decodeBody[PageResponse[ItemValue]](t, recorder)
if len(page.Items) != 1 {
t.Fatalf("first value page has %d items, want 1", len(page.Items))
}
return page.Items[0].ID, page.NextCursor, page.HasMore
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
firstPath := test.endpoint + "?limit=1"
firstRecorder := api.mustDo(http.MethodGet, firstPath, "", nil, http.StatusOK)
firstID, cursor, hasMore := test.decode(t, firstRecorder)
if !hasMore || cursor == "" {
t.Fatalf("first page hasMore=%v cursor=%q, want another page", hasMore, cursor)
}
secondPath := firstPath + "&cursor=" + url.QueryEscape(cursor)
secondRecorder := api.mustDo(http.MethodGet, secondPath, "", nil, http.StatusOK)
secondID, nextCursor, hasMore := test.decode(t, secondRecorder)
if secondID == firstID {
t.Fatalf("cursor repeated item %q", firstID)
}
if hasMore || nextCursor != "" {
t.Fatalf("second page hasMore=%v cursor=%q, want final page", hasMore, nextCursor)
}
})
}
api.mustDo(http.MethodGet, "/api/lists?limit=501", "", nil, http.StatusBadRequest)
api.mustDo(http.MethodGet, "/api/lists?cursor=not-a-cursor", "", nil, http.StatusBadRequest)
api.mustDo(http.MethodGet, "/api/lists?cursor="+url.QueryEscape(encodePageCursor(pageCursor{Kind: "items", Key: 1, ID: "x"})), "", nil, http.StatusBadRequest)
}
func TestSyncUsesServerChangeTokenInsteadOfClientTimestamp(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
cursor := api.currentSyncToken()
clientTimestamp := Timestamp(time.Now().UnixMilli())
response := api.sync("tablet", SyncRequest{
LastSyncTimestamp: clientTimestamp,
LastSyncToken: ptrInt64(cursor),
Lists: []List{testList("g-list", "Edited offline", t0+20, false)},
})
if len(response.Lists) != 1 || response.Lists[0].Name != "Edited offline" {
t.Fatalf("change with an old client timestamp = %+v, want the updated list", response.Lists)
}
if response.NextSyncToken <= cursor {
t.Fatalf("next sync token = %d, want greater than previous cursor %d", response.NextSyncToken, cursor)
}
}
func TestSyncBoundsAndPagesLargeInitialSync(t *testing.T) {
api := newTestAPI(t)
api.mustDo(http.MethodPost, "/api/sync", "phone", map[string]any{}, http.StatusBadRequest)
lists := make([]List, 501)
for i := range lists {
id := fmt.Sprintf("list-%03d", i)
lists[i] = testList(id, id, t0+int64(i), false)
}
first := api.sync("phone", SyncRequest{Lists: lists})
if len(first.Lists) != syncPageSize || !first.HasMore {
t.Fatalf("first page has lists=%d hasMore=%v, want %d and true", len(first.Lists), first.HasMore, syncPageSize)
}
if first.NextSyncToken <= 0 || first.NextSyncToken >= first.ServerChangeToken {
t.Fatalf("first page tokens are next=%d server=%d, want next before server high-water mark", first.NextSyncToken, first.ServerChangeToken)
}
second := api.sync("phone", SyncRequest{LastSyncToken: ptrInt64(first.NextSyncToken)})
if len(second.Lists) != 1 || second.HasMore || second.NextSyncToken != second.ServerChangeToken {
t.Fatalf("second page has lists=%d hasMore=%v next=%d server=%d, want 1, false, and caught up", len(second.Lists), second.HasMore, second.NextSyncToken, second.ServerChangeToken)
}
if second.Lists[0].ID == first.Lists[len(first.Lists)-1].ID {
t.Fatalf("second page repeated list %q", second.Lists[0].ID)
}
}
func TestPerListMembershipScopesDataAndSync(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
const secondUserID = int64(2)
const secondToken = "second-user-device-token"
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken(secondToken)); err != nil {
t.Fatal(err)
}
firstUserLists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
if len(firstUserLists.Items) != 1 || firstUserLists.Items[0].ID != "g-list" {
t.Fatalf("first user lists = %+v, want g-list", firstUserLists.Items)
}
secondUserLists := decodeBody[PageResponse[List]](t, api.mustDoAs(http.MethodGet, "/api/lists", "", secondToken, nil, http.StatusOK))
if len(secondUserLists.Items) != 0 {
t.Fatalf("second user lists = %+v, want no access to the first user's list", secondUserLists.Items)
}
api.mustDoAs(http.MethodGet, "/api/items/g-item/values", "", secondToken, nil, http.StatusNotFound)
foreignCursor := int64(0)
foreignSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken,
SyncRequest{LastSyncToken: &foreignCursor}, http.StatusOK))
if len(foreignSync.Lists)+len(foreignSync.Fields)+len(foreignSync.Items)+len(foreignSync.ItemValues) != 0 {
t.Fatalf("second user's initial sync returned another list's data: %+v", foreignSync)
}
api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
LastSyncToken: ptrInt64(0),
Lists: []List{testList("g-list", "Overwritten", t0+20, false)},
}, http.StatusNotFound)
var name string
if err := api.db.pool.QueryRow(context.Background(), `SELECT name FROM lists WHERE id = 'g-list'`).Scan(&name); err != nil {
t.Fatal(err)
}
if name != "Groceries" {
t.Fatalf("unauthorized sync changed list name to %q", name)
}
newListSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
LastSyncToken: ptrInt64(0),
Lists: []List{testList("second-list", "Private", t0+30, false)},
}, http.StatusOK))
if len(newListSync.Lists) != 1 || newListSync.Lists[0].ID != "second-list" {
t.Fatalf("creator's sync response = %+v, want only second-list", newListSync.Lists)
}
if !hasMembership(t, api.db, secondUserID, "second-list") || hasMembership(t, api.db, testUserID, "second-list") {
t.Fatal("new sync list was not private to its creator")
}
var creator bool
if err := api.db.pool.QueryRow(context.Background(), `SELECT is_owner FROM list_memberships WHERE listid = 'second-list' AND user_id = $1`, secondUserID).Scan(&creator); err != nil {
t.Fatal(err)
}
if !creator {
t.Fatal("new sync list did not mark its creator as owner")
}
api.mustDo(http.MethodGet, "/api/lists/second-list", "", nil, http.StatusNotFound)
}
func TestMembershipBackfillPreservesCurrentAPITokenUsers(t *testing.T) {
api := newTestAPI(t)
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('legacy-list', 'Legacy', $1, $1)`, t0); err != nil {
t.Fatal(err)
}
const secondUserID = int64(2)
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken("second-user-device-token")); err != nil {
t.Fatal(err)
}
if err := api.db.backfillListMemberships(context.Background()); err != nil {
t.Fatal(err)
}
if !hasMembership(t, api.db, testUserID, "legacy-list") || !hasMembership(t, api.db, secondUserID, "legacy-list") {
t.Fatal("membership migration did not grant every current API-token user access to the legacy list")
}
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('new-list', 'New', $1, $1)`, t0); err != nil {
t.Fatal(err)
}
if err := api.db.withTx(context.Background(), func(tx pgx.Tx) error {
return addListOwner(context.Background(), tx, secondUserID, "new-list")
}); err != nil {
t.Fatal(err)
}
if err := api.db.backfillListMemberships(context.Background()); err != nil {
t.Fatal(err)
}
if hasMembership(t, api.db, testUserID, "new-list") {
t.Fatal("re-running membership backfill exposed a creator-owned list to another token user")
}
}
func hasMembership(t *testing.T, db *DB, userID int64, listID string) bool {
t.Helper()
member, err := hasListMembership(context.Background(), db.pool, userID, listID)
if err != nil {
t.Fatal(err)
}
return member
}
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")
seedCursor := api.currentSyncToken()
const kept = "list=0 fields=0/2 items=0/1 values=2"
api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(seedCursor), 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{LastSyncToken: ptrInt64(seedCursor), 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{LastSyncToken: ptrInt64(seedCursor)})
if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted {
t.Fatalf("delta after the delete = %+v, want the tombstone", delta.Lists)
}
if lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists.Items) != 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")
server := &Server{db: api.db}
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()
server.writeWebData(recorder, request, testUserID)
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)
}
}