From 937f51b4fbc5ecfa3b06c566e4e5aeb72e2ee7c2 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Mon, 19 Oct 2026 21:16:08 +0000 Subject: [PATCH] fix: address performance and security findings - Add PostgreSQL-backed backend and frontend tests to CI - Harden Android API logging and disable app backups - Update the performance report with resolved findings --- .github/workflows/tests.yml | 20 + CollabTableAndroid/app/build.gradle | 1 + .../app/src/main/AndroidManifest.xml | 2 +- .../com/collabtable/app/data/api/ApiClient.kt | 21 +- PERFORMANCE_REPORT.md | 19 +- QUALITY_REPORT.md | 33 +- README.md | 14 +- SECURITY_REPORT.md | 45 +- backend/.env.example | 26 +- backend/README.md | 54 +- backend/auth.go | 11 +- backend/clientip.go | 95 +++ backend/clientip_test.go | 121 ++++ backend/csp.go | 51 ++ backend/csp_test.go | 95 +++ backend/data.go | 256 ++++++-- backend/data_test.go | 14 + backend/db.go | 4 + backend/db_test.go | 581 ++++++++++++++++++ backend/notifications.go | 27 + backend/ratelimit.go | 212 +++++++ backend/ratelimit_test.go | 226 +++++++ backend/routes_test.go | 29 +- backend/server.go | 211 ++++++- backend/server_test.go | 203 ++++++ backend/sync.go | 367 +++++------ backend/sync_test.go | 21 + frontend/package.json | 1 + .../src/lib/components/lists/ListsGrid.svelte | 9 +- .../lib/components/lists/ListsTable.svelte | 9 +- .../src/lib/features/lists/listHelpers.js | 16 +- .../lib/features/lists/listHelpers.test.js | 89 +++ frontend/src/routes/+page.svelte | 9 +- frontend/src/routes/lists/[id]/+page.svelte | 5 +- frontend/vite.config.js | 1 + 35 files changed, 2566 insertions(+), 332 deletions(-) create mode 100644 backend/clientip.go create mode 100644 backend/clientip_test.go create mode 100644 backend/csp.go create mode 100644 backend/csp_test.go create mode 100644 backend/data_test.go create mode 100644 backend/db_test.go create mode 100644 backend/ratelimit.go create mode 100644 backend/ratelimit_test.go create mode 100644 backend/server_test.go create mode 100644 frontend/src/lib/features/lists/listHelpers.test.js diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 18bd147..b4a8b69 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -29,6 +29,21 @@ jobs: working-directory: backend permissions: contents: read + # A throwaway database for the handler and sync tests. They create their own + # schema in it and drop it again, and are skipped when TEST_DATABASE_URL is unset. + services: + postgres: + image: postgres:16 + env: + POSTGRES_PASSWORD: postgres + POSTGRES_DB: collabtable_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres" + --health-interval 5s + --health-timeout 5s + --health-retries 10 steps: - name: Checkout @@ -43,6 +58,8 @@ jobs: - name: Test run: go test ./... + env: + TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/collabtable_test?sslmode=disable frontend: name: Dashboard checks @@ -72,3 +89,6 @@ jobs: - name: Check dashboard run: npm run check + + - name: Unit tests + run: npm test diff --git a/CollabTableAndroid/app/build.gradle b/CollabTableAndroid/app/build.gradle index f7edae1..246ace1 100644 --- a/CollabTableAndroid/app/build.gradle +++ b/CollabTableAndroid/app/build.gradle @@ -40,6 +40,7 @@ android { } buildFeatures { compose = true + buildConfig = true } packaging { resources { diff --git a/CollabTableAndroid/app/src/main/AndroidManifest.xml b/CollabTableAndroid/app/src/main/AndroidManifest.xml index 4a0048f..c92000d 100644 --- a/CollabTableAndroid/app/src/main/AndroidManifest.xml +++ b/CollabTableAndroid/app/src/main/AndroidManifest.xml @@ -8,7 +8,7 @@ = $1`, but `lists`, `fields`, `items` and `item_values` have no index on `updatedat`. Rows are soft-deleted and never physically removed, so the tables only grow. - **Impact:** Every sync from every device performs four full table scans, and the cost grows with history rather than with recent change volume. - **Recommendation:** Add `CREATE INDEX IF NOT EXISTS` on `updatedat` for `lists`, `items`, `fields` and `item_values` in `initSchema`. Consider `(isdeleted, updatedat)` if soft-delete filtering is common in the same queries. +- **Status:** Fixed 2026-10-19 — `initSchema` creates indexes on `updatedat` for lists, fields, items and item values, so delta queries stop scanning whole tables. The index builds run at startup and briefly block writes on large tables. Files: backend/db.go. -### P-004 · No pagination on list endpoints or the sync response; the first sync returns everything · **Medium** +### P-004 · No pagination on list endpoints or the sync response; the first sync returns everything · **Medium** · Open - **Location:** `backend/data.go:68-204` (`queryLists`, `queryFields`, `queryItems`, `queryValues`, none with LIMIT), `backend/data.go:228-235` (`GET /api/lists`), `backend/sync.go:216-248` (`since` is nil when `lastSync == 0`, so the full table is returned). - **Description:** Collection endpoints return unbounded arrays. The first sync from any device (`lastSync == 0`) returns every list, field, item and value in the database in one response. - **Impact:** Response size and server memory grow linearly with total data. Large first syncs risk the 60-second write timeout and slow mobile clients. - **Recommendation:** Add keyset pagination (a `(updatedat, id)` cursor and a `limit` parameter) to the collection endpoints. For sync, return a `hasMore` flag and a cursor, and let the client loop until it is caught up. +- **Status:** Open 2026-10-19 — Re-checked, unchanged: the collection queries have no LIMIT and `lastSync == 0` still returns every row. Decision needed: the pagination contract (`hasMore` plus a cursor, or keyset on `(updatedat, id)`), the default page size, and the rollout order. CollabTableAndroid has to loop until caught up before the server may page, or existing clients would silently get a truncated sync. -### P-005 · Frontend scans full arrays for every row, card and cell on each poll · **Medium** +### P-005 · Frontend scans full arrays for every row, card and cell on each poll · **Medium** · Fixed - **Location:** `frontend/src/routes/lists/[id]/+page.svelte:94` (`itemValuesFor(overview.values, item.id)` runs once per visible row and scans every value in the database) and `:98` (`valueFor` per cell); `frontend/src/lib/components/lists/ListCard.svelte:7-8` (each card filters all fields and all items); `frontend/src/lib/features/lists/listHelpers.js:1-15` (linear `filter` and `find` with no index). - **Description:** The helpers are linear scans over the complete data set, and they run for every visible row and card. Because each 5-second poll replaces the arrays, every derived value is recomputed on every poll. - **Impact:** Cost per render is roughly visible rows times total values. With a large data set this appears as delayed input and scroll jank. - **Recommendation:** Build lookup maps once per data change in a `$derived` (a `Map` keyed by `listId`, by `itemId`, and by `itemId + fieldId`). Pass pre-grouped slices into the card and row components. Rely on TanStack's structural sharing so unchanged data keeps its references. +- **Status:** Fixed 2026-10-19 — Fields, items and item values are grouped once per data change with `groupByKey`, and each grid card, table row and detail row reads only its own slice. `itemValuesFor` is removed because it had no other callers. Files: frontend/src/lib/features/lists/listHelpers.js, frontend/src/routes/+page.svelte, frontend/src/routes/lists/[id]/+page.svelte, frontend/src/lib/components/lists/ListsGrid.svelte, frontend/src/lib/components/lists/ListsTable.svelte. -### P-006 · No HTTP compression and no cache headers on JSON or static assets · **Medium** +### P-006 · No HTTP compression and no cache headers on JSON or static assets · **Medium** · Fixed - **Location:** `backend/server.go:118-125` (plain `http.Server`, no compression middleware), `backend/server.go:292-316` (`spaFileServer` sets no `Cache-Control`), `backend/web.go:74-76` (`no-store` on `/web/data`). - **Description:** JSON responses (`/web/data`, `/api/sync`, `/api/lists`) are sent uncompressed. Static build output, including content-hashed Vite assets, is served with no cache-control, and the embedded filesystem provides no modification times for conditional requests. - **Impact:** Large JSON bodies transfer several times more bytes than necessary, and browsers refetch the whole app bundle on each visit. - **Recommendation:** Add gzip or brotli middleware, or enable it at the reverse proxy. Set `Cache-Control: public, max-age=31536000, immutable` for `_app/immutable/*` and `no-cache` for `index.html`. Add ETags for `/web/data` (see P-001). +- **Status:** Fixed 2026-10-19 — Responses are gzip-compressed for clients that accept it, `_app/immutable/` assets are cached for a year as immutable, and `index.html` and other static files are sent with `no-cache`. Files: backend/server.go, backend/server_test.go. -### P-007 · Request bodies up to 50 MB are decoded into memory with no per-route limit · **Medium** +### P-007 · Request bodies up to 50 MB are decoded into memory with no per-route limit · **Medium** · Fixed - **Location:** `backend/server.go:253-259` (`decodeJSON` uses `io.LimitReader(r.Body, 50*1024*1024)`), used by `backend/sync.go:46` and by the write handlers in `backend/data.go`. - **Description:** Every write endpoint accepts up to 50 MB of JSON and decodes it fully into Go structs. `io.LimitReader` truncates silently, so an oversized body fails with a confusing decode error instead of `413`. These handlers have no concurrency cap, so each concurrent request can allocate its full decode buffer. - **Impact:** A few concurrent large requests can exhaust memory. It is also an easy denial-of-service vector (see the rate-limiting note in the Security report). - **Recommendation:** Use `http.MaxBytesReader` with per-route limits (for example 1 to 5 MB for single-entity writes, and a higher bound for sync), returning `413` when exceeded. Bound concurrent sync transactions with a semaphore sized below `DATABASE_MAX_CONNS`. +- **Status:** Fixed 2026-10-19 — Request bodies are limited with `http.MaxBytesReader` (2 MB for single-entity writes, 50 MB for sync), oversized bodies get 413, and at most four syncs run at once. Single-entity writes above 2 MB now fail with 413; the shared auth proxy already caps bodies at 128 KB. Files: backend/server.go, backend/sync.go, backend/data.go. ### P-008 · One notification row per changed row, on every write path · **Low** - **Location:** `backend/sync.go:79`, `:126`, `:164`, `:206`; `backend/data.go:256`, `:302`, `:364`, `:418`, `:507`, `:561`, `:605`, `:621`; retention in `backend/db.go:212-230`; polling in `backend/web.go:92-141` (`LIMIT 500` at `:109`). diff --git a/QUALITY_REPORT.md b/QUALITY_REPORT.md index 6eeeb0b..2b5b5ea 100644 --- a/QUALITY_REPORT.md +++ b/QUALITY_REPORT.md @@ -5,58 +5,65 @@ - **Analyzed:** 2026-10-16 - **Commit:** 6aec03f on main - **Working tree:** clean (no uncommitted changes, no untracked files) +- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed); open Medium findings name their blocker in their status lines. A second Medium pass added database-backed backend tests, frontend helper tests and a CI Postgres service (Q-004, still open for Android tests) and re-checked Q-006. - **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, Tailwind 4, TanStack Query) embedded in the Go binary; Android client (Kotlin, Jetpack Compose, Room, Retrofit/OkHttp); Docker; GitHub Actions. - **Scope:** Read all first-party backend code (`backend/*.go`, including the five test files), the frontend data layer, routes, list components and Vite config, the Android API client, preferences, sync repository and app Gradle file, `README.md`, `.github/workflows/*`, `docker/Dockerfile`, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper jar, generated build output, lock files (read for versions only), and the rest of `shared/`. The tracked SQLite files were inspected read-only from a copy. No tests, linters or builds were run. ## Summary -| Severity | Count | -|---|---:| -| Critical | 0 | -| High | 0 | -| Medium | 6 | -| Low | 8 | -| Info | 0 | +| Severity | Count | Fixed | Not reproduced | Open | +|---|---:|---:|---:|---:| +| Critical | 0 | 0 | 0 | 0 | +| High | 0 | 0 | 0 | 0 | +| Medium | 6 | 4 | 0 | 2 | +| Low | 8 | 0 | 0 | 8 | +| Info | 0 | 0 | 0 | 0 | The backend is small and readable, but its transactional and delete logic is duplicated across the REST and sync paths and has drifted apart. A few error-handling assumptions are wrong, and the data layer has essentially no test coverage. ## Issues -### Q-001 · Notification errors inside transactions abort the sync they were meant to tolerate · **Medium** +### Q-001 · Notification errors inside transactions abort the sync they were meant to tolerate · **Medium** · Fixed - **Location:** `backend/notifications.go:51-57` (`ignoreNotificationError`); called inside transactions at `backend/sync.go:79`, `:126`, `:164`, `:206` and `backend/data.go:453`. - **Description:** `ignoreNotificationError` says a failed notification "must never roll back the data mutation". When the notification insert runs inside the transaction, PostgreSQL marks the transaction as aborted after any failing statement, so the next statement fails and the commit cannot succeed. The error is only logged, which makes the function look like it tolerates the failure, but the whole sync then returns `500 Sync failed` after rolling back. The comment is wrong for these paths. - **Impact:** A transient failure of a notification insert turns a successful write into a failed sync, and the client retries the same payload. Maintainers reading the comment will assume the opposite of what happens. - **Recommendation:** Isolate the notification insert in a savepoint (a nested `tx.Begin` in pgx, or `SAVEPOINT` and `ROLLBACK TO SAVEPOINT`), or write notifications after commit. Update the comment to match the actual behavior. +- **Status:** Fixed 2026-10-19 — Notification inserts inside a transaction now run in a savepoint (`enqueueNotificationInTx`), so a failed insert rolls back only the notification and the data change still commits. Each such notification adds two statements (savepoint and release). Files: backend/notifications.go, backend/sync.go, backend/data.go. -### Q-002 · Delete semantics differ between REST endpoints and sync · **Medium** +### Q-002 · Delete semantics differ between REST endpoints and sync · **Medium** · Fixed - **Location:** `backend/data.go:309-321` (REST list delete sets only `lists.isdeleted`); `backend/sync.go:81-91` (sync list delete also cascades to fields, items and values); `backend/data.go:420-455` (field delete cascades only when no active fields remain); `backend/data.go:609-621` (item delete updates the item, then deletes its values in a separate statement whose error is discarded at `:620`, and skips the notification at `:618-619` if the re-read fails). - **Description:** The same logical operations (delete a list, delete an item) leave different state depending on the entry point. A list deleted through REST keeps its fields, items and values active, while the same delete through sync removes the children. `/web/data` filters out deleted lists but still returns the active items and values that belong to them (`backend/web.go:31-72`). Item deletion is not atomic and can leave orphaned values if the second statement fails. - **Impact:** The dashboard, the Android client and sync can disagree about what exists, and orphaned values are silently accepted. - **Recommendation:** Implement `deleteList`, `deleteField` and `deleteItem` once, each inside a transaction, and call them from both REST and sync. Check every error. +- **Status:** Fixed 2026-10-19 — REST and sync now share `cascadeDeleteList`, `cascadeDeleteField` and `cascadeDeleteItem`, each delete runs in one transaction, and the value-delete error is no longer discarded. REST list deletes now cascade to fields, items and values as sync already did, which is a client-visible change for REST callers. Files: backend/data.go, backend/sync.go. -### Q-003 · `handleSync` is a 200-line function, and cascade logic is duplicated · **Medium** +### Q-003 · `handleSync` is a 200-line function, and cascade logic is duplicated · **Medium** · Fixed - **Location:** `backend/sync.go:45-249` (one function; the transaction closure spans `:61-209`). Duplicated cascade logic: `sync.go:128-143` and `backend/data.go:440-452`. Event-type selection repeated at `sync.go:72-78`, `:119-125` and `:157-163`. Default-value handling repeated at `sync.go:96-103` and `backend/data.go:349-354` and `:393-398`. - **Description:** Upserts, notifications, cascades and response assembly all live in one closure. The business rules for deletion, defaults and event types are implemented twice, once in the sync handler and once in the REST handlers. Q-002 is a direct result of this duplication. - **Impact:** Hard to test or change safely, and the two code paths have already diverged. - **Recommendation:** Extract a small repository layer (`upsertList`, `upsertField`, `upsertItem`, `upsertValue`, `deleteList`, `deleteField`, `deleteItem`) shared by the REST handlers and sync, and keep the handlers as thin request and response adapters. Move event-type selection into one helper. +- **Status:** Fixed 2026-10-19 — `handleSync` is now a thin adapter over `applySyncRequest` and the per-table `applyLists`, `applyFields`, `applyItems` and `applyValues` helpers. The cascades (`cascadeDeleteList`, `cascadeDeleteField`, `cascadeDeleteItem`), `fieldDefaults` and `upsertValue` are shared by REST and sync, and sync picks its event type through one helper (`changeEventType`). The REST list, field and item create and update handlers keep their own SQL on purpose, because a plain `INSERT` rejects a duplicate id and switching it to the last-writer-wins upsert would change REST behaviour. Files: backend/sync.go, backend/data.go. -### Q-004 · Core data layer has no tests, and CI never starts a database · **Medium** +### Q-004 · Core data layer has no tests, and CI never starts a database · **Medium** · Open - **Location:** `backend/routes_test.go:8-11` (registers routes with a nil database and asserts nothing); `backend/auth_test.go`, `env_test.go`, `models_test.go` and `sync_test.go` (cover env parsing, JSON timestamp parsing, timestamp normalization and the auth stub only); `.github/workflows/tests.yml` (Go job runs `go test ./...` with no Postgres service); the frontend has no unit tests (CI runs `npm run check` only); `CollabTableAndroid/app/src` has no test sources. - **Description:** No test exercises `handleSync`, the list, field, item and value handlers, `/web/data`, the CORS wrapper, the SPA fallback, or the frontend helpers in `listHelpers.js`. The one route test runs without assertions. - **Impact:** The most complex logic (sync merge, cascades, notification side effects, timestamp handling) is covered only by manual testing, so regressions like Q-001 and Q-002 are invisible. - **Recommendation:** Add `httptest` integration tests against a real Postgres (as a CI service container), starting with sync round trips and delete cascades. Give `routes_test.go` real assertions on methods and status codes. Add Vitest tests for `listHelpers.js`, and JVM unit tests for the Android sync merge logic. +- **Status:** Open 2026-10-19 — Partly fixed: route and middleware tests assert real behaviour (`backend/routes_test.go`, `backend/server_test.go`). New database-backed tests in `backend/db_test.go` cover sync round trips between devices, the `updatedat >= since` delta, last-writer-wins, stale and newer deletes, delete cascades on the REST and sync paths, the value-cell guard, orphan values, the notification savepoint, `/web/data` ETags and API tokens. They need `TEST_DATABASE_URL` (each test uses its own schema and drops it) and are skipped without it; `tests.yml` now starts a PostgreSQL service container and sets it. A `node --test` suite covers `listHelpers.js` (`npm test`, no new dependency, also run in CI). Run against PostgreSQL 18 here: all pass, and breaking four of the rules made a test fail. Still open: Android JVM unit tests for the sync merge logic. JUnit is declared, but there is no JDK or Gradle here to compile or run them, so none were written. The CI change itself has not run. -### Q-005 · Setup documentation contradicts the configuration · **Medium** +### Q-005 · Setup documentation contradicts the configuration · **Medium** · Fixed - **Location:** `README.md:52` (`SECRET` marked as optional, default "unset (push endpoint refuses every caller)"); `README.md:70-79` (Quick Start `docker run` sets no `SECRET`); `README.md:55` (`COOKIE_SECURE` described as marking cookies `Secure`); `shared/backend/auth/proxy.go:359-361` and `:838-841`; `backend/auth.go:113-120`; `frontend/vite.config.js:38-41` (dev proxy forwards only `/web` and `/health`). - **Description:** The auth service is built with `RequireSecret()` (`auth.go:118`). When `SECRET` is unset, `/api/auth/status` and every auth-gated route return `500 SECRET environment variable is not set.`, so the documented Quick Start produces a dashboard that cannot load. The README table also calls `SECRET` optional. The live session cookie's `Secure` and `SameSite` attributes come from AuthGuard (see Security S-013), so `COOKIE_SECURE` does not do what the README says. `npm run dev` proxies only `/web` and `/health`, but the dashboard calls `/api/auth/*` and `/api/tech-stack` (`frontend/src/lib/api.js`), so the dev server cannot reach the API. - **Impact:** Operators who follow the docs get a deployment that fails or looks secure when it is not, and developers hit a confusing dev setup. - **Recommendation:** Mark `SECRET` as required when auth is enabled, add it to the Quick Start, correct the `COOKIE_SECURE` description, and add `/api` to the Vite proxy. +- **Status:** Fixed 2026-10-19 — README and backend README now mark `SECRET` as required unless `AUTH_DISABLED=true`, add it to the Quick Start, correct the `COOKIE_SECURE` description, and document `ALLOWED_ORIGINS`; the Vite dev proxy now forwards `/api`. Files: README.md, backend/README.md, frontend/vite.config.js. -### Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · **Medium** +### Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · **Medium** · Open - **Location:** `backend/sync.go:20-43` (client timestamps accepted as sent, clamped only if in the future); upserts that overwrite regardless of the stored `updatedat`: `sync.go:64-69`, `:104-116`, `:149-156`, `:198-203`; the delta cursor filters on the stored value at `backend/data.go:75`, `:108`, `:145`, `:178`. Android: local edits stamped with device time (`CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt:148`), and the cursor is the server's `serverTimestamp` (`CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt:49-60`, `:283`). - **Description:** Two related problems. (1) A device that edits offline stamps the change with an old local time. If another device has already advanced its cursor past that time, the `updatedat >= since` filter never returns the change to it. (2) Upserts overwrite the stored row whatever its `updatedat`, so an older change that arrives later replaces a newer one. The Android client mitigates (1) by forcing a full down-sync at app start (`SyncRepository.kt:122`), so the devices affected are those that stay open for a long time. - **Impact:** Silent divergence between devices, and lost updates when two devices edit the same row offline. Dashboard users see stale data until a device restarts. - **Recommendation:** Assign server-side change tokens (a monotonically increasing sequence, or the server receive time) to every write and use that as the cursor, keeping client `updatedat` for display only. Alternatively, make each upsert conditional on `EXCLUDED.updatedat` being newer than the stored value, and document the last-writer-wins rule. +- **Status:** Open 2026-10-19 — Re-checked, unchanged. Conditional upserts are in place and now covered by `backend/db_test.go` (`TestSyncLastWriterWinsByTimestamp`, `TestStaleDeleteDoesNotCascadeButNewerDeleteDoes`; an equal timestamp still applies). Still open: a change stamped with an old device clock can miss the `updatedat >= since` cursor. The fix needs a server-side change token on every row (a new column with a backfill, so a stored-data-format change) and a rollout plan. Decision needed: the token design (server receive time or a sequence) and whether the Android cursor changes with it. ### Q-007 · Validation and error mapping return misleading status codes and contract drift · **Low** - **Location:** `backend/data.go:248-255` (duplicate list id returns `500 Failed to create list` rather than `409`); `backend/data.go:549-558` (an item value for a missing item or field fails on a foreign key and returns `500`); `backend/data.go:589-607` (`PUT /api/items/{id}` accepts a body but only bumps `updatedat`, ignoring the body); `backend/server.go:292-316` (unknown `/api/...` paths return `index.html` with `200`). diff --git a/README.md b/README.md index cfcc1a6..c05f266 100644 --- a/README.md +++ b/README.md @@ -49,10 +49,13 @@ The device-sync API token (generated from the dashboard's Settings page, used by | `AUTHGUARD_URL` | No | unset (pending) | Optional bootstrap/override base URL of the AuthGuard identity service. Leaving it unset does not disable authentication — it leaves the service "pending" until ProjectConfigurator pushes a URL, failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off. | | `AUTH_DISABLED` | No | `false` | Set `true` to disable authentication entirely (no login screen, nothing gated, every request treated as authenticated) — for local development or a standalone deployment with no AuthGuard integration at all. | | `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. | -| `SECRET` | No | unset (push endpoint refuses every caller) | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal`. | +| `SECRET` | Yes, unless `AUTH_DISABLED=true` | unset | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal` and `PUT /api/auth/access/internal`. Without it, `GET /api/auth/status` reports `SECRET environment variable is not set.` and every auth-gated route returns 500, and the internal endpoints refuse every caller. | +| `ALLOWED_ORIGINS` | No | unset | Comma-separated browser origins that may call the API cross-origin with credentials. Leave unset: the dashboard is same-origin and needs no CORS. | | `PORT` | No | `8080` | HTTP listen port | | `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page | -| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS, to mark cookies `Secure` | +| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS. It marks only the cookies CollabTable clears on logout as `Secure`; the session cookie's `Secure`, `SameSite` and `Domain` attributes are set by AuthGuard. | +| `TRUSTED_PROXIES` | No | unset | Comma-separated IPs or CIDR ranges of reverse proxies. `X-Forwarded-For` (client IP for rate limits) and `X-Forwarded-Proto` are read only from these peers. | +| `PRODUCTION` | No | `false` | Set `true` to refuse plain HTTP: requests must arrive over TLS or through a `TRUSTED_PROXIES` proxy sending `X-Forwarded-Proto: https`. Requires `TRUSTED_PROXIES`. With `false`, the server logs a warning that TLS is off. | | `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup | | `DB_INIT_RETRY_MAX_ATTEMPTS` | No | `0` (retry forever) | Max database-connection retry attempts at startup | | `SYNC_MAX_FUTURE_SKEW_MS` | No | `0` | Client clock skew tolerated in sync timestamps, to avoid re-sending future-dated rows in hot loops | @@ -73,6 +76,7 @@ docker run -d \ -p 8080:8080 \ -e DATABASE_URL="postgresql://user:password@host:5432/collabtable" \ -e AUTHGUARD_URL="https://auth.example.com" \ + -e SECRET="" \ collabtable:local ``` @@ -120,8 +124,12 @@ Open `CollabTableAndroid` in Android Studio, let Gradle sync, and run on an emul ```bash cd backend go test ./... +# The handler and sync tests need a disposable PostgreSQL and are skipped without one. +# Never point this at your real DATABASE_URL: each test creates and drops its own schema. +TEST_DATABASE_URL='postgres://postgres:postgres@localhost:5432/collabtable_test?sslmode=disable' go test ./... cd ../frontend +npm test npm run check npm run lint ``` @@ -136,7 +144,7 @@ Every push runs three GitHub Actions workflows against the backend and frontend - **`docker.yml`** — builds a multi-arch image (`linux/amd64` + `linux/arm64` on `main`, `linux/amd64` otherwise) from `docker/Dockerfile` and pushes `${DOCKERHUB_USERNAME}/collabtableserver` to Docker Hub on pushes to `main`, tagged by branch name, `sha-`, and `latest`. - **`lint.yml`** — runs `npm run lint` (ESLint) against `frontend`. -- **`tests.yml`** — runs `go test ./...` against `backend` and `npm run check` against `frontend`. +- **`tests.yml`** — runs `go test ./...` against `backend` (with a PostgreSQL service container, so the database-backed tests run) and `npm test` and `npm run check` against `frontend`. **Required secrets / variables in your GitHub repository settings:** diff --git a/SECURITY_REPORT.md b/SECURITY_REPORT.md index 763215e..a080c62 100644 --- a/SECURITY_REPORT.md +++ b/SECURITY_REPORT.md @@ -5,82 +5,93 @@ - **Analyzed:** 2026-10-16 - **Commit:** 6aec03f on main - **Working tree:** clean (no uncommitted changes, no untracked files) +- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). S-006 and S-009 follow owner decisions 5 (trusted-proxy client IP) and 11 (LAN HTTP with a warning). A second Medium pass re-checked the open items: S-007 is fixed (full dashboard CSP), S-002 does not reproduce, and S-003 and S-005 stay open for owner or shared decisions. - **Stack:** Go 1.26 (net/http, pgx v5) API server with PostgreSQL; identity delegated to a separate AuthGuard service via `shared/backend/auth`; SvelteKit 2 / Svelte 5 static dashboard embedded in the Go binary; Android client (Kotlin, Retrofit/OkHttp, Room, SharedPreferences); Docker multi-stage image on `scratch`; GitHub Actions. - **Scope:** Read all first-party backend code (`backend/*.go`), the Docker and CI configuration, the frontend API client, routes and query layer, the Vite config, the Android API client, preferences, manifest, network security config and app Gradle file, and the shared auth, authclient, authproxy, coreconfig and postgres code that CollabTable calls. Git history was searched for credential-shaped strings and `.env` files. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, generated build output, lock files (read for versions only), and the rest of `shared/`. Tracked SQLite files were inspected read-only from a copy, schema and row counts only. No tests, audits, builds or network calls were made; the analysis is static. ## Summary -| Severity | Count | -|---|---:| -| Critical | 0 | -| High | 0 | -| Medium | 10 | -| Low | 7 | -| Info | 2 | +| Severity | Count | Fixed | Not reproduced | Open | +|---|---:|---:|---:|---:| +| Critical | 0 | 0 | 0 | 0 | +| High | 0 | 0 | 0 | 0 | +| Medium | 10 | 7 | 1 | 2 | +| Low | 7 | 0 | 0 | 7 | +| Info | 2 | 0 | 0 | 2 | No critical or high-severity issues were confirmed. Authentication is delegated to AuthGuard and fails closed when it is not configured, and sync tokens are generated with 256 bits of randomness and stored hashed. The main concerns are a reflective CORS policy with credentials, a login-disabled mode that hands out sync tokens to anyone, the absence of object-level authorization on data (possibly intended, but unscoped), missing rate limiting and security headers, and several Android client exposures (the token written to logcat, cleartext traffic permitted, and the token stored in plain preferences). ## Issues -### S-001 · Reflective CORS with credentials on every route · **Medium** +### S-001 · Reflective CORS with credentials on every route · **Medium** · Fixed - **Location:** `backend/server.go:274-290` (`withCORS`), in particular `:276-281`. - **Description:** The middleware echoes any request `Origin` into `Access-Control-Allow-Origin` and sets `Access-Control-Allow-Credentials: true` on all responses, including session-protected routes (`/web/data`, `/api/auth/users`, `/api/auth/token/regenerate`). If the browser sends the user's cookies, any origin can read those responses. The preflight `Allow-Methods` list also omits `PATCH`, which `server.go:181` accepts. - **Impact:** Exploitability depends on the AuthGuard cookie attributes, which are not in this repository. With `SameSite=Lax`, a cross-site page will not receive the cookie, but a same-site origin will (another subdomain of the same site, or a sibling app on a shared cookie domain, which the authclient docs describe as a cross-project SSO option). Such an origin could read `/web/data` or call `POST /api/auth/token/regenerate` and read the new sync token. Rated Medium here; it would be High if the cookie is scoped to a parent domain. Needs verification against the deployed AuthGuard cookie. - **Recommendation:** Replace the reflection with an explicit allow-list from configuration (for example `ALLOWED_ORIGINS`) and set credentials headers only for those origins. The dashboard is same-origin and needs no CORS headers at all, so the default should be none. Keep `Vary: Origin` and add `PATCH` to the allowed methods if it is needed. +- **Status:** Fixed 2026-10-19 — `withCORS` now reflects only origins listed in `ALLOWED_ORIGINS` (empty by default), sends credentials headers only for them, and allows `PATCH` in preflight. Browser clients on other origins lose cross-origin access, which the same-origin dashboard does not need. Files: backend/server.go, backend/server_test.go, backend/README.md, README.md. -### S-002 · Login-disabled mode lets anyone obtain a write-capable sync token · **Medium** +### S-002 · Login-disabled mode lets anyone obtain a write-capable sync token · **Medium** · Not reproduced - **Location:** `backend/server.go:186-188` (`POST /api/auth/token/regenerate` behind `RequireIfLoginRequired`); `shared/backend/auth/proxy.go:504-519` (`CurrentUser` returns the superadmin placeholder whenever login is not required); `backend/auth.go:194-210` (`handleTokenRegenerate` mints a token for the placeholder identity). - **Description:** When login is not required (`AUTH_DISABLED=true`, or the login-required override pushed by ProjectConfigurator set to false), `RequireIfLoginRequired` lets any caller reach token regeneration without credentials. The endpoint mints a write-capable sync token for identity 0, and the bearer-token check on the sync API then passes for that caller. - **Impact:** The sync API's token requirement protects nothing in that mode, and any network client can obtain full read, write and delete access. The README describes `AUTH_DISABLED` as "nothing gated", so this matches the documented intent. The override path can be set centrally in a shared deployment, however, and nobody may notice that the token API has become open. - **Recommendation:** Keep token minting behind a real credential even when login is off (for example, always require a session for token regeneration), or document the consequence prominently and log a warning when the override is set to false. +- **Status:** Not reproduced 2026-10-19 — The last step of the chain fails. With login off, callers resolve to the placeholder identity 0, and `requireAPIToken` (`backend/auth.go`) never accepts identity 0, so the token minted without a session gets 401 on `/api/sync` and `/api/lists`. Test `TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI` (`backend/db_test.go`, run against PostgreSQL) pins this. Write and delete access through the token API is not reachable. What login-off mode does open is the dashboard (`/web/data`, user management), as `AUTH_DISABLED` documents; `backend/README.md` now says so. Side effect: with login off, devices cannot get a working sync token; accepting identity 0 would fix that and open the sync API, so it is an owner decision. The `auth.go` comment that called such a token functional is corrected. -### S-003 · No object-level ownership or roles on list, field, item or value data · **Medium** +### S-003 · No object-level ownership or roles on list, field, item or value data · **Medium** · Open - **Location:** `backend/auth.go:129-149` (`requireAPIToken` only checks that a token exists); `backend/server.go:195-219` (all data routes); `backend/data.go` (all handlers); `backend/sync.go:61-209`; `backend/db.go:40-189` (no owner or tenant columns); `backend/sync.go:198-203` and `backend/data.go:549-558` (item values upserted by `id` alone). - **Description:** Any valid sync token (one per account) and any logged-in account can read, overwrite, soft-delete and move every list, field, item and value. The item-value conflict clause updates only `value` and `updatedat`, so a write that names a different `itemId` or `fieldId` than the stored row is silently applied to the stored row. The schema has no owner column, and `api_tokens.user_id` is used only for token regeneration. Item values are hard-deleted when their item or list is deleted (`sync.go:88`, `:129`, `:140`, `:166`), so those deletions cannot be undone by a later sync, even though lists and items are soft-deleted. - **Impact:** For a collaborative tool this may be intended, in which case every account is effectively an administrator of the data. If it is not intended, it is an authorization gap. Either way, one compromised device token can wipe or rewrite the database, and some of that loss is permanent. - **Recommendation:** Confirm the intended model and document it. If the data is shared, make item-value upserts reject writes whose `itemid` or `fieldid` do not match the stored row. If per-list access is needed, add a membership table and check it in every handler. +- **Status:** Open 2026-10-19 — Partly addressed: item values apply only to a stored row with the same `itemId` and `fieldId` (sync and REST; tests in `backend/db_test.go`), stale writes are ignored (see Q-006), and the current access model is written down in `backend/README.md` ("Access model"). Still needed: an owner decision on the model (shared data, or per-list membership, which needs a membership table checked in every handler), and whether item values should be soft-deleted instead of removed for good (a schema change). -### S-004 · Managed-user routes require a login only, leaving the role check to AuthGuard · **Medium** +### S-004 · Managed-user routes require a login only, leaving the role check to AuthGuard · **Medium** · Fixed - **Location:** `backend/server.go:178-182` (list, create, update and delete users, behind `RequireIfLoginRequired`); `shared/backend/auth/proxy.go:897-1013` (handlers forward the caller's session to AuthGuard without a local role check); `shared/backend/auth/proxy.go:618` (`RequireUserManager` exists but CollabTable does not use it). - **Description:** The handlers document that AuthGuard enforces authorization, which holds only if AuthGuard rejects non-admin sessions. CollabTable does not check the role before proxying. If AuthGuard does not reject it, `GET /api/auth/users` returns every account's username, email and role to any logged-in account. - **Impact:** No defense in depth. A bug or policy change in AuthGuard would expose administrative functions here. Needs verification against the deployed AuthGuard version. - **Recommendation:** Gate these routes with `RequireUserManager` (or `RequireAdminIfLoginRequired`), which the shared package already provides, so the policy is visible in this repository. +- **Status:** Fixed 2026-10-19 — Managed-user routes now pass the shared `RequireUserManager` gate, so the role check happens in this repository as well as in AuthGuard; accounts without user-management rights get 403 locally. Files: backend/server.go, backend/routes_test.go. -### S-005 · Password change does not require the current password, and existing sessions stay valid · **Medium** +### S-005 · Password change does not require the current password, and existing sessions stay valid · **Medium** · Open - **Location:** `shared/backend/auth/proxy.go:664-705` (`UpdateMe` accepts only `email`, `username` and `password`); `backend/auth.go:39-43` (documented behavior: a credentials change "simply returns the updated account and leaves the current session valid"). - **Description:** Anyone holding a session cookie can change the account password without knowing the current one. Sessions on other devices also remain valid, and there is no re-authentication step. - **Impact:** A stolen or unattended session can lock the owner out. The usual defenses (re-authentication, and revoking other sessions on password change) are absent. - **Recommendation:** Require `currentPassword` (and the TOTP code when enabled) on `POST /api/auth/credentials` whenever the password changes, and have AuthGuard revoke other sessions on a password change. +- **Status:** Open 2026-10-19 — Re-checked, shared-dependent. `UpdateMe` in the vendored `shared/backend/auth/proxy.go` accepts no `currentPassword`, and the shared medium pass left this open pending a decision on the request shape. Needed: that decision, then the change in Web/shared (and AuthGuard revoking other sessions), re-synced here. CollabTable cannot add the check alone without changing the `POST /api/auth/credentials` request. -### S-006 · No rate limiting or request budgets on login, token use, writes or body size · **Medium** +### S-006 · No rate limiting or request budgets on login, token use, writes or body size · **Medium** · Fixed - **Location:** `shared/backend/auth/proxy.go:1093-1142` (`Login` forwards every attempt to AuthGuard with no local throttling); `backend/auth.go:129-149` (sync-token check, no throttling); `backend/server.go:188` (token regeneration); `backend/server.go:253-259` (up to 50 MB per request, see P-007). - **Description:** A search of CollabTable and the shared auth packages finds no rate limiter, lockout or request throttle. Brute-force protection for passwords and TOTP codes depends entirely on AuthGuard. Sync tokens carry 256 bits of entropy, so guessing them is not a practical concern; the issue is request volume and availability. - **Impact:** Credential stuffing against the login proxy, load from unthrottled token checks, and memory exhaustion from large bodies. - **Recommendation:** Add per-IP and per-account limits on `/api/auth/login`, `/api/auth/totp/*` and `/api/auth/setup`, either in-process or at the proxy. Confirm AuthGuard's own limits. Enforce body size per route (see P-007). +- **Status:** Fixed 2026-10-19 — In-process budgets (owner decision 5) on setup, login, the TOTP routes and token regeneration: 30 requests per minute per client IP, and 10 failed logins per account identifier per 15 minutes, answered with 429 and `Retry-After`. The client IP is read from `X-Forwarded-For` only when the socket peer is in the new `TRUSTED_PROXIES` list, and is the socket address otherwise. Not throttled per request: the sync API and writes, because the bearer token is 256 bits and devices sync often; body size and concurrent syncs bound their cost (P-007). Still to confirm: AuthGuard's own login limits on the deployed instance. Verified by Go unit and route tests only, not against a running instance. Files: backend/clientip.go, backend/ratelimit.go, backend/server.go, backend/clientip_test.go, backend/ratelimit_test.go, backend/.env.example, backend/README.md, README.md. -### S-007 · No security headers on the dashboard or API · **Medium** +### S-007 · No security headers on the dashboard or API · **Medium** · Fixed - **Location:** `backend/server.go:118-125` (no header middleware); `backend/server.go:292-316` (`spaFileServer` writes `index.html` with only `Content-Type`); `backend/web.go:74-76` (cache headers only). - **Description:** Responses carry no `Content-Security-Policy`, no `X-Frame-Options` or `frame-ancestors`, no `X-Content-Type-Options` and no `Referrer-Policy`. The app can be framed, which allows clickjacking of user-management and token-regeneration actions. Without a CSP, an injected script would have no restrictions. No unsafe HTML rendering was found in first-party code, which limits the immediate risk. - **Impact:** Clickjacking of logged-in actions and a weaker defense against future XSS. HSTS belongs at the TLS terminator and is not set here. - **Recommendation:** Add middleware that sets `X-Frame-Options: DENY` (or `frame-ancestors 'none'`), `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, and a CSP such as `default-src 'self'` with hashes or nonces for SvelteKit's inline bootstrap script. Set HSTS at the proxy. +- **Status:** Fixed 2026-10-19 — The dashboard page (`index.html` and the deep-link fallback) now sends a full Content-Security-Policy (`backend/csp.go`, set in `spaFileServer`): `default-src 'self'`, `script-src 'self'` plus the SHA-256 of the page's inline bootstrap script (read from the embedded `index.html` at request time, so it follows each build), `style-src 'self' 'unsafe-inline'` (the page shell uses a style attribute), `connect-src 'self'`, `object-src 'none'`, `base-uri`, `form-action` and `frame-ancestors 'none'`. Other responses keep `frame-ancestors 'none'`. HSTS stays with the TLS proxy, as recommended, and `backend/README.md` says so. Checked on a real build: the Go hash equals an independent computation, and the bundle has no eval, workers, external URLs or CSS `url()`. Not loaded in a browser (none available here), so open the dashboard once after deploying. -### S-008 · Android app logs full HTTP traffic, including the bearer token, in every build · **Medium** +### S-008 · Android app logs full HTTP traffic, including the bearer token, in every build · **Medium** · Fixed - **Location:** `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt:20-23` (`HttpLoggingInterceptor` at `Level.BODY`), and `:55-64` (the interceptor is added to the client unconditionally; `authInterceptor` at `:58` sets the `Authorization` header first). - **Description:** The logging interceptor is not gated on the debug build type, and it does not redact headers. Its output includes the `Authorization: Bearer ` header and the full request and response bodies, which carry all list and item data, in release builds. - **Impact:** The long-lived sync token and user data end up in logcat and in any log capture or bug report. Exploiting this requires access to device logs (ADB, a debugging tool, or a bug report), not a remote attack. - **Recommendation:** Use `Level.NONE` for release builds (for example `if (BuildConfig.DEBUG)`), call `redactHeader("Authorization")`, and do not log bodies in production. +- **Status:** Fixed 2026-10-19 — HTTP logging now uses `Level.NONE` unless `BuildConfig.DEBUG`, and the `Authorization` header is redacted in every build; `buildConfig` is enabled because AGP 8.8 does not generate `BuildConfig` by default. The Kotlin compile could not run in this environment (the JVM hit the process limit), so it is unverified. Files: CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt, CollabTableAndroid/app/build.gradle. -### S-009 · Cleartext HTTP is allowed for all domains and is the default server URL · **Medium** +### S-009 · Cleartext HTTP is allowed for all domains and is the default server URL · **Medium** · Fixed - **Location:** `CollabTableAndroid/app/src/main/res/xml/network_security_config.xml:3-4` (`cleartextTrafficPermitted="true"` in `base-config`); `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt:298` (default `http://10.0.2.2:8080/api/`); `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt:25-44` (the bearer token is attached to every request). - **Description:** The release app accepts `http://` server URLs for any host, and the bearer token is sent with every request. Traffic is unencrypted and can be read or altered on the network path. - **Impact:** Token and data exposure on untrusted networks whenever an operator configures an HTTP URL. Cleartext is needed only for the emulator default. - **Recommendation:** Keep cleartext only for debug builds (a debug resource overlay) or for `10.0.2.2` and `localhost`. Require HTTPS for remote hosts and reject `http://` in the settings UI otherwise. +- **Status:** Fixed 2026-10-19 — Handled by owner decision 11 (LAN HTTP allowed, with a warning). Cleartext stays permitted, so the network security config and the default emulator URL are unchanged. `ApiClient` logs a warning whenever the server URL is `http://`. The backend logs a warning at startup while TLS is off. `PRODUCTION=true` refuses plain HTTP requests unless they arrive over TLS or through a `TRUSTED_PROXIES` proxy that sends `X-Forwarded-Proto: https` (`/health` stays open). The Android app has no production profile, so release builds keep cleartext. The settings screen does not reject `http://` for remote hosts, which the decision replaces. Files: CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt, backend/server.go, backend/.env.example, backend/README.md, README.md. The Kotlin change is not compiled: the Android build cannot run on this Alpine (musl) host, because the SDK's aapt2 needs glibc. -### S-010 · Long-lived sync token stored in plain SharedPreferences, with app backup enabled · **Medium** +### S-010 · Long-lived sync token stored in plain SharedPreferences, with app backup enabled · **Medium** · Fixed - **Location:** `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt:73-80` and `:283` (token written to `collab_table_prefs` with `MODE_PRIVATE`, unencrypted); `CollabTableAndroid/app/src/main/AndroidManifest.xml:11` (`android:allowBackup="true"`). - **Description:** The API token is written to ordinary SharedPreferences. With `allowBackup="true"` the file is included in device backups, and on a rooted device or with ADB backup access it can be read directly. - **Impact:** The token grants full sync access (see S-003) and can be recovered from a backup or a compromised device. - **Recommendation:** Store the token with `EncryptedSharedPreferences` or the Android Keystore, exclude it from backups with `dataExtractionRules` and `fullBackupContent`, or set `allowBackup="false"`. +- **Status:** Fixed 2026-10-19 — `android:allowBackup` is now `false`, so the sync token is kept out of device backups and transfers. Users must re-enter the token on a new device, and the token remains plain text on the device, which a rooted device can still read. Files: CollabTableAndroid/app/src/main/AndroidManifest.xml. ### S-011 · Sync token has no expiry, scope or per-device identity · **Low** - **Location:** `backend/db.go:181-188` (`api_tokens` has no expiry column); `backend/auth.go:159-170` (32 random bytes, stored as an unsalted SHA-256 hash); `backend/auth.go:194-210` (regeneration replaces the account's single token). diff --git a/backend/.env.example b/backend/.env.example index 11557b5..86d1711 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -7,6 +7,16 @@ APP_VERSION=dev # Set to "true" once served over HTTPS - marks the admin session cookie Secure. COOKIE_SECURE=false +# Comma-separated IPs or CIDR ranges of reverse proxies whose X-Forwarded-For and +# X-Forwarded-Proto headers are believed. Empty (default) trusts no proxy, so the +# socket address is used for rate limits. Example: 10.0.0.1,172.18.0.0/16 +TRUSTED_PROXIES= + +# Set to "true" in production. Plain HTTP requests are refused unless they arrive +# over TLS or through a TRUSTED_PROXIES proxy that sends X-Forwarded-Proto: https. +# Requires TRUSTED_PROXIES. Default false: plain HTTP is allowed and logs a warning. +PRODUCTION=false + ################################################################# # Authentication (AuthGuard) ################################################################# @@ -38,8 +48,8 @@ COOKIE_SECURE=false # see Core/ProjectConfigurator/README.md's "Pushing core service info to # other projects". That push is itself authenticated with this secret, so it # still needs to be set even though AUTHGUARD_URL/CARRIERNODE_URL don't. A -# push never overrides AUTH_DISABLED=true; it only ever retargets an -# already-enabled AuthGuard connection. +# push never overrides AUTH_DISABLED=true; it only ever retargets an +# already-enabled AuthGuard connection. ################################################################# # PostgreSQL configuration @@ -62,9 +72,9 @@ DB_INIT_RETRY_MAX_ATTEMPTS=0 SYNC_MAX_FUTURE_SKEW_MS=0 # Notification retention period in milliseconds (default: 7 days) -NOTIF_RETENTION_MS=604800000 - -# Required shared-service authentication secret. -SECRET=change-me-to-a-long-random-value -# Set true only for local development or a standalone deployment. -AUTH_DISABLED=false +NOTIF_RETENTION_MS=604800000 + +# Required shared-service authentication secret. +SECRET=change-me-to-a-long-random-value +# Set true only for local development or a standalone deployment. +AUTH_DISABLED=false diff --git a/backend/README.md b/backend/README.md index 75e0018..5fda1cf 100644 --- a/backend/README.md +++ b/backend/README.md @@ -24,6 +24,7 @@ docker run -d --name collabtable-server --restart unless-stopped \ -p 8080:8080 \ -e DATABASE_URL=postgres://user:password@host:5432/collabtable \ -e AUTHGUARD_URL=https://auth.example.com \ + -e SECRET= \ -e COOKIE_SECURE=false \ collabtable-server ``` @@ -41,6 +42,10 @@ go test ./... go run . ``` +`go test ./...` skips the tests that need a database. To run them, set `TEST_DATABASE_URL` to a +disposable PostgreSQL (a `postgres://` URL, never your real `DATABASE_URL`). Each test creates +its own schema in it and drops the schema afterwards. + To build the dashboard for the embedded production binary: ```bash @@ -112,7 +117,19 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate - `PORT` — HTTP port, default `8080` - `APP_VERSION` — optional version displayed in the dashboard, default `dev` -- `COOKIE_SECURE` — set to `true` when served over HTTPS +- `COOKIE_SECURE` — set to `true` when served over HTTPS. It marks only the cookies CollabTable + clears on logout as `Secure`; the session cookie's attributes are set by AuthGuard. +- `TRUSTED_PROXIES` — comma-separated IP addresses or CIDR ranges of reverse proxies, default + unset (no proxy trusted). `X-Forwarded-For` is read for the client IP, used by the rate limits, + only when the socket peer is in this list; `X-Forwarded-Proto` is honoured the same way. +- `PRODUCTION` — set `true` for a production deployment, default `false`. Plain HTTP requests + get 403 unless they arrive over TLS or through a `TRUSTED_PROXIES` proxy that sends + `X-Forwarded-Proto: https` (`/health` stays open). Requires `TRUSTED_PROXIES`. With it unset, + the server logs a warning that TLS is off. +- `SECRET` — shared secret for the internal endpoints. Required unless `AUTH_DISABLED=true`: + without it the auth status endpoint reports the missing secret and auth-gated routes return 500. +- `ALLOWED_ORIGINS` — comma-separated browser origins allowed to call the API cross-origin with + credentials, default unset (no CORS headers; the dashboard is same-origin). - `DATABASE_URL` — PostgreSQL connection string, required - `AUTHGUARD_URL` — optional bootstrap/override base URL of the AuthGuard identity service CollabTable authenticates against, default unset (pending). Leaving it unset does not disable @@ -129,6 +146,41 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate The Go server initializes the existing CollabTable tables in place, so switching from the previous server does not require a data export or schema conversion. +## Rate limits + +The auth routes are throttled in process, per client IP (see `TRUSTED_PROXIES` for how the IP is +resolved): setup, login, TOTP and token regeneration allow 30 requests per minute, after which +the server answers 429 with `Retry-After`. Failed logins (401) are also counted per account +identifier, and an account is locked for its 15-minute window after 10 failures. Anyone who knows +an account name can therefore lock that account out for the window. Limits are per instance and +reset on restart. AuthGuard applies its own limits; confirm them separately. +The sync API is not throttled per request, because the bearer token is 256 bits and devices +sync often. + +## Security headers + +Every response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, +`Referrer-Policy: strict-origin-when-cross-origin` and `Content-Security-Policy: frame-ancestors +'none'`. The dashboard page (`index.html`, including the fallback for deep links) gets a full +Content-Security-Policy instead: scripts only from this origin plus the page's own inline +bootstrap script, whose hash is read from the embedded `index.html` at request time, so it +follows every dashboard build. Styles allow `'unsafe-inline'` because the page shell uses a style +attribute. `Strict-Transport-Security` is not set here; set it at the TLS proxy. + +## Access model + +There is one shared data set. Lists, fields, items and values have no owner and no per-list +roles: any valid sync token can read, change and delete all of them, and any signed-in dashboard +user can see all of them. Tokens are per account only so that each can be regenerated on its own. +Deleting an item, field or list removes its values for good, while the rows themselves are soft +deleted. Per-list access would need a membership table checked in every handler; that has not +been decided. + +When login is off (`AUTH_DISABLED=true`, or the login-required switch turned off in +ProjectConfigurator), the dashboard data and user management need no session. Sync tokens are a +separate matter: a caller without a session can only mint a token for the placeholder identity, +and the sync API refuses that identity. + ## License MIT diff --git a/backend/auth.go b/backend/auth.go index b6b1550..aad1eaf 100644 --- a/backend/auth.go +++ b/backend/auth.go @@ -139,6 +139,9 @@ func requireAPIToken(db *DB) func(http.Handler) http.Handler { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } + // getAPITokenUserID answers 0 for an unknown token. 0 is also the + // placeholder identity used when login is off, so tokens minted without + // a session are refused here as well (see handleTokenRegenerate). if userID == 0 { writeJSONError(w, http.StatusUnauthorized, "Invalid API token") return @@ -173,10 +176,10 @@ func hashToken(token string) string { // view/regenerate the bearer token its own devices use against the sync API. // The caller's identity is resolved via sharedauth.UserFromContext, populated // by the s.auth.Require wrapper server.go mounts these routes behind -- in -// auth-disabled mode that middleware always resolves to sharedauth's fixed -// placeholder identity (ID 0), so a token minted in that mode is real and -// functional, just scoped to that one shared identity rather than a -// per-account AuthGuard identity, matching the pre-migration behavior. +// auth-disabled mode, or while login is switched off, that middleware always +// resolves to sharedauth's fixed placeholder identity (ID 0). A token minted +// for it is stored, but requireAPIToken never accepts identity 0, so a caller +// without a session cannot turn it into access to the sync API. func (s *Server) handleTokenStatus(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) if user == nil { diff --git a/backend/clientip.go b/backend/clientip.go new file mode 100644 index 0000000..6fbdee7 --- /dev/null +++ b/backend/clientip.go @@ -0,0 +1,95 @@ +package main + +import ( + "fmt" + "net" + "net/http" + "strings" +) + +// parseTrustedProxies reads TRUSTED_PROXIES, a comma-separated list of IP +// addresses and CIDR ranges for reverse proxies whose forwarding headers may be +// believed. An empty value trusts no proxy. +func parseTrustedProxies(value string) ([]*net.IPNet, error) { + var networks []*net.IPNet + for _, entry := range strings.Split(value, ",") { + entry = strings.TrimSpace(entry) + if entry == "" { + continue + } + if ip := net.ParseIP(entry); ip != nil { + if v4 := ip.To4(); v4 != nil { + ip = v4 + } + networks = append(networks, &net.IPNet{IP: ip, Mask: net.CIDRMask(8*len(ip), 8*len(ip))}) + continue + } + _, network, err := net.ParseCIDR(entry) + if err != nil { + return nil, fmt.Errorf("TRUSTED_PROXIES entry %q is neither an IP address nor a CIDR range", entry) + } + networks = append(networks, network) + } + return networks, nil +} + +// clientIP returns the address a request is attributed to, for rate limits and +// logs. The socket peer is used unless it is a trusted proxy. Only then is +// X-Forwarded-For read, walking from the nearest hop outwards and stopping at +// the first address that is not itself a trusted proxy. A malformed chain falls +// back to the peer, so an unknown caller cannot choose the address it appears as. +func clientIP(r *http.Request, trusted []*net.IPNet) string { + peer := remoteHost(r.RemoteAddr) + peerIP := net.ParseIP(peer) + if peerIP == nil || !inNetworks(peerIP, trusted) { + return peer + } + hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",") + var leftmost net.IP + for i := len(hops) - 1; i >= 0; i-- { + hop := net.ParseIP(strings.TrimSpace(hops[i])) + if hop == nil { + return peer + } + if !inNetworks(hop, trusted) { + return hop.String() + } + leftmost = hop + } + if leftmost != nil { + return leftmost.String() + } + return peer +} + +// requestIsHTTPS reports whether the client's connection was encrypted: either +// TLS terminated in this process, or a trusted proxy reported https through +// X-Forwarded-Proto. The header is ignored from any other peer. +func requestIsHTTPS(r *http.Request, trusted []*net.IPNet) bool { + if r.TLS != nil { + return true + } + peerIP := net.ParseIP(remoteHost(r.RemoteAddr)) + if peerIP == nil || !inNetworks(peerIP, trusted) { + return false + } + protos := strings.Split(r.Header.Get("X-Forwarded-Proto"), ",") + return strings.EqualFold(strings.TrimSpace(protos[len(protos)-1]), "https") +} + +func remoteHost(remoteAddr string) string { + host, _, err := net.SplitHostPort(remoteAddr) + if err != nil { + return remoteAddr + } + return host +} + +func inNetworks(ip net.IP, networks []*net.IPNet) bool { + for _, network := range networks { + if network.Contains(ip) { + return true + } + } + return false +} diff --git a/backend/clientip_test.go b/backend/clientip_test.go new file mode 100644 index 0000000..03e3c15 --- /dev/null +++ b/backend/clientip_test.go @@ -0,0 +1,121 @@ +package main + +import ( + "crypto/tls" + "net" + "net/http" + "net/http/httptest" + "testing" +) + +func mustTrusted(t *testing.T, value string) []*net.IPNet { + t.Helper() + networks, err := parseTrustedProxies(value) + if err != nil { + t.Fatalf("parseTrustedProxies(%q) error = %v", value, err) + } + return networks +} + +func TestParseTrustedProxiesAcceptsAddressesAndRanges(t *testing.T) { + networks := mustTrusted(t, " 10.0.0.5, 192.168.2.0/24 ,, fd00::1 ") + if len(networks) != 3 { + t.Fatalf("parsed %d networks, want 3", len(networks)) + } + for _, ip := range []string{"10.0.0.5", "192.168.2.77", "fd00::1"} { + if !inNetworks(net.ParseIP(ip), networks) { + t.Fatalf("%s should be trusted", ip) + } + } + for _, ip := range []string{"10.0.0.6", "192.168.3.1", "fd00::2"} { + if inNetworks(net.ParseIP(ip), networks) { + t.Fatalf("%s should not be trusted", ip) + } + } +} + +func TestParseTrustedProxiesEmptyTrustsNothing(t *testing.T) { + networks := mustTrusted(t, "") + if len(networks) != 0 { + t.Fatalf("empty TRUSTED_PROXIES parsed %d networks, want none", len(networks)) + } +} + +func TestParseTrustedProxiesRejectsGarbage(t *testing.T) { + for _, value := range []string{"proxy.local", "10.0.0.0/33", "10.0.0.1/", "999.1.1.1"} { + if _, err := parseTrustedProxies(value); err == nil { + t.Fatalf("parseTrustedProxies(%q) returned no error", value) + } + } +} + +func TestClientIPUsesSocketPeerUnlessPeerIsTrusted(t *testing.T) { + trusted := mustTrusted(t, "10.0.0.1") + + cases := []struct { + name string + remoteAddr string + forwarded string + trusted []*net.IPNet + want string + }{ + {name: "untrusted peer ignores forwarded header", remoteAddr: "192.0.2.9:4000", forwarded: "203.0.113.7", trusted: trusted, want: "192.0.2.9"}, + {name: "no trusted proxies at all", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7", trusted: nil, want: "10.0.0.1"}, + {name: "trusted peer uses forwarded client", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7", trusted: trusted, want: "203.0.113.7"}, + {name: "trusted peer without header uses peer", remoteAddr: "10.0.0.1:4000", forwarded: "", trusted: trusted, want: "10.0.0.1"}, + {name: "chain skips trusted hops", remoteAddr: "10.0.0.1:4000", forwarded: "198.51.100.4, 203.0.113.7, 10.0.0.1", trusted: trusted, want: "203.0.113.7"}, + {name: "spoofed leftmost entry is not used", remoteAddr: "10.0.0.1:4000", forwarded: "1.2.3.4, 203.0.113.7", trusted: trusted, want: "203.0.113.7"}, + {name: "malformed entry falls back to peer", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7, not-an-ip", trusted: trusted, want: "10.0.0.1"}, + {name: "all hops trusted returns leftmost", remoteAddr: "10.0.0.1:4000", forwarded: "10.0.0.1, 10.0.0.1", trusted: trusted, want: "10.0.0.1"}, + {name: "IPv6 forwarded client is normalised", remoteAddr: "10.0.0.1:4000", forwarded: "2001:DB8::7", trusted: trusted, want: "2001:db8::7"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodPost, "/api/auth/login", nil) + request.RemoteAddr = tc.remoteAddr + if tc.forwarded != "" { + request.Header.Set("X-Forwarded-For", tc.forwarded) + } + if got := clientIP(request, tc.trusted); got != tc.want { + t.Fatalf("clientIP() = %q, want %q", got, tc.want) + } + }) + } +} + +func TestRequestIsHTTPSHonoursTLSOrTrustedProxyOnly(t *testing.T) { + trusted := mustTrusted(t, "10.0.0.1") + + direct := httptest.NewRequest(http.MethodGet, "/api/lists", nil) + direct.TLS = &tls.ConnectionState{} + + cases := []struct { + name string + remoteAddr string + proto string + tlsConn bool + want bool + }{ + {name: "plain request", remoteAddr: "192.0.2.9:4000", want: false}, + {name: "terminated here", remoteAddr: "192.0.2.9:4000", tlsConn: true, want: true}, + {name: "trusted proxy reports https", remoteAddr: "10.0.0.1:4000", proto: "https", want: true}, + {name: "trusted proxy reports http", remoteAddr: "10.0.0.1:4000", proto: "http", want: false}, + {name: "untrusted peer claims https", remoteAddr: "192.0.2.9:4000", proto: "https", want: false}, + {name: "last proto hop decides", remoteAddr: "10.0.0.1:4000", proto: "https, http", want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodGet, "/api/lists", nil) + request.RemoteAddr = tc.remoteAddr + if tc.proto != "" { + request.Header.Set("X-Forwarded-Proto", tc.proto) + } + if tc.tlsConn { + request.TLS = direct.TLS + } + if got := requestIsHTTPS(request, trusted); got != tc.want { + t.Fatalf("requestIsHTTPS() = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/backend/csp.go b/backend/csp.go new file mode 100644 index 0000000..220b2e3 --- /dev/null +++ b/backend/csp.go @@ -0,0 +1,51 @@ +package main + +import ( + "crypto/sha256" + "encoding/base64" + "regexp" + "strings" +) + +var ( + scriptElement = regexp.MustCompile(`(?is)]*)>(.*?)`) + scriptSrcAttribute = regexp.MustCompile(`(?i)\bsrc\s*=`) + // A browser reads a CR or CRLF in the HTML source as LF, and hashes that. + htmlNewlines = strings.NewReplacer("\r\n", "\n", "\r", "\n") +) + +// inlineScriptHashes returns a CSP hash source for every inline + +` + + got := inlineScriptHashes([]byte(page)) + if len(got) != 1 || got[0] != scriptHash(bootstrap) { + t.Fatalf("inlineScriptHashes() = %v, want only %s", got, scriptHash(bootstrap)) + } +} + +func TestInlineScriptHashesNormalizesNewlinesLikeABrowser(t *testing.T) { + got := inlineScriptHashes([]byte("")) + if len(got) != 1 || got[0] != scriptHash("a();\nb();\nc();") { + t.Fatalf("inlineScriptHashes() = %v, want the hash of the LF-normalized text", got) + } +} + +func TestDashboardCSPAllowsOnlyOwnAndHashedScripts(t *testing.T) { + const bootstrap = "start();" + policy := dashboardCSP([]byte("")) + + directives := map[string]string{} + for _, part := range strings.Split(policy, "; ") { + name, value, _ := strings.Cut(part, " ") + directives[name] = value + } + if want := "'self' " + scriptHash(bootstrap); directives["script-src"] != want { + t.Fatalf("script-src = %q, want %q", directives["script-src"], want) + } + for name, want := range map[string]string{ + "default-src": "'self'", + "object-src": "'none'", + "base-uri": "'self'", + "frame-ancestors": "'none'", + } { + if directives[name] != want { + t.Fatalf("%s = %q, want %q", name, directives[name], want) + } + } + if strings.Contains(directives["script-src"], "unsafe") { + t.Fatalf("script-src = %q, must not allow unsafe-inline or unsafe-eval", directives["script-src"]) + } +} + +func TestDashboardCSPWithoutInlineScriptAllowsOnlyOwnOrigin(t *testing.T) { + policy := dashboardCSP([]byte("")) + if !strings.Contains(policy, "script-src 'self';") { + t.Fatalf("policy = %q, want script-src limited to 'self'", policy) + } +} + +func TestSPAFileServerSendsDashboardCSPOnThePageOnly(t *testing.T) { + const bootstrap = "start();" + root := fstest.MapFS{ + "index.html": {Data: []byte("")}, + "_app/immutable/app.abc.js": {Data: []byte("console.log(1)")}, + } + // Behind withSecurityHeaders, as in main: the page's policy replaces the + // frame-ancestors-only default instead of being added to it. + handler := withSecurityHeaders(spaFileServer(root)) + + for _, path := range []string{"/", "/index.html", "/lists/123"} { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil)) + values := recorder.Header().Values("Content-Security-Policy") + if len(values) != 1 || !strings.Contains(values[0], scriptHash(bootstrap)) || !strings.Contains(values[0], "frame-ancestors 'none'") { + t.Fatalf("GET %s Content-Security-Policy = %q, want one full policy with the bootstrap hash", path, values) + } + } + + asset := httptest.NewRecorder() + handler.ServeHTTP(asset, httptest.NewRequest(http.MethodGet, "/_app/immutable/app.abc.js", nil)) + if got := asset.Header().Get("Content-Security-Policy"); got != "frame-ancestors 'none'" { + t.Fatalf("asset Content-Security-Policy = %q, want the frame-ancestors default", got) + } +} diff --git a/backend/data.go b/backend/data.go index 67eccad..58b8146 100644 --- a/backend/data.go +++ b/backend/data.go @@ -220,6 +220,132 @@ func boolInt(value bool) int { return 0 } +// fieldDefaults fills in the field type and alignment that clients may leave out. +func fieldDefaults(fieldType, alignment string) (string, string) { + if fieldType == "" { + fieldType = "TEXT" + } + if alignment == "" { + alignment = "start" + } + return fieldType, alignment +} + +// The upsert helpers below write one row each and report whether the write was +// applied. A write older than the stored row loses (last writer wins by client +// timestamp) and changes nothing, so callers skip the cascade and notification +// for it. +func upsertList(ctx context.Context, executor queryExecutor, list List, createdAt, updatedAt int64) (bool, error) { + result, err := executor.Exec(ctx, ` + INSERT INTO lists (id, name, createdat, updatedat, isdeleted) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (id) DO UPDATE + SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted + WHERE EXCLUDED.updatedat >= lists.updatedat + `, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted)) + if err != nil { + return false, err + } + return result.RowsAffected() > 0, nil +} + +func upsertField(ctx context.Context, executor queryExecutor, field Field, createdAt, updatedAt int64) (bool, error) { + fieldType, alignment := fieldDefaults(field.FieldType, field.Alignment) + result, err := executor.Exec(ctx, ` + INSERT INTO fields + (id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + ON CONFLICT (id) DO UPDATE + SET name = EXCLUDED.name, + fieldtype = EXCLUDED.fieldtype, + fieldoptions = EXCLUDED.fieldoptions, + alignment = EXCLUDED.alignment, + "order" = EXCLUDED."order", + updatedat = EXCLUDED.updatedat, + isdeleted = EXCLUDED.isdeleted + WHERE EXCLUDED.updatedat >= fields.updatedat + `, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted)) + if err != nil { + return false, err + } + return result.RowsAffected() > 0, nil +} + +func upsertItem(ctx context.Context, executor queryExecutor, item Item, createdAt, updatedAt int64) (bool, error) { + result, err := executor.Exec(ctx, ` + INSERT INTO items (id, listid, createdat, updatedat, isdeleted) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (id) DO UPDATE + SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted + WHERE EXCLUDED.updatedat >= items.updatedat + `, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted)) + if err != nil { + return false, err + } + return result.RowsAffected() > 0, nil +} + +// upsertValue also ignores a value that names a different item or field than the +// stored row, so a write cannot move a value onto another cell. +func upsertValue(ctx context.Context, executor queryExecutor, value ItemValue, updatedAt int64) (bool, error) { + result, err := executor.Exec(ctx, ` + INSERT INTO item_values (id, itemid, fieldid, value, updatedat) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (id) DO UPDATE + SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat + WHERE EXCLUDED.updatedat >= item_values.updatedat + AND item_values.itemid = EXCLUDED.itemid + AND item_values.fieldid = EXCLUDED.fieldid + `, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt) + if err != nil { + return false, err + } + return result.RowsAffected() > 0, nil +} + +// cascadeDeleteList removes the children of a deleted list: its fields and items +// are soft-deleted and their values are hard-deleted. The REST and sync delete +// paths both call it, so they leave the same state behind. +func cascadeDeleteList(ctx context.Context, tx pgx.Tx, listID string, updatedAt int64) error { + if _, err := tx.Exec(ctx, `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil { + return err + } + if _, err := tx.Exec(ctx, `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil { + return err + } + _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID) + return err +} + +// cascadeDeleteField removes the values of a deleted field. When no active field +// remains in the list, the list's items are deleted too, and the returned flag +// reports that. +func cascadeDeleteField(ctx context.Context, tx pgx.Tx, fieldID, listID string, updatedAt int64) (bool, error) { + if _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE fieldid = $1`, fieldID); err != nil { + return false, err + } + var remaining int + if err := tx.QueryRow(ctx, `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, listID).Scan(&remaining); err != nil { + return false, err + } + if remaining > 0 { + return false, nil + } + if _, err := tx.Exec(ctx, `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil { + return false, err + } + if _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID); err != nil { + return false, err + } + return true, nil +} + +// cascadeDeleteItem removes the values of a deleted item. +func cascadeDeleteItem(ctx context.Context, tx pgx.Tx, itemID string) error { + _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid = $1`, itemID) + return err +} + type listMutation struct { List DeviceID string `json:"deviceId,omitempty"` @@ -237,8 +363,8 @@ func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) { } var request listMutation - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") + if err := decodeJSON(w, r, &request); err != nil { + writeDecodeError(w, err, "Invalid JSON body") return } if request.ID == "" || request.Name == "" { @@ -285,8 +411,8 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) { Name string `json:"name"` DeviceID string `json:"deviceId,omitempty"` } - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") + if err := decodeJSON(w, r, &request); err != nil { + writeDecodeError(w, err, "Invalid JSON body") return } updatedAt := time.Now().UnixMilli() @@ -308,16 +434,28 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, list) case http.MethodDelete: updatedAt := time.Now().UnixMilli() - result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id) + err := s.db.withTx(r.Context(), func(tx pgx.Tx) error { + result, err := tx.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id) + if err != nil { + return err + } + if result.RowsAffected() == 0 { + return pgx.ErrNoRows + } + if err := cascadeDeleteList(r.Context(), tx, id, updatedAt); err != nil { + return err + } + ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt)) + return nil + }) + if errors.Is(err, pgx.ErrNoRows) { + writeJSONError(w, http.StatusNotFound, "List not found") + return + } if err != nil { writeJSONError(w, http.StatusInternalServerError, "Failed to delete list") return } - if result.RowsAffected() == 0 { - writeJSONError(w, http.StatusNotFound, "List not found") - return - } - ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt)) writeJSON(w, http.StatusOK, map[string]string{"message": "List deleted successfully"}) } } @@ -338,20 +476,15 @@ func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) { func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) { var request fieldMutation - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") + if err := decodeJSON(w, r, &request); err != nil { + writeDecodeError(w, err, "Invalid JSON body") return } if request.ID == "" || request.ListID == "" || request.Name == "" { writeJSONError(w, http.StatusBadRequest, "Field id, listId, and name are required") return } - if request.Alignment == "" { - request.Alignment = "start" - } - if request.FieldType == "" { - request.FieldType = "TEXT" - } + request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment) _, err := s.db.pool.Exec(r.Context(), ` INSERT INTO fields (id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted) @@ -386,16 +519,11 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) { Order int `json:"order"` DeviceID string `json:"deviceId,omitempty"` } - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") + if err := decodeJSON(w, r, &request); err != nil { + writeDecodeError(w, err, "Invalid JSON body") return } - if request.Alignment == "" { - request.Alignment = "start" - } - if request.FieldType == "" { - request.FieldType = "TEXT" - } + request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment) updatedAt := time.Now().UnixMilli() result, err := s.db.pool.Exec(r.Context(), ` UPDATE fields @@ -421,7 +549,7 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) { var request struct { DeviceID string `json:"deviceId,omitempty"` } - _ = decodeJSON(r, &request) // DELETE bodies are optional. + _ = decodeJSON(w, r, &request) // DELETE bodies are optional. updatedAt := time.Now().UnixMilli() var field Field cascade := false @@ -434,23 +562,11 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) { if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil { return err } - if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, id); err != nil { + cascade, err = cascadeDeleteField(r.Context(), tx, id, field.ListID, updatedAt) + if err != nil { return err } - var remaining int - if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil { - return err - } - if remaining == 0 { - cascade = true - if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil { - return err - } - if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil { - return err - } - } - ignoreNotificationError(enqueueNotification(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt)) + ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt)) return nil }) if errors.Is(err, pgx.ErrNoRows) { @@ -488,8 +604,8 @@ func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) { func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) { var request itemMutation - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") + if err := decodeJSON(w, r, &request); err != nil { + writeDecodeError(w, err, "Invalid JSON body") return } if request.ID == "" || request.ListID == "" { @@ -538,27 +654,25 @@ func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Reques ItemValue DeviceID string `json:"deviceId,omitempty"` } - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") + if err := decodeJSON(w, r, &request); err != nil { + writeDecodeError(w, err, "Invalid JSON body") return } if request.ID == "" || request.ItemID == "" || request.FieldID == "" { writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required") return } - _, err := s.db.pool.Exec(r.Context(), ` - INSERT INTO item_values (id, itemid, fieldid, value, updatedat) - VALUES ($1, $2, $3, $4, $5) - ON CONFLICT (id) DO UPDATE - SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat - `, request.ID, request.ItemID, request.FieldID, request.Value, int64(request.UpdatedAt)) + applied, err := upsertValue(r.Context(), s.db.pool, request.ItemValue, int64(request.UpdatedAt)) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Failed to save item value") return } + // An older write than the stored value changes nothing, so it notifies no one. var listID string - if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil { - ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli())) + if applied { + if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil { + ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli())) + } } var value ItemValue err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan( @@ -584,7 +698,7 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) { DeviceID string `json:"deviceId,omitempty"` } if r.Method == http.MethodPut || r.Method == http.MethodDelete { - _ = decodeJSON(r, &request) + _ = decodeJSON(w, r, &request) } updatedAt := time.Now().UnixMilli() if r.Method == http.MethodPut { @@ -606,19 +720,31 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, item) return } - result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Failed to delete item") - return - } - if result.RowsAffected() == 0 { + err := s.db.withTx(r.Context(), func(tx pgx.Tx) error { + result, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id) + if err != nil { + return err + } + if result.RowsAffected() == 0 { + return pgx.ErrNoRows + } + item, err := scanItem(tx.QueryRow(r.Context(), `SELECT `+itemColumns+` FROM items WHERE id = $1`, id)) + if err != nil { + return err + } + if err := cascadeDeleteItem(r.Context(), tx, id); err != nil { + return err + } + ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt)) + return nil + }) + if errors.Is(err, pgx.ErrNoRows) { writeJSONError(w, http.StatusNotFound, "Item not found") return } - item, itemErr := s.getItem(r.Context(), id) - if itemErr == nil { - _, _ = s.db.pool.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, id) - ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt)) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, "Failed to delete item") + return } writeJSON(w, http.StatusOK, map[string]string{"message": "Item deleted successfully"}) } diff --git a/backend/data_test.go b/backend/data_test.go new file mode 100644 index 0000000..5c5f165 --- /dev/null +++ b/backend/data_test.go @@ -0,0 +1,14 @@ +package main + +import "testing" + +func TestFieldDefaultsFillMissingValues(t *testing.T) { + fieldType, alignment := fieldDefaults("", "") + if fieldType != "TEXT" || alignment != "start" { + t.Fatalf("fieldDefaults(empty) = (%q, %q), want (TEXT, start)", fieldType, alignment) + } + fieldType, alignment = fieldDefaults("NUMBER", "end") + if fieldType != "NUMBER" || alignment != "end" { + t.Fatalf("fieldDefaults(set) = (%q, %q), want (NUMBER, end)", fieldType, alignment) + } +} diff --git a/backend/db.go b/backend/db.go index 4deb3b3..3392818 100644 --- a/backend/db.go +++ b/backend/db.go @@ -84,6 +84,10 @@ func (d *DB) initSchema(ctx context.Context) error { CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid); CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid); CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid); + CREATE INDEX IF NOT EXISTS idx_lists_updatedat ON lists(updatedat); + CREATE INDEX IF NOT EXISTS idx_fields_updatedat ON fields(updatedat); + CREATE INDEX IF NOT EXISTS idx_items_updatedat ON items(updatedat); + CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat); CREATE TABLE IF NOT EXISTS notifications ( id TEXT PRIMARY KEY, diff --git a/backend/db_test.go b/backend/db_test.go new file mode 100644 index 0000000..f935662 --- /dev/null +++ b/backend/db_test.go @@ -0,0 +1,581 @@ +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) + } +} diff --git a/backend/notifications.go b/backend/notifications.go index ddb151d..59e2fdc 100644 --- a/backend/notifications.go +++ b/backend/notifications.go @@ -41,6 +41,31 @@ func enqueueNotification( return err } +// enqueueNotificationInTx writes a notification inside a savepoint. PostgreSQL +// aborts the whole transaction after any failing statement, so without the +// savepoint a failed notification insert would make the data mutation's commit +// fail too. +func enqueueNotificationInTx( + ctx context.Context, + tx pgx.Tx, + deviceID string, + eventType string, + entityType string, + entityID string, + listID string, + createdAt int64, +) error { + savepoint, err := tx.Begin(ctx) + if err != nil { + return err + } + if err := enqueueNotification(ctx, savepoint, deviceID, eventType, entityType, entityID, listID, createdAt); err != nil { + _ = savepoint.Rollback(ctx) + return err + } + return savepoint.Commit(ctx) +} + func nullableString(value string) any { if value == "" { return nil @@ -48,6 +73,8 @@ func nullableString(value string) any { return value } +// ignoreNotificationError logs a failed notification. Use it only for +// notifications written by enqueueNotificationInTx or outside a transaction. func ignoreNotificationError(err error) { if err != nil { // Notifications are an acceleration path for clients that poll. A failed diff --git a/backend/ratelimit.go b/backend/ratelimit.go new file mode 100644 index 0000000..70c8942 --- /dev/null +++ b/backend/ratelimit.go @@ -0,0 +1,212 @@ +package main + +import ( + "bytes" + "encoding/json" + "io" + "math" + "net" + "net/http" + "strconv" + "strings" + "sync" + "time" +) + +// Budgets for the credential-bearing auth routes. Client IPs are resolved with +// clientIP, so they honour X-Forwarded-For only from TRUSTED_PROXIES. +const ( + authIPLimit = 30 + authIPWindow = time.Minute + loginFailureLimit = 10 + loginFailureWindow = 15 * time.Minute + // loginBodyLimit matches the body cap AuthGuard's login handler reads. + loginBodyLimit = 128 * 1024 + // rateLimiterMaxKeys bounds memory held for distinct keys. + rateLimiterMaxKeys = 10000 +) + +// rateLimiter counts events per key in fixed windows. It lives in process, so +// the budgets apply to one server instance. +type rateLimiter struct { + mu sync.Mutex + limit int + window time.Duration + maxKeys int + now func() time.Time + counts map[string]*rateWindow +} + +type rateWindow struct { + start time.Time + count int +} + +func newRateLimiter(limit int, window time.Duration) *rateLimiter { + return &rateLimiter{ + limit: limit, + window: window, + maxKeys: rateLimiterMaxKeys, + now: time.Now, + counts: make(map[string]*rateWindow), + } +} + +// Blocked reports whether key has spent its budget in the current window, and +// how long until that window ends. +func (l *rateLimiter) Blocked(key string) (bool, time.Duration) { + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + window, ok := l.counts[key] + if !ok || now.Sub(window.start) >= l.window || window.count < l.limit { + return false, 0 + } + return true, window.start.Add(l.window).Sub(now) +} + +// Hit counts one event for key in the current window. +func (l *rateLimiter) Hit(key string) { + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + window, ok := l.counts[key] + if !ok || now.Sub(window.start) >= l.window { + if !ok && len(l.counts) >= l.maxKeys { + l.evictLocked(now) + } + window = &rateWindow{start: now} + l.counts[key] = window + } + window.count++ +} + +// evictLocked drops expired windows. If every window is still live, it clears +// the map rather than let memory grow without bound. That can reset budgets +// under a flood of distinct keys, which is the cost of a bounded map. +func (l *rateLimiter) evictLocked(now time.Time) { + for key, window := range l.counts { + if now.Sub(window.start) >= l.window { + delete(l.counts, key) + } + } + if len(l.counts) >= l.maxKeys { + clear(l.counts) + } +} + +// writeRateLimited answers 429 with a Retry-After in whole seconds. +func writeRateLimited(w http.ResponseWriter, retryAfter time.Duration) { + seconds := int(math.Ceil(retryAfter.Seconds())) + if seconds < 1 { + seconds = 1 + } + w.Header().Set("Retry-After", strconv.Itoa(seconds)) + writeJSONError(w, http.StatusTooManyRequests, "Too many attempts. Try again later.") +} + +// authRateLimits holds the budgets for the auth routes. A fresh set is built +// per route registration, so tests start with empty counters. +type authRateLimits struct { + trusted []*net.IPNet + ip *rateLimiter + failures *rateLimiter +} + +func newAuthRateLimits(trusted []*net.IPNet) *authRateLimits { + return &authRateLimits{ + trusted: trusted, + ip: newRateLimiter(authIPLimit, authIPWindow), + failures: newRateLimiter(loginFailureLimit, loginFailureWindow), + } +} + +// perClient counts every request against the client's IP and refuses it once +// the IP has spent its budget. Used on setup, TOTP and token regeneration. +func (l *authRateLimits) perClient(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + key := clientIP(r, l.trusted) + if blocked, retryAfter := l.ip.Blocked(key); blocked { + writeRateLimited(w, retryAfter) + return + } + l.ip.Hit(key) + next.ServeHTTP(w, r) + }) +} + +// login applies two budgets. Every attempt counts against the client IP. Failed +// attempts (401) count against the account named in the body, so guessing one +// password is capped even when the attacker rotates addresses. +func (l *authRateLimits) login(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + key := clientIP(r, l.trusted) + if blocked, retryAfter := l.ip.Blocked(key); blocked { + writeRateLimited(w, retryAfter) + return + } + l.ip.Hit(key) + + account := loginAccount(r) + if account != "" { + if blocked, retryAfter := l.failures.Blocked(account); blocked { + writeRateLimited(w, retryAfter) + return + } + } + recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK} + next.ServeHTTP(recorder, r) + if account != "" && recorder.status == http.StatusUnauthorized { + l.failures.Hit(account) + } + }) +} + +// loginAccount returns the normalised identifier from a login body and restores +// the body for the handler. It returns "" when the body names no account. +func loginAccount(r *http.Request) string { + if r.Body == nil { + return "" + } + raw, err := io.ReadAll(io.LimitReader(r.Body, loginBodyLimit)) + _ = r.Body.Close() + r.Body = io.NopCloser(bytes.NewReader(raw)) + if err != nil { + return "" + } + var input struct { + Identifier string `json:"identifier"` + Email string `json:"email"` + } + if json.Unmarshal(raw, &input) != nil { + return "" + } + identifier := strings.TrimSpace(input.Identifier) + if identifier == "" { + identifier = strings.TrimSpace(input.Email) + } + return strings.ToLower(identifier) +} + +// statusRecorder notes the status code a handler writes, so login can tell a +// rejected password from other outcomes. +type statusRecorder struct { + http.ResponseWriter + status int + wroteHeader bool +} + +func (w *statusRecorder) WriteHeader(status int) { + if !w.wroteHeader { + w.status = status + w.wroteHeader = true + } + w.ResponseWriter.WriteHeader(status) +} + +func (w *statusRecorder) Write(p []byte) (int, error) { + if !w.wroteHeader { + w.WriteHeader(http.StatusOK) + } + return w.ResponseWriter.Write(p) +} diff --git a/backend/ratelimit_test.go b/backend/ratelimit_test.go new file mode 100644 index 0000000..4c6d123 --- /dev/null +++ b/backend/ratelimit_test.go @@ -0,0 +1,226 @@ +package main + +import ( + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" +) + +func TestRateLimiterBlocksAfterLimitAndResetsWithWindow(t *testing.T) { + now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC) + limiter := newRateLimiter(3, time.Minute) + limiter.now = func() time.Time { return now } + + for i := 0; i < 3; i++ { + if blocked, _ := limiter.Blocked("a"); blocked { + t.Fatalf("hit %d blocked before the budget was spent", i+1) + } + limiter.Hit("a") + } + blocked, retryAfter := limiter.Blocked("a") + if !blocked { + t.Fatal("fourth attempt was not blocked") + } + if retryAfter != time.Minute { + t.Fatalf("retryAfter = %s, want 1m0s", retryAfter) + } + if blocked, _ := limiter.Blocked("b"); blocked { + t.Fatal("budget for one key blocked another key") + } + + now = now.Add(30 * time.Second) + if blocked, retryAfter := limiter.Blocked("a"); !blocked || retryAfter != 30*time.Second { + t.Fatalf("mid-window Blocked() = %v, %s; want true, 30s", blocked, retryAfter) + } + + now = now.Add(31 * time.Second) + if blocked, _ := limiter.Blocked("a"); blocked { + t.Fatal("budget did not reset when the window ended") + } +} + +func TestRateLimiterBoundsDistinctKeys(t *testing.T) { + now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC) + limiter := newRateLimiter(5, time.Minute) + limiter.maxKeys = 4 + limiter.now = func() time.Time { return now } + + for i := 0; i < 20; i++ { + limiter.Hit("ip-" + strconv.Itoa(i)) + if len(limiter.counts) > limiter.maxKeys { + t.Fatalf("tracked %d keys, want at most %d", len(limiter.counts), limiter.maxKeys) + } + } + + // Once the windows have expired, a new key evicts them instead of clearing live ones. + now = now.Add(2 * time.Minute) + limiter.Hit("fresh") + if len(limiter.counts) != 1 { + t.Fatalf("after expiry tracked %d keys, want 1", len(limiter.counts)) + } +} + +func TestPerClientBudgetCountsEveryRequest(t *testing.T) { + limits := newAuthRateLimits(nil) + reached := 0 + handler := limits.perClient(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + reached++ + w.WriteHeader(http.StatusOK) + })) + + for i := 0; i < authIPLimit+1; i++ { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/auth/totp/enable", nil)) + if i < authIPLimit && recorder.Code != http.StatusOK { + t.Fatalf("request %d status = %d, want 200", i+1, recorder.Code) + } + if i == authIPLimit { + if recorder.Code != http.StatusTooManyRequests { + t.Fatalf("request %d status = %d, want 429", i+1, recorder.Code) + } + if recorder.Header().Get("Retry-After") == "" { + t.Fatal("429 response has no Retry-After header") + } + } + } + if reached != authIPLimit { + t.Fatalf("handler ran %d times, want %d", reached, authIPLimit) + } +} + +// loginRequest sends one login attempt from the given address and returns the status. +func loginRequest(handler http.Handler, remoteAddr, forwardedFor, body string) int { + request := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(body)) + request.RemoteAddr = remoteAddr + if forwardedFor != "" { + request.Header.Set("X-Forwarded-For", forwardedFor) + } + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + return recorder.Code +} + +func TestLoginLocksAccountAfterFailuresAcrossAddresses(t *testing.T) { + limits := newAuthRateLimits(nil) + handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // The handler must still see the body that the limiter read. + raw, _ := io.ReadAll(r.Body) + if !strings.Contains(string(raw), `"password":"wrong"`) { + t.Errorf("handler body = %q, want the original login body", raw) + } + w.WriteHeader(http.StatusUnauthorized) + })) + + body := `{"identifier":" Alice@Example.com ","password":"wrong"}` + for i := 0; i < loginFailureLimit; i++ { + // A new address each time, so only the per-account budget can trip. + addr := "198.51.100." + strconv.Itoa(i+1) + ":5000" + if status := loginRequest(handler, addr, "", body); status != http.StatusUnauthorized { + t.Fatalf("failed attempt %d status = %d, want 401", i+1, status) + } + } + if status := loginRequest(handler, "203.0.113.50:5000", "", body); status != http.StatusTooManyRequests { + t.Fatalf("attempt after lockout status = %d, want 429", status) + } + other := `{"identifier":"bob@example.com","password":"wrong"}` + if status := loginRequest(handler, "203.0.113.51:5000", "", other); status != http.StatusUnauthorized { + t.Fatalf("different account status = %d, want 401", status) + } +} + +func TestLoginSuccessesDoNotCountAgainstAccount(t *testing.T) { + limits := newAuthRateLimits(nil) + handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + body := `{"email":"carol@example.com","password":"right"}` + for i := 0; i < loginFailureLimit+5; i++ { + if status := loginRequest(handler, "198.51.100.9:5000", "", body); status != http.StatusOK { + t.Fatalf("successful attempt %d status = %d, want 200", i+1, status) + } + } +} + +func TestLoginIPBudgetUsesForwardedClientOnlyFromTrustedProxy(t *testing.T) { + trusted := mustTrusted(t, "10.0.0.1") + body := `{"identifier":"someone","password":"x"}` + ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + + // Behind the trusted proxy, each forwarded client has its own budget. + proxied := newAuthRateLimits(trusted).login(ok) + for i := 0; i < authIPLimit+10; i++ { + forwarded := "203.0.113." + strconv.Itoa(i+1) + if status := loginRequest(proxied, "10.0.0.1:5000", forwarded, body); status != http.StatusOK { + t.Fatalf("forwarded client %s status = %d, want 200", forwarded, status) + } + } + + // A caller that is not a trusted proxy cannot pick its own address. + direct := newAuthRateLimits(trusted).login(ok) + statuses := make(map[int]int) + for i := 0; i < authIPLimit+10; i++ { + forwarded := "203.0.113." + strconv.Itoa(i+1) + statuses[loginRequest(direct, "192.0.2.9:5000", forwarded, body)]++ + } + if statuses[http.StatusTooManyRequests] == 0 { + t.Fatalf("forged X-Forwarded-For bypassed the IP budget: %v", statuses) + } +} + +func TestRegisterRoutesLimitsLoginPerClient(t *testing.T) { + // Auth is disabled, so login answers 200 without touching the database. + server := &Server{auth: newAuthService(nil, "", false, true)} + mux := http.NewServeMux() + server.registerRoutes(mux, webFS) + + body := `{"identifier":"admin","password":"x"}` + for i := 0; i < authIPLimit; i++ { + if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusOK { + t.Fatalf("attempt %d status = %d, want 200", i+1, status) + } + } + if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusTooManyRequests { + t.Fatalf("attempt over the budget status = %d, want 429", status) + } + if status := loginRequest(mux, "192.0.2.21:5000", "", body); status != http.StatusOK { + t.Fatalf("other client status = %d, want 200", status) + } +} + +func TestWithHTTPSRequiredRefusesPlainHTTP(t *testing.T) { + trusted := mustTrusted(t, "10.0.0.1") + ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + handler := withHTTPSRequired(trusted, ok) + + cases := []struct { + name string + path string + remoteAddr string + proto string + want int + }{ + {name: "plain request refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", want: http.StatusForbidden}, + {name: "health probe stays open", path: "/health", remoteAddr: "192.0.2.9:5000", want: http.StatusOK}, + {name: "trusted proxy over https allowed", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "https", want: http.StatusOK}, + {name: "trusted proxy over http refused", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "http", want: http.StatusForbidden}, + {name: "untrusted https claim refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", proto: "https", want: http.StatusForbidden}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodGet, tc.path, nil) + request.RemoteAddr = tc.remoteAddr + if tc.proto != "" { + request.Header.Set("X-Forwarded-Proto", tc.proto) + } + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + if recorder.Code != tc.want { + t.Fatalf("status = %d, want %d", recorder.Code, tc.want) + } + }) + } +} diff --git a/backend/routes_test.go b/backend/routes_test.go index b5f1c16..1b90c35 100644 --- a/backend/routes_test.go +++ b/backend/routes_test.go @@ -2,10 +2,35 @@ package main import ( "net/http" + "net/http/httptest" "testing" ) func TestRegisterRoutes(t *testing.T) { - server := &Server{auth: newAuthService(nil, "", false, false)} - server.registerRoutes(http.NewServeMux(), webFS) + // Auth is disabled and there is no database, so these checks only touch + // routes that answer before any query runs. + server := &Server{auth: newAuthService(nil, "", false, true)} + mux := http.NewServeMux() + server.registerRoutes(mux, webFS) + + cases := []struct { + name string + method string + path string + want int + }{ + {name: "health is public", method: http.MethodGet, path: "/health", want: http.StatusOK}, + {name: "sync needs a bearer token", method: http.MethodPost, path: "/api/sync", want: http.StatusUnauthorized}, + {name: "lists need a bearer token", method: http.MethodGet, path: "/api/lists", want: http.StatusUnauthorized}, + {name: "managed users pass the role gate when auth is disabled", method: http.MethodGet, path: "/api/auth/users", want: http.StatusOK}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + mux.ServeHTTP(recorder, httptest.NewRequest(tc.method, tc.path, nil)) + if recorder.Code != tc.want { + t.Fatalf("%s %s status = %d, want %d", tc.method, tc.path, recorder.Code, tc.want) + } + }) + } } diff --git a/backend/server.go b/backend/server.go index cf6aa78..97711a0 100644 --- a/backend/server.go +++ b/backend/server.go @@ -1,12 +1,14 @@ package main import ( + "compress/gzip" "context" "embed" "encoding/json" + "errors" "fmt" - "io" "io/fs" + "net" "net/http" "os" "path" @@ -36,8 +38,19 @@ type Server struct { internalServiceSecret string coreConfig *coreconfig.Store carrierNode *carriernodeclient.Client + syncSlots chan struct{} + // trustedProxies are the TRUSTED_PROXIES networks whose X-Forwarded-For and + // X-Forwarded-Proto headers are believed. Nil trusts no proxy. + trustedProxies []*net.IPNet } +// Request body limits per route. Sync pushes can carry many rows at once, so +// they keep the larger limit; single-entity writes get the smaller one. +const ( + jsonBodyLimit = 2 << 20 + syncBodyLimit = 50 << 20 +) + func main() { port := envOrDefault("PORT", "8080") connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL")) @@ -47,6 +60,19 @@ func main() { } internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET")) + trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES")) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + // PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so + // the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES. + production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true") + if production && len(trustedProxies) == 0 { + fmt.Fprintln(os.Stderr, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there") + os.Exit(1) + } + ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -104,6 +130,8 @@ func main() { internalServiceSecret: internalServiceSecret, coreConfig: coreConfig, carrierNode: carrierNode, + syncSlots: make(chan struct{}, maxConcurrentSyncs), + trustedProxies: trustedProxies, } webRoot, err := fs.Sub(webFS, "web") @@ -115,9 +143,17 @@ func main() { mux := http.NewServeMux() server.registerRoutes(mux, webRoot) + handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux))) + if production { + handler = withHTTPSRequired(trustedProxies, handler) + fmt.Println("PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https") + } else { + fmt.Fprintln(os.Stderr, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.") + } + httpServer := &http.Server{ Addr: ":" + port, - Handler: withCORS(mux), + Handler: handler, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 60 * time.Second, WriteTimeout: 60 * time.Second, @@ -163,6 +199,10 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) } func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) { + // Budgets for setup, login, TOTP and token regeneration, keyed by client IP + // (and by account for failed logins). See ratelimit.go. + limits := newAuthRateLimits(s.trustedProxies) + // Health and auth bootstrap routes are intentionally public. mux.HandleFunc("GET /health", s.handleHealth) mux.HandleFunc("GET /api/info", s.handleInfo) @@ -170,22 +210,23 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) { // to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above). mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig)) mux.HandleFunc("GET /api/auth/status", s.auth.Status) - mux.HandleFunc("POST /api/auth/setup", s.auth.Signup) - mux.HandleFunc("POST /api/auth/login", s.auth.Login) + mux.Handle("POST /api/auth/setup", limits.perClient(http.HandlerFunc(s.auth.Signup))) + mux.Handle("POST /api/auth/login", limits.login(http.HandlerFunc(s.auth.Login))) mux.Handle("PUT /api/auth/access/internal", s.auth.SetLoginRequiredInternal(s.internalServiceSecret)) mux.Handle("POST /api/auth/logout", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.Logout))) mux.Handle("POST /api/auth/credentials", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.UpdateMe))) - mux.Handle("GET /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUsers))) - mux.Handle("POST /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedCreateUser))) - mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser))) - mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser))) - mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedDeleteUser))) - mux.Handle("GET /api/auth/totp/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus))) - mux.Handle("POST /api/auth/totp/setup", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate))) - mux.Handle("POST /api/auth/totp/enable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify))) - mux.Handle("POST /api/auth/totp/disable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable))) + // Managed-user routes check the caller's role here, not only in AuthGuard. + mux.Handle("GET /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUsers))) + mux.Handle("POST /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedCreateUser))) + mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser))) + mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser))) + mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedDeleteUser))) + mux.Handle("GET /api/auth/totp/status", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus)))) + mux.Handle("POST /api/auth/totp/setup", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate)))) + mux.Handle("POST /api/auth/totp/enable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify)))) + mux.Handle("POST /api/auth/totp/disable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable)))) mux.Handle("GET /api/auth/token/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenStatus))) - mux.Handle("POST /api/auth/token/regenerate", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate))) + mux.Handle("POST /api/auth/token/regenerate", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate)))) // Sync/collaboration API routes use a long-lived bearer token shared by the // user's devices. This is deliberately separate from browser sessions. @@ -250,12 +291,24 @@ func envOrDefault(name, fallback string) string { return fallback } -func decodeJSON(r *http.Request, target any) error { - decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024)) - if err := decoder.Decode(target); err != nil { - return err +func decodeJSON(w http.ResponseWriter, r *http.Request, target any) error { + return decodeJSONLimit(w, r, target, jsonBodyLimit) +} + +// decodeJSONLimit decodes a body of at most limit bytes. An oversized body fails +// with *http.MaxBytesError, which writeDecodeError turns into 413. +func decodeJSONLimit(w http.ResponseWriter, r *http.Request, target any, limit int64) error { + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit)) + return decoder.Decode(target) +} + +func writeDecodeError(w http.ResponseWriter, err error, message string) { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + writeJSONError(w, http.StatusRequestEntityTooLarge, "Request body too large") + return } - return nil + writeJSONError(w, http.StatusBadRequest, message) } func writeJSON(w http.ResponseWriter, status int, value any) { @@ -271,17 +324,42 @@ func writeJSONError(w http.ResponseWriter, status int, message string) { }) } -func withCORS(next http.Handler) http.Handler { +// allowedOriginsFromEnv reads ALLOWED_ORIGINS, a comma-separated list of browser +// origins that may call the API cross-origin with credentials. It is empty by +// default: the dashboard is same-origin and needs no CORS headers. +func allowedOriginsFromEnv() []string { + var origins []string + for _, origin := range strings.Split(os.Getenv("ALLOWED_ORIGINS"), ",") { + if origin = strings.TrimSpace(origin); origin != "" { + origins = append(origins, origin) + } + } + return origins +} + +// withCORS sends CORS headers only for origins in allowedOrigins. Any other +// origin gets no Access-Control-Allow-Origin and no credentials header, so a +// browser refuses its cross-origin reads. +func withCORS(allowedOrigins []string, next http.Handler) http.Handler { + allowed := make(map[string]bool, len(allowedOrigins)) + for _, origin := range allowedOrigins { + allowed[origin] = true + } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get("Origin") if origin != "" { - w.Header().Set("Access-Control-Allow-Origin", origin) - w.Header().Set("Access-Control-Allow-Credentials", "true") w.Header().Add("Vary", "Origin") } + permitted := origin != "" && allowed[origin] + if permitted { + w.Header().Set("Access-Control-Allow-Origin", origin) + w.Header().Set("Access-Control-Allow-Credentials", "true") + } if r.Method == http.MethodOptions { - w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id") - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + if permitted { + w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id") + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") + } w.WriteHeader(http.StatusNoContent) return } @@ -289,6 +367,82 @@ func withCORS(next http.Handler) http.Handler { }) } +// withSecurityHeaders sets headers that stop the dashboard and API from being +// framed (clickjacking) or MIME-sniffed. The dashboard page replaces the +// Content-Security-Policy with the full one from dashboardCSP. HSTS is not set +// here: this process has no TLS, so the TLS proxy sets Strict-Transport-Security. +func withSecurityHeaders(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + headers := w.Header() + headers.Set("X-Content-Type-Options", "nosniff") + headers.Set("X-Frame-Options", "DENY") + headers.Set("Content-Security-Policy", "frame-ancestors 'none'") + headers.Set("Referrer-Policy", "strict-origin-when-cross-origin") + next.ServeHTTP(w, r) + }) +} + +// withHTTPSRequired is the PRODUCTION=true profile: a request that did not +// arrive over TLS, directly or through a trusted proxy, gets 403. The health +// probe is exempt so local container checks keep working. +func withHTTPSRequired(trusted []*net.IPNet, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/health" || requestIsHTTPS(r, trusted) { + next.ServeHTTP(w, r) + return + } + writeJSONError(w, http.StatusForbidden, "HTTPS is required on this server") + }) +} + +// gzipResponseWriter compresses a response body when the client accepts gzip. +// Responses that carry no body (204, 304) are passed through unchanged. +type gzipResponseWriter struct { + http.ResponseWriter + gzipWriter *gzip.Writer + wroteHeader bool +} + +func (w *gzipResponseWriter) WriteHeader(status int) { + if w.wroteHeader { + return + } + w.wroteHeader = true + // Partial (206) bodies are left alone: a byte range of the plain file is not a gzip stream. + if status != http.StatusNoContent && status != http.StatusNotModified && status != http.StatusPartialContent { + w.Header().Set("Content-Encoding", "gzip") + w.Header().Del("Content-Length") + w.gzipWriter = gzip.NewWriter(w.ResponseWriter) + } + w.ResponseWriter.WriteHeader(status) +} + +func (w *gzipResponseWriter) Write(p []byte) (int, error) { + if !w.wroteHeader { + w.WriteHeader(http.StatusOK) + } + if w.gzipWriter == nil { + return w.ResponseWriter.Write(p) + } + return w.gzipWriter.Write(p) +} + +// withGzip compresses responses for clients that send Accept-Encoding: gzip. +func withGzip(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Vary", "Accept-Encoding") + if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { + next.ServeHTTP(w, r) + return + } + compressed := &gzipResponseWriter{ResponseWriter: w} + next.ServeHTTP(compressed, r) + if compressed.gzipWriter != nil { + _ = compressed.gzipWriter.Close() + } + }) +} + func spaFileServer(root fs.FS) http.Handler { fileServer := http.FileServer(http.FS(root)) serveIndex := func(w http.ResponseWriter, r *http.Request) { @@ -298,6 +452,8 @@ func spaFileServer(root fs.FS) http.Handler { return } w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Content-Security-Policy", dashboardCSP(data)) _, _ = w.Write(data) } @@ -311,6 +467,13 @@ func spaFileServer(root fs.FS) http.Handler { serveIndex(w, r) return } + // SvelteKit names its content-hashed bundle files under _app/immutable/, so + // those can be cached for a long time. Everything else is revalidated. + if strings.HasPrefix(cleanPath, "_app/immutable/") { + w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") + } else { + w.Header().Set("Cache-Control", "no-cache") + } fileServer.ServeHTTP(w, r) }) } diff --git a/backend/server_test.go b/backend/server_test.go new file mode 100644 index 0000000..2812251 --- /dev/null +++ b/backend/server_test.go @@ -0,0 +1,203 @@ +package main + +import ( + "compress/gzip" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "testing/fstest" +) + +func TestWithCORSAllowsOnlyListedOrigins(t *testing.T) { + const listed = "https://dashboard.example.com" + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + cases := []struct { + name string + allowed []string + origin string + want string + }{ + {name: "listed origin is echoed", allowed: []string{listed}, origin: listed, want: listed}, + {name: "unlisted origin gets no header", allowed: []string{listed}, origin: "https://evil.example", want: ""}, + {name: "no allow list means no CORS", allowed: nil, origin: listed, want: ""}, + {name: "no origin header means no CORS", allowed: []string{listed}, origin: "", want: ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/api/lists", nil) + if tc.origin != "" { + request.Header.Set("Origin", tc.origin) + } + withCORS(tc.allowed, next).ServeHTTP(recorder, request) + + if got := recorder.Header().Get("Access-Control-Allow-Origin"); got != tc.want { + t.Fatalf("Access-Control-Allow-Origin = %q, want %q", got, tc.want) + } + wantCredentials := "" + if tc.want != "" { + wantCredentials = "true" + } + if got := recorder.Header().Get("Access-Control-Allow-Credentials"); got != wantCredentials { + t.Fatalf("Access-Control-Allow-Credentials = %q, want %q", got, wantCredentials) + } + }) + } +} + +func TestWithCORSPreflightAllowsPatchForListedOrigin(t *testing.T) { + const listed = "https://dashboard.example.com" + handler := withCORS([]string{listed}, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodOptions, "/api/auth/users/1", nil) + request.Header.Set("Origin", listed) + handler.ServeHTTP(recorder, request) + + if recorder.Code != http.StatusNoContent { + t.Fatalf("preflight status = %d, want %d", recorder.Code, http.StatusNoContent) + } + if methods := recorder.Header().Get("Access-Control-Allow-Methods"); !strings.Contains(methods, "PATCH") { + t.Fatalf("Access-Control-Allow-Methods = %q, want PATCH included", methods) + } +} + +func TestWithSecurityHeadersSetsFramingAndSniffingDefaults(t *testing.T) { + handler := withSecurityHeaders(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + + want := map[string]string{ + "X-Content-Type-Options": "nosniff", + "X-Frame-Options": "DENY", + "Content-Security-Policy": "frame-ancestors 'none'", + "Referrer-Policy": "strict-origin-when-cross-origin", + } + for name, value := range want { + if got := recorder.Header().Get(name); got != value { + t.Fatalf("%s = %q, want %q", name, got, value) + } + } +} + +func TestWithGzipCompressesOnlyWhenAccepted(t *testing.T) { + handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) + })) + + accepted := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/web/data", nil) + request.Header.Set("Accept-Encoding", "gzip, deflate") + handler.ServeHTTP(accepted, request) + if got := accepted.Header().Get("Content-Encoding"); got != "gzip" { + t.Fatalf("Content-Encoding = %q, want gzip", got) + } + reader, err := gzip.NewReader(accepted.Body) + if err != nil { + t.Fatalf("gzip.NewReader() error = %v", err) + } + body, err := io.ReadAll(reader) + if err != nil { + t.Fatalf("reading gzip body error = %v", err) + } + if got := strings.TrimSpace(string(body)); got != `{"ok":true}` { + t.Fatalf("decompressed body = %q, want the JSON document", got) + } + + plain := httptest.NewRecorder() + handler.ServeHTTP(plain, httptest.NewRequest(http.MethodGet, "/web/data", nil)) + if got := plain.Header().Get("Content-Encoding"); got != "" { + t.Fatalf("Content-Encoding without Accept-Encoding = %q, want none", got) + } + if got := strings.TrimSpace(plain.Body.String()); got != `{"ok":true}` { + t.Fatalf("plain body = %q, want the JSON document", got) + } +} + +func TestWithGzipLeavesNotModifiedWithoutBody(t *testing.T) { + handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("ETag", `W/"abc"`) + w.WriteHeader(http.StatusNotModified) + })) + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/web/data", nil) + request.Header.Set("Accept-Encoding", "gzip") + handler.ServeHTTP(recorder, request) + + if recorder.Code != http.StatusNotModified { + t.Fatalf("status = %d, want %d", recorder.Code, http.StatusNotModified) + } + if got := recorder.Header().Get("Content-Encoding"); got != "" { + t.Fatalf("Content-Encoding on 304 = %q, want none", got) + } + if recorder.Body.Len() != 0 { + t.Fatalf("304 body length = %d, want 0", recorder.Body.Len()) + } +} + +func TestSPAFileServerCachesHashedAssetsLong(t *testing.T) { + root := fstest.MapFS{ + "index.html": {Data: []byte("")}, + "favicon.svg": {Data: []byte("")}, + "_app/immutable/app.abc.js": {Data: []byte("console.log(1)")}, + } + handler := spaFileServer(root) + + cases := []struct { + path string + want string + }{ + {path: "/", want: "no-cache"}, + {path: "/favicon.svg", want: "no-cache"}, + {path: "/_app/immutable/app.abc.js", want: "public, max-age=31536000, immutable"}, + {path: "/lists/123", want: "no-cache"}, + } + for _, tc := range cases { + t.Run(tc.path, func(t *testing.T) { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, tc.path, nil)) + if got := recorder.Header().Get("Cache-Control"); got != tc.want { + t.Fatalf("Cache-Control = %q, want %q", got, tc.want) + } + }) + } +} + +func TestDecodeJSONLimitRejectsOversizedBodies(t *testing.T) { + type payload struct { + Name string `json:"name"` + } + + small := httptest.NewRecorder() + var ok payload + if err := decodeJSONLimit(small, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{"name":"a"}`)), &ok, 64); err != nil { + t.Fatalf("decodeJSONLimit() within limit error = %v", err) + } + + large := httptest.NewRecorder() + var tooBig payload + body := `{"name":"` + strings.Repeat("a", 256) + `"}` + err := decodeJSONLimit(large, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(body)), &tooBig, 64) + if err == nil { + t.Fatal("decodeJSONLimit() over limit returned no error") + } + answer := httptest.NewRecorder() + writeDecodeError(answer, err, "Invalid JSON body") + if answer.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status for oversized body = %d, want %d", answer.Code, http.StatusRequestEntityTooLarge) + } + + malformed := httptest.NewRecorder() + err = decodeJSONLimit(malformed, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{`)), &tooBig, 64) + writeDecodeError(malformed, err, "Invalid JSON body") + if malformed.Code != http.StatusBadRequest { + t.Fatalf("status for malformed body = %d, want %d", malformed.Code, http.StatusBadRequest) + } +} diff --git a/backend/sync.go b/backend/sync.go index f08ffb2..7f66c6c 100644 --- a/backend/sync.go +++ b/backend/sync.go @@ -9,6 +9,10 @@ import ( "github.com/jackc/pgx/v5" ) +// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size +// (DATABASE_MAX_CONNS defaults to 20), so syncs cannot hold every connection. +const maxConcurrentSyncs = 4 + func syncMaxFutureSkew() int64 { value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0) if value < 0 { @@ -91,16 +95,193 @@ func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[st return fieldLists, existingItems, nil } +// changeEventType names a synced change for the notification feed: a tombstone +// is "deleted", a first sync reports "created", and anything else "updated". +func changeEventType(initialSync, deleted bool) string { + if deleted { + return "deleted" + } + if initialSync { + return "created" + } + return "updated" +} + +// syncBatch holds what every row of one sync request shares. +type syncBatch struct { + now int64 + initialSync bool + deviceID string +} + +func (b syncBatch) notify(ctx context.Context, tx pgx.Tx, eventType, entityType, entityID, listID string, createdAt int64) { + ignoreNotificationError(enqueueNotificationInTx(ctx, tx, b.deviceID, eventType, entityType, entityID, listID, createdAt)) +} + +// applyLists upserts the pushed lists. A write older than the stored row +// changes nothing, so it triggers no cascade or notification. +func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) error { + for _, list := range lists { + createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), batch.now) + applied, err := upsertList(ctx, tx, list, createdAt, updatedAt) + if err != nil { + return err + } + if !applied { + continue + } + batch.notify(ctx, tx, changeEventType(batch.initialSync, list.IsDeleted), "list", list.ID, list.ID, updatedAt) + + if list.IsDeleted { + if err := cascadeDeleteList(ctx, tx, list.ID, updatedAt); err != nil { + return err + } + } + } + return nil +} + +func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error { + for _, field := range fields { + createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now) + applied, err := upsertField(ctx, tx, field, createdAt, updatedAt) + if err != nil { + return err + } + if !applied { + continue + } + batch.notify(ctx, tx, changeEventType(batch.initialSync, field.IsDeleted), "field", field.ID, field.ListID, updatedAt) + + if field.IsDeleted { + if _, err := cascadeDeleteField(ctx, tx, field.ID, field.ListID, updatedAt); err != nil { + return err + } + } + } + return nil +} + +func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error { + for _, item := range items { + createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now) + applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt) + if err != nil { + return err + } + if !applied { + continue + } + batch.notify(ctx, tx, changeEventType(batch.initialSync, item.IsDeleted), "item", item.ID, item.ListID, updatedAt) + if item.IsDeleted { + if err := cascadeDeleteItem(ctx, tx, item.ID); err != nil { + return err + } + } + } + return nil +} + +// applyValues upserts the pushed item values and returns the ones it could not +// place. Items are read after applyItems has run, so a request's own item inserts +// are visible. +func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncBatch) ([]OrphanValue, error) { + orphans := make([]OrphanValue, 0) + // Resolve the fields and items the values refer to once per request, not once + // per value. + fieldLists, existingItems, err := valueReferences(ctx, tx, values) + if err != nil { + return nil, err + } + + for _, value := range values { + updatedAt := normalizeTimestamp(int64(value.UpdatedAt), batch.now, batch.now) + listID, ok := fieldLists[value.FieldID] + if !ok { + orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"}) + continue + } + + if !existingItems[value.ItemID] { + if _, err := tx.Exec(ctx, ` + INSERT INTO items (id, listid, createdat, updatedat, isdeleted) + VALUES ($1, $2, $3, $3, 0) + ON CONFLICT (id) DO NOTHING + `, value.ItemID, listID, updatedAt); err != nil { + orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"}) + continue + } + existingItems[value.ItemID] = true + } + applied, err := upsertValue(ctx, tx, value, updatedAt) + if err != nil { + return nil, err + } + if !applied { + continue + } + batch.notify(ctx, tx, "listContentUpdated", "value", value.ID, listID, updatedAt) + } + return orphans, nil +} + +// applySyncRequest writes everything a device pushed, parents before children. +func applySyncRequest(ctx context.Context, tx pgx.Tx, request SyncRequest, batch syncBatch) ([]OrphanValue, error) { + if err := applyLists(ctx, tx, request.Lists, batch); err != nil { + return nil, err + } + if err := applyFields(ctx, tx, request.Fields, batch); err != nil { + return nil, err + } + if err := applyItems(ctx, tx, request.Items, batch); err != nil { + return nil, err + } + return applyValues(ctx, tx, request.ItemValues, batch) +} + +// changesSince reads what a device has to pull: everything when since is nil, +// otherwise the rows updated at or after it. The caller adds the orphan list and +// the server timestamp. +func (d *DB) changesSince(ctx context.Context, since *int64) (SyncResponse, error) { + lists, err := d.queryLists(ctx, true, since) + if err != nil { + return SyncResponse{}, err + } + fields, err := d.queryFields(ctx, true, since, "") + if err != nil { + return SyncResponse{}, err + } + items, err := d.queryItems(ctx, true, since, "") + if err != nil { + return SyncResponse{}, err + } + values, err := d.queryValues(ctx, since, "") + if err != nil { + return SyncResponse{}, err + } + return SyncResponse{Lists: lists, Fields: fields, Items: items, ItemValues: values}, nil +} + func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) { + // Bound the number of syncs in flight, so large bodies and transactions cannot + // take every database connection at once. + select { + case s.syncSlots <- struct{}{}: + defer func() { <-s.syncSlots }() + case <-r.Context().Done(): + writeJSONError(w, http.StatusServiceUnavailable, "Sync busy") + return + } + var request SyncRequest - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid sync request") + if err := decodeJSONLimit(w, r, &request, syncBodyLimit); err != nil { + writeDecodeError(w, err, "Invalid sync request") return } now := time.Now().UnixMilli() lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now) - deviceID := requestDeviceID(r, request.DeviceID) + batch := syncBatch{now: now, initialSync: lastSync == 0, deviceID: requestDeviceID(r, request.DeviceID)} orphans := make([]OrphanValue, 0) incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues) if incoming > 0 { @@ -108,154 +289,9 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) { } err := s.db.withTx(r.Context(), func(tx pgx.Tx) error { - for _, list := range request.Lists { - createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), now) - if _, err := tx.Exec(r.Context(), ` - INSERT INTO lists (id, name, createdat, updatedat, isdeleted) - VALUES ($1, $2, $3, $4, $5) - ON CONFLICT (id) DO UPDATE - SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted - `, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted)); err != nil { - return err - } - event := "updated" - if lastSync == 0 { - event = "created" - } - if list.IsDeleted { - event = "deleted" - } - ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "list", list.ID, list.ID, updatedAt)) - - if list.IsDeleted { - if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil { - return err - } - if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil { - return err - } - if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, list.ID); err != nil { - return err - } - } - } - - for _, field := range request.Fields { - createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), now) - fieldType := field.FieldType - if fieldType == "" { - fieldType = "TEXT" - } - alignment := field.Alignment - if alignment == "" { - alignment = "start" - } - if _, err := tx.Exec(r.Context(), ` - INSERT INTO fields - (id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) - ON CONFLICT (id) DO UPDATE - SET name = EXCLUDED.name, - fieldtype = EXCLUDED.fieldtype, - fieldoptions = EXCLUDED.fieldoptions, - alignment = EXCLUDED.alignment, - "order" = EXCLUDED."order", - updatedat = EXCLUDED.updatedat, - isdeleted = EXCLUDED.isdeleted - `, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted)); err != nil { - return err - } - event := "updated" - if lastSync == 0 { - event = "created" - } - if field.IsDeleted { - event = "deleted" - } - ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "field", field.ID, field.ListID, updatedAt)) - - if field.IsDeleted { - if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, field.ID); err != nil { - return err - } - var remaining int - if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil { - return err - } - if remaining == 0 { - if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil { - return err - } - if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil { - return err - } - } - } - } - - for _, item := range request.Items { - createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), now) - if _, err := tx.Exec(r.Context(), ` - INSERT INTO items (id, listid, createdat, updatedat, isdeleted) - VALUES ($1, $2, $3, $4, $5) - ON CONFLICT (id) DO UPDATE - SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted - `, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted)); err != nil { - return err - } - event := "updated" - if lastSync == 0 { - event = "created" - } - if item.IsDeleted { - event = "deleted" - } - ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "item", item.ID, item.ListID, updatedAt)) - if item.IsDeleted { - if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, item.ID); err != nil { - return err - } - } - } - - // Resolve the fields and items the values refer to once per request, not once - // per value. Items are read after the item loop above, so this request's own - // item inserts are visible. - fieldLists, existingItems, err := valueReferences(r.Context(), tx, request.ItemValues) - if err != nil { - return err - } - - for _, value := range request.ItemValues { - updatedAt := normalizeTimestamp(int64(value.UpdatedAt), now, now) - listID, ok := fieldLists[value.FieldID] - if !ok { - orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"}) - continue - } - - if !existingItems[value.ItemID] { - if _, err := tx.Exec(r.Context(), ` - INSERT INTO items (id, listid, createdat, updatedat, isdeleted) - VALUES ($1, $2, $3, $3, 0) - ON CONFLICT (id) DO NOTHING - `, value.ItemID, listID, updatedAt); err != nil { - orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"}) - continue - } - existingItems[value.ItemID] = true - } - if _, err := tx.Exec(r.Context(), ` - INSERT INTO item_values (id, itemid, fieldid, value, updatedat) - VALUES ($1, $2, $3, $4, $5) - ON CONFLICT (id) DO UPDATE - SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat - `, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt); err != nil { - return err - } - ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, "listContentUpdated", "value", value.ID, listID, updatedAt)) - } - return nil + var err error + orphans, err = applySyncRequest(r.Context(), tx, request, batch) + return err }) if err != nil { fmt.Printf("[SYNC] Failed: %v\n", err) @@ -267,33 +303,12 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) { if lastSync != 0 { since = &lastSync } - lists, err := s.db.queryLists(r.Context(), true, since) + response, err := s.db.changesSince(r.Context(), since) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Sync failed") return } - fields, err := s.db.queryFields(r.Context(), true, since, "") - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Sync failed") - return - } - items, err := s.db.queryItems(r.Context(), true, since, "") - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Sync failed") - return - } - values, err := s.db.queryValues(r.Context(), since, "") - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Sync failed") - return - } - - writeJSON(w, http.StatusOK, SyncResponse{ - Lists: lists, - Fields: fields, - Items: items, - ItemValues: values, - OrphanItemValues: orphans, - ServerTimestamp: time.Now().UnixMilli(), - }) + response.OrphanItemValues = orphans + response.ServerTimestamp = time.Now().UnixMilli() + writeJSON(w, http.StatusOK, response) } diff --git a/backend/sync_test.go b/backend/sync_test.go index 2a650e3..16f7b97 100644 --- a/backend/sync_test.go +++ b/backend/sync_test.go @@ -25,3 +25,24 @@ func TestNormalizeEntityTimestampsKeepsUpdatedAfterCreated(t *testing.T) { t.Fatalf("timestamps = (%d, %d), want (%d, %d)", created, updated, now-100, now-100) } } + +func TestChangeEventTypeNamesEachChange(t *testing.T) { + cases := []struct { + name string + initialSync bool + deleted bool + want string + }{ + {name: "first sync creates", initialSync: true, want: "created"}, + {name: "later edit updates", initialSync: false, want: "updated"}, + {name: "tombstone is deleted on first sync", initialSync: true, deleted: true, want: "deleted"}, + {name: "tombstone is deleted later", initialSync: false, deleted: true, want: "deleted"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := changeEventType(tc.initialSync, tc.deleted); got != tc.want { + t.Fatalf("changeEventType(%v, %v) = %q, want %q", tc.initialSync, tc.deleted, got, tc.want) + } + }) + } +} diff --git a/frontend/package.json b/frontend/package.json index 655b4ff..99f4685 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -7,6 +7,7 @@ "dev": "vite dev", "build": "vite build", "preview": "vite preview", + "test": "node --test", "check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json", "lint": "eslint .", "format": "prettier --write .", diff --git a/frontend/src/lib/components/lists/ListsGrid.svelte b/frontend/src/lib/components/lists/ListsGrid.svelte index 34b6bd9..3b0bca0 100644 --- a/frontend/src/lib/components/lists/ListsGrid.svelte +++ b/frontend/src/lib/components/lists/ListsGrid.svelte @@ -1,7 +1,7 @@ {#if lists.length === 0} @@ -12,7 +12,12 @@ {:else}
{#each lists as list (list.id)} - + {/each}
{/if} diff --git a/frontend/src/lib/components/lists/ListsTable.svelte b/frontend/src/lib/components/lists/ListsTable.svelte index 9d1c440..d3b6292 100644 --- a/frontend/src/lib/components/lists/ListsTable.svelte +++ b/frontend/src/lib/components/lists/ListsTable.svelte @@ -1,7 +1,7 @@ @@ -15,7 +15,12 @@ {#each lists as list (list.id)} - + {/each}
diff --git a/frontend/src/lib/features/lists/listHelpers.js b/frontend/src/lib/features/lists/listHelpers.js index 4f45e15..57f3850 100644 --- a/frontend/src/lib/features/lists/listHelpers.js +++ b/frontend/src/lib/features/lists/listHelpers.js @@ -6,8 +6,20 @@ export function listItemsFor(items, listId) { return items.filter((i) => i.listId === listId && !i.isDeleted); } -export function itemValuesFor(values, itemId) { - return values.filter((v) => v.itemId === itemId); +// groupByKey indexes rows by keyOf in one pass. Build it once per data change in a +// $derived, then look rows up per card, row or cell instead of rescanning the data. +export function groupByKey(rows, keyOf) { + const groups = new Map(); + for (const row of rows) { + const key = keyOf(row); + const group = groups.get(key); + if (group) { + group.push(row); + } else { + groups.set(key, [row]); + } + } + return groups; } export function valueFor(values, itemId, fieldId) { diff --git a/frontend/src/lib/features/lists/listHelpers.test.js b/frontend/src/lib/features/lists/listHelpers.test.js new file mode 100644 index 0000000..d1dfa3d --- /dev/null +++ b/frontend/src/lib/features/lists/listHelpers.test.js @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { fmtDate, groupByKey, listFieldsFor, listItemsFor, valueFor } from './listHelpers.js'; + +test('listFieldsFor keeps the list’s live fields in display order', () => { + const fields = [ + { id: 'c', listId: 'l1', order: 2 }, + { id: 'gone', listId: 'l1', order: 0, isDeleted: true }, + { id: 'other', listId: 'l2', order: 0 }, + { id: 'a', listId: 'l1', order: 0 }, + { id: 'unordered', listId: 'l1' }, + { id: 'b', listId: 'l1', order: 1 }, + ]; + + const ids = listFieldsFor(fields, 'l1').map((f) => f.id); + + // A field without an order sorts as 0, and the sort is stable. + assert.deepEqual(ids, ['a', 'unordered', 'b', 'c']); +}); + +test('listFieldsFor does not reorder the array it was given', () => { + const fields = [ + { id: 'b', listId: 'l1', order: 1 }, + { id: 'a', listId: 'l1', order: 0 }, + ]; + listFieldsFor(fields, 'l1'); + assert.deepEqual( + fields.map((f) => f.id), + ['b', 'a'], + ); +}); + +test('listItemsFor keeps only the list’s live items', () => { + const items = [ + { id: 'i1', listId: 'l1' }, + { id: 'i2', listId: 'l1', isDeleted: true }, + { id: 'i3', listId: 'l2' }, + ]; + assert.deepEqual( + listItemsFor(items, 'l1').map((i) => i.id), + ['i1'], + ); + assert.deepEqual(listItemsFor(items, 'missing'), []); +}); + +test('groupByKey indexes rows by key and keeps their order', () => { + const rows = [ + { id: 1, listId: 'a' }, + { id: 2, listId: 'b' }, + { id: 3, listId: 'a' }, + ]; + + const groups = groupByKey(rows, (row) => row.listId); + + assert.deepEqual([...groups.keys()], ['a', 'b']); + assert.deepEqual( + groups.get('a').map((row) => row.id), + [1, 3], + ); + assert.equal(groups.get('missing'), undefined); + assert.equal(groupByKey([], (row) => row.listId).size, 0); +}); + +test('valueFor finds the value in one cell, or null', () => { + const values = [ + { itemId: 'i1', fieldId: 'f1', value: 'milk' }, + { itemId: 'i1', fieldId: 'f2', value: '' }, + { itemId: 'i2', fieldId: 'f1', value: 'eggs' }, + ]; + + assert.equal(valueFor(values, 'i1', 'f1'), 'milk'); + assert.equal(valueFor(values, 'i2', 'f1'), 'eggs'); + // An empty value is a value, not a missing one. + assert.equal(valueFor(values, 'i1', 'f2'), ''); + assert.equal(valueFor(values, 'i2', 'f2'), null); +}); + +test('fmtDate shows a dash for missing or invalid dates', () => { + assert.equal(fmtDate(null), '—'); + assert.equal(fmtDate(undefined), '—'); + assert.equal(fmtDate('not a date'), '—'); +}); + +test('fmtDate formats a millisecond timestamp for the reader’s locale', () => { + const ms = 1_700_000_000_000; + assert.equal(fmtDate(ms), new Date(ms).toLocaleString()); + assert.notEqual(fmtDate(ms), '—'); +}); diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelte index cc4e8de..07c2f57 100644 --- a/frontend/src/routes/+page.svelte +++ b/frontend/src/routes/+page.svelte @@ -3,6 +3,7 @@ import { resolve } from '$app/paths'; import { ArrowDown, ArrowUp, LayoutGrid, List, Search, X } from '@lucide/svelte'; import { createOverviewData } from '$lib/features/lists/listsData.svelte.js'; + import { groupByKey } from '$lib/features/lists/listHelpers.js'; import { searchState, filterListsBySearch } from '$lib/search.svelte.js'; import { createDashboardViewMode } from '$lib/preferences/viewMode.svelte.js'; import Button from '$lib/components/ui/button.svelte'; @@ -42,6 +43,10 @@ let searched = $derived(filterListsBySearch(overview.lists, searchState.query)); let sorted = $derived(sortLists(searched, sortField, sortDir)); let pageItems = $derived(sorted.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize)); + // Index fields and items by list once per data change, so each visible card or row + // reads its own slice instead of scanning every field and item. + let fieldsByList = $derived(groupByKey(overview.fields, (f) => f.listId)); + let itemsByList = $derived(groupByKey(overview.items, (i) => i.listId)); $effect(() => { void searchState.query; @@ -148,9 +153,9 @@
{#if viewMode.mode === 'list'} - + {:else} - + {/if}
diff --git a/frontend/src/routes/lists/[id]/+page.svelte b/frontend/src/routes/lists/[id]/+page.svelte index 0aaea26..4f2ece6 100644 --- a/frontend/src/routes/lists/[id]/+page.svelte +++ b/frontend/src/routes/lists/[id]/+page.svelte @@ -5,7 +5,7 @@ import Button from '$lib/components/ui/button.svelte'; import { Pagination } from '@gabriel20xx/web-ui'; import { createOverviewData } from '$lib/features/lists/listsData.svelte.js'; - import { listFieldsFor, listItemsFor, itemValuesFor, valueFor, fmtDate } from '$lib/features/lists/listHelpers.js'; + import { listFieldsFor, listItemsFor, groupByKey, valueFor, fmtDate } from '$lib/features/lists/listHelpers.js'; let { data } = $props(); @@ -22,6 +22,7 @@ const list = $derived(overview.lists.find((l) => l.id === data.id)); const listFields = $derived(listFieldsFor(overview.fields, data.id)); const listItems = $derived(listItemsFor(overview.items, data.id)); + const valuesByItem = $derived(groupByKey(overview.values, (v) => v.itemId)); let page = $state(1); let pageSize = $state(24); @@ -91,7 +92,7 @@ {#each pageItems as item (item.id)} - {@const itemValues = itemValuesFor(overview.values, item.id)} + {@const itemValues = valuesByItem.get(item.id) ?? []} {item.id.slice(0, 8)}… {#each listFields as f (f.id)} diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 2b4722b..79a96f3 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -38,6 +38,7 @@ export default defineConfig({ proxy: { '/web': 'http://localhost:8080', '/health': 'http://localhost:8080', + '/api': 'http://localhost:8080', }, }, });