feat(sync): paginate Android sync with change tokens
This commit is contained in:
1 parent
0ff94f9b10
commit
97c237be80
76 files changed
+3258
-708
No files matched your search
@@ -12,6 +12,7 @@ import retrofit2.http.Query
|
|||||||
|
|
||||||
data class SyncRequest(
|
data class SyncRequest(
|
||||||
val lastSyncTimestamp: Long,
|
val lastSyncTimestamp: Long,
|
||||||
|
val lastSyncToken: Long,
|
||||||
val lists: List<CollabList>,
|
val lists: List<CollabList>,
|
||||||
val fields: List<Field>,
|
val fields: List<Field>,
|
||||||
val items: List<Item>,
|
val items: List<Item>,
|
||||||
@@ -24,6 +25,9 @@ data class SyncResponse(
|
|||||||
val items: List<Item>,
|
val items: List<Item>,
|
||||||
val itemValues: List<ItemValue>,
|
val itemValues: List<ItemValue>,
|
||||||
val serverTimestamp: Long,
|
val serverTimestamp: Long,
|
||||||
|
val serverChangeToken: Long,
|
||||||
|
val nextSyncToken: Long,
|
||||||
|
val hasMore: Boolean,
|
||||||
)
|
)
|
||||||
|
|
||||||
interface CollabTableApi {
|
interface CollabTableApi {
|
||||||
|
|||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package com.collabtable.app.data.repository
|
||||||
|
|
||||||
|
import com.collabtable.app.data.api.SyncResponse
|
||||||
|
|
||||||
|
internal data class SyncPageProgress(
|
||||||
|
val cursor: Long,
|
||||||
|
val firstPage: Boolean = true,
|
||||||
|
) {
|
||||||
|
fun after(response: SyncResponse): SyncPageProgress? {
|
||||||
|
if (response.hasMore && response.nextSyncToken <= cursor) {
|
||||||
|
throw IllegalStateException("Sync page cursor did not advance")
|
||||||
|
}
|
||||||
|
return if (response.hasMore) SyncPageProgress(response.nextSyncToken, firstPage = false) else null
|
||||||
|
}
|
||||||
|
}
|
||||||
+55
-37
@@ -52,6 +52,12 @@ class SyncRepository(
|
|||||||
return prefs.getLong("last_server_sync_ts", 0)
|
return prefs.getLong("last_server_sync_ts", 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun getLastServerSyncToken(): Long = prefs.getLong("last_server_sync_token", 0)
|
||||||
|
|
||||||
|
private fun setLastServerSyncToken(token: Long) {
|
||||||
|
prefs.edit().putLong("last_server_sync_token", token).apply()
|
||||||
|
}
|
||||||
|
|
||||||
private fun setLastServerSyncTs(ts: Long) {
|
private fun setLastServerSyncTs(ts: Long) {
|
||||||
prefs
|
prefs
|
||||||
.edit()
|
.edit()
|
||||||
@@ -101,30 +107,29 @@ class SyncRepository(
|
|||||||
return@withContext Result.success(Unit)
|
return@withContext Result.success(Unit)
|
||||||
}
|
}
|
||||||
val lastServerTs = getLastServerSyncTs()
|
val lastServerTs = getLastServerSyncTs()
|
||||||
|
val lastServerToken = getLastServerSyncToken()
|
||||||
val lastLocalTs = getLastLocalSyncTs()
|
val lastLocalTs = getLastLocalSyncTs()
|
||||||
// Capture a snapshot timestamp BEFORE reading local changes to avoid missing
|
// Capture a snapshot timestamp BEFORE reading local changes to avoid missing
|
||||||
// updates that happen during an in-flight sync. We'll advance the local watermark
|
// updates that happen during an in-flight sync. We'll advance the local watermark
|
||||||
// to this snapshot once the sync completes successfully.
|
// to this snapshot once the sync completes successfully.
|
||||||
val localSnapshotTs = System.currentTimeMillis()
|
val localSnapshotTs = System.currentTimeMillis()
|
||||||
val isInitialSync = lastServerTs == 0L
|
// If our local DB appears empty or this install still has the legacy timestamp cursor,
|
||||||
|
// request a full down-sync through the server change-token cursor.
|
||||||
|
val hasAnyLists = database.listDao().getAllListIds().isNotEmpty()
|
||||||
|
val hasAnyItems = database.itemDao().getAllItemIds().isNotEmpty()
|
||||||
|
val effectiveLastServerToken =
|
||||||
|
when {
|
||||||
|
// App start can request a full down-sync regardless of local contents
|
||||||
|
forceFullDown && (lastServerTs > 0L || lastServerToken > 0L) -> 0L
|
||||||
|
// Fallback: if local has no lists or items but we have a watermark, do a full down-sync
|
||||||
|
(lastServerTs > 0L || lastServerToken > 0L) && (!hasAnyLists && !hasAnyItems) -> 0L
|
||||||
|
else -> lastServerToken
|
||||||
|
}
|
||||||
|
val isInitialSync = effectiveLastServerToken == 0L
|
||||||
if (isInitialSync) {
|
if (isInitialSync) {
|
||||||
Logger.i("Sync", "[SYNC] Starting initial sync with server")
|
Logger.i("Sync", "[SYNC] Starting initial sync with server")
|
||||||
}
|
}
|
||||||
|
if (effectiveLastServerToken == 0L && (lastServerTs > 0L || lastServerToken > 0L)) {
|
||||||
// If our local DB appears empty but we have a nonzero server watermark (e.g., after reinstall
|
|
||||||
// or clearing local data), request a one-time full down-sync by resetting the effective
|
|
||||||
// lastSyncTimestamp to 0 for this request. This avoids permanently missing historical rows.
|
|
||||||
val hasAnyLists = database.listDao().getAllListIds().isNotEmpty()
|
|
||||||
val hasAnyItems = database.itemDao().getAllItemIds().isNotEmpty()
|
|
||||||
val effectiveLastServerTs =
|
|
||||||
when {
|
|
||||||
// App start can request a full down-sync regardless of local contents
|
|
||||||
forceFullDown && lastServerTs > 0L -> 0L
|
|
||||||
// Fallback: if local looks empty but we have a watermark, do a one-time full down-sync
|
|
||||||
lastServerTs > 0L && (!hasAnyLists || !hasAnyItems) -> 0L
|
|
||||||
else -> lastServerTs
|
|
||||||
}
|
|
||||||
if (effectiveLastServerTs == 0L && lastServerTs > 0L) {
|
|
||||||
val reason = if (forceFullDown) "startup forced" else "local empty"
|
val reason = if (forceFullDown) "startup forced" else "local empty"
|
||||||
Logger.w("Sync", "$reason full down-sync requested")
|
Logger.w("Sync", "$reason full down-sync requested")
|
||||||
}
|
}
|
||||||
@@ -162,22 +167,25 @@ class SyncRepository(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send to server and get updates
|
// Upload local changes once, then follow the server's bounded pages without
|
||||||
val syncRequest =
|
// replaying the same writes on every request.
|
||||||
SyncRequest(
|
var cursor = effectiveLastServerToken
|
||||||
lastSyncTimestamp = effectiveLastServerTs,
|
var pageProgress = SyncPageProgress(cursor)
|
||||||
lists = localLists,
|
var serverTimestamp = lastServerTs
|
||||||
fields = localFields,
|
while (true) {
|
||||||
items = localItems,
|
|
||||||
itemValues = localValues,
|
|
||||||
)
|
|
||||||
|
|
||||||
// HTTP-only sync
|
|
||||||
val response =
|
val response =
|
||||||
try {
|
try {
|
||||||
api.sync(syncRequest)
|
api.sync(
|
||||||
|
SyncRequest(
|
||||||
|
lastSyncTimestamp = lastServerTs,
|
||||||
|
lastSyncToken = pageProgress.cursor,
|
||||||
|
lists = if (pageProgress.firstPage) localLists else emptyList(),
|
||||||
|
fields = if (pageProgress.firstPage) localFields else emptyList(),
|
||||||
|
items = if (pageProgress.firstPage) localItems else emptyList(),
|
||||||
|
itemValues = if (pageProgress.firstPage) localValues else emptyList(),
|
||||||
|
),
|
||||||
|
)
|
||||||
} catch (e: UnknownHostException) {
|
} catch (e: UnknownHostException) {
|
||||||
// Host could not be resolved; apply exponential backoff and surface a warning once.
|
|
||||||
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
||||||
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
||||||
Logger.w("Sync", "Network host unresolved (DNS). Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
Logger.w("Sync", "Network host unresolved (DNS). Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
||||||
@@ -193,18 +201,16 @@ class SyncRepository(
|
|||||||
}
|
}
|
||||||
if (!response.isSuccessful) {
|
if (!response.isSuccessful) {
|
||||||
if (response.code() == 401) {
|
if (response.code() == 401) {
|
||||||
// Unauthorized: likely bad/missing API token. Reset sync baseline and surface a clear error.
|
|
||||||
setLastServerSyncTs(0)
|
setLastServerSyncTs(0)
|
||||||
|
setLastServerSyncToken(0)
|
||||||
setLastLocalSyncTs(0)
|
setLastLocalSyncTs(0)
|
||||||
// Apply exponential backoff on repeated auth failures
|
|
||||||
authBackoffMs = if (authBackoffMs == 0L) 2_000L else (authBackoffMs * 2).coerceAtMost(300_000L)
|
authBackoffMs = if (authBackoffMs == 0L) 2_000L else (authBackoffMs * 2).coerceAtMost(300_000L)
|
||||||
authBackoffUntil = System.currentTimeMillis() + authBackoffMs
|
authBackoffUntil = System.currentTimeMillis() + authBackoffMs
|
||||||
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server API token."))
|
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server API token."))
|
||||||
}
|
}
|
||||||
return@withContext Result.failure(Exception("Sync failed: ${response.code()}"))
|
return@withContext Result.failure(Exception("Sync failed: ${response.code()}"))
|
||||||
}
|
}
|
||||||
val syncResponse = response.body()!!
|
val syncResponse = response.body() ?: return@withContext Result.failure(Exception("Sync response was empty"))
|
||||||
// Only log receive when there are actual server changes
|
|
||||||
val inTotal =
|
val inTotal =
|
||||||
syncResponse.lists.size +
|
syncResponse.lists.size +
|
||||||
syncResponse.fields.size +
|
syncResponse.fields.size +
|
||||||
@@ -219,12 +225,12 @@ class SyncRepository(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apply server changes to local database atomically in correct order
|
|
||||||
database.withTransaction {
|
database.withTransaction {
|
||||||
// 1) Upsert lists first, preserving local orderIndex when present
|
// 1) Upsert lists first, preserving local orderIndex when present
|
||||||
val localIdToOrder = database.listDao().getListIdsAndOrder().associate { it.id to it.orderIndex }
|
val localIdToOrder = database.listDao().getListIdsAndOrder().associate { it.id to it.orderIndex }
|
||||||
// Build a map of local updatedAt to avoid overwriting newer local changes with older server data
|
// Build a map of local updatedAt to avoid overwriting newer local changes with older server data
|
||||||
val localUpdatedMap = database.listDao().getListsUpdatedSince(0).associateBy({ it.id }, { it.updatedAt })
|
val localUpdatedMap =
|
||||||
|
database.listDao().getListsUpdatedSince(0).associateBy({ it.id }, { it.updatedAt })
|
||||||
|
|
||||||
val listsPreservingOrder =
|
val listsPreservingOrder =
|
||||||
syncResponse.lists
|
syncResponse.lists
|
||||||
@@ -278,9 +284,20 @@ class SyncRepository(
|
|||||||
database.itemValueDao().insertValues(filteredValues)
|
database.itemValueDao().insertValues(filteredValues)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val nextPage = try {
|
||||||
|
pageProgress.after(syncResponse)
|
||||||
|
} catch (e: IllegalStateException) {
|
||||||
|
return@withContext Result.failure(e)
|
||||||
|
}
|
||||||
|
cursor = syncResponse.nextSyncToken
|
||||||
|
serverTimestamp = syncResponse.serverTimestamp
|
||||||
|
if (nextPage == null) break
|
||||||
|
pageProgress = nextPage
|
||||||
|
}
|
||||||
|
|
||||||
// Update watermarks: server ts from response, local ts from device clock now
|
// Save the server-owned change cursor only after every page has been applied.
|
||||||
setLastServerSyncTs(syncResponse.serverTimestamp)
|
setLastServerSyncToken(cursor)
|
||||||
|
setLastServerSyncTs(serverTimestamp)
|
||||||
// Advance local watermark to the snapshot taken before reading local changes.
|
// Advance local watermark to the snapshot taken before reading local changes.
|
||||||
// This avoids missing updates that occurred while the sync was in-flight.
|
// This avoids missing updates that occurred while the sync was in-flight.
|
||||||
setLastLocalSyncTs(localSnapshotTs)
|
setLastLocalSyncTs(localSnapshotTs)
|
||||||
@@ -298,6 +315,7 @@ class SyncRepository(
|
|||||||
// If WS indicated unauthorized, align behavior with HTTP path
|
// If WS indicated unauthorized, align behavior with HTTP path
|
||||||
if (e.message?.contains("Unauthorized") == true) {
|
if (e.message?.contains("Unauthorized") == true) {
|
||||||
setLastServerSyncTs(0)
|
setLastServerSyncTs(0)
|
||||||
|
setLastServerSyncToken(0)
|
||||||
setLastLocalSyncTs(0)
|
setLastLocalSyncTs(0)
|
||||||
}
|
}
|
||||||
// Do not reset network backoff here; it's managed where thrown.
|
// Do not reset network backoff here; it's managed where thrown.
|
||||||
|
|||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
package com.collabtable.app.data.repository
|
||||||
|
|
||||||
|
import com.collabtable.app.data.api.SyncResponse
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SyncPageProgressTest {
|
||||||
|
@Test
|
||||||
|
fun `first page advances and marks later pages as download only`() {
|
||||||
|
val first = SyncPageProgress(cursor = 4)
|
||||||
|
|
||||||
|
assertTrue(first.firstPage)
|
||||||
|
val second = first.after(response(nextToken = 9, hasMore = true))
|
||||||
|
|
||||||
|
assertEquals(9, second?.cursor)
|
||||||
|
assertFalse(second?.firstPage ?: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `final page ends the loop`() {
|
||||||
|
val progress = SyncPageProgress(cursor = 9, firstPage = false)
|
||||||
|
|
||||||
|
assertNull(progress.after(response(nextToken = 12, hasMore = false)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `non advancing page is rejected`() {
|
||||||
|
val progress = SyncPageProgress(cursor = 9)
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException::class.java) {
|
||||||
|
progress.after(response(nextToken = 9, hasMore = true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun response(nextToken: Long, hasMore: Boolean) =
|
||||||
|
SyncResponse(
|
||||||
|
lists = emptyList(),
|
||||||
|
fields = emptyList(),
|
||||||
|
items = emptyList(),
|
||||||
|
itemValues = emptyList(),
|
||||||
|
serverTimestamp = 0,
|
||||||
|
serverChangeToken = nextToken,
|
||||||
|
nextSyncToken = nextToken,
|
||||||
|
hasMore = hasMore,
|
||||||
|
)
|
||||||
|
}
|
||||||
+11
-11
@@ -4,10 +4,10 @@
|
|||||||
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
||||||
- **Analyzed:** 2026-10-16
|
- **Analyzed:** 2026-10-16
|
||||||
- **Commit:** 6aec03f on main
|
- **Commit:** 6aec03f on main
|
||||||
- **Working tree:** clean (no uncommitted changes, no untracked files)
|
- **Working tree:** contains uncommitted changes from the earlier and current medium passes.
|
||||||
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, TanStack Query) embedded in the Go binary; Android client (Kotlin, Room, Retrofit) with offline sync; Docker multi-stage image on `scratch`; GitHub Actions.
|
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, TanStack Query) embedded in the Go binary; Android client (Kotlin, Room, Retrofit) with offline sync; Docker multi-stage image on `scratch`; GitHub Actions.
|
||||||
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). A second Medium pass re-checked P-004, which stays open for a pagination contract decision.
|
- **Updated:** 2026-10-20 — P-004 now uses bounded keyset pages for collection endpoints and sync; Android follows all sync pages. Database-backed behavior remains unverified locally because no test database is available.
|
||||||
- **Scope:** Read all first-party backend code (`backend/*.go`, including tests), `docker/Dockerfile`, `.dockerignore`, `.github/workflows/*`, the frontend data layer, list components, routes and Vite config, the Android API client, preferences and sync repository, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, lock files (read for versions only), build output, and the rest of `shared/` (node, python and java packages, which CollabTable does not use). Tracked SQLite files were inspected read-only from a copy (schema and row counts only). No tests, builds or linters were run; the analysis is static.
|
- **Scope:** Read all first-party backend code (`backend/*.go`, including tests), `docker/Dockerfile`, `.dockerignore`, `.github/workflows/*`, the frontend data layer, list components, routes and Vite config, the Android API client, preferences and sync repository, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, lock files (read for versions only), build output, and the rest of `shared/` (node, python and java packages, which CollabTable does not use). Tracked SQLite files were inspected read-only from a copy (schema and row counts only). Verification limits are recorded in `QUALITY_REPORT.md`.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -15,11 +15,11 @@
|
|||||||
|---|---:|---:|---:|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 0 | 0 | 0 | 0 |
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
| High | 2 | 1 | 0 | 1 |
|
| High | 2 | 1 | 0 | 1 |
|
||||||
| Medium | 5 | 4 | 0 | 1 |
|
| Medium | 5 | 5 | 0 | 0 |
|
||||||
| Low | 3 | 0 | 0 | 3 |
|
| Low | 3 | 0 | 0 | 3 |
|
||||||
| Info | 1 | 0 | 0 | 1 |
|
| Info | 1 | 0 | 0 | 1 |
|
||||||
|
|
||||||
Two structural costs dominate: the dashboard re-downloads the full database every 5 seconds, and sync writes row by row with several round trips per value inside one long transaction. Missing indexes and pagination will make both worse as data grows.
|
The dashboard still sends the full dataset after a change, and sync writes rows one at a time inside one transaction. Collection endpoints and sync are now paged, while the updated-at indexes are present. Database runtime and load behavior still need verification on PostgreSQL.
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
@@ -44,12 +44,12 @@ Two structural costs dominate: the dashboard re-downloads the full database ever
|
|||||||
- **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.
|
- **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.
|
- **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** · Open
|
### P-004 · No pagination on list endpoints or the sync response; the first sync returns everything · **Medium** · Fixed
|
||||||
- **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).
|
- **Location:** `backend/pagination.go` (bounded keyset pages); `backend/data.go` collection handlers; `backend/sync.go:326-405` (bounded sync response); `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt` (client page loop).
|
||||||
- **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.
|
- **Description:** Collection endpoints now return pages of at most 500 rows (default 200), with opaque keyset cursors and `hasMore`. Sync returns at most 500 changes with a server token cursor; Android requests all pages before saving the cursor.
|
||||||
- **Impact:** Response size and server memory grow linearly with total data. Large first syncs risk the 60-second write timeout and slow mobile clients.
|
- **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.
|
- **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.
|
- **Status:** Fixed 2026-10-20 — Collection queries use keyset cursors with a default page of 200 and maximum of 500; sync responses are capped at 500 and include `hasMore` and `nextSyncToken`. Android uploads local changes on the first request, then loops through server pages and stores the final cursor only after completion. Collection GET responses now wrap `items`, `nextCursor` and `hasMore` instead of returning bare arrays. Old sync clients that omit `lastSyncToken` receive 400 and must be upgraded with the backend. PostgreSQL runtime tests are written but skipped locally; see `QUALITY_REPORT.md` Verification. Files: `backend/pagination.go`, `backend/data.go`, `backend/sync.go`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt`.
|
||||||
|
|
||||||
### P-005 · Frontend scans full arrays for every row, card and cell on each poll · **Medium** · Fixed
|
### 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).
|
- **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).
|
||||||
@@ -97,8 +97,8 @@ Two structural costs dominate: the dashboard re-downloads the full database ever
|
|||||||
- **Recommendation:** None.
|
- **Recommendation:** None.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- Static analysis only. No tests, builds, Docker builds, lint runs or load tests were executed. Estimates come from code reading and should be confirmed with a benchmark on realistic data (for example a few thousand items across several devices).
|
- Go and frontend verification results are in `QUALITY_REPORT.md`. No load test ran. Estimates should be confirmed with realistic data across several devices.
|
||||||
- AuthGuard's own performance is outside this repository and was not analyzed.
|
- AuthGuard's own performance is outside this repository and was not analyzed.
|
||||||
- `shared/` was reviewed selectively: the parts CollabTable imports (`backend/auth`, `authclient`, `authproxy`, `coreconfig`, `postgres`, and the `carriernodeclient` construction). The shared web-ui was searched with grep only. The node, python and java packages were not reviewed.
|
- `shared/` was reviewed selectively: the parts CollabTable imports (`backend/auth`, `authclient`, `authproxy`, `coreconfig`, `postgres`, and the `carriernodeclient` construction). The shared web-ui was searched with grep only. The node, python and java packages were not reviewed.
|
||||||
- The frontend bundle was not measured. The web-ui is imported through its barrel (`import { Pagination } from '@gabriel20xx/web-ui'`), and whether that tree-shakes needs verification with a production build.
|
- The production frontend build passed after the consumer wired the local design-tokens package and preserved shared-package symlinks; the resulting bundle size was reported by Vite but not benchmarked in a browser.
|
||||||
- No TODO, FIXME or HACK markers were found in `backend/` or `frontend/src/`.
|
- No TODO, FIXME or HACK markers were found in `backend/` or `frontend/src/`.
|
||||||
+24
-10
@@ -4,10 +4,10 @@
|
|||||||
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
||||||
- **Analyzed:** 2026-10-16
|
- **Analyzed:** 2026-10-16
|
||||||
- **Commit:** 6aec03f on main
|
- **Commit:** 6aec03f on main
|
||||||
- **Working tree:** clean (no uncommitted changes, no untracked files)
|
- **Working tree:** contains uncommitted changes from the earlier and current medium passes.
|
||||||
- **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.
|
- **Updated:** 2026-10-20 — Q-006 now uses a server-side change token; Q-004 remains partly open because its Android JVM test and PostgreSQL integration tests could not be run here.
|
||||||
- **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.
|
- **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.
|
- **Scope:** Read all first-party backend code (`backend/*.go`, including the tests), 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. Verification commands and results are below.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
|---|---:|---:|---:|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 0 | 0 | 0 | 0 |
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
| High | 0 | 0 | 0 | 0 |
|
| High | 0 | 0 | 0 | 0 |
|
||||||
| Medium | 6 | 4 | 0 | 2 |
|
| Medium | 6 | 5 | 0 | 1 |
|
||||||
| Low | 8 | 0 | 0 | 8 |
|
| Low | 8 | 0 | 0 | 8 |
|
||||||
| Info | 0 | 0 | 0 | 0 |
|
| Info | 0 | 0 | 0 | 0 |
|
||||||
|
|
||||||
@@ -45,11 +45,11 @@ The backend is small and readable, but its transactional and delete logic is dup
|
|||||||
- **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.
|
- **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** · Open
|
### 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.
|
- **Location:** `backend/db_test.go` and `.github/workflows/tests.yml` (database-backed tests and a PostgreSQL service); `frontend/src/lib/api.test.js` and the `node:test` suite; `CollabTableAndroid/app/src/test/java/com/collabtable/app/data/repository/SyncPageProgressTest.kt` (new JVM test, not yet run here).
|
||||||
- **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.
|
- **Description:** Backend and frontend coverage now exercises core paths, but local database-backed tests need PostgreSQL and the Android sync-page test has not been compiled or run. There is no Android CI job. The new coverage still needs a successful database and JVM execution.
|
||||||
- **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.
|
- **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.
|
- **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.
|
- **Status:** Open 2026-10-20 — Partly fixed: route and middleware tests assert behavior; PostgreSQL-backed tests now cover sync, pagination, change-token backfill, membership isolation, cascades, values, notifications, `/web/data` and tokens; frontend tests cover list helpers and credential proof forwarding; and `SyncPageProgressTest.kt` covers the Android page loop. The PostgreSQL tests skip locally because `TEST_DATABASE_URL` is unset and no local PostgreSQL binaries are available. The workflow defines a PostgreSQL service but was not run here. Java and Gradle are unavailable, so the JVM test remains uncompiled and unrun; no Android CI job runs it.
|
||||||
|
|
||||||
### Q-005 · Setup documentation contradicts the configuration · **Medium** · Fixed
|
### 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`).
|
- **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`).
|
||||||
@@ -58,12 +58,12 @@ The backend is small and readable, but its transactional and delete logic is dup
|
|||||||
- **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.
|
- **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.
|
- **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** · Open
|
### Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · **Medium** · Fixed
|
||||||
- **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`).
|
- **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.
|
- **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.
|
- **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.
|
- **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.
|
- **Status:** Fixed 2026-10-20 — Every list, field, item and value write now receives a monotonic server `change_token`; startup backfills existing rows. Sync reads a repeatable-read snapshot and returns a bounded page with `nextSyncToken`; Android follows all pages and saves the cursor after completion. Client timestamps remain metadata and govern stale-write handling. Existing clients must update because requests without `lastSyncToken` now receive 400. PostgreSQL runtime tests are written but skipped locally; see Verification. Files: `backend/db.go`, `backend/models.go`, `backend/sync.go`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt`.
|
||||||
|
|
||||||
### Q-007 · Validation and error mapping return misleading status codes and contract drift · **Low**
|
### 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`).
|
- **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`).
|
||||||
@@ -113,8 +113,22 @@ The backend is small and readable, but its transactional and delete logic is dup
|
|||||||
- **Impact:** Confusing for contributors, and a risk if real data is ever saved there.
|
- **Impact:** Confusing for contributors, and a risk if real data is ever saved there.
|
||||||
- **Recommendation:** Remove the tracked files, add ignore rules for `*.db` and `build-*.txt`, and keep only the placeholder `backend/web/.gitkeep`.
|
- **Recommendation:** Remove the tracked files, add ignore rules for `*.db` and `build-*.txt`, and keep only the placeholder `backend/web/.gitkeep`.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- Go command (all database URL variables unset):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
unset DATABASE_URL SHARED_TEST_DATABASE_URL TEST_DATABASE_URL && export PATH=/tmp/medium-pass-gosdk/go/bin:$PATH GOCACHE=/tmp/medium-pass-go-cache GOMODCACHE=/tmp/medium-pass-go-mod && go test ./... && go test -v -run 'Test(ParsePageRequest|InitSchemaCanRunAgainstAnExistingDatabase|CollectionEndpointsPageWithStableCursors|SyncUsesServerChangeTokenInsteadOfClientTimestamp|SyncBoundsAndPagesLargeInitialSync|PerListMembershipScopesDataAndSync|MembershipBackfillPreservesCurrentAPITokenUsers)$' && go vet ./... && gofmt -l . && for bin in postgres psql initdb; do command -v "$bin" || true; done
|
||||||
|
```
|
||||||
|
|
||||||
|
`go test ./...` passed. All nine `TestParsePageRequest` cases passed; the six PostgreSQL-backed cases in the focused run skipped because `TEST_DATABASE_URL` is unset. `go vet ./...` passed and `gofmt -l .` printed no files. `postgres`, `psql` and `initdb` were not found.
|
||||||
|
- Frontend commands: `unset DATABASE_URL && npm test` (9 passed); `unset DATABASE_URL && npm run check` (0 errors, 0 warnings); `unset DATABASE_URL && npm run lint` (passed); `unset DATABASE_URL && npm run build` (passed after adding the local design-tokens dependency and enabling `resolve.preserveSymlinks`; the build reports one Svelte warning in shared `layout.svelte.js:44`); `unset DATABASE_URL && npx prettier --check src/lib/api.js src/lib/api.test.js src/lib/features/layout/AppShell.svelte` and `unset DATABASE_URL && npx prettier --check --end-of-line crlf vite.config.js` (both passed).
|
||||||
|
- Build dependency wiring: `unset DATABASE_URL && npm install --save '@gabriel20xx/design-tokens@file:../shared/packages/design-tokens' --offline` added the local package to `frontend/package.json` and the lockfile. The Vite build initially exposed the local shared-package symlink resolution issue; `resolve.preserveSymlinks` fixed it.
|
||||||
|
- `unset DATABASE_URL && npm run format:check` failed on four untouched files (`src/app.css`, `src/lib/components/ui/dropdown-menu/content.svelte`, `src/lib/features/layout/SettingsDialog.svelte`, `src/routes/+layout.svelte`) and `vite.config.js`, whose original CRLF line endings were preserved to keep the change limited.
|
||||||
|
- Android JVM tests were not run: Java and Gradle executables and a Unix `gradlew` wrapper are unavailable. The source test exists at the path listed in Q-004. A final redundant Svelte-check rerun was stopped after the process remained in uninterruptible I/O for several minutes; an earlier `npm run check` completed successfully before the Vite-only symlink setting.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- Static review only. No tests, linters, Go or Node builds, or Gradle runs were executed. Test coverage was assessed by reading the `_test.go` files and the CI workflows.
|
- No live AuthGuard instance or browser session was available, and no load benchmark was run. Performance estimates still need realistic data and multiple devices.
|
||||||
- Checked and clean: no `{@html}`, `innerHTML` or `eval` in the dashboard; error wrapping in `backend/db.go` and the auth helpers is consistent; `shared/backend/postgres/postgres.go:216-235` (`WithTx`) rolls back through a deferred call on every path; no TODO, FIXME or HACK markers in `backend/` or `frontend/src/`.
|
- Checked and clean: no `{@html}`, `innerHTML` or `eval` in the dashboard; error wrapping in `backend/db.go` and the auth helpers is consistent; `shared/backend/postgres/postgres.go:216-235` (`WithTx`) rolls back through a deferred call on every path; no TODO, FIXME or HACK markers in `backend/` or `frontend/src/`.
|
||||||
- `map[string]any` is used for several ad hoc response bodies (`backend/web.go:77-89`, `backend/data.go:464` and `:623`). That is acceptable for these responses, and no weakly typed data flows through the core domain types.
|
- `map[string]any` is used for several ad hoc response bodies (`backend/web.go:77-89`, `backend/data.go:464` and `:623`). That is acceptable for these responses, and no weakly typed data flows through the core domain types.
|
||||||
- `shared/` was reviewed selectively. Two items in it are outside CollabTable's runtime and are noted for the shared package owners rather than counted here: `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify` (which disables WebSocket origin checks) when the allowed origin is `*`, and the package is not imported by CollabTable.
|
- `shared/` was reviewed selectively. Two items in it are outside CollabTable's runtime and are noted for the shared package owners rather than counted here: `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify` (which disables WebSocket origin checks) when the allowed origin is `*`, and the package is not imported by CollabTable.
|
||||||
@@ -35,7 +35,7 @@ CollabTable's browser dashboard authenticates through AuthGuard, a centralized i
|
|||||||
AuthGuard integration has three states:
|
AuthGuard integration has three states:
|
||||||
- `AUTHGUARD_URL` set — used immediately.
|
- `AUTHGUARD_URL` set — used immediately.
|
||||||
- `AUTHGUARD_URL` unset, `AUTH_DISABLED` unset/false (the default) — "pending": auth stays fully enabled/gated, waiting for ProjectConfigurator to push a live URL (see below), and fails closed on auth calls until one arrives.
|
- `AUTHGUARD_URL` unset, `AUTH_DISABLED` unset/false (the default) — "pending": auth stays fully enabled/gated, waiting for ProjectConfigurator to push a live URL (see below), and fails closed on auth calls until one arrives.
|
||||||
- `AUTH_DISABLED=true` — authentication is fully off (no login screen, nothing gated, every request treated as authenticated) — only use this for local development or a deployment you are certain does not need access control.
|
- `AUTH_DISABLED=true` — browser-session gates are off. List access still requires membership; the placeholder identity used in this mode has no memberships, so dashboard data is empty and sync tokens minted for it are rejected. Use this only to develop the auth shell, not for a working data deployment.
|
||||||
|
|
||||||
Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state.
|
Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state.
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ The device-sync API token (generated from the dashboard's Settings page, used by
|
|||||||
|----------|----------|---------|--------------|
|
|----------|----------|---------|--------------|
|
||||||
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
|
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
|
||||||
| `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. |
|
| `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. |
|
| `AUTH_DISABLED` | No | `false` | Set `true` to disable browser-session gates. List access remains membership-scoped; the placeholder identity has no memberships and its sync tokens are rejected. Use only for auth-shell development, not for a working data deployment. |
|
||||||
| `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. |
|
| `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. |
|
||||||
| `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. |
|
| `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. |
|
| `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. |
|
||||||
|
|||||||
+11
-11
@@ -4,10 +4,10 @@
|
|||||||
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
||||||
- **Analyzed:** 2026-10-16
|
- **Analyzed:** 2026-10-16
|
||||||
- **Commit:** 6aec03f on main
|
- **Commit:** 6aec03f on main
|
||||||
- **Working tree:** clean (no uncommitted changes, no untracked files)
|
- **Working tree:** contains uncommitted changes from the earlier and current medium passes.
|
||||||
- **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.
|
- **Updated:** 2026-10-20 — S-003 now enforces the approved per-list membership model; S-005 applies the shared reauthentication rule and remains open only for other-session revocation. S-002 remains Not reproduced by owner decision.
|
||||||
- **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.
|
- **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.
|
- **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. Available tests and builds are recorded in `QUALITY_REPORT.md`; no network audit or live deployment check was made.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -15,11 +15,11 @@
|
|||||||
|---|---:|---:|---:|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 0 | 0 | 0 | 0 |
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
| High | 0 | 0 | 0 | 0 |
|
| High | 0 | 0 | 0 | 0 |
|
||||||
| Medium | 10 | 7 | 1 | 2 |
|
| Medium | 10 | 8 | 1 | 1 |
|
||||||
| Low | 7 | 0 | 0 | 7 |
|
| Low | 7 | 0 | 0 | 7 |
|
||||||
| Info | 2 | 0 | 0 | 2 |
|
| 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).
|
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. Data access is now scoped by list membership; legacy lists remain available to all API-token users present during migration, as approved. Other concerns include reflective CORS with credentials, missing rate limits and security headers, and Android token exposure through cleartext traffic or plain device preferences.
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
@@ -35,14 +35,14 @@ No critical or high-severity issues were confirmed. Authentication is delegated
|
|||||||
- **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.
|
- **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.
|
- **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.
|
- **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.
|
- **Status:** Not reproduced 2026-10-20 — The last step of the chain fails. With login off, callers resolve to placeholder identity 0, and `requireAPIToken` (`backend/auth.go`) never accepts identity 0, so a token minted without a session gets 401 on `/api/sync` and `/api/lists`. `TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI` pins this. Write and delete access through that token is not reachable. Login-off still bypasses the browser-session gate, but `/web/data` returns no list rows because identity 0 has no memberships. Devices cannot get a working sync token; accepting identity 0 would open sync and is not part of this decision.
|
||||||
|
|
||||||
### S-003 · No object-level ownership or roles on list, field, item or value data · **Medium** · Open
|
### S-003 · No object-level ownership or roles on list, field, item or value data · **Medium** · Fixed
|
||||||
- **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).
|
- **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.
|
- **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.
|
- **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.
|
- **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).
|
- **Status:** Fixed 2026-10-20 — `list_memberships` now scopes REST, sync, dashboard and notification reads; cross-list item/field IDs are rejected. New lists belong only to their creator. Per the owner decision, migration grants every current API-token user access to each legacy list because prior ownership cannot be reconstructed. Login-disabled identity 0 has no list access. Item values still hard-delete with their parent, as before. Files: `backend/db.go`, `backend/ownership.go`, `backend/data.go`, `backend/sync.go`, `backend/web.go`.
|
||||||
|
|
||||||
### S-004 · Managed-user routes require a login only, leaving the role check to AuthGuard · **Medium** · Fixed
|
### 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).
|
- **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).
|
||||||
@@ -56,7 +56,7 @@ No critical or high-severity issues were confirmed. Authentication is delegated
|
|||||||
- **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.
|
- **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.
|
- **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.
|
- **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.
|
- **Status:** Open 2026-10-20 — Partly fixed: the mirrored shared `UpdateMe` requires the current password and TOTP proof when enabled, and the dashboard forwards both values. Still open: revoking other sessions after a password change; no owner decision was made for that behavior. Files: `frontend/src/lib/api.js`, `frontend/src/lib/features/layout/AppShell.svelte`, `shared/backend/auth/proxy.go`.
|
||||||
|
|
||||||
### S-006 · No rate limiting or request budgets on login, token use, writes or body size · **Medium** · Fixed
|
### 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).
|
- **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).
|
||||||
@@ -147,8 +147,8 @@ No critical or high-severity issues were confirmed. Authentication is delegated
|
|||||||
- **Recommendation:** None.
|
- **Recommendation:** None.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- Static analysis only. Nothing was executed: no tests, builds, dependency audits or network calls. Fail-closed behavior was confirmed by reading the code, not by running the server.
|
- Source review and available checks are recorded in `QUALITY_REPORT.md` under Verification. No live AuthGuard instance or browser session was available, so delegated auth behavior was not exercised end to end.
|
||||||
- AuthGuard, the identity service, is outside this repository. S-001 (exploitability), S-004, S-005, S-006 and S-013 depend on how it behaves and should be verified against a running instance.
|
- AuthGuard, the identity service, is outside this repository. S-001 (exploitability), S-004, S-005, S-006 and S-013 depend on how it behaves and should be verified against a running instance.
|
||||||
- Android findings come from source, manifest and Gradle review. The app was not built or run.
|
- Android findings come from source, manifest and Gradle review. The sync-page JVM test source was added, but could not be compiled or run here because Java and Gradle are unavailable.
|
||||||
- `shared/` was reviewed selectively. `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify = true` (which disables WebSocket origin checks in the library) when the allowed origin is `*`. CollabTable does not import this package, so it is not counted here, but its owners should review it.
|
- `shared/` was reviewed selectively. `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify = true` (which disables WebSocket origin checks in the library) when the allowed origin is `*`. CollabTable does not import this package, so it is not counted here, but its owners should review it.
|
||||||
- `shared/.githooks/post-commit` runs `shared/scripts/sync-consumers.ps1 -Commit` on commit once the hook path is configured (see `install-sync-hook.ps1`). `-Push` is opt-in (`sync-consumers.ps1:11-12` and `:370`). This is a developer-workflow concern rather than a runtime one.
|
- `shared/.githooks/post-commit` runs `shared/scripts/sync-consumers.ps1 -Commit` on commit once the hook path is configured (see `install-sync-hook.ps1`). `-Push` is opt-in (`sync-consumers.ps1:11-12` and `:370`). This is a developer-workflow concern rather than a runtime one.
|
||||||
+25
-15
@@ -87,9 +87,11 @@ accounts can exist, with `user`/`admin`/`superadmin` roles managed via `/api/aut
|
|||||||
AuthGuard integration has three states: `AUTHGUARD_URL` set (used immediately); unset with
|
AuthGuard integration has three states: `AUTHGUARD_URL` set (used immediately); unset with
|
||||||
`AUTH_DISABLED` unset/false (the default -- "pending": auth stays fully enabled/gated, waiting
|
`AUTH_DISABLED` unset/false (the default -- "pending": auth stays fully enabled/gated, waiting
|
||||||
for ProjectConfigurator's push, failing closed on auth calls until then); or `AUTH_DISABLED=true`
|
for ProjectConfigurator's push, failing closed on auth calls until then); or `AUTH_DISABLED=true`
|
||||||
(authentication fully off -- no login screen, nothing gated). Only set `AUTH_DISABLED=true` for
|
(the browser-session gate is off). List access still requires membership. In this mode requests
|
||||||
local development or a deployment you are certain does not need access control. API tokens are
|
use placeholder identity 0, which has no list memberships, so the dashboard data is empty and
|
||||||
unrelated to AuthGuard (see below), hashed at rest, and shown only when generated.
|
sync API tokens for identity 0 are rejected. Use it only for local development of the auth shell,
|
||||||
|
not for a working data deployment. API tokens are unrelated to AuthGuard (see below), hashed at
|
||||||
|
rest, and shown only when generated.
|
||||||
|
|
||||||
### Data
|
### Data
|
||||||
|
|
||||||
@@ -106,6 +108,14 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
|||||||
- `POST /api/sync`
|
- `POST /api/sync`
|
||||||
- `GET /api/notifications/poll?since=<timestamp-ms>`
|
- `GET /api/notifications/poll?since=<timestamp-ms>`
|
||||||
|
|
||||||
|
The list, field, item and item-value collection GETs accept `limit` (default 200, maximum 500)
|
||||||
|
and an opaque `cursor`. They return `{ "items": [...], "nextCursor": "...", "hasMore": true }`;
|
||||||
|
continue with `nextCursor` while `hasMore` is true. The final page has an empty `nextCursor`.
|
||||||
|
`POST /api/sync` requires `lastSyncToken` (use `0` for the first sync) and returns at most 500
|
||||||
|
changes with `nextSyncToken` and `hasMore`. Clients must request each page until `hasMore` is
|
||||||
|
false. Older sync clients without `lastSyncToken` receive HTTP 400 and must be updated with the
|
||||||
|
server.
|
||||||
|
|
||||||
### Dashboard and health
|
### Dashboard and health
|
||||||
|
|
||||||
- `GET /health` is public.
|
- `GET /health` is public.
|
||||||
@@ -135,9 +145,9 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
|||||||
CollabTable authenticates against, default unset (pending). Leaving it unset does not disable
|
CollabTable authenticates against, default unset (pending). Leaving it unset does not disable
|
||||||
authentication -- it leaves the service "pending" until ProjectConfigurator pushes a URL,
|
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.
|
failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off.
|
||||||
- `AUTH_DISABLED` — set `true` to disable authentication entirely (no login screen, nothing
|
- `AUTH_DISABLED` — set `true` to disable browser-session gates, default `false`. List access is
|
||||||
gated, every request treated as authenticated), default `false`. For local development or a
|
still membership-scoped; placeholder identity 0 has no memberships and its sync tokens are
|
||||||
standalone deployment with no AuthGuard integration at all.
|
rejected. Use only for local auth-shell development, not a working data deployment.
|
||||||
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
|
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
|
||||||
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
||||||
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
||||||
@@ -169,17 +179,17 @@ attribute. `Strict-Transport-Security` is not set here; set it at the TLS proxy.
|
|||||||
|
|
||||||
## Access model
|
## Access model
|
||||||
|
|
||||||
There is one shared data set. Lists, fields, items and values have no owner and no per-list
|
List, field, item and value reads and writes are scoped to `list_memberships`. On migration,
|
||||||
roles: any valid sync token can read, change and delete all of them, and any signed-in dashboard
|
every current API-token user is granted access to every existing list because the old schema did
|
||||||
user can see all of them. Tokens are per account only so that each can be regenerated on its own.
|
not store owners. Lists created afterward are owned only by their creator. There is currently no
|
||||||
Deleting an item, field or list removes its values for good, while the rows themselves are soft
|
API for owners to add or remove members, so a newly created list is private to its creator's
|
||||||
deleted. Per-list access would need a membership table checked in every handler; that has not
|
account and devices. Deleting an item, field or list still removes its values permanently, while
|
||||||
been decided.
|
the parent rows remain soft-deleted.
|
||||||
|
|
||||||
When login is off (`AUTH_DISABLED=true`, or the login-required switch turned off in
|
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
|
ProjectConfigurator), browser-session gates are bypassed. Data remains membership-scoped; the
|
||||||
separate matter: a caller without a session can only mint a token for the placeholder identity,
|
placeholder identity 0 has no memberships, so `/web/data` contains no lists. A caller without a
|
||||||
and the sync API refuses that identity.
|
session can only mint a token for that placeholder identity, and the sync API refuses it.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
+14
-1
@@ -146,11 +146,24 @@ func requireAPIToken(db *DB) func(http.Handler) http.Handler {
|
|||||||
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next.ServeHTTP(w, r)
|
ctx := context.WithValue(r.Context(), apiUserIDContextKey{}, userID)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type apiUserIDContextKey struct{}
|
||||||
|
|
||||||
|
func requestUserID(r *http.Request) int64 {
|
||||||
|
if userID, ok := r.Context().Value(apiUserIDContextKey{}).(int64); ok {
|
||||||
|
return userID
|
||||||
|
}
|
||||||
|
if user := sharedauth.UserFromContext(r.Context()); user != nil {
|
||||||
|
return user.ID
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
func extractBearer(r *http.Request) string {
|
func extractBearer(r *http.Request) string {
|
||||||
header := r.Header.Get("Authorization")
|
header := r.Header.Get("Authorization")
|
||||||
if !strings.HasPrefix(header, "Bearer ") {
|
if !strings.HasPrefix(header, "Bearer ") {
|
||||||
|
|||||||
+289
-55
@@ -65,15 +65,17 @@ func (d *DB) getList(ctx context.Context, id string) (List, error) {
|
|||||||
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64) ([]List, error) {
|
func (d *DB) queryLists(ctx context.Context, userID int64, includeDeleted bool, since *int64) ([]List, error) {
|
||||||
conditions := make([]string, 0, 2)
|
conditions := make([]string, 0, 3)
|
||||||
args := make([]any, 0, 1)
|
args := make([]any, 0, 2)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = lists.id AND m.user_id = $%d)", len(args)))
|
||||||
if !includeDeleted {
|
if !includeDeleted {
|
||||||
conditions = append(conditions, "isdeleted = 0")
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
}
|
}
|
||||||
if since != nil {
|
if since != nil {
|
||||||
conditions = append(conditions, "updatedat >= $1")
|
|
||||||
args = append(args, *since)
|
args = append(args, *since)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||||
}
|
}
|
||||||
query := `SELECT ` + listColumns + ` FROM lists`
|
query := `SELECT ` + listColumns + ` FROM lists`
|
||||||
if len(conditions) > 0 {
|
if len(conditions) > 0 {
|
||||||
@@ -98,9 +100,11 @@ func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64)
|
|||||||
return lists, rows.Err()
|
return lists, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
func (d *DB) queryFields(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||||
conditions := make([]string, 0, 3)
|
conditions := make([]string, 0, 4)
|
||||||
args := make([]any, 0, 2)
|
args := make([]any, 0, 3)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = fields.listid AND m.user_id = $%d)", len(args)))
|
||||||
if !includeDeleted {
|
if !includeDeleted {
|
||||||
conditions = append(conditions, "isdeleted = 0")
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
}
|
}
|
||||||
@@ -134,9 +138,11 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
|
|||||||
return fields, rows.Err()
|
return fields, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
func (d *DB) queryItems(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||||
conditions := make([]string, 0, 3)
|
conditions := make([]string, 0, 4)
|
||||||
args := make([]any, 0, 2)
|
args := make([]any, 0, 3)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = items.listid AND m.user_id = $%d)", len(args)))
|
||||||
if !includeDeleted {
|
if !includeDeleted {
|
||||||
conditions = append(conditions, "isdeleted = 0")
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
}
|
}
|
||||||
@@ -170,9 +176,11 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
|
|||||||
return items, rows.Err()
|
return items, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]ItemValue, error) {
|
func (d *DB) queryValues(ctx context.Context, userID int64, since *int64, itemID string) ([]ItemValue, error) {
|
||||||
conditions := make([]string, 0, 2)
|
conditions := make([]string, 0, 3)
|
||||||
args := make([]any, 0, 2)
|
args := make([]any, 0, 3)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM items i JOIN list_memberships m ON m.listid = i.listid WHERE i.id = item_values.itemid AND m.user_id = $%d)", len(args)))
|
||||||
if since != nil {
|
if since != nil {
|
||||||
args = append(args, *since)
|
args = append(args, *since)
|
||||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||||
@@ -353,7 +361,11 @@ type listMutation struct {
|
|||||||
|
|
||||||
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == http.MethodGet {
|
if r.Method == http.MethodGet {
|
||||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
page, ok := requestPage(w, r, "lists")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lists, err := s.db.queryListPage(r.Context(), requestUserID(r), false, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
||||||
return
|
return
|
||||||
@@ -371,15 +383,34 @@ func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := authorizeList(r.Context(), tx, requestUserID(r), request.ID, true); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := tx.Exec(r.Context(), `
|
||||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := addListOwner(r.Context(), tx, requestUserID(r), request.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
|
||||||
list, err := s.db.getList(r.Context(), request.ID)
|
list, err := s.db.getList(r.Context(), request.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||||
@@ -392,6 +423,9 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
id := r.PathValue("id")
|
id := r.PathValue("id")
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
|
if !s.requireListMembership(w, r, id) {
|
||||||
|
return
|
||||||
|
}
|
||||||
list, err := s.db.getList(r.Context(), id)
|
list, err := s.db.getList(r.Context(), id)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
@@ -416,17 +450,34 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
var list List
|
||||||
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
return err
|
||||||
return
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
||||||
|
var scanErr error
|
||||||
|
list, scanErr = scanList(tx.QueryRow(r.Context(), `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||||
|
return scanErr
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
|
||||||
list, err := s.db.getList(r.Context(), id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||||
return
|
return
|
||||||
@@ -435,6 +486,16 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
case http.MethodDelete:
|
case http.MethodDelete:
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
result, err := tx.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
result, err := tx.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -448,7 +509,7 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -466,7 +527,15 @@ type fieldMutation struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
||||||
fields, err := s.db.queryFields(r.Context(), false, nil, r.PathValue("listId"))
|
listID := r.PathValue("listId")
|
||||||
|
if !s.requireListMembership(w, r, listID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, ok := requestPage(w, r, "fields")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fields, err := s.db.queryFieldsPage(r.Context(), requestUserID(r), false, listID, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
||||||
return
|
return
|
||||||
@@ -485,16 +554,36 @@ func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), request.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(r.Context(), `
|
||||||
INSERT INTO fields
|
INSERT INTO fields
|
||||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||||
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
|
||||||
field, err := s.getField(r.Context(), request.ID)
|
field, err := s.getField(r.Context(), request.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||||
@@ -525,25 +614,49 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
result, err := s.db.pool.Exec(r.Context(), `
|
var field Field
|
||||||
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var listID string
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `
|
||||||
UPDATE fields
|
UPDATE fields
|
||||||
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
||||||
WHERE id = $7
|
WHERE id = $7
|
||||||
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
return err
|
||||||
return
|
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
var scanErr error
|
||||||
|
field, scanErr = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||||
|
if scanErr != nil {
|
||||||
|
return scanErr
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
field, err := s.getField(r.Context(), id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
|
||||||
writeJSON(w, http.StatusOK, field)
|
writeJSON(w, http.StatusOK, field)
|
||||||
case http.MethodDelete:
|
case http.MethodDelete:
|
||||||
var request struct {
|
var request struct {
|
||||||
@@ -554,11 +667,21 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
var field Field
|
var field Field
|
||||||
cascade := false
|
cascade := false
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
var err error
|
var err error
|
||||||
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), field.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -569,7 +692,7 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
ignoreNotificationError(enqueueNotificationInTx(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
|
return nil
|
||||||
})
|
})
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -594,7 +717,14 @@ func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
|||||||
listID = parts[1]
|
listID = parts[1]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
items, err := s.db.queryItems(r.Context(), false, nil, listID)
|
if !s.requireListMembership(w, r, listID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, ok := requestPage(w, r, "items")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, err := s.db.queryItemsPage(r.Context(), requestUserID(r), false, listID, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
||||||
return
|
return
|
||||||
@@ -612,15 +742,35 @@ func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), request.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(r.Context(), `
|
||||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
|
||||||
item, err := s.getItem(r.Context(), request.ID)
|
item, err := s.getItem(r.Context(), request.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||||
@@ -641,7 +791,23 @@ func (s *Server) handleValuesForItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
itemID = parts[0]
|
itemID = parts[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
values, err := s.db.queryValues(r.Context(), nil, itemID)
|
var listID string
|
||||||
|
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, itemID).Scan(&listID); err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||||
|
} else {
|
||||||
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !s.requireListMembership(w, r, listID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, ok := requestPage(w, r, "values")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
values, err := s.db.queryValuesPage(r.Context(), requestUserID(r), itemID, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||||
return
|
return
|
||||||
@@ -662,27 +828,57 @@ func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Reques
|
|||||||
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
applied, err := upsertValue(r.Context(), s.db.pool, request.ItemValue, int64(request.UpdatedAt))
|
var value ItemValue
|
||||||
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var fieldListID, itemListID string
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&fieldListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, request.ItemID).Scan(&itemListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fieldListID != itemListID {
|
||||||
|
return errCellIdentityMismatch
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), fieldListID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
return err
|
||||||
return
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
var storedItemID, storedFieldID string
|
||||||
|
storedErr := tx.QueryRow(r.Context(), `SELECT itemid, fieldid FROM item_values WHERE id = $1`, request.ID).Scan(&storedItemID, &storedFieldID)
|
||||||
|
if storedErr == nil && (storedItemID != request.ItemID || storedFieldID != request.FieldID) {
|
||||||
|
return errCellIdentityMismatch
|
||||||
|
}
|
||||||
|
if storedErr != nil && !errors.Is(storedErr, pgx.ErrNoRows) {
|
||||||
|
return storedErr
|
||||||
|
}
|
||||||
|
applied, err := upsertValue(r.Context(), tx, request.ItemValue, int64(request.UpdatedAt))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
// An older write than the stored value changes nothing, so it notifies no one.
|
// An older write than the stored value changes nothing, so it notifies no one.
|
||||||
var listID string
|
|
||||||
if applied {
|
if applied {
|
||||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
|
var listID string
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||||
}
|
}
|
||||||
var value ItemValue
|
var scanErr error
|
||||||
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
|
value, scanErr = scanItemValue(tx.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID))
|
||||||
&value.ID,
|
return scanErr
|
||||||
&value.ItemID,
|
})
|
||||||
&value.FieldID,
|
|
||||||
&value.Value,
|
|
||||||
&value.UpdatedAt,
|
|
||||||
)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) || errors.Is(err, errCellIdentityMismatch) || errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "Item value not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -702,25 +898,63 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
if r.Method == http.MethodPut {
|
if r.Method == http.MethodPut {
|
||||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
var item Item
|
||||||
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var listID string
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
return err
|
||||||
return
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
var scanErr error
|
||||||
|
item, scanErr = scanItem(tx.QueryRow(r.Context(), `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
|
||||||
|
if scanErr != nil {
|
||||||
|
return scanErr
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
item, err := s.getItem(r.Context(), id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
|
||||||
writeJSON(w, http.StatusOK, item)
|
writeJSON(w, http.StatusOK, item)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var listID string
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
result, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
result, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -738,7 +972,7 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
+108
-1
@@ -35,6 +35,11 @@ func (d *DB) withTx(ctx context.Context, fn func(pgx.Tx) error) error {
|
|||||||
return sharedpostgres.WithTx(ctx, d.pool, fn)
|
return sharedpostgres.WithTx(ctx, d.pool, fn)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func lockChangeClock(ctx context.Context, tx pgx.Tx) error {
|
||||||
|
var token int64
|
||||||
|
return tx.QueryRow(ctx, `SELECT token FROM collabtable_sync_clock WHERE id = 1 FOR UPDATE`).Scan(&token)
|
||||||
|
}
|
||||||
|
|
||||||
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
||||||
// be used by the Go server without a separate migration step.
|
// be used by the Go server without a separate migration step.
|
||||||
func (d *DB) initSchema(ctx context.Context) error {
|
func (d *DB) initSchema(ctx context.Context) error {
|
||||||
@@ -44,7 +49,8 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
createdat BIGINT NOT NULL,
|
createdat BIGINT NOT NULL,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
isdeleted INTEGER NOT NULL DEFAULT 0
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS fields (
|
CREATE TABLE IF NOT EXISTS fields (
|
||||||
@@ -58,6 +64,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
createdat BIGINT NOT NULL,
|
createdat BIGINT NOT NULL,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0,
|
||||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -67,6 +74,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
createdat BIGINT NOT NULL,
|
createdat BIGINT NOT NULL,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0,
|
||||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -76,6 +84,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
fieldid TEXT NOT NULL,
|
fieldid TEXT NOT NULL,
|
||||||
value TEXT,
|
value TEXT,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0,
|
||||||
FOREIGN KEY (itemid) REFERENCES items(id),
|
FOREIGN KEY (itemid) REFERENCES items(id),
|
||||||
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
||||||
);
|
);
|
||||||
@@ -88,6 +97,54 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
CREATE INDEX IF NOT EXISTS idx_fields_updatedat ON fields(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_items_updatedat ON items(updatedat);
|
||||||
CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat);
|
CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_lists_page ON lists(updatedat DESC, id ASC) WHERE isdeleted = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fields_page ON fields(listid, "order" ASC, id ASC) WHERE isdeleted = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_items_page ON items(listid, updatedat DESC, id ASC) WHERE isdeleted = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_item_values_page ON item_values(itemid, updatedat ASC, id ASC);
|
||||||
|
ALTER TABLE lists ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE fields ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE items ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE item_values ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS collabtable_sync_clock (
|
||||||
|
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||||
|
token BIGINT NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
INSERT INTO collabtable_sync_clock (id, token) VALUES (1, 0) ON CONFLICT (id) DO NOTHING;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_lists_change_token ON lists(change_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fields_change_token ON fields(change_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_items_change_token ON items(change_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_item_values_change_token ON item_values(change_token);
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION collabtable_assign_change_token()
|
||||||
|
RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE next_token BIGINT;
|
||||||
|
BEGIN
|
||||||
|
UPDATE collabtable_sync_clock SET token = token + 1 WHERE id = 1 RETURNING token INTO next_token;
|
||||||
|
IF next_token IS NULL THEN
|
||||||
|
RAISE EXCEPTION 'sync clock row is missing';
|
||||||
|
END IF;
|
||||||
|
NEW.change_token := next_token;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'lists_change_token' AND tgrelid = 'lists'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER lists_change_token BEFORE INSERT OR UPDATE ON lists FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'fields_change_token' AND tgrelid = 'fields'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER fields_change_token BEFORE INSERT OR UPDATE ON fields FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'items_change_token' AND tgrelid = 'items'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER items_change_token BEFORE INSERT OR UPDATE ON items FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'item_values_change_token' AND tgrelid = 'item_values'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER item_values_change_token BEFORE INSERT OR UPDATE ON item_values FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS notifications (
|
CREATE TABLE IF NOT EXISTS notifications (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
@@ -190,14 +247,64 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
||||||
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
|
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS list_memberships (
|
||||||
|
listid TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
is_owner BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (listid, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_list_memberships_user ON list_memberships(user_id, listid);
|
||||||
`)
|
`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("initialize schema: %w", err)
|
return fmt.Errorf("initialize schema: %w", err)
|
||||||
}
|
}
|
||||||
|
if err := d.backfillChangeTokens(ctx); err != nil {
|
||||||
|
return fmt.Errorf("backfill change tokens: %w", err)
|
||||||
|
}
|
||||||
|
if err := d.backfillListMemberships(ctx); err != nil {
|
||||||
|
return fmt.Errorf("backfill list memberships: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *DB) backfillListMemberships(ctx context.Context) error {
|
||||||
|
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(ctx, tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO list_memberships (listid, user_id, is_owner)
|
||||||
|
SELECT lists.id, token_users.user_id, FALSE
|
||||||
|
FROM lists
|
||||||
|
CROSS JOIN (SELECT DISTINCT user_id FROM api_tokens WHERE user_id <> 0) AS token_users
|
||||||
|
-- New lists already have their creator's membership, so they are not
|
||||||
|
-- expanded to every token user on later starts.
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM list_memberships existing WHERE existing.listid = lists.id)
|
||||||
|
ON CONFLICT (listid, user_id) DO NOTHING
|
||||||
|
`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) backfillChangeTokens(ctx context.Context) error {
|
||||||
|
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(ctx, tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, table := range []string{"lists", "fields", "items", "item_values"} {
|
||||||
|
if _, err := tx.Exec(ctx, `UPDATE `+table+` SET change_token = change_token WHERE change_token = 0`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
||||||
ticker := time.NewTicker(time.Hour)
|
ticker := time.NewTicker(time.Hour)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|||||||
+299
-14
@@ -110,6 +110,10 @@ func newTestAPI(t *testing.T) *testAPI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRecorder {
|
func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRecorder {
|
||||||
|
return a.doAs(method, path, device, testBearer, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) doAs(method, path, device, token string, body any) *httptest.ResponseRecorder {
|
||||||
a.t.Helper()
|
a.t.Helper()
|
||||||
var reader *bytes.Reader
|
var reader *bytes.Reader
|
||||||
if body == nil {
|
if body == nil {
|
||||||
@@ -122,7 +126,7 @@ func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRe
|
|||||||
reader = bytes.NewReader(encoded)
|
reader = bytes.NewReader(encoded)
|
||||||
}
|
}
|
||||||
request := httptest.NewRequest(method, path, reader)
|
request := httptest.NewRequest(method, path, reader)
|
||||||
request.Header.Set("Authorization", "Bearer "+testBearer)
|
request.Header.Set("Authorization", "Bearer "+token)
|
||||||
if device != "" {
|
if device != "" {
|
||||||
request.Header.Set("X-Device-Id", device)
|
request.Header.Set("X-Device-Id", device)
|
||||||
}
|
}
|
||||||
@@ -140,6 +144,15 @@ func (a *testAPI) mustDo(method, path, device string, body any, wantStatus int)
|
|||||||
return recorder
|
return recorder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) mustDoAs(method, path, device, token string, body any, wantStatus int) *httptest.ResponseRecorder {
|
||||||
|
a.t.Helper()
|
||||||
|
recorder := a.doAs(method, path, device, token, body)
|
||||||
|
if recorder.Code != wantStatus {
|
||||||
|
a.t.Fatalf("%s %s status = %d, want %d; body %s", method, path, recorder.Code, wantStatus, recorder.Body.String())
|
||||||
|
}
|
||||||
|
return recorder
|
||||||
|
}
|
||||||
|
|
||||||
func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
var value T
|
var value T
|
||||||
@@ -151,10 +164,25 @@ func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
|||||||
|
|
||||||
func (a *testAPI) sync(device string, request SyncRequest) SyncResponse {
|
func (a *testAPI) sync(device string, request SyncRequest) SyncResponse {
|
||||||
a.t.Helper()
|
a.t.Helper()
|
||||||
|
if request.LastSyncToken == nil {
|
||||||
|
initialToken := int64(0)
|
||||||
|
request.LastSyncToken = &initialToken
|
||||||
|
}
|
||||||
request.DeviceID = device
|
request.DeviceID = device
|
||||||
return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK))
|
return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) currentSyncToken() int64 {
|
||||||
|
a.t.Helper()
|
||||||
|
var token int64
|
||||||
|
if err := a.db.pool.QueryRow(context.Background(), `SELECT token FROM collabtable_sync_clock WHERE id = 1`).Scan(&token); err != nil {
|
||||||
|
a.t.Fatalf("read sync token: %v", err)
|
||||||
|
}
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
func ptrInt64(value int64) *int64 { return &value }
|
||||||
|
|
||||||
func (a *testAPI) count(query string, args ...any) int {
|
func (a *testAPI) count(query string, args ...any) int {
|
||||||
a.t.Helper()
|
a.t.Helper()
|
||||||
var n int
|
var n int
|
||||||
@@ -219,9 +247,38 @@ func (a *testAPI) seedList(device, prefix string) {
|
|||||||
|
|
||||||
func TestInitSchemaCanRunAgainstAnExistingDatabase(t *testing.T) {
|
func TestInitSchemaCanRunAgainstAnExistingDatabase(t *testing.T) {
|
||||||
db := testDB(t)
|
db := testDB(t)
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('backfill', 'Backfill', $1, $1)`, t0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists DISABLE TRIGGER lists_change_token`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `UPDATE lists SET change_token = 0 WHERE id = 'backfill'`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists ENABLE TRIGGER lists_change_token`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
if err := db.initSchema(context.Background()); err != nil {
|
if err := db.initSchema(context.Background()); err != nil {
|
||||||
t.Fatalf("second initSchema() error = %v", err)
|
t.Fatalf("second initSchema() error = %v", err)
|
||||||
}
|
}
|
||||||
|
var firstToken int64
|
||||||
|
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&firstToken); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if firstToken == 0 {
|
||||||
|
t.Fatal("initSchema left an existing list without a change token")
|
||||||
|
}
|
||||||
|
if err := db.initSchema(context.Background()); err != nil {
|
||||||
|
t.Fatalf("third initSchema() error = %v", err)
|
||||||
|
}
|
||||||
|
var secondToken int64
|
||||||
|
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&secondToken); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if secondToken != firstToken {
|
||||||
|
t.Fatalf("re-running initSchema changed backfilled token from %d to %d", firstToken, secondToken)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
||||||
@@ -240,21 +297,21 @@ func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
|||||||
t.Fatalf("orphanItemValues = %v, want none", full.OrphanItemValues)
|
t.Fatalf("orphanItemValues = %v, want none", full.OrphanItemValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// The delta filter is "updated at or after the cursor".
|
// The server returns a cursor from the same snapshot as its data page.
|
||||||
if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 11)}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 {
|
if got := api.sync("tablet", SyncRequest{LastSyncToken: &full.NextSyncToken}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 {
|
||||||
t.Fatalf("sync after the last change returned %+v, want nothing", got)
|
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 {
|
if got := api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(0)}); 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))
|
t.Fatalf("initial page returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues))
|
||||||
}
|
}
|
||||||
|
|
||||||
// The REST reads see the same data.
|
// The REST reads see the same data.
|
||||||
lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||||
if len(lists) != 1 || lists[0].Name != "Groceries" {
|
if len(lists.Items) != 1 || lists.Items[0].Name != "Groceries" || lists.HasMore {
|
||||||
t.Fatalf("GET /api/lists = %+v, want the pushed list", lists)
|
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))
|
values := decodeBody[PageResponse[ItemValue]](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK))
|
||||||
if len(values) != 2 {
|
if len(values.Items) != 2 || values.HasMore {
|
||||||
t.Fatalf("GET item values = %+v, want 2", values)
|
t.Fatalf("GET item values = %+v, want 2", values)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -274,6 +331,232 @@ func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCollectionEndpointsPageWithStableCursors(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
api.sync("phone", SyncRequest{
|
||||||
|
Lists: []List{testList("a-list", "A", t0+10, false)},
|
||||||
|
Items: []Item{testItem("a-item", "g-list", t0+10, false)},
|
||||||
|
})
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
endpoint string
|
||||||
|
decode func(*testing.T, *httptest.ResponseRecorder) (string, string, bool)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "lists",
|
||||||
|
endpoint: "/api/lists",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[List]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first list page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "fields",
|
||||||
|
endpoint: "/api/fields/list/g-list",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[Field]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first field page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "items",
|
||||||
|
endpoint: "/api/items/list/g-list",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[Item]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first item page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "values",
|
||||||
|
endpoint: "/api/items/g-item/values",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[ItemValue]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first value page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
firstPath := test.endpoint + "?limit=1"
|
||||||
|
firstRecorder := api.mustDo(http.MethodGet, firstPath, "", nil, http.StatusOK)
|
||||||
|
firstID, cursor, hasMore := test.decode(t, firstRecorder)
|
||||||
|
if !hasMore || cursor == "" {
|
||||||
|
t.Fatalf("first page hasMore=%v cursor=%q, want another page", hasMore, cursor)
|
||||||
|
}
|
||||||
|
secondPath := firstPath + "&cursor=" + url.QueryEscape(cursor)
|
||||||
|
secondRecorder := api.mustDo(http.MethodGet, secondPath, "", nil, http.StatusOK)
|
||||||
|
secondID, nextCursor, hasMore := test.decode(t, secondRecorder)
|
||||||
|
if secondID == firstID {
|
||||||
|
t.Fatalf("cursor repeated item %q", firstID)
|
||||||
|
}
|
||||||
|
if hasMore || nextCursor != "" {
|
||||||
|
t.Fatalf("second page hasMore=%v cursor=%q, want final page", hasMore, nextCursor)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists?limit=501", "", nil, http.StatusBadRequest)
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists?cursor=not-a-cursor", "", nil, http.StatusBadRequest)
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists?cursor="+url.QueryEscape(encodePageCursor(pageCursor{Kind: "items", Key: 1, ID: "x"})), "", nil, http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncUsesServerChangeTokenInsteadOfClientTimestamp(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
cursor := api.currentSyncToken()
|
||||||
|
clientTimestamp := Timestamp(time.Now().UnixMilli())
|
||||||
|
|
||||||
|
response := api.sync("tablet", SyncRequest{
|
||||||
|
LastSyncTimestamp: clientTimestamp,
|
||||||
|
LastSyncToken: ptrInt64(cursor),
|
||||||
|
Lists: []List{testList("g-list", "Edited offline", t0+20, false)},
|
||||||
|
})
|
||||||
|
if len(response.Lists) != 1 || response.Lists[0].Name != "Edited offline" {
|
||||||
|
t.Fatalf("change with an old client timestamp = %+v, want the updated list", response.Lists)
|
||||||
|
}
|
||||||
|
if response.NextSyncToken <= cursor {
|
||||||
|
t.Fatalf("next sync token = %d, want greater than previous cursor %d", response.NextSyncToken, cursor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncBoundsAndPagesLargeInitialSync(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.mustDo(http.MethodPost, "/api/sync", "phone", map[string]any{}, http.StatusBadRequest)
|
||||||
|
lists := make([]List, 501)
|
||||||
|
for i := range lists {
|
||||||
|
id := fmt.Sprintf("list-%03d", i)
|
||||||
|
lists[i] = testList(id, id, t0+int64(i), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
first := api.sync("phone", SyncRequest{Lists: lists})
|
||||||
|
if len(first.Lists) != syncPageSize || !first.HasMore {
|
||||||
|
t.Fatalf("first page has lists=%d hasMore=%v, want %d and true", len(first.Lists), first.HasMore, syncPageSize)
|
||||||
|
}
|
||||||
|
if first.NextSyncToken <= 0 || first.NextSyncToken >= first.ServerChangeToken {
|
||||||
|
t.Fatalf("first page tokens are next=%d server=%d, want next before server high-water mark", first.NextSyncToken, first.ServerChangeToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
second := api.sync("phone", SyncRequest{LastSyncToken: ptrInt64(first.NextSyncToken)})
|
||||||
|
if len(second.Lists) != 1 || second.HasMore || second.NextSyncToken != second.ServerChangeToken {
|
||||||
|
t.Fatalf("second page has lists=%d hasMore=%v next=%d server=%d, want 1, false, and caught up", len(second.Lists), second.HasMore, second.NextSyncToken, second.ServerChangeToken)
|
||||||
|
}
|
||||||
|
if second.Lists[0].ID == first.Lists[len(first.Lists)-1].ID {
|
||||||
|
t.Fatalf("second page repeated list %q", second.Lists[0].ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPerListMembershipScopesDataAndSync(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
const secondUserID = int64(2)
|
||||||
|
const secondToken = "second-user-device-token"
|
||||||
|
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken(secondToken)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
firstUserLists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||||
|
if len(firstUserLists.Items) != 1 || firstUserLists.Items[0].ID != "g-list" {
|
||||||
|
t.Fatalf("first user lists = %+v, want g-list", firstUserLists.Items)
|
||||||
|
}
|
||||||
|
secondUserLists := decodeBody[PageResponse[List]](t, api.mustDoAs(http.MethodGet, "/api/lists", "", secondToken, nil, http.StatusOK))
|
||||||
|
if len(secondUserLists.Items) != 0 {
|
||||||
|
t.Fatalf("second user lists = %+v, want no access to the first user's list", secondUserLists.Items)
|
||||||
|
}
|
||||||
|
api.mustDoAs(http.MethodGet, "/api/items/g-item/values", "", secondToken, nil, http.StatusNotFound)
|
||||||
|
|
||||||
|
foreignCursor := int64(0)
|
||||||
|
foreignSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken,
|
||||||
|
SyncRequest{LastSyncToken: &foreignCursor}, http.StatusOK))
|
||||||
|
if len(foreignSync.Lists)+len(foreignSync.Fields)+len(foreignSync.Items)+len(foreignSync.ItemValues) != 0 {
|
||||||
|
t.Fatalf("second user's initial sync returned another list's data: %+v", foreignSync)
|
||||||
|
}
|
||||||
|
|
||||||
|
api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
|
||||||
|
LastSyncToken: ptrInt64(0),
|
||||||
|
Lists: []List{testList("g-list", "Overwritten", t0+20, false)},
|
||||||
|
}, http.StatusNotFound)
|
||||||
|
var name string
|
||||||
|
if err := api.db.pool.QueryRow(context.Background(), `SELECT name FROM lists WHERE id = 'g-list'`).Scan(&name); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if name != "Groceries" {
|
||||||
|
t.Fatalf("unauthorized sync changed list name to %q", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
newListSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
|
||||||
|
LastSyncToken: ptrInt64(0),
|
||||||
|
Lists: []List{testList("second-list", "Private", t0+30, false)},
|
||||||
|
}, http.StatusOK))
|
||||||
|
if len(newListSync.Lists) != 1 || newListSync.Lists[0].ID != "second-list" {
|
||||||
|
t.Fatalf("creator's sync response = %+v, want only second-list", newListSync.Lists)
|
||||||
|
}
|
||||||
|
if !hasMembership(t, api.db, secondUserID, "second-list") || hasMembership(t, api.db, testUserID, "second-list") {
|
||||||
|
t.Fatal("new sync list was not private to its creator")
|
||||||
|
}
|
||||||
|
var creator bool
|
||||||
|
if err := api.db.pool.QueryRow(context.Background(), `SELECT is_owner FROM list_memberships WHERE listid = 'second-list' AND user_id = $1`, secondUserID).Scan(&creator); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !creator {
|
||||||
|
t.Fatal("new sync list did not mark its creator as owner")
|
||||||
|
}
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists/second-list", "", nil, http.StatusNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMembershipBackfillPreservesCurrentAPITokenUsers(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('legacy-list', 'Legacy', $1, $1)`, t0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
const secondUserID = int64(2)
|
||||||
|
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken("second-user-device-token")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := api.db.backfillListMemberships(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !hasMembership(t, api.db, testUserID, "legacy-list") || !hasMembership(t, api.db, secondUserID, "legacy-list") {
|
||||||
|
t.Fatal("membership migration did not grant every current API-token user access to the legacy list")
|
||||||
|
}
|
||||||
|
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('new-list', 'New', $1, $1)`, t0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := api.db.withTx(context.Background(), func(tx pgx.Tx) error {
|
||||||
|
return addListOwner(context.Background(), tx, secondUserID, "new-list")
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := api.db.backfillListMemberships(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if hasMembership(t, api.db, testUserID, "new-list") {
|
||||||
|
t.Fatal("re-running membership backfill exposed a creator-owned list to another token user")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasMembership(t *testing.T, db *DB, userID int64, listID string) bool {
|
||||||
|
t.Helper()
|
||||||
|
member, err := hasListMembership(context.Background(), db.pool, userID, listID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return member
|
||||||
|
}
|
||||||
|
|
||||||
func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
||||||
api := newTestAPI(t)
|
api := newTestAPI(t)
|
||||||
push := func(name string, updatedAt int64) {
|
push := func(name string, updatedAt int64) {
|
||||||
@@ -307,9 +590,10 @@ func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
|||||||
func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
||||||
api := newTestAPI(t)
|
api := newTestAPI(t)
|
||||||
api.seedList("phone", "g")
|
api.seedList("phone", "g")
|
||||||
|
seedCursor := api.currentSyncToken()
|
||||||
const kept = "list=0 fields=0/2 items=0/1 values=2"
|
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)}})
|
api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(seedCursor), Lists: []List{testList("g-list", "Groceries", t0+5, true)}})
|
||||||
if got := api.cascadeState("g-list"); got != kept {
|
if got := api.cascadeState("g-list"); got != kept {
|
||||||
t.Fatalf("state after a stale delete = %s, want %s", got, kept)
|
t.Fatalf("state after a stale delete = %s, want %s", got, kept)
|
||||||
}
|
}
|
||||||
@@ -317,7 +601,7 @@ func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
|||||||
t.Fatalf("a stale delete produced %d deleted notification(s)", got)
|
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)}})
|
api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(seedCursor), Lists: []List{testList("g-list", "Groceries", t0+20, true)}})
|
||||||
if got, want := api.cascadeState("g-list"), "list=1 fields=2/2 items=1/1 values=0"; got != want {
|
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)
|
t.Fatalf("state after a newer delete = %s, want %s (fields and items soft-deleted, values removed)", got, want)
|
||||||
}
|
}
|
||||||
@@ -326,11 +610,11 @@ func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The tombstone travels to other devices, but the REST list read hides it.
|
// The tombstone travels to other devices, but the REST list read hides it.
|
||||||
delta := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 15)})
|
delta := api.sync("phone", SyncRequest{LastSyncToken: ptrInt64(seedCursor)})
|
||||||
if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted {
|
if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted {
|
||||||
t.Fatalf("delta after the delete = %+v, want the tombstone", delta.Lists)
|
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 {
|
if lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists.Items) != 0 {
|
||||||
t.Fatalf("GET /api/lists = %+v, want the deleted list hidden", lists)
|
t.Fatalf("GET /api/lists = %+v, want the deleted list hidden", lists)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -466,13 +750,14 @@ func TestRESTValueWriteIgnoresAnOlderTimestamp(t *testing.T) {
|
|||||||
func TestWebDataSupportsConditionalRequests(t *testing.T) {
|
func TestWebDataSupportsConditionalRequests(t *testing.T) {
|
||||||
api := newTestAPI(t)
|
api := newTestAPI(t)
|
||||||
api.seedList("phone", "g")
|
api.seedList("phone", "g")
|
||||||
|
server := &Server{db: api.db}
|
||||||
get := func(etag string) *httptest.ResponseRecorder {
|
get := func(etag string) *httptest.ResponseRecorder {
|
||||||
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
||||||
if etag != "" {
|
if etag != "" {
|
||||||
request.Header.Set("If-None-Match", etag)
|
request.Header.Set("If-None-Match", etag)
|
||||||
}
|
}
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
api.mux.ServeHTTP(recorder, request)
|
server.writeWebData(recorder, request, testUserID)
|
||||||
return recorder
|
return recorder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -86,6 +86,7 @@ type ItemValue struct {
|
|||||||
|
|
||||||
type SyncRequest struct {
|
type SyncRequest struct {
|
||||||
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
||||||
|
LastSyncToken *int64 `json:"lastSyncToken"`
|
||||||
Lists []List `json:"lists"`
|
Lists []List `json:"lists"`
|
||||||
Fields []Field `json:"fields"`
|
Fields []Field `json:"fields"`
|
||||||
Items []Item `json:"items"`
|
Items []Item `json:"items"`
|
||||||
@@ -100,6 +101,15 @@ type SyncResponse struct {
|
|||||||
ItemValues []ItemValue `json:"itemValues"`
|
ItemValues []ItemValue `json:"itemValues"`
|
||||||
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
||||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||||
|
ServerChangeToken int64 `json:"serverChangeToken"`
|
||||||
|
NextSyncToken int64 `json:"nextSyncToken"`
|
||||||
|
HasMore bool `json:"hasMore"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PageResponse[T any] struct {
|
||||||
|
Items []T `json:"items"`
|
||||||
|
NextCursor string `json:"nextCursor"`
|
||||||
|
HasMore bool `json:"hasMore"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type OrphanValue struct {
|
type OrphanValue struct {
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errListAccessDenied = errors.New("list access denied")
|
||||||
|
errCellIdentityMismatch = errors.New("item and field belong to different lists")
|
||||||
|
)
|
||||||
|
|
||||||
|
type rowQueryer interface {
|
||||||
|
QueryRow(context.Context, string, ...any) pgx.Row
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasListMembership(ctx context.Context, queryer rowQueryer, userID int64, listID string) (bool, error) {
|
||||||
|
var member bool
|
||||||
|
err := queryer.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM list_memberships WHERE listid = $1 AND user_id = $2)`, listID, userID).Scan(&member)
|
||||||
|
return member, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func authorizeList(ctx context.Context, queryer rowQueryer, userID int64, listID string, allowCreate bool) (bool, error) {
|
||||||
|
if userID <= 0 || listID == "" {
|
||||||
|
return false, errListAccessDenied
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, queryer, userID, listID)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if member {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
var exists bool
|
||||||
|
if err := queryer.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM lists WHERE id = $1)`, listID).Scan(&exists); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if exists || !allowCreate {
|
||||||
|
return false, errListAccessDenied
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func addListOwner(ctx context.Context, tx pgx.Tx, userID int64, listID string) error {
|
||||||
|
_, err := tx.Exec(ctx, `INSERT INTO list_memberships (listid, user_id, is_owner) VALUES ($1, $2, TRUE) ON CONFLICT (listid, user_id) DO NOTHING`, listID, userID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) requireListMembership(w http.ResponseWriter, r *http.Request, listID string) bool {
|
||||||
|
member, err := hasListMembership(r.Context(), s.db.pool, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
writeJSONError(w, http.StatusInternalServerError, "Failed to authorize list")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultPageSize = 200
|
||||||
|
maxPageSize = 500
|
||||||
|
)
|
||||||
|
|
||||||
|
type pageCursor struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Key int64 `json:"key"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type pageRequest struct {
|
||||||
|
Limit int
|
||||||
|
Cursor *pageCursor
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePageRequest(r *http.Request, kind string) (pageRequest, error) {
|
||||||
|
page := pageRequest{Limit: defaultPageSize}
|
||||||
|
if rawLimit := r.URL.Query().Get("limit"); rawLimit != "" {
|
||||||
|
limit, err := strconv.Atoi(rawLimit)
|
||||||
|
if err != nil || limit < 1 || limit > maxPageSize {
|
||||||
|
return pageRequest{}, fmt.Errorf("limit must be between 1 and %d", maxPageSize)
|
||||||
|
}
|
||||||
|
page.Limit = limit
|
||||||
|
}
|
||||||
|
if rawCursor := r.URL.Query().Get("cursor"); rawCursor != "" {
|
||||||
|
decoded, err := base64.RawURLEncoding.DecodeString(rawCursor)
|
||||||
|
if err != nil {
|
||||||
|
return pageRequest{}, errors.New("cursor is invalid")
|
||||||
|
}
|
||||||
|
var cursor pageCursor
|
||||||
|
if err := json.Unmarshal(decoded, &cursor); err != nil || cursor.Kind != kind || cursor.ID == "" {
|
||||||
|
return pageRequest{}, errors.New("cursor is invalid")
|
||||||
|
}
|
||||||
|
page.Cursor = &cursor
|
||||||
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestPage(w http.ResponseWriter, r *http.Request, kind string) (pageRequest, bool) {
|
||||||
|
page, err := parsePageRequest(r, kind)
|
||||||
|
if err != nil {
|
||||||
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return pageRequest{}, false
|
||||||
|
}
|
||||||
|
return page, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodePageCursor(cursor pageCursor) string {
|
||||||
|
encoded, _ := json.Marshal(cursor)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(encoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readPage[T any](rows pgx.Rows, request pageRequest, kind string, scan func(rowScanner) (T, error), key func(T) int64, id func(T) string) (PageResponse[T], error) {
|
||||||
|
defer rows.Close()
|
||||||
|
items := make([]T, 0, request.Limit+1)
|
||||||
|
for rows.Next() {
|
||||||
|
item, err := scan(rows)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[T]{}, err
|
||||||
|
}
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return PageResponse[T]{}, err
|
||||||
|
}
|
||||||
|
hasMore := len(items) > request.Limit
|
||||||
|
if hasMore {
|
||||||
|
items = items[:request.Limit]
|
||||||
|
}
|
||||||
|
response := PageResponse[T]{Items: items, HasMore: hasMore}
|
||||||
|
if hasMore {
|
||||||
|
last := items[len(items)-1]
|
||||||
|
response.NextCursor = encodePageCursor(pageCursor{Kind: kind, Key: key(last), ID: id(last)})
|
||||||
|
}
|
||||||
|
return response, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func addPageCursor(conditions *[]string, args *[]any, column string, direction string, cursor *pageCursor) {
|
||||||
|
if cursor == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
*args = append(*args, cursor.Key)
|
||||||
|
keyParam := len(*args)
|
||||||
|
*args = append(*args, cursor.ID)
|
||||||
|
idParam := len(*args)
|
||||||
|
comparison := ">"
|
||||||
|
if direction == "desc" {
|
||||||
|
comparison = "<"
|
||||||
|
}
|
||||||
|
*conditions = append(*conditions, fmt.Sprintf("(%s %s $%d OR (%s = $%d AND id > $%d))", column, comparison, keyParam, column, keyParam, idParam))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryListPage(ctx context.Context, userID int64, includeDeleted bool, request pageRequest) (PageResponse[List], error) {
|
||||||
|
conditions := make([]string, 0, 3)
|
||||||
|
args := make([]any, 0, 4)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = lists.id AND m.user_id = $%d)", len(args)))
|
||||||
|
if !includeDeleted {
|
||||||
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
|
}
|
||||||
|
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + listColumns + ` FROM lists`
|
||||||
|
if len(conditions) > 0 {
|
||||||
|
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||||
|
}
|
||||||
|
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[List]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "lists", scanList, func(item List) int64 { return int64(item.UpdatedAt) }, func(item List) string { return item.ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryFieldsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Field], error) {
|
||||||
|
conditions := make([]string, 0, 4)
|
||||||
|
args := make([]any, 0, 5)
|
||||||
|
if !includeDeleted {
|
||||||
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
|
}
|
||||||
|
args = append(args, listID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = fields.listid AND m.user_id = $%d)", len(args)))
|
||||||
|
addPageCursor(&conditions, &args, `"order"`, "asc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + fieldColumns + ` FROM fields WHERE ` + strings.Join(conditions, " AND ")
|
||||||
|
query += fmt.Sprintf(` ORDER BY "order" ASC, id ASC LIMIT $%d`, len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[Field]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "fields", scanField, func(item Field) int64 { return int64(item.Order) }, func(item Field) string { return item.ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryItemsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Item], error) {
|
||||||
|
conditions := make([]string, 0, 4)
|
||||||
|
args := make([]any, 0, 5)
|
||||||
|
if !includeDeleted {
|
||||||
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
|
}
|
||||||
|
args = append(args, listID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = items.listid AND m.user_id = $%d)", len(args)))
|
||||||
|
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + itemColumns + ` FROM items WHERE ` + strings.Join(conditions, " AND ")
|
||||||
|
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[Item]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "items", scanItem, func(item Item) int64 { return int64(item.UpdatedAt) }, func(item Item) string { return item.ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryValuesPage(ctx context.Context, userID int64, itemID string, request pageRequest) (PageResponse[ItemValue], error) {
|
||||||
|
conditions := make([]string, 0, 2)
|
||||||
|
args := make([]any, 0, 4)
|
||||||
|
args = append(args, itemID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("itemid = $%d", len(args)))
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM items i JOIN list_memberships m ON m.listid = i.listid WHERE i.id = item_values.itemid AND m.user_id = $%d)", len(args)))
|
||||||
|
addPageCursor(&conditions, &args, "updatedat", "asc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + valueColumns + ` FROM item_values WHERE ` + strings.Join(conditions, " AND ")
|
||||||
|
query += fmt.Sprintf(" ORDER BY updatedat ASC, id ASC LIMIT $%d", len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[ItemValue]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "values", scanItemValue, func(item ItemValue) int64 { return int64(item.UpdatedAt) }, func(item ItemValue) string { return item.ID })
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParsePageRequest(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
query string
|
||||||
|
wantLimit int
|
||||||
|
wantCursor *pageCursor
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "defaults", wantLimit: defaultPageSize},
|
||||||
|
{name: "custom limit", query: "limit=17", wantLimit: 17},
|
||||||
|
{name: "maximum limit", query: "limit=500", wantLimit: 500},
|
||||||
|
{name: "zero limit", query: "limit=0", wantErr: true},
|
||||||
|
{name: "oversized limit", query: "limit=501", wantErr: true},
|
||||||
|
{name: "invalid limit", query: "limit=large", wantErr: true},
|
||||||
|
{
|
||||||
|
name: "cursor",
|
||||||
|
query: "cursor=" + encodePageCursor(pageCursor{Kind: "lists", Key: 123, ID: "list-1"}),
|
||||||
|
wantLimit: defaultPageSize,
|
||||||
|
wantCursor: &pageCursor{Kind: "lists", Key: 123, ID: "list-1"},
|
||||||
|
},
|
||||||
|
{name: "malformed cursor", query: "cursor=not-a-cursor", wantErr: true},
|
||||||
|
{
|
||||||
|
name: "cursor for another collection",
|
||||||
|
query: "cursor=" + encodePageCursor(pageCursor{Kind: "items", Key: 123, ID: "item-1"}),
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
request := httptest.NewRequest("GET", "/api/lists?"+test.query, nil)
|
||||||
|
got, err := parsePageRequest(request, "lists")
|
||||||
|
if (err != nil) != test.wantErr {
|
||||||
|
t.Fatalf("parsePageRequest() error = %v, wantErr %v", err, test.wantErr)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got.Limit != test.wantLimit {
|
||||||
|
t.Fatalf("limit = %d, want %d", got.Limit, test.wantLimit)
|
||||||
|
}
|
||||||
|
if test.wantCursor == nil {
|
||||||
|
if got.Cursor != nil {
|
||||||
|
t.Fatalf("cursor = %+v, want none", got.Cursor)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got.Cursor == nil || *got.Cursor != *test.wantCursor {
|
||||||
|
t.Fatalf("cursor = %+v, want %+v", got.Cursor, test.wantCursor)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+177
-28
@@ -2,8 +2,10 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sort"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
@@ -12,6 +14,7 @@ import (
|
|||||||
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
|
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
|
||||||
// (DATABASE_MAX_CONNS defaults to 20), so syncs cannot hold every connection.
|
// (DATABASE_MAX_CONNS defaults to 20), so syncs cannot hold every connection.
|
||||||
const maxConcurrentSyncs = 4
|
const maxConcurrentSyncs = 4
|
||||||
|
const syncPageSize = 500
|
||||||
|
|
||||||
func syncMaxFutureSkew() int64 {
|
func syncMaxFutureSkew() int64 {
|
||||||
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
||||||
@@ -48,11 +51,11 @@ func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
|
|||||||
|
|
||||||
// valueReferences returns the list ID of each field and the existence of each
|
// valueReferences returns the list ID of each field and the existence of each
|
||||||
// item that the values refer to, using one statement per table.
|
// item that the values refer to, using one statement per table.
|
||||||
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]bool, error) {
|
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]string, error) {
|
||||||
fieldLists := make(map[string]string)
|
fieldLists := make(map[string]string)
|
||||||
existingItems := make(map[string]bool)
|
itemLists := make(map[string]string)
|
||||||
if len(values) == 0 {
|
if len(values) == 0 {
|
||||||
return fieldLists, existingItems, nil
|
return fieldLists, itemLists, nil
|
||||||
}
|
}
|
||||||
fieldIDs := make([]string, 0, len(values))
|
fieldIDs := make([]string, 0, len(values))
|
||||||
itemIDs := make([]string, 0, len(values))
|
itemIDs := make([]string, 0, len(values))
|
||||||
@@ -77,22 +80,22 @@ func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[st
|
|||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
itemRows, err := tx.Query(ctx, `SELECT id FROM items WHERE id = ANY($1)`, itemIDs)
|
itemRows, err := tx.Query(ctx, `SELECT id, listid FROM items WHERE id = ANY($1)`, itemIDs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
defer itemRows.Close()
|
defer itemRows.Close()
|
||||||
for itemRows.Next() {
|
for itemRows.Next() {
|
||||||
var itemID string
|
var itemID, listID string
|
||||||
if err := itemRows.Scan(&itemID); err != nil {
|
if err := itemRows.Scan(&itemID, &listID); err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
existingItems[itemID] = true
|
itemLists[itemID] = listID
|
||||||
}
|
}
|
||||||
if err := itemRows.Err(); err != nil {
|
if err := itemRows.Err(); err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
return fieldLists, existingItems, nil
|
return fieldLists, itemLists, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// changeEventType names a synced change for the notification feed: a tombstone
|
// changeEventType names a synced change for the notification feed: a tombstone
|
||||||
@@ -110,6 +113,7 @@ func changeEventType(initialSync, deleted bool) string {
|
|||||||
// syncBatch holds what every row of one sync request shares.
|
// syncBatch holds what every row of one sync request shares.
|
||||||
type syncBatch struct {
|
type syncBatch struct {
|
||||||
now int64
|
now int64
|
||||||
|
userID int64
|
||||||
initialSync bool
|
initialSync bool
|
||||||
deviceID string
|
deviceID string
|
||||||
}
|
}
|
||||||
@@ -122,11 +126,20 @@ func (b syncBatch) notify(ctx context.Context, tx pgx.Tx, eventType, entityType,
|
|||||||
// changes nothing, so it triggers no cascade or notification.
|
// changes nothing, so it triggers no cascade or notification.
|
||||||
func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) error {
|
func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) error {
|
||||||
for _, list := range lists {
|
for _, list := range lists {
|
||||||
|
member, err := authorizeList(ctx, tx, batch.userID, list.ID, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), batch.now)
|
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), batch.now)
|
||||||
applied, err := upsertList(ctx, tx, list, createdAt, updatedAt)
|
applied, err := upsertList(ctx, tx, list, createdAt, updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if !member {
|
||||||
|
if err := addListOwner(ctx, tx, batch.userID, list.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
if !applied {
|
if !applied {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -141,8 +154,33 @@ func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) e
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ensureEntityList(ctx context.Context, tx pgx.Tx, table, id, listID string) error {
|
||||||
|
var storedListID string
|
||||||
|
err := tx.QueryRow(ctx, `SELECT listid FROM `+table+` WHERE id = $1`, id).Scan(&storedListID)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if storedListID != listID {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
|
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
|
||||||
for _, field := range fields {
|
for _, field := range fields {
|
||||||
|
if err := ensureEntityList(ctx, tx, "fields", field.ID, field.ListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, tx, batch.userID, field.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
|
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
|
||||||
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
|
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -164,6 +202,16 @@ func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch
|
|||||||
|
|
||||||
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
|
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
|
||||||
for _, item := range items {
|
for _, item := range items {
|
||||||
|
if err := ensureEntityList(ctx, tx, "items", item.ID, item.ListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, tx, batch.userID, item.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
|
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
|
||||||
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
|
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -189,7 +237,7 @@ func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncB
|
|||||||
orphans := make([]OrphanValue, 0)
|
orphans := make([]OrphanValue, 0)
|
||||||
// Resolve the fields and items the values refer to once per request, not once
|
// Resolve the fields and items the values refer to once per request, not once
|
||||||
// per value.
|
// per value.
|
||||||
fieldLists, existingItems, err := valueReferences(ctx, tx, values)
|
fieldLists, itemLists, err := valueReferences(ctx, tx, values)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -201,8 +249,16 @@ func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncB
|
|||||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
member, err := hasListMembership(ctx, tx, batch.userID, listID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return nil, errListAccessDenied
|
||||||
|
}
|
||||||
|
|
||||||
if !existingItems[value.ItemID] {
|
itemListID, itemExists := itemLists[value.ItemID]
|
||||||
|
if !itemExists {
|
||||||
if _, err := tx.Exec(ctx, `
|
if _, err := tx.Exec(ctx, `
|
||||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||||
VALUES ($1, $2, $3, $3, 0)
|
VALUES ($1, $2, $3, $3, 0)
|
||||||
@@ -211,7 +267,17 @@ func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncB
|
|||||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
existingItems[value.ItemID] = true
|
itemLists[value.ItemID] = listID
|
||||||
|
} else if itemListID != listID {
|
||||||
|
itemMember, err := hasListMembership(ctx, tx, batch.userID, itemListID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !itemMember {
|
||||||
|
return nil, errListAccessDenied
|
||||||
|
}
|
||||||
|
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "itemFieldListMismatch"})
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
applied, err := upsertValue(ctx, tx, value, updatedAt)
|
applied, err := upsertValue(ctx, tx, value, updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -239,27 +305,104 @@ func applySyncRequest(ctx context.Context, tx pgx.Tx, request SyncRequest, batch
|
|||||||
return applyValues(ctx, tx, request.ItemValues, batch)
|
return applyValues(ctx, tx, request.ItemValues, batch)
|
||||||
}
|
}
|
||||||
|
|
||||||
// changesSince reads what a device has to pull: everything when since is nil,
|
type syncChange struct {
|
||||||
// otherwise the rows updated at or after it. The caller adds the orphan list and
|
token int64
|
||||||
// the server timestamp.
|
kind string
|
||||||
func (d *DB) changesSince(ctx context.Context, since *int64) (SyncResponse, error) {
|
value any
|
||||||
lists, err := d.queryLists(ctx, true, since)
|
}
|
||||||
|
|
||||||
|
type trailingTokenScanner struct {
|
||||||
|
row rowScanner
|
||||||
|
token int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *trailingTokenScanner) Scan(dest ...any) error {
|
||||||
|
return s.row.Scan(append(dest, &s.token)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// changesSince returns a bounded page from one repeatable-read snapshot. Each
|
||||||
|
// data write takes the clock row lock before touching a row, so a later commit
|
||||||
|
// cannot publish a lower token than a cursor already returned to a device.
|
||||||
|
func (d *DB) changesSince(ctx context.Context, userID int64, cursor int64) (SyncResponse, error) {
|
||||||
|
tx, err := d.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return SyncResponse{}, err
|
return SyncResponse{}, err
|
||||||
}
|
}
|
||||||
fields, err := d.queryFields(ctx, true, since, "")
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
var serverToken int64
|
||||||
|
if err := tx.QueryRow(ctx, `SELECT token FROM collabtable_sync_clock WHERE id = 1`).Scan(&serverToken); err != nil {
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
if cursor > serverToken {
|
||||||
|
cursor = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
queries := []struct {
|
||||||
|
kind string
|
||||||
|
stmt string
|
||||||
|
scan func(rowScanner) (any, error)
|
||||||
|
}{
|
||||||
|
{kind: "list", stmt: `SELECT lists.id, lists.name, lists.createdat, lists.updatedat, COALESCE(lists.isdeleted, 0), lists.change_token FROM lists JOIN list_memberships m ON m.listid = lists.id WHERE m.user_id = $1 AND lists.change_token > $2 ORDER BY lists.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanList(row) }},
|
||||||
|
{kind: "field", stmt: `SELECT fields.id, fields.name, fields.fieldtype, COALESCE(fields.fieldoptions, ''), COALESCE(fields.alignment, 'start'), fields.listid, fields."order", fields.createdat, fields.updatedat, COALESCE(fields.isdeleted, 0), fields.change_token FROM fields JOIN list_memberships m ON m.listid = fields.listid WHERE m.user_id = $1 AND fields.change_token > $2 ORDER BY fields.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanField(row) }},
|
||||||
|
{kind: "item", stmt: `SELECT items.id, items.listid, items.createdat, items.updatedat, COALESCE(items.isdeleted, 0), items.change_token FROM items JOIN list_memberships m ON m.listid = items.listid WHERE m.user_id = $1 AND items.change_token > $2 ORDER BY items.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanItem(row) }},
|
||||||
|
{kind: "value", stmt: `SELECT item_values.id, item_values.itemid, item_values.fieldid, COALESCE(item_values.value, ''), item_values.updatedat, item_values.change_token FROM item_values JOIN items i ON i.id = item_values.itemid JOIN list_memberships m ON m.listid = i.listid WHERE m.user_id = $1 AND item_values.change_token > $2 ORDER BY item_values.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanItemValue(row) }},
|
||||||
|
}
|
||||||
|
changes := make([]syncChange, 0, syncPageSize*2)
|
||||||
|
for _, query := range queries {
|
||||||
|
rows, err := tx.Query(ctx, query.stmt, userID, cursor, syncPageSize+1)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return SyncResponse{}, err
|
return SyncResponse{}, err
|
||||||
}
|
}
|
||||||
items, err := d.queryItems(ctx, true, since, "")
|
for rows.Next() {
|
||||||
|
scanner := trailingTokenScanner{row: rows}
|
||||||
|
value, err := query.scan(&scanner)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
rows.Close()
|
||||||
return SyncResponse{}, err
|
return SyncResponse{}, err
|
||||||
}
|
}
|
||||||
values, err := d.queryValues(ctx, since, "")
|
changes = append(changes, syncChange{token: scanner.token, kind: query.kind, value: value})
|
||||||
if err != nil {
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
rows.Close()
|
||||||
return SyncResponse{}, err
|
return SyncResponse{}, err
|
||||||
}
|
}
|
||||||
return SyncResponse{Lists: lists, Fields: fields, Items: items, ItemValues: values}, nil
|
rows.Close()
|
||||||
|
}
|
||||||
|
sort.Slice(changes, func(i, j int) bool { return changes[i].token < changes[j].token })
|
||||||
|
hasMore := len(changes) > syncPageSize
|
||||||
|
if hasMore {
|
||||||
|
changes = changes[:syncPageSize]
|
||||||
|
}
|
||||||
|
nextToken := serverToken
|
||||||
|
if hasMore {
|
||||||
|
nextToken = changes[len(changes)-1].token
|
||||||
|
}
|
||||||
|
response := SyncResponse{
|
||||||
|
Lists: make([]List, 0),
|
||||||
|
Fields: make([]Field, 0),
|
||||||
|
Items: make([]Item, 0),
|
||||||
|
ItemValues: make([]ItemValue, 0),
|
||||||
|
ServerChangeToken: serverToken,
|
||||||
|
NextSyncToken: nextToken,
|
||||||
|
HasMore: hasMore,
|
||||||
|
}
|
||||||
|
for _, change := range changes {
|
||||||
|
switch change.kind {
|
||||||
|
case "list":
|
||||||
|
response.Lists = append(response.Lists, change.value.(List))
|
||||||
|
case "field":
|
||||||
|
response.Fields = append(response.Fields, change.value.(Field))
|
||||||
|
case "item":
|
||||||
|
response.Items = append(response.Items, change.value.(Item))
|
||||||
|
case "value":
|
||||||
|
response.ItemValues = append(response.ItemValues, change.value.(ItemValue))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -278,10 +421,13 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeDecodeError(w, err, "Invalid sync request")
|
writeDecodeError(w, err, "Invalid sync request")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if request.LastSyncToken == nil || *request.LastSyncToken < 0 {
|
||||||
|
writeJSONError(w, http.StatusBadRequest, "lastSyncToken is required; update the CollabTable client")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
|
batch := syncBatch{now: now, userID: requestUserID(r), initialSync: *request.LastSyncToken == 0, deviceID: requestDeviceID(r, request.DeviceID)}
|
||||||
batch := syncBatch{now: now, initialSync: lastSync == 0, deviceID: requestDeviceID(r, request.DeviceID)}
|
|
||||||
orphans := make([]OrphanValue, 0)
|
orphans := make([]OrphanValue, 0)
|
||||||
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
||||||
if incoming > 0 {
|
if incoming > 0 {
|
||||||
@@ -289,21 +435,24 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
var err error
|
var err error
|
||||||
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
|
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
fmt.Printf("[SYNC] Failed: %v\n", err)
|
fmt.Printf("[SYNC] Failed: %v\n", err)
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var since *int64
|
response, err := s.db.changesSince(r.Context(), requestUserID(r), *request.LastSyncToken)
|
||||||
if lastSync != 0 {
|
|
||||||
since = &lastSync
|
|
||||||
}
|
|
||||||
response, err := s.db.changesSince(r.Context(), since)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||||
return
|
return
|
||||||
|
|||||||
+14
-6
@@ -11,22 +11,26 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
||||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
s.writeWebData(w, r, requestUserID(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) writeWebData(w http.ResponseWriter, r *http.Request, userID int64) {
|
||||||
|
lists, err := s.db.queryLists(r.Context(), userID, false, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fields, err := s.db.queryFields(r.Context(), false, nil, "")
|
fields, err := s.db.queryFields(r.Context(), userID, false, nil, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
items, err := s.db.queryItems(r.Context(), false, nil, "")
|
items, err := s.db.queryItems(r.Context(), userID, false, nil, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
values, err := s.db.queryValues(r.Context(), nil, "")
|
values, err := s.db.queryValues(r.Context(), userID, nil, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
@@ -134,10 +138,14 @@ func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request)
|
|||||||
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
||||||
FROM notifications
|
FROM notifications
|
||||||
WHERE createdat > $1
|
WHERE createdat > $1
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM list_memberships m
|
||||||
|
WHERE m.listid = notifications.listid AND m.user_id = $2
|
||||||
|
)
|
||||||
`
|
`
|
||||||
args := []any{since}
|
args := []any{since, requestUserID(r)}
|
||||||
if deviceID != "" {
|
if deviceID != "" {
|
||||||
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $2)`
|
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $3)`
|
||||||
args = append(args, deviceID)
|
args = append(args, deviceID)
|
||||||
}
|
}
|
||||||
query += ` ORDER BY createdat ASC LIMIT 500`
|
query += ` ORDER BY createdat ASC LIMIT 500`
|
||||||
|
|||||||
Generated
+11
@@ -8,6 +8,7 @@
|
|||||||
"name": "collabtable-server-frontend",
|
"name": "collabtable-server-frontend",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@gabriel20xx/design-tokens": "file:../shared/packages/design-tokens",
|
||||||
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
||||||
"@lucide/svelte": "latest",
|
"@lucide/svelte": "latest",
|
||||||
"@tanstack/svelte-query": "latest",
|
"@tanstack/svelte-query": "latest",
|
||||||
@@ -34,11 +35,17 @@
|
|||||||
"vite": "latest"
|
"vite": "latest"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"../shared/packages/design-tokens": {
|
||||||
|
"name": "@gabriel20xx/design-tokens",
|
||||||
|
"version": "0.1.1",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"../shared/packages/web-ui": {
|
"../shared/packages/web-ui": {
|
||||||
"name": "@gabriel20xx/web-ui",
|
"name": "@gabriel20xx/web-ui",
|
||||||
"version": "0.1.1",
|
"version": "0.1.1",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@gabriel20xx/design-tokens": "0.1.1",
|
||||||
"@lucide/svelte": "1.28.0"
|
"@lucide/svelte": "1.28.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -236,6 +243,10 @@
|
|||||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@gabriel20xx/design-tokens": {
|
||||||
|
"resolved": "../shared/packages/design-tokens",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
"node_modules/@gabriel20xx/web-ui": {
|
"node_modules/@gabriel20xx/web-ui": {
|
||||||
"resolved": "../shared/packages/web-ui",
|
"resolved": "../shared/packages/web-ui",
|
||||||
"link": true
|
"link": true
|
||||||
|
|||||||
@@ -31,6 +31,7 @@
|
|||||||
"vite": "latest"
|
"vite": "latest"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@gabriel20xx/design-tokens": "file:../shared/packages/design-tokens",
|
||||||
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
||||||
"@lucide/svelte": "latest",
|
"@lucide/svelte": "latest",
|
||||||
"@tanstack/svelte-query": "latest",
|
"@tanstack/svelte-query": "latest",
|
||||||
|
|||||||
@@ -120,12 +120,13 @@ export async function logout() {
|
|||||||
// always be the account's current values when the caller isn't actually
|
// always be the account's current values when the caller isn't actually
|
||||||
// changing them. ProfileDialog's form (@gabriel20xx/web-ui) always pre-fills
|
// changing them. ProfileDialog's form (@gabriel20xx/web-ui) always pre-fills
|
||||||
// and requires both fields, so AppShell.svelte's saveProfile always has them
|
// and requires both fields, so AppShell.svelte's saveProfile always has them
|
||||||
// on hand. newPassword remains genuinely optional (omitted/blank leaves the
|
// on hand. When changing the password, the shared ProfileDialog also supplies
|
||||||
// password unchanged).
|
// currentPassword and (when enabled) totpToken for sharedauth's reauthentication
|
||||||
export async function updateCredentials({ newUsername, newEmail, newPassword }) {
|
// check. newPassword remains optional when it is not being changed.
|
||||||
|
export async function updateCredentials({ newUsername, newEmail, newPassword, currentPassword, totpToken }) {
|
||||||
return request('/api/auth/credentials', {
|
return request('/api/auth/credentials', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ username: newUsername, email: newEmail, password: newPassword }),
|
body: JSON.stringify({ username: newUsername, email: newEmail, password: newPassword, currentPassword, totpToken }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { test } from 'node:test';
|
||||||
|
|
||||||
|
import { updateCredentials } from './api.js';
|
||||||
|
|
||||||
|
test('updateCredentials forwards current password and TOTP proof', async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
let captured;
|
||||||
|
globalThis.fetch = async (url, options) => {
|
||||||
|
captured = { url, options };
|
||||||
|
return { ok: true, status: 200, json: async () => ({}) };
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await updateCredentials({
|
||||||
|
newUsername: 'owner',
|
||||||
|
newEmail: 'owner@example.com',
|
||||||
|
newPassword: 'new-password',
|
||||||
|
currentPassword: 'current-password',
|
||||||
|
totpToken: '123456',
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(captured.url, '/api/auth/credentials');
|
||||||
|
assert.deepEqual(JSON.parse(captured.options.body), {
|
||||||
|
username: 'owner',
|
||||||
|
email: 'owner@example.com',
|
||||||
|
password: 'new-password',
|
||||||
|
currentPassword: 'current-password',
|
||||||
|
totpToken: '123456',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('updateCredentials omits reauthentication proof when password is unchanged', async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
let captured;
|
||||||
|
globalThis.fetch = async (_url, options) => {
|
||||||
|
captured = options;
|
||||||
|
return { ok: true, status: 200, json: async () => ({}) };
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await updateCredentials({ newUsername: 'owner', newEmail: 'owner@example.com' });
|
||||||
|
assert.deepEqual(JSON.parse(captured.body), {
|
||||||
|
username: 'owner',
|
||||||
|
email: 'owner@example.com',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -30,6 +30,8 @@
|
|||||||
newUsername: input.username.trim(),
|
newUsername: input.username.trim(),
|
||||||
newEmail: input.email.trim(),
|
newEmail: input.email.trim(),
|
||||||
newPassword: input.password || undefined,
|
newPassword: input.password || undefined,
|
||||||
|
currentPassword: input.currentPassword,
|
||||||
|
totpToken: input.totpToken,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ const frontendTechStack = FRONTEND_TECH_STACK_PACKAGES.flatMap(({ name, pkg }) =
|
|||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [tailwindcss(), sveltekit()],
|
plugins: [tailwindcss(), sveltekit()],
|
||||||
|
resolve: {
|
||||||
|
preserveSymlinks: true,
|
||||||
|
},
|
||||||
define: {
|
define: {
|
||||||
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -3,11 +3,11 @@
|
|||||||
- **Project:** shared
|
- **Project:** shared
|
||||||
- **Path:** /workspace/Personal/Web/shared
|
- **Path:** /workspace/Personal/Web/shared
|
||||||
- **Analyzed:** 2026-10-16
|
- **Analyzed:** 2026-10-16
|
||||||
- **Commit:** 5216031 on main
|
- **Commit:** 22887fe on main
|
||||||
- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. Findings reflect the working tree.
|
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
|
||||||
- **Stack:** Go 1.25 (`backend/`, module `repos.gfranz.ch/Gabriel20xx/shared/backend`, pgx, chi, coder/websocket, goose); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; PowerShell and Node scripts; Gitea and GitHub Actions. No Dockerfile, compose file or `.dockerignore` exists in the repo.
|
- **Stack:** Go 1.25 (`backend/`, module `repos.gfranz.ch/Gabriel20xx/shared/backend`, pgx, chi, coder/websocket, goose); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; PowerShell and Node scripts; Gitea and GitHub Actions. No Dockerfile, compose file or `.dockerignore` exists in the repo.
|
||||||
- **Scope:** This is a shared library consumed by other projects (vendored snapshot), not an application. Read: all first-party Go packages except `backend/auth/*` and `backend/config` (reviewed in a separate pass), the Node, Python and Java AuthGuard clients and stores, the web-ui components that perform I/O or timers, root manifests, `.github` and `.gitea` workflows, and `scripts/`. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies (used only for coverage notes). Paths below are relative to the repo root. Backend findings come from read-only static review passes; the highest-severity citations were re-checked in the code. Nothing was built, run or profiled.
|
- **Scope:** This is a shared library consumed by other projects (vendored snapshot), not an application. Read: all first-party Go packages except `backend/auth/*` and `backend/config` (reviewed in a separate pass), the Node, Python and Java AuthGuard clients and stores, the web-ui components that perform I/O or timers, root manifests, `.github` and `.gitea` workflows, and `scripts/`. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies (used only for coverage notes). Paths below are relative to the repo root. Backend findings come from read-only static review passes; the highest-severity citations were re-checked in the code. Nothing was built, run or profiled.
|
||||||
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). Second Medium pass: P-002 fixed.
|
- **Updated:** 2026-10-20 — the two-second session-validation cache remains enabled by owner decision; code comments and README now state its revocation window and same-client logout behavior.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -92,5 +92,5 @@ The auth code has no obvious SQL N+1 outside the playlist reorder path, and most
|
|||||||
- **Docker:** No Dockerfile, compose file or `.dockerignore` exists in this repository, so image size, multi-stage builds and base-image checks do not apply here. Consumer projects that build images from the vendored snapshot should be reviewed separately.
|
- **Docker:** No Dockerfile, compose file or `.dockerignore` exists in this repository, so image size, multi-stage builds and base-image checks do not apply here. Consumer projects that build images from the vendored snapshot should be reviewed separately.
|
||||||
- **Frontend checks:** No whole-library imports were found; `@lucide/svelte` is imported by name in every component. No `{@html}`, unbounded caches or leaked intervals were found in the web-ui, and the timers and listeners in `MediaPlayer`, `MediaPlayerControls`, `StatusWidget`, `AppShell` and `notifications.svelte.ts` are cleaned up. `shared-styles.css` (1134 lines, about 21 KB) is loaded in full by consumers. As a component library it has no route-level code-splitting, which is expected rather than a defect. Four of seven `{#each}` blocks in the components are keyed; the remaining ones are listed under quality findings.
|
- **Frontend checks:** No whole-library imports were found; `@lucide/svelte` is imported by name in every component. No `{@html}`, unbounded caches or leaked intervals were found in the web-ui, and the timers and listeners in `MediaPlayer`, `MediaPlayerControls`, `StatusWidget`, `AppShell` and `notifications.svelte.ts` are cleaned up. `shared-styles.css` (1134 lines, about 21 KB) is loaded in full by consumers. As a component library it has no route-level code-splitting, which is expected rather than a defect. Four of seven `{#each}` blocks in the components are keyed; the remaining ones are listed under quality findings.
|
||||||
- **HTTP caching and compression:** Not applicable to the library code; the backends are API services and the static styles are shipped to consumers' own build pipelines.
|
- **HTTP caching and compression:** Not applicable to the library code; the backends are API services and the static styles are shipped to consumers' own build pipelines.
|
||||||
- **Not verified:** No query plans (no database access), no benchmarks or profiling, no build or test runs. Counts and ordering are based on code reading only.
|
- **Not verified:** No query plans (no database access), benchmarks or profiling. Node, Python and web-ui test suites and the web-ui package build passed; Go and Java checks were unavailable because their toolchains are absent.
|
||||||
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (used for versions only).
|
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (used for versions only).
|
||||||
@@ -3,11 +3,11 @@
|
|||||||
- **Project:** shared
|
- **Project:** shared
|
||||||
- **Path:** /workspace/Personal/Web/shared
|
- **Path:** /workspace/Personal/Web/shared
|
||||||
- **Analyzed:** 2026-10-16
|
- **Analyzed:** 2026-10-16
|
||||||
- **Commit:** 5216031 on main
|
- **Commit:** 22887fe on main
|
||||||
- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. Findings reflect the working tree (for example, README component count, Q-014).
|
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
|
||||||
- **Stack:** Go 1.25 (`backend/`); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`, ruff configured); Java 8 target with Jackson and JUnit 5 (`packages/java-backend`); Svelte 5 and TypeScript with svelte-check (`packages/web-ui`); PowerShell and Node build and sync scripts; Gitea and GitHub Actions.
|
- **Stack:** Go 1.25 (`backend/`); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`, ruff configured); Java 8 target with Jackson and JUnit 5 (`packages/java-backend`); Svelte 5 and TypeScript with svelte-check (`packages/web-ui`); PowerShell and Node build and sync scripts; Gitea and GitHub Actions.
|
||||||
- **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings come from read-only static review passes; the highest-impact citations were re-checked in the code. No lint, build or test was executed.
|
- **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings came from read-only static review passes; the highest-impact citations were re-checked in the code. The shared Node, Python and web-ui suites, web-ui package build and checks were run during this continuation; Go and Java toolchains are absent.
|
||||||
- **Updated:** 2026-10-19 — Medium findings handled in the working tree (not committed): Q-004 and Q-009 fixed; Q-008 stays open for the cross-runtime hash-format decision.
|
- **Updated:** 2026-10-20 — Q-008 fixed in the working tree: all password writers use bcrypt cost 12, legacy PBKDF2 verifies and upgrades after a successful login, and shared contract fixtures cover all runtimes. Node tests, web-ui tests, package build, Svelte check and Node syntax check passed.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
|
|||||||
- **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately.
|
- **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately.
|
||||||
- **Impact:** A service behaves differently depending on which runtime serves it, and a password hash can reach an API response in Python.
|
- **Impact:** A service behaves differently depending on which runtime serves it, and a password hash can reach an API response in Python.
|
||||||
- **Recommendation:** Standardise the hash format (or rehash on login), strip `password_hash` from every DTO, align the retry policy and the middleware failure modes, and add cross-language contract tests that run the same fixtures against each client.
|
- **Recommendation:** Standardise the hash format (or rehash on login), strip `password_hash` from every DTO, align the retry policy and the middleware failure modes, and add cross-language contract tests that run the same fixtures against each client.
|
||||||
- **Status:** Open 2026-10-19 — partly fixed: Python list and create payloads no longer return `password_hash`, Python startup retries only transient connection errors like Node, the Java middleware answers 401 when no base URL is set, and Java `Totp` compares with `MessageDigest.isEqual`. Node, Python and Go version their password hashes and rewrite older ones on login (see S-013). New in this pass: `contract/auth-contract.json` holds shared fixtures (password hashes per runtime, RFC 6238 TOTP cases, client-address cases) that the Go, Node and Python suites all load (`backend/auth/contract_test.go`, `packages/node-backend/test/contract.test.js`, `packages/python-backend/tests/test_contract.py`); it records the remaining hash divergence on purpose. Running it found Python `verify_totp` raising `TypeError` on a six-digit token written in non-ASCII digits where Go and Node answer false, fixed in `totp.py`. The Node and Python stores now share Go's guards (see S-016), and Python refuses passwords over 72 bytes like Go. Still open: Node (PBKDF2) writes a different hash format into `auth_users.password_hash` than Python and Go (bcrypt); Node cannot verify bcrypt, and Python and Go cannot verify Node's. Decision needed: pick one write scheme for all runtimes (or accept a new bcrypt dependency in Node), because letting one runtime verify another's format would make a shared database ping-pong between schemes on re-key. The Java client is not in the contract tests: no JDK or Maven is available here to compile them. Files: `contract/auth-contract.json`, `backend/auth/contract_test.go`, `packages/node-backend/test/contract.test.js`, `packages/python-backend/tests/test_contract.py`, `packages/python-backend/src/shared_backend/totp.py`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/src/shared_backend/postgres.py`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java`, `packages/node-backend/src/auth.js`, `backend/auth/password.go`.
|
- **Status:** Fixed 2026-10-20 — Node now writes the same prefixed bcrypt cost-12 scheme as Go and Python, and each runtime verifies current/legacy bcrypt plus both legacy Node PBKDF2 formats. Successful legacy verification returns an upgraded hash; AuthGuard conditionally persists that upgrade after a successful login. Long legacy PBKDF2 passwords use the explicit `bcrypt-sha256$` scheme to avoid bcrypt truncation, while new passwords over 72 bytes are rejected. The Java AuthClient does not create or verify stored password hashes. Node also depends on `bcryptjs` to share the scheme. The shared contract covers current, low-cost, malformed, legacy and over-limit cases. Files: `backend/auth/password.go`, `backend/auth/contract_test.go`, `Central/AuthGuard/internal/httpapi/{auth.go,server.go,server_test.go}`, `packages/node-backend/{package.json,src/auth.js,test/auth.test.js,test/contract.test.js}`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/tests/{test_core.py,test_contract.py}`, `contract/auth-contract.json`.
|
||||||
|
|
||||||
### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium** · Fixed
|
### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium** · Fixed
|
||||||
- **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script)
|
- **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script)
|
||||||
@@ -132,6 +132,6 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
|
|||||||
- **Checked, clean:** No `TODO`, `FIXME`, `HACK` or `XXX` markers in first-party non-test code. No `any`, `@ts-ignore`, `@ts-expect-error` or `svelte-ignore` in `packages/web-ui/src`. No `{@html}`, `innerHTML`, `eval` or `new Function` in the web-ui or scripts. External links use `rel="noreferrer"`. Timers and document listeners are cleaned up in `StatusWidget`, `MediaPlayer`, `MediaPlayerControls`, `PrimaryColorPicker` and `notifications.svelte.ts`.
|
- **Checked, clean:** No `TODO`, `FIXME`, `HACK` or `XXX` markers in first-party non-test code. No `any`, `@ts-ignore`, `@ts-expect-error` or `svelte-ignore` in `packages/web-ui/src`. No `{@html}`, `innerHTML`, `eval` or `new Function` in the web-ui or scripts. External links use `rel="noreferrer"`. Timers and document listeners are cleaned up in `StatusWidget`, `MediaPlayer`, `MediaPlayerControls`, `PrimaryColorPicker` and `notifications.svelte.ts`.
|
||||||
- **Checked, consistent:** Go code is gofmt-checked and `go vet`-checked in CI. Python code is ruff-checked (`E`, `F`, `I`). Node syntax is checked for `packages/node-backend`. Parameterised SQL is used across the Go, Node and Python stores.
|
- **Checked, consistent:** Go code is gofmt-checked and `go vet`-checked in CI. Python code is ruff-checked (`E`, `F`, `I`). Node syntax is checked for `packages/node-backend`. Parameterised SQL is used across the Go, Node and Python stores.
|
||||||
- **Duplication by design:** The AuthGuard client exists in four languages on purpose. Q-008 covers where the behaviour has drifted.
|
- **Duplication by design:** The AuthGuard client exists in four languages on purpose. Q-008 covers where the behaviour has drifted.
|
||||||
- **Not run:** No lint, build, test, `go vet`, `ruff`, `svelte-check` or `npm` command was executed. All findings are from reading the code.
|
- **Verification:** Node backend: 73 tests passed. Python backend: 122 tests and Ruff passed. Web-ui: 29 tests, package build, `svelte-check`, `npm run lint`, and `format:check` passed. Go test/gofmt and Java tests were not run because Go and Java tools are absent. No database-backed integration test ran.
|
||||||
- **Not verified:** Whether consumers depend on the removed `UserManagement` export or the `MediaPlayerControls` barrel removal (the changeset says only AuthGuard used it). Whether the `packages/media-shared-assets` and `media-backend` paths in history were ever shipped.
|
- **Not verified:** Whether consumers depend on the removed `UserManagement` export or the `MediaPlayerControls` barrel removal (the changeset says only AuthGuard used it). Whether the `packages/media-shared-assets` and `media-backend` paths in history were ever shipped.
|
||||||
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies beyond coverage notes.
|
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies beyond coverage notes.
|
||||||
+6
-2
@@ -82,13 +82,17 @@ These are the complete Svelte component exports from `packages/web-ui/src/lib/in
|
|||||||
| Component | Includes |
|
| Component | Includes |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
|
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
|
||||||
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. |
|
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. Changing a password asks for the current password and, when TOTP is enabled, a current authenticator code; `onSave` receives both proofs in `ProfileUpdateInput`. |
|
||||||
| `TotpSettings` | TOTP status, setup, enable, and disable controls. |
|
| `TotpSettings` | TOTP status, setup, enable, and disable controls. |
|
||||||
|
|
||||||
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update the matching category table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the tables aligned with that barrel file, place each component in the category that matches its primary purpose, and do not add internal or generated components to them.
|
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update the matching category table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the tables aligned with that barrel file, place each component in the category that matches its primary purpose, and do not add internal or generated components to them.
|
||||||
|
|
||||||
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
|
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
|
||||||
|
|
||||||
|
### AuthGuard session validation
|
||||||
|
|
||||||
|
The Go and Python `AuthClient.validate()` helpers cache both valid and invalid session results for two seconds. If a session is revoked directly in AuthGuard, a service using that cache may accept it for up to two more seconds. Calling logout through the same client clears its cached result immediately.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## How consumers actually use this
|
## How consumers actually use this
|
||||||
@@ -134,7 +138,7 @@ go vet ./...
|
|||||||
|
|
||||||
Go tests that need PostgreSQL skip themselves unless a scratch database is named: `DATABASE_URL` for the auth store tests, `SHARED_TEST_DATABASE_URL` for the platform-user, mediacore and migrate tests. They create tables and delete rows, so never point either at a real database. CI runs them against a throwaway PostgreSQL service (`go test -p 1 ./...`).
|
Go tests that need PostgreSQL skip themselves unless a scratch database is named: `DATABASE_URL` for the auth store tests, `SHARED_TEST_DATABASE_URL` for the platform-user, mediacore and migrate tests. They create tables and delete rows, so never point either at a real database. CI runs them against a throwaway PostgreSQL service (`go test -p 1 ./...`).
|
||||||
|
|
||||||
`contract/auth-contract.json` holds fixtures (password hashes, TOTP codes, client addresses) that the Go, Node and Python test suites all load, so the runtimes cannot drift apart unnoticed.
|
`contract/auth-contract.json` holds fixtures (password hashes, TOTP codes, client addresses, and the internal-secret rule: minimum length and example placeholders) that the Go, Node and Python test suites all load, so the runtimes cannot drift apart unnoticed.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -3,11 +3,11 @@
|
|||||||
- **Project:** shared
|
- **Project:** shared
|
||||||
- **Path:** /workspace/Personal/Web/shared
|
- **Path:** /workspace/Personal/Web/shared
|
||||||
- **Analyzed:** 2026-10-16
|
- **Analyzed:** 2026-10-16
|
||||||
- **Commit:** 5216031 on main
|
- **Commit:** 22887fe on main
|
||||||
- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. None of them touches authentication code.
|
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
|
||||||
- **Stack:** Go 1.25 (`backend/`: session proxy, AuthGuard client, websocket sync hub, media core, CarrierNode client, log shipper, Postgres helpers, goose migrations); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; Gitea and GitHub Actions. No Dockerfile is present.
|
- **Stack:** Go 1.25 (`backend/`: session proxy, AuthGuard client, websocket sync hub, media core, CarrierNode client, log shipper, Postgres helpers, goose migrations); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; Gitea and GitHub Actions. No Dockerfile is present.
|
||||||
- **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings come from read-only static review passes, and the highest-severity citations were re-checked in the code. Nothing was built, run, audited or sent to the network.
|
- **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings came from read-only static review passes, and the highest-severity citations were re-checked in the code. Available checks run during this continuation: shared Node/Python/web-ui suites, Svelte check, Node lint, Ruff, formatting and web-ui package build. Go and Java toolchains are absent; no production service or real database was used.
|
||||||
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). Owner decisions 5, 8 and 12 applied in the same working tree (not committed). Second Medium pass: S-009 and S-016 fixed (S-013's heading corrected to Fixed); S-010 and S-011 stay open and name the decisions they need.
|
- **Updated:** 2026-10-20 — shared decisions implemented in the working tree: S-011 fixed; S-010 partly fixed with its undecided session-revocation portion left open. Available Node and web-ui checks pass; Python, Go and Java verification limits are recorded below.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
|---|---:|---:|---:|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 1 | 1 | 0 | 0 |
|
| Critical | 1 | 1 | 0 | 0 |
|
||||||
| High | 3 | 2 | 0 | 1 |
|
| High | 3 | 2 | 0 | 1 |
|
||||||
| Medium | 13 | 11 | 0 | 2 |
|
| Medium | 13 | 12 | 0 | 1 |
|
||||||
| Low | 5 | 0 | 0 | 5 |
|
| Low | 5 | 0 | 0 | 5 |
|
||||||
| Info | 0 | 0 | 0 | 0 |
|
| Info | 0 | 0 | 0 | 0 |
|
||||||
|
|
||||||
@@ -91,14 +91,14 @@ The most serious issue is a Python router route that lets an anonymous caller sw
|
|||||||
- **Description:** A new password is validated and forwarded to AuthGuard without asking for the current password or a TOTP code.
|
- **Description:** A new password is validated and forwarded to AuthGuard without asking for the current password or a TOTP code.
|
||||||
- **Impact:** A stolen or fixated session cookie becomes permanent account takeover, because the attacker can set a new password. Needs verification of whether AuthGuard revokes other sessions on password change.
|
- **Impact:** A stolen or fixated session cookie becomes permanent account takeover, because the attacker can set a new password. Needs verification of whether AuthGuard revokes other sessions on password change.
|
||||||
- **Recommendation:** Require the current password (and a TOTP code when enabled) for password or email changes, and revoke other sessions when the password changes.
|
- **Recommendation:** Require the current password (and a TOTP code when enabled) for password or email changes, and revoke other sessions when the password changes.
|
||||||
- **Status:** Open 2026-10-19 — re-verified, not changed: `UpdateMe` (`backend/auth/proxy.go`) and `update_me` (`authproxy.py`) still forward a new password on the session cookie alone. Decisions needed: (1) require `currentPassword` (and `totpToken` when TOTP is on) whenever `password` is set, checked through an AuthGuard login call or a new AuthGuard endpoint; this changes the request shape that web-ui and every consumer client send; (2) whether a password change revokes the account's other sessions, which AuthGuard owns.
|
- **Status:** Partly fixed 2026-10-20 — the decided rule is implemented: Go and Python self-service profile updates require `currentPassword` for a password change and a TOTP code when enabled; both reauthenticate through AuthGuard, omit proof fields from the managed-user update, and attempt to clear the temporary session. The shared web-ui prompts for and sends those values. No self-service `UpdateMe` route exists in the shared Node or Java clients. Still open: revoking other sessions after a password change is controlled by AuthGuard and has no owner decision. Files: `backend/auth/proxy.go`, `backend/auth/proxy_handlers_test.go`, `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`, `packages/web-ui/src/lib/components/ProfileDialog.svelte`, `packages/web-ui/tests/ProfileDialog.test.ts`.
|
||||||
|
|
||||||
### S-011 · TOTP codes can be replayed within their validity window in every runtime · **Medium** · Open
|
### S-011 · TOTP codes can be replayed within their validity window in every runtime · **Medium** · Open
|
||||||
- **Location:** `backend/auth/totp.go:56` (`VerifyTOTP` returns only a bool and does not report the matched step), `backend/auth/store.go:70-84` (no last-used-step column), `packages/node-backend/src/totp.js:26-53`, `packages/python-backend/src/shared_backend/totp.py:38-66`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:44-88` (per review)
|
- **Location:** `backend/auth/totp.go` and `packages/{node-backend/src/totp.js,python-backend/src/shared_backend/totp.py,java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}` return the matched time step; Go, Node and Python auth stores persist it.
|
||||||
- **Description:** Verification accepts the current and adjacent 30-second steps and records nothing about use. A code that an attacker observes stays valid for about 90 seconds and can be submitted repeatedly within that window.
|
- **Description:** Verification accepts the current and adjacent 30-second steps and records nothing about use. A code that an attacker observes stays valid for about 90 seconds and can be submitted repeatedly within that window.
|
||||||
- **Impact:** A phished or shoulder-surfed code can be reused.
|
- **Impact:** A phished or shoulder-surfed code can be reused.
|
||||||
- **Recommendation:** Return the matched time step, persist `last_used_step` per user, and reject any step less than or equal to it, updating it atomically.
|
- **Recommendation:** Return the matched time step, persist `last_used_step` per user, and reject any step less than or equal to it, updating it atomically.
|
||||||
- **Status:** Open 2026-10-19 — re-verified, not changed. AuthGuard calls the shared `VerifyTOTP` for login, verify and disable (`Central/AuthGuard/internal/httpapi/auth.go`, `totp.go`) and keeps TOTP state in the shared `auth.Store`, so the fix spans this library and AuthGuard. It needs the verifiers to return the matched time step, a `last_used_step` column on `auth_users` (an additive `ADD COLUMN IF NOT EXISTS` in each runtime's schema) advanced atomically with a `WHERE last_used_step < $step` guard, and AuthGuard calling the new API. Decision needed: approve the new column and the semantics change (a code already used inside its window is refused at login), after which the three stores and AuthGuard change together.
|
- **Status:** Fixed 2026-10-20 — verifiers return the matched time step; Go, Node and Python stores add `last_used_step` through additive schema changes and atomically advance it only when the step is newer. AuthGuard consumes steps for login, enrollment and disable, so a code already used in its validity window is refused. Files: `backend/auth/{totp.go,store.go}`, `Central/AuthGuard/internal/httpapi/{auth.go,totp.go,server.go}`, `packages/{node-backend/src/{auth.js,totp.js},python-backend/src/shared_backend/{auth.py,totp.py},java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}`. Node/backend and web-ui checks passed; Go, Java and Python runtime tests could not run in this environment.
|
||||||
|
|
||||||
### S-012 · The Java client parses the authentication decision with unanchored regular expressions · **Medium** · Fixed
|
### S-012 · The Java client parses the authentication decision with unanchored regular expressions · **Medium** · Fixed
|
||||||
- **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review)
|
- **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review)
|
||||||
@@ -178,5 +178,5 @@ The most serious issue is a Python router route that lets an anonymous caller sw
|
|||||||
- **Web UI:** No `{@html}`, `innerHTML`, `eval` or `new Function` was found. External links use `rel="noreferrer"`. `fetch` is used only in `StatusWidget.svelte` (same-origin relative paths with credentials included); auth requests are delegated to the consuming application through callbacks, so CSRF and session handling live in the backend. The primary-color writer builds CSS only from palette values.
|
- **Web UI:** No `{@html}`, `innerHTML`, `eval` or `new Function` was found. External links use `rel="noreferrer"`. `fetch` is used only in `StatusWidget.svelte` (same-origin relative paths with credentials included); auth requests are delegated to the consuming application through callbacks, so CSRF and session handling live in the backend. The primary-color writer builds CSS only from palette values.
|
||||||
- **Checked, no issue found:** SQL is parameterised in the Go, Node and Python stores and in the mediacore queries; dynamic `SET` fragments use fixed column names. Tokens and secrets come from `crypto/rand`, `crypto.randomBytes`, Python `secrets` and `SecureRandom`; no `math/rand`, `Math.random`, `random.` or `java.util.Random` was found. Session tokens are 256-bit and stored as SHA-256 hashes, and no JWT is used. No `eval`, `pickle`, `yaml.load`, `shell=True`, `os.system` or `exec.Command` appears in scope. No `InsecureSkipVerify` on any TLS configuration; the only use is the websocket origin option (S-014). The Go request bodies are capped (512 KB for mediacore, 4 KB for coreconfig, 128 KB for the proxy). Outbound clients have timeouts. Logout clears cookies with `HttpOnly` and `SameSite` in the Python proxy. No CORS configuration or debug mode was found.
|
- **Checked, no issue found:** SQL is parameterised in the Go, Node and Python stores and in the mediacore queries; dynamic `SET` fragments use fixed column names. Tokens and secrets come from `crypto/rand`, `crypto.randomBytes`, Python `secrets` and `SecureRandom`; no `math/rand`, `Math.random`, `random.` or `java.util.Random` was found. Session tokens are 256-bit and stored as SHA-256 hashes, and no JWT is used. No `eval`, `pickle`, `yaml.load`, `shell=True`, `os.system` or `exec.Command` appears in scope. No `InsecureSkipVerify` on any TLS configuration; the only use is the websocket origin option (S-014). The Go request bodies are capped (512 KB for mediacore, 4 KB for coreconfig, 128 KB for the proxy). Outbound clients have timeouts. Logout clears cookies with `HttpOnly` and `SameSite` in the Python proxy. No CORS configuration or debug mode was found.
|
||||||
- **Dependencies (not audited):** No known-vulnerable version is asserted in this report, since no audit tool or network access was used. Versions to confirm: Go `coder/websocket` v1.8.15, `go-chi/chi` v5.3.1, `pgx` v5.10.0, `goose` v3.27.3, `golang.org/x/crypto` v0.54.0 (`backend/go.mod`); Node `pg` 8.22.0 (locked in `package-lock.json`, declared `^8.17.2`); Python `bcrypt>=4.2` and `asyncpg>=0.30` with no upper bounds (`packages/python-backend/pyproject.toml`); Java Jackson 2.18.6, JUnit 5.10.2 (`packages/java-backend/pom.xml`). Run `govulncheck`, `npm audit`, `pip-audit` and an OWASP dependency check.
|
- **Dependencies (not audited):** No known-vulnerable version is asserted in this report, since no audit tool or network access was used. Versions to confirm: Go `coder/websocket` v1.8.15, `go-chi/chi` v5.3.1, `pgx` v5.10.0, `goose` v3.27.3, `golang.org/x/crypto` v0.54.0 (`backend/go.mod`); Node `pg` 8.22.0 (locked in `package-lock.json`, declared `^8.17.2`); Python `bcrypt>=4.2` and `asyncpg>=0.30` with no upper bounds (`packages/python-backend/pyproject.toml`); Java Jackson 2.18.6, JUnit 5.10.2 (`packages/java-backend/pom.xml`). Run `govulncheck`, `npm audit`, `pip-audit` and an OWASP dependency check.
|
||||||
- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. Test bodies were not run, and no server was started.
|
- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. The shared Node (73 tests), Python (122 tests), and web-ui (29 tests) suites were run; Go and Java suites were unavailable because their toolchains are absent. No server was started.
|
||||||
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and `node_modules`.
|
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and `node_modules`.
|
||||||
@@ -21,6 +21,8 @@ type authContract struct {
|
|||||||
Hashes []struct {
|
Hashes []struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Hash string `json:"hash"`
|
Hash string `json:"hash"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
WrongPassword string `json:"wrongPassword"`
|
||||||
Verifies map[string]bool `json:"verifies"`
|
Verifies map[string]bool `json:"verifies"`
|
||||||
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
|
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
|
||||||
} `json:"hashes"`
|
} `json:"hashes"`
|
||||||
@@ -36,6 +38,7 @@ type authContract struct {
|
|||||||
Unix int64 `json:"unix"`
|
Unix int64 `json:"unix"`
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
Secret *string `json:"secret"`
|
Secret *string `json:"secret"`
|
||||||
|
MatchedStep *int64 `json:"matchedStep"`
|
||||||
Valid bool `json:"valid"`
|
Valid bool `json:"valid"`
|
||||||
} `json:"cases"`
|
} `json:"cases"`
|
||||||
} `json:"totp"`
|
} `json:"totp"`
|
||||||
@@ -71,21 +74,29 @@ func TestContractPasswordHashes(t *testing.T) {
|
|||||||
contract := loadContract(t)
|
contract := loadContract(t)
|
||||||
for _, entry := range contract.Password.Hashes {
|
for _, entry := range contract.Password.Hashes {
|
||||||
t.Run(entry.Name, func(t *testing.T) {
|
t.Run(entry.Name, func(t *testing.T) {
|
||||||
if got := VerifyPassword(entry.Hash, contract.Password.Plaintext); got != entry.Verifies["go"] {
|
password := entry.Password
|
||||||
|
if password == "" {
|
||||||
|
password = contract.Password.Plaintext
|
||||||
|
}
|
||||||
|
wrongPassword := entry.WrongPassword
|
||||||
|
if wrongPassword == "" {
|
||||||
|
wrongPassword = contract.Password.WrongPassword
|
||||||
|
}
|
||||||
|
if got := VerifyPassword(entry.Hash, password); got != entry.Verifies["go"] {
|
||||||
t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"])
|
t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"])
|
||||||
}
|
}
|
||||||
if VerifyPassword(entry.Hash, contract.Password.WrongPassword) {
|
if VerifyPassword(entry.Hash, wrongPassword) {
|
||||||
t.Error("VerifyPassword accepted the wrong password")
|
t.Error("VerifyPassword accepted the wrong password")
|
||||||
}
|
}
|
||||||
if want, ok := entry.NeedsUpgrade["go"]; ok {
|
if want, ok := entry.NeedsUpgrade["go"]; ok {
|
||||||
if got := PasswordHashNeedsUpgrade(entry.Hash); got != want {
|
if got := PasswordHashNeedsUpgrade(entry.Hash); got != want {
|
||||||
t.Errorf("PasswordHashNeedsUpgrade = %v, want %v", got, want)
|
t.Errorf("PasswordHashNeedsUpgrade = %v, want %v", got, want)
|
||||||
}
|
}
|
||||||
valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, contract.Password.Plaintext)
|
valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, password)
|
||||||
if err != nil || !valid || (upgraded != "") != want {
|
if err != nil || !valid || (upgraded != "") != want {
|
||||||
t.Errorf("VerifyAndUpgradePassword = %v, upgraded %v, %v; want valid with an upgrade = %v", valid, upgraded != "", err, want)
|
t.Errorf("VerifyAndUpgradePassword = %v, upgraded %v, %v; want valid with an upgrade = %v", valid, upgraded != "", err, want)
|
||||||
}
|
}
|
||||||
if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) || !VerifyPassword(upgraded, contract.Password.Plaintext)) {
|
if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) && !strings.HasPrefix(upgraded, bcryptSHA256Scheme) || !VerifyPassword(upgraded, password)) {
|
||||||
t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded)
|
t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -109,9 +120,19 @@ func TestContractTOTP(t *testing.T) {
|
|||||||
if entry.Secret != nil {
|
if entry.Secret != nil {
|
||||||
secret = *entry.Secret
|
secret = *entry.Secret
|
||||||
}
|
}
|
||||||
if got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0)); got != entry.Valid {
|
step, got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0))
|
||||||
|
if got != entry.Valid {
|
||||||
t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid)
|
t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid)
|
||||||
}
|
}
|
||||||
|
if got {
|
||||||
|
want := entry.Unix / 30
|
||||||
|
if entry.MatchedStep != nil {
|
||||||
|
want = *entry.MatchedStep
|
||||||
|
}
|
||||||
|
if step != want {
|
||||||
|
t.Errorf("VerifyTOTP matched step %d, want %d", step, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"golang.org/x/crypto/pbkdf2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// BcryptCost is kept in one place so all services use the same password
|
// BcryptCost is kept in one place so all services use the same password
|
||||||
@@ -17,9 +23,19 @@ const BcryptCost = 12
|
|||||||
// with "$"). Unprefixed bcrypt hashes from before the prefix still verify and
|
// with "$"). Unprefixed bcrypt hashes from before the prefix still verify and
|
||||||
// are upgraded on login.
|
// are upgraded on login.
|
||||||
const bcryptScheme = "bcrypt$"
|
const bcryptScheme = "bcrypt$"
|
||||||
|
const bcryptSHA256Scheme = "bcrypt-sha256$"
|
||||||
|
|
||||||
|
const (
|
||||||
|
maxPasswordBytes = 72
|
||||||
|
legacyPBKDF2Iterations = 100000
|
||||||
|
maxPBKDF2Iterations = 10000000
|
||||||
|
)
|
||||||
|
|
||||||
// HashPassword returns a versioned password hash suitable for storage.
|
// HashPassword returns a versioned password hash suitable for storage.
|
||||||
func HashPassword(password string) (string, error) {
|
func HashPassword(password string) (string, error) {
|
||||||
|
if len([]byte(password)) > maxPasswordBytes {
|
||||||
|
return "", errors.New("password must be at most 72 bytes")
|
||||||
|
}
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -27,20 +43,38 @@ func HashPassword(password string) (string, error) {
|
|||||||
return bcryptScheme + string(hash), nil
|
return bcryptScheme + string(hash), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// VerifyPassword checks a plaintext password against a stored hash. It accepts
|
// VerifyPassword checks a plaintext password against bcrypt and legacy Node
|
||||||
// hashes from HashPassword and unprefixed bcrypt hashes; any other format
|
// PBKDF2 hashes. A valid legacy hash is rewritten by VerifyAndUpgradePassword.
|
||||||
// fails closed.
|
|
||||||
func VerifyPassword(hash, password string) bool {
|
func VerifyPassword(hash, password string) bool {
|
||||||
|
if bcryptHash, ok := strings.CutPrefix(hash, bcryptSHA256Scheme); ok {
|
||||||
|
digest := sha256.Sum256([]byte(password))
|
||||||
|
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(hex.EncodeToString(digest[:]))) == nil
|
||||||
|
}
|
||||||
|
if iterations, salt, expected, ok := parsePBKDF2Hash(hash); ok {
|
||||||
|
actual := pbkdf2.Key([]byte(password), []byte(salt), iterations, 32, sha256.New)
|
||||||
|
expectedBytes, err := hex.DecodeString(expected)
|
||||||
|
return err == nil && subtle.ConstantTimeCompare(expectedBytes, actual) == 1
|
||||||
|
}
|
||||||
bcryptHash, ok := bcryptHashOf(hash)
|
bcryptHash, ok := bcryptHashOf(hash)
|
||||||
if !ok {
|
if !ok {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
if len([]byte(password)) > maxPasswordBytes {
|
||||||
|
return false
|
||||||
|
}
|
||||||
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(password)) == nil
|
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(password)) == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// PasswordHashNeedsUpgrade reports whether a stored hash is not in the current
|
// PasswordHashNeedsUpgrade reports whether a stored hash is not in the current
|
||||||
// scheme: an unprefixed legacy hash, or a bcrypt cost below BcryptCost.
|
// scheme: an unprefixed legacy hash, or a bcrypt cost below BcryptCost.
|
||||||
func PasswordHashNeedsUpgrade(hash string) bool {
|
func PasswordHashNeedsUpgrade(hash string) bool {
|
||||||
|
if bcryptHash, prefixed := strings.CutPrefix(hash, bcryptSHA256Scheme); prefixed {
|
||||||
|
cost, err := bcrypt.Cost([]byte(bcryptHash))
|
||||||
|
return err != nil || cost < BcryptCost
|
||||||
|
}
|
||||||
|
if _, _, _, ok := parsePBKDF2Hash(hash); ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme)
|
bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme)
|
||||||
if !prefixed {
|
if !prefixed {
|
||||||
return true
|
return true
|
||||||
@@ -61,6 +95,15 @@ func VerifyAndUpgradePassword(hash, password string) (valid bool, upgraded strin
|
|||||||
if !PasswordHashNeedsUpgrade(hash) {
|
if !PasswordHashNeedsUpgrade(hash) {
|
||||||
return true, "", nil
|
return true, "", nil
|
||||||
}
|
}
|
||||||
|
if len([]byte(password)) > maxPasswordBytes {
|
||||||
|
digest := sha256.Sum256([]byte(password))
|
||||||
|
var hashBytes []byte
|
||||||
|
hashBytes, err = bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(digest[:])), BcryptCost)
|
||||||
|
if err == nil {
|
||||||
|
upgraded = bcryptSHA256Scheme + string(hashBytes)
|
||||||
|
}
|
||||||
|
return true, upgraded, err
|
||||||
|
}
|
||||||
upgraded, err = HashPassword(password)
|
upgraded, err = HashPassword(password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return true, "", err
|
return true, "", err
|
||||||
@@ -78,3 +121,32 @@ func bcryptHashOf(stored string) (string, bool) {
|
|||||||
}
|
}
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parsePBKDF2Hash(stored string) (iterations int, salt, expected string, ok bool) {
|
||||||
|
if strings.HasPrefix(stored, "pbkdf2-sha256$") {
|
||||||
|
parts := strings.Split(stored, "$")
|
||||||
|
if len(parts) != 4 {
|
||||||
|
return 0, "", "", false
|
||||||
|
}
|
||||||
|
parsedIterations, err := strconv.Atoi(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return 0, "", "", false
|
||||||
|
}
|
||||||
|
iterations, salt, expected = parsedIterations, parts[2], parts[3]
|
||||||
|
} else if strings.Count(stored, ":") == 1 {
|
||||||
|
parts := strings.SplitN(stored, ":", 2)
|
||||||
|
iterations, salt, expected = legacyPBKDF2Iterations, parts[0], parts[1]
|
||||||
|
} else {
|
||||||
|
return 0, "", "", false
|
||||||
|
}
|
||||||
|
if iterations < 1 || iterations > maxPBKDF2Iterations || len(salt) != 32 || len(expected) != 64 {
|
||||||
|
return 0, "", "", false
|
||||||
|
}
|
||||||
|
if _, err := hex.DecodeString(salt); err != nil {
|
||||||
|
return 0, "", "", false
|
||||||
|
}
|
||||||
|
if _, err := hex.DecodeString(expected); err != nil {
|
||||||
|
return 0, "", "", false
|
||||||
|
}
|
||||||
|
return iterations, salt, expected, true
|
||||||
|
}
|
||||||
@@ -165,9 +165,9 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/subtle"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"mime"
|
"mime"
|
||||||
"net"
|
"net"
|
||||||
@@ -183,6 +183,7 @@ import (
|
|||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ProxyUser is this service's own /auth/... response shape - UNCHANGED from
|
// ProxyUser is this service's own /auth/... response shape - UNCHANGED from
|
||||||
@@ -223,7 +224,7 @@ var (
|
|||||||
// message rather than a generic "internal error" that would be
|
// message rather than a generic "internal error" that would be
|
||||||
// indistinguishable from any other server bug.
|
// indistinguishable from any other server bug.
|
||||||
errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.")
|
errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.")
|
||||||
errSecretNotSet = errors.New("SECRET environment variable is not set.")
|
errSecretNotUsable = fmt.Errorf("SECRET environment variable is unset, shorter than %d characters, or an example placeholder.", coreconfig.MinInternalSecretLength)
|
||||||
errTooManyAttempts = errors.New("Too many attempts. Try again later.")
|
errTooManyAttempts = errors.New("Too many attempts. Try again later.")
|
||||||
errSetupRequiresLogin = errors.New("Account setup is only available while login is required.")
|
errSetupRequiresLogin = errors.New("Account setup is only available while login is required.")
|
||||||
errNoLoginRequiredStore = errors.New("the login-required setting has no store to save to")
|
errNoLoginRequiredStore = errors.New("the login-required setting has no store to save to")
|
||||||
@@ -286,6 +287,10 @@ type Service struct {
|
|||||||
// real base URL.
|
// real base URL.
|
||||||
authGuard *authclient.Client
|
authGuard *authclient.Client
|
||||||
configurationError error
|
configurationError error
|
||||||
|
// reauthenticateEmailChanges is opt-in because older consumers historically
|
||||||
|
// allowed email-only edits without the current password. Password changes
|
||||||
|
// always require current credentials in UpdateMe.
|
||||||
|
reauthenticateEmailChanges bool
|
||||||
loginCacheMu sync.Mutex
|
loginCacheMu sync.Mutex
|
||||||
loginCacheValue bool
|
loginCacheValue bool
|
||||||
loginCacheSet bool
|
loginCacheSet bool
|
||||||
@@ -307,6 +312,7 @@ type ServiceOption func(*serviceOptions)
|
|||||||
type serviceOptions struct {
|
type serviceOptions struct {
|
||||||
disabled bool
|
disabled bool
|
||||||
requireSecret bool
|
requireSecret bool
|
||||||
|
reauthenticateEmailChanges bool
|
||||||
trustedProxies []*net.IPNet
|
trustedProxies []*net.IPNet
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,6 +335,14 @@ func RequireSecret() ServiceOption {
|
|||||||
return func(o *serviceOptions) { o.requireSecret = true }
|
return func(o *serviceOptions) { o.requireSecret = true }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReauthenticateEmailChanges requires current-password proof, and TOTP when
|
||||||
|
// enabled, for email changes through UpdateMe. Password changes already
|
||||||
|
// require the same proof. This is opt-in to preserve existing consumers that
|
||||||
|
// have not adopted the matching profile-dialog flow.
|
||||||
|
func ReauthenticateEmailChanges() ServiceOption {
|
||||||
|
return func(o *serviceOptions) { o.reauthenticateEmailChanges = true }
|
||||||
|
}
|
||||||
|
|
||||||
// WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is
|
// WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is
|
||||||
// honoured when a login's client address is taken. Build the list from the
|
// honoured when a login's client address is taken. Build the list from the
|
||||||
// TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer
|
// TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer
|
||||||
@@ -379,8 +393,8 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
|
|||||||
client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey))
|
client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey))
|
||||||
}
|
}
|
||||||
var configurationError error
|
var configurationError error
|
||||||
if options.requireSecret && !options.disabled && strings.TrimSpace(os.Getenv("SECRET")) == "" {
|
if options.requireSecret && !options.disabled && !coreconfig.InternalSecretUsable(strings.TrimSpace(os.Getenv("SECRET"))) {
|
||||||
configurationError = errSecretNotSet
|
configurationError = errSecretNotUsable
|
||||||
}
|
}
|
||||||
return &Service{
|
return &Service{
|
||||||
store: store,
|
store: store,
|
||||||
@@ -388,6 +402,7 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
|
|||||||
secureCookies: secureCookies,
|
secureCookies: secureCookies,
|
||||||
authGuard: client,
|
authGuard: client,
|
||||||
configurationError: configurationError,
|
configurationError: configurationError,
|
||||||
|
reauthenticateEmailChanges: options.reauthenticateEmailChanges,
|
||||||
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
|
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
|
||||||
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
|
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
|
||||||
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
|
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
|
||||||
@@ -697,6 +712,8 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
|||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
|
CurrentPassword string `json:"currentPassword"`
|
||||||
|
TOTPToken string `json:"totpToken"`
|
||||||
}
|
}
|
||||||
if err := decodeProxyJSON(r, &input); err != nil {
|
if err := decodeProxyJSON(r, &input); err != nil {
|
||||||
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
|
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
@@ -719,8 +736,30 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeProxyError(w, http.StatusBadRequest, err.Error())
|
writeProxyError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
if input.Password != "" || (s.reauthenticateEmailChanges && email != current.Email) {
|
||||||
|
if input.CurrentPassword == "" {
|
||||||
|
writeProxyError(w, http.StatusBadRequest, "currentPassword is required to change email or password")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if current.MFAEnabled && strings.TrimSpace(input.TOTPToken) == "" {
|
||||||
|
writeProxyError(w, http.StatusBadRequest, "totpToken is required to change email or password")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reauthenticated, err := s.authGuard.Login(r.Context(), current.Username, input.CurrentPassword, input.TOTPToken)
|
||||||
|
if err != nil {
|
||||||
|
writeAuthGuardError(w, err, "current credentials could not be verified")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if token := temporarySessionToken(reauthenticated); token != "" {
|
||||||
|
defer func() {
|
||||||
|
_, _ = s.authGuard.Logout(context.WithoutCancel(r.Context()), token)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
if input.Password != "" {
|
||||||
managedInput.Password = input.Password
|
managedInput.Password = input.Password
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
token := s.sessionToken(r)
|
token := s.sessionToken(r)
|
||||||
if err := s.authGuard.UpdateManagedUser(r.Context(), token, current.ID, managedInput); err != nil {
|
if err := s.authGuard.UpdateManagedUser(r.Context(), token, current.ID, managedInput); err != nil {
|
||||||
@@ -736,6 +775,18 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeProxyJSON(w, http.StatusOK, map[string]any{"user": updated})
|
writeProxyJSON(w, http.StatusOK, map[string]any{"user": updated})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func temporarySessionToken(session *authclient.SessionResult) string {
|
||||||
|
if session == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for _, cookie := range session.Cookies {
|
||||||
|
if cookie != nil && cookie.Name == authclient.DefaultCookieName {
|
||||||
|
return cookie.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
// AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc
|
// AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc
|
||||||
// comment's "Setup flow" section.
|
// comment's "Setup flow" section.
|
||||||
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
|
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -856,7 +907,7 @@ func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
|
|||||||
// expose the same propagation endpoint without duplicating its JSON handling.
|
// expose the same propagation endpoint without duplicating its JSON handling.
|
||||||
func (s *Service) SetLoginRequiredInternal(secret string) http.Handler {
|
func (s *Service) SetLoginRequiredInternal(secret string) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
if strings.TrimSpace(secret) == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 {
|
if !coreconfig.InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) {
|
||||||
writeProxyError(w, http.StatusUnauthorized, "internal service authentication required")
|
writeProxyError(w, http.StatusUnauthorized, "internal service authentication required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -406,6 +406,12 @@ func TestTOTPInitiateAndStatus(t *testing.T) {
|
|||||||
|
|
||||||
func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
||||||
guard := newFakeAuthGuard(t)
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) {
|
||||||
|
w.Header().Add("Set-Cookie", authclient.DefaultCookieName+"=reauth-token; Path=/; HttpOnly")
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
|
||||||
|
})
|
||||||
|
guard.reply("POST /api/logout", http.StatusOK, map[string]any{"ok": true})
|
||||||
guard.reply("PUT /api/admin/users/7", http.StatusOK, map[string]any{})
|
guard.reply("PUT /api/admin/users/7", http.StatusOK, map[string]any{})
|
||||||
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
|
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
|
||||||
service, _ := guard.service(t)
|
service, _ := guard.service(t)
|
||||||
@@ -418,7 +424,7 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
|||||||
service.UpdateMe(rec, req)
|
service.UpdateMe(rec, req)
|
||||||
return rec
|
return rec
|
||||||
}
|
}
|
||||||
manager := &ProxyUser{ID: 7, Role: "admin"}
|
manager := &ProxyUser{ID: 7, Username: "boss", Role: "admin", MFAEnabled: true}
|
||||||
|
|
||||||
if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized {
|
if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized {
|
||||||
t.Fatalf("no session user: status = %d, want 401", rec.Code)
|
t.Fatalf("no session user: status = %d, want 401", rec.Code)
|
||||||
@@ -431,6 +437,8 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
|||||||
"at in username": `{"email":"a@b.com","username":"a@b.com"}`,
|
"at in username": `{"email":"a@b.com","username":"a@b.com"}`,
|
||||||
"short password": `{"email":"a@b.com","username":"boss","password":"short"}`,
|
"short password": `{"email":"a@b.com","username":"boss","password":"short"}`,
|
||||||
"long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`,
|
"long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`,
|
||||||
|
"missing current password": `{"email":"a@b.com","username":"boss","password":"new-password"}`,
|
||||||
|
"missing current totp": `{"email":"a@b.com","username":"boss","password":"new-password","currentPassword":"current-password"}`,
|
||||||
"not JSON": `nope`,
|
"not JSON": `nope`,
|
||||||
} {
|
} {
|
||||||
if rec := update(manager, body); rec.Code != http.StatusBadRequest {
|
if rec := update(manager, body); rec.Code != http.StatusBadRequest {
|
||||||
@@ -452,6 +460,29 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
|||||||
if _, sent := calls[0].Body["password"]; sent {
|
if _, sent := calls[0].Body["password"]; sent {
|
||||||
t.Fatal("an update without a password sent one to AuthGuard")
|
t.Fatal("an update without a password sent one to AuthGuard")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
rec = update(manager, `{"email":"boss@example.com","username":"boss","password":"new-password","currentPassword":"current-password","totpToken":"123456"}`)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("password update status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
loginCalls := guard.callsTo("POST /api/login")
|
||||||
|
if len(loginCalls) != 1 || loginCalls[0].Body["username_or_email"] != "boss" || loginCalls[0].Body["password"] != "current-password" || loginCalls[0].Body["totp_token"] != "123456" {
|
||||||
|
t.Fatalf("reauthentication request = %+v", loginCalls)
|
||||||
|
}
|
||||||
|
calls = guard.callsTo("PUT /api/admin/users/7")
|
||||||
|
if len(calls) != 2 || calls[1].Body["password"] != "new-password" {
|
||||||
|
t.Fatalf("password update request = %+v", calls)
|
||||||
|
}
|
||||||
|
if _, sent := calls[1].Body["currentPassword"]; sent {
|
||||||
|
t.Fatal("current password was forwarded to the managed-user API")
|
||||||
|
}
|
||||||
|
if _, sent := calls[1].Body["totpToken"]; sent {
|
||||||
|
t.Fatal("TOTP code was forwarded to the managed-user API")
|
||||||
|
}
|
||||||
|
logoutCalls := guard.callsTo("POST /api/logout")
|
||||||
|
if len(logoutCalls) != 1 || logoutCalls[0].Authorization != "Bearer reauth-token" {
|
||||||
|
t.Fatalf("temporary login session was not removed: %+v", logoutCalls)
|
||||||
|
}
|
||||||
if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" {
|
if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" {
|
||||||
t.Fatalf("response user = %v", user)
|
t.Fatalf("response user = %v", user)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
|||||||
role TEXT NOT NULL DEFAULT 'user',
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
totp_secret TEXT NOT NULL DEFAULT '',
|
totp_secret TEXT NOT NULL DEFAULT '',
|
||||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
last_used_step BIGINT NOT NULL DEFAULT -1,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
last_login_at TIMESTAMPTZ
|
last_login_at TIMESTAMPTZ
|
||||||
@@ -95,6 +96,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
|||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
-- last_login_at is nullable (NULL means "never logged in" - registration
|
-- last_login_at is nullable (NULL means "never logged in" - registration
|
||||||
@@ -222,6 +224,7 @@ func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error {
|
|||||||
type TOTPState struct {
|
type TOTPState struct {
|
||||||
Secret string
|
Secret string
|
||||||
Enabled bool
|
Enabled bool
|
||||||
|
LastUsedStep int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetTOTPState reads the stored TOTP provisioning state for an account.
|
// GetTOTPState reads the stored TOTP provisioning state for an account.
|
||||||
@@ -230,7 +233,7 @@ func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, erro
|
|||||||
return TOTPState{}, err
|
return TOTPState{}, err
|
||||||
}
|
}
|
||||||
var state TOTPState
|
var state TOTPState
|
||||||
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled)
|
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false), COALESCE(last_used_step, -1) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled, &state.LastUsedStep)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return TOTPState{}, nil
|
return TOTPState{}, nil
|
||||||
}
|
}
|
||||||
@@ -246,7 +249,7 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string)
|
|||||||
if err := s.validate(); err != nil {
|
if err := s.validate(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID)
|
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("set TOTP secret: %w", err)
|
return fmt.Errorf("set TOTP secret: %w", err)
|
||||||
}
|
}
|
||||||
@@ -262,16 +265,39 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnableTOTP marks a previously provisioned secret as active.
|
// EnableTOTP marks a previously provisioned secret as active and records the
|
||||||
func (s *Store) EnableTOTP(ctx context.Context, userID int64) error {
|
// step used to confirm it, preventing that code from being reused at login.
|
||||||
|
func (s *Store) EnableTOTP(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
|
||||||
if err := s.validate(); err != nil {
|
if err := s.validate(); err != nil {
|
||||||
return err
|
return false, err
|
||||||
}
|
}
|
||||||
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID)
|
tag, err := s.pool.Exec(ctx, `
|
||||||
|
UPDATE auth_users
|
||||||
|
SET totp_enabled = true, last_used_step = $1, updated_at = now()
|
||||||
|
WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1
|
||||||
|
`, step, userID, secret)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("enable TOTP: %w", err)
|
return false, fmt.Errorf("enable TOTP: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return tag.RowsAffected() == 1, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsumeTOTPStep advances an account's accepted TOTP step only once. The
|
||||||
|
// expected secret and enabled flag are part of the update so a concurrent
|
||||||
|
// disable or re-enrollment cannot consume a code against stale state.
|
||||||
|
func (s *Store) ConsumeTOTPStep(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
|
||||||
|
if err := s.validate(); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
tag, err := s.pool.Exec(ctx, `
|
||||||
|
UPDATE auth_users
|
||||||
|
SET last_used_step = $1, updated_at = now()
|
||||||
|
WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1
|
||||||
|
`, step, userID, secret)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("consume TOTP step: %w", err)
|
||||||
|
}
|
||||||
|
return tag.RowsAffected() == 1, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DisableTOTP clears both the active and pending TOTP secret.
|
// DisableTOTP clears both the active and pending TOTP secret.
|
||||||
@@ -279,7 +305,7 @@ func (s *Store) DisableTOTP(ctx context.Context, userID int64) error {
|
|||||||
if err := s.validate(); err != nil {
|
if err := s.validate(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID)
|
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1`, userID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("disable TOTP: %w", err)
|
return fmt.Errorf("disable TOTP: %w", err)
|
||||||
}
|
}
|
||||||
@@ -382,6 +408,22 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpgradePasswordHash replaces an old verifier only if it is still current,
|
||||||
|
// so a concurrent password change cannot be overwritten by a login rehash.
|
||||||
|
func (s *Store) UpgradePasswordHash(ctx context.Context, id int64, oldHash, newHash string) (bool, error) {
|
||||||
|
if err := s.validate(); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
tag, err := s.pool.Exec(ctx, `
|
||||||
|
UPDATE auth_users SET password_hash = $1, updated_at = now()
|
||||||
|
WHERE id = $2 AND password_hash = $3
|
||||||
|
`, newHash, id, oldHash)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("upgrade password hash: %w", err)
|
||||||
|
}
|
||||||
|
return tag.RowsAffected() == 1, nil
|
||||||
|
}
|
||||||
|
|
||||||
// ListUsers returns the non-secret account fields used by the shared user
|
// ListUsers returns the non-secret account fields used by the shared user
|
||||||
// management screen.
|
// management screen.
|
||||||
func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
|
func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
|
||||||
|
|||||||
@@ -230,8 +230,8 @@ func TestStoreTOTPAndIdentifierPrimitives(t *testing.T) {
|
|||||||
if err := store.SetTOTPSecret(ctx, owner.ID, "JBSWY3DPEHPK3PXP"); err != nil {
|
if err := store.SetTOTPSecret(ctx, owner.ID, "JBSWY3DPEHPK3PXP"); err != nil {
|
||||||
t.Fatalf("SetTOTPSecret() while disabled error = %v", err)
|
t.Fatalf("SetTOTPSecret() while disabled error = %v", err)
|
||||||
}
|
}
|
||||||
if err := store.EnableTOTP(ctx, owner.ID); err != nil {
|
if enabled, err := store.EnableTOTP(ctx, owner.ID, "JBSWY3DPEHPK3PXP", 123); err != nil || !enabled {
|
||||||
t.Fatal(err)
|
t.Fatalf("EnableTOTP() = %v, %v; want enabled", enabled, err)
|
||||||
}
|
}
|
||||||
if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) {
|
if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) {
|
||||||
t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err)
|
t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err)
|
||||||
|
|||||||
@@ -52,19 +52,22 @@ func TOTPProvisioningURI(issuer, account, secret string) string {
|
|||||||
return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode()
|
return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode()
|
||||||
}
|
}
|
||||||
|
|
||||||
// VerifyTOTP checks a six-digit token with a one-period clock-skew window.
|
// VerifyTOTP checks a six-digit token with a one-period clock-skew window and
|
||||||
func VerifyTOTP(secret, token string, now time.Time) bool {
|
// returns the matching time step. A caller must atomically record that step
|
||||||
|
// before accepting the code so it cannot be used twice.
|
||||||
|
func VerifyTOTP(secret, token string, now time.Time) (int64, bool) {
|
||||||
secret = normalizeTOTPSecret(secret)
|
secret = normalizeTOTPSecret(secret)
|
||||||
token = normalizeTOTPToken(token)
|
token = normalizeTOTPToken(token)
|
||||||
if secret == "" || len(token) != TOTPDigits {
|
if secret == "" || len(token) != TOTPDigits {
|
||||||
return false
|
return -1, false
|
||||||
}
|
}
|
||||||
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
|
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
|
||||||
if err != nil || len(key) == 0 {
|
if err != nil || len(key) == 0 {
|
||||||
return false
|
return -1, false
|
||||||
}
|
}
|
||||||
period := now.Unix() / int64(TOTPPeriod/time.Second)
|
period := now.Unix() / int64(TOTPPeriod/time.Second)
|
||||||
for offset := int64(-TOTPWindow); offset <= TOTPWindow; offset++ {
|
// Prefer the current step if a six-digit collision occurs in the window.
|
||||||
|
for _, offset := range [...]int64{0, -1, 1} {
|
||||||
if period+offset < 0 {
|
if period+offset < 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -80,10 +83,10 @@ func VerifyTOTP(secret, token string, now time.Time) bool {
|
|||||||
uint32(digest[index+3])
|
uint32(digest[index+3])
|
||||||
candidate := fmt.Sprintf("%06d", value%1000000)
|
candidate := fmt.Sprintf("%06d", value%1000000)
|
||||||
if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 {
|
if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 {
|
||||||
return true
|
return period + offset, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return -1, false
|
||||||
}
|
}
|
||||||
|
|
||||||
func normalizeTOTPSecret(value string) string {
|
func normalizeTOTPSecret(value string) string {
|
||||||
|
|||||||
@@ -18,8 +18,11 @@ func TestVerifyTOTPRFC6238SHA1Vectors(t *testing.T) {
|
|||||||
{unix: 2000000000, code: "279037"},
|
{unix: 2000000000, code: "279037"},
|
||||||
}
|
}
|
||||||
for _, testCase := range cases {
|
for _, testCase := range cases {
|
||||||
if !VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0)) {
|
step, valid := VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0))
|
||||||
|
if !valid {
|
||||||
t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code)
|
t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code)
|
||||||
|
} else if want := testCase.unix / int64(TOTPPeriod/time.Second); step != want {
|
||||||
|
t.Errorf("VerifyTOTP(%d, %q) matched step %d, want %d", testCase.unix, testCase.code, step, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ type Client struct {
|
|||||||
projectKey string
|
projectKey string
|
||||||
validationMu sync.Mutex
|
validationMu sync.Mutex
|
||||||
validationCache map[[32]byte]validationCacheEntry
|
validationCache map[[32]byte]validationCacheEntry
|
||||||
|
profileCache map[[32]byte]profileCacheEntry
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProjectKeyHeader is the header Client attaches to every request identifying
|
// ProjectKeyHeader is the header Client attaches to every request identifying
|
||||||
@@ -118,6 +119,7 @@ func New(baseURL string, opts ...Option) *Client {
|
|||||||
httpClient: &http.Client{Timeout: 5 * time.Second},
|
httpClient: &http.Client{Timeout: 5 * time.Second},
|
||||||
cookieName: DefaultCookieName,
|
cookieName: DefaultCookieName,
|
||||||
validationCache: make(map[[32]byte]validationCacheEntry),
|
validationCache: make(map[[32]byte]validationCacheEntry),
|
||||||
|
profileCache: make(map[[32]byte]profileCacheEntry),
|
||||||
}
|
}
|
||||||
for _, opt := range opts {
|
for _, opt := range opts {
|
||||||
opt(c)
|
opt(c)
|
||||||
@@ -583,12 +585,24 @@ func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, erro
|
|||||||
|
|
||||||
// Me calls GET /api/me, resolving token to its account.
|
// Me calls GET /api/me, resolving token to its account.
|
||||||
func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) {
|
func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) {
|
||||||
|
token = strings.TrimSpace(token)
|
||||||
|
if token == "" {
|
||||||
|
return nil, ErrInvalidSession
|
||||||
|
}
|
||||||
|
if profile, ok := c.cachedProfile(token); ok {
|
||||||
|
return profile, nil
|
||||||
|
}
|
||||||
var out struct {
|
var out struct {
|
||||||
User PublicUser `json:"user"`
|
User PublicUser `json:"user"`
|
||||||
}
|
}
|
||||||
if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil {
|
if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil {
|
||||||
|
var apiErr *APIError
|
||||||
|
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized {
|
||||||
|
c.invalidateValidation(token)
|
||||||
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
c.cacheProfile(token, &out.User)
|
||||||
return &out.User, nil
|
return &out.User, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -607,6 +621,9 @@ func (c *Client) TOTPEnable(ctx context.Context, token string) (*TOTPEnableResul
|
|||||||
// pending secret TOTPEnable provisioned and activating two-factor auth.
|
// pending secret TOTPEnable provisioned and activating two-factor auth.
|
||||||
func (c *Client) TOTPVerify(ctx context.Context, token, code string) error {
|
func (c *Client) TOTPVerify(ctx context.Context, token, code string) error {
|
||||||
_, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil)
|
_, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil)
|
||||||
|
if err == nil {
|
||||||
|
c.invalidateValidation(token)
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -615,6 +632,9 @@ func (c *Client) TOTPVerify(ctx context.Context, token, code string) error {
|
|||||||
// as proof of possession.
|
// as proof of possession.
|
||||||
func (c *Client) TOTPDisable(ctx context.Context, token, code string) error {
|
func (c *Client) TOTPDisable(ctx context.Context, token, code string) error {
|
||||||
_, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil)
|
_, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil)
|
||||||
|
if err == nil {
|
||||||
|
c.invalidateValidation(token)
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,12 +10,20 @@ const (
|
|||||||
maxValidationCacheSize = 10000
|
maxValidationCacheSize = 10000
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// A session revoked directly in AuthGuard may remain accepted by this client
|
||||||
|
// for up to two seconds. Logout through this Client clears the cached result.
|
||||||
|
|
||||||
type validationCacheEntry struct {
|
type validationCacheEntry struct {
|
||||||
user User
|
user User
|
||||||
valid bool
|
valid bool
|
||||||
expires time.Time
|
expires time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type profileCacheEntry struct {
|
||||||
|
profile PublicUser
|
||||||
|
expires time.Time
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) cachedValidation(token string) (*User, error, bool) {
|
func (c *Client) cachedValidation(token string) (*User, error, bool) {
|
||||||
key := sha256.Sum256([]byte(token))
|
key := sha256.Sum256([]byte(token))
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
@@ -64,15 +72,61 @@ func (c *Client) cacheValidation(token string, user *User, valid bool) {
|
|||||||
c.validationCache[key] = entry
|
c.validationCache[key] = entry
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Client) cachedProfile(token string) (*PublicUser, bool) {
|
||||||
|
key := sha256.Sum256([]byte(token))
|
||||||
|
now := time.Now()
|
||||||
|
c.validationMu.Lock()
|
||||||
|
defer c.validationMu.Unlock()
|
||||||
|
entry, ok := c.profileCache[key]
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if !now.Before(entry.expires) {
|
||||||
|
delete(c.profileCache, key)
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
profile := entry.profile
|
||||||
|
return &profile, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) cacheProfile(token string, profile *PublicUser) {
|
||||||
|
if profile == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key := sha256.Sum256([]byte(token))
|
||||||
|
now := time.Now()
|
||||||
|
c.validationMu.Lock()
|
||||||
|
defer c.validationMu.Unlock()
|
||||||
|
if c.profileCache == nil {
|
||||||
|
c.profileCache = make(map[[32]byte]profileCacheEntry)
|
||||||
|
}
|
||||||
|
if len(c.profileCache) >= maxValidationCacheSize {
|
||||||
|
for existing, entry := range c.profileCache {
|
||||||
|
if !now.Before(entry.expires) {
|
||||||
|
delete(c.profileCache, existing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(c.profileCache) >= maxValidationCacheSize {
|
||||||
|
for existing := range c.profileCache {
|
||||||
|
delete(c.profileCache, existing)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.profileCache[key] = profileCacheEntry{profile: *profile, expires: now.Add(validationCacheTTL)}
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) invalidateValidation(token string) {
|
func (c *Client) invalidateValidation(token string) {
|
||||||
key := sha256.Sum256([]byte(token))
|
key := sha256.Sum256([]byte(token))
|
||||||
c.validationMu.Lock()
|
c.validationMu.Lock()
|
||||||
delete(c.validationCache, key)
|
delete(c.validationCache, key)
|
||||||
|
delete(c.profileCache, key)
|
||||||
c.validationMu.Unlock()
|
c.validationMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) clearValidationCache() {
|
func (c *Client) clearValidationCache() {
|
||||||
c.validationMu.Lock()
|
c.validationMu.Lock()
|
||||||
c.validationCache = make(map[[32]byte]validationCacheEntry)
|
c.validationCache = make(map[[32]byte]validationCacheEntry)
|
||||||
|
c.profileCache = make(map[[32]byte]profileCacheEntry)
|
||||||
c.validationMu.Unlock()
|
c.validationMu.Unlock()
|
||||||
}
|
}
|
||||||
@@ -22,12 +22,25 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// httpClient has no blanket timeout since it streams large media files;
|
// httpClient has no total timeout since it streams large media files. The
|
||||||
// callers bound individual calls with a context deadline instead.
|
// transport still bounds how long a request may wait for response headers;
|
||||||
var httpClient = &http.Client{}
|
// callers that need a shorter bound add a context deadline as well.
|
||||||
|
var httpClient = newHTTPClient()
|
||||||
|
|
||||||
|
func newHTTPClient() *http.Client {
|
||||||
|
var transport *http.Transport
|
||||||
|
if defaultTransport, ok := http.DefaultTransport.(*http.Transport); ok {
|
||||||
|
transport = defaultTransport.Clone()
|
||||||
|
} else {
|
||||||
|
transport = &http.Transport{Proxy: http.ProxyFromEnvironment}
|
||||||
|
}
|
||||||
|
transport.ResponseHeaderTimeout = 10 * time.Second
|
||||||
|
return &http.Client{Transport: transport}
|
||||||
|
}
|
||||||
|
|
||||||
var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
|
var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
|
||||||
var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
|
var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
|
||||||
@@ -69,6 +82,17 @@ type Client struct {
|
|||||||
// multiple candidates are actually used (union for discovery, first-match
|
// multiple candidates are actually used (union for discovery, first-match
|
||||||
// for reads, primary-only for writes).
|
// for reads, primary-only for writes).
|
||||||
BaseURLs func(ctx context.Context) []string
|
BaseURLs func(ctx context.Context) []string
|
||||||
|
|
||||||
|
thumbnailMu sync.Mutex
|
||||||
|
thumbnailPaths map[string]thumbnailPathEntry
|
||||||
|
}
|
||||||
|
|
||||||
|
const thumbnailPathCacheTTL = 5 * time.Minute
|
||||||
|
const thumbnailPathCacheLimit = 2048
|
||||||
|
|
||||||
|
type thumbnailPathEntry struct {
|
||||||
|
path string
|
||||||
|
expires time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
// New returns a Client backed by a single CarrierNode instance. baseURL is
|
// New returns a Client backed by a single CarrierNode instance. baseURL is
|
||||||
@@ -536,15 +560,103 @@ func (c *Client) ProxyThumbnail(w http.ResponseWriter, r *http.Request, project,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
cacheKey := project + "\x00" + id
|
||||||
|
cachedPath := c.cachedThumbnailPath(cacheKey)
|
||||||
|
if cachedPath != "" {
|
||||||
|
ordered := make([]string, 0, len(paths))
|
||||||
|
ordered = append(ordered, cachedPath)
|
||||||
for _, path := range paths {
|
for _, path := range paths {
|
||||||
if exists, _, _, probeErr := c.Probe(r.Context(), path); probeErr == nil && exists {
|
if path != cachedPath {
|
||||||
c.Proxy(w, r, path)
|
ordered = append(ordered, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
paths = ordered
|
||||||
|
}
|
||||||
|
for _, path := range paths {
|
||||||
|
for _, baseURL := range c.candidateBaseURLs(r.Context()) {
|
||||||
|
request, err := c.newRequest(r.Context(), baseURL, r.Method, path, nil)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, header := range forwardRequestHeaders {
|
||||||
|
if value := r.Header.Get(header); value != "" {
|
||||||
|
request.Header.Set(header, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
response, err := httpClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if response.StatusCode >= http.StatusBadRequest {
|
||||||
|
response.Body.Close()
|
||||||
|
if path == cachedPath {
|
||||||
|
c.forgetThumbnailPath(cacheKey)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, header := range forwardResponseHeaders {
|
||||||
|
if value := response.Header.Get(header); value != "" {
|
||||||
|
w.Header().Set(header, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.WriteHeader(response.StatusCode)
|
||||||
|
if r.Method != http.MethodHead {
|
||||||
|
_, _ = io.Copy(w, response.Body)
|
||||||
|
}
|
||||||
|
response.Body.Close()
|
||||||
|
c.rememberThumbnailPath(cacheKey, path)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Client) cachedThumbnailPath(key string) string {
|
||||||
|
c.thumbnailMu.Lock()
|
||||||
|
defer c.thumbnailMu.Unlock()
|
||||||
|
entry, ok := c.thumbnailPaths[key]
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if !time.Now().Before(entry.expires) {
|
||||||
|
delete(c.thumbnailPaths, key)
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return entry.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) rememberThumbnailPath(key, path string) {
|
||||||
|
c.thumbnailMu.Lock()
|
||||||
|
defer c.thumbnailMu.Unlock()
|
||||||
|
if c.thumbnailPaths == nil {
|
||||||
|
c.thumbnailPaths = make(map[string]thumbnailPathEntry)
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
for cacheKey, entry := range c.thumbnailPaths {
|
||||||
|
if !now.Before(entry.expires) {
|
||||||
|
delete(c.thumbnailPaths, cacheKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(c.thumbnailPaths) >= thumbnailPathCacheLimit {
|
||||||
|
var oldestKey string
|
||||||
|
var oldest time.Time
|
||||||
|
first := true
|
||||||
|
for cacheKey, entry := range c.thumbnailPaths {
|
||||||
|
if first || entry.expires.Before(oldest) {
|
||||||
|
oldestKey, oldest, first = cacheKey, entry.expires, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delete(c.thumbnailPaths, oldestKey)
|
||||||
|
}
|
||||||
|
c.thumbnailPaths[key] = thumbnailPathEntry{path: path, expires: now.Add(thumbnailPathCacheTTL)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) forgetThumbnailPath(key string) {
|
||||||
|
c.thumbnailMu.Lock()
|
||||||
|
delete(c.thumbnailPaths, key)
|
||||||
|
c.thumbnailMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
// FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking
|
// FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking
|
||||||
// in the project's thumbnails mount and then the legacy root. Callers must invoke the returned
|
// in the project's thumbnails mount and then the legacy root. Callers must invoke the returned
|
||||||
// cleanup once done.
|
// cleanup once done.
|
||||||
|
|||||||
@@ -1,265 +1,21 @@
|
|||||||
package carriernodeclient
|
package carriernodeclient
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestListFilesMergesAcrossInstances(t *testing.T) {
|
func TestHTTPClientBoundsResponseHeaderWaitWithoutLimitingStreams(t *testing.T) {
|
||||||
first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
client := newHTTPClient()
|
||||||
w.Header().Set("Content-Type", "application/json")
|
if client.Timeout != 0 {
|
||||||
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`))
|
t.Fatalf("client total timeout = %s, want no total timeout for media streams", client.Timeout)
|
||||||
}))
|
|
||||||
defer first.Close()
|
|
||||||
second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
_, _ = w.Write([]byte(`{"files":[{"rel":"b.mp4"}]}`))
|
|
||||||
}))
|
|
||||||
defer second.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
|
|
||||||
|
|
||||||
files, err := client.ListFiles(context.Background(), "", false, 0)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("ListFiles error: %v", err)
|
|
||||||
}
|
}
|
||||||
if len(files) != 2 {
|
transport, ok := client.Transport.(*http.Transport)
|
||||||
t.Fatalf("ListFiles returned %d files, want 2: %+v", len(files), files)
|
if !ok {
|
||||||
|
t.Fatalf("transport type = %T, want *http.Transport", client.Transport)
|
||||||
}
|
}
|
||||||
}
|
if transport.ResponseHeaderTimeout != 10*time.Second {
|
||||||
|
t.Fatalf("response header timeout = %s, want 10s", transport.ResponseHeaderTimeout)
|
||||||
func TestRequestsCarryProjectAttribution(t *testing.T) {
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if got := r.Header.Get("X-Internal-Auth"); got != "secret" {
|
|
||||||
t.Fatalf("X-Internal-Auth = %q, want secret", got)
|
|
||||||
}
|
|
||||||
if got := r.Header.Get("X-Project-Key"); got != "ContentScanner" {
|
|
||||||
t.Fatalf("X-Project-Key = %q, want ContentScanner", got)
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
_, _ = w.Write([]byte(`{"files":[]}`))
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
client := New("secret", func(ctx context.Context) string { return server.URL })
|
|
||||||
client.ProjectKey = "ContentScanner"
|
|
||||||
if _, err := client.ListFiles(context.Background(), "", false, 0); err != nil {
|
|
||||||
t.Fatalf("ListFiles error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestListFilesSkipsUnreachableInstance(t *testing.T) {
|
|
||||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`))
|
|
||||||
}))
|
|
||||||
defer up.Close()
|
|
||||||
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
}))
|
|
||||||
down.Close() // closed immediately so requests to it fail outright
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL, up.URL} })
|
|
||||||
|
|
||||||
files, err := client.ListFiles(context.Background(), "", false, 0)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("ListFiles error: %v", err)
|
|
||||||
}
|
|
||||||
if len(files) != 1 || files[0].Rel != "a.mp4" {
|
|
||||||
t.Fatalf("ListFiles = %+v, want just the reachable instance's file", files)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestListFilesErrorsWhenNoInstanceReachable(t *testing.T) {
|
|
||||||
down := httptest.NewServer(nil)
|
|
||||||
down.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL} })
|
|
||||||
|
|
||||||
if _, err := client.ListFiles(context.Background(), "", false, 0); err == nil {
|
|
||||||
t.Fatal("ListFiles error = nil, want an error when every instance is unreachable")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestProbeFallsBackToNextInstance(t *testing.T) {
|
|
||||||
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
}))
|
|
||||||
defer notFound.Close()
|
|
||||||
found := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Length", "42")
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer found.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, found.URL} })
|
|
||||||
|
|
||||||
exists, size, _, err := client.Probe(context.Background(), "/media/a.mp4")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Probe error: %v", err)
|
|
||||||
}
|
|
||||||
if !exists {
|
|
||||||
t.Fatal("Probe exists = false, want true (second instance has it)")
|
|
||||||
}
|
|
||||||
if size != 42 {
|
|
||||||
t.Fatalf("Probe size = %d, want 42", size)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestProbeExistsFalseWhenNoInstanceHasFile(t *testing.T) {
|
|
||||||
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
}))
|
|
||||||
defer notFound.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
|
|
||||||
|
|
||||||
exists, _, _, err := client.Probe(context.Background(), "/media/missing.mp4")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Probe error: %v", err)
|
|
||||||
}
|
|
||||||
if exists {
|
|
||||||
t.Fatal("Probe exists = true, want false")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestProxyPrefersPrimaryInstanceWhenItHasTheFile(t *testing.T) {
|
|
||||||
var primaryHit, secondaryHit bool
|
|
||||||
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
primaryHit = true
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer primary.Close()
|
|
||||||
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
secondaryHit = true
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer secondary.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/thumbnails/x.jpg", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
client.Proxy(rec, req, "/thumbnails/x.jpg")
|
|
||||||
|
|
||||||
if !primaryHit {
|
|
||||||
t.Fatal("Proxy did not hit the primary instance")
|
|
||||||
}
|
|
||||||
if secondaryHit {
|
|
||||||
t.Fatal("Proxy hit the secondary instance even though the primary had the file")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestProxyFallsBackToSecondaryInstanceWhenPrimaryMisses(t *testing.T) {
|
|
||||||
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
}))
|
|
||||||
defer primary.Close()
|
|
||||||
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "video/mp4")
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
_, _ = w.Write([]byte("video bytes"))
|
|
||||||
}))
|
|
||||||
defer secondary.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/media/a.mp4", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
client.Proxy(rec, req, "/media/a.mp4")
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200 from the secondary instance", rec.Code)
|
|
||||||
}
|
|
||||||
if rec.Body.String() != "video bytes" {
|
|
||||||
t.Fatalf("body = %q, want secondary instance's bytes", rec.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestProxyForwardsLastInstanceErrorWhenNoneHaveTheFile(t *testing.T) {
|
|
||||||
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
}))
|
|
||||||
defer notFound.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/media/missing.mp4", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
client.Proxy(rec, req, "/media/missing.mp4")
|
|
||||||
|
|
||||||
if rec.Code != http.StatusNotFound {
|
|
||||||
t.Fatalf("status = %d, want 404 forwarded from the last instance", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func mountListingServer(status int, body string) *httptest.Server {
|
|
||||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(status)
|
|
||||||
_, _ = w.Write([]byte(body))
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestListMountFilesReportsNotFoundWhenEveryInstanceMisses(t *testing.T) {
|
|
||||||
first := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
|
|
||||||
defer first.Close()
|
|
||||||
second := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
|
|
||||||
defer second.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
|
|
||||||
|
|
||||||
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "gone")
|
|
||||||
if !errors.Is(err, ErrMountNotFound) {
|
|
||||||
t.Fatalf("ListMountFiles error = %v, want ErrMountNotFound", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestListMountFilesDoesNotReportNotFoundWhenAnInstanceIsUnreachable(t *testing.T) {
|
|
||||||
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
|
|
||||||
defer missing.Close()
|
|
||||||
down := httptest.NewServer(nil)
|
|
||||||
down.Close() // closed immediately so requests to it fail outright
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, down.URL} })
|
|
||||||
|
|
||||||
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "maybe-on-the-down-instance")
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("ListMountFiles succeeded, want an error")
|
|
||||||
}
|
|
||||||
if errors.Is(err, ErrMountNotFound) {
|
|
||||||
t.Fatalf("ListMountFiles error = %v, must not claim the directory is missing when an instance could not be checked", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestListMountFilesDoesNotReportNotFoundOnServerError(t *testing.T) {
|
|
||||||
broken := mountListingServer(http.StatusInternalServerError, `{"error":"boom"}`)
|
|
||||||
defer broken.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{broken.URL} })
|
|
||||||
|
|
||||||
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
|
|
||||||
if err == nil || errors.Is(err, ErrMountNotFound) {
|
|
||||||
t.Fatalf("ListMountFiles error = %v, want a non-ErrMountNotFound failure", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestListMountFilesUsesTheInstanceThatHasTheDirectory(t *testing.T) {
|
|
||||||
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
|
|
||||||
defer missing.Close()
|
|
||||||
present := mountListingServer(http.StatusOK, `{"files":[{"name":"repo","path":"repo","directory":true}]}`)
|
|
||||||
defer present.Close()
|
|
||||||
|
|
||||||
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, present.URL} })
|
|
||||||
|
|
||||||
files, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("ListMountFiles error: %v", err)
|
|
||||||
}
|
|
||||||
if len(files) != 1 || files[0].Name != "repo" || !files[0].Directory {
|
|
||||||
t.Fatalf("ListMountFiles = %+v, want the one directory from the instance that has it", files)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
@@ -94,16 +93,15 @@ func TestProxyThumbnailPrefersProjectMount(t *testing.T) {
|
|||||||
if rec.Body.String() != "from mount" {
|
if rec.Body.String() != "from mount" {
|
||||||
t.Fatalf("body = %q, want the mount copy", rec.Body.String())
|
t.Fatalf("body = %q, want the mount copy", rec.Body.String())
|
||||||
}
|
}
|
||||||
for _, request := range node.seen() {
|
want := []string{"GET " + mount}
|
||||||
if !strings.Contains(request, "/api/mount/") {
|
if got := node.seen(); !slices.Equal(got, want) {
|
||||||
t.Fatalf("legacy root was consulted although the mount had the thumbnail: %v", node.seen())
|
t.Fatalf("requests = %v, want one direct GET to the mount", got)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
|
func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
|
||||||
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
|
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
|
||||||
client, _ := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
|
client, node := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
|
||||||
|
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
if !client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
|
if !client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
|
||||||
@@ -112,10 +110,28 @@ func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
|
|||||||
if rec.Body.String() != "from legacy" {
|
if rec.Body.String() != "from legacy" {
|
||||||
t.Fatalf("body = %q, want the legacy copy", rec.Body.String())
|
t.Fatalf("body = %q, want the legacy copy", rec.Body.String())
|
||||||
}
|
}
|
||||||
|
want := []string{"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg", "GET " + legacy}
|
||||||
|
if got := node.seen(); !slices.Equal(got, want) {
|
||||||
|
t.Fatalf("requests = %v, want mount miss followed by legacy GET", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyThumbnailCachesResolvedPath(t *testing.T) {
|
||||||
|
mount := "/api/mount/MediaViewer/thumbnails/" + testThumbnailID + ".jpg"
|
||||||
|
client, node := newThumbnailTestClient(t, map[string]string{mount: "from mount"})
|
||||||
|
for range 2 {
|
||||||
|
if !client.ProxyThumbnail(httptest.NewRecorder(), thumbnailRequest(), "MediaViewer", testThumbnailID) {
|
||||||
|
t.Fatal("ProxyThumbnail missed although the mount holds the thumbnail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
want := []string{"GET " + mount, "GET " + mount}
|
||||||
|
if got := node.seen(); !slices.Equal(got, want) {
|
||||||
|
t.Fatalf("requests = %v, want one direct GET per request to the cached path", got)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
|
func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
|
||||||
client, _ := newThumbnailTestClient(t, nil)
|
client, node := newThumbnailTestClient(t, nil)
|
||||||
|
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
if client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
|
if client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
|
||||||
@@ -124,6 +140,13 @@ func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
|
|||||||
if rec.Body.Len() != 0 {
|
if rec.Body.Len() != 0 {
|
||||||
t.Fatalf("ProxyThumbnail wrote %q on a miss; the caller needs a clean fallback", rec.Body.String())
|
t.Fatalf("ProxyThumbnail wrote %q on a miss; the caller needs a clean fallback", rec.Body.String())
|
||||||
}
|
}
|
||||||
|
want := []string{
|
||||||
|
"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg",
|
||||||
|
"GET /thumbnails/" + testThumbnailID + ".jpg",
|
||||||
|
}
|
||||||
|
if got := node.seen(); !slices.Equal(got, want) {
|
||||||
|
t.Fatalf("requests = %v, want one GET for each candidate path", got)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFetchThumbnailToScratchFallsBackToLegacyRoot(t *testing.T) {
|
func TestFetchThumbnailToScratchFallsBackToLegacyRoot(t *testing.T) {
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package coreconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// contractFile holds the fixtures the Go, Node and Python internal-secret checks must agree on. The
|
||||||
|
// Node and Python suites load the same file; see the "description" field in it.
|
||||||
|
const contractFile = "../../contract/auth-contract.json"
|
||||||
|
|
||||||
|
type internalSecretContract struct {
|
||||||
|
InternalSecret struct {
|
||||||
|
MinLength int `json:"minLength"`
|
||||||
|
Placeholders []string `json:"placeholders"`
|
||||||
|
Cases []struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
Provided string `json:"provided"`
|
||||||
|
Matches bool `json:"matches"`
|
||||||
|
} `json:"cases"`
|
||||||
|
} `json:"internalSecret"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContractInternalSecret(t *testing.T) {
|
||||||
|
data, err := os.ReadFile(contractFile)
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
t.Skipf("%s is not part of this checkout", contractFile)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var contract internalSecretContract
|
||||||
|
if err := json.Unmarshal(data, &contract); err != nil {
|
||||||
|
t.Fatalf("decode %s: %v", contractFile, err)
|
||||||
|
}
|
||||||
|
rule := contract.InternalSecret
|
||||||
|
if MinInternalSecretLength != rule.MinLength {
|
||||||
|
t.Fatalf("MinInternalSecretLength = %d, contract says %d", MinInternalSecretLength, rule.MinLength)
|
||||||
|
}
|
||||||
|
for _, placeholder := range rule.Placeholders {
|
||||||
|
if InternalSecretUsable(placeholder) {
|
||||||
|
t.Errorf("placeholder %q is usable, contract says it never gates a route", placeholder)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, entry := range rule.Cases {
|
||||||
|
if got := InternalSecretMatches(entry.Provided, entry.Secret); got != entry.Matches {
|
||||||
|
t.Errorf("%s: InternalSecretMatches = %v, contract says %v", entry.Name, got, entry.Matches)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,8 +18,35 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"unicode/utf8"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// MinInternalSecretLength is the shortest SECRET a service accepts for its internal routes.
|
||||||
|
const MinInternalSecretLength = 16
|
||||||
|
|
||||||
|
// exampleInternalSecrets are the placeholders shipped in .env.example files, plus the bare variable
|
||||||
|
// name. They are public, so they never gate a route.
|
||||||
|
var exampleInternalSecrets = map[string]bool{
|
||||||
|
"SECRET": true,
|
||||||
|
"change-me-to-a-long-random-value": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// InternalSecretUsable reports whether secret is strong enough to gate an internal route: at least
|
||||||
|
// MinInternalSecretLength characters and not an example placeholder. Length counts characters, as
|
||||||
|
// the Python and Node helpers do, not bytes.
|
||||||
|
func InternalSecretUsable(secret string) bool {
|
||||||
|
return utf8.RuneCountInString(secret) >= MinInternalSecretLength && !exampleInternalSecrets[secret]
|
||||||
|
}
|
||||||
|
|
||||||
|
// InternalSecretMatches reports whether presented is the configured secret. A secret that is not
|
||||||
|
// usable (see InternalSecretUsable) never matches, and the comparison is constant-time.
|
||||||
|
func InternalSecretMatches(presented, secret string) bool {
|
||||||
|
if !InternalSecretUsable(secret) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return subtle.ConstantTimeCompare([]byte(presented), []byte(secret)) == 1
|
||||||
|
}
|
||||||
|
|
||||||
// Info is AuthGuard's, CarrierNode's, and ProjectConfigurator's current base URL(s), as pushed by
|
// Info is AuthGuard's, CarrierNode's, and ProjectConfigurator's current base URL(s), as pushed by
|
||||||
// ProjectConfigurator.
|
// ProjectConfigurator.
|
||||||
type Info struct {
|
type Info struct {
|
||||||
@@ -178,11 +205,11 @@ func normalizeInfo(info Info) Info {
|
|||||||
// ProjectConfigurator calls to push a fresh Info: mount it at that path (see
|
// ProjectConfigurator calls to push a fresh Info: mount it at that path (see
|
||||||
// ProjectConfigurator/README.md) behind a secret check for this service's own
|
// ProjectConfigurator/README.md) behind a secret check for this service's own
|
||||||
// SECRET (the same value ProjectConfigurator and CarrierNode were configured
|
// SECRET (the same value ProjectConfigurator and CarrierNode were configured
|
||||||
// with - an empty secret refuses every caller, the same fail-closed default ProjectConfigurator's
|
// with - a secret that is not usable (see InternalSecretUsable) refuses every caller, the same
|
||||||
// own internal-auth-gated routes use).
|
// fail-closed default ProjectConfigurator's own internal-auth-gated routes use).
|
||||||
func Handler(secret string, store *Store) http.HandlerFunc {
|
func Handler(secret string, store *Store) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
if secret == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 {
|
if !InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) {
|
||||||
writeError(w, http.StatusUnauthorized, "internal service authentication required")
|
writeError(w, http.StatusUnauthorized, "internal service authentication required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ func TestStoreOnUpdateFiresWithNewInfo(t *testing.T) {
|
|||||||
|
|
||||||
func TestHandlerRejectsMissingOrWrongSecret(t *testing.T) {
|
func TestHandlerRejectsMissingOrWrongSecret(t *testing.T) {
|
||||||
store := NewStore(Info{})
|
store := NewStore(Info{})
|
||||||
handler := Handler("s3cret", store)
|
handler := Handler("test-internal-secret", store)
|
||||||
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"})
|
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"})
|
||||||
|
|
||||||
cases := []string{"", "wrong"}
|
cases := []string{"", "wrong"}
|
||||||
@@ -127,14 +127,14 @@ func equalStrings(got, want []string) bool {
|
|||||||
|
|
||||||
func TestHandlerAppliesPushedInfo(t *testing.T) {
|
func TestHandlerAppliesPushedInfo(t *testing.T) {
|
||||||
store := NewStore(Info{})
|
store := NewStore(Info{})
|
||||||
handler := Handler("s3cret", store)
|
handler := Handler("test-internal-secret", store)
|
||||||
body, _ := json.Marshal(Info{
|
body, _ := json.Marshal(Info{
|
||||||
AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com", CarrierNodeSecret: "carrier-secret",
|
AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com", CarrierNodeSecret: "carrier-secret",
|
||||||
ContentScannerURL: "http://scanner.example.com/", ContentScannerSecret: "scanner-secret",
|
ContentScannerURL: "http://scanner.example.com/", ContentScannerSecret: "scanner-secret",
|
||||||
})
|
})
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
|
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
|
||||||
req.Header.Set("X-Internal-Auth", "s3cret")
|
req.Header.Set("X-Internal-Auth", "test-internal-secret")
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
handler(rec, req)
|
handler(rec, req)
|
||||||
|
|
||||||
@@ -152,7 +152,7 @@ func TestHandlerAppliesPushedInfo(t *testing.T) {
|
|||||||
|
|
||||||
func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
|
func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
|
||||||
store := NewStore(Info{AuthGuardURL: "http://auth.example.com"})
|
store := NewStore(Info{AuthGuardURL: "http://auth.example.com"})
|
||||||
handler := Handler("s3cret", store)
|
handler := Handler("test-internal-secret", store)
|
||||||
for _, bad := range []Info{
|
for _, bad := range []Info{
|
||||||
{AuthGuardURL: "javascript:alert(1)"},
|
{AuthGuardURL: "javascript:alert(1)"},
|
||||||
{AuthGuardURL: "auth.example.com"},
|
{AuthGuardURL: "auth.example.com"},
|
||||||
@@ -161,7 +161,7 @@ func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
|
|||||||
} {
|
} {
|
||||||
body, _ := json.Marshal(bad)
|
body, _ := json.Marshal(bad)
|
||||||
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
|
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
|
||||||
req.Header.Set("X-Internal-Auth", "s3cret")
|
req.Header.Set("X-Internal-Auth", "test-internal-secret")
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
handler(rec, req)
|
handler(rec, req)
|
||||||
if rec.Code != http.StatusBadRequest {
|
if rec.Code != http.StatusBadRequest {
|
||||||
@@ -172,3 +172,21 @@ func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
|
|||||||
t.Fatalf("store changed by a rejected push: %+v", got)
|
t.Fatalf("store changed by a rejected push: %+v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHandlerRefusesAnUnusableSecret(t *testing.T) {
|
||||||
|
for _, secret := range []string{"short", "SECRET", "change-me-to-a-long-random-value"} {
|
||||||
|
store := NewStore(Info{})
|
||||||
|
handler := Handler(secret, store)
|
||||||
|
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"})
|
||||||
|
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
|
||||||
|
req.Header.Set("X-Internal-Auth", secret)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
handler(rec, req)
|
||||||
|
if rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("secret %q: status = %d, want %d", secret, rec.Code, http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
if store.Get().AuthGuardURL != "" {
|
||||||
|
t.Fatalf("secret %q: store changed despite a refused push", secret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,6 +43,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
@@ -335,13 +336,25 @@ func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) {
|
|||||||
MediaKey string `json:"mediaKey"`
|
MediaKey string `json:"mediaKey"`
|
||||||
}
|
}
|
||||||
if r.Body != nil && r.ContentLength != 0 {
|
if r.Body != nil && r.ContentLength != 0 {
|
||||||
_ = decodeRequestJSON(r, &input)
|
if err := decodeRequestJSON(r, &input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
key := strings.TrimSpace(firstNonEmpty(input.MediaKey, r.URL.Query().Get("mediaKey")))
|
key := strings.TrimSpace(firstNonEmpty(input.MediaKey, r.URL.Query().Get("mediaKey")))
|
||||||
if key == "" {
|
if key == "" {
|
||||||
writeError(w, http.StatusBadRequest, "missing mediaKey")
|
writeError(w, http.StatusBadRequest, "missing mediaKey")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
exists, err := c.mediaExists(r.Context(), key)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "media lookup failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
writeError(w, http.StatusNotFound, "media not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
var userID any
|
var userID any
|
||||||
if user != nil {
|
if user != nil {
|
||||||
userID = user.ID
|
userID = user.ID
|
||||||
@@ -368,15 +381,25 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) {
|
|||||||
if duration <= 0 {
|
if duration <= 0 {
|
||||||
duration = input.Duration
|
duration = input.Duration
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(input.MediaKey) == "" || duration <= 0 {
|
key := strings.TrimSpace(input.MediaKey)
|
||||||
writeError(w, http.StatusBadRequest, "mediaKey and positive duration are required")
|
if key == "" || duration <= 0 || duration > maxViewSessionDurationMs {
|
||||||
|
writeError(w, http.StatusBadRequest, "mediaKey and duration between 1ms and 24h are required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
exists, err := c.mediaExists(r.Context(), key)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "media lookup failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
writeError(w, http.StatusNotFound, "media not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var userID any
|
var userID any
|
||||||
if user != nil {
|
if user != nil {
|
||||||
userID = user.ID
|
userID = user.ID
|
||||||
}
|
}
|
||||||
_, err := c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, strings.TrimSpace(input.MediaKey), userID, duration)
|
_, err = c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, key, userID, duration)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, "view session could not be recorded")
|
writeError(w, http.StatusInternalServerError, "view session could not be recorded")
|
||||||
return
|
return
|
||||||
@@ -384,6 +407,15 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}})
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const maxViewSessionDurationMs int64 = 24 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
func (c *Core) mediaExists(ctx context.Context, identifier string) (bool, error) {
|
||||||
|
var exists bool
|
||||||
|
err := c.db.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM media WHERE media_key=$1 OR id=$2)`,
|
||||||
|
identifier, mediaIDArg(identifier)).Scan(&exists)
|
||||||
|
return exists, err
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) {
|
func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) {
|
||||||
user := sharedauth.UserFromContext(r.Context())
|
user := sharedauth.UserFromContext(r.Context())
|
||||||
rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID)
|
rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID)
|
||||||
@@ -793,9 +825,18 @@ func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
|
|||||||
return err != nil || hidden
|
return err != nil || hidden
|
||||||
}
|
}
|
||||||
|
|
||||||
// findMedia looks up one media item by media key or numeric id. Hidden media is only returned
|
// MediaLookupOptions controls which otherwise-hidden records a media lookup may return.
|
||||||
// when includeHidden is set.
|
type MediaLookupOptions struct {
|
||||||
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
|
// IncludeHidden lets moderators look up media with active = FALSE.
|
||||||
|
IncludeHidden bool
|
||||||
|
// RequireContentScannerProcessed limits the result to items imported by ContentScanner.
|
||||||
|
RequireContentScannerProcessed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindMedia looks up one media item by media key or numeric id. Shared media routes
|
||||||
|
// preserve moderator access to hidden items; ContentScanner-backed consumers can also
|
||||||
|
// request the same processed-only filtering used by MediaViewer's library routes.
|
||||||
|
func (c *Core) FindMedia(ctx context.Context, identifier string, options MediaLookupOptions) (MediaRecord, error) {
|
||||||
identifier = strings.TrimSpace(identifier)
|
identifier = strings.TrimSpace(identifier)
|
||||||
var record MediaRecord
|
var record MediaRecord
|
||||||
row := c.db.QueryRow(ctx, `
|
row := c.db.QueryRow(ctx, `
|
||||||
@@ -804,7 +845,8 @@ func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden b
|
|||||||
COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0),
|
COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0),
|
||||||
COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count,
|
COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count,
|
||||||
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at)
|
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at)
|
||||||
FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) LIMIT 1`, identifier, mediaIDArg(identifier), includeHidden)
|
FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) AND (NOT $4 OR content_scanner_processed) LIMIT 1`,
|
||||||
|
identifier, mediaIDArg(identifier), options.IncludeHidden, options.RequireContentScannerProcessed)
|
||||||
var title, description string
|
var title, description string
|
||||||
var width, height int
|
var width, height int
|
||||||
var duration, size int64
|
var duration, size int64
|
||||||
@@ -850,6 +892,12 @@ func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden b
|
|||||||
return record, nil
|
return record, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// findMedia keeps the shared routes on the same lookup implementation used by
|
||||||
|
// media-family applications that need ContentScanner's processed-only filter.
|
||||||
|
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
|
||||||
|
return c.FindMedia(ctx, identifier, MediaLookupOptions{IncludeHidden: includeHidden})
|
||||||
|
}
|
||||||
|
|
||||||
// ToJSON is the shared wire shape for a media record, matching every
|
// ToJSON is the shared wire shape for a media record, matching every
|
||||||
// mediacore route's own response shape (id/mediaKey/filename/url/thumbnail/
|
// mediacore route's own response shape (id/mediaKey/filename/url/thumbnail/
|
||||||
// etc.) - services with their own media listing routes (e.g. MediaViewer's
|
// etc.) - services with their own media listing routes (e.g. MediaViewer's
|
||||||
@@ -875,11 +923,28 @@ func (record MediaRecord) ToJSON() map[string]any {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SettingValue reads one key from the shared `settings` table, returning
|
// SettingValue reads one key from the shared `settings` table. An absent or empty
|
||||||
// fallback if it is unset or the read fails.
|
// setting returns fallback; database errors are returned to the caller.
|
||||||
func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) string {
|
func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) (string, error) {
|
||||||
var value string
|
var value string
|
||||||
if err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value); err != nil || value == "" {
|
err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return fallback, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if value == "" {
|
||||||
|
return fallback, nil
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SettingValueOrFallback preserves the old fallback-on-error behavior for callers
|
||||||
|
// whose API cannot return a read error. New request paths should use SettingValue.
|
||||||
|
func SettingValueOrFallback(ctx context.Context, db *pgxpool.Pool, key, fallback string) string {
|
||||||
|
value, err := SettingValue(ctx, db, key, fallback)
|
||||||
|
if err != nil {
|
||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
return value
|
return value
|
||||||
@@ -888,7 +953,7 @@ func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) s
|
|||||||
// SettingBool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true,
|
// SettingBool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true,
|
||||||
// anything else is fallback).
|
// anything else is fallback).
|
||||||
func SettingBool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool {
|
func SettingBool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool {
|
||||||
value := strings.ToLower(strings.TrimSpace(SettingValue(ctx, db, key, "")))
|
value := strings.ToLower(strings.TrimSpace(SettingValueOrFallback(ctx, db, key, "")))
|
||||||
if value == "" {
|
if value == "" {
|
||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
@@ -922,19 +987,19 @@ var carrierNodeInstancePattern = regexp.MustCompile(`^carriernode(_\d+)?$`)
|
|||||||
// Returns fallback if no carriernode* instance is registered (or none has a URL) yet.
|
// Returns fallback if no carriernode* instance is registered (or none has a URL) yet.
|
||||||
func CarrierNodeURLs(ctx context.Context, db *pgxpool.Pool, fallback []string) []string {
|
func CarrierNodeURLs(ctx context.Context, db *pgxpool.Pool, fallback []string) []string {
|
||||||
var registered []string
|
var registered []string
|
||||||
_ = json.Unmarshal([]byte(SettingValue(ctx, db, "configured_central", "")), ®istered)
|
_ = json.Unmarshal([]byte(SettingValueOrFallback(ctx, db, "configured_central", "")), ®istered)
|
||||||
var urls []string
|
var urls []string
|
||||||
for _, project := range registered {
|
for _, project := range registered {
|
||||||
key := strings.ToLower(strings.TrimSpace(project))
|
key := strings.ToLower(strings.TrimSpace(project))
|
||||||
if !carrierNodeInstancePattern.MatchString(key) {
|
if !carrierNodeInstancePattern.MatchString(key) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if url := strings.TrimSpace(SettingValue(ctx, db, key+"_url", "")); url != "" {
|
if url := strings.TrimSpace(SettingValueOrFallback(ctx, db, key+"_url", "")); url != "" {
|
||||||
urls = append(urls, url)
|
urls = append(urls, url)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(urls) == 0 {
|
if len(urls) == 0 {
|
||||||
if url := strings.TrimSpace(SettingValue(ctx, db, "carriernode_url", "")); url != "" {
|
if url := strings.TrimSpace(SettingValueOrFallback(ctx, db, "carriernode_url", "")); url != "" {
|
||||||
urls = []string{url}
|
urls = []string{url}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,11 +9,28 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestSettingValueReturnsDatabaseErrors(t *testing.T) {
|
||||||
|
db, err := pgxpool.New(context.Background(), "postgres://nobody@127.0.0.1:1/none?sslmode=disable&connect_timeout=1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pgxpool.New: %v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
value, err := SettingValue(context.Background(), db, "example", "fallback")
|
||||||
|
if err == nil || value != "" {
|
||||||
|
t.Fatalf("SettingValue() = %q, %v; want empty value and database error", value, err)
|
||||||
|
}
|
||||||
|
if got := SettingValueOrFallback(context.Background(), db, "example", "fallback"); got != "fallback" {
|
||||||
|
t.Fatalf("SettingValueOrFallback() = %q, want fallback on error", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be
|
// loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be
|
||||||
// exercised without a database.
|
// exercised without a database.
|
||||||
type loginRequiredStore struct{}
|
type loginRequiredStore struct{}
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ func (c *Core) Migrate(ctx context.Context) error {
|
|||||||
var migrationStatements = []string{
|
var migrationStatements = []string{
|
||||||
`CREATE EXTENSION IF NOT EXISTS pgcrypto`,
|
`CREATE EXTENSION IF NOT EXISTS pgcrypto`,
|
||||||
`CREATE EXTENSION IF NOT EXISTS pg_trgm`,
|
`CREATE EXTENSION IF NOT EXISTS pg_trgm`,
|
||||||
|
`DROP INDEX IF EXISTS media_search_idx`,
|
||||||
|
|
||||||
`CREATE TABLE IF NOT EXISTS users (
|
`CREATE TABLE IF NOT EXISTS users (
|
||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
@@ -85,7 +86,6 @@ var migrationStatements = []string{
|
|||||||
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`,
|
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`,
|
||||||
`CREATE INDEX IF NOT EXISTS media_active_idx ON media (active)`,
|
`CREATE INDEX IF NOT EXISTS media_active_idx ON media (active)`,
|
||||||
`CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path)`,
|
`CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path)`,
|
||||||
`CREATE INDEX IF NOT EXISTS media_search_idx ON media USING GIN (to_tsvector('simple', COALESCE(title, '') || ' ' || COALESCE(original_filename, '') || ' ' || COALESCE(file_path, '')))`,
|
|
||||||
`CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`,
|
`CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`,
|
||||||
|
|
||||||
`CREATE TABLE IF NOT EXISTS media_stats (
|
`CREATE TABLE IF NOT EXISTS media_stats (
|
||||||
|
|||||||
@@ -1,31 +1,60 @@
|
|||||||
{
|
{
|
||||||
"description": "Fixtures that the Go, Node and Python auth helpers must agree on. Each runtime's test suite loads this file and checks its own column; a value that differs between runtimes is a known divergence (Q-008) and is written down here rather than hidden. Change a value only together with the code that changes the behaviour.",
|
"description": "Fixtures that the Go, Node and Python auth helpers must agree on. Each runtime's test suite loads this file and checks its own column. Change a value only together with the code that changes the behavior.",
|
||||||
"password": {
|
"password": {
|
||||||
"plaintext": "correct horse battery staple",
|
"plaintext": "correct horse battery staple",
|
||||||
"wrongPassword": "not the right password",
|
"wrongPassword": "not the right password",
|
||||||
"hashes": [
|
"hashes": [
|
||||||
{
|
{
|
||||||
"name": "Node, current pbkdf2-sha256 scheme",
|
"name": "Legacy PBKDF2 scheme with recorded iteration count",
|
||||||
"hash": "pbkdf2-sha256$600000$76add00c36dafceac62928d01f706c20$f50eec2591755f169bd151369e41a4e6918c6a2816d19516cc38763bfa63c0ca",
|
"hash": "pbkdf2-sha256$600000$76add00c36dafceac62928d01f706c20$f50eec2591755f169bd151369e41a4e6918c6a2816d19516cc38763bfa63c0ca",
|
||||||
"verifies": {
|
"verifies": {
|
||||||
"go": false,
|
"go": true,
|
||||||
"node": true,
|
"node": true,
|
||||||
"python": false
|
"python": true
|
||||||
},
|
},
|
||||||
"needsUpgrade": {
|
"needsUpgrade": {
|
||||||
"node": false
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "Node, legacy salt:hex at 100000 iterations",
|
"name": "Legacy salt:hex PBKDF2 at 100000 iterations",
|
||||||
"hash": "0123456789abcdef0123456789abcdef:69a26fc4b1624cd29ecc2b2444aa876251575c65deb4af9effbd9eadbd4195c6",
|
"hash": "0123456789abcdef0123456789abcdef:69a26fc4b1624cd29ecc2b2444aa876251575c65deb4af9effbd9eadbd4195c6",
|
||||||
"verifies": {
|
"verifies": {
|
||||||
"go": false,
|
"go": true,
|
||||||
"node": true,
|
"node": true,
|
||||||
"python": false
|
"python": true
|
||||||
},
|
},
|
||||||
"needsUpgrade": {
|
"needsUpgrade": {
|
||||||
"node": true
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Legacy PBKDF2 password over bcrypt's input limit",
|
||||||
|
"hash": "0123456789abcdef0123456789abcdef:a8a80395df31b48bfb1dc4fabb6457dc61a50aae0c8d469f618303f0cea367b2",
|
||||||
|
"password": "legacy:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||||
|
"wrongPassword": "legacy:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy",
|
||||||
|
"verifies": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
},
|
||||||
|
"needsUpgrade": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Current bcrypt scheme with cost 12",
|
||||||
|
"hash": "bcrypt$$2b$12$NExB1DALH97MOTr6ZSUjYOb4gc.2g/uWCqbUX1d/c450damk1A9r2",
|
||||||
|
"verifies": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -33,11 +62,12 @@
|
|||||||
"hash": "bcrypt$$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
|
"hash": "bcrypt$$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
|
||||||
"verifies": {
|
"verifies": {
|
||||||
"go": true,
|
"go": true,
|
||||||
"node": false,
|
"node": true,
|
||||||
"python": true
|
"python": true
|
||||||
},
|
},
|
||||||
"needsUpgrade": {
|
"needsUpgrade": {
|
||||||
"go": true,
|
"go": true,
|
||||||
|
"node": true,
|
||||||
"python": true
|
"python": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -46,11 +76,12 @@
|
|||||||
"hash": "$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
|
"hash": "$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
|
||||||
"verifies": {
|
"verifies": {
|
||||||
"go": true,
|
"go": true,
|
||||||
"node": false,
|
"node": true,
|
||||||
"python": true
|
"python": true
|
||||||
},
|
},
|
||||||
"needsUpgrade": {
|
"needsUpgrade": {
|
||||||
"go": true,
|
"go": true,
|
||||||
|
"node": true,
|
||||||
"python": true
|
"python": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -86,10 +117,10 @@
|
|||||||
"bytes": 73,
|
"bytes": 73,
|
||||||
"accepted": {
|
"accepted": {
|
||||||
"go": false,
|
"go": false,
|
||||||
"node": true,
|
"node": false,
|
||||||
"python": false
|
"python": false
|
||||||
},
|
},
|
||||||
"note": "bcrypt reads only the first 72 bytes, so Go and Python refuse a longer password; PBKDF2 has no such limit."
|
"note": "New passwords over 72 bytes are refused. Existing longer PBKDF2 passwords still verify and migrate to the marked bcrypt-sha256 scheme without truncation."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"totp": {
|
"totp": {
|
||||||
@@ -129,12 +160,14 @@
|
|||||||
"name": "the next step still accepts the previous code",
|
"name": "the next step still accepts the previous code",
|
||||||
"unix": 1111111139,
|
"unix": 1111111139,
|
||||||
"code": "081804",
|
"code": "081804",
|
||||||
|
"matchedStep": 37037036,
|
||||||
"valid": true
|
"valid": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "the previous step accepts the next code",
|
"name": "the previous step accepts the next code",
|
||||||
"unix": 1111111079,
|
"unix": 1111111079,
|
||||||
"code": "081804",
|
"code": "081804",
|
||||||
|
"matchedStep": 37037036,
|
||||||
"valid": true
|
"valid": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -321,5 +354,75 @@
|
|||||||
"want": "2001:db8::9"
|
"want": "2001:db8::9"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
"internalSecret": {
|
||||||
|
"note": "The SECRET that gates a service's internal routes (X-Internal-Auth). Length counts characters (code points), not bytes. Every runtime reads minLength and placeholders from here.",
|
||||||
|
"minLength": 16,
|
||||||
|
"placeholders": [
|
||||||
|
"SECRET",
|
||||||
|
"change-me-to-a-long-random-value"
|
||||||
|
],
|
||||||
|
"cases": [
|
||||||
|
{
|
||||||
|
"name": "unset secret never matches",
|
||||||
|
"secret": "",
|
||||||
|
"provided": "",
|
||||||
|
"matches": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "missing header never matches",
|
||||||
|
"secret": "0123456789abcdef",
|
||||||
|
"provided": "",
|
||||||
|
"matches": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "secret one character under the minimum never matches",
|
||||||
|
"secret": "0123456789abcde",
|
||||||
|
"provided": "0123456789abcde",
|
||||||
|
"matches": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "secret at the minimum matches itself",
|
||||||
|
"secret": "0123456789abcdef",
|
||||||
|
"provided": "0123456789abcdef",
|
||||||
|
"matches": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "a prefix of the secret does not match",
|
||||||
|
"secret": "0123456789abcdef",
|
||||||
|
"provided": "0123456789abcde",
|
||||||
|
"matches": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comparison is exact",
|
||||||
|
"secret": "0123456789abcdef",
|
||||||
|
"provided": "0123456789abcdeF",
|
||||||
|
"matches": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "length counts characters, not bytes",
|
||||||
|
"secret": "éééééééééééééééé",
|
||||||
|
"provided": "éééééééééééééééé",
|
||||||
|
"matches": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "fifteen multibyte characters are too short",
|
||||||
|
"secret": "ééééééééééééééé",
|
||||||
|
"provided": "ééééééééééééééé",
|
||||||
|
"matches": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "the example placeholder never matches",
|
||||||
|
"secret": "change-me-to-a-long-random-value",
|
||||||
|
"provided": "change-me-to-a-long-random-value",
|
||||||
|
"matches": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "the bare variable name never matches",
|
||||||
|
"secret": "SECRET",
|
||||||
|
"provided": "SECRET",
|
||||||
|
"matches": false
|
||||||
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Generated
+10
@@ -2491,6 +2491,15 @@
|
|||||||
"node": "18 || 20 || >=22"
|
"node": "18 || 20 || >=22"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/bcryptjs": {
|
||||||
|
"version": "3.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz",
|
||||||
|
"integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"bin": {
|
||||||
|
"bcrypt": "bin/bcrypt"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/better-path-resolve": {
|
"node_modules/better-path-resolve": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/better-path-resolve/-/better-path-resolve-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/better-path-resolve/-/better-path-resolve-1.0.0.tgz",
|
||||||
@@ -5482,6 +5491,7 @@
|
|||||||
"version": "0.1.1",
|
"version": "0.1.1",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
"pg": "^8.17.2"
|
"pg": "^8.17.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ public final class Totp {
|
|||||||
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||||
private static final int SECRET_BYTES = 20;
|
private static final int SECRET_BYTES = 20;
|
||||||
private static final int PERIOD_SECONDS = 30;
|
private static final int PERIOD_SECONDS = 30;
|
||||||
private static final int WINDOW = 1;
|
|
||||||
private static final int DIGITS = 6;
|
private static final int DIGITS = 6;
|
||||||
private static final SecureRandom RANDOM = new SecureRandom();
|
private static final SecureRandom RANDOM = new SecureRandom();
|
||||||
|
|
||||||
@@ -43,22 +42,28 @@ public final class Totp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static boolean verify(String secret, String token, long nowMillis) {
|
public static boolean verify(String secret, String token, long nowMillis) {
|
||||||
|
return verifyStep(secret, token, nowMillis) >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns the matching 30-second step, or {@code -1} when no code matches. */
|
||||||
|
public static long verifyStep(String secret, String token, long nowMillis) {
|
||||||
String normalizedSecret = normalizeSecret(secret);
|
String normalizedSecret = normalizeSecret(secret);
|
||||||
String normalizedToken = token == null ? "" : token.trim();
|
String normalizedToken = token == null ? "" : token.trim();
|
||||||
if (normalizedSecret.isEmpty() || !normalizedToken.matches("\\d{" + DIGITS + "}")) {
|
if (normalizedSecret.isEmpty() || !normalizedToken.matches("\\d{" + DIGITS + "}")) {
|
||||||
return false;
|
return -1;
|
||||||
}
|
}
|
||||||
byte[] key;
|
byte[] key;
|
||||||
try {
|
try {
|
||||||
key = decodeBase32(normalizedSecret);
|
key = decodeBase32(normalizedSecret);
|
||||||
} catch (IllegalArgumentException ex) {
|
} catch (IllegalArgumentException ex) {
|
||||||
return false;
|
return -1;
|
||||||
}
|
}
|
||||||
if (key.length == 0) {
|
if (key.length == 0) {
|
||||||
return false;
|
return -1;
|
||||||
}
|
}
|
||||||
long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L);
|
long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L);
|
||||||
for (long offset = -WINDOW; offset <= WINDOW; offset++) {
|
// Prefer the current step if a six-digit collision occurs in the window.
|
||||||
|
for (long offset : new long[] {0, -1, 1}) {
|
||||||
if (counter + offset < 0) {
|
if (counter + offset < 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -80,13 +85,13 @@ public final class Totp {
|
|||||||
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
|
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
|
||||||
if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII),
|
if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII),
|
||||||
normalizedToken.getBytes(StandardCharsets.US_ASCII))) {
|
normalizedToken.getBytes(StandardCharsets.US_ASCII))) {
|
||||||
return true;
|
return counter + offset;
|
||||||
}
|
}
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
return false;
|
return -1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String normalizeSecret(String value) {
|
private static String normalizeSecret(String value) {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ class TotpTest {
|
|||||||
void verifyAcceptsTheRfc6238Vectors() {
|
void verifyAcceptsTheRfc6238Vectors() {
|
||||||
// The RFC lists 8-digit codes; these are their last six digits.
|
// The RFC lists 8-digit codes; these are their last six digits.
|
||||||
assertTrue(Totp.verify(RFC_SECRET, "287082", 59_000L));
|
assertTrue(Totp.verify(RFC_SECRET, "287082", 59_000L));
|
||||||
|
assertEquals(1L, Totp.verifyStep(RFC_SECRET, "287082", 59_000L));
|
||||||
assertTrue(Totp.verify(RFC_SECRET, "081804", 1_111_111_109_000L));
|
assertTrue(Totp.verify(RFC_SECRET, "081804", 1_111_111_109_000L));
|
||||||
assertTrue(Totp.verify(RFC_SECRET, "050471", 1_111_111_111_000L));
|
assertTrue(Totp.verify(RFC_SECRET, "050471", 1_111_111_111_000L));
|
||||||
assertTrue(Totp.verify(RFC_SECRET, "005924", 1_234_567_890_000L));
|
assertTrue(Totp.verify(RFC_SECRET, "005924", 1_234_567_890_000L));
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
"./package.json": "./package.json"
|
"./package.json": "./package.json"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
"pg": "^8.17.2"
|
"pg": "^8.17.2"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
import { promisify } from 'node:util';
|
import { promisify } from 'node:util';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
import { verifyTotpStep } from './totp.js';
|
||||||
|
|
||||||
const pbkdf2 = promisify(crypto.pbkdf2);
|
const pbkdf2 = promisify(crypto.pbkdf2);
|
||||||
|
|
||||||
// Hashes written before the format recorded its parameters are `salt:hex` at
|
// Node's old formats remain readable so successful logins can migrate them.
|
||||||
// this count. They still verify and are rewritten on the next successful login.
|
|
||||||
// New hashes use PASSWORD_ITERATIONS and carry the scheme prefix PASSWORD_FORMAT.
|
|
||||||
const LEGACY_PASSWORD_ITERATIONS = 100000;
|
const LEGACY_PASSWORD_ITERATIONS = 100000;
|
||||||
const PASSWORD_ITERATIONS = 600000;
|
const MAX_PBKDF2_ITERATIONS = 10000000;
|
||||||
const PASSWORD_KEY_LENGTH = 32;
|
const PASSWORD_KEY_LENGTH = 32;
|
||||||
const PASSWORD_DIGEST = 'sha256';
|
const PASSWORD_DIGEST = 'sha256';
|
||||||
const PASSWORD_FORMAT = 'pbkdf2-sha256';
|
const PASSWORD_FORMAT = 'pbkdf2-sha256';
|
||||||
|
const BCRYPT_SCHEME = 'bcrypt$';
|
||||||
|
const BCRYPT_SHA256_SCHEME = 'bcrypt-sha256$';
|
||||||
|
const BCRYPT_ROUNDS = 12;
|
||||||
|
const BCRYPT_MAX_PASSWORD_BYTES = 72;
|
||||||
const LEGACY_PASSWORD_PATTERN = /^[0-9a-f]+:[0-9a-f]+$/;
|
const LEGACY_PASSWORD_PATTERN = /^[0-9a-f]+:[0-9a-f]+$/;
|
||||||
export const RESET_CODE_TTL_MS = 5 * 60 * 1000;
|
export const RESET_CODE_TTL_MS = 5 * 60 * 1000;
|
||||||
export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' });
|
export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' });
|
||||||
@@ -38,6 +42,7 @@ CREATE TABLE IF NOT EXISTS auth_users (
|
|||||||
role TEXT NOT NULL DEFAULT 'user',
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
totp_secret TEXT NOT NULL DEFAULT '',
|
totp_secret TEXT NOT NULL DEFAULT '',
|
||||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
last_used_step BIGINT NOT NULL DEFAULT -1,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
);
|
);
|
||||||
@@ -45,6 +50,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
|||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
UPDATE auth_users SET role = 'superadmin'
|
UPDATE auth_users SET role = 'superadmin'
|
||||||
@@ -100,38 +106,47 @@ function assertPasswordLength(password) {
|
|||||||
if (typeof password !== 'string' || password.length < 8) {
|
if (typeof password !== 'string' || password.length < 8) {
|
||||||
throw new Error('Password must be at least 8 characters');
|
throw new Error('Password must be at least 8 characters');
|
||||||
}
|
}
|
||||||
|
if (Buffer.byteLength(password, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) {
|
||||||
|
throw new Error(`Password must be at most ${BCRYPT_MAX_PASSWORD_BYTES} bytes`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function encodePasswordHash(salt, hash, iterations) {
|
function parsePbkdf2Hash(stored) {
|
||||||
return [PASSWORD_FORMAT, iterations, salt, hash.toString('hex')].join('$');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the salt, expected hash and iteration count recorded in a stored hash,
|
|
||||||
// or null for a format this module does not verify (such as bcrypt written by
|
|
||||||
// the Python or Go packages).
|
|
||||||
function parsePasswordHash(stored) {
|
|
||||||
const text = String(stored);
|
const text = String(stored);
|
||||||
|
let iterations = LEGACY_PASSWORD_ITERATIONS;
|
||||||
|
let salt;
|
||||||
|
let expected;
|
||||||
if (text.startsWith(`${PASSWORD_FORMAT}$`)) {
|
if (text.startsWith(`${PASSWORD_FORMAT}$`)) {
|
||||||
const parts = text.split('$');
|
const parts = text.split('$');
|
||||||
if (parts.length !== 4) return null;
|
if (parts.length !== 4) return null;
|
||||||
const [, iterations, salt, expected] = parts;
|
[, iterations, salt, expected] = parts;
|
||||||
return { iterations: Number(iterations), salt, expected, legacy: false };
|
iterations = Number(iterations);
|
||||||
}
|
} else if (LEGACY_PASSWORD_PATTERN.test(text)) {
|
||||||
if (LEGACY_PASSWORD_PATTERN.test(text)) {
|
[salt, expected] = text.split(':');
|
||||||
const [salt, expected] = text.split(':');
|
} else {
|
||||||
return { iterations: LEGACY_PASSWORD_ITERATIONS, salt, expected, legacy: true };
|
return null;
|
||||||
}
|
}
|
||||||
|
if (!/^[0-9a-f]{32}$/.test(salt) || !/^[0-9a-f]{64}$/.test(expected)) return null;
|
||||||
|
if (!Number.isSafeInteger(iterations) || iterations < 1 || iterations > MAX_PBKDF2_ITERATIONS) return null;
|
||||||
|
return { iterations, salt, expected };
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBcryptHash(stored) {
|
||||||
|
const text = String(stored);
|
||||||
|
if (text.startsWith(BCRYPT_SHA256_SCHEME)) return { hash: text.slice(BCRYPT_SHA256_SCHEME.length), prehashed: true };
|
||||||
|
if (text.startsWith(BCRYPT_SCHEME)) return { hash: text.slice(BCRYPT_SCHEME.length), prehashed: false };
|
||||||
|
if (/^\$2[aby]\$/.test(text)) return { hash: text, prehashed: false, legacy: true };
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function usablePasswordHash(stored) {
|
function validBcryptHash(parsed) {
|
||||||
const parsed = parsePasswordHash(stored);
|
if (!parsed?.hash) return false;
|
||||||
if (!parsed || !parsed.salt || !parsed.expected || !isValidIterations(parsed.iterations)) return null;
|
try {
|
||||||
return parsed;
|
bcrypt.getRounds(parsed.hash);
|
||||||
}
|
return true;
|
||||||
|
} catch {
|
||||||
function isValidIterations(iterations) {
|
return false;
|
||||||
return Number.isSafeInteger(iterations) && iterations >= 1;
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function passwordHashMatches(expected, actual) {
|
function passwordHashMatches(expected, actual) {
|
||||||
@@ -140,34 +155,52 @@ function passwordHashMatches(expected, actual) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Blocking PBKDF2 hash. Prefer hashPasswordAsync in request handlers, because
|
* Blocking bcrypt hash. Prefer hashPasswordAsync in request handlers, because
|
||||||
* this call holds the event loop for the whole derivation.
|
* this call holds the event loop for the whole derivation.
|
||||||
*/
|
*/
|
||||||
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
|
export function hashPassword(password) {
|
||||||
assertPasswordLength(password);
|
assertPasswordLength(password);
|
||||||
const salt = crypto.randomBytes(16).toString('hex');
|
return BCRYPT_SCHEME + bcrypt.hashSync(password, BCRYPT_ROUNDS);
|
||||||
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
|
||||||
return encodePasswordHash(salt, hash, iterations);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Non-blocking variant of hashPassword with the same output format. */
|
/** Non-blocking variant of hashPassword with the same bcrypt format. */
|
||||||
export async function hashPasswordAsync(password, { iterations = PASSWORD_ITERATIONS } = {}) {
|
export async function hashPasswordAsync(password) {
|
||||||
assertPasswordLength(password);
|
assertPasswordLength(password);
|
||||||
return derivePasswordHashAsync(password, iterations);
|
return BCRYPT_SCHEME + await bcrypt.hash(password, BCRYPT_ROUNDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The length rule belongs to user-facing hashing. Upgrading an old hash must
|
// A legacy PBKDF2 password can exceed bcrypt's 72-byte input limit. Preserve
|
||||||
// not refuse a password that was accepted when it was first set.
|
// the full password by hashing its UTF-8 bytes before bcrypt and marking that
|
||||||
async function derivePasswordHashAsync(password, iterations) {
|
// representation explicitly in the stored scheme.
|
||||||
const salt = crypto.randomBytes(16).toString('hex');
|
function bcryptInputForLegacyPassword(password) {
|
||||||
const hash = await pbkdf2(String(password), salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
const text = String(password);
|
||||||
return encodePasswordHash(salt, hash, iterations);
|
if (Buffer.byteLength(text, 'utf8') <= BCRYPT_MAX_PASSWORD_BYTES) {
|
||||||
|
return { scheme: BCRYPT_SCHEME, input: text };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
scheme: BCRYPT_SHA256_SCHEME,
|
||||||
|
input: crypto.createHash('sha256').update(text, 'utf8').digest('hex'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function derivePasswordHashAsync(password) {
|
||||||
|
const { scheme, input } = bcryptInputForLegacyPassword(password);
|
||||||
|
return scheme + await bcrypt.hash(input, BCRYPT_ROUNDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Blocking verify. Prefer verifyPasswordAsync in request handlers. */
|
/** Blocking verify. Prefer verifyPasswordAsync in request handlers. */
|
||||||
export function verifyPassword(password, stored) {
|
export function verifyPassword(password, stored) {
|
||||||
try {
|
try {
|
||||||
const parsed = usablePasswordHash(stored);
|
const bcryptHash = parseBcryptHash(stored);
|
||||||
|
if (bcryptHash) {
|
||||||
|
if (!validBcryptHash(bcryptHash)) return false;
|
||||||
|
const input = bcryptHash.prehashed
|
||||||
|
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
|
||||||
|
: String(password);
|
||||||
|
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
|
||||||
|
return bcrypt.compareSync(input, bcryptHash.hash);
|
||||||
|
}
|
||||||
|
const parsed = parsePbkdf2Hash(stored);
|
||||||
if (!parsed) return false;
|
if (!parsed) return false;
|
||||||
const actual = crypto.pbkdf2Sync(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
const actual = crypto.pbkdf2Sync(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||||
return passwordHashMatches(parsed.expected, actual);
|
return passwordHashMatches(parsed.expected, actual);
|
||||||
@@ -179,7 +212,16 @@ export function verifyPassword(password, stored) {
|
|||||||
/** Non-blocking variant of verifyPassword. */
|
/** Non-blocking variant of verifyPassword. */
|
||||||
export async function verifyPasswordAsync(password, stored) {
|
export async function verifyPasswordAsync(password, stored) {
|
||||||
try {
|
try {
|
||||||
const parsed = usablePasswordHash(stored);
|
const bcryptHash = parseBcryptHash(stored);
|
||||||
|
if (bcryptHash) {
|
||||||
|
if (!validBcryptHash(bcryptHash)) return false;
|
||||||
|
const input = bcryptHash.prehashed
|
||||||
|
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
|
||||||
|
: String(password);
|
||||||
|
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
|
||||||
|
return await bcrypt.compare(input, bcryptHash.hash);
|
||||||
|
}
|
||||||
|
const parsed = parsePbkdf2Hash(stored);
|
||||||
if (!parsed) return false;
|
if (!parsed) return false;
|
||||||
const actual = await pbkdf2(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
const actual = await pbkdf2(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||||
return passwordHashMatches(parsed.expected, actual);
|
return passwordHashMatches(parsed.expected, actual);
|
||||||
@@ -189,12 +231,15 @@ export async function verifyPasswordAsync(password, stored) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* True when a stored hash should be rewritten after a successful login: a
|
* True when a stored hash should be rewritten after a successful login.
|
||||||
* legacy `salt:hex` hash, or a PBKDF2 hash below PASSWORD_ITERATIONS.
|
|
||||||
*/
|
*/
|
||||||
export function passwordHashNeedsUpgrade(stored) {
|
export function passwordHashNeedsUpgrade(stored) {
|
||||||
const parsed = parsePasswordHash(stored);
|
const bcryptHash = parseBcryptHash(stored);
|
||||||
return !parsed || parsed.legacy || parsed.iterations < PASSWORD_ITERATIONS;
|
if (bcryptHash) {
|
||||||
|
if (!validBcryptHash(bcryptHash)) return true;
|
||||||
|
return Boolean(bcryptHash.legacy) || bcrypt.getRounds(bcryptHash.hash) < BCRYPT_ROUNDS;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -210,7 +255,7 @@ export async function verifyAndUpgradePasswordAsync(password, stored) {
|
|||||||
if (!passwordHashNeedsUpgrade(stored)) {
|
if (!passwordHashNeedsUpgrade(stored)) {
|
||||||
return { valid: true, upgradedHash: null };
|
return { valid: true, upgradedHash: null };
|
||||||
}
|
}
|
||||||
return { valid: true, upgradedHash: await derivePasswordHashAsync(password, PASSWORD_ITERATIONS) };
|
return { valid: true, upgradedHash: await derivePasswordHashAsync(password) };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createSessionToken() {
|
export function createSessionToken() {
|
||||||
@@ -412,10 +457,10 @@ export class AuthStore {
|
|||||||
|
|
||||||
async getTotpState(userId) {
|
async getTotpState(userId) {
|
||||||
const result = await this.database.query(
|
const result = await this.database.query(
|
||||||
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled FROM auth_users WHERE id = $1',
|
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled, COALESCE(last_used_step, -1) AS last_used_step FROM auth_users WHERE id = $1',
|
||||||
[userId],
|
[userId],
|
||||||
);
|
);
|
||||||
return result.rows[0] || { secret: '', enabled: false };
|
return result.rows[0] || { secret: '', enabled: false, last_used_step: -1 };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -425,7 +470,7 @@ export class AuthStore {
|
|||||||
*/
|
*/
|
||||||
async setTotpSecret(userId, secret) {
|
async setTotpSecret(userId, secret) {
|
||||||
const result = await this.database.query(
|
const result = await this.database.query(
|
||||||
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled',
|
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled',
|
||||||
[secret, userId],
|
[secret, userId],
|
||||||
);
|
);
|
||||||
if (result.rowCount === 0 && (await this.getTotpState(userId)).enabled) {
|
if (result.rowCount === 0 && (await this.getTotpState(userId)).enabled) {
|
||||||
@@ -433,16 +478,33 @@ export class AuthStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async enableTotp(userId) {
|
async enableTotp(userId, token, now = Date.now()) {
|
||||||
await this.database.query(
|
const state = await this.getTotpState(userId);
|
||||||
"UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''",
|
if (!state.secret || state.enabled) return false;
|
||||||
[userId],
|
const step = verifyTotpStep(state.secret, token, now);
|
||||||
|
if (step === null) return false;
|
||||||
|
const result = await this.database.query(
|
||||||
|
"UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1",
|
||||||
|
[step, userId, state.secret],
|
||||||
);
|
);
|
||||||
|
return result.rowCount === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
async consumeTotpCode(userId, token, now = Date.now()) {
|
||||||
|
const state = await this.getTotpState(userId);
|
||||||
|
if (!state.secret || !state.enabled) return false;
|
||||||
|
const step = verifyTotpStep(state.secret, token, now);
|
||||||
|
if (step === null) return false;
|
||||||
|
const result = await this.database.query(
|
||||||
|
'UPDATE auth_users SET last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1',
|
||||||
|
[step, userId, state.secret],
|
||||||
|
);
|
||||||
|
return result.rowCount === 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
async disableTotp(userId) {
|
async disableTotp(userId) {
|
||||||
await this.database.query(
|
await this.database.query(
|
||||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1",
|
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1",
|
||||||
[userId],
|
[userId],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,16 +60,38 @@ export class Info {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Shortest SECRET a service accepts for its internal routes. */
|
||||||
|
export const MIN_INTERNAL_SECRET_LENGTH = 16;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* True when the X-Internal-Auth value equals the configured secret. An unset
|
* Placeholders from .env.example files and the bare variable name. They are
|
||||||
* or empty secret never matches, and the comparison is constant-time.
|
* public, so they never gate a route.
|
||||||
|
*/
|
||||||
|
export const EXAMPLE_INTERNAL_SECRETS = new Set(['SECRET', 'change-me-to-a-long-random-value']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the configured secret is strong enough to gate an internal route:
|
||||||
|
* at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
|
||||||
|
* placeholder. Length counts characters, as the Python and Go helpers do.
|
||||||
|
* @param {unknown} secret
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function internalSecretUsable(secret) {
|
||||||
|
const value = String(secret ?? '');
|
||||||
|
return [...value].length >= MIN_INTERNAL_SECRET_LENGTH && !EXAMPLE_INTERNAL_SECRETS.has(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the X-Internal-Auth value equals the configured secret. A secret
|
||||||
|
* that is not usable (see internalSecretUsable) never matches, and the
|
||||||
|
* comparison is constant-time.
|
||||||
* @param {unknown} provided
|
* @param {unknown} provided
|
||||||
* @param {unknown} secret
|
* @param {unknown} secret
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
export function internalSecretMatches(provided, secret) {
|
export function internalSecretMatches(provided, secret) {
|
||||||
const expected = Buffer.from(String(secret ?? ''));
|
if (!internalSecretUsable(secret)) return false;
|
||||||
if (expected.length === 0) return false;
|
const expected = Buffer.from(String(secret));
|
||||||
const actual = Buffer.from(String(provided ?? ''));
|
const actual = Buffer.from(String(provided ?? ''));
|
||||||
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,11 +33,15 @@ export {
|
|||||||
generateTotpSecret,
|
generateTotpSecret,
|
||||||
totpProvisioningUri,
|
totpProvisioningUri,
|
||||||
verifyTotp,
|
verifyTotp,
|
||||||
|
verifyTotpStep,
|
||||||
} from './totp.js';
|
} from './totp.js';
|
||||||
export { runMigrations } from './migrate.js';
|
export { runMigrations } from './migrate.js';
|
||||||
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
|
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
|
||||||
export {
|
export {
|
||||||
|
EXAMPLE_INTERNAL_SECRETS,
|
||||||
Info as CoreConfigInfo,
|
Info as CoreConfigInfo,
|
||||||
|
MIN_INTERNAL_SECRET_LENGTH,
|
||||||
Store as CoreConfigStore,
|
Store as CoreConfigStore,
|
||||||
internalSecretMatches,
|
internalSecretMatches,
|
||||||
|
internalSecretUsable,
|
||||||
} from './coreconfig.js';
|
} from './coreconfig.js';
|
||||||
@@ -24,19 +24,24 @@ export function totpProvisioningUri(issuer, account, secret) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function verifyTotp(secret, token, now = Date.now()) {
|
export function verifyTotp(secret, token, now = Date.now()) {
|
||||||
|
return verifyTotpStep(secret, token, now) !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verifyTotpStep(secret, token, now = Date.now()) {
|
||||||
const normalizedSecret = normalizeSecret(secret);
|
const normalizedSecret = normalizeSecret(secret);
|
||||||
const normalizedToken = normalizeToken(token);
|
const normalizedToken = normalizeToken(token);
|
||||||
if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return false;
|
if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return null;
|
||||||
|
|
||||||
let key;
|
let key;
|
||||||
try {
|
try {
|
||||||
key = decodeBase32(normalizedSecret);
|
key = decodeBase32(normalizedSecret);
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return null;
|
||||||
}
|
}
|
||||||
if (key.length === 0) return false;
|
if (key.length === 0) return null;
|
||||||
const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS);
|
const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS);
|
||||||
for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset += 1) {
|
// Prefer the current step if a six-digit collision occurs in the window.
|
||||||
|
for (const offset of [0, -1, 1]) {
|
||||||
if (period + offset < 0) continue;
|
if (period + offset < 0) continue;
|
||||||
const counter = Buffer.alloc(8);
|
const counter = Buffer.alloc(8);
|
||||||
counter.writeBigUInt64BE(BigInt(period + offset));
|
counter.writeBigUInt64BE(BigInt(period + offset));
|
||||||
@@ -47,9 +52,9 @@ export function verifyTotp(secret, token, now = Date.now()) {
|
|||||||
| (digest[index + 2] << 8)
|
| (digest[index + 2] << 8)
|
||||||
| digest[index + 3];
|
| digest[index + 3];
|
||||||
const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0');
|
const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0');
|
||||||
if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return true;
|
if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return period + offset;
|
||||||
}
|
}
|
||||||
return false;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeSecret(value) {
|
function normalizeSecret(value) {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
verifyPassword,
|
verifyPassword,
|
||||||
verifyPasswordAsync,
|
verifyPasswordAsync,
|
||||||
} from '../src/auth.js';
|
} from '../src/auth.js';
|
||||||
import { totpProvisioningUri, verifyTotp } from '../src/totp.js';
|
import { totpProvisioningUri, verifyTotp, verifyTotpStep } from '../src/totp.js';
|
||||||
|
|
||||||
test('reset codes are printed, case-insensitive, expiring, and one-time', () => {
|
test('reset codes are printed, case-insensitive, expiring, and one-time', () => {
|
||||||
const messages = [];
|
const messages = [];
|
||||||
@@ -38,9 +38,9 @@ test('password hashes verify and reject a different password', () => {
|
|||||||
assert.equal(verifyPassword('wrong password', hash), false);
|
assert.equal(verifyPassword('wrong password', hash), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('new password hashes record their iteration count', () => {
|
test('new password hashes use the shared bcrypt scheme and cost', () => {
|
||||||
const hash = hashPassword('correct horse battery staple');
|
const hash = hashPassword('correct horse battery staple');
|
||||||
assert.match(hash, /^pbkdf2-sha256\$600000\$[0-9a-f]{32}\$[0-9a-f]{64}$/);
|
assert.match(hash, /^bcrypt\$\$2b\$12\$/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('legacy salt:hex hashes still verify at the original iteration count', () => {
|
test('legacy salt:hex hashes still verify at the original iteration count', () => {
|
||||||
@@ -55,16 +55,16 @@ test('a hash with a malformed iteration count never verifies', () => {
|
|||||||
assert.equal(verifyPassword('correct horse battery staple', 'pbkdf2-sha256$x$aa$bb'), false);
|
assert.equal(verifyPassword('correct horse battery staple', 'pbkdf2-sha256$x$aa$bb'), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('async password helpers produce and verify the same format', async () => {
|
test('async password helpers produce and verify the same bcrypt format', async () => {
|
||||||
const hash = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 });
|
const hash = await hashPasswordAsync('correct horse battery staple');
|
||||||
assert.match(hash, /^pbkdf2-sha256\$1000\$/);
|
assert.match(hash, /^bcrypt\$\$2b\$12\$/);
|
||||||
assert.equal(await verifyPasswordAsync('correct horse battery staple', hash), true);
|
assert.equal(await verifyPasswordAsync('correct horse battery staple', hash), true);
|
||||||
assert.equal(await verifyPasswordAsync('wrong password', hash), false);
|
assert.equal(await verifyPasswordAsync('wrong password', hash), false);
|
||||||
assert.equal(verifyPassword('correct horse battery staple', hash), true);
|
assert.equal(verifyPassword('correct horse battery staple', hash), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('formats this module does not verify fail closed', () => {
|
test('formats this module does not verify fail closed', () => {
|
||||||
for (const stored of ['', '$2b$12$abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQ', 'bcrypt$$2a$12$abc', 'pbkdf2-sha256$600000$00$00$extra']) {
|
for (const stored of ['', '$2b$12$abc', 'bcrypt$$2a$12$abc', 'bcrypt-sha256$$2b$12$abc', 'pbkdf2-sha256$600000$00$00$extra']) {
|
||||||
assert.equal(verifyPassword('correct horse battery staple', stored), false);
|
assert.equal(verifyPassword('correct horse battery staple', stored), false);
|
||||||
}
|
}
|
||||||
assert.equal(passwordHashNeedsUpgrade('$2b$12$abc'), true);
|
assert.equal(passwordHashNeedsUpgrade('$2b$12$abc'), true);
|
||||||
@@ -77,15 +77,27 @@ test('a legacy salt:hex hash is rewritten in the current scheme after a successf
|
|||||||
|
|
||||||
const result = await verifyAndUpgradePasswordAsync('legacy password', legacy);
|
const result = await verifyAndUpgradePasswordAsync('legacy password', legacy);
|
||||||
assert.equal(result.valid, true);
|
assert.equal(result.valid, true);
|
||||||
assert.match(result.upgradedHash, /^pbkdf2-sha256\$600000\$/);
|
assert.match(result.upgradedHash, /^bcrypt\$\$2b\$12\$/);
|
||||||
assert.equal(passwordHashNeedsUpgrade(result.upgradedHash), false);
|
assert.equal(passwordHashNeedsUpgrade(result.upgradedHash), false);
|
||||||
assert.equal(verifyPassword('legacy password', result.upgradedHash), true);
|
assert.equal(verifyPassword('legacy password', result.upgradedHash), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a hash below the current iteration count is rewritten, and a short legacy password still upgrades', async () => {
|
test('a long legacy PBKDF2 password is migrated without truncation', async () => {
|
||||||
const low = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 });
|
const longPassword = 'a'.repeat(80);
|
||||||
|
const salt = crypto.randomBytes(16).toString('hex');
|
||||||
|
const legacy = `pbkdf2-sha256$600000$${salt}$${crypto.pbkdf2Sync(longPassword, salt, 600000, 32, 'sha256').toString('hex')}`;
|
||||||
|
const result = await verifyAndUpgradePasswordAsync(longPassword, legacy);
|
||||||
|
assert.equal(result.valid, true);
|
||||||
|
assert.match(result.upgradedHash, /^bcrypt-sha256\$\$2b\$12\$/);
|
||||||
|
assert.equal(await verifyPasswordAsync(longPassword, result.upgradedHash), true);
|
||||||
|
assert.equal(await verifyPasswordAsync(`${longPassword}x`, result.upgradedHash), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a low-cost bcrypt hash is rewritten, and a short legacy password still upgrades', async () => {
|
||||||
|
const bcrypt = (await import('bcryptjs')).default;
|
||||||
|
const low = `bcrypt$${await bcrypt.hash('correct horse battery staple', 4)}`;
|
||||||
const lowResult = await verifyAndUpgradePasswordAsync('correct horse battery staple', low);
|
const lowResult = await verifyAndUpgradePasswordAsync('correct horse battery staple', low);
|
||||||
assert.match(lowResult.upgradedHash, /^pbkdf2-sha256\$600000\$/);
|
assert.match(lowResult.upgradedHash, /^bcrypt\$\$2b\$12\$/);
|
||||||
|
|
||||||
const salt = crypto.randomBytes(16).toString('hex');
|
const salt = crypto.randomBytes(16).toString('hex');
|
||||||
const shortLegacy = `${salt}:${crypto.pbkdf2Sync('short', salt, 100000, 32, 'sha256').toString('hex')}`;
|
const shortLegacy = `${salt}:${crypto.pbkdf2Sync('short', salt, 100000, 32, 'sha256').toString('hex')}`;
|
||||||
@@ -95,7 +107,7 @@ test('a hash below the current iteration count is rewritten, and a short legacy
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('a wrong password neither verifies nor upgrades, and a current hash is not rewritten', async () => {
|
test('a wrong password neither verifies nor upgrades, and a current hash is not rewritten', async () => {
|
||||||
const hash = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 });
|
const hash = await hashPasswordAsync('correct horse battery staple');
|
||||||
assert.deepEqual(await verifyAndUpgradePasswordAsync('wrong password', hash), { valid: false, upgradedHash: null });
|
assert.deepEqual(await verifyAndUpgradePasswordAsync('wrong password', hash), { valid: false, upgradedHash: null });
|
||||||
|
|
||||||
const current = await hashPasswordAsync('correct horse battery staple');
|
const current = await hashPasswordAsync('correct horse battery staple');
|
||||||
@@ -117,6 +129,7 @@ test('TOTP verifies RFC 6238 SHA-1 vectors', () => {
|
|||||||
];
|
];
|
||||||
for (const [seconds, code] of vectors) {
|
for (const [seconds, code] of vectors) {
|
||||||
assert.equal(verifyTotp(secret, code, seconds * 1000), true);
|
assert.equal(verifyTotp(secret, code, seconds * 1000), true);
|
||||||
|
assert.equal(verifyTotpStep(secret, code, seconds * 1000), Math.floor(seconds / 30));
|
||||||
}
|
}
|
||||||
assert.match(totpProvisioningUri('Example App', 'admin@example.com', secret), /^otpauth:\/\/totp\//);
|
assert.match(totpProvisioningUri('Example App', 'admin@example.com', secret), /^otpauth:\/\/totp\//);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ function fakeDatabase({ rowCount = 1, totpEnabled = false, rowsByCondition = {}
|
|||||||
async query(text, params = []) {
|
async query(text, params = []) {
|
||||||
queries.push({ text, params });
|
queries.push({ text, params });
|
||||||
if (text.includes('totp_enabled, false) AS enabled')) {
|
if (text.includes('totp_enabled, false) AS enabled')) {
|
||||||
return { rows: [{ secret: 'S', enabled: totpEnabled }], rowCount: 1 };
|
return { rows: [{ secret: 'S', enabled: totpEnabled, last_used_step: -1 }], rowCount: 1 };
|
||||||
}
|
}
|
||||||
for (const [condition, row] of Object.entries(rowsByCondition)) {
|
for (const [condition, row] of Object.entries(rowsByCondition)) {
|
||||||
if (text.includes(condition)) return { rows: [row], rowCount: 1 };
|
if (text.includes(condition)) return { rows: [row], rowCount: 1 };
|
||||||
@@ -27,6 +27,7 @@ test('ensureSchema requests the case-insensitive username index, only while no c
|
|||||||
assert.match(statements, /auth_users_username_lower_idx/);
|
assert.match(statements, /auth_users_username_lower_idx/);
|
||||||
assert.match(statements, /lower\(username\)/);
|
assert.match(statements, /lower\(username\)/);
|
||||||
assert.match(statements, /HAVING count\(\*\) > 1/);
|
assert.match(statements, /HAVING count\(\*\) > 1/);
|
||||||
|
assert.match(statements, /ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('setTotpSecret refuses to replace an enabled second factor', async () => {
|
test('setTotpSecret refuses to replace an enabled second factor', async () => {
|
||||||
@@ -41,6 +42,39 @@ test('setTotpSecret stores a pending secret while TOTP is off, and ignores an un
|
|||||||
await new AuthStore(fakeDatabase({ rowCount: 0 })).setTotpSecret(2, 'NEWSECRET');
|
await new AuthStore(fakeDatabase({ rowCount: 0 })).setTotpSecret(2, 'NEWSECRET');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('TOTP enrollment records its code step and a replay is rejected atomically', async () => {
|
||||||
|
const state = { secret: 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', enabled: false, last_used_step: -1 };
|
||||||
|
const database = {
|
||||||
|
async query(text, params = []) {
|
||||||
|
if (text.startsWith('SELECT COALESCE(totp_secret')) {
|
||||||
|
return { rows: [{ ...state }], rowCount: 1 };
|
||||||
|
}
|
||||||
|
const [step, , secret] = params;
|
||||||
|
if (text.includes('SET totp_enabled = true')) {
|
||||||
|
if (!state.enabled && secret === state.secret && state.last_used_step < step) {
|
||||||
|
state.enabled = true;
|
||||||
|
state.last_used_step = step;
|
||||||
|
return { rows: [], rowCount: 1 };
|
||||||
|
}
|
||||||
|
return { rows: [], rowCount: 0 };
|
||||||
|
}
|
||||||
|
if (text.includes('SET last_used_step = $1')) {
|
||||||
|
if (state.enabled && secret === state.secret && state.last_used_step < step) {
|
||||||
|
state.last_used_step = step;
|
||||||
|
return { rows: [], rowCount: 1 };
|
||||||
|
}
|
||||||
|
return { rows: [], rowCount: 0 };
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected query: ${text}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const store = new AuthStore(database);
|
||||||
|
assert.equal(await store.enableTotp(1, '287082', 59000), true);
|
||||||
|
assert.equal(state.last_used_step, 1);
|
||||||
|
assert.equal(await store.consumeTotpCode(1, '287082', 59000), false);
|
||||||
|
assert.equal(state.last_used_step, 1);
|
||||||
|
});
|
||||||
|
|
||||||
test('credential writes refuse an empty hash and a username containing @', async () => {
|
test('credential writes refuse an empty hash and a username containing @', async () => {
|
||||||
const database = fakeDatabase();
|
const database = fakeDatabase();
|
||||||
const store = new AuthStore(database);
|
const store = new AuthStore(database);
|
||||||
|
|||||||
@@ -2,7 +2,12 @@ import test from 'node:test';
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { existsSync, readFileSync } from 'node:fs';
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
import { hashPassword, passwordHashNeedsUpgrade, verifyAndUpgradePasswordAsync, verifyPassword } from '../src/auth.js';
|
import { hashPassword, passwordHashNeedsUpgrade, verifyAndUpgradePasswordAsync, verifyPassword } from '../src/auth.js';
|
||||||
import { verifyTotp } from '../src/totp.js';
|
import { verifyTotp, verifyTotpStep } from '../src/totp.js';
|
||||||
|
import {
|
||||||
|
EXAMPLE_INTERNAL_SECRETS,
|
||||||
|
MIN_INTERNAL_SECRET_LENGTH,
|
||||||
|
internalSecretMatches,
|
||||||
|
} from '../src/coreconfig.js';
|
||||||
|
|
||||||
// The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
|
// The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
|
||||||
const contractUrl = new URL('../../../contract/auth-contract.json', import.meta.url);
|
const contractUrl = new URL('../../../contract/auth-contract.json', import.meta.url);
|
||||||
@@ -12,14 +17,16 @@ const skip = contract ? false : 'contract/auth-contract.json is not part of this
|
|||||||
test('password hashes verify as the contract says for Node', { skip }, async () => {
|
test('password hashes verify as the contract says for Node', { skip }, async () => {
|
||||||
const { plaintext, wrongPassword, hashes } = contract.password;
|
const { plaintext, wrongPassword, hashes } = contract.password;
|
||||||
for (const entry of hashes) {
|
for (const entry of hashes) {
|
||||||
assert.equal(verifyPassword(plaintext, entry.hash), entry.verifies.node, entry.name);
|
const password = entry.password ?? plaintext;
|
||||||
assert.equal(verifyPassword(wrongPassword, entry.hash), false, `${entry.name}: wrong password`);
|
const rejectedPassword = entry.wrongPassword ?? wrongPassword;
|
||||||
|
assert.equal(verifyPassword(password, entry.hash), entry.verifies.node, entry.name);
|
||||||
|
assert.equal(verifyPassword(rejectedPassword, entry.hash), false, `${entry.name}: wrong password`);
|
||||||
if ('node' in (entry.needsUpgrade ?? {})) {
|
if ('node' in (entry.needsUpgrade ?? {})) {
|
||||||
assert.equal(passwordHashNeedsUpgrade(entry.hash), entry.needsUpgrade.node, `${entry.name}: needs upgrade`);
|
assert.equal(passwordHashNeedsUpgrade(entry.hash), entry.needsUpgrade.node, `${entry.name}: needs upgrade`);
|
||||||
const { valid, upgradedHash } = await verifyAndUpgradePasswordAsync(plaintext, entry.hash);
|
const { valid, upgradedHash } = await verifyAndUpgradePasswordAsync(password, entry.hash);
|
||||||
assert.equal(valid, true, `${entry.name}: valid on upgrade`);
|
assert.equal(valid, true, `${entry.name}: valid on upgrade`);
|
||||||
assert.equal(upgradedHash !== null, entry.needsUpgrade.node, `${entry.name}: upgraded hash`);
|
assert.equal(upgradedHash !== null, entry.needsUpgrade.node, `${entry.name}: upgraded hash`);
|
||||||
if (upgradedHash) assert.equal(verifyPassword(plaintext, upgradedHash), true);
|
if (upgradedHash) assert.equal(verifyPassword(password, upgradedHash), true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -28,7 +35,7 @@ test('the password length contract holds for Node', { skip }, () => {
|
|||||||
const { bytes, accepted } = contract.password.tooLongToHash;
|
const { bytes, accepted } = contract.password.tooLongToHash;
|
||||||
let didHash = true;
|
let didHash = true;
|
||||||
try {
|
try {
|
||||||
hashPassword('a'.repeat(bytes), { iterations: 1000 });
|
hashPassword('a'.repeat(bytes));
|
||||||
} catch {
|
} catch {
|
||||||
didHash = false;
|
didHash = false;
|
||||||
}
|
}
|
||||||
@@ -39,5 +46,20 @@ test('TOTP verifies as the contract says', { skip }, () => {
|
|||||||
for (const entry of contract.totp.cases) {
|
for (const entry of contract.totp.cases) {
|
||||||
const secret = entry.secret ?? contract.totp.secret;
|
const secret = entry.secret ?? contract.totp.secret;
|
||||||
assert.equal(verifyTotp(secret, entry.code, entry.unix * 1000), entry.valid, entry.name);
|
assert.equal(verifyTotp(secret, entry.code, entry.unix * 1000), entry.valid, entry.name);
|
||||||
|
if (entry.valid)
|
||||||
|
assert.equal(
|
||||||
|
verifyTotpStep(secret, entry.code, entry.unix * 1000),
|
||||||
|
entry.matchedStep ?? Math.floor(entry.unix / 30),
|
||||||
|
entry.name,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the internal secret gate matches the contract for Node', { skip }, () => {
|
||||||
|
const rule = contract.internalSecret;
|
||||||
|
assert.equal(MIN_INTERNAL_SECRET_LENGTH, rule.minLength);
|
||||||
|
assert.deepEqual([...EXAMPLE_INTERNAL_SECRETS].sort(), [...rule.placeholders].sort());
|
||||||
|
for (const entry of rule.cases) {
|
||||||
|
assert.equal(internalSecretMatches(entry.provided, entry.secret), entry.matches, entry.name);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -1,6 +1,13 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { Info, Store, internalSecretMatches } from '../src/coreconfig.js';
|
import {
|
||||||
|
EXAMPLE_INTERNAL_SECRETS,
|
||||||
|
Info,
|
||||||
|
MIN_INTERNAL_SECRET_LENGTH,
|
||||||
|
Store,
|
||||||
|
internalSecretMatches,
|
||||||
|
internalSecretUsable,
|
||||||
|
} from '../src/coreconfig.js';
|
||||||
|
|
||||||
test('store seeds from the fallback Info', () => {
|
test('store seeds from the fallback Info', () => {
|
||||||
const store = new Store({ authGuardUrl: 'http://auth.example.com', carrierNodeUrl: 'http://carrier.example.com' });
|
const store = new Store({ authGuardUrl: 'http://auth.example.com', carrierNodeUrl: 'http://carrier.example.com' });
|
||||||
@@ -49,13 +56,30 @@ test('Info.fromJSON/toJSON round-trip the wire shape', () => {
|
|||||||
assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com');
|
assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const LONG_SECRET = 'shared-secret-value';
|
||||||
|
|
||||||
test('internal secret check fails closed when the secret is unset or empty', () => {
|
test('internal secret check fails closed when the secret is unset or empty', () => {
|
||||||
assert.equal(internalSecretMatches(undefined, undefined), false);
|
assert.equal(internalSecretMatches(undefined, undefined), false);
|
||||||
assert.equal(internalSecretMatches(undefined, ''), false);
|
assert.equal(internalSecretMatches(undefined, ''), false);
|
||||||
assert.equal(internalSecretMatches('', ''), false);
|
assert.equal(internalSecretMatches('', ''), false);
|
||||||
assert.equal(internalSecretMatches(undefined, 'shared-secret'), false);
|
assert.equal(internalSecretMatches(undefined, LONG_SECRET), false);
|
||||||
assert.equal(internalSecretMatches('shared-secreT', 'shared-secret'), false);
|
assert.equal(internalSecretMatches('shared-secret-valuE', LONG_SECRET), false);
|
||||||
assert.equal(internalSecretMatches('shared-secret', 'shared-secret'), true);
|
assert.equal(internalSecretMatches(LONG_SECRET, LONG_SECRET), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('internal secret check refuses a short or placeholder secret', () => {
|
||||||
|
const short = 'x'.repeat(MIN_INTERNAL_SECRET_LENGTH - 1);
|
||||||
|
assert.equal(internalSecretMatches(short, short), false);
|
||||||
|
for (const placeholder of EXAMPLE_INTERNAL_SECRETS) {
|
||||||
|
assert.equal(internalSecretMatches(placeholder, placeholder), false, placeholder);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('internal secret usability needs the minimum length and no placeholder', () => {
|
||||||
|
assert.equal(internalSecretUsable('x'.repeat(MIN_INTERNAL_SECRET_LENGTH - 1)), false);
|
||||||
|
assert.equal(internalSecretUsable('x'.repeat(MIN_INTERNAL_SECRET_LENGTH)), true);
|
||||||
|
assert.equal(internalSecretUsable('change-me-to-a-long-random-value'), false);
|
||||||
|
assert.equal(internalSecretUsable(undefined), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('set rejects a URL that is not an http or https URL and changes nothing', () => {
|
test('set rejects a URL that is not an http or https URL and changes nothing', () => {
|
||||||
|
|||||||
@@ -129,6 +129,11 @@ async def push_core_services(request):
|
|||||||
return {"ok": True, "info": info.to_json()}
|
return {"ok": True, "info": info.to_json()}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`internal_secret_matches` also refuses a SECRET shorter than `MIN_INTERNAL_SECRET_LENGTH`
|
||||||
|
(16 characters) or equal to an example placeholder (`EXAMPLE_INTERNAL_SECRETS`), so every
|
||||||
|
internal route gated by it rejects all callers until the secret is set properly. Call
|
||||||
|
`internal_secret_usable(SECRET)` at startup to log a warning for that case.
|
||||||
|
|
||||||
## `authproxy`: a ready-to-mount FastAPI router (optional)
|
## `authproxy`: a ready-to-mount FastAPI router (optional)
|
||||||
|
|
||||||
Wiring up `authclient` still leaves each service reimplementing the same
|
Wiring up `authclient` still leaves each service reimplementing the same
|
||||||
|
|||||||
@@ -28,12 +28,12 @@ from .authclient import (
|
|||||||
token_from_request,
|
token_from_request,
|
||||||
)
|
)
|
||||||
from .config import DatabaseConfig, database_url_from_env
|
from .config import DatabaseConfig, database_url_from_env
|
||||||
|
from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches, internal_secret_usable
|
||||||
from .coreconfig import Info as CoreConfigInfo
|
from .coreconfig import Info as CoreConfigInfo
|
||||||
from .coreconfig import Store as CoreConfigStore
|
from .coreconfig import Store as CoreConfigStore
|
||||||
from .coreconfig import internal_secret_matches
|
|
||||||
from .postgres import Database
|
from .postgres import Database
|
||||||
from .tokens import hash_token, new_session_token
|
from .tokens import hash_token, new_session_token
|
||||||
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
|
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp, verify_totp_step
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"AuthStore",
|
"AuthStore",
|
||||||
@@ -47,6 +47,8 @@ __all__ = [
|
|||||||
"CoreConfigInfo",
|
"CoreConfigInfo",
|
||||||
"CoreConfigStore",
|
"CoreConfigStore",
|
||||||
"internal_secret_matches",
|
"internal_secret_matches",
|
||||||
|
"internal_secret_usable",
|
||||||
|
"MIN_INTERNAL_SECRET_LENGTH",
|
||||||
"ROLE_ADMIN",
|
"ROLE_ADMIN",
|
||||||
"ROLE_SUPERADMIN",
|
"ROLE_SUPERADMIN",
|
||||||
"ROLE_USER",
|
"ROLE_USER",
|
||||||
@@ -70,4 +72,5 @@ __all__ = [
|
|||||||
"verify_password",
|
"verify_password",
|
||||||
"verify_password_async",
|
"verify_password_async",
|
||||||
"verify_totp",
|
"verify_totp",
|
||||||
|
"verify_totp_step",
|
||||||
]
|
]
|
||||||
@@ -3,6 +3,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
import threading
|
import threading
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
@@ -12,6 +15,7 @@ import asyncpg
|
|||||||
import bcrypt
|
import bcrypt
|
||||||
|
|
||||||
from .postgres import Database
|
from .postgres import Database
|
||||||
|
from .totp import verify_totp_step
|
||||||
|
|
||||||
_SCHEMA = """
|
_SCHEMA = """
|
||||||
CREATE TABLE IF NOT EXISTS auth_users (
|
CREATE TABLE IF NOT EXISTS auth_users (
|
||||||
@@ -22,6 +26,7 @@ CREATE TABLE IF NOT EXISTS auth_users (
|
|||||||
role TEXT NOT NULL DEFAULT 'user',
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
totp_secret TEXT NOT NULL DEFAULT '',
|
totp_secret TEXT NOT NULL DEFAULT '',
|
||||||
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
last_used_step BIGINT NOT NULL DEFAULT -1,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
);
|
);
|
||||||
@@ -29,6 +34,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
|||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
|
||||||
@@ -179,7 +185,12 @@ def _validate_credentials(username: str | None, password_hash: str | None) -> No
|
|||||||
# so a stored value reads "bcrypt$$2b$12$...". Unprefixed bcrypt hashes written
|
# so a stored value reads "bcrypt$$2b$12$...". Unprefixed bcrypt hashes written
|
||||||
# before the prefix still verify and are rewritten on the next successful login.
|
# before the prefix still verify and are rewritten on the next successful login.
|
||||||
_BCRYPT_SCHEME = "bcrypt$"
|
_BCRYPT_SCHEME = "bcrypt$"
|
||||||
|
_BCRYPT_SHA256_SCHEME = "bcrypt-sha256$"
|
||||||
_LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$")
|
_LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$")
|
||||||
|
_PBKDF2_SCHEME = "pbkdf2-sha256"
|
||||||
|
BCRYPT_MAX_PASSWORD_BYTES = 72
|
||||||
|
_LEGACY_PBKDF2_ITERATIONS = 100_000
|
||||||
|
_MAX_PBKDF2_ITERATIONS = 10_000_000
|
||||||
BCRYPT_ROUNDS = 12
|
BCRYPT_ROUNDS = 12
|
||||||
|
|
||||||
|
|
||||||
@@ -188,9 +199,9 @@ def _new_bcrypt_hash(password: str) -> str:
|
|||||||
return _BCRYPT_SCHEME + hashed.decode("utf-8")
|
return _BCRYPT_SCHEME + hashed.decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
# bcrypt reads only the first 72 bytes. Older bcrypt releases drop the rest silently, so the limit
|
# bcrypt reads only the first 72 bytes, so new passwords are refused above this limit. Legacy
|
||||||
# is enforced here instead of depending on the installed version.
|
# PBKDF2 passwords over the limit are migrated with an explicitly marked SHA-256 pre-hash.
|
||||||
MAX_PASSWORD_BYTES = 72
|
MAX_PASSWORD_BYTES = BCRYPT_MAX_PASSWORD_BYTES
|
||||||
|
|
||||||
|
|
||||||
def hash_password(password: str) -> str:
|
def hash_password(password: str) -> str:
|
||||||
@@ -209,24 +220,75 @@ def _bcrypt_string_of(stored_hash: str) -> str | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _bcrypt_hash_info(stored_hash: str) -> tuple[str, bool, bool] | None:
|
||||||
|
if stored_hash.startswith(_BCRYPT_SHA256_SCHEME):
|
||||||
|
return stored_hash[len(_BCRYPT_SHA256_SCHEME) :], True, False
|
||||||
|
if stored_hash.startswith(_BCRYPT_SCHEME):
|
||||||
|
return stored_hash[len(_BCRYPT_SCHEME) :], False, False
|
||||||
|
if stored_hash.startswith(_LEGACY_BCRYPT_PREFIXES):
|
||||||
|
return stored_hash, False, True
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _pbkdf2_hash_info(stored_hash: str) -> tuple[int, str, str] | None:
|
||||||
|
if stored_hash.startswith(f"{_PBKDF2_SCHEME}$"):
|
||||||
|
parts = stored_hash.split("$")
|
||||||
|
if len(parts) != 4:
|
||||||
|
return None
|
||||||
|
_, raw_iterations, salt, expected = parts
|
||||||
|
try:
|
||||||
|
iterations = int(raw_iterations)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
elif re.fullmatch(r"[0-9a-f]+:[0-9a-f]+", stored_hash):
|
||||||
|
salt, expected = stored_hash.split(":", 1)
|
||||||
|
iterations = _LEGACY_PBKDF2_ITERATIONS
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
if len(salt) != 32 or len(expected) != 64 or not (1 <= iterations <= _MAX_PBKDF2_ITERATIONS):
|
||||||
|
return None
|
||||||
|
return iterations, salt, expected
|
||||||
|
|
||||||
|
|
||||||
|
def _new_bcrypt_sha256_hash(password: str) -> str:
|
||||||
|
digest = hashlib.sha256(password.encode("utf-8")).hexdigest()
|
||||||
|
hashed = bcrypt.hashpw(digest.encode("ascii"), bcrypt.gensalt(rounds=BCRYPT_ROUNDS))
|
||||||
|
return _BCRYPT_SHA256_SCHEME + hashed.decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
def verify_password(password: str, stored_hash: str) -> bool:
|
def verify_password(password: str, stored_hash: str) -> bool:
|
||||||
bcrypt_hash = _bcrypt_string_of(stored_hash)
|
bcrypt_info = _bcrypt_hash_info(stored_hash)
|
||||||
if bcrypt_hash is None:
|
if bcrypt_info is not None:
|
||||||
|
bcrypt_hash, prehashed, _ = bcrypt_info
|
||||||
|
raw_password = password.encode("utf-8")
|
||||||
|
if prehashed:
|
||||||
|
raw_password = hashlib.sha256(raw_password).hexdigest().encode("ascii")
|
||||||
|
elif len(raw_password) > BCRYPT_MAX_PASSWORD_BYTES:
|
||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
return bcrypt.checkpw(password.encode("utf-8"), bcrypt_hash.encode("utf-8"))
|
return bcrypt.checkpw(raw_password, bcrypt_hash.encode("utf-8"))
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
parsed = _pbkdf2_hash_info(stored_hash)
|
||||||
|
if parsed is None:
|
||||||
|
return False
|
||||||
|
iterations, salt, expected = parsed
|
||||||
|
actual = hashlib.pbkdf2_hmac(
|
||||||
|
"sha256", password.encode("utf-8"), salt.encode("ascii"), iterations
|
||||||
|
)
|
||||||
|
return hmac.compare_digest(actual.hex(), expected)
|
||||||
|
|
||||||
|
|
||||||
def password_hash_needs_upgrade(stored_hash: str) -> bool:
|
def password_hash_needs_upgrade(stored_hash: str) -> bool:
|
||||||
"""True for an unprefixed legacy hash, or a bcrypt cost below BCRYPT_ROUNDS."""
|
"""True for legacy PBKDF2/bcrypt formats or a bcrypt cost below policy."""
|
||||||
if not stored_hash.startswith(_BCRYPT_SCHEME):
|
bcrypt_info = _bcrypt_hash_info(stored_hash)
|
||||||
|
if bcrypt_info is None:
|
||||||
return True
|
return True
|
||||||
# The bcrypt string after the prefix is "$2b$<cost>$<salt+hash>".
|
bcrypt_hash, _, legacy = bcrypt_info
|
||||||
parts = stored_hash[len(_BCRYPT_SCHEME) :].split("$")
|
parts = bcrypt_hash.split("$")
|
||||||
try:
|
try:
|
||||||
return int(parts[2]) < BCRYPT_ROUNDS
|
return legacy or int(parts[2]) < BCRYPT_ROUNDS
|
||||||
except (IndexError, ValueError):
|
except (IndexError, ValueError):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -243,6 +305,8 @@ def verify_and_upgrade_password(password: str, stored_hash: str) -> tuple[bool,
|
|||||||
if not password_hash_needs_upgrade(stored_hash):
|
if not password_hash_needs_upgrade(stored_hash):
|
||||||
return True, None
|
return True, None
|
||||||
# The length rule applies when a password is first set, not when an old hash is upgraded.
|
# The length rule applies when a password is first set, not when an old hash is upgraded.
|
||||||
|
if len(password.encode("utf-8")) > BCRYPT_MAX_PASSWORD_BYTES:
|
||||||
|
return True, _new_bcrypt_sha256_hash(password)
|
||||||
return True, _new_bcrypt_hash(password)
|
return True, _new_bcrypt_hash(password)
|
||||||
|
|
||||||
|
|
||||||
@@ -431,18 +495,19 @@ class AuthStore:
|
|||||||
|
|
||||||
async def get_totp_state(self, user_id: int) -> dict[str, object]:
|
async def get_totp_state(self, user_id: int) -> dict[str, object]:
|
||||||
row = await self.database.fetchrow(
|
row = await self.database.fetchrow(
|
||||||
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled "
|
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled, "
|
||||||
|
"COALESCE(last_used_step, -1) AS last_used_step "
|
||||||
"FROM auth_users WHERE id = $1",
|
"FROM auth_users WHERE id = $1",
|
||||||
user_id,
|
user_id,
|
||||||
)
|
)
|
||||||
return dict(row) if row else {"secret": "", "enabled": False}
|
return dict(row) if row else {"secret": "", "enabled": False, "last_used_step": -1}
|
||||||
|
|
||||||
async def set_totp_secret(self, user_id: int, secret: str) -> None:
|
async def set_totp_secret(self, user_id: int, secret: str) -> None:
|
||||||
"""Stores a pending secret without enabling two-factor auth. Raises
|
"""Stores a pending secret without enabling two-factor auth. Raises
|
||||||
TotpAlreadyEnabledError while it is enabled, so a replaced secret cannot silently switch
|
TotpAlreadyEnabledError while it is enabled, so a replaced secret cannot silently switch
|
||||||
the second factor off."""
|
the second factor off."""
|
||||||
status = await self.database.execute(
|
status = await self.database.execute(
|
||||||
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, "
|
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, "
|
||||||
"updated_at = now() WHERE id = $2 AND NOT totp_enabled",
|
"updated_at = now() WHERE id = $2 AND NOT totp_enabled",
|
||||||
secret,
|
secret,
|
||||||
user_id,
|
user_id,
|
||||||
@@ -450,16 +515,41 @@ class AuthStore:
|
|||||||
if status == "UPDATE 0" and (await self.get_totp_state(user_id))["enabled"]:
|
if status == "UPDATE 0" and (await self.get_totp_state(user_id))["enabled"]:
|
||||||
raise TotpAlreadyEnabledError("TOTP is already enabled; disable it first")
|
raise TotpAlreadyEnabledError("TOTP is already enabled; disable it first")
|
||||||
|
|
||||||
async def enable_totp(self, user_id: int) -> None:
|
async def enable_totp(self, user_id: int, token: str, now: float | None = None) -> bool:
|
||||||
await self.database.execute(
|
state = await self.get_totp_state(user_id)
|
||||||
"UPDATE auth_users SET totp_enabled = true, updated_at = now() "
|
if not state["secret"] or state["enabled"]:
|
||||||
"WHERE id = $1 AND totp_secret <> ''",
|
return False
|
||||||
|
step = verify_totp_step(str(state["secret"]), token, now)
|
||||||
|
if step is None:
|
||||||
|
return False
|
||||||
|
status = await self.database.execute(
|
||||||
|
"UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() "
|
||||||
|
"WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1",
|
||||||
|
step,
|
||||||
user_id,
|
user_id,
|
||||||
|
state["secret"],
|
||||||
)
|
)
|
||||||
|
return status == "UPDATE 1"
|
||||||
|
|
||||||
|
async def consume_totp_code(self, user_id: int, token: str, now: float | None = None) -> bool:
|
||||||
|
state = await self.get_totp_state(user_id)
|
||||||
|
if not state["secret"] or not state["enabled"]:
|
||||||
|
return False
|
||||||
|
step = verify_totp_step(str(state["secret"]), token, now)
|
||||||
|
if step is None:
|
||||||
|
return False
|
||||||
|
status = await self.database.execute(
|
||||||
|
"UPDATE auth_users SET last_used_step = $1, updated_at = now() "
|
||||||
|
"WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1",
|
||||||
|
step,
|
||||||
|
user_id,
|
||||||
|
state["secret"],
|
||||||
|
)
|
||||||
|
return status == "UPDATE 1"
|
||||||
|
|
||||||
async def disable_totp(self, user_id: int) -> None:
|
async def disable_totp(self, user_id: int) -> None:
|
||||||
await self.database.execute(
|
await self.database.execute(
|
||||||
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, "
|
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, "
|
||||||
"updated_at = now() WHERE id = $1",
|
"updated_at = now() WHERE id = $1",
|
||||||
user_id,
|
user_id,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -64,11 +64,14 @@ from typing import Any, Mapping
|
|||||||
|
|
||||||
DEFAULT_COOKIE_NAME = "auth_session"
|
DEFAULT_COOKIE_NAME = "auth_session"
|
||||||
DEFAULT_TIMEOUT = 5.0
|
DEFAULT_TIMEOUT = 5.0
|
||||||
# validate() results, positive and negative, are reused for this many seconds so a burst of
|
# validate() results (positive and negative) and /api/me profiles are reused for this many
|
||||||
# requests with one token costs one AuthGuard call. Revocation through this client (logout)
|
# seconds so a burst of requests with one token costs one AuthGuard call. Revocation through
|
||||||
# clears the entry at once; revocation elsewhere is seen within the TTL. Mirrors the Go client.
|
# this client (logout) and token-authenticated writes clear both entries at once; changes made
|
||||||
|
# directly in AuthGuard may take up to two seconds to reach consumers.
|
||||||
VALIDATION_CACHE_TTL = 2.0
|
VALIDATION_CACHE_TTL = 2.0
|
||||||
MAX_VALIDATION_CACHE_ENTRIES = 10000
|
MAX_VALIDATION_CACHE_ENTRIES = 10000
|
||||||
|
PROFILE_CACHE_TTL = VALIDATION_CACHE_TTL
|
||||||
|
MAX_PROFILE_CACHE_ENTRIES = MAX_VALIDATION_CACHE_ENTRIES
|
||||||
|
|
||||||
_BEARER_PREFIX = "Bearer "
|
_BEARER_PREFIX = "Bearer "
|
||||||
|
|
||||||
@@ -274,6 +277,7 @@ class AuthClient:
|
|||||||
self.project_key = (project_key or "").strip().lower()
|
self.project_key = (project_key or "").strip().lower()
|
||||||
self._validation_lock = threading.Lock()
|
self._validation_lock = threading.Lock()
|
||||||
self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {}
|
self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {}
|
||||||
|
self._profile_cache: dict[str, tuple[float, PublicUser]] = {}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _validation_key(token: str) -> str:
|
def _validation_key(token: str) -> str:
|
||||||
@@ -307,8 +311,36 @@ class AuthClient:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def _forget_validation(self, token: str) -> None:
|
def _forget_validation(self, token: str) -> None:
|
||||||
|
"""Clears cached validation and /api/me data for this token."""
|
||||||
with self._validation_lock:
|
with self._validation_lock:
|
||||||
self._validation_cache.pop(self._validation_key(token), None)
|
key = self._validation_key(token)
|
||||||
|
self._validation_cache.pop(key, None)
|
||||||
|
self._profile_cache.pop(key, None)
|
||||||
|
|
||||||
|
def _cached_profile(self, token: str) -> tuple[bool, PublicUser | None]:
|
||||||
|
key = self._validation_key(token)
|
||||||
|
with self._validation_lock:
|
||||||
|
entry = self._profile_cache.get(key)
|
||||||
|
if entry is None:
|
||||||
|
return False, None
|
||||||
|
expires, profile = entry
|
||||||
|
if time.monotonic() >= expires:
|
||||||
|
del self._profile_cache[key]
|
||||||
|
return False, None
|
||||||
|
return True, profile
|
||||||
|
|
||||||
|
def _cache_profile(self, token: str, profile: PublicUser) -> None:
|
||||||
|
with self._validation_lock:
|
||||||
|
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
|
||||||
|
now = time.monotonic()
|
||||||
|
for key in [k for k, entry in self._profile_cache.items() if now >= entry[0]]:
|
||||||
|
del self._profile_cache[key]
|
||||||
|
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
|
||||||
|
del self._profile_cache[next(iter(self._profile_cache))]
|
||||||
|
self._profile_cache[self._validation_key(token)] = (
|
||||||
|
time.monotonic() + PROFILE_CACHE_TTL,
|
||||||
|
profile,
|
||||||
|
)
|
||||||
|
|
||||||
def set_base_url(self, base_url: str) -> None:
|
def set_base_url(self, base_url: str) -> None:
|
||||||
"""Atomically replaces the AuthGuard base URL this client calls,
|
"""Atomically replaces the AuthGuard base URL this client calls,
|
||||||
@@ -326,6 +358,7 @@ class AuthClient:
|
|||||||
self.base_url = normalized
|
self.base_url = normalized
|
||||||
with self._validation_lock:
|
with self._validation_lock:
|
||||||
self._validation_cache.clear()
|
self._validation_cache.clear()
|
||||||
|
self._profile_cache.clear()
|
||||||
|
|
||||||
# --- session validation (the original, minimal surface) ----------------
|
# --- session validation (the original, minimal surface) ----------------
|
||||||
|
|
||||||
@@ -465,6 +498,9 @@ class AuthClient:
|
|||||||
message = str(payload.get("error") or f"request failed ({status})")
|
message = str(payload.get("error") or f"request failed ({status})")
|
||||||
raise APIError(status, message, totp_required=bool(payload.get("totp_required")))
|
raise APIError(status, message, totp_required=bool(payload.get("totp_required")))
|
||||||
|
|
||||||
|
if token and method.upper() not in {"GET", "HEAD"}:
|
||||||
|
self._forget_validation(token)
|
||||||
|
|
||||||
return payload, list(cookies)
|
return payload, list(cookies)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -533,9 +569,26 @@ class AuthClient:
|
|||||||
return cookies
|
return cookies
|
||||||
|
|
||||||
async def me(self, token: str) -> PublicUser:
|
async def me(self, token: str) -> PublicUser:
|
||||||
"""Calls GET /api/me, resolving token to its account."""
|
"""Calls GET /api/me, resolving token to its account.
|
||||||
payload, _ = await self._call("GET", "/api/me", token=token)
|
|
||||||
return self._public_user(payload)
|
Successful profiles are cached by the SHA-256 token digest for the
|
||||||
|
same short window as validate(). This keeps protected API calls from
|
||||||
|
blocking on one AuthGuard round trip each while bounding how long an
|
||||||
|
external profile change or session revocation can remain stale.
|
||||||
|
"""
|
||||||
|
if not self.base_url:
|
||||||
|
raise AuthClientError("authclient: client has no base URL")
|
||||||
|
trimmed = (token or "").strip()
|
||||||
|
if trimmed:
|
||||||
|
hit, cached = self._cached_profile(trimmed)
|
||||||
|
if hit:
|
||||||
|
assert cached is not None
|
||||||
|
return cached
|
||||||
|
payload, _ = await self._call("GET", "/api/me", token=trimmed)
|
||||||
|
profile = self._public_user(payload)
|
||||||
|
if trimmed:
|
||||||
|
self._cache_profile(trimmed, profile)
|
||||||
|
return profile
|
||||||
|
|
||||||
# --- TOTP ------------------------------------------------------------------
|
# --- TOTP ------------------------------------------------------------------
|
||||||
|
|
||||||
|
|||||||
@@ -56,6 +56,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import abc
|
import abc
|
||||||
import os
|
import os
|
||||||
|
from http.cookies import CookieError, SimpleCookie
|
||||||
from typing import Any, Callable, Optional
|
from typing import Any, Callable, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||||
@@ -72,6 +73,7 @@ from .authclient import (
|
|||||||
forwarded_client_ip,
|
forwarded_client_ip,
|
||||||
)
|
)
|
||||||
from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env
|
from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env
|
||||||
|
from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches
|
||||||
from .ratelimit import AttemptLimiter
|
from .ratelimit import AttemptLimiter
|
||||||
|
|
||||||
__all__ = ["ProxyStore", "build_auth_router"]
|
__all__ = ["ProxyStore", "build_auth_router"]
|
||||||
@@ -104,7 +106,10 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
|
|||||||
# rather than a generic "internal error" indistinguishable from any other bug.
|
# rather than a generic "internal error" indistinguishable from any other bug.
|
||||||
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
|
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
|
||||||
ERR_AUTHGUARD_NOT_CONFIGURED = "AUTHGUARD_URL is not configured, so sessions cannot be verified."
|
ERR_AUTHGUARD_NOT_CONFIGURED = "AUTHGUARD_URL is not configured, so sessions cannot be verified."
|
||||||
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
|
ERR_SECRET_NOT_SET = (
|
||||||
|
"SECRET environment variable is unset, shorter than "
|
||||||
|
f"{MIN_INTERNAL_SECRET_LENGTH} characters, or an example placeholder."
|
||||||
|
)
|
||||||
ERR_ADMIN_REQUIRED = "Administrator access required."
|
ERR_ADMIN_REQUIRED = "Administrator access required."
|
||||||
|
|
||||||
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
|
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
|
||||||
@@ -175,6 +180,8 @@ class UpdateMeRequest(BaseModel):
|
|||||||
email: str = ""
|
email: str = ""
|
||||||
username: str = ""
|
username: str = ""
|
||||||
password: str = ""
|
password: str = ""
|
||||||
|
currentPassword: str = ""
|
||||||
|
totpToken: str = ""
|
||||||
|
|
||||||
|
|
||||||
class UpdateAccessRequest(BaseModel):
|
class UpdateAccessRequest(BaseModel):
|
||||||
@@ -333,8 +340,30 @@ def build_auth_router(
|
|||||||
)
|
)
|
||||||
|
|
||||||
def _forward_cookies(response: Response, cookies: list[str]) -> None:
|
def _forward_cookies(response: Response, cookies: list[str]) -> None:
|
||||||
for cookie in cookies:
|
for header in cookies:
|
||||||
response.headers.append("set-cookie", cookie)
|
parsed = SimpleCookie()
|
||||||
|
try:
|
||||||
|
parsed.load(header)
|
||||||
|
except CookieError:
|
||||||
|
continue
|
||||||
|
for morsel in parsed.values():
|
||||||
|
morsel["httponly"] = True
|
||||||
|
morsel["samesite"] = "lax"
|
||||||
|
if secure_cookie:
|
||||||
|
morsel["secure"] = True
|
||||||
|
response.headers.append("set-cookie", morsel.OutputString())
|
||||||
|
|
||||||
|
def _temporary_session_token(cookies: list[str]) -> str:
|
||||||
|
for header in cookies:
|
||||||
|
parsed = SimpleCookie()
|
||||||
|
try:
|
||||||
|
parsed.load(header)
|
||||||
|
except CookieError:
|
||||||
|
continue
|
||||||
|
morsel = parsed.get(cookie_name)
|
||||||
|
if morsel is not None and morsel.value:
|
||||||
|
return morsel.value
|
||||||
|
return ""
|
||||||
|
|
||||||
async def _current_profile(
|
async def _current_profile(
|
||||||
request: Request, client: AuthClient
|
request: Request, client: AuthClient
|
||||||
@@ -610,14 +639,42 @@ def build_auth_router(
|
|||||||
email = _normalize_email(req.email)
|
email = _normalize_email(req.email)
|
||||||
username = _normalize_username(req.username)
|
username = _normalize_username(req.username)
|
||||||
password = None
|
password = None
|
||||||
|
temporary_token = ""
|
||||||
if req.password:
|
if req.password:
|
||||||
_validate_password(req.password)
|
_validate_password(req.password)
|
||||||
|
if not req.currentPassword:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Current password is required to change the password.",
|
||||||
|
)
|
||||||
|
if current.totp_enabled and not req.totpToken.strip():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="A current authenticator code is required to change the password.",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
reauthenticated = await client.login(
|
||||||
|
current.username,
|
||||||
|
req.currentPassword,
|
||||||
|
req.totpToken,
|
||||||
|
)
|
||||||
|
except AuthClientError as exc:
|
||||||
|
_raise_authguard_error(exc, "Current credentials could not be verified.")
|
||||||
|
raise # unreachable
|
||||||
|
temporary_token = _temporary_session_token(reauthenticated.cookies)
|
||||||
password = req.password
|
password = req.password
|
||||||
|
|
||||||
|
try:
|
||||||
try:
|
try:
|
||||||
await client.update_managed_user(
|
await client.update_managed_user(
|
||||||
token, current.id, username=username, email=email, password=password
|
token, current.id, username=username, email=email, password=password
|
||||||
)
|
)
|
||||||
|
finally:
|
||||||
|
if password is not None and temporary_token:
|
||||||
|
try:
|
||||||
|
await client.logout(temporary_token)
|
||||||
|
except AuthClientError:
|
||||||
|
pass
|
||||||
except AuthClientError as exc:
|
except AuthClientError as exc:
|
||||||
_raise_authguard_error(exc, "Profile could not be updated.")
|
_raise_authguard_error(exc, "Profile could not be updated.")
|
||||||
raise # unreachable
|
raise # unreachable
|
||||||
@@ -651,9 +708,8 @@ def build_auth_router(
|
|||||||
request: Request,
|
request: Request,
|
||||||
store: ProxyStore = Depends(get_store), # noqa: B008
|
store: ProxyStore = Depends(get_store), # noqa: B008
|
||||||
) -> dict[str, bool]:
|
) -> dict[str, bool]:
|
||||||
if (
|
if not internal_secret_matches(
|
||||||
not configured_internal_secret
|
request.headers.get("X-Internal-Auth"), configured_internal_secret
|
||||||
or request.headers.get("X-Internal-Auth") != configured_internal_secret
|
|
||||||
):
|
):
|
||||||
raise HTTPException(status_code=401, detail="internal service authentication required")
|
raise HTTPException(status_code=401, detail="internal service authentication required")
|
||||||
await store.set_login_required(req.loginRequired)
|
await store.set_login_required(req.loginRequired)
|
||||||
|
|||||||
@@ -25,13 +25,29 @@ from dataclasses import dataclass, field
|
|||||||
from typing import Callable, Optional
|
from typing import Callable, Optional
|
||||||
from urllib.parse import urlsplit
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
MIN_INTERNAL_SECRET_LENGTH = 16
|
||||||
|
"""Shortest SECRET a service accepts for its internal routes."""
|
||||||
|
|
||||||
|
EXAMPLE_INTERNAL_SECRETS = frozenset({"SECRET", "change-me-to-a-long-random-value"})
|
||||||
|
"""Placeholders from .env.example files and the bare variable name. They are
|
||||||
|
public, so they never gate a route."""
|
||||||
|
|
||||||
|
|
||||||
|
def internal_secret_usable(secret: Optional[str]) -> bool:
|
||||||
|
"""True when the configured secret is strong enough to gate an internal
|
||||||
|
route: at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
|
||||||
|
placeholder. A route whose secret is not usable rejects every caller."""
|
||||||
|
value = secret or ""
|
||||||
|
return len(value) >= MIN_INTERNAL_SECRET_LENGTH and value not in EXAMPLE_INTERNAL_SECRETS
|
||||||
|
|
||||||
|
|
||||||
def internal_secret_matches(provided: Optional[str], secret: Optional[str]) -> bool:
|
def internal_secret_matches(provided: Optional[str], secret: Optional[str]) -> bool:
|
||||||
"""True when the X-Internal-Auth value equals the configured secret. An
|
"""True when the X-Internal-Auth value equals the configured secret. A
|
||||||
unset or empty secret never matches, and the comparison is constant-time."""
|
secret that is not usable (see internal_secret_usable) never matches, and
|
||||||
expected = (secret or "").encode("utf-8")
|
the comparison is constant-time."""
|
||||||
if not expected:
|
if not internal_secret_usable(secret):
|
||||||
return False
|
return False
|
||||||
|
expected = (secret or "").encode("utf-8")
|
||||||
return hmac.compare_digest(expected, (provided or "").encode("utf-8"))
|
return hmac.compare_digest(expected, (provided or "").encode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -36,19 +36,24 @@ def totp_provisioning_uri(issuer: str, account: str, secret: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
|
def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
|
||||||
|
return verify_totp_step(secret, token, now) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def verify_totp_step(secret: str, token: str, now: float | None = None) -> int | None:
|
||||||
normalized_secret = _normalize_secret(secret)
|
normalized_secret = _normalize_secret(secret)
|
||||||
normalized_token = _normalize_token(token)
|
normalized_token = _normalize_token(token)
|
||||||
if not normalized_secret or len(normalized_token) != TOTP_DIGITS:
|
if not normalized_secret or len(normalized_token) != TOTP_DIGITS:
|
||||||
return False
|
return None
|
||||||
try:
|
try:
|
||||||
key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8))
|
key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8))
|
||||||
except (ValueError, binascii.Error):
|
except (ValueError, binascii.Error):
|
||||||
return False
|
return None
|
||||||
if not key:
|
if not key:
|
||||||
return False
|
return None
|
||||||
|
|
||||||
period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS)
|
period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS)
|
||||||
for offset in range(-TOTP_WINDOW, TOTP_WINDOW + 1):
|
# Prefer the current step if a six-digit collision occurs in the window.
|
||||||
|
for offset in (0, -1, 1):
|
||||||
counter = period + offset
|
counter = period + offset
|
||||||
if counter < 0:
|
if counter < 0:
|
||||||
continue
|
continue
|
||||||
@@ -62,8 +67,8 @@ def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
|
|||||||
)
|
)
|
||||||
candidate = f"{value % 1_000_000:06d}"
|
candidate = f"{value % 1_000_000:06d}"
|
||||||
if hmac.compare_digest(candidate, normalized_token):
|
if hmac.compare_digest(candidate, normalized_token):
|
||||||
return True
|
return counter
|
||||||
return False
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _normalize_secret(value: str) -> str:
|
def _normalize_secret(value: str) -> str:
|
||||||
|
|||||||
@@ -175,15 +175,32 @@ class AccessSettingsTests(unittest.TestCase):
|
|||||||
self.assertEqual(response.status_code, 500)
|
self.assertEqual(response.status_code, 500)
|
||||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||||
|
|
||||||
|
def test_internal_update_refuses_a_short_or_placeholder_secret(self) -> None:
|
||||||
|
for secret in ("short", "change-me-to-a-long-random-value"):
|
||||||
|
with self.subTest(secret=secret):
|
||||||
|
store = _FakeStore(login_required=True)
|
||||||
|
client = TestClient(
|
||||||
|
_build_app(store, _FakeClient(setup_required=False), internal_secret=secret)
|
||||||
|
)
|
||||||
|
response = client.put(
|
||||||
|
"/api/auth/access/internal",
|
||||||
|
headers={"X-Internal-Auth": secret},
|
||||||
|
json={"loginRequired": False},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 401)
|
||||||
|
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||||
|
|
||||||
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
||||||
store = _FakeStore(login_required=True)
|
store = _FakeStore(login_required=True)
|
||||||
client = TestClient(
|
client = TestClient(
|
||||||
_build_app(store, _FakeClient(setup_required=False), internal_secret="secret")
|
_build_app(
|
||||||
|
store, _FakeClient(setup_required=False), internal_secret="internal-test-secret"
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
response = client.put(
|
response = client.put(
|
||||||
"/api/auth/access/internal",
|
"/api/auth/access/internal",
|
||||||
headers={"X-Internal-Auth": "secret"},
|
headers={"X-Internal-Auth": "internal-test-secret"},
|
||||||
json={"loginRequired": False},
|
json={"loginRequired": False},
|
||||||
)
|
)
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
@@ -244,6 +261,97 @@ class _RoleClient(_FakeClient):
|
|||||||
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
|
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
|
||||||
|
|
||||||
|
|
||||||
|
class _ProfileClient(_RoleClient):
|
||||||
|
def __init__(self, *, totp_enabled: bool = False) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.totp_enabled = totp_enabled
|
||||||
|
self.login_calls: list[tuple[str, str, str]] = []
|
||||||
|
self.update_calls: list[dict[str, object]] = []
|
||||||
|
|
||||||
|
async def me(self, token: str) -> PublicUser:
|
||||||
|
if token != "admin-token":
|
||||||
|
raise APIError(401, "unauthenticated")
|
||||||
|
return PublicUser(
|
||||||
|
id=1,
|
||||||
|
username="admin",
|
||||||
|
email="admin@example.com",
|
||||||
|
role="superadmin",
|
||||||
|
totp_enabled=self.totp_enabled,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
|
||||||
|
self.login_calls.append((username_or_email, password, totp_token))
|
||||||
|
if password != "current-password":
|
||||||
|
raise APIError(401, "invalid credentials")
|
||||||
|
return SessionResult(
|
||||||
|
user=PublicUser(id=1, username="admin", email="admin@example.com", role="superadmin"),
|
||||||
|
cookies=["auth_session=reauth-token; Path=/; HttpOnly"],
|
||||||
|
)
|
||||||
|
|
||||||
|
async def update_managed_user(self, token: str, user_id: int, **kwargs) -> None:
|
||||||
|
self.update_calls.append({"token": token, "user_id": user_id, **kwargs})
|
||||||
|
|
||||||
|
|
||||||
|
class ProfileReauthenticationTests(unittest.TestCase):
|
||||||
|
def _put(self, fake: _ProfileClient, body: dict[str, str]):
|
||||||
|
client = TestClient(_build_app(_FakeStore(), fake))
|
||||||
|
return client.put(
|
||||||
|
"/api/auth/me",
|
||||||
|
headers={"Cookie": f"{DEFAULT_COOKIE_NAME}=admin-token"},
|
||||||
|
json=body,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_password_update_requires_current_password_and_totp_when_enabled(self) -> None:
|
||||||
|
no_totp = _ProfileClient()
|
||||||
|
response = self._put(
|
||||||
|
no_totp,
|
||||||
|
{"username": "admin", "email": "admin@example.com", "password": "new-password"},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 400)
|
||||||
|
self.assertEqual(no_totp.login_calls, [])
|
||||||
|
|
||||||
|
totp = _ProfileClient(totp_enabled=True)
|
||||||
|
response = self._put(
|
||||||
|
totp,
|
||||||
|
{
|
||||||
|
"username": "admin",
|
||||||
|
"email": "admin@example.com",
|
||||||
|
"password": "new-password",
|
||||||
|
"currentPassword": "current-password",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 400)
|
||||||
|
self.assertEqual(totp.login_calls, [])
|
||||||
|
|
||||||
|
def test_password_update_reauthenticates_and_cleans_up_temporary_session(self) -> None:
|
||||||
|
fake = _ProfileClient(totp_enabled=True)
|
||||||
|
response = self._put(
|
||||||
|
fake,
|
||||||
|
{
|
||||||
|
"username": "admin",
|
||||||
|
"email": "admin@example.com",
|
||||||
|
"password": "new-password",
|
||||||
|
"currentPassword": "current-password",
|
||||||
|
"totpToken": "123456",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 200, response.text)
|
||||||
|
self.assertEqual(fake.login_calls, [("admin", "current-password", "123456")])
|
||||||
|
self.assertEqual(
|
||||||
|
fake.update_calls,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"token": "admin-token",
|
||||||
|
"user_id": 1,
|
||||||
|
"username": "admin",
|
||||||
|
"email": "admin@example.com",
|
||||||
|
"password": "new-password",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
self.assertIn("reauth-token", fake.logged_out)
|
||||||
|
|
||||||
|
|
||||||
class EnabledModeSetupAndLoginTests(unittest.TestCase):
|
class EnabledModeSetupAndLoginTests(unittest.TestCase):
|
||||||
"""Exercises the real (client is not None) path, including the
|
"""Exercises the real (client is not None) path, including the
|
||||||
setup-claim flag's interaction with the store."""
|
setup-claim flag's interaction with the store."""
|
||||||
|
|||||||
@@ -9,7 +9,12 @@ from shared_backend.auth import (
|
|||||||
verify_password,
|
verify_password,
|
||||||
)
|
)
|
||||||
from shared_backend.clientip import client_address, parse_trusted_proxies
|
from shared_backend.clientip import client_address, parse_trusted_proxies
|
||||||
from shared_backend.totp import verify_totp
|
from shared_backend.coreconfig import (
|
||||||
|
EXAMPLE_INTERNAL_SECRETS,
|
||||||
|
MIN_INTERNAL_SECRET_LENGTH,
|
||||||
|
internal_secret_matches,
|
||||||
|
)
|
||||||
|
from shared_backend.totp import verify_totp, verify_totp_step
|
||||||
|
|
||||||
# The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
|
# The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
|
||||||
CONTRACT_PATH = Path(__file__).resolve().parents[3] / "contract" / "auth-contract.json"
|
CONTRACT_PATH = Path(__file__).resolve().parents[3] / "contract" / "auth-contract.json"
|
||||||
@@ -27,22 +32,24 @@ class AuthContractTests(unittest.TestCase):
|
|||||||
password = self.contract["password"]
|
password = self.contract["password"]
|
||||||
for entry in password["hashes"]:
|
for entry in password["hashes"]:
|
||||||
with self.subTest(entry["name"]):
|
with self.subTest(entry["name"]):
|
||||||
|
plaintext = entry.get("password", password["plaintext"])
|
||||||
|
wrong_password = entry.get("wrongPassword", password["wrongPassword"])
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
verify_password(password["plaintext"], entry["hash"]),
|
verify_password(plaintext, entry["hash"]),
|
||||||
entry["verifies"]["python"],
|
entry["verifies"]["python"],
|
||||||
)
|
)
|
||||||
self.assertFalse(verify_password(password["wrongPassword"], entry["hash"]))
|
self.assertFalse(verify_password(wrong_password, entry["hash"]))
|
||||||
if "python" in entry.get("needsUpgrade", {}):
|
if "python" in entry.get("needsUpgrade", {}):
|
||||||
want = entry["needsUpgrade"]["python"]
|
want = entry["needsUpgrade"]["python"]
|
||||||
self.assertEqual(password_hash_needs_upgrade(entry["hash"]), want)
|
self.assertEqual(password_hash_needs_upgrade(entry["hash"]), want)
|
||||||
valid, upgraded = verify_and_upgrade_password(
|
valid, upgraded = verify_and_upgrade_password(
|
||||||
password["plaintext"], entry["hash"]
|
plaintext, entry["hash"]
|
||||||
)
|
)
|
||||||
self.assertTrue(valid)
|
self.assertTrue(valid)
|
||||||
self.assertEqual(upgraded is not None, want)
|
self.assertEqual(upgraded is not None, want)
|
||||||
if upgraded is not None:
|
if upgraded is not None:
|
||||||
self.assertTrue(upgraded.startswith("bcrypt$"))
|
self.assertTrue(upgraded.startswith(("bcrypt$", "bcrypt-sha256$")))
|
||||||
self.assertTrue(verify_password(password["plaintext"], upgraded))
|
self.assertTrue(verify_password(plaintext, upgraded))
|
||||||
|
|
||||||
def test_the_password_length_contract_holds_for_python(self) -> None:
|
def test_the_password_length_contract_holds_for_python(self) -> None:
|
||||||
too_long = self.contract["password"]["tooLongToHash"]
|
too_long = self.contract["password"]["tooLongToHash"]
|
||||||
@@ -59,6 +66,11 @@ class AuthContractTests(unittest.TestCase):
|
|||||||
with self.subTest(entry["name"]):
|
with self.subTest(entry["name"]):
|
||||||
secret = entry.get("secret", totp["secret"])
|
secret = entry.get("secret", totp["secret"])
|
||||||
self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"])
|
self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"])
|
||||||
|
if entry["valid"]:
|
||||||
|
self.assertEqual(
|
||||||
|
verify_totp_step(secret, entry["code"], entry["unix"]),
|
||||||
|
entry.get("matchedStep", entry["unix"] // 30),
|
||||||
|
)
|
||||||
|
|
||||||
def test_client_address_follows_the_contract(self) -> None:
|
def test_client_address_follows_the_contract(self) -> None:
|
||||||
section = self.contract["clientAddress"]
|
section = self.contract["clientAddress"]
|
||||||
@@ -72,6 +84,17 @@ class AuthContractTests(unittest.TestCase):
|
|||||||
with self.subTest(value), self.assertRaises(ValueError):
|
with self.subTest(value), self.assertRaises(ValueError):
|
||||||
parse_trusted_proxies(value)
|
parse_trusted_proxies(value)
|
||||||
|
|
||||||
|
def test_internal_secret_gate_follows_the_contract(self) -> None:
|
||||||
|
rule = self.contract["internalSecret"]
|
||||||
|
self.assertEqual(MIN_INTERNAL_SECRET_LENGTH, rule["minLength"])
|
||||||
|
self.assertEqual(EXAMPLE_INTERNAL_SECRETS, frozenset(rule["placeholders"]))
|
||||||
|
for entry in rule["cases"]:
|
||||||
|
with self.subTest(entry["name"]):
|
||||||
|
self.assertEqual(
|
||||||
|
internal_secret_matches(entry["provided"], entry["secret"]),
|
||||||
|
entry["matches"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -22,7 +22,7 @@ from shared_backend.postgres import (
|
|||||||
retry_startup,
|
retry_startup,
|
||||||
)
|
)
|
||||||
from shared_backend.tokens import hash_token, new_session_token
|
from shared_backend.tokens import hash_token, new_session_token
|
||||||
from shared_backend.totp import totp_provisioning_uri, verify_totp
|
from shared_backend.totp import totp_provisioning_uri, verify_totp, verify_totp_step
|
||||||
|
|
||||||
|
|
||||||
class SharedBackendTests(unittest.TestCase):
|
class SharedBackendTests(unittest.TestCase):
|
||||||
@@ -61,6 +61,19 @@ class SharedBackendTests(unittest.TestCase):
|
|||||||
self.assertTrue(verify_password("correct horse battery staple", upgraded))
|
self.assertTrue(verify_password("correct horse battery staple", upgraded))
|
||||||
self.assertFalse(password_hash_needs_upgrade(upgraded))
|
self.assertFalse(password_hash_needs_upgrade(upgraded))
|
||||||
|
|
||||||
|
def test_long_legacy_pbkdf2_password_migrates_without_truncation(self):
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
password = "legacy:" + "x" * 80
|
||||||
|
salt = "0123456789abcdef0123456789abcdef"
|
||||||
|
expected = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 100_000).hex()
|
||||||
|
legacy = f"{salt}:{expected}"
|
||||||
|
valid, upgraded = verify_and_upgrade_password(password, legacy)
|
||||||
|
self.assertTrue(valid)
|
||||||
|
self.assertTrue(upgraded.startswith("bcrypt-sha256$$2b$12$"))
|
||||||
|
self.assertTrue(verify_password(password, upgraded))
|
||||||
|
self.assertFalse(verify_password(password + "x", upgraded))
|
||||||
|
|
||||||
def test_a_cost_below_the_current_policy_is_upgraded(self):
|
def test_a_cost_below_the_current_policy_is_upgraded(self):
|
||||||
low_cost = "bcrypt$" + bcrypt.hashpw(
|
low_cost = "bcrypt$" + bcrypt.hashpw(
|
||||||
b"correct horse battery staple", bcrypt.gensalt(rounds=4)
|
b"correct horse battery staple", bcrypt.gensalt(rounds=4)
|
||||||
@@ -151,6 +164,8 @@ class SharedBackendTests(unittest.TestCase):
|
|||||||
]
|
]
|
||||||
for timestamp, code in vectors:
|
for timestamp, code in vectors:
|
||||||
self.assertTrue(verify_totp(secret, code, timestamp))
|
self.assertTrue(verify_totp(secret, code, timestamp))
|
||||||
|
self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30)
|
||||||
|
self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30)
|
||||||
self.assertTrue(
|
self.assertTrue(
|
||||||
totp_provisioning_uri("Example App", "admin@example.com", secret).startswith(
|
totp_provisioning_uri("Example App", "admin@example.com", secret).startswith(
|
||||||
"otpauth://totp/"
|
"otpauth://totp/"
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from shared_backend.coreconfig import Info, Store, internal_secret_matches
|
from shared_backend.coreconfig import (
|
||||||
|
MIN_INTERNAL_SECRET_LENGTH,
|
||||||
|
Info,
|
||||||
|
Store,
|
||||||
|
internal_secret_matches,
|
||||||
|
internal_secret_usable,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class StoreDefaultsTests(unittest.TestCase):
|
class StoreDefaultsTests(unittest.TestCase):
|
||||||
@@ -62,6 +68,9 @@ class StoreSetTests(unittest.TestCase):
|
|||||||
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
|
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
|
||||||
|
|
||||||
|
|
||||||
|
LONG_SECRET = "shared-secret-value"
|
||||||
|
|
||||||
|
|
||||||
class InternalSecretTests(unittest.TestCase):
|
class InternalSecretTests(unittest.TestCase):
|
||||||
def test_unset_or_empty_secret_never_matches(self):
|
def test_unset_or_empty_secret_never_matches(self):
|
||||||
self.assertFalse(internal_secret_matches(None, None))
|
self.assertFalse(internal_secret_matches(None, None))
|
||||||
@@ -70,9 +79,26 @@ class InternalSecretTests(unittest.TestCase):
|
|||||||
self.assertFalse(internal_secret_matches("", None))
|
self.assertFalse(internal_secret_matches("", None))
|
||||||
|
|
||||||
def test_compares_the_whole_secret(self):
|
def test_compares_the_whole_secret(self):
|
||||||
self.assertTrue(internal_secret_matches("shared-secret", "shared-secret"))
|
self.assertTrue(internal_secret_matches(LONG_SECRET, LONG_SECRET))
|
||||||
self.assertFalse(internal_secret_matches("shared-secreT", "shared-secret"))
|
self.assertFalse(internal_secret_matches("shared-secret-valuE", LONG_SECRET))
|
||||||
self.assertFalse(internal_secret_matches(None, "shared-secret"))
|
self.assertFalse(internal_secret_matches(None, LONG_SECRET))
|
||||||
|
|
||||||
|
def test_short_secret_never_matches(self):
|
||||||
|
short = "x" * (MIN_INTERNAL_SECRET_LENGTH - 1)
|
||||||
|
self.assertFalse(internal_secret_matches(short, short))
|
||||||
|
|
||||||
|
def test_placeholder_secret_never_matches(self):
|
||||||
|
for placeholder in ("SECRET", "change-me-to-a-long-random-value"):
|
||||||
|
with self.subTest(placeholder=placeholder):
|
||||||
|
self.assertFalse(internal_secret_matches(placeholder, placeholder))
|
||||||
|
|
||||||
|
def test_usable_requires_minimum_length_and_no_placeholder(self):
|
||||||
|
self.assertFalse(internal_secret_usable(None))
|
||||||
|
self.assertFalse(internal_secret_usable(""))
|
||||||
|
self.assertFalse(internal_secret_usable("x" * (MIN_INTERNAL_SECRET_LENGTH - 1)))
|
||||||
|
self.assertTrue(internal_secret_usable("x" * MIN_INTERNAL_SECRET_LENGTH))
|
||||||
|
self.assertFalse(internal_secret_usable("change-me-to-a-long-random-value"))
|
||||||
|
self.assertTrue(internal_secret_usable(LONG_SECRET))
|
||||||
|
|
||||||
|
|
||||||
class UrlValidationTests(unittest.TestCase):
|
class UrlValidationTests(unittest.TestCase):
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ class _FakeDatabase:
|
|||||||
async def fetchrow(self, query: str, *args):
|
async def fetchrow(self, query: str, *args):
|
||||||
self.fetched.append((query, args))
|
self.fetched.append((query, args))
|
||||||
if "totp_enabled" in query:
|
if "totp_enabled" in query:
|
||||||
return {"secret": "S", "enabled": self.totp_enabled}
|
return {"secret": "S", "enabled": self.totp_enabled, "last_used_step": -1}
|
||||||
for condition, row in self.rows_by_condition.items():
|
for condition, row in self.rows_by_condition.items():
|
||||||
if condition in query:
|
if condition in query:
|
||||||
return row
|
return row
|
||||||
@@ -60,6 +60,9 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.assertIn("lower(username)", statements)
|
self.assertIn("lower(username)", statements)
|
||||||
# The index is created only while no clashing pair exists.
|
# The index is created only while no clashing pair exists.
|
||||||
self.assertIn("HAVING count(*) > 1", statements)
|
self.assertIn("HAVING count(*) > 1", statements)
|
||||||
|
self.assertIn(
|
||||||
|
"ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1", statements
|
||||||
|
)
|
||||||
|
|
||||||
async def test_set_totp_secret_refuses_while_enabled(self) -> None:
|
async def test_set_totp_secret_refuses_while_enabled(self) -> None:
|
||||||
self.db.execute_status = "UPDATE 0"
|
self.db.execute_status = "UPDATE 0"
|
||||||
@@ -73,6 +76,52 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse
|
self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse
|
||||||
await self.store.set_totp_secret(2, "NEWSECRET")
|
await self.store.set_totp_secret(2, "NEWSECRET")
|
||||||
|
|
||||||
|
async def test_totp_enrollment_records_its_step_and_replay_is_rejected(self) -> None:
|
||||||
|
class ReplayDatabase(_FakeDatabase):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.state = {
|
||||||
|
"secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
|
||||||
|
"enabled": False,
|
||||||
|
"last_used_step": -1,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def fetchrow(self, query: str, *args):
|
||||||
|
if "FROM auth_users WHERE id = $1" in query and "totp_enabled" in query:
|
||||||
|
return dict(self.state)
|
||||||
|
return await super().fetchrow(query, *args)
|
||||||
|
|
||||||
|
async def execute(self, query: str, *args) -> str:
|
||||||
|
self.executed.append((query, args))
|
||||||
|
step, _, secret = args
|
||||||
|
if "SET totp_enabled = true" in query:
|
||||||
|
if (
|
||||||
|
not self.state["enabled"]
|
||||||
|
and secret == self.state["secret"]
|
||||||
|
and self.state["last_used_step"] < step
|
||||||
|
):
|
||||||
|
self.state["enabled"] = True
|
||||||
|
self.state["last_used_step"] = step
|
||||||
|
return "UPDATE 1"
|
||||||
|
return "UPDATE 0"
|
||||||
|
if "SET last_used_step = $1" in query:
|
||||||
|
if (
|
||||||
|
self.state["enabled"]
|
||||||
|
and secret == self.state["secret"]
|
||||||
|
and self.state["last_used_step"] < step
|
||||||
|
):
|
||||||
|
self.state["last_used_step"] = step
|
||||||
|
return "UPDATE 1"
|
||||||
|
return "UPDATE 0"
|
||||||
|
return await super().execute(query, *args)
|
||||||
|
|
||||||
|
database = ReplayDatabase()
|
||||||
|
store = AuthStore(database) # type: ignore[arg-type]
|
||||||
|
self.assertTrue(await store.enable_totp(1, "287082", 59.0))
|
||||||
|
self.assertEqual(database.state["last_used_step"], 1)
|
||||||
|
self.assertFalse(await store.consume_totp_code(1, "287082", 59.0))
|
||||||
|
self.assertEqual(database.state["last_used_step"], 1)
|
||||||
|
|
||||||
async def test_credential_writes_refuse_an_empty_hash_and_an_at_username(self) -> None:
|
async def test_credential_writes_refuse_an_empty_hash_and_an_at_username(self) -> None:
|
||||||
writes = [
|
writes = [
|
||||||
lambda u, h: self.store.create_user(u, "", h),
|
lambda u, h: self.store.create_user(u, "", h),
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
onTotpSetup,
|
onTotpSetup,
|
||||||
onTotpStatus,
|
onTotpStatus,
|
||||||
totpEnabled = false,
|
totpEnabled = false,
|
||||||
|
requireCredentialsForEmailChange = false,
|
||||||
open = $bindable(false)
|
open = $bindable(false)
|
||||||
}: {
|
}: {
|
||||||
currentEmail?: string;
|
currentEmail?: string;
|
||||||
@@ -23,6 +24,7 @@
|
|||||||
onTotpSetup?: TotpSetupRequest;
|
onTotpSetup?: TotpSetupRequest;
|
||||||
onTotpStatus?: TotpStatusRequest;
|
onTotpStatus?: TotpStatusRequest;
|
||||||
totpEnabled?: boolean;
|
totpEnabled?: boolean;
|
||||||
|
requireCredentialsForEmailChange?: boolean;
|
||||||
open?: boolean;
|
open?: boolean;
|
||||||
} = $props();
|
} = $props();
|
||||||
|
|
||||||
@@ -30,8 +32,13 @@
|
|||||||
let email = $state('');
|
let email = $state('');
|
||||||
let password = $state('');
|
let password = $state('');
|
||||||
let confirmPassword = $state('');
|
let confirmPassword = $state('');
|
||||||
|
let currentPassword = $state('');
|
||||||
|
let totpToken = $state('');
|
||||||
let error = $state('');
|
let error = $state('');
|
||||||
let saving = $state(false);
|
let saving = $state(false);
|
||||||
|
let requiresCurrentCredentials = $derived(
|
||||||
|
!!password || (requireCredentialsForEmailChange && email.trim() !== currentEmail.trim())
|
||||||
|
);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (open) {
|
if (open) {
|
||||||
@@ -39,6 +46,8 @@
|
|||||||
email = currentEmail;
|
email = currentEmail;
|
||||||
password = '';
|
password = '';
|
||||||
confirmPassword = '';
|
confirmPassword = '';
|
||||||
|
currentPassword = '';
|
||||||
|
totpToken = '';
|
||||||
error = '';
|
error = '';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -52,6 +61,16 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (requiresCurrentCredentials && !currentPassword) {
|
||||||
|
error = 'Enter your current password to change your email or password.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requiresCurrentCredentials && totpEnabled && !totpToken) {
|
||||||
|
error = 'Enter a current authenticator code to change your email or password.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!onSave) {
|
if (!onSave) {
|
||||||
error = 'The application has not configured its profile update handler.';
|
error = 'The application has not configured its profile update handler.';
|
||||||
return;
|
return;
|
||||||
@@ -59,7 +78,13 @@
|
|||||||
|
|
||||||
saving = true;
|
saving = true;
|
||||||
try {
|
try {
|
||||||
await onSave({ username, email, password: password || undefined });
|
const input: ProfileUpdateInput = { username, email };
|
||||||
|
if (requiresCurrentCredentials) {
|
||||||
|
input.currentPassword = currentPassword;
|
||||||
|
if (totpEnabled) input.totpToken = totpToken;
|
||||||
|
}
|
||||||
|
if (password) input.password = password;
|
||||||
|
await onSave(input);
|
||||||
open = false;
|
open = false;
|
||||||
} catch (caught) {
|
} catch (caught) {
|
||||||
error = caught instanceof Error ? caught.message : 'Profile update failed.';
|
error = caught instanceof Error ? caught.message : 'Profile update failed.';
|
||||||
@@ -100,6 +125,35 @@
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
|
{#if requiresCurrentCredentials}
|
||||||
|
<label class="sc-field">
|
||||||
|
<span class="sc-label">Current password</span>
|
||||||
|
<input
|
||||||
|
autocomplete="current-password"
|
||||||
|
class="sc-input"
|
||||||
|
required
|
||||||
|
type="password"
|
||||||
|
bind:value={currentPassword}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{#if totpEnabled}
|
||||||
|
<label class="sc-field">
|
||||||
|
<span class="sc-label">Current authenticator code</span>
|
||||||
|
<input
|
||||||
|
autocomplete="one-time-code"
|
||||||
|
class="sc-input"
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="6"
|
||||||
|
pattern="[0-9]{6}"
|
||||||
|
required
|
||||||
|
type="text"
|
||||||
|
bind:value={totpToken}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
|
||||||
{#if password}
|
{#if password}
|
||||||
<label class="sc-field">
|
<label class="sc-field">
|
||||||
<span class="sc-label">Confirm new password</span>
|
<span class="sc-label">Confirm new password</span>
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ export interface ProfileUpdateInput {
|
|||||||
username: string;
|
username: string;
|
||||||
email: string;
|
email: string;
|
||||||
password?: string;
|
password?: string;
|
||||||
|
currentPassword?: string;
|
||||||
|
totpToken?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type UserRole = "superadmin" | "admin" | "user";
|
export type UserRole = "superadmin" | "admin" | "user";
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import ProfileDialog from '../src/lib/components/ProfileDialog.svelte';
|
||||||
|
|
||||||
|
afterEach(cleanup);
|
||||||
|
|
||||||
|
const fieldLabels: Record<string, string> = {
|
||||||
|
username: 'Username',
|
||||||
|
email: 'Email',
|
||||||
|
password: 'New password',
|
||||||
|
confirmPassword: 'Confirm new password',
|
||||||
|
currentPassword: 'Current password',
|
||||||
|
totpToken: 'Current authenticator code',
|
||||||
|
};
|
||||||
|
|
||||||
|
const field = (name: string): HTMLInputElement => screen.getByLabelText(fieldLabels[name]) as HTMLInputElement;
|
||||||
|
|
||||||
|
async function fill(name: string, value: string): Promise<void> {
|
||||||
|
await fireEvent.input(field(name), { target: { value } });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit(): Promise<void> {
|
||||||
|
const form = document.querySelector('form');
|
||||||
|
if (!form) throw new Error('no form');
|
||||||
|
await fireEvent.submit(form);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ProfileDialog password changes', () => {
|
||||||
|
it('requires current password and a current TOTP code when enabled', async () => {
|
||||||
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||||
|
render(ProfileDialog, { props: { open: true, onSave, totpEnabled: true } });
|
||||||
|
await fill('username', 'alice');
|
||||||
|
await fill('email', 'alice@example.com');
|
||||||
|
await fill('password', 'new-password');
|
||||||
|
await fill('confirmPassword', 'new-password');
|
||||||
|
|
||||||
|
await submit();
|
||||||
|
expect(onSave).not.toHaveBeenCalled();
|
||||||
|
expect(screen.getByText('Enter your current password to change it.')).toBeTruthy();
|
||||||
|
|
||||||
|
await fill('currentPassword', 'old-password');
|
||||||
|
await submit();
|
||||||
|
expect(onSave).not.toHaveBeenCalled();
|
||||||
|
expect(screen.getByText('Enter a current authenticator code to change your password.')).toBeTruthy();
|
||||||
|
|
||||||
|
await fill('totpToken', '123456');
|
||||||
|
await submit();
|
||||||
|
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||||
|
expect(onSave).toHaveBeenCalledWith({
|
||||||
|
username: 'alice',
|
||||||
|
email: 'alice@example.com',
|
||||||
|
password: 'new-password',
|
||||||
|
currentPassword: 'old-password',
|
||||||
|
totpToken: '123456',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not ask for password proof when only profile fields change', async () => {
|
||||||
|
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||||
|
render(ProfileDialog, { props: { open: true, onSave, totpEnabled: true } });
|
||||||
|
await fill('username', 'alice');
|
||||||
|
await fill('email', 'alice@example.com');
|
||||||
|
await submit();
|
||||||
|
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||||
|
expect(onSave).toHaveBeenCalledWith({ username: 'alice', email: 'alice@example.com' });
|
||||||
|
expect(screen.queryByLabelText('Current password')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user