ci: expand CI checks and make consumer sync opt-in

- Add Go, npm, Python, and Java validation to CI
- Run Go tests against PostgreSQL
- Record performance fixes in the report
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:14:31 +00:00
1 parent 199a5efaef
commit 22887fef03
100 files changed
+9740 -429

No files matched your search

+11
View File
@@ -26,6 +26,17 @@ jobs:
go-version-file: backend/go.mod go-version-file: backend/go.mod
cache: false cache: false
- name: Check formatting and vet the Go module
working-directory: backend
shell: bash
run: |
set -euo pipefail
mapfile -d '' go_files < <(find . -type f -name '*.go' -print0)
if ((${#go_files[@]})); then
test -z "$(gofmt -l "${go_files[@]}")"
fi
go vet ./...
- name: Test Go module - name: Test Go module
working-directory: backend working-directory: backend
run: go test ./... run: go test ./...
+5
View File
@@ -29,6 +29,11 @@ jobs:
npm ci npm ci
npm run build npm run build
- name: Run the lint and test checks that gate pull requests
run: |
npm run lint
npm test
- name: Configure Gitea npm registry - name: Configure Gitea npm registry
env: env:
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }} PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
+7
View File
@@ -23,6 +23,13 @@ jobs:
with: with:
python-version: '3.12' python-version: '3.12'
- name: Run the lint and test checks that gate pull requests
run: |
set -euo pipefail
python -m pip install --disable-pip-version-check --upgrade pip ruff -e "packages/python-backend[fastapi]"
ruff check packages/python-backend/src packages/python-backend/tests
python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
- name: Build and publish package - name: Build and publish package
env: env:
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }} PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
+6
View File
@@ -1,6 +1,12 @@
#!/bin/sh #!/bin/sh
set -euo pipefail set -euo pipefail
# Consumer synchronization is opt-in. It commits into every registered consumer repository, so it
# runs only for a commit made with SHARED_SYNC_COMMIT=1 in the environment.
if [ "${SHARED_SYNC_COMMIT:-0}" != "1" ]; then
exit 0
fi
repo_root="$(git rev-parse --show-toplevel)" repo_root="$(git rev-parse --show-toplevel)"
sync_script="$repo_root/scripts/sync-consumers.ps1" sync_script="$repo_root/scripts/sync-consumers.ps1"
+6
View File
@@ -43,8 +43,14 @@ jobs:
cache-dependency-path: package-lock.json cache-dependency-path: package-lock.json
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Check the generated root stylesheet is current
run: git diff --exit-code -- shared-styles.css
- name: Check for skipped tests
run: npm run media:enforce:no-skipped-tests
- name: Run Node/Svelte lint checks - name: Run Node/Svelte lint checks
run: npm run lint run: npm run lint
- name: Check Prettier formatting
run: npm run format:check
go: go:
name: Lint (Go) name: Lint (Go)
+43 -1
View File
@@ -54,6 +54,26 @@ jobs:
defaults: defaults:
run: run:
working-directory: backend working-directory: backend
# A throwaway PostgreSQL for the tests that need a real database (the auth store, the
# platform-user SQL, mediacore's routes and the migrate package). Without these two
# variables those tests skip themselves.
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: scratch
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/scratch?sslmode=disable
SHARED_TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/scratch?sslmode=disable
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -62,8 +82,9 @@ jobs:
with: with:
go-version-file: backend/go.mod go-version-file: backend/go.mod
cache: true cache: true
# -p 1 runs one package at a time, because the database tests share one scratch database.
- name: Run Go tests - name: Run Go tests
run: go test ./... run: go test -p 1 ./...
python: python:
name: Test (Python) name: Test (Python)
@@ -81,3 +102,24 @@ jobs:
run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi]" run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi]"
- name: Run Python tests - name: Run Python tests
run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py' run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
java:
name: Test (Java)
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: packages/java-backend
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up JDK
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
cache: maven
cache-dependency-path: packages/java-backend/pom.xml
- name: Run Java tests
run: mvn -B test
+8
View File
@@ -0,0 +1,8 @@
**/dist/
**/.svelte-kit/
**/node_modules/
backend/
packages/java-backend/
packages/python-backend/
shared-styles.css
package-lock.json
+7
View File
@@ -0,0 +1,7 @@
{
"singleQuote": true,
"printWidth": 120,
"trailingComma": "all",
"plugins": ["prettier-plugin-svelte"],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}
+10 -6
View File
@@ -7,7 +7,7 @@
- **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:** 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.
- **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 and High findings handled in the working tree (not committed). - **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). Second Medium pass: P-002 fixed.
## Summary ## Summary
@@ -15,7 +15,7 @@
|---|---:|---:|---:|---:| |---|---:|---:|---:|---:|
| Critical | 0 | 0 | 0 | 0 | | Critical | 0 | 0 | 0 | 0 |
| High | 1 | 1 | 0 | 0 | | High | 1 | 1 | 0 | 0 |
| Medium | 4 | 0 | 0 | 4 | | Medium | 4 | 4 | 0 | 0 |
| Low | 4 | 0 | 0 | 4 | | Low | 4 | 0 | 0 | 4 |
| Info | 1 | 0 | 0 | 1 | | Info | 1 | 0 | 0 | 1 |
@@ -30,29 +30,33 @@ The auth code has no obvious SQL N+1 outside the playlist reorder path, and most
- **Recommendation:** Remove timing entries when a session is evicted or loses its last peer. Apply the same cap to all per-session maps. Add a maximum connection count and per-IP and per-peer message-rate limits. - **Recommendation:** Remove timing entries when a session is evicted or loses its last peer. Apply the same cap to all per-session maps. Add a maximum connection count and per-IP and per-peer message-rate limits.
- **Status:** Fixed 2026-10-19 — the `playAt`, `playAtLocalMs` and `capturedAtMs` maps are trimmed to `maxSyncSessions` (1000) after each `sync:update` write, and `ServeWebSocket` refuses connections past `maxSyncConnections` (1000) by closing with 1013 Try Again Later. Over the cap, entries are dropped arbitrarily, as `states` already is, instead of being removed on last-peer exit; per-IP and per-peer message-rate limits are not added. Behaviour change: an 1001st concurrent websocket is closed at once. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`. - **Status:** Fixed 2026-10-19 — the `playAt`, `playAtLocalMs` and `capturedAtMs` maps are trimmed to `maxSyncSessions` (1000) after each `sync:update` write, and `ServeWebSocket` refuses connections past `maxSyncConnections` (1000) by closing with 1013 Try Again Later. Over the cap, entries are dropped arbitrarily, as `states` already is, instead of being removed on last-peer exit; per-IP and per-peer message-rate limits are not added. Behaviour change: an 1001st concurrent websocket is closed at once. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`.
### P-002 · Sync fan-out runs on the HTTP request path and writes to peers one at a time · **Medium** ### P-002 · Sync fan-out runs on the HTTP request path and writes to peers one at a time · **Medium** · Fixed
- **Location:** `backend/syncsocket/syncsocket.go:234` (`Broadcast`), `backend/syncsocket/syncsocket.go:247-261` (serial per-peer writes, 2 s timeout each; JSON marshalled once per peer), `backend/mediacore/mediacore.go:150` (`PUT /sync` calls `Broadcast` inline), `backend/syncsocket/syncsocket.go:486` (each `sync:update` fans out to the whole session) - **Location:** `backend/syncsocket/syncsocket.go:234` (`Broadcast`), `backend/syncsocket/syncsocket.go:247-261` (serial per-peer writes, 2 s timeout each; JSON marshalled once per peer), `backend/mediacore/mediacore.go:150` (`PUT /sync` calls `Broadcast` inline), `backend/syncsocket/syncsocket.go:486` (each `sync:update` fans out to the whole session)
- **Description:** `Broadcast` marshals the payload once per peer and writes to peers sequentially, each with up to a 2 s deadline. The HTTP handler for `PUT /sync` calls it on the request goroutine, so one slow peer can hold the HTTP response for up to 2 s per peer. Peers may send `sync:update` at any rate, and each message is fanned out to the entire session. - **Description:** `Broadcast` marshals the payload once per peer and writes to peers sequentially, each with up to a 2 s deadline. The HTTP handler for `PUT /sync` calls it on the request goroutine, so one slow peer can hold the HTTP response for up to 2 s per peer. Peers may send `sync:update` at any rate, and each message is fanned out to the entire session.
- **Impact:** Slow or hostile peers add latency to unrelated HTTP responses, and one client can multiply its traffic across every peer in its session. - **Impact:** Slow or hostile peers add latency to unrelated HTTP responses, and one client can multiply its traffic across every peer in its session.
- **Recommendation:** Marshal once per broadcast, send through per-peer buffered queues written concurrently, and drop peers whose queue is full. Move HTTP-triggered broadcasts off the request goroutine. Add per-peer message-rate limits. - **Recommendation:** Marshal once per broadcast, send through per-peer buffered queues written concurrently, and drop peers whose queue is full. Move HTTP-triggered broadcasts off the request goroutine. Add per-peer message-rate limits.
- **Status:** Fixed 2026-10-19 — `Broadcast` marshals once and queues the message on a buffered per-peer channel without waiting on the network, a peer whose queue is full is dropped, and each peer now has a message-rate limit (120 messages per second; a faster client is closed with status 1008). Verifying it with a real stuck peer found that dropping the peer still blocked the caller: `conn.Close` waits up to five seconds for a close frame that a stuck peer never sends, and `Broadcast` (so `PUT /sync` and every other peer's read loop) ran that inline. `peer.drop` now closes the peer's `done` channel and runs the close handshake in its own goroutine, used by `Broadcast` and by the targeted send in `handleSyncUpdate`; a test fails without it (five seconds instead of microseconds). Behaviour change: none for well-behaved clients; a client sending over 120 messages in one second is disconnected. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`, `backend/mediacore/mediacore.go`, `backend/mediacore/routes_test.go`.
### P-003 · Media lookup defeats the `media_key` index, and playlist reorder issues one UPDATE per id · **Medium** ### P-003 · Media lookup defeats the `media_key` index, and playlist reorder issues one UPDATE per id · **Medium** · Fixed
- **Location:** `backend/mediacore/mediacore.go:735` (`findMedia`: `WHERE media_key=$1 OR CAST(id AS TEXT)=$1`), `backend/mediacore/mediacore.go:210` (thumbnail join with the same OR pattern), `backend/mediacore/mediacore.go:711-713` (reorder loop, one UPDATE per id, errors discarded, no transaction) - **Location:** `backend/mediacore/mediacore.go:735` (`findMedia`: `WHERE media_key=$1 OR CAST(id AS TEXT)=$1`), `backend/mediacore/mediacore.go:210` (thumbnail join with the same OR pattern), `backend/mediacore/mediacore.go:711-713` (reorder loop, one UPDATE per id, errors discarded, no transaction)
- **Description:** An OR with a cast on `id` makes the planner unlikely to use the `media_key` index alone. Stream and thumbnail requests call this path on every request (`mediacore.go:181`, `194-224`). The reorder handler issues one statement per submitted id without a transaction and ignores errors; the 512 KB body cap allows tens of thousands of ids. - **Description:** An OR with a cast on `id` makes the planner unlikely to use the `media_key` index alone. Stream and thumbnail requests call this path on every request (`mediacore.go:181`, `194-224`). The reorder handler issues one statement per submitted id without a transaction and ignores errors; the 512 KB body cap allows tens of thousands of ids.
- **Impact:** Each media request can cost a sequential scan on a large `media` table, and a single reorder call can issue tens of thousands of statements and report success after a partial failure. Plan impact was not measured (no database access). - **Impact:** Each media request can cost a sequential scan on a large `media` table, and a single reorder call can issue tens of thousands of statements and report success after a partial failure. Plan impact was not measured (no database access).
- **Recommendation:** Look up by `media_key` only, and try the numeric id only when the input is all digits. Replace the loop with one `UPDATE ... FROM unnest(...)` inside a transaction, check errors, and cap the id count. Confirm with `EXPLAIN` on a populated table. - **Recommendation:** Look up by `media_key` only, and try the numeric id only when the input is all digits. Replace the loop with one `UPDATE ... FROM unnest(...)` inside a transaction, check errors, and cap the id count. Confirm with `EXPLAIN` on a populated table.
- **Status:** Fixed 2026-10-19 — `findMedia` and the thumbnail join match `media_key` and only a canonical decimal `id` (`canonicalMediaID`), so the id comparison no longer casts the column. Playlist reorder is one `UPDATE ... FROM unnest(...)` in a transaction, its error is checked, and requests above 10,000 ids are refused. Not measured: no database was available, so the `EXPLAIN` check on a populated table is still needed. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/paths_test.go`.
### P-004 · Password hashing blocks the event loop · **Medium** ### P-004 · Password hashing blocks the event loop · **Medium** · Fixed
- **Location:** `packages/node-backend/src/auth.js:61` and `:69` (`crypto.pbkdf2Sync` in `hashPassword` and `verifyPassword`), `packages/python-backend/src/shared_backend/auth.py:126` and `:131` (`bcrypt.hashpw` and `bcrypt.checkpw` called synchronously inside an otherwise async module) - **Location:** `packages/node-backend/src/auth.js:61` and `:69` (`crypto.pbkdf2Sync` in `hashPassword` and `verifyPassword`), `packages/python-backend/src/shared_backend/auth.py:126` and `:131` (`bcrypt.hashpw` and `bcrypt.checkpw` called synchronously inside an otherwise async module)
- **Description:** Both runtimes perform deliberately expensive hashing synchronously on the thread that serves requests. Node uses 100,000 PBKDF2 iterations; Python uses bcrypt defaults. Each call takes tens to hundreds of milliseconds of CPU. - **Description:** Both runtimes perform deliberately expensive hashing synchronously on the thread that serves requests. Node uses 100,000 PBKDF2 iterations; Python uses bcrypt defaults. Each call takes tens to hundreds of milliseconds of CPU.
- **Impact:** A burst of login or signup attempts stalls every other request in the process, which makes this a cheap denial-of-service lever as well as a latency problem. - **Impact:** A burst of login or signup attempts stalls every other request in the process, which makes this a cheap denial-of-service lever as well as a latency problem.
- **Recommendation:** In Node, use the async `crypto.pbkdf2` or `scrypt`. In Python, wrap the bcrypt calls in `asyncio.to_thread` or expose async variants and use them from async handlers. - **Recommendation:** In Node, use the async `crypto.pbkdf2` or `scrypt`. In Python, wrap the bcrypt calls in `asyncio.to_thread` or expose async variants and use them from async handlers.
- **Status:** Fixed 2026-10-19 — Node exports `hashPasswordAsync` and `verifyPasswordAsync` (async PBKDF2), and Python exports `hash_password_async` and `verify_password_async` (bcrypt in `asyncio.to_thread`). The sync helpers are unchanged, so consumers that hash inside request handlers must call the async variants. Files: `packages/node-backend/src/auth.js`, `packages/node-backend/src/index.js`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/src/shared_backend/__init__.py`.
### P-005 · Every authenticated request costs a fresh AuthGuard round trip, and the login-required flag is re-read per request · **Medium** ### P-005 · Every authenticated request costs a fresh AuthGuard round trip, and the login-required flag is re-read per request · **Medium** · Fixed
- **Location:** `backend/auth/proxy.go:504` (`CurrentUser` calls AuthGuard `/api/me` on each request), `backend/auth/proxy.go:512`, `:566`, `:598`, `:651`, `:733`, `:773`, `:848` (each re-reads the login-required setting from the store), `packages/node-backend/src/authclient.js:167` (`validate` per request), `packages/python-backend/src/shared_backend/authclient.py:254` (same), `backend/authclient/client.go:265-285` (middleware validates per request) - **Location:** `backend/auth/proxy.go:504` (`CurrentUser` calls AuthGuard `/api/me` on each request), `backend/auth/proxy.go:512`, `:566`, `:598`, `:651`, `:733`, `:773`, `:848` (each re-reads the login-required setting from the store), `packages/node-backend/src/authclient.js:167` (`validate` per request), `packages/python-backend/src/shared_backend/authclient.py:254` (same), `backend/authclient/client.go:265-285` (middleware validates per request)
- **Description:** No client caches validated sessions, and the Go proxy re-reads the login-required flag from Postgres in each middleware and handler. A request carrying an invalid token still triggers an outbound call. The clients are otherwise correct about timeouts and context propagation. - **Description:** No client caches validated sessions, and the Go proxy re-reads the login-required flag from Postgres in each middleware and handler. A request carrying an invalid token still triggers an outbound call. The clients are otherwise correct about timeouts and context propagation.
- **Impact:** Every request pays an AuthGuard round trip and at least one database read, so latency and load on AuthGuard and Postgres scale directly with traffic. Invalid tokens can be used to drive outbound calls. - **Impact:** Every request pays an AuthGuard round trip and at least one database read, so latency and load on AuthGuard and Postgres scale directly with traffic. Invalid tokens can be used to drive outbound calls.
- **Recommendation:** Cache the login-required flag in memory with a short TTL, passing the resolved value down the request. Add a short-TTL session cache keyed by a SHA-256 of the token, storing both positive and negative results and bounded in size. Keep connections pooled in every client. - **Recommendation:** Cache the login-required flag in memory with a short TTL, passing the resolved value down the request. Add a short-TTL session cache keyed by a SHA-256 of the token, storing both positive and negative results and bounded in size. Keep connections pooled in every client.
- **Status:** Fixed 2026-10-19 — the Go proxy caches the login-required flag, and the Go AuthGuard client caches validation results, for two seconds, positive and negative, bounded at 10,000 entries and keyed by the SHA-256 of the token. The Node and Python AuthGuard clients now cache `validate` the same way, drop the entry on `logout`, and clear the cache when the base URL changes. Behaviour change: a session revoked elsewhere can still validate for up to two seconds. Files: `backend/auth/proxy.go`, `backend/authclient/client.go`, `backend/authclient/validation_cache.go`, `packages/node-backend/src/authclient.js`, `packages/node-backend/test/authclient.test.js`, `packages/python-backend/src/shared_backend/authclient.py`, `packages/python-backend/tests/test_authclient.py`.
### P-006 · Outbound AuthGuard calls use blocking `urllib` on the default thread pool · **Low** ### P-006 · Outbound AuthGuard calls use blocking `urllib` on the default thread pool · **Low**
- **Location:** `packages/python-backend/src/shared_backend/authclient.py:265` (`asyncio.to_thread`), `:276` (`urllib.request.urlopen`), `packages/node-backend/src/authclient.js:177` (abort timer) - **Location:** `packages/python-backend/src/shared_backend/authclient.py:265` (`asyncio.to_thread`), `:276` (`urllib.request.urlopen`), `packages/node-backend/src/authclient.js:177` (abort timer)
+19 -9
View File
@@ -7,6 +7,7 @@
- **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:** 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).
- **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 come from read-only static review passes; the highest-impact citations were re-checked in the code. No lint, build or test was executed.
- **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.
## Summary ## Summary
@@ -22,59 +23,68 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
## Issues ## Issues
### Q-001 · Node database wrapper: no pool `error` listener, and writes are retried blindly · **Medium** ### Q-001 · Node database wrapper: no pool `error` listener, and writes are retried blindly · **Medium** · Fixed
- **Location:** `packages/node-backend/src/db.js:43` (`new Pool(...)` with no `'error'` handler; grep of the package finds none), `packages/node-backend/src/db.js:80-88` (`query()` retries once on any transient error) - **Location:** `packages/node-backend/src/db.js:43` (`new Pool(...)` with no `'error'` handler; grep of the package finds none), `packages/node-backend/src/db.js:80-88` (`query()` retries once on any transient error)
- **Description:** `pg` emits `'error'` on the pool when an idle client fails, for example after a database restart. With no listener, that event is thrown and can terminate the process. Separately, `query()` retries once on any transient error for every statement, including `INSERT` and `UPDATE`, so a write that committed before the connection dropped can be applied twice. - **Description:** `pg` emits `'error'` on the pool when an idle client fails, for example after a database restart. With no listener, that event is thrown and can terminate the process. Separately, `query()` retries once on any transient error for every statement, including `INSERT` and `UPDATE`, so a write that committed before the connection dropped can be applied twice.
- **Impact:** A database restart can crash a service that uses this wrapper, and non-idempotent writes can be duplicated. - **Impact:** A database restart can crash a service that uses this wrapper, and non-idempotent writes can be duplicated.
- **Recommendation:** Attach a logging `pool.on('error', ...)` handler. Retry only reads, or require the caller to opt in to retrying a specific statement. - **Recommendation:** Attach a logging `pool.on('error', ...)` handler. Retry only reads, or require the caller to opt in to retrying a specific statement.
- **Status:** Fixed 2026-10-19 — `Database` attaches a logging `error` listener to the pool, so a failed idle client is logged instead of thrown. `query()` retries after a transient error only for plain read-only SELECTs, and a caller can opt a statement in with `{ retry: true }`. Behaviour change: a write that hits a transient error is no longer retried by default. Files: `packages/node-backend/src/db.js`, `packages/node-backend/test/db.test.js`.
### Q-002 · Repo-level media lint and test tooling points at directories that no longer exist · **Medium** ### Q-002 · Repo-level media lint and test tooling points at directories that no longer exist · **Medium** · Fixed
- **Location:** `scripts/media/lint-all.mjs:26` (package list `webui`) and `:51` (fails with "directory not found"), `scripts/media/enforce-no-skipped-tests.mjs:18-20` (roots `tests`, `webui/src`, `shared/packages`) and `:99-102` (prints OK when nothing is scanned), `scripts/media/upgrade-deps.mjs:102-104` (comment asserts there is no root `package.json`, which is false), `package.json:49-65` (`media:*` scripts) - **Location:** `scripts/media/lint-all.mjs:26` (package list `webui`) and `:51` (fails with "directory not found"), `scripts/media/enforce-no-skipped-tests.mjs:18-20` (roots `tests`, `webui/src`, `shared/packages`) and `:99-102` (prints OK when nothing is scanned), `scripts/media/upgrade-deps.mjs:102-104` (comment asserts there is no root `package.json`, which is false), `package.json:49-65` (`media:*` scripts)
- **Description:** This tooling was carried over from a monorepo. `webui/`, `media-backend/` and `shared/packages` do not exist here; the real package is `packages/web-ui`. `media:lint:all` fails immediately, and `media:enforce:no-skipped-tests` scans zero files and still reports success, which gives false confidence. None of these scripts runs in CI. - **Description:** This tooling was carried over from a monorepo. `webui/`, `media-backend/` and `shared/packages` do not exist here; the real package is `packages/web-ui`. `media:lint:all` fails immediately, and `media:enforce:no-skipped-tests` scans zero files and still reports success, which gives false confidence. None of these scripts runs in CI.
- **Impact:** Dead tooling that either fails or passes vacuously, and misleading comments about the repository layout. - **Impact:** Dead tooling that either fails or passes vacuously, and misleading comments about the repository layout.
- **Recommendation:** Delete the unused scripts, or repoint them at `packages/web-ui` and `packages/*/test(s)`. Make the no-skipped-tests check fail when it scans zero files, and wire any script that is kept into CI. - **Recommendation:** Delete the unused scripts, or repoint them at `packages/web-ui` and `packages/*/test(s)`. Make the no-skipped-tests check fail when it scans zero files, and wire any script that is kept into CI.
- **Status:** Fixed 2026-10-19 — `lint-all.mjs` and `lint-all-json.mjs` point at `packages/web-ui`, `upgrade-deps.mjs` names the real local packages, and `enforce-no-skipped-tests.mjs` scans `packages/web-ui/src` and `packages/node-backend/test` and fails when it finds no files. The no-skipped-tests check now runs in `lint.yml`; `lint-all` is still not wired into CI because web-ui has no ESLint config (Q-009). Files: `scripts/media/lint-all.mjs`, `scripts/media/lint-all-json.mjs`, `scripts/media/upgrade-deps.mjs`, `scripts/media/enforce-no-skipped-tests.mjs`, `.github/workflows/lint.yml`.
### Q-003 · Java package has tests, but no CI job runs them · **Medium** ### Q-003 · Java package has tests, but no CI job runs them · **Medium** · Fixed
- **Location:** `packages/java-backend/pom.xml`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`, `.github/workflows/tests.yml`, `.github/workflows/lint.yml` (neither mentions Java or Maven) - **Location:** `packages/java-backend/pom.xml`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`, `.github/workflows/tests.yml`, `.github/workflows/lint.yml` (neither mentions Java or Maven)
- **Description:** The only Java test class is `AuthClientTest`. `Totp`, `ResetManager`, `Roles` and cookie extraction have no direct tests. The package is compiled into a consuming project as source, so a regression here reaches that project without any signal in this repository. - **Description:** The only Java test class is `AuthClientTest`. `Totp`, `ResetManager`, `Roles` and cookie extraction have no direct tests. The package is compiled into a consuming project as source, so a regression here reaches that project without any signal in this repository.
- **Impact:** Java changes can break without detection. - **Impact:** Java changes can break without detection.
- **Recommendation:** Add a Java job (`mvn -B test` on a JDK matching the target) to `tests.yml`, and add unit tests for `Totp`, `ResetManager`, `Roles` and cookie extraction. - **Recommendation:** Add a Java job (`mvn -B test` on a JDK matching the target) to `tests.yml`, and add unit tests for `Totp`, `ResetManager`, `Roles` and cookie extraction.
- **Status:** Fixed 2026-10-19 — `tests.yml` has a `java` job that runs `mvn -B test` on JDK 17 in `packages/java-backend`. Not compiled or run: no JDK or Maven is available here, so the workflow and the Java test classes were checked by reading only. Files: `.github/workflows/tests.yml`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`.
### Q-004 · Go test coverage is absent for several packages, including the media core and the sync hub · **Medium** ### Q-004 · Go test coverage is absent for several packages, including the media core and the sync hub · **Medium** · Fixed
- **Location:** `backend/mediacore/mediacore.go` (1107 lines, no tests), `backend/syncsocket/syncsocket.go` (581 lines, no tests), `backend/logshipper/shipper.go` (438 lines, no tests), `backend/config/config.go` and `backend/migrate/migrate.go` (no tests), `backend/auth/proxy.go` (1525 lines; `proxy_test.go` covers constructors, middleware gating and normalizers only) - **Location:** `backend/mediacore/mediacore.go` (1107 lines, no tests), `backend/syncsocket/syncsocket.go` (581 lines, no tests), `backend/logshipper/shipper.go` (438 lines, no tests), `backend/config/config.go` and `backend/migrate/migrate.go` (no tests), `backend/auth/proxy.go` (1525 lines; `proxy_test.go` covers constructors, middleware gating and normalizers only)
- **Description:** `git ls-files` shows no `_test.go` file in `mediacore`, `syncsocket`, `logshipper`, `config` or `migrate`. In `backend/auth`, the handler-level behaviour of Signup, Login, Logout, UpdateMe, the managed-user endpoints, the TOTP endpoints and the platform-user SQL is untested (per review pass). - **Description:** `git ls-files` shows no `_test.go` file in `mediacore`, `syncsocket`, `logshipper`, `config` or `migrate`. In `backend/auth`, the handler-level behaviour of Signup, Login, Logout, UpdateMe, the managed-user endpoints, the TOTP endpoints and the platform-user SQL is untested (per review pass).
- **Impact:** The largest and most security-relevant code paths (media routes, websocket hub message handling, log redaction) change without tests. - **Impact:** The largest and most security-relevant code paths (media routes, websocket hub message handling, log redaction) change without tests.
- **Recommendation:** Add `httptest` handler tests for the auth-gated routes and for websocket message handling, and table tests for the path helpers (`SafeRelative`, `ResolveUnderRoots`, `thumbnailFile`). - **Recommendation:** Add `httptest` handler tests for the auth-gated routes and for websocket message handling, and table tests for the path helpers (`SafeRelative`, `ResolveUnderRoots`, `thumbnailFile`).
- **Status:** Fixed 2026-10-19 — every gap the finding names now has tests. `syncsocket`: connection cap, origin handling, identity, the per-peer message rate (`allowMessage`, and a flooding client is closed with 1008), and a stuck peer being dropped without holding up `Broadcast`. `logshipper`: levels, the local line, ID scrubbing, batching, the bounded buffer, flush and close, and a failing sink never failing the caller. `config` and `migrate`: the environment helpers, the argument and connection errors, and real goose runs. `mediacore`: the auth gate on every `Require` route, the sync routes (validation, clamping, broadcast to the session only), and, against PostgreSQL, stream and thumbnail (hidden media, escaped and refused paths), likes, saves, views, tags, and playlists including reorder and ownership. `auth`: handler tests for Login, Signup, Logout, UpdateMe, the managed-user routes, the TOTP routes, the gating middlewares and `Me` against a fake AuthGuard, the platform-user SQL against PostgreSQL, and the new contract file. Writing them found and fixed two defects: `Broadcast` could block for five seconds in the close handshake of a stuck peer (see P-002), and `GET /media/{id}/tags` always answered an empty list because the query's `tag` column was ambiguous (`backend/mediacore/mediacore.go`). The PostgreSQL tests skip unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` names a scratch database; `.github/workflows/tests.yml` now provides one to the Go job (`go test -p 1 ./...`). Files: `backend/syncsocket/syncsocket_test.go`, `backend/logshipper/shipper_test.go`, `backend/config/config_test.go`, `backend/migrate/migrate_test.go`, `backend/mediacore/routes_test.go`, `backend/mediacore/routes_db_test.go`, `backend/auth/proxy_handlers_test.go`, `backend/auth/platform_users_integration_test.go`, `backend/auth/store_integration_test.go`, `backend/auth/contract_test.go`, `backend/auth/proxy_test.go`, `.github/workflows/tests.yml`.
### Q-005 · The generated root stylesheet keeps a package import that the build was meant to strip · **Medium** ### Q-005 · The generated root stylesheet keeps a package import that the build was meant to strip · **Medium** · Fixed
- **Location:** `scripts/build-root-styles.mjs:4` (token import as a single-quoted string) and `:7` (filter compares exact text), `shared-styles.css:3` (`@import "@gabriel20xx/design-tokens/theme.css";` kept) - **Location:** `scripts/build-root-styles.mjs:4` (token import as a single-quoted string) and `:7` (filter compares exact text), `shared-styles.css:3` (`@import "@gabriel20xx/design-tokens/theme.css";` kept)
- **Description:** The build removes the token import only when it matches the single-quoted string. `packages/web-ui/src/lib/styles.css:1` uses double quotes, so the filter misses it. The generated `shared-styles.css` keeps a bare package import on line 3 beside the relative import on line 1. This was already present at HEAD. No CI step checks that the committed generated file matches the build output. - **Description:** The build removes the token import only when it matches the single-quoted string. `packages/web-ui/src/lib/styles.css:1` uses double quotes, so the filter misses it. The generated `shared-styles.css` keeps a bare package import on line 3 beside the relative import on line 1. This was already present at HEAD. No CI step checks that the committed generated file matches the build output.
- **Impact:** Consumers that vendor this file must resolve a package they may not install, or their bundler fails. The duplicated import also shows that the generation step is not verified. - **Impact:** Consumers that vendor this file must resolve a package they may not install, or their bundler fails. The duplicated import also shows that the generation step is not verified.
- **Recommendation:** Normalise quotes in the filter (or match both forms), then add a CI step that rebuilds and runs `git diff --exit-code shared-styles.css`. - **Recommendation:** Normalise quotes in the filter (or match both forms), then add a CI step that rebuilds and runs `git diff --exit-code shared-styles.css`.
- **Status:** Fixed 2026-10-19 — the build's token-import filter matches both quote styles and an optional semicolon, so the package import is stripped. Running the build reproduces `shared-styles.css` byte for byte, and `lint.yml` now runs `git diff --exit-code -- shared-styles.css` after `npm ci`. Files: `scripts/build-root-styles.mjs`, `shared-styles.css`, `.github/workflows/lint.yml`.
### Q-006 · The sync script can overwrite consumer changes, and the post-commit hook commits into consumer repositories · **Medium** ### Q-006 · The sync script can overwrite consumer changes, and the post-commit hook commits into consumer repositories · **Medium** · Fixed
- **Location:** `scripts/sync-consumers.ps1:273` (dirty-destination check bypassed by `-Force`), `scripts/sync-consumers.ps1:291` (stale files removed) and `:301` (files overwritten), `.githooks/post-commit:8-10` (runs the sync with `-Commit` after every commit), `scripts/install-sync-hook.ps1` (enables the hook) - **Location:** `scripts/sync-consumers.ps1:273` (dirty-destination check bypassed by `-Force`), `scripts/sync-consumers.ps1:291` (stale files removed) and `:301` (files overwritten), `.githooks/post-commit:8-10` (runs the sync with `-Commit` after every commit), `scripts/install-sync-hook.ps1` (enables the hook)
- **Description:** With `-Force`, uncommitted changes inside a consumer's `shared/` folder are deleted or overwritten with no backup. The hook, once installed, runs the sync with `-Commit` after every commit in this repository, which creates commits in each registered consumer repository (22 entries in `$consumerProjects`). - **Description:** With `-Force`, uncommitted changes inside a consumer's `shared/` folder are deleted or overwritten with no backup. The hook, once installed, runs the sync with `-Commit` after every commit in this repository, which creates commits in each registered consumer repository (22 entries in `$consumerProjects`).
- **Impact:** Possible loss of uncommitted consumer work, and unexpected commits in other projects after an unrelated commit here. - **Impact:** Possible loss of uncommitted consumer work, and unexpected commits in other projects after an unrelated commit here.
- **Recommendation:** Make destructive overwrite require an explicit flag that first stashes or backs up the destination. Make the hook opt-in, or have it report what would change instead of committing. Document the behaviour in the README. - **Recommendation:** Make destructive overwrite require an explicit flag that first stashes or backs up the destination. Make the hook opt-in, or have it report what would change instead of committing. Document the behaviour in the README.
- **Status:** Fixed 2026-10-19 — the post-commit hook runs the consumer sync only when `SHARED_SYNC_COMMIT=1` is set for that commit, and `sync-consumers.ps1` copies a dirty destination to a temp backup before `-Force` overwrites it. Behaviour change: an ordinary commit no longer syncs or commits into consumer repositories. Not run: PowerShell is not installed here, so the script change is unparsed. Files: `.githooks/post-commit`, `scripts/sync-consumers.ps1`, `scripts/install-sync-hook.ps1`.
### Q-007 · Publish workflows release without running the checks that exist for pull requests · **Medium** ### Q-007 · Publish workflows release without running the checks that exist for pull requests · **Medium** · Fixed
- **Location:** `.gitea/workflows/publish-npm.yml:27-49` (builds, then publishes; no lint or test step), `.gitea/workflows/publish-python.yml:26-39` (builds and uploads; no ruff or unittest), `.gitea/workflows/publish-go.yml:29-31` (runs `go test` only; no `go vet` or gofmt) - **Location:** `.gitea/workflows/publish-npm.yml:27-49` (builds, then publishes; no lint or test step), `.gitea/workflows/publish-python.yml:26-39` (builds and uploads; no ruff or unittest), `.gitea/workflows/publish-go.yml:29-31` (runs `go test` only; no `go vet` or gofmt)
- **Description:** A `v*` tag or a published release publishes whatever is tagged, without the lint and test jobs in `.github/workflows` that gate changes. The publish workflows run in a separate system, so the same checks are not enforced at release time. - **Description:** A `v*` tag or a published release publishes whatever is tagged, without the lint and test jobs in `.github/workflows` that gate changes. The publish workflows run in a separate system, so the same checks are not enforced at release time.
- **Impact:** Broken or unlinted code can reach the shared registries that projects consume. - **Impact:** Broken or unlinted code can reach the shared registries that projects consume.
- **Recommendation:** Make each publish job run the same checks as CI (`npm run lint` and `npm test`, `ruff check`, `python -m unittest`, `go vet` and gofmt) before upload, or depend on a prior successful workflow run. - **Recommendation:** Make each publish job run the same checks as CI (`npm run lint` and `npm test`, `ruff check`, `python -m unittest`, `go vet` and gofmt) before upload, or depend on a prior successful workflow run.
- **Status:** Fixed 2026-10-19 — each publish workflow runs the checks that gate pull requests before it uploads: npm runs `npm run lint` and `npm test`, Python runs ruff and the unittest suite, and Go runs gofmt and `go vet` before `go test`. Not run: no Gitea runner is available here. The Go gofmt step will fail until `backend/authclient/client.go` and `backend/syncsocket/syncsocket.go` are gofmt-clean; their in-progress hunks were not reformatted in this pass. Files: `.gitea/workflows/publish-npm.yml`, `.gitea/workflows/publish-python.yml`, `.gitea/workflows/publish-go.yml`.
### Q-008 · The four AuthGuard clients diverge in behaviour and in the stored password-hash format · **Medium** ### Q-008 · The four AuthGuard clients diverge in behaviour and in the stored password-hash format · **Medium** · Open
- **Location:** `packages/node-backend/src/auth.js:56-81` (PBKDF2 `salt:hex` hashes) vs `packages/python-backend/src/shared_backend/auth.py:123-133` (bcrypt hashes) in the same `auth_users.password_hash` column; `packages/python-backend/src/shared_backend/auth.py:225-240` (`list_users` and `create_managed_user` return `password_hash`) vs `packages/node-backend/src/auth.js:221-233` (excludes it); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:195` (`IllegalStateException` escapes `middleware` while Node returns 401); `packages/node-backend/src/db.js:69-74` (retries only transient errors) vs `packages/python-backend/src/shared_backend/postgres.py:63` (retries every exception); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:80` (`String.equals`) vs constant-time comparison in Node and Python - **Location:** `packages/node-backend/src/auth.js:56-81` (PBKDF2 `salt:hex` hashes) vs `packages/python-backend/src/shared_backend/auth.py:123-133` (bcrypt hashes) in the same `auth_users.password_hash` column; `packages/python-backend/src/shared_backend/auth.py:225-240` (`list_users` and `create_managed_user` return `password_hash`) vs `packages/node-backend/src/auth.js:221-233` (excludes it); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:195` (`IllegalStateException` escapes `middleware` while Node returns 401); `packages/node-backend/src/db.js:69-74` (retries only transient errors) vs `packages/python-backend/src/shared_backend/postgres.py:63` (retries every exception); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:80` (`String.equals`) vs constant-time comparison in Node and Python
- **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`.
### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium** ### 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)
- **Description:** No ESLint, Prettier or Stylelint configuration is tracked for `packages/web-ui` or `packages/node-backend`. Lint covers type checks and syntax only. `packages/web-ui` has no tests, so components such as `AuthPage`, `MediaPlayer` and the notification and primary-color stores are unverified. - **Description:** No ESLint, Prettier or Stylelint configuration is tracked for `packages/web-ui` or `packages/node-backend`. Lint covers type checks and syntax only. `packages/web-ui` has no tests, so components such as `AuthPage`, `MediaPlayer` and the notification and primary-color stores are unverified.
- **Impact:** Style drift and behavioural regressions in a UI library that several applications consume. - **Impact:** Style drift and behavioural regressions in a UI library that several applications consume.
- **Recommendation:** Add ESLint (with `eslint-plugin-svelte`) and Prettier configuration at package level, and a small Vitest and `@testing-library/svelte` suite covering `AuthPage`, the notification store and the primary-color helpers. - **Recommendation:** Add ESLint (with `eslint-plugin-svelte`) and Prettier configuration at package level, and a small Vitest and `@testing-library/svelte` suite covering `AuthPage`, the notification store and the primary-color helpers.
- **Status:** Fixed 2026-10-19 — ESLint (flat config `eslint.config.js`: `@eslint/js`, `typescript-eslint`, `eslint-plugin-svelte`) now lints `packages/web-ui`, `packages/node-backend` and `scripts` with `--max-warnings=0`; it is part of `npm run lint` (so of `lint.yml` and the publish gate) and each package has a `lint` script. Prettier 3 with `prettier-plugin-svelte` is configured in `.prettierrc.json`, with `npm run format` and `format:check` (also a `lint.yml` step). `packages/web-ui` has a Vitest and `@testing-library/svelte` suite in `packages/web-ui/tests` (27 tests: `AuthPage` login, two-factor challenge, setup and reset flows; the notification store and `NotificationStack`; the primary-color helpers), run by `npm run test:web-ui`, which `npm test` and `release` now include. All of it is root `devDependencies` (`eslint`, `@eslint/js`, `typescript-eslint`, `eslint-plugin-svelte`, `globals`, `prettier`, `prettier-plugin-svelte`, `vitest`, `jsdom`, `@testing-library/svelte`; no way to fix the finding without them), so `packages/web-ui/package.json`'s dependencies and the consumers' lockfile entries for it are unchanged; only a `lint` and a `test` script were added there. The existing code passes ESLint without code changes beyond three unused bindings in `scripts/media`; three Svelte rules that would change how shipped components render or hold state (`require-each-key`, `prefer-writable-derived`, `prefer-svelte-reactivity`) are turned off with a comment. Not done: Prettier is enforced only on the files written to its style (44 older files differ from it and were not reformatted, to keep the mirrored diff small), and Stylelint was not added. Files: `eslint.config.js`, `.prettierrc.json`, `.prettierignore`, `package.json`, `package-lock.json`, `packages/web-ui/{package.json,vitest.config.ts,tests/}`, `packages/node-backend/package.json`, `scripts/media/{lint-all,lint-all-json,list-skipped-tests,enforce-no-skipped-tests}.mjs`, `.github/workflows/lint.yml`.
### Q-010 · Errors on security paths are masked as invalid codes or swallowed · **Low** ### Q-010 · Errors on security paths are masked as invalid codes or swallowed · **Low**
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:723` and `:740` (`except Exception` returns "Invalid authenticator code"), `packages/python-backend/src/shared_backend/authproxy.py:506-507` (logout ignores `APIError` but clears the cookie), `backend/auth/proxy.go:1232-1235` (`TOTPVerify` maps every error to 401 invalid code), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:282-284` (`IOException` discarded without logging) - **Location:** `packages/python-backend/src/shared_backend/authproxy.py:723` and `:740` (`except Exception` returns "Invalid authenticator code"), `packages/python-backend/src/shared_backend/authproxy.py:506-507` (logout ignores `APIError` but clears the cookie), `backend/auth/proxy.go:1232-1235` (`TOTPVerify` maps every error to 401 invalid code), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:282-284` (`IOException` discarded without logging)
+9 -2
View File
@@ -106,7 +106,7 @@ To pull the latest snapshot into every registered consumer:
.\scripts\sync-consumers.ps1 -Commit -Push .\scripts\sync-consumers.ps1 -Commit -Push
``` ```
The script copies every tracked file in this repo into each consumer's `shared/` folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared snapshot from `<short-sha>`"). Consumers are registered in the script's `$consumerProjects` list. A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) runs this automatically — with `-Commit` only, never `-Push` — after every commit to this repo, so pushing the sync commits it creates to each consumer is still a manual follow-up step. The script copies every tracked file in this repo into each consumer's `shared/` folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared snapshot from `<short-sha>`"). Consumers are registered in the script's `$consumerProjects` list. A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) can run this automatically, with `-Commit` only and never `-Push`. It is opt-in: it does nothing unless the commit is made with `SHARED_SYNC_COMMIT=1` in the environment, so an ordinary commit here never writes to a consumer repository. Pushing the sync commits to each consumer remains a manual follow-up step. Running with `-Force` over a consumer that has local changes first copies the replaced `shared/` folder to a temporary backup directory, and the script prints its path.
### Published registry packages (for standalone/external use) ### Published registry packages (for standalone/external use)
@@ -119,8 +119,11 @@ The npm, Go, and Python packages are also published to this Gitea instance's pac
```bash ```bash
npm install npm install
npm run check npm run check
npm run lint # svelte-check, Node syntax check and ESLint
npm run format:check # Prettier, for the files written to its style (.prettierrc.json)
npm run build # builds packages/web-ui/dist (gitignored, not committed) npm run build # builds packages/web-ui/dist (gitignored, not committed)
npm run test:node-backend npm run test:node-backend
npm run test:web-ui # Vitest component and store tests (jsdom)
``` ```
```bash ```bash
@@ -129,6 +132,10 @@ go test ./...
go vet ./... 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 ./...`).
`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.
--- ---
## Typical `web-ui` wiring ## Typical `web-ui` wiring
@@ -196,4 +203,4 @@ The Go module lives under `backend`, so its release tag uses the submodule prefi
## CI/CD ## CI/CD
`lint.yml` and `tests.yml` each run three jobs — Node/Svelte, Go, and Python. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above. `lint.yml` runs three jobs — Node/Svelte (svelte-check, ESLint, Prettier), Go, and Python; `tests.yml` runs four — Node/Svelte (including the web-ui Vitest suite), Go (against a PostgreSQL service), Python, and Java. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above.
+29 -16
View File
@@ -7,7 +7,7 @@
- **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:** 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.
- **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 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.
- **Updated:** 2026-10-19 — Critical and High findings handled in the working tree (not committed). - **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.
## 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 | 0 | 0 | 13 | | Medium | 13 | 11 | 0 | 2 |
| Low | 5 | 0 | 0 | 5 | | Low | 5 | 0 | 0 | 5 |
| Info | 0 | 0 | 0 | 0 | | Info | 0 | 0 | 0 | 0 |
@@ -42,7 +42,7 @@ The most serious issue is a Python router route that lets an anonymous caller sw
- **Description:** The hub does not authenticate the connection. A client chooses its `clientId` in `sync:hello` or `client:status`, with no uniqueness or ownership check. Peers can see each other's IDs and control state, so a new client can adopt the ID of a peer that has remote control enabled and then claim or release that control. - **Description:** The hub does not authenticate the connection. A client chooses its `clientId` in `sync:hello` or `client:status`, with no uniqueness or ownership check. Peers can see each other's IDs and control state, so a new client can adopt the ID of a peer that has remote control enabled and then claim or release that control.
- **Impact:** Any client that can reach `/ws` and join a session can take over playback control or impersonate another device. Exposure depends on whether each consumer gates `/ws` with authentication (not verifiable here; the package's own example wires it with no middleware). - **Impact:** Any client that can reach `/ws` and join a session can take over playback control or impersonate another device. Exposure depends on whether each consumer gates `/ws` with authentication (not verifiable here; the package's own example wires it with no middleware).
- **Recommendation:** Bind each connection to a server-issued identity (an authenticated user or a signed session token) at upgrade time. Reject duplicate client IDs within a session. Require authentication on the `/ws` route in every consumer, and show that in the package documentation. - **Recommendation:** Bind each connection to a server-issued identity (an authenticated user or a signed session token) at upgrade time. Reject duplicate client IDs within a session. Require authentication on the `/ws` route in every consumer, and show that in the package documentation.
- **Status:** Open 2026-10-19 — not changed in this run. `clientId` is still self-asserted and `/ws` still accepts unauthenticated connections. The fix needs a protocol change: `ServeWebSocket` must take an identity from the consumer's authenticated `/ws` route, and the hub must bind `clientId` to it. Rejecting duplicate IDs is a policy decision, not a patch: a legitimate reconnect can be refused until the server notices the old socket is dead, and no consumer client was found under `/workspace/Personal/Web` to confirm clients never reuse an ID. The connection cap added under P-001 limits flooding only; it does not add identity. - **Status:** Open 2026-10-19 — partly fixed (decision 12): each websocket connection is issued a random `clientId` at upgrade time and receives it in its `hello` frame. A message naming any other identity gets a `client-id-mismatch` error frame and is dropped, so self-chosen and duplicate IDs are no longer possible. Behaviour change: a client must take its ID from `hello`, and a reconnect gets a new identity, so control claims and remote-control flags do not carry over. Still open: `/ws` still accepts unauthenticated connections, so an anonymous connection can still obtain an identity and claim control of any peer that enabled remote control. Requiring authentication on each consumer's `/ws` route is a consumer change and was not made here. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`.
### S-004 · Anonymous `PUT /sync` writes unvalidated JSON into shared session state · **High** · Fixed ### S-004 · Anonymous `PUT /sync` writes unvalidated JSON into shared session state · **High** · Fixed
- **Location:** `backend/mediacore/mediacore.go:88` (`r.With(c.auth.Optional).Put("/sync", ...)`), `backend/mediacore/mediacore.go:124-152` (`putSyncState`, which does not check the caller), `backend/mediacore/mediacore.go:135` (session ID defaults to `"default"`), `backend/mediacore/mediacore.go:138` and `:146-148` (raw `mediaId` and `playAt` stored), `backend/mediacore/mediacore.go:1049` (512 KB body cap), `backend/syncsocket/syncsocket.go:204-213` (1000-session cap, no per-entry size limit) - **Location:** `backend/mediacore/mediacore.go:88` (`r.With(c.auth.Optional).Put("/sync", ...)`), `backend/mediacore/mediacore.go:124-152` (`putSyncState`, which does not check the caller), `backend/mediacore/mediacore.go:135` (session ID defaults to `"default"`), `backend/mediacore/mediacore.go:138` and `:146-148` (raw `mediaId` and `playAt` stored), `backend/mediacore/mediacore.go:1049` (512 KB body cap), `backend/syncsocket/syncsocket.go:204-213` (1000-session cap, no per-entry size limit)
@@ -51,83 +51,96 @@ The most serious issue is a Python router route that lets an anonymous caller sw
- **Recommendation:** Require authentication, or a session-scoped token, for `PUT /sync`. Validate `mediaId` and `playAt` types the way the websocket path does, and cap the stored size per session. - **Recommendation:** Require authentication, or a session-scoped token, for `PUT /sync`. Validate `mediaId` and `playAt` types the way the websocket path does, and cap the stored size per session.
- **Status:** Fixed 2026-10-19 — `PUT /sync` now sits behind `Require`, so anonymous callers get 401 when login is required. `mediaId` and `playAt` must be null, a number or a string, and strings are trimmed and capped at 128 bytes, so other shapes are refused with 400 and the stored state holds only scalars. Behaviour change: clients that send anonymous `PUT /sync` with login enabled are now refused, and non-scalar `mediaId` or `playAt` values get 400. Any authenticated user can still write any session, including `"default"`, which is the session model rather than part of this finding. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/mediacore_test.go`. - **Status:** Fixed 2026-10-19 — `PUT /sync` now sits behind `Require`, so anonymous callers get 401 when login is required. `mediaId` and `playAt` must be null, a number or a string, and strings are trimmed and capped at 128 bytes, so other shapes are refused with 400 and the stored state holds only scalars. Behaviour change: clients that send anonymous `PUT /sync` with login enabled are now refused, and non-scalar `mediaId` or `playAt` values get 400. Any authenticated user can still write any session, including `"default"`, which is the session model rather than part of this finding. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/mediacore_test.go`.
### S-005 · The Python proxy fails open to superadmin when AuthGuard is not configured, and the login override is per process · **Medium** ### S-005 · The Python proxy fails open to superadmin when AuthGuard is not configured, and the login override is per process · **Medium** · Fixed
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns `_LOCAL_PROFILE` when `get_client` returns `None` or login is off), `packages/python-backend/src/shared_backend/authproxy.py:349` and `:389` (the configuration check runs only in `get_me` and `get_status`), `packages/python-backend/src/shared_backend/authproxy.py:255` and `:308-311` (process-local override that is never refreshed from the store), `packages/python-backend/src/shared_backend/authproxy.py:565-567` and `:582-583` (set the override). The Go handler has the same override pattern (`backend/auth/proxy.go:759-811`, per review). - **Location:** `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns `_LOCAL_PROFILE` when `get_client` returns `None` or login is off), `packages/python-backend/src/shared_backend/authproxy.py:349` and `:389` (the configuration check runs only in `get_me` and `get_status`), `packages/python-backend/src/shared_backend/authproxy.py:255` and `:308-311` (process-local override that is never refreshed from the store), `packages/python-backend/src/shared_backend/authproxy.py:565-567` and `:582-583` (set the override). The Go handler has the same override pattern (`backend/auth/proxy.go:759-811`, per review).
- **Description:** A missing or unset AuthGuard URL silently makes every guarded route public with a superadmin identity, because the configuration error is enforced on only two routes. Separately, once a process has seen a login-required change, it keeps its own value and never re-reads the store, so other workers or replicas can disagree. - **Description:** A missing or unset AuthGuard URL silently makes every guarded route public with a superadmin identity, because the configuration error is enforced on only two routes. Separately, once a process has seen a login-required change, it keeps its own value and never re-reads the store, so other workers or replicas can disagree.
- **Impact:** A missing environment variable in production silently removes authentication. A worker can stay unauthenticated after login has been re-enabled elsewhere, until it restarts. - **Impact:** A missing environment variable in production silently removes authentication. A worker can stay unauthenticated after login has been re-enabled elsewhere, until it restarts.
- **Recommendation:** Make auth-disabled mode an explicit opt-in flag that must be set, and apply the configuration check inside `require_session`. Remove the process-local override and read the store on each call, with a short-TTL cache if needed. - **Recommendation:** Make auth-disabled mode an explicit opt-in flag that must be set, and apply the configuration check inside `require_session`. Remove the process-local override and read the store on each call, with a short-TTL cache if needed.
- **Status:** Fixed 2026-10-19 — the Python guarded routes now resolve through `_configured_client`, which fails closed with a 500 when AUTHGUARD_URL is unset unless the consumer passes `local_profile_without_authguard=True`, and the process-local login override is gone because the store is read on each call. In Go, `SetLoginRequired` now clears the two-second login cache instead of writing its own value, so a store that discards writes cannot leave a process with a local setting. Behaviour change: Python consumers that run without AuthGuard must pass `local_profile_without_authguard=True`, or their guarded routes return 500. Files: `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`, `backend/auth/proxy.go`, `backend/auth/proxy_test.go`.
### S-006 · The documented core-config push guard fails open when the secret is unset, and the pushed AuthGuard URL is not validated · **Medium** ### S-006 · The documented core-config push guard fails open when the secret is unset, and the pushed AuthGuard URL is not validated · **Medium** · Fixed
- **Location:** `packages/node-backend/README.md:50` (documented handler), `packages/node-backend/src/coreconfig.js:121` (same check, inside a JSDoc example), `packages/node-backend/src/coreconfig.js:67` (URL normalised, with no scheme or host check), `packages/python-backend/README.md:104` and `packages/python-backend/src/shared_backend/coreconfig.py:111` (same comparison in the Python example), `backend/coreconfig/coreconfig.go:182` (fails closed on an empty secret but compares with `!=`; per review), `backend/auth/proxy.go:819` (`r.Header.Get("X-Internal-Auth") != secret`) - **Location:** `packages/node-backend/README.md:50` (documented handler), `packages/node-backend/src/coreconfig.js:121` (same check, inside a JSDoc example), `packages/node-backend/src/coreconfig.js:67` (URL normalised, with no scheme or host check), `packages/python-backend/README.md:104` and `packages/python-backend/src/shared_backend/coreconfig.py:111` (same comparison in the Python example), `backend/coreconfig/coreconfig.go:182` (fails closed on an empty secret but compares with `!=`; per review), `backend/auth/proxy.go:819` (`r.Header.Get("X-Internal-Auth") != secret`)
- **Description:** The documented guard is `req.get('X-Internal-Auth') !== process.env.SECRET` (and the Python equivalent). If `SECRET` is unset and the header is absent, both sides are `undefined`, so the check passes. The examples do not reject an empty secret, and every comparison is non-constant-time. The store accepts any `authGuardUrl` and forwards it to `AuthClient.setBaseUrl`, so an accepted push can point session validation at a server the attacker controls. The Python internal route at `authproxy.py:576-581` does reject an empty secret, which is the correct pattern. - **Description:** The documented guard is `req.get('X-Internal-Auth') !== process.env.SECRET` (and the Python equivalent). If `SECRET` is unset and the header is absent, both sides are `undefined`, so the check passes. The examples do not reject an empty secret, and every comparison is non-constant-time. The store accepts any `authGuardUrl` and forwards it to `AuthClient.setBaseUrl`, so an accepted push can point session validation at a server the attacker controls. The Python internal route at `authproxy.py:576-581` does reject an empty secret, which is the correct pattern.
- **Impact:** A consumer that copies the example gets an authentication bypass through a push that controls the AuthGuard target. The timing difference is small in practice but is avoidable. - **Impact:** A consumer that copies the example gets an authentication bypass through a push that controls the AuthGuard target. The timing difference is small in practice but is avoidable.
- **Recommendation:** Reject an empty configured secret in every handler. Compare with `crypto.timingSafeEqual` or `hmac.compare_digest`. Validate the scheme and host in the store before accepting a URL. Correct the examples. - **Recommendation:** Reject an empty configured secret in every handler. Compare with `crypto.timingSafeEqual` or `hmac.compare_digest`. Validate the scheme and host in the store before accepting a URL. Correct the examples.
- **Status:** Fixed 2026-10-19 — the Go handler, the Node and Python guards and the stores now reject an empty secret and compare in constant time (`subtle.ConstantTimeCompare`, `crypto.timingSafeEqual`, `hmac.compare_digest`). The Node and Python stores accept only http or https URLs with a host, the Go handler checks the same before storing, and the README examples call `internalSecretMatches` and `internal_secret_matches`. Files: `backend/coreconfig/coreconfig.go`, `backend/coreconfig/coreconfig_test.go`, `backend/auth/proxy.go`, `packages/node-backend/src/coreconfig.js`, `packages/node-backend/test/coreconfig.test.js`, `packages/python-backend/src/shared_backend/coreconfig.py`, `packages/python-backend/tests/test_coreconfig.py`, `packages/node-backend/README.md`, `packages/python-backend/README.md`.
### S-007 · Go proxy routes that change state accept any Content-Type and Origin · **Medium** ### S-007 · Go proxy routes that change state accept any Content-Type and Origin · **Medium** · Fixed
- **Location:** `backend/auth/proxy.go:1509` (`decodeProxyJSON` does not check `Content-Type`, `Origin` or `Sec-Fetch-Site`), state-changing handlers including `UpdateAccessSettings` (`proxy.go:781`), `UpdateMe` (`proxy.go:664`), managed-user create, update and delete (around `proxy.go:920`, `:951`, `:994`), `TOTPDisable` (`proxy.go:1239`) and `Logout` (`proxy.go:1144`) - **Location:** `backend/auth/proxy.go:1509` (`decodeProxyJSON` does not check `Content-Type`, `Origin` or `Sec-Fetch-Site`), state-changing handlers including `UpdateAccessSettings` (`proxy.go:781`), `UpdateMe` (`proxy.go:664`), managed-user create, update and delete (around `proxy.go:920`, `:951`, `:994`), `TOTPDisable` (`proxy.go:1239`) and `Logout` (`proxy.go:1144`)
- **Description:** There is no CSRF protection in the proxy. A cross-site form submission with a `text/plain` body is decoded just like a JSON request, so protection rests entirely on the `SameSite` attribute of the session cookie. That attribute is set by AuthGuard and forwarded here. `backend/authclient/client.go:324` notes that the cookie can be domain-scoped (`AUTH_COOKIE_DOMAIN`) for cross-project SSO, which makes sibling subdomains same-site. - **Description:** There is no CSRF protection in the proxy. A cross-site form submission with a `text/plain` body is decoded just like a JSON request, so protection rests entirely on the `SameSite` attribute of the session cookie. That attribute is set by AuthGuard and forwarded here. `backend/authclient/client.go:324` notes that the cookie can be domain-scoped (`AUTH_COOKIE_DOMAIN`) for cross-project SSO, which makes sibling subdomains same-site.
- **Impact:** If a session cookie is domain-scoped and a sibling application is compromised or hostile, it can forge admin actions against this proxy. Needs verification of AuthGuard's cookie attributes. - **Impact:** If a session cookie is domain-scoped and a sibling application is compromised or hostile, it can forge admin actions against this proxy. Needs verification of AuthGuard's cookie attributes.
- **Recommendation:** On non-GET routes, require `Content-Type: application/json` and check `Origin` or `Sec-Fetch-Site` against an allowlist, or require a custom header that cross-site forms cannot set. Confirm AuthGuard's `SameSite` setting. - **Recommendation:** On non-GET routes, require `Content-Type: application/json` and check `Origin` or `Sec-Fetch-Site` against an allowlist, or require a custom header that cross-site forms cannot set. Confirm AuthGuard's `SameSite` setting.
- **Status:** Fixed 2026-10-19 — `decodeProxyJSON` refuses any body that is not `application/json` and any request marked `Sec-Fetch-Site: cross-site`, and the body-less state-changing handlers (logout, TOTP initiate, managed user delete) refuse cross-site requests with a 403. Origin is still not checked, and requests from browsers that omit `Sec-Fetch-Site` are accepted, so SameSite remains a second layer. Behaviour change: clients that send a non-JSON body, or a cross-site request, to these routes are now refused. Files: `backend/auth/proxy.go`, `backend/auth/proxy_test.go`.
### S-008 · Signup and first-run setup are not gated on the login setting, and the oldest user is re-promoted to superadmin on restart · **Medium** ### S-008 · Signup and first-run setup are not gated on the login setting, and the oldest user is re-promoted to superadmin on restart · **Medium** · Fixed
- **Location:** `backend/auth/proxy.go:1014` (`Signup` checks only whether the service is enabled; no login-required check before forwarding), `backend/auth/proxy.go:724` (`AdminNeeded`), `backend/auth/store.go:92-94` (`EnsureSchema` promotes the oldest user when no superadmin exists), `backend/auth/store.go:237` (first account becomes superadmin) - **Location:** `backend/auth/proxy.go:1014` (`Signup` checks only whether the service is enabled; no login-required check before forwarding), `backend/auth/proxy.go:724` (`AdminNeeded`), `backend/auth/store.go:92-94` (`EnsureSchema` promotes the oldest user when no superadmin exists), `backend/auth/store.go:237` (first account becomes superadmin)
- **Description:** When login is not required, `AdminNeeded` reports no setup is needed, but `Signup` does not check the setting. On a fresh AuthGuard the first caller to sign up becomes superadmin, and there is no bootstrap secret. Separately, at each schema initialisation, if no superadmin exists, the oldest user is promoted. Deleting or demoting the superadmin and then restarting elevates whoever is oldest, possibly an ordinary user. - **Description:** When login is not required, `AdminNeeded` reports no setup is needed, but `Signup` does not check the setting. On a fresh AuthGuard the first caller to sign up becomes superadmin, and there is no bootstrap secret. Separately, at each schema initialisation, if no superadmin exists, the oldest user is promoted. Deleting or demoting the superadmin and then restarting elevates whoever is oldest, possibly an ordinary user.
- **Impact:** On a service with login disabled and no accounts, an anonymous visitor could register as superadmin of the shared AuthGuard (needs verification of AuthGuard's behaviour). Restarts can silently escalate privileges. - **Impact:** On a service with login disabled and no accounts, an anonymous visitor could register as superadmin of the shared AuthGuard (needs verification of AuthGuard's behaviour). Restarts can silently escalate privileges.
- **Recommendation:** Reject `Signup` when login is not required, or require a one-time setup token. Run the promotion only when the table is created, and otherwise require an explicit administrator action. - **Recommendation:** Reject `Signup` when login is not required, or require a one-time setup token. Run the promotion only when the table is created, and otherwise require an explicit administrator action.
- **Status:** Fixed 2026-10-19 — `Signup` answers 409 while login is not required, so an anonymous caller cannot become superadmin on a service with login off. The oldest-user promotion in `EnsureSchema` now runs only in the migration that adds the `role` column, so a restart no longer promotes someone when no superadmin exists. Residual: with login required and an empty AuthGuard the first signup still becomes superadmin, as designed; a one-time setup token would be a product decision. Files: `backend/auth/proxy.go`, `backend/auth/store.go`, `backend/auth/proxy_test.go`.
### S-009 · Login and TOTP endpoints have no attempt limiting, and the client's IP address is not forwarded · **Medium** ### S-009 · Login and TOTP endpoints have no attempt limiting, and the client's IP address is not forwarded · **Medium** · Fixed
- **Location:** `backend/auth/proxy.go:1093` (`Login`), `backend/auth/proxy.go:1210` (`TOTPVerify`), `backend/auth/proxy.go:1239` (`TOTPDisable`), `backend/authclient/client.go:426-459` (outbound headers are bearer token, content type and project key only), `packages/python-backend/src/shared_backend/authclient.py` and `packages/node-backend/src/authclient.js` (same pattern; per review) - **Location:** `backend/auth/proxy.go:1093` (`Login`), `backend/auth/proxy.go:1210` (`TOTPVerify`), `backend/auth/proxy.go:1239` (`TOTPDisable`), `backend/authclient/client.go:426-459` (outbound headers are bearer token, content type and project key only), `packages/python-backend/src/shared_backend/authclient.py` and `packages/node-backend/src/authclient.js` (same pattern; per review)
- **Description:** The proxy adds no throttling or lockout to password or six-digit TOTP attempts. The AuthGuard clients do not send the end user's IP address, so any per-IP limit that AuthGuard applies sees the proxy's address for every user. - **Description:** The proxy adds no throttling or lockout to password or six-digit TOTP attempts. The AuthGuard clients do not send the end user's IP address, so any per-IP limit that AuthGuard applies sees the proxy's address for every user.
- **Impact:** Password and TOTP guessing is limited only by AuthGuard, whose behaviour is not in this repository. A per-IP limit at AuthGuard either does nothing or locks out all users together. Needs verification of AuthGuard's limiter. - **Impact:** Password and TOTP guessing is limited only by AuthGuard, whose behaviour is not in this repository. A per-IP limit at AuthGuard either does nothing or locks out all users together. Needs verification of AuthGuard's limiter.
- **Recommendation:** Add a per-identifier and per-client-IP limiter in the proxy. Forward the client IP over a trusted channel using trusted-proxy-aware extraction, and confirm how AuthGuard limits attempts. - **Recommendation:** Add a per-identifier and per-client-IP limiter in the proxy. Forward the client IP over a trusted channel using trusted-proxy-aware extraction, and confirm how AuthGuard limits attempts.
- **Status:** Fixed 2026-10-19 — login has a per-account limit (10 per 15 minutes) and a per-client-address limit (200), and TOTP verify and disable share a per-user limit (5), all held in process memory: `backend/auth/ratelimit.go` for the Go proxy and, new in this pass, `shared_backend/ratelimit.py` and `authproxy.build_auth_router` for the Python router (same numbers, `429` beyond them). The client address honours `X-Forwarded-For` only from peers listed in `TRUSTED_PROXIES` (decision 5): `backend/auth/clientip.go`, and the new `shared_backend/clientip.py` (the router reads the variable, or a `trusted_proxies` argument; an invalid list raises `ValueError` at startup). The verified address is now forwarded to AuthGuard as `X-Forwarded-For` on login, signup/register and TOTP verify/disable: Go `authclient.WithClientIP` (set by `auth.Service`), Python `authclient.forwarded_client_ip` (set by the router), Node an optional `{ clientIp }` on `register`, `login`, `totpVerify`, `totpDisable` and the reset calls. Only IP-address values are sent, never a raw request header. AuthGuard's own limiters (`Central/AuthGuard/internal/httpapi`, read for this pass) key on its `clientIP`, which reads the header only from peers inside AuthGuard's own `TRUSTED_PROXIES`, so the forwarding takes effect once an operator lists the consuming service's address there and is ignored until then. Residual: counters are per replica, so N replicas of one service allow N times the attempts (AuthGuard's central limiter still applies). Behaviour change: Python services now answer 429 on login and TOTP routes after the limits, and `build_auth_router` gains the `trusted_proxies` argument and reads `TRUSTED_PROXIES`. Files: `backend/auth/ratelimit.go`, `backend/auth/proxy.go`, `backend/auth/clientip.go`, `backend/authclient/client.go`, `backend/auth/proxy_handlers_test.go`, `backend/authclient/client_test.go`, `packages/python-backend/src/shared_backend/{authproxy,authclient,clientip,ratelimit}.py`, `packages/python-backend/tests/{test_authproxy,test_authclient,test_attempt_limits}.py`, `packages/node-backend/src/authclient.js`, `packages/node-backend/test/authclient.test.js`.
### S-010 · Self-service profile update changes the password without re-authentication · **Medium** ### S-010 · Self-service profile update changes the password without re-authentication · **Medium** · Open
- **Location:** `backend/auth/proxy.go:664-712` (`UpdateMe` accepts `password` at `:700-709` and forwards it with only the session cookie) - **Location:** `backend/auth/proxy.go:664-712` (`UpdateMe` accepts `password` at `:700-709` and forwards it with only the session cookie)
- **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.
### S-011 · TOTP codes can be replayed within their validity window in every runtime · **Medium** ### 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: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)
- **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.
### S-012 · The Java client parses the authentication decision with unanchored regular expressions · **Medium** ### 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)
- **Description:** The values are extracted from the raw response body with `Matcher.find()`, which returns the first match anywhere in the text, including inside nested objects. The class already depends on Jackson (`packages/java-backend/pom.xml`), so a real parser is available. - **Description:** The values are extracted from the raw response body with `Matcher.find()`, which returns the first match anywhere in the text, including inside nested objects. The class already depends on Jackson (`packages/java-backend/pom.xml`), so a real parser is available.
- **Impact:** A change to AuthGuard's response shape, or a nested field with the same name, could make the client accept a session for the wrong user or role. - **Impact:** A change to AuthGuard's response shape, or a nested field with the same name, could make the client accept a session for the wrong user or role.
- **Recommendation:** Parse the response with Jackson and read top-level fields only. Add tests with nested and reordered fields. - **Recommendation:** Parse the response with Jackson and read top-level fields only. Add tests with nested and reordered fields.
- **Status:** Fixed 2026-10-19 — `AuthClient.validate` parses the AuthGuard response with Jackson and reads only the top-level `valid`, `user_id`, `username` and `role` fields, so nested fields with the same names are ignored, and tests cover nested and reordered fields. Not compiled or run: no JDK or Maven is available here, so this was checked by reading only. Files: `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`.
### S-013 · Password hashing is below the intended settings in two runtimes · **Medium** ### S-013 · Password hashing is below the intended settings in two runtimes · **Medium** · Fixed
- **Location:** `packages/node-backend/src/auth.js:3` and `:56` (100,000 PBKDF2-SHA256 iterations, with an `iterations` option), `packages/node-backend/src/auth.js:61` and `:69-72` (verification always uses the constant, and the stored `salt:hash` format records no parameters), `backend/auth/proxy.go:1344` and `:1417` (`bcrypt.DefaultCost`, which is 10, for platform users) vs `backend/auth/password.go:7` (`BcryptCost = 12`, described as the one policy), `backend/auth/proxy.go:1460` (accepts up to 1024 runes, but bcrypt uses only the first 72 bytes) - **Location:** `packages/node-backend/src/auth.js:3` and `:56` (100,000 PBKDF2-SHA256 iterations, with an `iterations` option), `packages/node-backend/src/auth.js:61` and `:69-72` (verification always uses the constant, and the stored `salt:hash` format records no parameters), `backend/auth/proxy.go:1344` and `:1417` (`bcrypt.DefaultCost`, which is 10, for platform users) vs `backend/auth/password.go:7` (`BcryptCost = 12`, described as the one policy), `backend/auth/proxy.go:1460` (accepts up to 1024 runes, but bcrypt uses only the first 72 bytes)
- **Description:** The Node PBKDF2 count is fixed at 100,000 iterations. OWASP's current guidance for PBKDF2-HMAC-SHA256 is 600,000 (confirm against the current cheat sheet). A caller passing a different `iterations` value produces hashes that can never verify, and because the format stores no parameters the cost cannot be raised without a migration. Go's platform-user path hashes at cost 10 rather than the package's stated cost of 12. Bcrypt ignores bytes beyond 72, so long passwords are silently truncated, which the current validation does not prevent. - **Description:** The Node PBKDF2 count is fixed at 100,000 iterations. OWASP's current guidance for PBKDF2-HMAC-SHA256 is 600,000 (confirm against the current cheat sheet). A caller passing a different `iterations` value produces hashes that can never verify, and because the format stores no parameters the cost cannot be raised without a migration. Go's platform-user path hashes at cost 10 rather than the package's stated cost of 12. Bcrypt ignores bytes beyond 72, so long passwords are silently truncated, which the current validation does not prevent.
- **Impact:** Stored hashes are cheaper to crack than the package intends, and the cost cannot be upgraded. - **Impact:** Stored hashes are cheaper to crack than the package intends, and the cost cannot be upgraded.
- **Recommendation:** Store the algorithm and parameters with each hash and rehash on login. Raise the PBKDF2 count, or move to scrypt or argon2id. Call `HashPassword` everywhere in Go, and reject or pre-hash passwords longer than 72 bytes with a clear message. - **Recommendation:** Store the algorithm and parameters with each hash and rehash on login. Raise the PBKDF2 count, or move to scrypt or argon2id. Call `HashPassword` everywhere in Go, and reject or pre-hash passwords longer than 72 bytes with a clear message.
- **Status:** Fixed 2026-10-19 — every hash now carries a scheme prefix, and verification dispatches on it. Node writes `pbkdf2-sha256$<iterations>$<salt>$<hash>` at 600,000 iterations. Go and Python write `bcrypt$` followed by an unchanged bcrypt string at cost 12 (`BcryptCost`). Legacy Node `salt:hex` hashes (100,000 iterations) and unprefixed bcrypt hashes still verify, and any other format fails closed. Rehash on login: `verifyAndUpgradePasswordAsync` (Node), `verify_and_upgrade_password_async` (Python) and `VerifyAndUpgradePassword` (Go) return a current-scheme hash after a matching password, for the caller to store. Go platform-user writes now use `HashPassword`. Caveats: no login route in this repository checks local hashes (AuthGuard checks logins), so the rewrite happens only in a consumer that calls the helper; Node still cannot verify bcrypt. Behaviour change: Python and Go code from before this change cannot verify the new `bcrypt$` hashes, so services that share a database must move together. The 72-byte limit is enforced in Go (`validateProxyPassword` refuses more than 72 bytes, and bcrypt itself refuses them) and, since this pass, in Python (`MAX_PASSWORD_BYTES`: `hash_password` raises `ValueError` and the router's `_validate_password` answers 400, whatever bcrypt version is installed); Node's PBKDF2 has no such limit. Files: `backend/auth/password.go`, `backend/auth/password_test.go`, `backend/auth/store_test.go`, `backend/auth/proxy.go`, `packages/node-backend/src/auth.js`, `packages/node-backend/src/index.js`, `packages/node-backend/test/auth.test.js`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/src/shared_backend/__init__.py`, `packages/python-backend/tests/test_core.py`, `packages/python-backend/tests/test_store.py`.
### S-014 · Websocket origin verification is disabled when the allowed origin is `*` · **Medium** ### S-014 · Websocket origin verification is disabled when the allowed origin is `*` · **Medium** · Fixed
- **Location:** `backend/syncsocket/syncsocket.go:267-270` (`websocketAcceptOptions` sets `InsecureSkipVerify = true` when `allowedOrigin == "*"`) - **Location:** `backend/syncsocket/syncsocket.go:267-270` (`websocketAcceptOptions` sets `InsecureSkipVerify = true` when `allowedOrigin == "*"`)
- **Description:** In `coder/websocket`, that option disables the Origin check. It is not TLS verification, despite the name. With the wildcard setting, any web page can open a sync socket from a visitor's browser, which combines with S-003 to let cross-site pages act as peers. - **Description:** In `coder/websocket`, that option disables the Origin check. It is not TLS verification, despite the name. With the wildcard setting, any web page can open a sync socket from a visitor's browser, which combines with S-003 to let cross-site pages act as peers.
- **Impact:** A page on any origin can connect to a LAN-hosted sync hub, read session state and send control messages if identity is not enforced. - **Impact:** A page on any origin can connect to a LAN-hosted sync hub, read session state and send control messages if identity is not enforced.
- **Recommendation:** Remove the wildcard escape hatch, or require an explicit origin list. Never map `"*"` to `InsecureSkipVerify`. - **Recommendation:** Remove the wildcard escape hatch, or require an explicit origin list. Never map `"*"` to `InsecureSkipVerify`.
- **Status:** Fixed 2026-10-19 — `websocketAcceptOptions` no longer maps `*` to `InsecureSkipVerify`; origin verification is always on, and `*` adds no extra origin. Behaviour change: a deployment that relied on `CORS_ORIGIN=*` to accept sockets from any page must now list each origin explicitly. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`.
### S-015 · Peer IP addresses and user agents are broadcast to all session members, and X-Forwarded-For is trusted unconditionally · **Medium** ### S-015 · Peer IP addresses and user agents are broadcast to all session members, and X-Forwarded-For is trusted unconditionally · **Medium** · Fixed
- **Location:** `backend/syncsocket/syncsocket.go:301` (first `X-Forwarded-For` value used with no trusted-proxy check), `backend/syncsocket/syncsocket.go:146-150` (IP address and user agent sent to every peer in the session) - **Location:** `backend/syncsocket/syncsocket.go:301` (first `X-Forwarded-For` value used with no trusted-proxy check), `backend/syncsocket/syncsocket.go:146-150` (IP address and user agent sent to every peer in the session)
- **Description:** The client's address is taken from the first `X-Forwarded-For` value whenever that header is present, and it is shared with every session member along with the user agent. - **Description:** The client's address is taken from the first `X-Forwarded-For` value whenever that header is present, and it is shared with every session member along with the user agent.
- **Impact:** Any session member can see the addresses and user agents of other members, and a client can spoof the address that others see. - **Impact:** Any session member can see the addresses and user agents of other members, and a client can spoof the address that others see.
- **Recommendation:** Honour `X-Forwarded-For` only from configured trusted proxies, and remove IP address and user agent from broadcast payloads. - **Recommendation:** Honour `X-Forwarded-For` only from configured trusted proxies, and remove IP address and user agent from broadcast payloads.
- **Status:** Fixed 2026-10-19 — the sync hub no longer reads `X-Forwarded-For`, and it no longer sends a peer's IP address or user agent in the client list. The Go proxy's client address honours `X-Forwarded-For` only when the TCP peer is inside `TRUSTED_PROXIES` (decision 5), and otherwise uses the TCP peer. Behaviour change: clients that displayed the `ipAddress` or `userAgent` of other peers will no longer receive those fields. A service behind a reverse proxy gets per-client login limits only once it sets `TRUSTED_PROXIES`; until then its behaviour is unchanged. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`, `backend/auth/clientip.go`, `backend/auth/clientip_test.go`, `backend/auth/proxy.go`.
### S-016 · Store primitives allow identity confusion and silently disable TOTP · **Medium** ### S-016 · Store primitives allow identity confusion and silently disable TOTP · **Medium** · Fixed
- **Location:** `backend/auth/store.go:261` (`WHERE username = $1 OR lower(email) = lower($1)`, with no ordering), `backend/auth/store.go:72` (username is unique only case-sensitively), `backend/auth/store.go:184` (`SetTOTPSecret` sets `totp_enabled = false`), `backend/auth/store.go:277-285` (`UpdateCredentials` writes whatever `passwordHash` it receives, per review) - **Location:** `backend/auth/store.go:261` (`WHERE username = $1 OR lower(email) = lower($1)`, with no ordering), `backend/auth/store.go:72` (username is unique only case-sensitively), `backend/auth/store.go:184` (`SetTOTPSecret` sets `totp_enabled = false`), `backend/auth/store.go:277-285` (`UpdateCredentials` writes whatever `passwordHash` it receives, per review)
- **Description:** The identifier lookup matches a username against any account's email, so a username can equal another account's email and make the match ambiguous. Usernames are unique only case-sensitively, so `Admin` and `admin` can both exist. `SetTOTPSecret` silently disables an enabled second factor if it is called. Credential updates accept an empty hash. - **Description:** The identifier lookup matches a username against any account's email, so a username can equal another account's email and make the match ambiguous. Usernames are unique only case-sensitively, so `Admin` and `admin` can both exist. `SetTOTPSecret` silently disables an enabled second factor if it is called. Credential updates accept an empty hash.
- **Impact:** Ambiguous logins that can route a sign-in to the wrong account, and silent second-factor removal if a caller makes a mistake. - **Impact:** Ambiguous logins that can route a sign-in to the wrong account, and silent second-factor removal if a caller makes a mistake.
- **Recommendation:** Add a unique index on `lower(username)`. Reject usernames containing `@`. Look up usernames and emails separately with a deterministic order. Refuse `SetTOTPSecret` while TOTP is enabled, and reject empty password hashes. - **Recommendation:** Add a unique index on `lower(username)`. Reject usernames containing `@`. Look up usernames and emails separately with a deterministic order. Refuse `SetTOTPSecret` while TOTP is enabled, and reject empty password hashes.
- **Status:** Fixed 2026-10-19 — `SetTOTPSecret` refuses while TOTP is enabled (`ErrTOTPAlreadyEnabled`), credential writes refuse an empty password hash and a username containing `@`, and identifier lookup tries usernames before emails in a fixed order. New in this pass: usernames are unique ignoring case through an index on `lower(username)` (`auth_users_username_lower_idx`), created by `EnsureSchema` (Go), `AuthStore.ensureSchema` (Node) and `AuthStore.ensure_schema` (Python) only while no pair such as `Admin` and `admin` exists. Choice made without an owner decision: a database that already holds such a pair still starts, gets no index, and logs the clashing names on each start (a warning in Node and Python) until an operator renames or removes one account of each pair; no account is merged or renamed automatically. The Node and Python stores now carry the same guards as Go (empty hash, `@` in a username, no TOTP secret replacement while enabled, username-then-email lookup). Behaviour change: registering a username that differs from an existing one only by case now fails as an existing user; `setTotpSecret`/`set_totp_secret` throw (`AUTH_TOTP_ALREADY_ENABLED`, `TotpAlreadyEnabledError`) while TOTP is enabled; a credential write with an empty hash or an `@` username throws (`AUTH_EMPTY_PASSWORD_HASH`/`AUTH_INVALID_USERNAME`, `EmptyPasswordHashError`/`InvalidUsernameError`). Files: `backend/auth/store.go`, `backend/auth/store_test.go`, `backend/auth/store_integration_test.go`, `packages/node-backend/src/auth.js`, `packages/node-backend/test/authstore.test.js`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/tests/test_store.py`.
### S-017 · Stored paths and caller-supplied names are concatenated into CarrierNode URLs without escaping or validation · **Medium** ### S-017 · Stored paths and caller-supplied names are concatenated into CarrierNode URLs without escaping or validation · **Medium** · Fixed
- **Location:** `backend/mediacore/mediacore.go:187` and `:224` (`"/media/" + urlPath(record.FilePath)` from the database), `backend/mediacore/mediacore.go:992-997` (`urlPath` strips only leading slashes and a `media/` prefix), `backend/carriernodeclient/carriernodeclient.go:144` (path concatenated without escaping), `backend/carriernodeclient/carriernodeclient.go:673-719` (`PushThumbnail`, `DeleteThumbnail`, `PushOutput`, `PushInput`, `PushCopy` use `url.PathEscape` only, which leaves `.` and `..` unchanged), `backend/carriernodeclient/carriernodeclient.go:453-458` (a strict `thumbnailFile` check exists for thumbnails only), `backend/carriernodeclient/carriernodeclient.go:228-246` (`MountPath` escapes segments and rejects `..` correctly) - **Location:** `backend/mediacore/mediacore.go:187` and `:224` (`"/media/" + urlPath(record.FilePath)` from the database), `backend/mediacore/mediacore.go:992-997` (`urlPath` strips only leading slashes and a `media/` prefix), `backend/carriernodeclient/carriernodeclient.go:144` (path concatenated without escaping), `backend/carriernodeclient/carriernodeclient.go:673-719` (`PushThumbnail`, `DeleteThumbnail`, `PushOutput`, `PushInput`, `PushCopy` use `url.PathEscape` only, which leaves `.` and `..` unchanged), `backend/carriernodeclient/carriernodeclient.go:453-458` (a strict `thumbnailFile` check exists for thumbnails only), `backend/carriernodeclient/carriernodeclient.go:228-246` (`MountPath` escapes segments and rejects `..` correctly)
- **Description:** A stored `file_path` containing `?`, `#` or `..` is parsed by CarrierNode as a query, a fragment, or a traversal. `SafeRelative` is applied to IDs but not to stored paths. The push and delete helpers escape `/` but not `.` or `..`, and no name validation runs for them. - **Description:** A stored `file_path` containing `?`, `#` or `..` is parsed by CarrierNode as a query, a fragment, or a traversal. `SafeRelative` is applied to IDs but not to stored paths. The push and delete helpers escape `/` but not `.` or `..`, and no name validation runs for them.
- **Impact:** A malformed stored path or caller-supplied name can address a different upstream resource, or write or delete outside the intended root, depending on CarrierNode's own checks (not in this repository; needs verification). - **Impact:** A malformed stored path or caller-supplied name can address a different upstream resource, or write or delete outside the intended root, depending on CarrierNode's own checks (not in this repository; needs verification).
- **Recommendation:** Apply `SafeRelative` to stored paths, escape each segment as `MountPath` does, and reject query and fragment characters. Validate names in every push and delete helper the way `thumbnailFile` does (reject `.`, `..` and path separators). - **Recommendation:** Apply `SafeRelative` to stored paths, escape each segment as `MountPath` does, and reject query and fragment characters. Validate names in every push and delete helper the way `thumbnailFile` does (reject `.`, `..` and path separators).
- **Status:** Fixed 2026-10-19 — stored media paths go through `upstreamMediaPath`, which applies `SafeRelative`, refuses `?` and `#`, and escapes each segment before the CarrierNode call. The push and delete helpers for thumbnails, outputs, inputs and copies reject `.`, `..` and path separators through `validName`. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/paths_test.go`, `backend/carriernodeclient/carriernodeclient.go`, `backend/carriernodeclient/thumbnails_test.go`.
### S-018 · The role vocabulary is defined three ways, and role assignments are not checked locally · **Low** ### S-018 · The role vocabulary is defined three ways, and role assignments are not checked locally · **Low**
- **Location:** `backend/auth/proxy.go:629-634` (`IsAdmin` treats `moderator` as admin), `backend/auth/roles.go:13-32` (`NormalizeRole`, `CanManageUsers`, `CanAssignRole`; `CanAssignRole` is not called from the handlers), `backend/auth/proxy.go:935-938` and `:965-971` (client-supplied role forwarded to AuthGuard) - **Location:** `backend/auth/proxy.go:629-634` (`IsAdmin` treats `moderator` as admin), `backend/auth/roles.go:13-32` (`NormalizeRole`, `CanManageUsers`, `CanAssignRole`; `CanAssignRole` is not called from the handlers), `backend/auth/proxy.go:935-938` and `:965-971` (client-supplied role forwarded to AuthGuard)
+3 -3
View File
@@ -5,12 +5,12 @@ services, not application-specific SQL or HTTP handlers.
- `config` — environment string, required value, boolean, integer, and duration helpers. - `config` — environment string, required value, boolean, integer, and duration helpers.
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification. - `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
- `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence. - `auth` — versioned bcrypt password hashes (`HashPassword` writes a `bcrypt$` prefix; `VerifyAndUpgradePassword` rewrites older hashes on login), trusted-proxy client addresses (`ParseTrustedProxies` reads `TRUSTED_PROXIES`, a comma-separated CIDR list; `X-Forwarded-For` is honoured only from those peers), secure token generation/hashing, account/session schema (usernames are unique ignoring case once no clashing pair exists), account/session persistence, and attempt limits on the login and TOTP routes (per account and per client address, held in process memory).
- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database. - `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database. `WithClientIP(ctx, ip)` makes the credential calls send the end user's address as `X-Forwarded-For`; AuthServer reads it only from peers in its own `TRUSTED_PROXIES`.
- `migrate` — embedded filesystem adapter for Goose migrations. - `migrate` — embedded filesystem adapter for Goose migrations.
- `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package. - `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package.
Run `go test ./...` and `go vet ./...` from this directory. The module path is Run `go test ./...` and `go vet ./...` from this directory. Tests that need PostgreSQL skip themselves unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` (platform users, mediacore, migrate) names a scratch database; use `go test -p 1 ./...` when both are set. The module path is
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is `repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
hosted under a different repository path. hosted under a different repository path.
+115
View File
@@ -0,0 +1,115 @@
package auth
import (
"context"
"fmt"
"net"
"net/http"
"strings"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// ParseTrustedProxies parses the TRUSTED_PROXIES setting: a comma-separated
// list of CIDR ranges or bare IP addresses. Only a request whose TCP peer is
// inside one of these ranges may have its X-Forwarded-For header honoured. An
// empty value trusts no proxy.
func ParseTrustedProxies(value string) ([]*net.IPNet, error) {
var networks []*net.IPNet
for _, entry := range strings.Split(value, ",") {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
if !strings.Contains(entry, "/") {
ip := net.ParseIP(entry)
if ip == nil {
return nil, fmt.Errorf("trusted proxy %q is neither an IP address nor a CIDR range", entry)
}
bits := 8 * net.IPv6len
if ip.To4() != nil {
bits = 8 * net.IPv4len
}
entry = fmt.Sprintf("%s/%d", ip.String(), bits)
}
_, network, err := net.ParseCIDR(entry)
if err != nil {
return nil, fmt.Errorf("trusted proxy %q is not a valid CIDR range: %w", entry, err)
}
networks = append(networks, network)
}
return networks, nil
}
// clientAddress returns the address a login attempt is counted against. The
// TCP peer is used unless it is a trusted proxy. For a trusted peer,
// X-Forwarded-For is read from the right and trusted hops are skipped, so the
// first untrusted address is the one the proxy chain actually saw. A malformed
// entry makes the peer address the answer, so a bad header can never choose the
// key.
func (s *Service) clientAddress(r *http.Request) string {
peer := peerHost(r)
if !s.isTrustedProxy(peer) {
return peer
}
hops := forwardedHops(r.Header.Values("X-Forwarded-For"))
if len(hops) == 0 {
return peer
}
for i := len(hops) - 1; i >= 0; i-- {
ip := net.ParseIP(hops[i])
if ip == nil {
return peer
}
if !s.isTrustedProxyIP(ip) {
return ip.String()
}
}
// Every hop is a trusted proxy, so the left-most one is closest to the client.
return net.ParseIP(hops[0]).String()
}
// withClientIP returns the request context carrying clientAddress, so the
// credential calls to AuthGuard report the end user's address (as
// X-Forwarded-For) instead of this service's. AuthGuard honours that header
// only for peers in its own TRUSTED_PROXIES list.
func (s *Service) withClientIP(r *http.Request) context.Context {
return authclient.WithClientIP(r.Context(), s.clientAddress(r))
}
func (s *Service) isTrustedProxy(host string) bool {
ip := net.ParseIP(host)
return ip != nil && s.isTrustedProxyIP(ip)
}
func (s *Service) isTrustedProxyIP(ip net.IP) bool {
for _, network := range s.trustedProxies {
if network.Contains(ip) {
return true
}
}
return false
}
// peerHost is the host part of the address the TCP connection came from.
func peerHost(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
// forwardedHops flattens every X-Forwarded-For header line into its entries,
// left to right.
func forwardedHops(values []string) []string {
var hops []string
for _, value := range values {
for _, part := range strings.Split(value, ",") {
if part = strings.TrimSpace(part); part != "" {
hops = append(hops, part)
}
}
}
return hops
}
+91
View File
@@ -0,0 +1,91 @@
package auth
import (
"net"
"net/http"
"net/http/httptest"
"testing"
)
func mustTrustedProxies(t *testing.T, value string) []*net.IPNet {
t.Helper()
networks, err := ParseTrustedProxies(value)
if err != nil {
t.Fatalf("ParseTrustedProxies(%q) error = %v", value, err)
}
return networks
}
func TestParseTrustedProxiesAcceptsCIDRsAndBareAddresses(t *testing.T) {
networks := mustTrustedProxies(t, " 10.0.0.0/8, 192.168.1.5 , ::1 ,")
if len(networks) != 3 {
t.Fatalf("networks = %d, want 3", len(networks))
}
for _, ip := range []string{"10.20.30.40", "192.168.1.5", "::1"} {
if !(&Service{trustedProxies: networks}).isTrustedProxy(ip) {
t.Errorf("%s not trusted", ip)
}
}
if (&Service{trustedProxies: networks}).isTrustedProxy("192.168.1.6") {
t.Error("192.168.1.6 trusted, but only 192.168.1.5 was listed")
}
}
func TestParseTrustedProxiesRejectsInvalidEntries(t *testing.T) {
for _, value := range []string{"10.0.0.0/33", "proxy.internal", "10.0.0.1/8/8"} {
if _, err := ParseTrustedProxies(value); err == nil {
t.Errorf("ParseTrustedProxies(%q) accepted an invalid entry", value)
}
}
networks, err := ParseTrustedProxies(" ")
if err != nil || len(networks) != 0 {
t.Fatalf("empty setting = %v, %v; want no proxies and no error", networks, err)
}
}
func clientAddressFor(s *Service, remote string, forwarded ...string) string {
r := httptest.NewRequest(http.MethodPost, "/auth/login", nil)
r.RemoteAddr = remote
for _, value := range forwarded {
r.Header.Add("X-Forwarded-For", value)
}
return s.clientAddress(r)
}
func TestClientAddressIgnoresForwardedForWithoutTrustedProxies(t *testing.T) {
s := &Service{}
if got := clientAddressFor(s, "203.0.113.7:4444", "198.51.100.1"); got != "203.0.113.7" {
t.Fatalf("clientAddress = %q, want the TCP peer 203.0.113.7", got)
}
}
func TestClientAddressIgnoresForwardedForFromAnUnknownPeer(t *testing.T) {
s := &Service{trustedProxies: mustTrustedProxies(t, "10.0.0.0/8")}
if got := clientAddressFor(s, "203.0.113.7:4444", "198.51.100.1"); got != "203.0.113.7" {
t.Fatalf("clientAddress = %q, want the TCP peer 203.0.113.7", got)
}
}
func TestClientAddressHonoursForwardedForFromATrustedPeer(t *testing.T) {
s := &Service{trustedProxies: mustTrustedProxies(t, "10.0.0.0/8, 172.16.0.0/12")}
tests := []struct {
name string
forwarded []string
want string
}{
{"single client", []string{"198.51.100.9"}, "198.51.100.9"},
{"client behind a second trusted hop", []string{"198.51.100.9, 172.16.4.4"}, "198.51.100.9"},
{"spoofed left-most entry is skipped", []string{"6.6.6.6, 198.51.100.9, 172.16.4.4"}, "198.51.100.9"},
{"entries across header lines", []string{"6.6.6.6", "198.51.100.9"}, "198.51.100.9"},
{"malformed entry falls back to the peer", []string{"198.51.100.9, not-an-ip"}, "10.0.0.2"},
{"no header falls back to the peer", nil, "10.0.0.2"},
{"every hop trusted uses the left-most", []string{"10.1.1.1, 172.16.4.4"}, "10.1.1.1"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := clientAddressFor(s, "10.0.0.2:1000", tt.forwarded...); got != tt.want {
t.Fatalf("clientAddress = %q, want %q", got, tt.want)
}
})
}
}
+145
View File
@@ -0,0 +1,145 @@
package auth
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
)
// contractFile holds the fixtures the Go, Node and Python auth helpers 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 authContract struct {
Password struct {
Plaintext string `json:"plaintext"`
WrongPassword string `json:"wrongPassword"`
Hashes []struct {
Name string `json:"name"`
Hash string `json:"hash"`
Verifies map[string]bool `json:"verifies"`
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
} `json:"hashes"`
TooLongToHash struct {
Bytes int `json:"bytes"`
Accepted map[string]bool `json:"accepted"`
} `json:"tooLongToHash"`
} `json:"password"`
TOTP struct {
Secret string `json:"secret"`
Cases []struct {
Name string `json:"name"`
Unix int64 `json:"unix"`
Code string `json:"code"`
Secret *string `json:"secret"`
Valid bool `json:"valid"`
} `json:"cases"`
} `json:"totp"`
ClientAddress struct {
InvalidTrustedProxyLists []string `json:"invalidTrustedProxyLists"`
Cases []struct {
Name string `json:"name"`
Trusted string `json:"trusted"`
Peer string `json:"peer"`
Forwarded []string `json:"forwarded"`
Want string `json:"want"`
} `json:"cases"`
} `json:"clientAddress"`
}
func loadContract(t *testing.T) authContract {
t.Helper()
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 authContract
if err := json.Unmarshal(data, &contract); err != nil {
t.Fatalf("decode %s: %v", contractFile, err)
}
return contract
}
func TestContractPasswordHashes(t *testing.T) {
contract := loadContract(t)
for _, entry := range contract.Password.Hashes {
t.Run(entry.Name, func(t *testing.T) {
if got := VerifyPassword(entry.Hash, contract.Password.Plaintext); got != entry.Verifies["go"] {
t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"])
}
if VerifyPassword(entry.Hash, contract.Password.WrongPassword) {
t.Error("VerifyPassword accepted the wrong password")
}
if want, ok := entry.NeedsUpgrade["go"]; ok {
if got := PasswordHashNeedsUpgrade(entry.Hash); got != want {
t.Errorf("PasswordHashNeedsUpgrade = %v, want %v", got, want)
}
valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, contract.Password.Plaintext)
if err != nil || !valid || (upgraded != "") != 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)) {
t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded)
}
}
})
}
}
func TestContractPasswordLength(t *testing.T) {
contract := loadContract(t)
_, err := HashPassword(strings.Repeat("a", contract.Password.TooLongToHash.Bytes))
if accepted := err == nil; accepted != contract.Password.TooLongToHash.Accepted["go"] {
t.Fatalf("HashPassword of %d bytes accepted = %v, want %v (error %v)", contract.Password.TooLongToHash.Bytes, accepted, contract.Password.TooLongToHash.Accepted["go"], err)
}
}
func TestContractTOTP(t *testing.T) {
contract := loadContract(t)
for _, entry := range contract.TOTP.Cases {
t.Run(entry.Name, func(t *testing.T) {
secret := contract.TOTP.Secret
if entry.Secret != nil {
secret = *entry.Secret
}
if got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0)); got != entry.Valid {
t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid)
}
})
}
}
func TestContractClientAddress(t *testing.T) {
contract := loadContract(t)
for _, entry := range contract.ClientAddress.Cases {
t.Run(entry.Name, func(t *testing.T) {
networks, err := ParseTrustedProxies(entry.Trusted)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "/auth/login", nil)
request.RemoteAddr = entry.Peer + ":4000"
if strings.Contains(entry.Peer, ":") {
request.RemoteAddr = "[" + entry.Peer + "]:4000"
}
for _, line := range entry.Forwarded {
request.Header.Add("X-Forwarded-For", line)
}
if got := (&Service{trustedProxies: networks}).clientAddress(request); got != entry.Want {
t.Errorf("clientAddress = %q, want %q", got, entry.Want)
}
})
}
for _, list := range contract.ClientAddress.InvalidTrustedProxyLists {
if _, err := ParseTrustedProxies(list); err == nil {
t.Errorf("ParseTrustedProxies(%q) accepted an invalid list", list)
}
}
}
+65 -6
View File
@@ -1,21 +1,80 @@
package auth package auth
import "golang.org/x/crypto/bcrypt" import (
"strings"
"golang.org/x/crypto/bcrypt"
)
// 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
// storage policy. Existing hashes remain valid when this value is raised. // storage policy. Hashes stored at a lower cost are rewritten on the next
// successful login (see VerifyAndUpgradePassword).
const BcryptCost = 12 const BcryptCost = 12
// HashPassword returns a bcrypt password hash suitable for storage. // bcryptScheme prefixes every hash HashPassword writes, so verification picks
// the algorithm from the stored value. The bcrypt string follows unchanged, so
// a stored value reads "bcrypt$$2a$12$..." (the bcrypt string itself starts
// with "$"). Unprefixed bcrypt hashes from before the prefix still verify and
// are upgraded on login.
const bcryptScheme = "bcrypt$"
// HashPassword returns a versioned password hash suitable for storage.
func HashPassword(password string) (string, error) { func HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost) hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
if err != nil { if err != nil {
return "", err return "", err
} }
return string(hash), nil return bcryptScheme + string(hash), nil
} }
// VerifyPassword checks a plaintext password against a stored bcrypt hash. // VerifyPassword checks a plaintext password against a stored hash. It accepts
// hashes from HashPassword and unprefixed bcrypt hashes; any other format
// fails closed.
func VerifyPassword(hash, password string) bool { func VerifyPassword(hash, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil bcryptHash, ok := bcryptHashOf(hash)
if !ok {
return false
}
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(password)) == nil
}
// PasswordHashNeedsUpgrade reports whether a stored hash is not in the current
// scheme: an unprefixed legacy hash, or a bcrypt cost below BcryptCost.
func PasswordHashNeedsUpgrade(hash string) bool {
bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme)
if !prefixed {
return true
}
cost, err := bcrypt.Cost([]byte(bcryptHash))
return err != nil || cost < BcryptCost
}
// VerifyAndUpgradePassword checks password against a stored hash. When it
// matches a hash that is not in the current scheme, it returns a replacement
// from HashPassword for the caller to store; upgraded is empty when no rewrite
// is needed or the password does not match. A non-nil error with valid set
// means the login succeeded but the replacement could not be made.
func VerifyAndUpgradePassword(hash, password string) (valid bool, upgraded string, err error) {
if !VerifyPassword(hash, password) {
return false, "", nil
}
if !PasswordHashNeedsUpgrade(hash) {
return true, "", nil
}
upgraded, err = HashPassword(password)
if err != nil {
return true, "", err
}
return true, upgraded, nil
}
// bcryptHashOf returns the bcrypt string inside a stored hash.
func bcryptHashOf(stored string) (string, bool) {
if rest, prefixed := strings.CutPrefix(stored, bcryptScheme); prefixed {
return rest, true
}
if strings.HasPrefix(stored, "$2a$") || strings.HasPrefix(stored, "$2b$") || strings.HasPrefix(stored, "$2y$") {
return stored, true
}
return "", false
} }
+106
View File
@@ -0,0 +1,106 @@
package auth
import (
"strings"
"testing"
"golang.org/x/crypto/bcrypt"
)
const testPassword = "correct horse battery staple"
func TestHashPasswordWritesTheSchemePrefix(t *testing.T) {
hash, err := HashPassword(testPassword)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(hash, "bcrypt$$2") {
t.Fatalf("hash = %q, want the bcrypt$ scheme prefix before a bcrypt string", hash)
}
if PasswordHashNeedsUpgrade(hash) {
t.Fatal("a fresh hash in the current scheme needs no upgrade")
}
}
func TestVerifyPasswordAcceptsUnprefixedLegacyBcrypt(t *testing.T) {
legacy, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
if err != nil {
t.Fatal(err)
}
if !VerifyPassword(string(legacy), testPassword) {
t.Fatal("legacy unprefixed bcrypt hash no longer verifies")
}
if VerifyPassword(string(legacy), "wrong password") {
t.Fatal("legacy unprefixed bcrypt hash accepted the wrong password")
}
if !PasswordHashNeedsUpgrade(string(legacy)) {
t.Fatal("unprefixed hash should be marked for upgrade")
}
}
func TestVerifyPasswordFailsClosedOnUnknownFormats(t *testing.T) {
for _, stored := range []string{
"",
"salt:0123abcd",
"pbkdf2-sha256$600000$00$00",
"argon2id$v=19$whatever",
"bcrypt$",
"bcrypt$not-a-bcrypt-string",
} {
if VerifyPassword(stored, testPassword) {
t.Errorf("VerifyPassword accepted unknown format %q", stored)
}
}
}
func TestVerifyAndUpgradeRewritesLegacyHashesOnSuccess(t *testing.T) {
legacy, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
if err != nil {
t.Fatal(err)
}
valid, upgraded, err := VerifyAndUpgradePassword(string(legacy), testPassword)
if err != nil || !valid {
t.Fatalf("VerifyAndUpgradePassword() = %v, %v; want valid", valid, err)
}
if !strings.HasPrefix(upgraded, bcryptScheme) {
t.Fatalf("upgraded hash = %q, want the current scheme", upgraded)
}
if !VerifyPassword(upgraded, testPassword) {
t.Fatal("upgraded hash does not verify the password")
}
}
func TestVerifyAndUpgradeRewritesLowCostHashes(t *testing.T) {
lowCost, err := bcrypt.GenerateFromPassword([]byte(testPassword), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
stored := bcryptScheme + string(lowCost)
if !PasswordHashNeedsUpgrade(stored) {
t.Fatal("a prefixed hash below BcryptCost should be marked for upgrade")
}
valid, upgraded, err := VerifyAndUpgradePassword(stored, testPassword)
if err != nil || !valid || upgraded == "" {
t.Fatalf("VerifyAndUpgradePassword() = %v, %q, %v; want a rewrite", valid, upgraded, err)
}
}
func TestVerifyAndUpgradeLeavesCurrentAndFailedChecksAlone(t *testing.T) {
current, err := HashPassword(testPassword)
if err != nil {
t.Fatal(err)
}
valid, upgraded, err := VerifyAndUpgradePassword(current, testPassword)
if err != nil || !valid || upgraded != "" {
t.Fatalf("current hash: VerifyAndUpgradePassword() = %v, %q, %v; want valid with no rewrite", valid, upgraded, err)
}
legacy, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
if err != nil {
t.Fatal(err)
}
valid, upgraded, err = VerifyAndUpgradePassword(string(legacy), "wrong password")
if err != nil || valid || upgraded != "" {
t.Fatalf("wrong password: VerifyAndUpgradePassword() = %v, %q, %v; want a plain refusal", valid, upgraded, err)
}
}
@@ -0,0 +1,175 @@
package auth
import (
"context"
"net/url"
"os"
"strings"
"testing"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
)
// platformUsersSchema holds the test's own `users` table, so it never meets the fuller table that
// mediacore's migration creates in the same database.
const platformUsersSchema = "platform_users_test"
// withSearchPath returns databaseURL with its search_path set to schema.
func withSearchPath(t *testing.T, databaseURL, schema string) string {
t.Helper()
parsed, err := url.Parse(databaseURL)
if err != nil {
t.Fatalf("parse database URL: %v", err)
}
query := parsed.Query()
query.Set("search_path", schema)
parsed.RawQuery = query.Encode()
return parsed.String()
}
// TestPlatformUserSQL runs the moderatable platform-user methods (CreateUser, ListUsers,
// UpdateUser, SetPassword, DeleteUser) against a real database. The `users` table normally comes
// from mediacore's migration, which this package cannot import, so the test creates the columns it
// needs in a schema of its own. It is skipped unless SHARED_TEST_DATABASE_URL points at a scratch
// database, for example:
//
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./auth/ -run TestPlatformUserSQL
func TestPlatformUserSQL(t *testing.T) {
databaseURL := os.Getenv("SHARED_TEST_DATABASE_URL")
if databaseURL == "" {
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres platform-user test")
}
ctx := context.Background()
admin, err := postgres.Open(ctx, postgres.DefaultConfig(databaseURL))
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(admin.Close)
if _, err := admin.Exec(ctx, `DROP SCHEMA IF EXISTS `+platformUsersSchema+` CASCADE; CREATE SCHEMA `+platformUsersSchema); err != nil {
t.Fatalf("create schema: %v", err)
}
t.Cleanup(func() {
_, _ = admin.Exec(context.Background(), `DROP SCHEMA IF EXISTS `+platformUsersSchema+` CASCADE`)
})
pool, err := postgres.Open(ctx, postgres.DefaultConfig(withSearchPath(t, databaseURL, platformUsersSchema)))
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(pool.Close)
if _, err := pool.Exec(ctx, `
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
username TEXT,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
disabled BOOLEAN NOT NULL DEFAULT FALSE,
last_login_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`); err != nil {
t.Fatalf("create users table: %v", err)
}
service := New(pool, "session", false, "", "testproject")
if _, err := service.CreateUser(ctx, "not-an-email", "x", "password123", "user"); err == nil {
t.Fatal("CreateUser accepted an invalid email")
}
if _, err := service.CreateUser(ctx, "platform-test-bad@example.com", "x@y", "password123", "user"); err == nil {
t.Fatal("CreateUser accepted a username containing @")
}
if _, err := service.CreateUser(ctx, "platform-test-bad@example.com", "x", strings.Repeat("p", 73), "user"); err == nil {
t.Fatal("CreateUser accepted a password longer than 72 bytes")
}
alice, err := service.CreateUser(ctx, " Platform-Test-Alice@Example.com ", "alice-platform", "password123", "MODERATOR")
if err != nil {
t.Fatalf("CreateUser(alice) error = %v", err)
}
if alice.Email != "platform-test-alice@example.com" || alice.Username != "alice-platform" || alice.Role != "moderator" {
t.Fatalf("created user = %+v, want a lower-cased email and the normalized moderator role", alice)
}
bob, err := service.CreateUser(ctx, "platform-test-bob@example.com", "bob-platform", "password123", "superuser")
if err != nil {
t.Fatalf("CreateUser(bob) error = %v", err)
}
if bob.Role != "user" {
t.Fatalf("an unknown role was stored as %q, want it reduced to user", bob.Role)
}
if _, err := service.CreateUser(ctx, "platform-test-alice@example.com", "other", "password123", "user"); err == nil {
t.Fatal("CreateUser accepted a duplicate email")
}
var storedHash string
if err := pool.QueryRow(ctx, `SELECT password_hash FROM users WHERE id=$1`, alice.ID).Scan(&storedHash); err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(storedHash, bcryptScheme) || !VerifyPassword(storedHash, "password123") {
t.Fatalf("stored hash %q is not a verifiable versioned hash", storedHash)
}
listed, total, err := service.ListUsers(ctx, "platform-test-", 1, 0)
if err != nil || total != 2 || len(listed) != 1 {
t.Fatalf("ListUsers page 1 = %d rows, total %d, %v; want 1 row of 2", len(listed), total, err)
}
if listed[0]["id"] != bob.ID {
t.Fatalf("first row = %v, want the newest user (ordered by id descending)", listed[0]["id"])
}
if page, _, _ := service.ListUsers(ctx, "platform-test-", 1, 1); len(page) != 1 || page[0]["id"] != alice.ID {
t.Fatalf("second page = %v, want alice", page)
}
if found, total, _ := service.ListUsers(ctx, "ALICE-platform", 50, 0); total != 1 || len(found) != 1 || found[0]["email"] != "platform-test-alice@example.com" {
t.Fatalf("search by username = %v (total %d), want alice, matched ignoring case", found, total)
}
if found, total, _ := service.ListUsers(ctx, "no-such-person-anywhere", 50, 0); total != 0 || len(found) != 0 {
t.Fatalf("search with no match = %v (total %d)", found, total)
}
disabled := true
if err := service.UpdateUser(ctx, alice.ID, "", "alice-renamed", "", &disabled); err != nil {
t.Fatalf("UpdateUser error = %v", err)
}
account, err := service.managedAccount(ctx, alice.ID)
if err != nil || account == nil {
t.Fatalf("managedAccount = %v, %v", account, err)
}
if account.Username != "alice-renamed" || account.Email != "platform-test-alice@example.com" || account.Role != "moderator" || !account.Disabled {
t.Fatalf("after a partial update = %+v, want only the username and disabled flag changed", account)
}
if err := service.UpdateUser(ctx, alice.ID, "", "", " ADMIN ", nil); err != nil {
t.Fatal(err)
}
if account, _ := service.managedAccount(ctx, alice.ID); account.Role != "admin" || !account.Disabled {
t.Fatalf("after a role-only update = %+v, want the admin role and the disabled flag kept", account)
}
if err := service.UpdateUser(ctx, alice.ID, "", "", "wizard", nil); err != nil {
t.Fatal(err)
}
if account, _ := service.managedAccount(ctx, alice.ID); account.Role != "user" {
t.Fatalf("an unknown role was stored as %q, want it reduced to user", account.Role)
}
if missing, err := service.managedAccount(ctx, -1); err != nil || missing != nil {
t.Fatalf("managedAccount of a missing id = %v, %v; want nil, nil", missing, err)
}
if err := service.SetPassword(ctx, bob.ID, "short"); err == nil {
t.Fatal("SetPassword accepted a short password")
}
if err := service.SetPassword(ctx, bob.ID, "a-new-password-1"); err != nil {
t.Fatalf("SetPassword error = %v", err)
}
if err := pool.QueryRow(ctx, `SELECT password_hash FROM users WHERE id=$1`, bob.ID).Scan(&storedHash); err != nil {
t.Fatal(err)
}
if !VerifyPassword(storedHash, "a-new-password-1") || VerifyPassword(storedHash, "password123") {
t.Fatal("SetPassword did not replace the stored hash")
}
if err := service.DeleteUser(ctx, alice.ID); err != nil {
t.Fatal(err)
}
if gone, _ := service.managedAccount(ctx, alice.ID); gone != nil {
t.Fatal("DeleteUser left the account in place")
}
}
+155 -52
View File
@@ -165,9 +165,12 @@ package auth
import ( import (
"context" "context"
"crypto/subtle"
"encoding/json" "encoding/json"
"errors" "errors"
"io" "io"
"mime"
"net"
"net/http" "net/http"
"os" "os"
"strconv" "strconv"
@@ -178,7 +181,6 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
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"
) )
@@ -222,6 +224,11 @@ var (
// 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.") errSecretNotSet = errors.New("SECRET environment variable is not set.")
errTooManyAttempts = errors.New("Too many attempts. Try again later.")
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")
errCrossSiteRequest = errors.New("cross-site request refused")
errJSONContentType = errors.New("request body must be application/json")
errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.") errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.")
) )
@@ -230,6 +237,8 @@ const (
setupClaimedSettingKey = "setup_claimed" setupClaimedSettingKey = "setup_claimed"
proxyMinPasswordLength = 8 proxyMinPasswordLength = 8
// maxBcryptPasswordBytes is the longest password bcrypt hashes in full.
maxBcryptPasswordBytes = 72
proxyMaxUsernameLength = 64 proxyMaxUsernameLength = 64
proxyMaxEmailLength = 254 proxyMaxEmailLength = 254
) )
@@ -277,12 +286,17 @@ type Service struct {
// real base URL. // real base URL.
authGuard *authclient.Client authGuard *authclient.Client
configurationError error configurationError error
// loginRequiredOverride is populated by the internal ProjectConfigurator loginCacheMu sync.Mutex
// endpoint. Some legacy consumers intentionally use a no-op ProxyStore for loginCacheValue bool
// this setting because they historically had no local toggle; the live loginCacheSet bool
// override lets those services still honor the central setting immediately. loginCacheExpires time.Time
loginRequiredMu sync.RWMutex // Attempt counters for the credential endpoints; see ratelimit.go.
loginRequiredOverride *bool loginAccountAttempts *attemptLimiter
loginClientAttempts *attemptLimiter
totpAttempts *attemptLimiter
// trustedProxies are the peers whose X-Forwarded-For header is honoured;
// see clientAddress in clientip.go.
trustedProxies []*net.IPNet
} }
// ServiceOption configures optional New/NewWithStore construction behavior. // ServiceOption configures optional New/NewWithStore construction behavior.
@@ -291,8 +305,9 @@ type Service struct {
type ServiceOption func(*serviceOptions) type ServiceOption func(*serviceOptions)
type serviceOptions struct { type serviceOptions struct {
disabled bool disabled bool
requireSecret bool requireSecret bool
trustedProxies []*net.IPNet
} }
// Disabled explicitly builds a Service in auth-disabled mode (see the // Disabled explicitly builds a Service in auth-disabled mode (see the
@@ -314,6 +329,14 @@ func RequireSecret() ServiceOption {
return func(o *serviceOptions) { o.requireSecret = true } return func(o *serviceOptions) { o.requireSecret = true }
} }
// 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
// TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer
// is always the client address.
func WithTrustedProxies(networks []*net.IPNet) ServiceOption {
return func(o *serviceOptions) { o.trustedProxies = networks }
}
// New constructs a Service backed by the media family's shared `settings` // New constructs a Service backed by the media family's shared `settings`
// table (pgSettingsStore) for the login-required toggle and setup-claim // table (pgSettingsStore) for the login-required toggle and setup-claim
// flag, and by db directly for the unrelated "moderatable platform users" // flag, and by db directly for the unrelated "moderatable platform users"
@@ -359,7 +382,17 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
if options.requireSecret && !options.disabled && strings.TrimSpace(os.Getenv("SECRET")) == "" { if options.requireSecret && !options.disabled && strings.TrimSpace(os.Getenv("SECRET")) == "" {
configurationError = errSecretNotSet configurationError = errSecretNotSet
} }
return &Service{store: store, cookieName: cookieName, secureCookies: secureCookies, authGuard: client, configurationError: configurationError} return &Service{
store: store,
cookieName: cookieName,
secureCookies: secureCookies,
authGuard: client,
configurationError: configurationError,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
trustedProxies: options.trustedProxies,
}
} }
// pgSettingsStore is the default ProxyStore New builds over the media // pgSettingsStore is the default ProxyStore New builds over the media
@@ -562,16 +595,8 @@ func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
return return
} }
// CurrentUser returns no user only when login is required (it returns the
loginRequired, err := s.LoginRequired(r.Context()) // synthetic admin for every other case), so no second settings read is needed.
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
next.ServeHTTP(w, r)
return
}
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
})) }))
} }
@@ -595,15 +620,7 @@ func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler {
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context()) user := UserFromContext(r.Context())
if user == nil { if user == nil {
loginRequired, err := s.LoginRequired(r.Context()) // As in RequireIfLoginRequired, a nil user means login is required.
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
next.ServeHTTP(w, r)
return
}
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return return
} }
@@ -756,17 +773,37 @@ func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired}) writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired})
} }
// LoginRequired caches the store's value briefly to avoid a database read for
// every authenticated route. Updates through this Service clear the cache
// immediately; changes made by another replica become visible within two seconds.
func (s *Service) LoginRequired(ctx context.Context) (bool, error) { func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
s.loginRequiredMu.RLock()
override := s.loginRequiredOverride
s.loginRequiredMu.RUnlock()
if override != nil {
return *override, nil
}
if s.store == nil { if s.store == nil {
return true, nil return true, nil
} }
return s.store.LoginRequired(ctx) now := time.Now()
s.loginCacheMu.Lock()
if s.loginCacheSet && now.Before(s.loginCacheExpires) {
value := s.loginCacheValue
s.loginCacheMu.Unlock()
return value, nil
}
s.loginCacheMu.Unlock()
value, err := s.store.LoginRequired(ctx)
if err != nil {
return false, err
}
s.loginCacheMu.Lock()
if s.loginCacheSet && time.Now().Before(s.loginCacheExpires) {
cached := s.loginCacheValue
s.loginCacheMu.Unlock()
return cached, nil
}
s.loginCacheValue = value
s.loginCacheSet = true
s.loginCacheExpires = time.Now().Add(2 * time.Second)
s.loginCacheMu.Unlock()
return value, nil
} }
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) { func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) {
@@ -799,14 +836,17 @@ func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) {
// central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an // central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an
// admin session of its own. // admin session of its own.
func (s *Service) SetLoginRequired(ctx context.Context, required bool) error { func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
if s.store != nil { if s.store == nil {
if err := s.store.SetLoginRequired(ctx, required); err != nil { return errNoLoginRequiredStore
return err
}
} }
s.loginRequiredMu.Lock() if err := s.store.SetLoginRequired(ctx, required); err != nil {
s.loginRequiredOverride = &required return err
s.loginRequiredMu.Unlock() }
// Drop the cached value rather than setting it, so the next read comes from the store and a
// store that discards writes cannot leave this process with its own login setting.
s.loginCacheMu.Lock()
s.loginCacheSet = false
s.loginCacheMu.Unlock()
return nil return nil
} }
@@ -816,7 +856,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) == "" || r.Header.Get("X-Internal-Auth") != secret { if strings.TrimSpace(secret) == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 {
writeProxyError(w, http.StatusUnauthorized, "internal service authentication required") writeProxyError(w, http.StatusUnauthorized, "internal service authentication required")
return return
} }
@@ -992,6 +1032,9 @@ func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) {
// enforces authorization (including "this user cannot be deleted" rules) // enforces authorization (including "this user cannot be deleted" rules)
// itself. // itself.
func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) { func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) {
if refuseCrossSite(w, r) {
return
}
id, err := strconv.ParseInt(idURLParam(r), 10, 64) id, err := strconv.ParseInt(idURLParam(r), 10, 64)
if err != nil { if err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid user id") writeProxyError(w, http.StatusBadRequest, "invalid user id")
@@ -1017,6 +1060,18 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
writeProxyJSON(w, http.StatusCreated, map[string]any{"user": &user}) writeProxyJSON(w, http.StatusCreated, map[string]any{"user": &user})
return return
} }
// First-run setup only applies while login is required. With login off, every
// caller already gets the local admin identity, and a fresh AuthGuard would make
// an anonymous signup its superadmin.
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
writeProxyError(w, http.StatusConflict, errSetupRequiresLogin.Error())
return
}
var input struct { var input struct {
Email string `json:"email"` Email string `json:"email"`
@@ -1074,7 +1129,7 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
return return
} }
result, err := s.authGuard.Register(r.Context(), username, email, input.Password) result, err := s.authGuard.Register(s.withClientIP(r), username, email, input.Password)
if err != nil { if err != nil {
// The claim slot is only valid once actually backed by a real // The claim slot is only valid once actually backed by a real
// AuthGuard account; reopen it so a corrected retry can proceed. // AuthGuard account; reopen it so a corrected retry can proceed.
@@ -1115,8 +1170,13 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
writeProxyError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) writeProxyError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
return return
} }
now := time.Now()
if !s.loginAccountAttempts.allow(strings.ToLower(identifier), now) || !s.loginClientAttempts.allow(s.clientAddress(r), now) {
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
return
}
result, err := s.authGuard.Login(r.Context(), identifier, input.Password, input.TOTPToken) result, err := s.authGuard.Login(s.withClientIP(r), identifier, input.Password, input.TOTPToken)
if err != nil { if err != nil {
var apiErr *authclient.APIError var apiErr *authclient.APIError
if errors.As(err, &apiErr) { if errors.As(err, &apiErr) {
@@ -1142,6 +1202,9 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
} }
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) { func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
if refuseCrossSite(w, r) {
return
}
if !s.enabled() { if !s.enabled() {
writeProxyJSON(w, http.StatusOK, map[string]bool{"ok": true}) writeProxyJSON(w, http.StatusOK, map[string]bool{"ok": true})
return return
@@ -1181,6 +1244,9 @@ func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) {
// /api/totp/enable (AuthGuard's "enable" is this service's "initiate" step - // /api/totp/enable (AuthGuard's "enable" is this service's "initiate" step -
// naming differs, the two-step provision-then-confirm flow is identical). // naming differs, the two-step provision-then-confirm flow is identical).
func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) { func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) {
if refuseCrossSite(w, r) {
return
}
if !s.enabled() { if !s.enabled() {
writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return return
@@ -1217,6 +1283,10 @@ func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return return
} }
if !s.totpAttempts.allow(strconv.FormatInt(user.ID, 10), time.Now()) {
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
return
}
var input struct { var input struct {
Token string `json:"token"` Token string `json:"token"`
TOTPToken string `json:"totpToken"` TOTPToken string `json:"totpToken"`
@@ -1229,7 +1299,7 @@ func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
if token == "" { if token == "" {
token = strings.TrimSpace(input.Token) token = strings.TrimSpace(input.Token)
} }
if err := s.authGuard.TOTPVerify(r.Context(), s.sessionToken(r), token); err != nil { if err := s.authGuard.TOTPVerify(s.withClientIP(r), s.sessionToken(r), token); err != nil {
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.") writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
return return
} }
@@ -1246,6 +1316,10 @@ func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return return
} }
if !s.totpAttempts.allow(strconv.FormatInt(user.ID, 10), time.Now()) {
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
return
}
var input struct { var input struct {
Token string `json:"token"` Token string `json:"token"`
TOTPToken string `json:"totpToken"` TOTPToken string `json:"totpToken"`
@@ -1258,7 +1332,7 @@ func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
if token == "" { if token == "" {
token = strings.TrimSpace(input.Token) token = strings.TrimSpace(input.Token)
} }
if err := s.authGuard.TOTPDisable(r.Context(), s.sessionToken(r), token); err != nil { if err := s.authGuard.TOTPDisable(s.withClientIP(r), s.sessionToken(r), token); err != nil {
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.") writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
return return
} }
@@ -1341,7 +1415,7 @@ func (s *Service) CreateUser(ctx context.Context, email, username, password, rol
return nil, err return nil, err
} }
role = normalizePlatformRole(role) role = normalizePlatformRole(role)
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) hash, err := HashPassword(password)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -1350,7 +1424,7 @@ func (s *Service) CreateUser(ctx context.Context, email, username, password, rol
INSERT INTO users (email, username, password_hash, role) INSERT INTO users (email, username, password_hash, role)
VALUES ($1, $2, $3, $4) VALUES ($1, $2, $3, $4)
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user') RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user')
`, email, username, string(hash), role).Scan(&user.ID, &user.Email, &user.Username, &user.Role) `, email, username, hash, role).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -1414,11 +1488,11 @@ func (s *Service) SetPassword(ctx context.Context, id int64, password string) er
if err := validateProxyPassword(password); err != nil { if err := validateProxyPassword(password); err != nil {
return err return err
} }
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) hash, err := HashPassword(password)
if err != nil { if err != nil {
return err return err
} }
_, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, string(hash)) _, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, hash)
return err return err
} }
@@ -1445,6 +1519,10 @@ func normalizeProxyUsername(value string) (string, error) {
if len([]rune(value)) > proxyMaxUsernameLength { if len([]rune(value)) > proxyMaxUsernameLength {
return "", errors.New("username is too long") return "", errors.New("username is too long")
} }
// An identifier containing "@" could be read as another account's email at login.
if strings.Contains(value, "@") {
return "", errors.New("username cannot contain @")
}
return value, nil return value, nil
} }
@@ -1460,6 +1538,10 @@ func validateProxyPassword(password string) error {
if len([]rune(password)) < proxyMinPasswordLength || len([]rune(password)) > 1024 { if len([]rune(password)) < proxyMinPasswordLength || len([]rune(password)) > 1024 {
return errors.New("Password must be at least 8 characters.") return errors.New("Password must be at least 8 characters.")
} }
// bcrypt uses only the first 72 bytes, so a longer password would be refused at hashing time.
if len(password) > maxBcryptPasswordBytes {
return errors.New("Password must be at most 72 bytes.")
}
return nil return nil
} }
@@ -1506,8 +1588,29 @@ func idURLParam(r *http.Request) string {
return r.PathValue("id") return r.PathValue("id")
} }
// decodeProxyJSON reads a JSON request body. It refuses a body that is not sent as
// application/json, which a cross-site HTML form cannot produce, and any request the browser
// marks as cross-site.
// refuseCrossSite answers a state-changing request that carries no JSON body (logout, TOTP
// initiate, user delete) when the browser says it came from another site. Simple cross-site
// forms cannot send a JSON body, so decodeProxyJSON already refuses them; this covers the rest.
func refuseCrossSite(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
writeProxyError(w, http.StatusForbidden, errCrossSiteRequest.Error())
return true
}
return false
}
func decodeProxyJSON(r *http.Request, target any) error { func decodeProxyJSON(r *http.Request, target any) error {
defer r.Body.Close() defer r.Body.Close()
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
return errCrossSiteRequest
}
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" {
return errJSONContentType
}
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024)) decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
return decoder.Decode(target) return decoder.Decode(target)
} }
+663
View File
@@ -0,0 +1,663 @@
package auth
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// recordedCall is one request a fakeAuthGuard received.
type recordedCall struct {
Method string
Path string
Forwarded string
Authorization string
Body map[string]any
}
// fakeAuthGuard is an httptest AuthGuard that records every call and answers from a route table.
type fakeAuthGuard struct {
mu sync.Mutex
calls []recordedCall
routes map[string]func(w http.ResponseWriter, body map[string]any)
server *httptest.Server
}
func newFakeAuthGuard(t *testing.T) *fakeAuthGuard {
t.Helper()
f := &fakeAuthGuard{routes: map[string]func(http.ResponseWriter, map[string]any){}}
f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var body map[string]any
_ = json.Unmarshal(raw, &body)
f.mu.Lock()
f.calls = append(f.calls, recordedCall{
Method: r.Method, Path: r.URL.Path, Forwarded: r.Header.Get("X-Forwarded-For"),
Authorization: r.Header.Get("Authorization"), Body: body,
})
route := f.routes[r.Method+" "+r.URL.Path]
f.mu.Unlock()
if route == nil {
http.NotFound(w, r)
return
}
route(w, body)
}))
t.Cleanup(f.server.Close)
return f
}
func (f *fakeAuthGuard) handle(route string, handler func(w http.ResponseWriter, body map[string]any)) {
f.mu.Lock()
defer f.mu.Unlock()
f.routes[route] = handler
}
func (f *fakeAuthGuard) reply(route string, status int, payload any) {
f.handle(route, func(w http.ResponseWriter, _ map[string]any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(payload)
})
}
func (f *fakeAuthGuard) callsTo(route string) []recordedCall {
f.mu.Lock()
defer f.mu.Unlock()
var matched []recordedCall
for _, call := range f.calls {
if call.Method+" "+call.Path == route {
matched = append(matched, call)
}
}
return matched
}
func (f *fakeAuthGuard) service(t *testing.T, options ...ServiceOption) (*Service, *fakeProxyStore) {
t.Helper()
store := &fakeProxyStore{loginRequired: true}
return NewWithStore(store, "session", false, f.server.URL, "testproject", options...), store
}
func jsonRequest(method, target, body string) *http.Request {
req := httptest.NewRequest(method, target, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
return req
}
func withSession(req *http.Request, token string) *http.Request {
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: token})
return req
}
func withUser(req *http.Request, user *ProxyUser) *http.Request {
return req.WithContext(context.WithValue(req.Context(), proxyUserContextKey, user))
}
func decodeBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("response body %q is not JSON: %v", rec.Body.String(), err)
}
return out
}
func TestLoginForwardsTheVerifiedClientAddressToAuthGuard(t *testing.T) {
tests := []struct {
name string
trusted string
remote string
forwarded string
want string
}{
{"peer without trusted proxies", "", "203.0.113.7:4444", "", "203.0.113.7"},
{"spoofed header from an untrusted peer", "10.0.0.0/8", "203.0.113.7:4444", "6.6.6.6", "203.0.113.7"},
{"client behind a trusted proxy", "10.0.0.0/8", "10.0.0.2:4444", "6.6.6.6, 198.51.100.9", "198.51.100.9"},
{"unparseable peer sends nothing", "", "not-an-address", "", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/login", http.StatusOK, map[string]any{"user": map[string]any{"id": 1, "username": "a", "role": "user"}})
networks, err := ParseTrustedProxies(tt.trusted)
if err != nil {
t.Fatal(err)
}
service, _ := guard.service(t, WithTrustedProxies(networks))
req := jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"a","password":"password123"}`)
req.RemoteAddr = tt.remote
if tt.forwarded != "" {
req.Header.Set("X-Forwarded-For", tt.forwarded)
}
rec := httptest.NewRecorder()
service.Login(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("login status = %d, body %s", rec.Code, rec.Body.String())
}
calls := guard.callsTo("POST /api/login")
if len(calls) != 1 || calls[0].Forwarded != tt.want {
t.Fatalf("AuthGuard saw X-Forwarded-For %+v, want %q", calls, tt.want)
}
})
}
}
func TestLoginMapsAuthGuardAnswers(t *testing.T) {
login := func(guard *fakeAuthGuard) *httptest.ResponseRecorder {
service, _ := guard.service(t)
rec := httptest.NewRecorder()
service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"email":"a@b.com","password":"password123"}`))
return rec
}
t.Run("success forwards the session cookie", func(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) {
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "tok", Path: "/", HttpOnly: true})
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"user":{"id":3,"username":"a","email":"a@b.com","role":"admin","totp_enabled":true}}`))
})
rec := login(guard)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
user := decodeBody(t, rec)["user"].(map[string]any)
if user["role"] != "admin" || user["canManageUsers"] != true || user["mfaEnabled"] != true {
t.Fatalf("user = %v", user)
}
if cookies := rec.Result().Cookies(); len(cookies) != 1 || cookies[0].Value != "tok" {
t.Fatalf("cookies = %v, want the AuthGuard session cookie", cookies)
}
if body := guard.callsTo("POST /api/login")[0].Body; body["username_or_email"] != "a@b.com" {
t.Fatalf("AuthGuard body = %v, want the email used as the identifier", body)
}
})
t.Run("wrong credentials answer 401 with the generic message", func(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "no such account"})
rec := login(guard)
if rec.Code != http.StatusUnauthorized || decodeBody(t, rec)["error"] != ErrInvalidLogin.Error() {
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
}
})
t.Run("a required second factor is reported as mfaRequired", func(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "code required", "totp_required": true})
rec := login(guard)
if rec.Code != http.StatusUnauthorized || decodeBody(t, rec)["mfaRequired"] != true {
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
}
})
t.Run("an unreachable AuthGuard answers 500 with the unavailable message", func(t *testing.T) {
guard := newFakeAuthGuard(t)
service, _ := guard.service(t)
guard.server.Close()
rec := httptest.NewRecorder()
service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"a","password":"password123"}`))
if rec.Code != http.StatusInternalServerError || decodeBody(t, rec)["error"] != errAuthGuardUnavailable.Error() {
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
}
})
t.Run("a missing identifier and a non-JSON body are refused before AuthGuard", func(t *testing.T) {
guard := newFakeAuthGuard(t)
service, _ := guard.service(t)
rec := httptest.NewRecorder()
service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"password":"password123"}`))
if rec.Code != http.StatusUnauthorized {
t.Fatalf("missing identifier status = %d, want 401", rec.Code)
}
plain := httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader(`{"identifier":"a"}`))
rec = httptest.NewRecorder()
service.Login(rec, plain)
if rec.Code != http.StatusBadRequest {
t.Fatalf("form-typed body status = %d, want 400", rec.Code)
}
if len(guard.callsTo("POST /api/login")) != 0 {
t.Fatal("a refused login still reached AuthGuard")
}
})
}
func TestLoginIsLimitedPerClientAddress(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "bad"})
service, _ := guard.service(t)
attempt := func(i int, remote string) int {
req := jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"user`+strings.Repeat("x", i)+`","password":"guess"}`)
req.RemoteAddr = remote
rec := httptest.NewRecorder()
service.Login(rec, req)
return rec.Code
}
for i := 0; i < loginClientLimit; i++ {
if code := attempt(i, "203.0.113.7:1"); code == http.StatusTooManyRequests {
t.Fatalf("attempt %d refused before the limit", i+1)
}
}
if code := attempt(loginClientLimit, "203.0.113.7:1"); code != http.StatusTooManyRequests {
t.Fatalf("attempt past the per-address limit status = %d, want 429", code)
}
if code := attempt(loginClientLimit+1, "203.0.113.8:1"); code == http.StatusTooManyRequests {
t.Fatal("a different client address was refused")
}
}
func TestSignupForwardsTheClientAddressAndClaimsSetup(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("GET /api/setup-status", http.StatusOK, map[string]any{"setup_required": true})
guard.reply("POST /api/register", http.StatusCreated, map[string]any{"user": map[string]any{"id": 1, "username": "root", "email": "root@example.com", "role": "superadmin"}})
service, store := guard.service(t)
req := jsonRequest(http.MethodPost, "/auth/signup", `{"email":"Root@Example.com","username":"root","password":"password123"}`)
req.RemoteAddr = "198.51.100.20:5555"
rec := httptest.NewRecorder()
service.Signup(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("signup status = %d, body %s", rec.Code, rec.Body.String())
}
if !store.setupClaimed {
t.Fatal("signup did not claim the setup flag")
}
calls := guard.callsTo("POST /api/register")
if len(calls) != 1 || calls[0].Forwarded != "198.51.100.20" || calls[0].Body["email"] != "root@example.com" {
t.Fatalf("register call = %+v", calls)
}
}
func TestSignupValidatesInputBeforeClaimingSetup(t *testing.T) {
guard := newFakeAuthGuard(t)
service, store := guard.service(t)
for name, body := range map[string]string{
"missing username": `{"email":"a@b.com","password":"password123"}`,
"bad email": `{"email":"nope","username":"a","password":"password123"}`,
"at in username": `{"email":"a@b.com","username":"a@b.com","password":"password123"}`,
"short password": `{"email":"a@b.com","username":"a","password":"short"}`,
} {
rec := httptest.NewRecorder()
service.Signup(rec, jsonRequest(http.MethodPost, "/auth/signup", body))
if rec.Code != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400", name, rec.Code)
}
}
if store.setupClaimed || len(guard.calls) != 0 {
t.Fatal("a refused signup claimed setup or reached AuthGuard")
}
}
func TestSignupReleasesTheClaimWhenAuthGuardAlreadyHasAnAccount(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("GET /api/setup-status", http.StatusOK, map[string]any{"setup_required": false})
service, store := guard.service(t)
rec := httptest.NewRecorder()
service.Signup(rec, jsonRequest(http.MethodPost, "/auth/signup", `{"email":"a@b.com","username":"a","password":"password123"}`))
if rec.Code != http.StatusConflict || store.setupClaimed {
t.Fatalf("status = %d, claimed = %v; want 409 and a released claim", rec.Code, store.setupClaimed)
}
}
func TestTOTPVerifyAndDisableForwardTheAddressAndShareAUserLimit(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/totp/verify", http.StatusUnauthorized, map[string]any{"error": "bad code"})
guard.reply("POST /api/totp/disable", http.StatusUnauthorized, map[string]any{"error": "bad code"})
service, _ := guard.service(t)
user := &ProxyUser{ID: 7, Role: "user"}
post := func(handler http.HandlerFunc, body string) int {
req := withUser(withSession(jsonRequest(http.MethodPost, "/totp", body), "tok-7"), user)
req.RemoteAddr = "198.51.100.30:9"
rec := httptest.NewRecorder()
handler(rec, req)
return rec.Code
}
for i := 0; i < totpAttemptLimit-1; i++ {
if code := post(service.TOTPVerify, `{"totpToken":"000000"}`); code != http.StatusUnauthorized {
t.Fatalf("verify attempt %d status = %d, want 401", i+1, code)
}
}
if code := post(service.TOTPDisable, `{"token":"000000"}`); code != http.StatusUnauthorized {
t.Fatalf("disable attempt status = %d, want 401", code)
}
if code := post(service.TOTPVerify, `{"totpToken":"123456"}`); code != http.StatusTooManyRequests {
t.Fatalf("verify past the shared limit status = %d, want 429", code)
}
if code := post(service.TOTPDisable, `{"token":"123456"}`); code != http.StatusTooManyRequests {
t.Fatalf("disable past the shared limit status = %d, want 429", code)
}
verifies, disables := guard.callsTo("POST /api/totp/verify"), guard.callsTo("POST /api/totp/disable")
if len(verifies) != totpAttemptLimit-1 || len(disables) != 1 {
t.Fatalf("AuthGuard saw %d verify and %d disable calls, want %d and 1", len(verifies), len(disables), totpAttemptLimit-1)
}
for _, call := range append(verifies, disables...) {
if call.Forwarded != "198.51.100.30" || call.Authorization != "Bearer tok-7" {
t.Fatalf("call = %+v, want the client address and the session token", call)
}
}
if verifies[0].Body["token"] != "000000" {
t.Fatalf("verify body = %v, want the totpToken sent as token", verifies[0].Body)
}
other := withUser(withSession(jsonRequest(http.MethodPost, "/totp", `{"token":"1"}`), "tok-8"), &ProxyUser{ID: 8})
rec := httptest.NewRecorder()
service.TOTPVerify(rec, other)
if rec.Code == http.StatusTooManyRequests {
t.Fatal("another user shares the first user's TOTP limit")
}
}
func TestTOTPHandlersNeedASessionUser(t *testing.T) {
guard := newFakeAuthGuard(t)
service, _ := guard.service(t)
for name, handler := range map[string]http.HandlerFunc{
"status": service.TOTPStatus, "initiate": service.TOTPInitiate, "verify": service.TOTPVerify, "disable": service.TOTPDisable,
} {
rec := httptest.NewRecorder()
handler(rec, jsonRequest(http.MethodPost, "/totp", `{}`))
if rec.Code != http.StatusUnauthorized {
t.Errorf("%s without a session user: status = %d, want 401", name, rec.Code)
}
}
if len(guard.calls) != 0 {
t.Fatal("an unauthenticated TOTP request reached AuthGuard")
}
}
func TestTOTPInitiateAndStatus(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("POST /api/totp/enable", http.StatusOK, map[string]any{"secret": "JBSWY3DP", "otpauth_url": "otpauth://totp/x", "enabled": false})
service, _ := guard.service(t)
rec := httptest.NewRecorder()
service.TOTPStatus(rec, withUser(httptest.NewRequest(http.MethodGet, "/totp/status", nil), &ProxyUser{ID: 1, MFAEnabled: true}))
if body := decodeBody(t, rec); body["enabled"] != true || body["mfaEnabled"] != true {
t.Fatalf("status = %v", body)
}
rec = httptest.NewRecorder()
service.TOTPInitiate(rec, withUser(withSession(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), "tok"), &ProxyUser{ID: 1}))
data := decodeBody(t, rec)["data"].(map[string]any)
if rec.Code != http.StatusOK || data["secret"] != "JBSWY3DP" || data["otpauthUrl"] != "otpauth://totp/x" {
t.Fatalf("initiate status = %d, data %v", rec.Code, data)
}
rec = httptest.NewRecorder()
service.TOTPInitiate(rec, withUser(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), &ProxyUser{ID: 1, MFAEnabled: true}))
if rec.Code != http.StatusConflict {
t.Fatalf("initiate while enabled status = %d, want 409", rec.Code)
}
cross := withUser(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), &ProxyUser{ID: 1})
cross.Header.Set("Sec-Fetch-Site", "cross-site")
rec = httptest.NewRecorder()
service.TOTPInitiate(rec, cross)
if rec.Code != http.StatusForbidden {
t.Fatalf("cross-site initiate status = %d, want 403", rec.Code)
}
}
func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
guard := newFakeAuthGuard(t)
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"}})
service, _ := guard.service(t)
update := func(user *ProxyUser, body string) *httptest.ResponseRecorder {
req := withSession(jsonRequest(http.MethodPut, "/auth/me", body), "tok-7")
if user != nil {
req = withUser(req, user)
}
rec := httptest.NewRecorder()
service.UpdateMe(rec, req)
return rec
}
manager := &ProxyUser{ID: 7, Role: "admin"}
if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized {
t.Fatalf("no session user: status = %d, want 401", rec.Code)
}
if rec := update(&ProxyUser{ID: 7, Role: "user"}, `{"email":"a@b.com"}`); rec.Code != http.StatusForbidden {
t.Fatalf("ordinary user: status = %d, want 403", rec.Code)
}
for name, body := range map[string]string{
"bad email": `{"email":"nope","username":"boss"}`,
"at in username": `{"email":"a@b.com","username":"a@b.com"}`,
"short password": `{"email":"a@b.com","username":"boss","password":"short"}`,
"long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`,
"not JSON": `nope`,
} {
if rec := update(manager, body); rec.Code != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400", name, rec.Code)
}
}
if len(guard.callsTo("PUT /api/admin/users/7")) != 0 {
t.Fatal("a refused update reached AuthGuard")
}
rec := update(manager, `{"email":"Boss@Example.com","username":" boss "}`)
if rec.Code != http.StatusOK {
t.Fatalf("update status = %d, body %s", rec.Code, rec.Body.String())
}
calls := guard.callsTo("PUT /api/admin/users/7")
if len(calls) != 1 || calls[0].Authorization != "Bearer tok-7" || calls[0].Body["email"] != "boss@example.com" || calls[0].Body["username"] != "boss" {
t.Fatalf("AuthGuard update = %+v", calls)
}
if _, sent := calls[0].Body["password"]; sent {
t.Fatal("an update without a password sent one to AuthGuard")
}
if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" {
t.Fatalf("response user = %v", user)
}
}
func TestManagedUserHandlers(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("GET /api/admin/users", http.StatusOK, map[string]any{"users": []map[string]any{
{"id": 1, "username": "root", "email": "root@example.com", "role": "superadmin"},
{"id": 2, "username": "pat", "email": "pat@example.com", "role": "weird-role"},
}})
guard.reply("POST /api/admin/users", http.StatusCreated, map[string]any{"user": map[string]any{"id": 3, "username": "new", "email": "new@example.com", "role": "admin"}})
guard.reply("PUT /api/admin/users/2", http.StatusOK, map[string]any{})
guard.reply("DELETE /api/admin/users/2", http.StatusOK, map[string]any{})
guard.reply("DELETE /api/admin/users/1", http.StatusForbidden, map[string]any{"error": "the superadmin cannot be deleted"})
service, _ := guard.service(t)
t.Run("list normalizes roles", func(t *testing.T) {
rec := httptest.NewRecorder()
service.ManagedUsers(rec, withSession(httptest.NewRequest(http.MethodGet, "/users", nil), "tok"))
var users []map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &users); err != nil || len(users) != 2 {
t.Fatalf("users = %s, %v", rec.Body.String(), err)
}
if users[0]["role"] != "superadmin" || users[1]["role"] != "user" {
t.Fatalf("roles = %v, %v; want superadmin and the unknown role reduced to user", users[0]["role"], users[1]["role"])
}
if call := guard.callsTo("GET /api/admin/users")[0]; call.Authorization != "Bearer tok" {
t.Fatalf("list call = %+v, want the session token", call)
}
})
t.Run("create forwards the role", func(t *testing.T) {
rec := httptest.NewRecorder()
req := withSession(jsonRequest(http.MethodPost, "/users", `{"email":"new@example.com","username":"new","password":"password123","role":" admin "}`), "tok")
service.ManagedCreateUser(rec, req)
if rec.Code != http.StatusCreated || decodeBody(t, rec)["role"] != "admin" {
t.Fatalf("create status = %d, body %s", rec.Code, rec.Body.String())
}
if body := guard.callsTo("POST /api/admin/users")[0].Body; body["role"] != "admin" || body["username"] != "new" {
t.Fatalf("create body = %v", body)
}
})
t.Run("update answers with the refreshed user, or 404", func(t *testing.T) {
req := withSession(jsonRequest(http.MethodPut, "/users/2", `{"username":"pat2"}`), "tok")
req.SetPathValue("id", "2")
rec := httptest.NewRecorder()
service.ManagedUpdateUser(rec, req)
if rec.Code != http.StatusOK || decodeBody(t, rec)["username"] != "pat" {
t.Fatalf("update status = %d, body %s", rec.Code, rec.Body.String())
}
missing := withSession(jsonRequest(http.MethodPut, "/users/9", `{}`), "tok")
missing.SetPathValue("id", "9")
guard.reply("PUT /api/admin/users/9", http.StatusOK, map[string]any{})
rec = httptest.NewRecorder()
service.ManagedUpdateUser(rec, missing)
if rec.Code != http.StatusNotFound {
t.Fatalf("update of an id that is not listed: status = %d, want 404", rec.Code)
}
})
t.Run("delete", func(t *testing.T) {
del := func(id string, header http.Header) *httptest.ResponseRecorder {
req := withSession(httptest.NewRequest(http.MethodDelete, "/users/"+id, nil), "tok")
req.SetPathValue("id", id)
for key, values := range header {
req.Header[key] = values
}
rec := httptest.NewRecorder()
service.ManagedDeleteUser(rec, req)
return rec
}
if rec := del("2", nil); rec.Code != http.StatusOK {
t.Fatalf("delete status = %d", rec.Code)
}
if rec := del("1", nil); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "superadmin") {
t.Fatalf("AuthGuard refusal status = %d, body %s; want it forwarded", rec.Code, rec.Body.String())
}
if rec := del("abc", nil); rec.Code != http.StatusBadRequest {
t.Fatalf("bad id status = %d, want 400", rec.Code)
}
before := len(guard.callsTo("DELETE /api/admin/users/2"))
if rec := del("2", http.Header{"Sec-Fetch-Site": {"cross-site"}}); rec.Code != http.StatusForbidden {
t.Fatalf("cross-site delete status = %d, want 403", rec.Code)
}
if len(guard.callsTo("DELETE /api/admin/users/2")) != before {
t.Fatal("a cross-site delete reached AuthGuard")
}
})
}
func TestLogoutForwardsTheTokenAndClearsCookies(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.handle("POST /api/logout", func(w http.ResponseWriter, _ map[string]any) {
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "", Path: "/", MaxAge: -1})
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{}`))
})
service, _ := guard.service(t)
rec := httptest.NewRecorder()
service.Logout(rec, withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "tok"))
if rec.Code != http.StatusOK {
t.Fatalf("logout status = %d", rec.Code)
}
if calls := guard.callsTo("POST /api/logout"); len(calls) != 1 || calls[0].Authorization != "Bearer tok" {
t.Fatalf("logout calls = %+v", calls)
}
cleared := false
for _, cookie := range rec.Result().Cookies() {
if cookie.Name == "auth_session" && cookie.MaxAge < 0 {
cleared = true
}
}
if !cleared {
t.Fatalf("cookies = %v, want the session cookie cleared", rec.Result().Cookies())
}
guard.reply("POST /api/logout", http.StatusUnauthorized, map[string]any{"error": "expired"})
rec = httptest.NewRecorder()
service.Logout(rec, withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "stale"))
if rec.Code != http.StatusOK {
t.Fatalf("logout of an expired session status = %d, want 200", rec.Code)
}
cross := withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "tok")
cross.Header.Set("Sec-Fetch-Site", "cross-site")
rec = httptest.NewRecorder()
service.Logout(rec, cross)
if rec.Code != http.StatusForbidden {
t.Fatalf("cross-site logout status = %d, want 403", rec.Code)
}
}
func TestGatingMiddlewaresResolveSessionsThroughAuthGuard(t *testing.T) {
guard := newFakeAuthGuard(t)
roles := map[string]string{"user-tok": "user", "admin-tok": "admin", "mod-tok": "moderator"}
service, _ := guard.service(t)
served := func(role string) {
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 5, "username": "u", "role": role}})
}
ok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) })
run := func(mw func(http.Handler) http.Handler, token string) int {
req := httptest.NewRequest(http.MethodGet, "/x", nil)
if token != "" {
withSession(req, token)
}
rec := httptest.NewRecorder()
mw(ok).ServeHTTP(rec, req)
return rec.Code
}
guard.reply("GET /api/me", http.StatusUnauthorized, map[string]any{"error": "no session"})
if code := run(service.Require, ""); code != http.StatusUnauthorized {
t.Fatalf("Require without a cookie = %d, want 401", code)
}
if code := run(service.Require, "stale"); code != http.StatusUnauthorized {
t.Fatalf("Require with an expired session = %d, want 401", code)
}
for token, role := range roles {
served(role)
wantAdmin := http.StatusForbidden
if role == "admin" || role == "moderator" {
wantAdmin = http.StatusNoContent
}
wantManager := http.StatusForbidden
if role == "admin" {
wantManager = http.StatusNoContent
}
if code := run(service.Require, token); code != http.StatusNoContent {
t.Errorf("Require as %s = %d, want 204", role, code)
}
if code := run(service.RequireAdmin, token); code != wantAdmin {
t.Errorf("RequireAdmin as %s = %d, want %d", role, code, wantAdmin)
}
if code := run(service.RequireUserManager, token); code != wantManager {
t.Errorf("RequireUserManager as %s = %d, want %d", role, code, wantManager)
}
}
guard.server.Close()
if code := run(service.Require, "any-token"); code != http.StatusInternalServerError {
t.Fatalf("Require with AuthGuard down = %d, want 500", code)
}
}
func TestMeReportsTheSessionUserAndLoginRequirement(t *testing.T) {
guard := newFakeAuthGuard(t)
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 5, "username": "u", "email": "u@example.com", "role": "user"}})
service, store := guard.service(t)
rec := httptest.NewRecorder()
service.Me(rec, withSession(httptest.NewRequest(http.MethodGet, "/auth/me", nil), "tok"))
body := decodeBody(t, rec)
if rec.Code != http.StatusOK || body["authRequired"] != true || body["user"].(map[string]any)["username"] != "u" {
t.Fatalf("me status = %d, body %v", rec.Code, body)
}
// The login setting is cached for a moment, so the second answer comes from a fresh Service.
service, store = guard.service(t)
store.loginRequired = false
rec = httptest.NewRecorder()
service.Me(rec, httptest.NewRequest(http.MethodGet, "/auth/me", nil))
body = decodeBody(t, rec)
if body["authRequired"] != false || body["user"].(map[string]any)["username"] != "Admin" {
t.Fatalf("me with login off = %v, want the local admin and authRequired false", body)
}
}
+143 -3
View File
@@ -4,7 +4,10 @@ import (
"context" "context"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strconv"
"strings"
"testing" "testing"
"time"
) )
// fakeProxyStore is a minimal in-memory ProxyStore for constructing a // fakeProxyStore is a minimal in-memory ProxyStore for constructing a
@@ -95,7 +98,10 @@ func TestLoginDisabledUsesAdminIdentityWithoutCredentials(t *testing.T) {
} }
} }
func TestInternalLoginOverrideWorksWithNoOpStore(t *testing.T) { // TestNoOpStoreDoesNotKeepAProcessLocalLoginOverride checks that the login-required setting is read
// from the store on each call. A store that discards writes keeps login required everywhere, rather
// than letting one process diverge from the rest.
func TestNoOpStoreDoesNotKeepAProcessLocalLoginOverride(t *testing.T) {
store := &noOpLoginProxyStore{fakeProxyStore: fakeProxyStore{loginRequired: true}} store := &noOpLoginProxyStore{fakeProxyStore: fakeProxyStore{loginRequired: true}}
service := NewWithStore(store, "session", false, "", "testproject") service := NewWithStore(store, "session", false, "", "testproject")
if err := service.SetLoginRequired(context.Background(), false); err != nil { if err := service.SetLoginRequired(context.Background(), false); err != nil {
@@ -103,8 +109,142 @@ func TestInternalLoginOverrideWorksWithNoOpStore(t *testing.T) {
} }
user, err := service.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil)) user, err := service.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
if err != nil || user == nil || user.Username != "Admin" { if err != nil || user != nil {
t.Fatalf("no-op store override resolved user=%+v err=%v, want Admin", user, err) t.Fatalf("no-op store resolved user=%+v err=%v, want no user while login is still required", user, err)
}
}
// TestBodylessStateChangesRefuseCrossSite checks the routes that take no JSON body, which
// decodeProxyJSON cannot guard, refuse a request the browser marks as cross-site.
func TestBodylessStateChangesRefuseCrossSite(t *testing.T) {
service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject")
handlers := map[string]http.HandlerFunc{
"logout": service.Logout,
"totp initiate": service.TOTPInitiate,
"delete user": service.ManagedDeleteUser,
}
for name, handler := range handlers {
req := httptest.NewRequest(http.MethodPost, "/", nil)
req.Header.Set("Sec-Fetch-Site", "cross-site")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusForbidden {
t.Errorf("%s with Sec-Fetch-Site: cross-site returned %d, want 403", name, rec.Code)
}
}
}
func TestSetLoginRequiredNeedsAStore(t *testing.T) {
service := NewWithStore(nil, "session", false, "", "testproject")
if err := service.SetLoginRequired(context.Background(), false); err == nil {
t.Fatal("SetLoginRequired with no store succeeded, want an error")
}
}
func TestDecodeProxyJSONRequiresAJSONBodyAndRefusesCrossSite(t *testing.T) {
decode := func(contentType, fetchSite string) error {
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"loginRequired":true}`))
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
if fetchSite != "" {
req.Header.Set("Sec-Fetch-Site", fetchSite)
}
var input struct {
LoginRequired bool `json:"loginRequired"`
}
return decodeProxyJSON(req, &input)
}
if err := decode("application/json", ""); err != nil {
t.Fatalf("application/json body refused: %v", err)
}
if err := decode("application/json; charset=utf-8", "same-site"); err != nil {
t.Fatalf("same-site application/json body refused: %v", err)
}
for _, contentType := range []string{"", "text/plain", "application/x-www-form-urlencoded", "multipart/form-data; boundary=x"} {
if err := decode(contentType, ""); err == nil {
t.Errorf("Content-Type %q accepted, want refused", contentType)
}
}
if err := decode("application/json", "cross-site"); err == nil {
t.Error("cross-site application/json body accepted, want refused")
}
}
func TestSignupIsRefusedWhileLoginIsNotRequired(t *testing.T) {
store := &fakeProxyStore{loginRequired: false}
service := NewWithStore(store, "session", false, "", "testproject")
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"email":"a@b.com","username":"a","password":"password123"}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
service.Signup(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("signup with login off status = %d, want 409", rec.Code)
}
if store.setupClaimed {
t.Fatal("refused signup still claimed the setup flag")
}
}
func TestLoginIsRateLimitedPerAccount(t *testing.T) {
service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject")
post := func() int {
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"identifier":"Victim","password":"guess"}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
service.Login(rec, req)
return rec.Code
}
for i := 0; i < loginAccountLimit; i++ {
if code := post(); code == http.StatusTooManyRequests {
t.Fatalf("attempt %d refused before the limit", i+1)
}
}
if code := post(); code != http.StatusTooManyRequests {
t.Fatalf("attempt past the limit status = %d, want 429", code)
}
}
func TestAttemptLimiterWindowAndTableBound(t *testing.T) {
now := time.Now()
limiter := newAttemptLimiter(time.Minute, 2)
if !limiter.allow("k", now) || !limiter.allow("k", now) {
t.Fatal("attempts within the limit were refused")
}
if limiter.allow("k", now) {
t.Fatal("attempt past the limit was allowed")
}
if !limiter.allow("k", now.Add(time.Minute)) {
t.Fatal("limit did not reset after the window")
}
full := newAttemptLimiter(time.Hour, 1)
for i := 0; i < maxTrackedAttemptKeys; i++ {
full.allow(strconv.Itoa(i), now)
}
if full.allow("new-key", now) {
t.Fatal("a new key was tracked past the table bound")
}
}
func TestValidateProxyPasswordRefusesMoreThan72Bytes(t *testing.T) {
if err := validateProxyPassword(strings.Repeat("a", 72)); err != nil {
t.Fatalf("72-byte password refused: %v", err)
}
if err := validateProxyPassword(strings.Repeat("a", 73)); err == nil {
t.Fatal("73-byte password accepted, want refused")
}
if err := validateProxyPassword(strings.Repeat("é", 40)); err == nil {
t.Fatal("80-byte multi-byte password accepted, want refused")
}
}
func TestNormalizeProxyUsernameRefusesAt(t *testing.T) {
if _, err := normalizeProxyUsername("name@example.com"); err == nil {
t.Fatal("username containing @ accepted")
}
if got, err := normalizeProxyUsername(" plain "); err != nil || got != "plain" {
t.Fatalf("plain username = %q, %v", got, err)
} }
} }
+59
View File
@@ -0,0 +1,59 @@
package auth
import (
"sync"
"time"
)
// Attempt limits for the credential endpoints (login and the TOTP verify/disable routes). Each key
// may make limit attempts per window; further attempts are refused until the window ends. The
// counters live in this process, and AuthGuard's own limits still apply on top.
const (
attemptWindow = 15 * time.Minute
loginAccountLimit = 10
loginClientLimit = 200
totpAttemptLimit = 5
maxTrackedAttemptKeys = 10000
)
type attemptCounter struct {
windowStart time.Time
count int
}
// attemptLimiter is a fixed-window counter keyed by an account, a client address or a user.
type attemptLimiter struct {
mu sync.Mutex
window time.Duration
limit int
counts map[string]attemptCounter
}
func newAttemptLimiter(window time.Duration, limit int) *attemptLimiter {
return &attemptLimiter{window: window, limit: limit, counts: make(map[string]attemptCounter)}
}
// allow records one attempt for key at time now and reports whether it is within the limit. When
// the table is full of live keys, a new key is refused rather than tracked, so flooding distinct
// keys cannot grow memory without bound.
func (l *attemptLimiter) allow(key string, now time.Time) bool {
l.mu.Lock()
defer l.mu.Unlock()
counter, tracked := l.counts[key]
if !tracked && len(l.counts) >= maxTrackedAttemptKeys {
for existing, state := range l.counts {
if now.Sub(state.windowStart) >= l.window {
delete(l.counts, existing)
}
}
if len(l.counts) >= maxTrackedAttemptKeys {
return false
}
}
if counter.windowStart.IsZero() || now.Sub(counter.windowStart) >= l.window {
counter = attemptCounter{windowStart: now}
}
counter.count++
l.counts[key] = counter
return counter.count <= l.limit
}
+130 -6
View File
@@ -7,6 +7,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"log"
"strings" "strings"
"time" "time"
@@ -66,6 +67,17 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return errors.New("auth postgres pool is nil") return errors.New("auth postgres pool is nil")
} }
// Only a table that predates the role column needs its oldest account promoted, so the
// promotion below runs once, in the migration that adds the column.
var roleColumnMissing bool
if err := pool.QueryRow(ctx, `
SELECT NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = 'auth_users' AND column_name = 'role'
)`).Scan(&roleColumnMissing); err != nil {
return fmt.Errorf("check auth schema: %w", err)
}
_, err := pool.Exec(ctx, ` _, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_users ( CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
@@ -89,9 +101,6 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
-- alone does not count, only a successful POST /api/login) and has no -- alone does not count, only a successful POST /api/login) and has no
-- DEFAULT, unlike every other column here. -- DEFAULT, unlike every other column here.
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> ''; ON auth_users (lower(email)) WHERE email <> '';
@@ -109,6 +118,20 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return fmt.Errorf("ensure auth schema: %w", err) return fmt.Errorf("ensure auth schema: %w", err)
} }
if err := ensureUsernameCaseIndex(ctx, pool); err != nil {
return err
}
if roleColumnMissing {
if _, err := pool.Exec(ctx, `
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
`); err != nil {
return fmt.Errorf("promote oldest auth user: %w", err)
}
}
if options.SingleUser { if options.SingleUser {
if _, err := pool.Exec(ctx, ` if _, err := pool.Exec(ctx, `
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true)); CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
@@ -153,6 +176,47 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return nil return nil
} }
// ensureUsernameCaseIndex makes usernames unique ignoring case, so "Admin" and "admin" cannot both
// be registered. The index is created only while no such pair exists: a database that already
// holds one still starts, logs the clashing names, and gets the index on the first start after an
// operator has renamed or removed one of each pair.
func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error {
rows, err := pool.Query(ctx, `
SELECT min(username) FROM auth_users GROUP BY lower(username) HAVING count(*) > 1
ORDER BY 1 LIMIT 10
`)
if err != nil {
return fmt.Errorf("check duplicate usernames: %w", err)
}
var clashing []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
rows.Close()
return fmt.Errorf("check duplicate usernames: %w", err)
}
clashing = append(clashing, name)
}
rows.Close()
if err := rows.Err(); err != nil {
return fmt.Errorf("check duplicate usernames: %w", err)
}
if len(clashing) > 0 {
log.Printf("[auth] usernames that differ only by case exist (%q); the case-insensitive username index was not created. Rename or remove one account of each pair and restart.", clashing)
return nil
}
if _, err := pool.Exec(ctx, `CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx ON auth_users (lower(username))`); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
// An account was registered between the check and the index build; the next start retries.
log.Printf("[auth] the case-insensitive username index was not created because a clashing username was just added: %v", err)
return nil
}
return fmt.Errorf("ensure username index: %w", err)
}
return nil
}
// TOTPState is the private provisioning state for one account. Secret must // TOTPState is the private provisioning state for one account. Secret must
// never be included in an API response. // never be included in an API response.
type TOTPState struct { type TOTPState struct {
@@ -176,15 +240,25 @@ func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, erro
return state, nil return state, nil
} }
// SetTOTPSecret stores a pending secret without enabling two-factor auth. // SetTOTPSecret stores a pending secret without enabling two-factor auth. It refuses while TOTP is
// already enabled, so a replaced secret cannot silently switch the second factor off.
func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) error { func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) 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 = $1, totp_enabled = false, updated_at = now() WHERE id = $2`, secret, userID) 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)
if err != nil { if err != nil {
return fmt.Errorf("set TOTP secret: %w", err) return fmt.Errorf("set TOTP secret: %w", err)
} }
if tag.RowsAffected() == 0 {
state, err := s.GetTOTPState(ctx, userID)
if err != nil {
return err
}
if state.Enabled {
return ErrTOTPAlreadyEnabled
}
}
return nil return nil
} }
@@ -230,6 +304,9 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return nil, err return nil, err
} }
if err := validateCredentials(username, passwordHash); err != nil {
return nil, err
}
var user User var user User
err := s.pool.QueryRow(ctx, ` err := s.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at) INSERT INTO auth_users (username, email, password_hash, role, updated_at)
@@ -255,10 +332,19 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User,
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return nil, err return nil, err
} }
// Usernames are tried before emails, so an identifier resolves to one account in a fixed order.
user, err := s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users
WHERE username = $1
`, identifier)
if err != nil || user != nil {
return user, err
}
return s.find(ctx, ` return s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users FROM auth_users
WHERE username = $1 OR lower(email) = lower($1) WHERE lower(email) = lower($1)
`, identifier) `, identifier)
} }
@@ -278,12 +364,19 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return err return err
} }
if err := validateCredentials(username, passwordHash); err != nil {
return err
}
_, err := s.pool.Exec(ctx, ` _, err := s.pool.Exec(ctx, `
UPDATE auth_users UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, updated_at = now() SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4 WHERE id = $4
`, username, email, passwordHash, id) `, username, email, passwordHash, id)
if err != nil { if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return ErrUserExists
}
return fmt.Errorf("update auth credentials: %w", err) return fmt.Errorf("update auth credentials: %w", err)
} }
return nil return nil
@@ -319,6 +412,9 @@ func (s *Store) CreateManagedUser(ctx context.Context, username, email, password
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return nil, err return nil, err
} }
if err := validateCredentials(username, passwordHash); err != nil {
return nil, err
}
role = NormalizeRole(string(role)) role = NormalizeRole(string(role))
var user User var user User
err := s.pool.QueryRow(ctx, ` err := s.pool.QueryRow(ctx, `
@@ -343,6 +439,9 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return err return err
} }
if err := validateCredentials(username, passwordHash); err != nil {
return err
}
if role == nil { if role == nil {
return s.UpdateCredentials(ctx, id, username, email, passwordHash) return s.UpdateCredentials(ctx, id, username, email, passwordHash)
} }
@@ -353,6 +452,10 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
WHERE id = $5 WHERE id = $5
`, username, email, passwordHash, *role, id) `, username, email, passwordHash, *role, id)
if err != nil { if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return ErrUserExists
}
return fmt.Errorf("update managed auth user: %w", err) return fmt.Errorf("update managed auth user: %w", err)
} }
return nil return nil
@@ -627,6 +730,27 @@ func (s *Store) IsProjectAllowed(ctx context.Context, userID int64, project stri
var ErrUserExists = errors.New("auth user already exists") var ErrUserExists = errors.New("auth user already exists")
// ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on.
var ErrTOTPAlreadyEnabled = errors.New("auth: TOTP is already enabled; disable it before setting a new secret")
// ErrEmptyPasswordHash is returned when a credential write has no password hash.
var ErrEmptyPasswordHash = errors.New("auth: password hash is required")
// ErrInvalidUsername is returned for a username containing "@", which would be read as an email.
var ErrInvalidUsername = errors.New("auth: username cannot contain @")
// validateCredentials refuses a credential write that would leave an account without a password
// hash, or that stores a username which could be mistaken for another account's email.
func validateCredentials(username, passwordHash string) error {
if passwordHash == "" {
return ErrEmptyPasswordHash
}
if strings.Contains(username, "@") {
return ErrInvalidUsername
}
return nil
}
func (s *Store) validate() error { func (s *Store) validate() error {
if s == nil || s.pool == nil { if s == nil || s.pool == nil {
return errors.New("auth store has no postgres pool") return errors.New("auth store has no postgres pool")
+135
View File
@@ -2,10 +2,13 @@ package auth
import ( import (
"context" "context"
"errors"
"os" "os"
"testing" "testing"
"time" "time"
"github.com/jackc/pgx/v5/pgxpool"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres" "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
) )
@@ -119,3 +122,135 @@ func TestStoreIntegration(t *testing.T) {
t.Fatalf("FindByID() after UpdateLastLogin = %+v, want LastLoginAt set", afterLogin) t.Fatalf("FindByID() after UpdateLastLogin = %+v, want LastLoginAt set", afterLogin)
} }
} }
// openScratchStore opens DATABASE_URL (a scratch database, see TestStoreIntegration), applies the
// schema and removes every account before and after the test.
func openScratchStore(t *testing.T) (context.Context, *pgxpool.Pool, *Store) {
t.Helper()
url := os.Getenv("DATABASE_URL")
if url == "" {
t.Skip("DATABASE_URL not set; skipping Postgres integration test")
}
ctx := context.Background()
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(pool.Close)
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
t.Fatalf("EnsureSchema() error = %v", err)
}
store := NewStore(pool)
if err := store.DeleteAllUsers(ctx); err != nil {
t.Fatalf("DeleteAllUsers() (pre-test cleanup) error = %v", err)
}
t.Cleanup(func() {
if err := store.DeleteAllUsers(context.Background()); err != nil {
t.Logf("cleanup: DeleteAllUsers() error = %v", err)
}
})
return ctx, pool, store
}
// TestStoreRefusesUsernamesThatDifferOnlyByCase covers the unique index on lower(username).
func TestStoreRefusesUsernamesThatDifferOnlyByCase(t *testing.T) {
ctx, _, store := openScratchStore(t)
hash, err := HashPassword("correct horse battery staple")
if err != nil {
t.Fatal(err)
}
if _, err := store.CreateUser(ctx, "Admin", "", hash); err != nil {
t.Fatalf("CreateUser(Admin) error = %v", err)
}
if _, err := store.CreateUser(ctx, "admin", "", hash); !errors.Is(err, ErrUserExists) {
t.Fatalf("CreateUser(admin) error = %v, want ErrUserExists", err)
}
if _, err := store.CreateManagedUser(ctx, "ADMIN", "", hash, RoleUser); !errors.Is(err, ErrUserExists) {
t.Fatalf("CreateManagedUser(ADMIN) error = %v, want ErrUserExists", err)
}
bob, err := store.CreateUser(ctx, "bob", "", hash)
if err != nil {
t.Fatalf("CreateUser(bob) error = %v", err)
}
if err := store.UpdateCredentials(ctx, bob.ID, "admin", "", hash); !errors.Is(err, ErrUserExists) {
t.Fatalf("UpdateCredentials(admin) error = %v, want ErrUserExists", err)
}
role := RoleUser
if err := store.UpdateUser(ctx, bob.ID, "Admin", "", hash, &role); !errors.Is(err, ErrUserExists) {
t.Fatalf("UpdateUser(Admin) error = %v, want ErrUserExists", err)
}
}
// TestEnsureSchemaStartsWithExistingCaseVariantUsernames checks that a database already holding
// "Admin" and "admin" still starts, gets no index, and gets one after the pair is resolved.
func TestEnsureSchemaStartsWithExistingCaseVariantUsernames(t *testing.T) {
ctx, pool, store := openScratchStore(t)
if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS auth_users_username_lower_idx`); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO auth_users (username, password_hash) VALUES ('Admin', 'x'), ('admin', 'x')`); err != nil {
t.Fatal(err)
}
indexExists := func() bool {
var exists bool
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'auth_users_username_lower_idx')`).Scan(&exists); err != nil {
t.Fatal(err)
}
return exists
}
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
t.Fatalf("EnsureSchema() with clashing usernames error = %v, want it to start", err)
}
if indexExists() {
t.Fatal("the case-insensitive index was created over clashing usernames")
}
if err := store.DeleteAllUsers(ctx); err != nil {
t.Fatal(err)
}
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
t.Fatalf("EnsureSchema() after cleanup error = %v", err)
}
if !indexExists() {
t.Fatal("the case-insensitive index was not created once the clash was gone")
}
}
// TestStoreTOTPAndIdentifierPrimitives covers SetTOTPSecret refusing to replace an enabled second
// factor and FindByIdentifier trying usernames before emails.
func TestStoreTOTPAndIdentifierPrimitives(t *testing.T) {
ctx, pool, store := openScratchStore(t)
hash, err := HashPassword("correct horse battery staple")
if err != nil {
t.Fatal(err)
}
owner, err := store.CreateUser(ctx, "owner", "owner@example.com", hash)
if err != nil {
t.Fatal(err)
}
if err := store.SetTOTPSecret(ctx, owner.ID, "JBSWY3DPEHPK3PXP"); err != nil {
t.Fatalf("SetTOTPSecret() while disabled error = %v", err)
}
if err := store.EnableTOTP(ctx, owner.ID); err != nil {
t.Fatal(err)
}
if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) {
t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err)
}
if state, err := store.GetTOTPState(ctx, owner.ID); err != nil || !state.Enabled || state.Secret != "JBSWY3DPEHPK3PXP" {
t.Fatalf("TOTP state after a refused replace = %+v, %v; want the original secret still enabled", state, err)
}
// A username equal to another account's email (a row written outside the store's validation)
// resolves to the username's own account, not to the email's owner.
if _, err := pool.Exec(ctx, `INSERT INTO auth_users (username, email, password_hash) VALUES ('owner@example.com', 'second@example.com', 'x')`); err != nil {
t.Fatal(err)
}
found, err := store.FindByIdentifier(ctx, "owner@example.com")
if err != nil || found == nil || found.Username != "owner@example.com" {
t.Fatalf("FindByIdentifier() = %+v, %v; want the account whose username matches", found, err)
}
if err := store.UpdateCredentials(ctx, owner.ID, "owner", "owner@example.com", ""); !errors.Is(err, ErrEmptyPasswordHash) {
t.Fatalf("UpdateCredentials() with an empty hash error = %v, want ErrEmptyPasswordHash", err)
}
}
+28 -1
View File
@@ -1,6 +1,7 @@
package auth package auth
import ( import (
"errors"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -19,7 +20,7 @@ func TestPasswordRoundTrip(t *testing.T) {
if VerifyPassword(hash, "wrong password") { if VerifyPassword(hash, "wrong password") {
t.Fatal("VerifyPassword() accepted the wrong password") t.Fatal("VerifyPassword() accepted the wrong password")
} }
if cost, err := bcrypt.Cost([]byte(hash)); err != nil || cost != BcryptCost { if cost, err := bcrypt.Cost([]byte(strings.TrimPrefix(hash, bcryptScheme))); err != nil || cost != BcryptCost {
t.Fatalf("bcrypt cost = %d, error = %v; want %d", cost, err, BcryptCost) t.Fatalf("bcrypt cost = %d, error = %v; want %d", cost, err, BcryptCost)
} }
} }
@@ -67,3 +68,29 @@ func TestResetManagerExpiresCode(t *testing.T) {
t.Fatal("Confirm() accepted an expired reset code") t.Fatal("Confirm() accepted an expired reset code")
} }
} }
func TestValidateCredentialsRefusesEmptyHashAndAtUsername(t *testing.T) {
if err := validateCredentials("alice", ""); !errors.Is(err, ErrEmptyPasswordHash) {
t.Fatalf("empty hash error = %v, want ErrEmptyPasswordHash", err)
}
if err := validateCredentials("alice@example.com", "hash"); !errors.Is(err, ErrInvalidUsername) {
t.Fatalf("@ username error = %v, want ErrInvalidUsername", err)
}
if err := validateCredentials("alice", "hash"); err != nil {
t.Fatalf("valid credentials refused: %v", err)
}
}
func TestHashPasswordUsesTheSharedBcryptCost(t *testing.T) {
hash, err := HashPassword("correct horse battery staple")
if err != nil {
t.Fatal(err)
}
cost, err := bcrypt.Cost([]byte(strings.TrimPrefix(hash, bcryptScheme)))
if err != nil {
t.Fatal(err)
}
if cost != BcryptCost {
t.Fatalf("bcrypt cost = %d, want %d", cost, BcryptCost)
}
}
+52 -6
View File
@@ -68,7 +68,9 @@ type Client struct {
// restrictions can be enforced. Empty means "don't identify" - the // restrictions can be enforced. Empty means "don't identify" - the
// caller is treated as unrestricted; see AuthServer's project-scoping // caller is treated as unrestricted; see AuthServer's project-scoping
// feature and WithProjectKey. // feature and WithProjectKey.
projectKey string projectKey string
validationMu sync.Mutex
validationCache map[[32]byte]validationCacheEntry
} }
// ProjectKeyHeader is the header Client attaches to every request identifying // ProjectKeyHeader is the header Client attaches to every request identifying
@@ -112,9 +114,10 @@ func WithProjectKey(key string) Option {
// is always left as-is, overriding the inference. // is always left as-is, overriding the inference.
func New(baseURL string, opts ...Option) *Client { func New(baseURL string, opts ...Option) *Client {
c := &Client{ c := &Client{
baseURL: normalizeBaseURL(baseURL), baseURL: normalizeBaseURL(baseURL),
httpClient: &http.Client{Timeout: 5 * time.Second}, httpClient: &http.Client{Timeout: 5 * time.Second},
cookieName: DefaultCookieName, cookieName: DefaultCookieName,
validationCache: make(map[[32]byte]validationCacheEntry),
} }
for _, opt := range opts { for _, opt := range opts {
opt(c) opt(c)
@@ -138,6 +141,7 @@ func (c *Client) SetBaseURL(baseURL string) {
c.baseURLMu.Lock() c.baseURLMu.Lock()
c.baseURL = normalized c.baseURL = normalized
c.baseURLMu.Unlock() c.baseURLMu.Unlock()
c.clearValidationCache()
} }
func (c *Client) getBaseURL() string { func (c *Client) getBaseURL() string {
@@ -155,6 +159,33 @@ func (c *Client) setProjectKeyHeader(req *http.Request) {
} }
} }
// ForwardedForHeader carries the end user's address to AuthServer on the
// credential calls (see WithClientIP). AuthServer reads it only when the
// calling service's own address is listed in its TRUSTED_PROXIES, so sending
// it changes nothing for a deployment that has not opted in.
const ForwardedForHeader = "X-Forwarded-For"
type clientIPKey struct{}
// WithClientIP returns a context that makes Login, Register, TOTPVerify,
// TOTPDisable and the password-reset calls send ip as X-Forwarded-For, so
// AuthServer's per-address limits see the end user instead of this service.
// Pass an address the caller has already verified (for example
// auth.Service's trusted-proxy-aware client address), never a raw request
// header. Anything that is not an IP address is ignored.
func WithClientIP(ctx context.Context, ip string) context.Context {
return context.WithValue(ctx, clientIPKey{}, strings.TrimSpace(ip))
}
// setClientIPHeader attaches ForwardedForHeader when ctx carries a valid
// address from WithClientIP; a no-op otherwise.
func setClientIPHeader(ctx context.Context, req *http.Request) {
ip, _ := ctx.Value(clientIPKey{}).(string)
if parsed := net.ParseIP(ip); parsed != nil {
req.Header.Set(ForwardedForHeader, parsed.String())
}
}
func normalizeBaseURL(baseURL string) string { func normalizeBaseURL(baseURL string) string {
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/") trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if trimmed == "" { if trimmed == "" {
@@ -211,6 +242,9 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
if token == "" { if token == "" {
return nil, ErrInvalidSession return nil, ErrInvalidSession
} }
if user, cachedErr, ok := c.cachedValidation(token); ok {
return user, cachedErr
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api/session/validate", nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api/session/validate", nil)
if err != nil { if err != nil {
@@ -233,15 +267,22 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
} }
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil { if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
if resp.StatusCode == http.StatusUnauthorized { if resp.StatusCode == http.StatusUnauthorized {
c.cacheValidation(token, nil, false)
return nil, ErrInvalidSession return nil, ErrInvalidSession
} }
return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err) return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err)
} }
if resp.StatusCode != http.StatusOK || !payload.Valid { if resp.StatusCode == http.StatusUnauthorized || (resp.StatusCode == http.StatusOK && !payload.Valid) {
c.cacheValidation(token, nil, false)
return nil, ErrInvalidSession return nil, ErrInvalidSession
} }
return &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}, nil if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("authclient: AuthServer returned HTTP %d", resp.StatusCode)
}
user := &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}
c.cacheValidation(token, user, true)
return user, nil
} }
// contextKey is unexported so only this package can set/read the resolved // contextKey is unexported so only this package can set/read the resolved
@@ -451,6 +492,7 @@ func (c *Client) call(ctx context.Context, method, path, token string, body, out
req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Authorization", "Bearer "+token)
} }
c.setProjectKeyHeader(req) c.setProjectKeyHeader(req)
setClientIPHeader(ctx, req)
resp, err := c.httpClient.Do(req) resp, err := c.httpClient.Do(req)
if err != nil { if err != nil {
@@ -535,6 +577,7 @@ func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, erro
if err != nil { if err != nil {
return nil, err return nil, err
} }
c.invalidateValidation(token)
return resp.Cookies(), nil return resp.Cookies(), nil
} }
@@ -623,6 +666,9 @@ func (c *Client) CreateManagedUser(ctx context.Context, token string, input Mana
// UpdateManagedUser calls PUT /api/admin/users/{id}. // UpdateManagedUser calls PUT /api/admin/users/{id}.
func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error { func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error {
_, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil) _, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil)
if err == nil {
c.invalidateValidation(token)
}
return err return err
} }
+40
View File
@@ -110,3 +110,43 @@ func TestSetBaseURLIgnoresBlank(t *testing.T) {
t.Fatalf("SetBaseURL(blank) changed baseURL to %q, want unchanged", got) t.Fatalf("SetBaseURL(blank) changed baseURL to %q, want unchanged", got)
} }
} }
func TestWithClientIPSendsXForwardedForOnCredentialCalls(t *testing.T) {
var seen []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = append(seen, r.Header.Get(ForwardedForHeader))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"user":{"id":1,"username":"a"}}`))
}))
defer server.Close()
client := New(server.URL)
ctx := WithClientIP(context.Background(), " 203.0.113.9 ")
if _, err := client.Login(ctx, "a", "password123", ""); err != nil {
t.Fatal(err)
}
if _, err := client.Register(WithClientIP(context.Background(), "2001:db8::1"), "a", "a@b.com", "password123"); err != nil {
t.Fatal(err)
}
if err := client.TOTPVerify(ctx, "tok", "123456"); err != nil {
t.Fatal(err)
}
// No address, and values that are not IP addresses, send no header.
if _, err := client.Login(context.Background(), "a", "password123", ""); err != nil {
t.Fatal(err)
}
for _, bad := range []string{"", "not-an-ip", "203.0.113.9\r\nX-Evil: 1"} {
if _, err := client.Login(WithClientIP(context.Background(), bad), "a", "password123", ""); err != nil {
t.Fatal(err)
}
}
want := []string{"203.0.113.9", "2001:db8::1", "203.0.113.9", "", "", "", ""}
if len(seen) != len(want) {
t.Fatalf("server saw %d requests, want %d", len(seen), len(want))
}
for i := range want {
if seen[i] != want[i] {
t.Errorf("request %d X-Forwarded-For = %q, want %q", i, seen[i], want[i])
}
}
}
+78
View File
@@ -0,0 +1,78 @@
package authclient
import (
"crypto/sha256"
"time"
)
const (
validationCacheTTL = 2 * time.Second
maxValidationCacheSize = 10000
)
type validationCacheEntry struct {
user User
valid bool
expires time.Time
}
func (c *Client) cachedValidation(token string) (*User, error, bool) {
key := sha256.Sum256([]byte(token))
now := time.Now()
c.validationMu.Lock()
defer c.validationMu.Unlock()
entry, ok := c.validationCache[key]
if !ok {
return nil, nil, false
}
if !now.Before(entry.expires) {
delete(c.validationCache, key)
return nil, nil, false
}
if !entry.valid {
return nil, ErrInvalidSession, true
}
user := entry.user
return &user, nil, true
}
func (c *Client) cacheValidation(token string, user *User, valid bool) {
key := sha256.Sum256([]byte(token))
now := time.Now()
c.validationMu.Lock()
defer c.validationMu.Unlock()
if c.validationCache == nil {
c.validationCache = make(map[[32]byte]validationCacheEntry)
}
if len(c.validationCache) >= maxValidationCacheSize {
for existing, entry := range c.validationCache {
if !now.Before(entry.expires) {
delete(c.validationCache, existing)
}
}
if len(c.validationCache) >= maxValidationCacheSize {
for existing := range c.validationCache {
delete(c.validationCache, existing)
break
}
}
}
entry := validationCacheEntry{valid: valid, expires: now.Add(validationCacheTTL)}
if user != nil {
entry.user = *user
}
c.validationCache[key] = entry
}
func (c *Client) invalidateValidation(token string) {
key := sha256.Sum256([]byte(token))
c.validationMu.Lock()
delete(c.validationCache, key)
c.validationMu.Unlock()
}
func (c *Client) clearValidationCache() {
c.validationMu.Lock()
c.validationCache = make(map[[32]byte]validationCacheEntry)
c.validationMu.Unlock()
}
@@ -457,6 +457,30 @@ func thumbnailFile(id string) (string, error) {
return id + ".jpg", nil return id + ".jpg", nil
} }
// validName reports an error unless name can be used as one path segment: it must not be empty,
// ".", ".." or contain a path separator. Every push and delete helper checks its name with this.
func validName(name string) error {
if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) {
return fmt.Errorf("invalid name %q", name)
}
return nil
}
// validRelativeName is validName for outputs, inputs and copies, which may sit in nested
// directories (for example CraftStudio's "<user>/<workflow>/<file>"). It refuses an empty or
// absolute name, a backslash, and any empty, "." or ".." segment.
func validRelativeName(name string) error {
if name == "" || strings.HasPrefix(name, "/") || strings.ContainsRune(name, '\\') {
return fmt.Errorf("invalid name %q", name)
}
for _, segment := range strings.Split(name, "/") {
if segment == "" || segment == "." || segment == ".." {
return fmt.Errorf("invalid name %q", name)
}
}
return nil
}
// thumbnailPaths lists every CarrierNode path a thumbnail may live at, in lookup order: the // thumbnailPaths lists every CarrierNode path a thumbnail may live at, in lookup order: the
// project's thumbnails mount first, then CarrierNode's legacy thumbnail root. Thumbnails // project's thumbnails mount first, then CarrierNode's legacy thumbnail root. Thumbnails
// stored before the mount existed sit in the legacy root, and reads keep finding them there // stored before the mount existed sit in the legacy root, and reads keep finding them there
@@ -670,6 +694,9 @@ func pushedSize(response *http.Response) int64 {
// PushThumbnail uploads a locally-generated thumbnail to CarrierNode. // PushThumbnail uploads a locally-generated thumbnail to CarrierNode.
func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64, error) { func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
if err := validName(id); err != nil {
return 0, err
}
response, err := c.push(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath) response, err := c.push(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil { if err != nil {
return 0, err return 0, err
@@ -680,6 +707,9 @@ func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64
// DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as // DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as
// already-deleted, not an error. Always targets the primary instance. // already-deleted, not an error. Always targets the primary instance.
func (c *Client) DeleteThumbnail(ctx context.Context, id string) error { func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
if err := validName(id); err != nil {
return err
}
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil) request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil { if err != nil {
return err return err
@@ -698,6 +728,9 @@ func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
// PushOutput uploads a locally-produced output file (e.g. a converted or // PushOutput uploads a locally-produced output file (e.g. a converted or
// generated media file) to CarrierNode's OutputRoot. // generated media file) to CarrierNode's OutputRoot.
func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64, error) { func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64, error) {
if err := validRelativeName(name); err != nil {
return 0, err
}
response, err := c.push(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath) response, err := c.push(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil { if err != nil {
return 0, err return 0, err
@@ -707,6 +740,9 @@ func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64,
// PushInput uploads a local file to CarrierNode's InputRoot. // PushInput uploads a local file to CarrierNode's InputRoot.
func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64, error) { func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64, error) {
if err := validRelativeName(name); err != nil {
return 0, err
}
response, err := c.push(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath) response, err := c.push(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil { if err != nil {
return 0, err return 0, err
@@ -716,6 +752,9 @@ func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64,
// PushCopy uploads a local file to CarrierNode's CopyRoot. // PushCopy uploads a local file to CarrierNode's CopyRoot.
func (c *Client) PushCopy(ctx context.Context, name, localPath string) (int64, error) { func (c *Client) PushCopy(ctx context.Context, name, localPath string) (int64, error) {
if err := validRelativeName(name); err != nil {
return 0, err
}
response, err := c.push(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath) response, err := c.push(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil { if err != nil {
return 0, err return 0, err
@@ -181,3 +181,58 @@ func TestThumbnailIDsCannotEscapeTheThumbnailsDirectory(t *testing.T) {
t.Fatalf("invalid thumbnail ids reached CarrierNode: %v", got) t.Fatalf("invalid thumbnail ids reached CarrierNode: %v", got)
} }
} }
// TestPushAndDeleteNamesCannotEscapeTheirDirectory checks that the push and delete helpers refuse
// names that are "." or ".." or contain a separator before any request reaches CarrierNode.
func TestPushAndDeleteNamesCannotEscapeTheirDirectory(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
ctx := context.Background()
local := filepath.Join(t.TempDir(), "payload.bin")
if err := os.WriteFile(local, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
for _, name := range []string{"", ".", "..", "../escape", `..\escape`, "nested/name"} {
if _, err := client.PushThumbnail(ctx, name, local); err == nil {
t.Errorf("PushThumbnail accepted name %q", name)
}
if err := client.DeleteThumbnail(ctx, name); err == nil {
t.Errorf("DeleteThumbnail accepted name %q", name)
}
}
// Outputs, inputs and copies may nest, but no segment may climb out of its directory.
for _, name := range []string{"", ".", "..", "../escape", `..\escape`, "/abs", "a//b", "a/../b", "a/./b", "a/"} {
if _, err := client.PushOutput(ctx, name, local); err == nil {
t.Errorf("PushOutput accepted name %q", name)
}
if _, err := client.PushInput(ctx, name, local); err == nil {
t.Errorf("PushInput accepted name %q", name)
}
if _, err := client.PushCopy(ctx, name, local); err == nil {
t.Errorf("PushCopy accepted name %q", name)
}
}
if got := node.seen(); len(got) != 0 {
t.Fatalf("invalid names reached CarrierNode: %v", got)
}
}
// TestNestedOutputNamesAreAccepted checks that CraftStudio-style nested output names pass the
// relative-name check, so generator outputs keep their CarrierNode path.
func TestNestedOutputNamesAreAccepted(t *testing.T) {
for _, name := range []string{"CraftStudio/alice/flux/out.png", "a/b.txt"} {
if err := validRelativeName(name); err != nil {
t.Errorf("validRelativeName(%q) = %v, want nil", name, err)
}
}
}
// TestValidNamesAreNotRefused checks that ordinary names, including ones with spaces or query
// characters, pass the name check; the path escaping in MountPath and the push helpers handles them.
func TestValidNamesAreNotRefused(t *testing.T) {
for _, name := range []string{"clip.mp4", "my clip?.mp4", "a#b", "v1.2.final"} {
if err := validName(name); err != nil {
t.Errorf("validName(%q) = %v, want nil", name, err)
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package config
import (
"testing"
"time"
)
func TestStringTrimsAndFallsBack(t *testing.T) {
t.Setenv("CFG_TEST_STRING", " value ")
if got := String("CFG_TEST_STRING", "fallback"); got != "value" {
t.Fatalf("String = %q, want the trimmed value", got)
}
t.Setenv("CFG_TEST_STRING", " ")
if got := String("CFG_TEST_STRING", "fallback"); got != "fallback" {
t.Fatalf("String of a blank value = %q, want the fallback", got)
}
if got := String("CFG_TEST_UNSET", "fallback"); got != "fallback" {
t.Fatalf("String of an unset variable = %q, want the fallback", got)
}
}
func TestRequiredNamesTheMissingVariable(t *testing.T) {
t.Setenv("CFG_TEST_REQUIRED", " secret ")
if got, err := Required("CFG_TEST_REQUIRED"); err != nil || got != "secret" {
t.Fatalf("Required = %q, %v; want the trimmed value", got, err)
}
t.Setenv("CFG_TEST_REQUIRED", " ")
if _, err := Required("CFG_TEST_REQUIRED"); err == nil || err.Error() != "CFG_TEST_REQUIRED is required" {
t.Fatalf("Required of a blank value error = %v, want it to name the variable", err)
}
}
func TestBoolIntAndDurationFallBackOnInvalidValues(t *testing.T) {
t.Setenv("CFG_TEST_BOOL", "true")
t.Setenv("CFG_TEST_INT", " 42 ")
t.Setenv("CFG_TEST_DURATION", "1m30s")
if !Bool("CFG_TEST_BOOL", false) || Int("CFG_TEST_INT", 0) != 42 || Duration("CFG_TEST_DURATION", 0) != 90*time.Second {
t.Fatal("valid values were not parsed")
}
t.Setenv("CFG_TEST_BOOL", "maybe")
t.Setenv("CFG_TEST_INT", "4x")
t.Setenv("CFG_TEST_DURATION", "soon")
if !Bool("CFG_TEST_BOOL", true) || Bool("CFG_TEST_BOOL", false) {
t.Fatal("an invalid boolean did not fall back")
}
if Int("CFG_TEST_INT", 7) != 7 || Duration("CFG_TEST_DURATION", time.Second) != time.Second {
t.Fatal("an invalid integer or duration did not fall back")
}
t.Setenv("CFG_TEST_BOOL", "")
t.Setenv("CFG_TEST_INT", "")
t.Setenv("CFG_TEST_DURATION", "")
if !Bool("CFG_TEST_BOOL", true) || Int("CFG_TEST_INT", 7) != 7 || Duration("CFG_TEST_DURATION", time.Second) != time.Second {
t.Fatal("an empty value did not fall back")
}
}
+25 -1
View File
@@ -11,8 +11,11 @@
package coreconfig package coreconfig
import ( import (
"crypto/subtle"
"encoding/json" "encoding/json"
"errors"
"net/http" "net/http"
"net/url"
"strings" "strings"
"sync" "sync"
) )
@@ -179,7 +182,7 @@ func normalizeInfo(info Info) Info {
// own internal-auth-gated routes use). // 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 == "" || r.Header.Get("X-Internal-Auth") != secret { if secret == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 {
writeError(w, http.StatusUnauthorized, "internal service authentication required") writeError(w, http.StatusUnauthorized, "internal service authentication required")
return return
} }
@@ -188,6 +191,10 @@ func Handler(secret string, store *Store) http.HandlerFunc {
writeError(w, http.StatusBadRequest, "invalid JSON body") writeError(w, http.StatusBadRequest, "invalid JSON body")
return return
} }
if err := validateServiceURLs(input); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
store.Set(input) store.Set(input)
// Do not echo service credentials to the caller. The push is authenticated, but // Do not echo service credentials to the caller. The push is authenticated, but
// these credentials are needed only by the recipient. // these credentials are needed only by the recipient.
@@ -198,6 +205,23 @@ func Handler(secret string, store *Store) http.HandlerFunc {
} }
} }
// validateServiceURLs refuses a pushed URL that is not an http or https URL with a host, so a push
// cannot point this service's clients at another scheme or at an empty host.
func validateServiceURLs(info Info) error {
urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL}, info.CarrierNodeURLs...)
for _, raw := range urls {
value := strings.TrimSpace(raw)
if value == "" {
continue
}
parsed, err := url.Parse(value)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
return errors.New("core service URL must be an http or https URL with a host")
}
}
return nil
}
func writeJSON(w http.ResponseWriter, status int, value any) { func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status) w.WriteHeader(status)
+23
View File
@@ -149,3 +149,26 @@ func TestHandlerAppliesPushedInfo(t *testing.T) {
t.Fatal("response echoed the ContentScanner secret") t.Fatal("response echoed the ContentScanner secret")
} }
} }
func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
store := NewStore(Info{AuthGuardURL: "http://auth.example.com"})
handler := Handler("s3cret", store)
for _, bad := range []Info{
{AuthGuardURL: "javascript:alert(1)"},
{AuthGuardURL: "auth.example.com"},
{CarrierNodeURLs: []string{"http://carrier.example.com", "file:///etc/passwd"}},
{ContentScannerURL: "http://"},
} {
body, _ := json.Marshal(bad)
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", "s3cret")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d for %+v, want 400", rec.Code, bad)
}
}
if got := store.Get(); got.AuthGuardURL != "http://auth.example.com" || len(got.CarrierNodeURLs) != 0 {
t.Fatalf("store changed by a rejected push: %+v", got)
}
}
+1 -1
View File
@@ -18,5 +18,5 @@ require (
github.com/sethvargo/go-retry v0.4.0 // indirect github.com/sethvargo/go-retry v0.4.0 // indirect
go.uber.org/multierr v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sync v0.22.0 // indirect golang.org/x/sync v0.22.0 // indirect
golang.org/x/text v0.40.0 // indirect golang.org/x/text v0.41.0 // indirect
) )
+2
View File
@@ -46,6 +46,8 @@ golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+300
View File
@@ -0,0 +1,300 @@
package logshipper
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
)
// captureStd runs fn with os.Stdout and os.Stderr redirected, and returns what it wrote to each.
func captureStd(t *testing.T, fn func()) (stdout, stderr string) {
t.Helper()
oldOut, oldErr := os.Stdout, os.Stderr
outR, outW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
errR, errW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stdout, os.Stderr = outW, errW
defer func() { os.Stdout, os.Stderr = oldOut, oldErr }()
fn()
outW.Close()
errW.Close()
os.Stdout, os.Stderr = oldOut, oldErr
outBytes, _ := io.ReadAll(outR)
errBytes, _ := io.ReadAll(errR)
return string(outBytes), string(errBytes)
}
// ingest is a stand-in OmniLogger that records every batch it is sent.
type ingest struct {
mu sync.Mutex
batches [][]wireEntry
auth []string
status int
server *httptest.Server
}
func newIngest(t *testing.T, status int) *ingest {
t.Helper()
in := &ingest{status: status}
in.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var batch []wireEntry
_ = json.NewDecoder(r.Body).Decode(&batch)
in.mu.Lock()
in.batches = append(in.batches, batch)
in.auth = append(in.auth, r.Method+" "+r.URL.Path+" "+r.Header.Get("Authorization"))
in.mu.Unlock()
w.WriteHeader(in.status)
}))
t.Cleanup(in.server.Close)
return in
}
func (in *ingest) entries() []wireEntry {
in.mu.Lock()
defer in.mu.Unlock()
var all []wireEntry
for _, batch := range in.batches {
all = append(all, batch...)
}
return all
}
// newTestShipper keeps the background loop quiet so a test decides when entries are sent, and
// points a shipper that names no sink at a throwaway one so closing it prints nothing.
func newTestShipper(t *testing.T, cfg Config) *Shipper {
t.Helper()
if cfg.FlushInterval == 0 {
cfg.FlushInterval = time.Hour
}
if cfg.BaseURL == "" {
cfg.BaseURL = newIngest(t, http.StatusAccepted).server.URL
}
return New(cfg)
}
func TestLevelOfAcceptsTheSharedLogVocabulary(t *testing.T) {
cases := map[string]Level{
"debug": LevelDebug, " DEBUG ": LevelDebug, "info": LevelInfo, "": LevelInfo, "bogus": LevelInfo,
"warn": LevelWarn, "warning": LevelWarn, "error": LevelError, "critical": LevelCritical,
"silent": LevelSilent, "none": LevelSilent, "off": LevelSilent,
}
for input, want := range cases {
if got := levelOf(input); got != want {
t.Errorf("levelOf(%q) = %d, want %d", input, got, want)
}
}
}
func TestSevNameGivesTheLowercaseNameOmniLoggerExpects(t *testing.T) {
for sev, want := range map[Level][2]string{
LevelDebug: {"DEBUG", "debug"}, LevelInfo: {"INFO", "info"}, LevelWarn: {"WARN", "warn"},
LevelError: {"ERROR", "error"}, LevelCritical: {"CRITICAL", "critical"},
} {
if upper, lower := sevName(sev); upper != want[0] || lower != want[1] {
t.Errorf("sevName(%d) = %q, %q; want %q, %q", sev, upper, lower, want[0], want[1])
}
}
}
func TestFormatArgsJoinsErrorsStringsAndValues(t *testing.T) {
got := formatArgs([]any{"failed:", errors.New("boom"), 42, map[string]int{"a": 1}, make(chan int)})
if !strings.HasPrefix(got, `failed: boom 42 {"a":1} `) {
t.Fatalf("formatArgs = %q", got)
}
if formatArgs(nil) != "" {
t.Fatal("formatArgs(nil) is not empty")
}
}
func TestScrubIDsDropsIdentifierFieldsFromTheLocalDump(t *testing.T) {
ctx := map[string]any{
"id": 1, "userId": 2, "user_id": 3, "requestID": "r", "path": "/x", "status": 200, "ok": true,
}
got := scrubIDs(ctx)
if len(got) != 3 || got["path"] != "/x" || got["status"] != 200 || got["ok"] != true {
t.Fatalf("scrubIDs = %v, want only path, status and ok", got)
}
if len(ctx) != 7 {
t.Fatal("scrubIDs modified its input")
}
}
func TestEmitGatesOnTheThresholdAndWritesTheLocalLine(t *testing.T) {
shipper := newTestShipper(t, Config{Service: "svc", Module: "mod", Level: "warn"})
defer shipper.Close()
stdout, stderr := captureStd(t, func() {
shipper.Info("below threshold")
shipper.Warn("warned")
shipper.Error("failed", errors.New("boom"))
})
if stdout != "" {
t.Fatalf("stdout = %q, want nothing", stdout)
}
if strings.Contains(stderr, "below threshold") || !strings.Contains(stderr, "[WARN] [mod] warned") || !strings.Contains(stderr, "[ERROR] [mod] failed boom") {
t.Fatalf("stderr = %q", stderr)
}
if got := len(shipper.buffer); got != 2 {
t.Fatalf("buffered %d entries, want the 2 at or above the threshold", got)
}
}
func TestSilentLevelWritesAndBuffersNothing(t *testing.T) {
shipper := newTestShipper(t, Config{Service: "svc", Level: "silent"})
defer shipper.Close()
stdout, stderr := captureStd(t, func() {
shipper.Critical("never shown")
})
if stdout != "" || stderr != "" || len(shipper.buffer) != 0 {
t.Fatalf("silent shipper wrote %q / %q and buffered %d entries", stdout, stderr, len(shipper.buffer))
}
}
func TestLogAllScrubsIDsLocallyButShipsTheFullContext(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", LogAll: true})
defer shipper.Close()
stdout, _ := captureStd(t, func() {
shipper.InfoCtx(map[string]any{"userId": 7, "path": "/x"}, "request")
})
if !strings.Contains(stdout, `[DETAILS] {"path":"/x"}`) || strings.Contains(stdout, "userId") {
t.Fatalf("local dump = %q, want the ID scrubbed", stdout)
}
shipper.Flush()
entries := in.entries()
if len(entries) != 1 || !strings.Contains(string(entries[0].Context), `"userId":7`) {
t.Fatalf("shipped entries = %+v, want the unscrubbed context", entries)
}
}
func TestAuditShipsAnInfoEntryWithTheDetails(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
defer shipper.Close()
captureStd(t, func() { shipper.Audit("login", map[string]any{"user": "a"}) })
shipper.Flush()
entries := in.entries()
if len(entries) != 1 || entries[0].Level != "info" || !strings.HasPrefix(entries[0].Message, "audit:login") {
t.Fatalf("entries = %+v", entries)
}
}
func TestFlushSendsOneAuthenticatedBatchAndEmptiesTheBuffer(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL + "/", IngestToken: "secret", Service: "svc"})
defer shipper.Close()
captureStd(t, func() {
shipper.Info("one")
shipper.Error("two")
})
shipper.Flush()
shipper.Flush() // nothing left: no second request
in.mu.Lock()
defer in.mu.Unlock()
if len(in.batches) != 1 || len(in.batches[0]) != 2 {
t.Fatalf("batches = %+v, want one batch of two entries", in.batches)
}
if in.auth[0] != "POST /api/logs Bearer secret" {
t.Fatalf("request = %q", in.auth[0])
}
first := in.batches[0][0]
if first.Service != "svc" || first.Level != "info" || first.Message != "one" || first.OccurredAt.IsZero() {
t.Fatalf("first entry = %+v", first)
}
}
func TestBufferDropsNewEntriesOnceFullInsteadOfBlocking(t *testing.T) {
shipper := newTestShipper(t, Config{Service: "svc", BufferCapacity: 3, MaxBatchSize: 1000})
defer shipper.Close()
_, stderr := captureStd(t, func() {
for i := 0; i < 10; i++ {
shipper.enqueue(wireEntry{Message: "m"})
}
})
if len(shipper.buffer) != 3 {
t.Fatalf("buffer holds %d entries, want the capacity of 3", len(shipper.buffer))
}
if strings.Count(stderr, "buffer full") != 1 {
t.Fatalf("stderr = %q, want the full-buffer warning exactly once", stderr)
}
}
func TestReachingTheBatchSizeFlushesWithoutWaitingForTheInterval(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", MaxBatchSize: 2})
defer shipper.Close()
captureStd(t, func() {
shipper.Info("a")
shipper.Info("b")
})
deadline := time.Now().Add(5 * time.Second)
for len(in.entries()) < 2 {
if time.Now().After(deadline) {
t.Fatal("a full batch was not flushed ahead of the interval")
}
time.Sleep(10 * time.Millisecond)
}
}
func TestCloseFlushesWhatIsLeft(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
captureStd(t, func() { shipper.Info("last words") })
if err := shipper.Close(); err != nil {
t.Fatal(err)
}
if err := shipper.Close(); err != nil {
t.Fatalf("second Close error = %v", err)
}
if entries := in.entries(); len(entries) != 1 || entries[0].Message != "last words" {
t.Fatalf("entries after Close = %+v", entries)
}
}
func TestAFailingSinkNeverFailsTheCallerAndWarnsOnlyOnce(t *testing.T) {
in := newIngest(t, http.StatusInternalServerError)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
defer shipper.Close()
_, stderr := captureStd(t, func() {
shipper.Info("one")
shipper.Flush()
shipper.Info("two")
shipper.Flush()
})
if strings.Count(stderr, "OmniLogger rejected") != 1 {
t.Fatalf("stderr = %q, want one rate-limited warning", stderr)
}
in.server.Close()
_, stderr = captureStd(t, func() {
shipper.Info("three")
shipper.Flush() // the sink is gone: swallowed, and still inside the warning interval
})
if strings.Contains(stderr, "send 1 entries") {
t.Fatalf("stderr = %q, want the second warning suppressed", stderr)
}
}
func TestNewAppliesDefaults(t *testing.T) {
shipper := New(Config{BaseURL: "http://omni:8090///", IngestToken: "t", Service: "svc"})
defer shipper.Close()
if shipper.url != "http://omni:8090/api/logs" || shipper.module != "svc" || shipper.threshold != LevelInfo {
t.Fatalf("url = %q, module = %q, threshold = %d", shipper.url, shipper.module, shipper.threshold)
}
if shipper.maxBatch != defaultMaxBatchSize || shipper.bufCap != defaultBufferCapacity || shipper.client == nil {
t.Fatalf("defaults not applied: %+v", shipper)
}
}
+90 -11
View File
@@ -51,6 +51,10 @@ import (
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket" "repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
) )
// maxPlaylistReorderItems caps one reorder request. The reorder runs as a single statement, so the
// cap bounds its size; a playlist longer than this is reordered in more than one request.
const maxPlaylistReorderItems = 10000
// Config wires a Core to the rest of one service's dependencies. // Config wires a Core to the rest of one service's dependencies.
type Config struct { type Config struct {
DB *pgxpool.Pool DB *pgxpool.Pool
@@ -157,6 +161,8 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
state["playAt"] = playAt state["playAt"] = playAt
} }
c.sync.SetHTTPState(sessionID, state) c.sync.SetHTTPState(sessionID, state)
// Broadcast queues immutable messages without waiting for network writes, so a slow
// websocket peer does not hold this response or create one goroutine per request.
c.sync.Broadcast(sessionID) c.sync.Broadcast(sessionID)
writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state}) writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state})
} }
@@ -194,7 +200,12 @@ func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, ide
writeError(w, http.StatusNotFound, "media not found") writeError(w, http.StatusNotFound, "media not found")
return return
} }
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath)) upstream, ok := upstreamMediaPath(record.FilePath)
if !ok {
writeError(w, http.StatusNotFound, "media not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+upstream)
} }
func (c *Core) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) { func (c *Core) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) {
@@ -222,9 +233,9 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
SELECT t.id::text SELECT t.id::text
FROM thumbnails t FROM thumbnails t
JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE m.media_key=$1 OR CAST(m.id AS TEXT)=$1 WHERE m.media_key=$1 OR m.id=$2
ORDER BY t.created_at DESC ORDER BY t.created_at DESC
LIMIT 1`, id).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) { LIMIT 1`, id, mediaIDArg(id)).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) {
// A row whose file CarrierNode no longer has falls through to the original image below, // A row whose file CarrierNode no longer has falls through to the original image below,
// rather than proxying CarrierNode's 404. // rather than proxying CarrierNode's 404.
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, thumbnailID) { if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, thumbnailID) {
@@ -236,7 +247,12 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
writeError(w, http.StatusNotFound, "thumbnail not found") writeError(w, http.StatusNotFound, "thumbnail not found")
return return
} }
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath)) upstream, ok := upstreamMediaPath(record.FilePath)
if !ok {
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+upstream)
} }
func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) { func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) {
@@ -390,9 +406,9 @@ func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) {
func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) { func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) {
key := strings.TrimSpace(chi.URLParam(r, "id")) key := strings.TrimSpace(chi.URLParam(r, "id"))
rows, err := c.db.Query(r.Context(), ` rows, err := c.db.Query(r.Context(), `
SELECT tag, COALESCE(SUM(vote), 0) AS score SELECT mt.tag, COALESCE(SUM(mv.vote), 0) AS score
FROM media_tags mt LEFT JOIN media_tag_votes mv ON mv.media_key = mt.media_key AND LOWER(mv.tag) = LOWER(mt.tag) FROM media_tags mt LEFT JOIN media_tag_votes mv ON mv.media_key = mt.media_key AND LOWER(mv.tag) = LOWER(mt.tag)
WHERE mt.media_key = $1 GROUP BY tag ORDER BY score DESC, LOWER(tag)`, key) WHERE mt.media_key = $1 GROUP BY mt.tag ORDER BY score DESC, LOWER(mt.tag)`, key)
if err != nil { if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}}) writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}})
return return
@@ -723,8 +739,31 @@ func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) {
if len(ids) == 0 { if len(ids) == 0 {
ids = input.ItemIDs ids = input.ItemIDs
} }
for position, itemID := range ids { if len(ids) > maxPlaylistReorderItems {
_, _ = c.db.Exec(r.Context(), `UPDATE playlist_items SET position=$1 WHERE id=$2 AND playlist_id=$3 AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, position, itemID, id, user.ID) writeError(w, http.StatusBadRequest, "too many items to reorder")
return
}
positions := make([]int32, len(ids))
for position := range ids {
positions[position] = int32(position)
}
tx, err := c.db.Begin(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
return
}
defer func() { _ = tx.Rollback(r.Context()) }()
if _, err := tx.Exec(r.Context(), `
UPDATE playlist_items AS i SET position=v.position
FROM unnest($1::bigint[], $2::int[]) AS v(item_id, position)
WHERE i.id=v.item_id AND i.playlist_id=$3
AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, ids, positions, id, user.ID); err != nil {
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
return
}
if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
return
} }
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered")) writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered"))
} }
@@ -749,8 +788,8 @@ func canSeeHidden(r *http.Request) bool {
func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool { func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
var hidden bool var hidden bool
err := c.db.QueryRow(ctx, ` err := c.db.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR CAST(id AS TEXT)=$1))`, SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR id=$2))`,
strings.TrimSpace(identifier)).Scan(&hidden) strings.TrimSpace(identifier), mediaIDArg(strings.TrimSpace(identifier))).Scan(&hidden)
return err != nil || hidden return err != nil || hidden
} }
@@ -765,7 +804,7 @@ 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 CAST(id AS TEXT)=$1) AND (active OR $2) LIMIT 1`, identifier, includeHidden) FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) LIMIT 1`, identifier, mediaIDArg(identifier), includeHidden)
var title, description string var title, description string
var width, height int var width, height int
var duration, size int64 var duration, size int64
@@ -1029,6 +1068,46 @@ func urlPath(value string) string {
return value return value
} }
// upstreamMediaPath returns the escaped CarrierNode path for a stored file path. It reports false
// when the stored path is not a safe relative path, or when it contains a query or fragment marker
// that CarrierNode would read as the end of the path.
func upstreamMediaPath(filePath string) (string, bool) {
relative := urlPath(filePath)
if !SafeRelative(relative) || strings.ContainsAny(relative, "?#") {
return "", false
}
// Escape each segment so percent-escapes and other reserved characters in a stored name
// reach CarrierNode as literal text, not as an escape or a traversal it decodes later.
segments := strings.Split(relative, "/")
for i, segment := range segments {
segments[i] = url.PathEscape(segment)
}
return strings.Join(segments, "/"), true
}
// canonicalMediaID returns the numeric media id that identifier spells exactly. Leading zeros, signs
// and whitespace are not canonical, so they never match an id.
func canonicalMediaID(identifier string) (int64, bool) {
if identifier == "" || strings.Trim(identifier, "0123456789") != "" {
return 0, false
}
id, err := strconv.ParseInt(identifier, 10, 64)
if err != nil || strconv.FormatInt(id, 10) != identifier {
return 0, false
}
return id, true
}
// mediaIDArg is the id query argument for identifier: the id when identifier is a canonical number,
// otherwise NULL, which matches no row. Comparing the id column directly, instead of casting it to
// text, lets the planner use the primary-key index for the id arm.
func mediaIDArg(identifier string) any {
if id, ok := canonicalMediaID(identifier); ok {
return id
}
return nil
}
func firstNonEmpty(values ...string) string { func firstNonEmpty(values ...string) string {
for _, value := range values { for _, value := range values {
if strings.TrimSpace(value) != "" { if strings.TrimSpace(value) != "" {
+101
View File
@@ -0,0 +1,101 @@
package mediacore
import (
"errors"
"os"
"path/filepath"
"testing"
)
func TestSafeRelativeRejectsTraversalAndAbsolutePaths(t *testing.T) {
for _, value := range []string{"", ".", "..", "../x", "a/../../x", "sub/../a.mp4x", "/etc/passwd", `\etc\passwd`, `C:\x`, "a\x00b"} {
if SafeRelative(value) {
t.Errorf("SafeRelative(%q) = true, want false", value)
}
}
for _, value := range []string{"a.mp4", "sub/b.mp4", "v1..2/clip.mp4"} {
if !SafeRelative(value) {
t.Errorf("SafeRelative(%q) = false, want true", value)
}
}
}
func TestResolveUnderRootsStaysInsideTheRoots(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "sub"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "a.mp4"), []byte("a"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "sub", "b.mp4"), []byte("b"), 0o600); err != nil {
t.Fatal(err)
}
outside := filepath.Join(t.TempDir(), "secret.txt")
if err := os.WriteFile(outside, []byte("s"), 0o600); err != nil {
t.Fatal(err)
}
_ = os.Symlink(outside, filepath.Join(root, "link.txt"))
for value, want := range map[string]string{
"a.mp4": filepath.Join(root, "a.mp4"),
"/media/a.mp4": filepath.Join(root, "a.mp4"),
"sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
"/media/sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
} {
got, err := ResolveUnderRoots(value, []string{root})
if err != nil || got != want {
t.Errorf("ResolveUnderRoots(%q) = %q, %v; want %q", value, got, err, want)
}
}
for _, value := range []string{"../secret.txt", "sub", "missing.mp4", "link.txt", "", "a\x00b"} {
if _, err := ResolveUnderRoots(value, []string{root}); err == nil {
t.Errorf("ResolveUnderRoots(%q) resolved, want an error", value)
}
}
if _, err := ResolveUnderRoots("missing.mp4", []string{root}); !errors.Is(err, os.ErrNotExist) {
t.Errorf("missing file error = %v, want os.ErrNotExist", err)
}
}
func TestUpstreamMediaPathRefusesQueryFragmentAndTraversal(t *testing.T) {
for _, stored := range []string{"x?y.mp4", "a#b.mp4", "../x.mp4", "media/../../x.mp4", `..\x.mp4`} {
if _, ok := upstreamMediaPath(stored); ok {
t.Errorf("upstreamMediaPath(%q) accepted, want refused", stored)
}
}
}
func TestUpstreamMediaPathEscapesEachSegment(t *testing.T) {
cases := map[string]string{
"clips/clip.mp4": "clips/clip.mp4",
"my clip.mp4": "my%20clip.mp4",
"100%.mp4": "100%25.mp4",
"media/a b/c.mp4": "a%20b/c.mp4",
"/leading.mp4": "leading.mp4",
}
for stored, want := range cases {
got, ok := upstreamMediaPath(stored)
if !ok || got != want {
t.Errorf("upstreamMediaPath(%q) = %q, %v; want %q", stored, got, ok, want)
}
}
}
func TestCanonicalMediaIDAcceptsOnlyCanonicalDecimals(t *testing.T) {
for _, value := range []string{"", "007", "+1", "-1", "4a", " 4", "4 ", "99999999999999999999"} {
if id, ok := canonicalMediaID(value); ok {
t.Errorf("canonicalMediaID(%q) = %d, want refused", value, id)
}
}
if id, ok := canonicalMediaID("42"); !ok || id != 42 {
t.Errorf("canonicalMediaID(42) = %d, %v; want 42, true", id, ok)
}
if mediaIDArg("abc") != nil {
t.Error("mediaIDArg(non-numeric) is not NULL")
}
if mediaIDArg("42") != int64(42) {
t.Error("mediaIDArg(42) is not 42")
}
}
+483
View File
@@ -0,0 +1,483 @@
package mediacore
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
)
// The tests in this file run the media routes against a real PostgreSQL database and a stand-in
// CarrierNode. They create the media tables and a few rows, so they are skipped unless
// SHARED_TEST_DATABASE_URL points at a scratch database, for example:
//
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./mediacore/
const (
aliceID = 9101
bobID = 9102
modID = 9103
)
// newIdentityAuthGuard answers GET /api/me for three fixed sessions: two ordinary users and a moderator.
func newIdentityAuthGuard(t *testing.T) *httptest.Server {
t.Helper()
people := map[string]struct {
id int64
role string
}{"alice-token": {aliceID, "user"}, "bob-token": {bobID, "user"}, "mod-token": {modID, "moderator"}}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
person, ok := people[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
if !ok || r.URL.Path != "/api/me" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"user":{"id":%d,"username":"u%d","role":%q}}`, person.id, person.id, person.role)
}))
t.Cleanup(server.Close)
return server
}
// stubCarrierNode serves a body for every /media/ path and 404s the rest, recording what it was asked.
type stubCarrierNode struct {
mu sync.Mutex
requests []string
}
func (n *stubCarrierNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
n.mu.Lock()
n.requests = append(n.requests, r.Method+" "+r.URL.EscapedPath())
n.mu.Unlock()
if !strings.HasPrefix(r.URL.Path, "/media/") {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, "BYTES")
}
}
func (n *stubCarrierNode) seen() []string {
n.mu.Lock()
defer n.mu.Unlock()
return append([]string(nil), n.requests...)
}
type dbHarness struct {
pool *pgxpool.Pool
router chi.Router
carrier *stubCarrierNode
hub *syncsocket.Hub
}
func newDBHarness(t *testing.T) *dbHarness {
t.Helper()
url := os.Getenv("SHARED_TEST_DATABASE_URL")
if url == "" {
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres route tests")
}
ctx := context.Background()
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(pool.Close)
carrier := &stubCarrierNode{}
carrierServer := httptest.NewServer(carrier)
t.Cleanup(carrierServer.Close)
guard := newIdentityAuthGuard(t)
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
hub := syncsocket.NewHub()
core := New(Config{
DB: pool,
Auth: auth,
Sync: hub,
CarrierNode: carriernodeclient.New("", func(context.Context) string { return carrierServer.URL }),
ServiceName: "routes-test",
})
if err := core.Migrate(ctx); err != nil {
t.Fatalf("Migrate() error = %v", err)
}
cleanup := func() {
for _, statement := range []string{
`DELETE FROM playlists WHERE user_id IN (9101, 9102, 9103)`,
`DELETE FROM media_stats WHERE media_key LIKE 'rt-%' OR user_id IN (9101, 9102, 9103)`,
`DELETE FROM media_view_sessions WHERE media_key LIKE 'rt-%'`,
`DELETE FROM media_tag_votes WHERE media_key LIKE 'rt-%'`,
`DELETE FROM media_tags WHERE media_key LIKE 'rt-%'`,
`DELETE FROM media WHERE media_key LIKE 'rt-%'`,
`DELETE FROM users WHERE id IN (9101, 9102, 9103)`,
} {
if _, err := pool.Exec(ctx, statement); err != nil {
t.Fatalf("cleanup %q: %v", statement, err)
}
}
}
cleanup()
t.Cleanup(cleanup)
for _, id := range []int64{aliceID, bobID, modID} {
if _, err := pool.Exec(ctx, `INSERT INTO users (id, email, username, password_hash) VALUES ($1, $2, $3, 'x')`, id, fmt.Sprintf("rt%d@example.com", id), fmt.Sprintf("rt%d", id)); err != nil {
t.Fatalf("insert user: %v", err)
}
}
router := chi.NewRouter()
core.Mount(router)
return &dbHarness{pool: pool, router: router, carrier: carrier, hub: hub}
}
func (h *dbHarness) insertMedia(t *testing.T, key, mediaType, filePath string, active bool) {
t.Helper()
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media (media_key, media_type, file_path, active) VALUES ($1, $2, $3, $4)`, key, mediaType, filePath, active); err != nil {
t.Fatalf("insert media %s: %v", key, err)
}
}
func (h *dbHarness) do(method, target, token, body string) *httptest.ResponseRecorder {
var reader io.Reader
if body != "" {
reader = strings.NewReader(body)
}
request := httptest.NewRequest(method, target, reader)
if token != "" {
request.AddCookie(&http.Cookie{Name: "auth_session", Value: token})
}
response := httptest.NewRecorder()
h.router.ServeHTTP(response, request)
return response
}
func decode(t *testing.T, response *httptest.ResponseRecorder) map[string]any {
t.Helper()
var out map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &out); err != nil {
t.Fatalf("body %q is not JSON: %v", response.Body.String(), err)
}
return out
}
func dataOf(t *testing.T, response *httptest.ResponseRecorder) map[string]any {
t.Helper()
data, _ := decode(t, response)["data"].(map[string]any)
if data == nil {
t.Fatalf("response %s has no data object", response.Body.String())
}
return data
}
func TestMediaStreamAndThumbnailAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
h.insertMedia(t, "rt-visible", "video", "folder/clip one.mp4", true)
h.insertMedia(t, "rt-hidden", "video", "secret.mp4", false)
h.insertMedia(t, "rt-image", "image", "pics/photo.jpg", true)
h.insertMedia(t, "rt-escape", "video", "../etc/passwd", true)
h.insertMedia(t, "rt-query", "video", "a?b.mp4", true)
var visibleID int64
if err := h.pool.QueryRow(context.Background(), `SELECT id FROM media WHERE media_key='rt-visible'`).Scan(&visibleID); err != nil {
t.Fatal(err)
}
t.Run("an anonymous caller is refused while login is required", func(t *testing.T) {
if code := h.do(http.MethodGet, "/media/stream?mediaKey=rt-visible", "", "").Code; code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", code)
}
})
t.Run("a stored path reaches CarrierNode escaped, by key or by id, for GET and HEAD", func(t *testing.T) {
for _, target := range []string{"/media/stream?mediaKey=rt-visible", fmt.Sprintf("/media/stream?id=%d", visibleID)} {
response := h.do(http.MethodGet, target, "alice-token", "")
if response.Code != http.StatusOK || response.Body.String() != "BYTES" {
t.Fatalf("GET %s = %d %q, want the proxied bytes", target, response.Code, response.Body.String())
}
}
if response := h.do(http.MethodHead, "/media/stream?mediaKey=rt-visible", "alice-token", ""); response.Code != http.StatusOK || response.Body.Len() != 0 {
t.Fatalf("HEAD = %d with %d body bytes, want 200 and none", response.Code, response.Body.Len())
}
for _, request := range h.carrier.seen() {
if request != "GET /media/folder/clip%20one.mp4" && request != "HEAD /media/folder/clip%20one.mp4" {
t.Fatalf("CarrierNode saw %q, want the escaped stored path", request)
}
}
})
t.Run("unsafe stored paths and unknown keys are not found, and never reach CarrierNode", func(t *testing.T) {
before := len(h.carrier.seen())
for _, key := range []string{"rt-escape", "rt-query", "rt-missing", ""} {
if code := h.do(http.MethodGet, "/media/stream?mediaKey="+key, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("stream of %q status = %d, want 404", key, code)
}
}
if got := len(h.carrier.seen()); got != before {
t.Fatalf("CarrierNode got %d extra requests, want none", got-before)
}
})
t.Run("hidden media is visible to moderators only", func(t *testing.T) {
for _, target := range []string{"/media/stream?mediaKey=rt-hidden", "/media/thumb?mediaKey=rt-hidden"} {
if code := h.do(http.MethodGet, target, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("viewer GET %s = %d, want 404", target, code)
}
}
if response := h.do(http.MethodGet, "/media/stream?mediaKey=rt-hidden", "mod-token", ""); response.Code != http.StatusOK {
t.Errorf("moderator stream of hidden media = %d, want 200", response.Code)
}
})
t.Run("a thumbnail falls back to the original image, and only for images", func(t *testing.T) {
response := h.do(http.MethodGet, "/media/thumb?mediaKey=rt-image", "alice-token", "")
if response.Code != http.StatusOK || response.Body.String() != "BYTES" {
t.Fatalf("image thumbnail = %d %q, want the original image", response.Code, response.Body.String())
}
if code := h.do(http.MethodGet, "/media/thumb?mediaKey=rt-visible", "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("video without a thumbnail = %d, want 404", code)
}
if code := h.do(http.MethodGet, "/media/thumb?mediaKey=../x", "alice-token", "").Code; code != http.StatusBadRequest {
t.Errorf("unsafe thumbnail id = %d, want 400", code)
}
})
}
func TestMediaStatsAndViewsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
state := func(token string) map[string]any {
return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, ""))
}
if code := h.do(http.MethodGet, "/media/state", "", "").Code; code != http.StatusBadRequest {
t.Fatalf("state without a key = %d, want 400", code)
}
for _, body := range []string{`{}`, `{"mediaKey":"rt-stats","bogus":1}`, `nope`} {
if code := h.do(http.MethodPost, "/media/like", "alice-token", body).Code; code != http.StatusBadRequest {
t.Errorf("like with %q = %d, want 400", body, code)
}
}
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats"}`)
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats"}`) // a repeat is not a second like
h.do(http.MethodPost, "/media/like", "bob-token", `{"mediaKey":"rt-stats","like":true}`)
h.do(http.MethodPost, "/media/save", "alice-token", `{"mediaKey":"rt-stats"}`)
if got := state("alice-token"); got["likeCount"] != float64(2) || got["saveCount"] != float64(1) || got["likedByUser"] != true || got["savedByUser"] != true {
t.Fatalf("state for alice = %v", got)
}
if got := state("bob-token"); got["likedByUser"] != true || got["savedByUser"] != false {
t.Fatalf("state for bob = %v", got)
}
if response := h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats","like":false}`); dataOf(t, response)["enabled"] != false {
t.Fatalf("unlike = %s", response.Body.String())
}
if got := state("alice-token"); got["likeCount"] != float64(1) || got["likedByUser"] != false {
t.Fatalf("state after unliking = %v", got)
}
h.do(http.MethodPost, "/media/like", "bob-token", `{"mediaKey":"rt-stats","value":false}`)
if got := state(""); got["likeCount"] != float64(0) {
t.Fatalf("anonymous state after both unlikes = %v", got)
}
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-liked"}`)
liked := decode(t, h.do(http.MethodGet, "/media/liked", "alice-token", ""))["items"].([]any)
if len(liked) != 1 || liked[0].(map[string]any)["mediaKey"] != "rt-liked" {
t.Fatalf("liked = %v, want only rt-liked", liked)
}
// Views and watch sessions can be recorded without logging in.
if code := h.do(http.MethodPost, "/media/view?mediaKey=rt-stats", "", "").Code; code != http.StatusOK {
t.Fatalf("anonymous view = %d, want 200", code)
}
if code := h.do(http.MethodPost, "/media/view", "", "").Code; code != http.StatusBadRequest {
t.Fatalf("view without a key = %d, want 400", code)
}
if code := h.do(http.MethodPost, "/media/view-session", "", `{"mediaKey":"rt-stats","durationMs":1500}`).Code; code != http.StatusOK {
t.Fatalf("view session = %d, want 200", code)
}
for _, body := range []string{`{"mediaKey":"rt-stats"}`, `{"mediaKey":"rt-stats","durationMs":-3}`, `{"durationMs":10}`} {
if code := h.do(http.MethodPost, "/media/view-session", "", body).Code; code != http.StatusBadRequest {
t.Errorf("view session %q = %d, want 400", body, code)
}
}
if got := state(""); got["viewCount"] != float64(1) {
t.Fatalf("view count = %v, want 1", got["viewCount"])
}
}
func TestTagsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
for _, body := range []string{`{}`, `{"tag":" "}`, `{"tag":"` + strings.Repeat("x", 81) + `"}`, `nope`} {
if code := h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", body).Code; code != http.StatusBadRequest {
t.Errorf("add tag %q = %d, want 400", body, code)
}
}
if code := h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", `{"tag":"Funny"}`).Code; code != http.StatusCreated {
t.Fatalf("add tag = %d, want 201", code)
}
h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", `{"tag":"Funny"}`) // the same user's repeat is ignored
h.do(http.MethodPost, "/media/rt-tags/tags", "bob-token", `{"tag":"Quiet"}`)
for _, vote := range []string{"2", "-2", "\"up\""} {
if code := h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "alice-token", `{"vote":`+vote+`}`).Code; code != http.StatusBadRequest {
t.Errorf("vote %s = %d, want 400", vote, code)
}
}
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "alice-token", `{"vote":1}`)
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "bob-token", `{"vote":1}`)
h.do(http.MethodPost, "/media/rt-tags/tags/Quiet/vote", "alice-token", `{"vote":-1}`)
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "bob-token", `{"vote":0}`) // clears bob's vote
tags := decode(t, h.do(http.MethodGet, "/media/rt-tags/tags", "", ""))["tags"].([]any)
if len(tags) != 2 {
t.Fatalf("tags = %v, want Funny and Quiet", tags)
}
first, second := tags[0].(map[string]any), tags[1].(map[string]any)
if first["tag"] != "Funny" || first["score"] != float64(1) || second["tag"] != "Quiet" || second["score"] != float64(-1) {
t.Fatalf("tags = %v, want Funny at 1 ahead of Quiet at -1", tags)
}
suggestions := decode(t, h.do(http.MethodGet, "/tags/suggestions?limit=5", "", ""))["tags"].([]any)
if len(suggestions) == 0 {
t.Fatal("suggestions are empty")
}
listed := decode(t, h.do(http.MethodGet, "/tags/funny/media?limit=10", "", ""))["items"].([]any)
if len(listed) != 1 || listed[0].(map[string]any)["mediaKey"] != "rt-tags" {
t.Fatalf("media for the tag = %v, want rt-tags (the tag matches ignoring case)", listed)
}
}
func TestPlaylistsAgainstPostgres(t *testing.T) {
h := newDBHarness(t)
create := func(token, name string) *httptest.ResponseRecorder {
return h.do(http.MethodPost, "/playlists", token, `{"name":`+fmt.Sprintf("%q", name)+`}`)
}
for _, name := range []string{"", " ", strings.Repeat("n", 121)} {
if code := create("alice-token", name).Code; code != http.StatusBadRequest {
t.Errorf("create %q = %d, want 400", name, code)
}
}
response := create("alice-token", "Road trip")
if response.Code != http.StatusCreated {
t.Fatalf("create = %d, body %s", response.Code, response.Body.String())
}
id := int64(dataOf(t, response)["playlist"].(map[string]any)["id"].(float64))
if again := create("alice-token", "Road trip"); int64(dataOf(t, again)["playlist"].(map[string]any)["id"].(float64)) != id {
t.Fatal("creating the same name again made a second playlist")
}
base := fmt.Sprintf("/playlists/%d", id)
// Another user cannot see, change or delete it.
if code := h.do(http.MethodGet, base, "bob-token", "").Code; code != http.StatusNotFound {
t.Errorf("bob reading alice's playlist = %d, want 404", code)
}
if code := h.do(http.MethodPost, base+"/items", "bob-token", `{"mediaKey":"rt-a"}`).Code; code != http.StatusNotFound {
t.Errorf("bob adding to alice's playlist = %d, want 404", code)
}
if code := h.do(http.MethodDelete, base, "bob-token", "").Code; code != http.StatusNotFound {
t.Errorf("bob deleting alice's playlist = %d, want 404", code)
}
if code := h.do(http.MethodGet, base+"/items", "", "").Code; code != http.StatusNotFound {
t.Errorf("anonymous items = %d, want 404", code)
}
if code := h.do(http.MethodPost, "/playlists/abc/items", "alice-token", `{"mediaKey":"rt-a"}`).Code; code != http.StatusBadRequest {
t.Errorf("bad playlist id = %d, want 400", code)
}
for _, key := range []string{"rt-a", "rt-b", "rt-c"} {
if code := h.do(http.MethodPost, base+"/items", "alice-token", `{"mediaKey":"`+key+`"}`).Code; code != http.StatusCreated {
t.Fatalf("add %s = %d, want 201", key, code)
}
}
h.do(http.MethodPost, base+"/items", "alice-token", `{"media_key":"rt-a"}`) // a repeat is ignored
if code := h.do(http.MethodPost, base+"/items", "alice-token", `{}`).Code; code != http.StatusBadRequest {
t.Errorf("add without a key = %d, want 400", code)
}
keys := func() []string {
var out []string
for _, item := range dataOf(t, h.do(http.MethodGet, base+"/items", "alice-token", ""))["items"].([]any) {
out = append(out, item.(map[string]any)["mediaKey"].(string))
}
return out
}
itemIDs := map[string]int64{}
for _, item := range dataOf(t, h.do(http.MethodGet, base+"/items", "alice-token", ""))["items"].([]any) {
entry := item.(map[string]any)
itemIDs[entry["mediaKey"].(string)] = int64(entry["id"].(float64))
}
if len(itemIDs) != 3 {
t.Fatalf("items = %v, want three distinct entries", itemIDs)
}
reorder := fmt.Sprintf(`{"ids":[%d,%d,%d]}`, itemIDs["rt-c"], itemIDs["rt-a"], itemIDs["rt-b"])
if code := h.do(http.MethodPatch, base+"/items/reorder", "alice-token", reorder).Code; code != http.StatusOK {
t.Fatalf("reorder = %d, want 200", code)
}
if got := strings.Join(keys(), ","); got != "rt-c,rt-a,rt-b" {
t.Fatalf("order after reorder = %s, want rt-c,rt-a,rt-b", got)
}
// The older field name still works, and another user's reorder changes nothing.
h.do(http.MethodPatch, base+"/items/reorder", "alice-token", fmt.Sprintf(`{"itemIds":[%d,%d,%d]}`, itemIDs["rt-b"], itemIDs["rt-c"], itemIDs["rt-a"]))
if got := strings.Join(keys(), ","); got != "rt-b,rt-c,rt-a" {
t.Fatalf("order after itemIds reorder = %s, want rt-b,rt-c,rt-a", got)
}
h.do(http.MethodPatch, base+"/items/reorder", "bob-token", reorder)
if got := strings.Join(keys(), ","); got != "rt-b,rt-c,rt-a" {
t.Fatalf("bob's reorder changed alice's playlist to %s", got)
}
tooMany := make([]string, maxPlaylistReorderItems+1)
for i := range tooMany {
tooMany[i] = "1"
}
if code := h.do(http.MethodPatch, base+"/items/reorder", "alice-token", `{"ids":[`+strings.Join(tooMany, ",")+`]}`).Code; code != http.StatusBadRequest {
t.Errorf("an oversized reorder = %d, want 400", code)
}
random := dataOf(t, h.do(http.MethodGet, base+"/random", "alice-token", ""))
if key, _ := random["mediaKey"].(string); key != "rt-a" && key != "rt-b" && key != "rt-c" {
t.Fatalf("random item = %v", random)
}
if code := h.do(http.MethodGet, base+"/random", "bob-token", "").Code; code != http.StatusNotFound {
t.Errorf("bob's random pick from alice's playlist = %d, want 404", code)
}
summary := dataOf(t, h.do(http.MethodGet, "/playlists/summary", "alice-token", ""))["playlists"].([]any)
if len(summary) != 1 || summary[0].(map[string]any)["item_count"] != float64(3) {
t.Fatalf("summary = %v, want one playlist with three items", summary)
}
if anonymous := dataOf(t, h.do(http.MethodGet, "/playlists/summary", "", ""))["playlists"].([]any); len(anonymous) != 0 {
t.Fatalf("anonymous summary = %v, want none", anonymous)
}
deleteBody := `{"mediaKey":"rt-a"}`
if code := h.do(http.MethodDelete, base+"/items", "bob-token", deleteBody).Code; code != http.StatusNotFound {
t.Errorf("bob removing alice's item = %d, want 404", code)
}
if code := h.do(http.MethodDelete, base+"/items", "alice-token", deleteBody).Code; code != http.StatusOK {
t.Errorf("alice removing her item = %d, want 200", code)
}
if code := h.do(http.MethodDelete, base+"/items", "alice-token", deleteBody).Code; code != http.StatusNotFound {
t.Errorf("removing it twice = %d, want 404", code)
}
if code := h.do(http.MethodDelete, base, "alice-token", "").Code; code != http.StatusOK {
t.Errorf("deleting the playlist = %d, want 200", code)
}
if code := h.do(http.MethodGet, base, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("the deleted playlist = %d, want 404", code)
}
if listed := dataOf(t, h.do(http.MethodGet, "/playlists", "alice-token", ""))["playlists"].([]any); len(listed) != 0 {
t.Fatalf("playlists after deleting = %v, want none", listed)
}
}
+227
View File
@@ -0,0 +1,227 @@
package mediacore
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/go-chi/chi/v5"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
)
// TestSessionRoutesRefuseAnonymousRequests walks the route table: every route mounted behind
// Require answers 401 to a caller with no session, before any handler runs. The Core has no
// database, sync hub or CarrierNode client, so a request that got past the gate would panic.
func TestSessionRoutesRefuseAnonymousRequests(t *testing.T) {
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
for _, route := range []struct{ method, target string }{
{http.MethodGet, "/security/totp/status"},
{http.MethodGet, "/security/totp/initiate"},
{http.MethodPost, "/security/totp/verify"},
{http.MethodPost, "/security/totp/disable"},
{http.MethodPut, "/sync"},
{http.MethodPost, "/media/like"},
{http.MethodPost, "/media/save"},
{http.MethodGet, "/media/liked"},
{http.MethodPost, "/media/7/tags"},
{http.MethodPost, "/media/7/tags/funny/vote"},
{http.MethodGet, "/playlists"},
{http.MethodPost, "/playlists"},
{http.MethodDelete, "/playlists/3"},
{http.MethodPost, "/playlists/3/items"},
{http.MethodDelete, "/playlists/3/items"},
{http.MethodPatch, "/playlists/3/items/reorder"},
} {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(route.method, route.target, strings.NewReader(`{}`)))
if response.Code != http.StatusUnauthorized {
t.Errorf("%s %s status = %d, want 401", route.method, route.target, response.Code)
}
}
}
// syncRouter mounts the sync routes on a Core with no database. Auth is disabled, so every caller
// is the placeholder administrator.
func syncRouter(hub *syncsocket.Hub) chi.Router {
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject", sharedauth.Disabled())
router := chi.NewRouter()
New(Config{Auth: auth, Sync: hub}).Mount(router)
return router
}
func putSync(router http.Handler, target, body string) *httptest.ResponseRecorder {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodPut, target, strings.NewReader(body)))
return response
}
func TestPutSyncRejectsBadInput(t *testing.T) {
router := syncRouter(syncsocket.NewHub())
for name, body := range map[string]string{
"not JSON": `nope`,
"missing clientId": `{"mediaId":"m1"}`,
"blank clientId": `{"clientId":" ","mediaId":"m1"}`,
"object mediaId": `{"clientId":"c1","mediaId":{"a":1}}`,
"boolean mediaId": `{"clientId":"c1","mediaId":true}`,
"array playAt": `{"clientId":"c1","mediaId":"m1","playAt":[1]}`,
"object playAt": `{"clientId":"c1","mediaId":"m1","playAt":{"a":1}}`,
"clientId not text": `{"clientId":5,"mediaId":"m1"}`,
} {
if response := putSync(router, "/sync", body); response.Code != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400 (body %s)", name, response.Code, response.Body.String())
}
}
}
func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) {
hub := syncsocket.NewHub()
router := syncRouter(hub)
response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"c1","mediaId":42,"timeMs":-5,"paused":true,"fps":100000,"frame":9,"playAt":"2026-10-19T10:00:00Z"}`)
if response.Code != http.StatusOK {
t.Fatalf("PUT status = %d, body %s", response.Code, response.Body.String())
}
var written struct {
Success bool `json:"success"`
State map[string]any `json:"state"`
}
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil || !written.Success {
t.Fatalf("PUT body = %s, %v", response.Body.String(), err)
}
state := written.State
if state["sessionId"] != "room-1" || state["fromClientId"] != "c1" || state["mediaId"] != float64(42) || state["paused"] != true {
t.Fatalf("state = %v", state)
}
if state["timeMs"] != float64(0) || state["fps"] != float64(240) || state["frame"] != float64(9) || state["playAt"] != "2026-10-19T10:00:00Z" {
t.Fatalf("a negative time was not clamped to 0, or fps to 240: %v", state)
}
get := httptest.NewRecorder()
router.ServeHTTP(get, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-1", nil))
var read map[string]any
if err := json.Unmarshal(get.Body.Bytes(), &read); err != nil || read["fromClientId"] != "c1" || read["mediaId"] != float64(42) {
t.Fatalf("GET /sync = %s, %v; want the stored state", get.Body.String(), err)
}
other := httptest.NewRecorder()
router.ServeHTTP(other, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-2", nil))
var empty map[string]any
if err := json.Unmarshal(other.Body.Bytes(), &empty); err != nil || empty["fromClientId"] == "c1" {
t.Fatalf("another session got %s, %v; want it untouched", other.Body.String(), err)
}
}
func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) {
router := syncRouter(syncsocket.NewHub())
long := strings.Repeat("s", 300)
response := putSync(router, "/sync", `{"clientId":"`+strings.Repeat("c", 300)+`","mediaId":null,"sessionId":"`+long+`"}`)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, body %s", response.Code, response.Body.String())
}
var written struct{ State map[string]any }
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil {
t.Fatal(err)
}
if got := written.State["sessionId"].(string); len(got) != 128 {
t.Errorf("sessionId length = %d, want 128", len(got))
}
if got := written.State["fromClientId"].(string); len(got) != 128 {
t.Errorf("fromClientId length = %d, want 128", len(got))
}
}
// TestPutSyncBroadcastsToThePeersOfThatSession checks the HTTP write reaches websocket peers in
// the session, and only those.
func TestPutSyncBroadcastsToThePeersOfThatSession(t *testing.T) {
hub := syncsocket.NewHub()
router := syncRouter(hub)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "")
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
url := "ws" + strings.TrimPrefix(server.URL, "http")
join := func(session string) (*websocket.Conn, string) {
conn, _, err := websocket.Dial(ctx, url, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.CloseNow() })
hello := readFrame(t, ctx, conn, "hello")
id := hello["clientId"].(string)
data, _ := json.Marshal(map[string]any{"type": "sync:hello", "clientId": id, "sessionId": session})
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
t.Fatal(err)
}
readFrame(t, ctx, conn, "sync:state")
return conn, id
}
inRoom, _ := join("room-1")
elsewhere, _ := join("room-2")
if response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"http-client","mediaId":"clip-9","timeMs":1500}`); response.Code != http.StatusOK {
t.Fatalf("PUT status = %d", response.Code)
}
frame := readFrame(t, ctx, inRoom, "sync:state")
state, _ := frame["state"].(map[string]any)
if state["mediaId"] != "clip-9" || state["timeMs"] != float64(1500) {
t.Fatalf("the session peer got %v", frame)
}
short, shortCancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer shortCancel()
if _, _, err := elsewhere.Read(short); err == nil {
t.Fatal("a peer in another session received the broadcast")
}
}
func readFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) map[string]any {
t.Helper()
for {
_, data, err := conn.Read(ctx)
if err != nil {
t.Fatalf("read while waiting for %q: %v", want, err)
}
var message map[string]any
if err := json.Unmarshal(data, &message); err != nil {
t.Fatal(err)
}
if message["type"] == want {
return message
}
}
}
func TestProfileReportsTheSessionUser(t *testing.T) {
guard := newRoleAuthGuard(t)
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
anonymous := httptest.NewRecorder()
router.ServeHTTP(anonymous, httptest.NewRequest(http.MethodGet, "/profile", nil))
if anonymous.Code != http.StatusOK || strings.TrimSpace(anonymous.Body.String()) != `{"user":null}` {
t.Fatalf("anonymous profile = %d %s, want a null user", anonymous.Code, anonymous.Body.String())
}
request := httptest.NewRequest(http.MethodGet, "/profile", nil)
request.AddCookie(&http.Cookie{Name: "auth_session", Value: "viewer-token"})
known := httptest.NewRecorder()
router.ServeHTTP(known, request)
var body struct{ User map[string]any }
if err := json.Unmarshal(known.Body.Bytes(), &body); err != nil || body.User["username"] != "tester" || body.User["role"] != "user" {
t.Fatalf("profile = %s, %v", known.Body.String(), err)
}
}
+74
View File
@@ -0,0 +1,74 @@
package migrate
import (
"context"
"database/sql"
"os"
"strings"
"testing"
"testing/fstest"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
func TestUpRefusesMissingInputsBeforeConnecting(t *testing.T) {
files := fstest.MapFS{"migrations/001_init.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n")}}
if err := Up(context.Background(), "", files, "migrations"); err == nil || !strings.Contains(err.Error(), "database URL is required") {
t.Fatalf("empty URL error = %v", err)
}
if err := Up(context.Background(), "postgres://localhost/none", nil, "migrations"); err == nil || !strings.Contains(err.Error(), "migration filesystem is required") {
t.Fatalf("nil filesystem error = %v", err)
}
}
func TestUpReportsAnUnreachableDatabase(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
files := fstest.MapFS{"migrations/001_init.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n")}}
err := Up(ctx, "postgres://nobody@127.0.0.1:1/none?sslmode=disable&connect_timeout=2", files, "migrations")
if err == nil || !strings.Contains(err.Error(), "ping migration database") {
t.Fatalf("unreachable database error = %v, want a ping failure", err)
}
}
// TestUpAppliesMigrationsOnce runs real migrations. It creates goose_db_version and a table, so it
// is skipped unless SHARED_TEST_DATABASE_URL points at a scratch database, for example:
//
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./migrate/
func TestUpAppliesMigrationsOnce(t *testing.T) {
url := os.Getenv("SHARED_TEST_DATABASE_URL")
if url == "" {
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres migration test")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
db, err := sql.Open("pgx", url)
if err != nil {
t.Fatal(err)
}
defer db.Close()
t.Cleanup(func() {
_, _ = db.Exec(`DROP TABLE IF EXISTS migrate_test_widgets; DROP TABLE IF EXISTS goose_db_version`)
})
_, _ = db.Exec(`DROP TABLE IF EXISTS migrate_test_widgets; DROP TABLE IF EXISTS goose_db_version`)
files := fstest.MapFS{
"migrations/001_widgets.sql": {Data: []byte("-- +goose Up\nCREATE TABLE migrate_test_widgets (id INT PRIMARY KEY);\n-- +goose Down\nDROP TABLE migrate_test_widgets;\n")},
"migrations/002_seed.sql": {Data: []byte("-- +goose Up\nINSERT INTO migrate_test_widgets (id) VALUES (1);\n-- +goose Down\nDELETE FROM migrate_test_widgets;\n")},
}
for run := 1; run <= 2; run++ {
if err := Up(ctx, url, files, "migrations"); err != nil {
t.Fatalf("run %d: Up() error = %v", run, err)
}
}
var rows int
if err := db.QueryRowContext(ctx, `SELECT count(*) FROM migrate_test_widgets`).Scan(&rows); err != nil || rows != 1 {
t.Fatalf("widgets = %d, %v; want the seed applied exactly once", rows, err)
}
broken := fstest.MapFS{"migrations/003_broken.sql": {Data: []byte("-- +goose Up\nSELECT * FROM no_such_table;\n")}}
if err := Up(ctx, url, broken, "migrations"); err == nil || !strings.Contains(err.Error(), "run migrations") {
t.Fatalf("broken migration error = %v, want a run-migrations failure", err)
}
}
+156 -45
View File
@@ -19,7 +19,10 @@ package syncsocket
import ( import (
"context" "context"
"crypto/rand"
"encoding/hex"
"encoding/json" "encoding/json"
"errors"
"math" "math"
"net/http" "net/http"
"net/url" "net/url"
@@ -31,18 +34,22 @@ import (
) )
const ( const (
maxSyncIdentifier = 128 maxSyncIdentifier = 128
maxSyncSessions = 1000 maxSyncSessions = 1000
maxSyncConnections = 1000 maxSyncConnections = 1000
maxPeerWriteQueue = 64
maxPeerMessagesPerSecond = 120
) )
type peer struct { type peer struct {
conn *websocket.Conn conn *websocket.Conn
writeMu sync.Mutex out chan []byte
done chan struct{}
closeOnce sync.Once
messageWindow time.Time
messageCount int
clientID string clientID string
sessionID string sessionID string
userAgent string
ipAddress string
remoteControlEnabled bool remoteControlEnabled bool
uiView string uiView string
uiMediaID any uiMediaID any
@@ -77,11 +84,15 @@ func NewHub() *Hub {
// add registers a peer, or reports false when the hub already holds maxSyncConnections peers. // add registers a peer, or reports false when the hub already holds maxSyncConnections peers.
func (h *Hub) add(p *peer) bool { func (h *Hub) add(p *peer) bool {
h.mu.Lock() h.mu.Lock()
defer h.mu.Unlock()
if len(h.peers) >= maxSyncConnections { if len(h.peers) >= maxSyncConnections {
h.mu.Unlock()
return false return false
} }
p.out = make(chan []byte, maxPeerWriteQueue)
p.done = make(chan struct{})
h.peers[p] = struct{}{} h.peers[p] = struct{}{}
h.mu.Unlock()
go p.writeLoop()
return true return true
} }
@@ -89,6 +100,7 @@ func (h *Hub) remove(p *peer) string {
h.mu.Lock() h.mu.Lock()
defer h.mu.Unlock() defer h.mu.Unlock()
delete(h.peers, p) delete(h.peers, p)
p.closeOnce.Do(func() { close(p.done) })
if p.clientID != "" && !h.hasClientLocked(p.clientID) { if p.clientID != "" && !h.hasClientLocked(p.clientID) {
delete(h.controlOwners, p.clientID) delete(h.controlOwners, p.clientID)
for targetID, ownerID := range h.controlOwners { for targetID, ownerID := range h.controlOwners {
@@ -109,11 +121,8 @@ func (h *Hub) hasClientLocked(clientID string) bool {
return false return false
} }
func (h *Hub) updatePeer(p *peer, clientID, sessionID string) { func (h *Hub) updatePeer(p *peer, sessionID string) {
h.mu.Lock() h.mu.Lock()
if clientID != "" {
p.clientID = clientID
}
if sessionID != "" { if sessionID != "" {
p.sessionID = sessionID p.sessionID = sessionID
} }
@@ -151,8 +160,6 @@ func (h *Hub) clientsLocked(sessionID string) []map[string]any {
if !exists { if !exists {
entry = map[string]any{ entry = map[string]any{
"clientId": p.clientID, "clientId": p.clientID,
"userAgent": p.userAgent,
"ipAddress": p.ipAddress,
"remoteControlEnabled": p.remoteControlEnabled, "remoteControlEnabled": p.remoteControlEnabled,
"controlOwnerClientId": nil, "controlOwnerClientId": nil,
} }
@@ -250,9 +257,13 @@ func (h *Hub) Broadcast(sessionID string) {
h.mu.Unlock() h.mu.Unlock()
message := map[string]any{"type": "sync:state", "state": state, "clients": clients} message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
data, err := json.Marshal(message)
if err != nil {
return
}
for _, p := range peers { for _, p := range peers {
if err := p.send(message); err != nil { if err := p.sendData(data); err != nil {
_ = p.conn.Close(websocket.StatusGoingAway, "write failed") p.drop(websocket.StatusGoingAway, "slow or closed peer")
} }
} }
} }
@@ -262,20 +273,76 @@ func (p *peer) send(message any) error {
if err != nil { if err != nil {
return err return err
} }
p.writeMu.Lock() return p.sendData(data)
defer p.writeMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return p.conn.Write(ctx, websocket.MessageText, data)
} }
func (p *peer) sendData(data []byte) error {
select {
case <-p.done:
return context.Canceled
default:
}
select {
case p.out <- data:
return nil
case <-p.done:
return context.Canceled
default:
return errPeerWriteQueueFull
}
}
var errPeerWriteQueueFull = errors.New("sync websocket peer write queue is full")
func (p *peer) writeLoop() {
for {
select {
case <-p.done:
return
case data := <-p.out:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
err := p.conn.Write(ctx, websocket.MessageText, data)
cancel()
if err != nil {
p.stop(websocket.StatusGoingAway, "write failed")
return
}
}
}
}
func (p *peer) allowMessage(now time.Time) bool {
if now.Sub(p.messageWindow) >= time.Second {
p.messageWindow = now
p.messageCount = 0
}
p.messageCount++
return p.messageCount <= maxPeerMessagesPerSecond
}
func (p *peer) close() {
p.stop(websocket.StatusPolicyViolation, "message rate exceeded")
}
func (p *peer) stop(status websocket.StatusCode, reason string) {
p.closeOnce.Do(func() { close(p.done) })
_ = p.conn.Close(status, reason)
}
// drop stops a peer on behalf of code that is serving other peers or an HTTP request. Close waits
// for the peer's close frame (up to five seconds), which a stuck peer never sends, so it runs in
// its own goroutine instead of holding up the caller.
func (p *peer) drop(status websocket.StatusCode, reason string) {
p.closeOnce.Do(func() { close(p.done) })
go func() { _ = p.conn.Close(status, reason) }()
}
// websocketAcceptOptions enables origin verification for every connection. A
// configured origin and the request's own host are accepted. "*" adds no
// extra origin, so it does not turn the check off: a page on another site
// cannot open the socket unless its origin is listed explicitly.
func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions { func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions {
options := &websocket.AcceptOptions{} options := &websocket.AcceptOptions{}
if allowedOrigin == "*" {
options.InsecureSkipVerify = true
return options
}
patterns := make([]string, 0, 2) patterns := make([]string, 0, 2)
addOrigin := func(value string) { addOrigin := func(value string) {
parsed, err := url.Parse(strings.TrimSpace(value)) parsed, err := url.Parse(strings.TrimSpace(value))
@@ -293,19 +360,51 @@ func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.Ac
return options return options
} }
// newClientID returns a random identifier for one connection. The hub issues it
// at upgrade time and clients cannot choose it, so two connections never share
// an identity.
func newClientID() (string, error) {
var buf [16]byte
if _, err := rand.Read(buf[:]); err != nil {
return "", err
}
return hex.EncodeToString(buf[:]), nil
}
// acceptsClientID reports whether a message's clientId, if it carries one,
// names the identity issued to this connection. A message without clientId
// is taken as this connection's own.
func (p *peer) acceptsClientID(message map[string]any) bool {
requested := boundedSyncString(syncString(message, "clientId"))
return requested == "" || requested == p.clientID
}
// refuseClientID drops a message that named another identity. The connection
// stays open, and the error frame repeats the identity the client holds.
func (p *peer) refuseClientID() {
_ = p.send(map[string]any{"type": "error", "code": "client-id-mismatch", "clientId": p.clientID})
}
// ServeWebSocket upgrades the request to a websocket connection and services // ServeWebSocket upgrades the request to a websocket connection and services
// it until the client disconnects. allowedOrigin should be the service's own // it until the client disconnects. allowedOrigin should be the service's own
// CORS_ORIGIN config value (or "*" to accept any origin). // explicit CORS_ORIGIN value; "*" does not bypass origin verification.
//
// Each connection is issued a clientId at upgrade time. It is sent in the
// first "hello" frame, and every later message must either omit clientId or
// repeat it. A message naming any other identity gets a "client-id-mismatch"
// error frame and is otherwise ignored. A reconnect is a new connection with a
// new identity.
func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) { func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) {
conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin)) conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin))
if err != nil { if err != nil {
return return
} }
p := &peer{ clientID, err := newClientID()
conn: conn, if err != nil {
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"), _ = conn.Close(websocket.StatusInternalError, "could not issue client identity")
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"), return
} }
p := &peer{conn: conn, clientID: clientID}
if !h.add(p) { if !h.add(p) {
_ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections") _ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections")
return return
@@ -318,12 +417,16 @@ func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrig
} }
}() }()
_ = p.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()}) _ = p.send(map[string]any{"type": "hello", "clientId": clientID, "ts": time.Now().UnixMilli()})
for { for {
messageType, payload, readErr := conn.Read(r.Context()) messageType, payload, readErr := conn.Read(r.Context())
if readErr != nil { if readErr != nil {
return return
} }
if !p.allowMessage(time.Now()) {
p.close()
return
}
if messageType != websocket.MessageText { if messageType != websocket.MessageText {
continue continue
} }
@@ -346,20 +449,23 @@ func (h *Hub) handleMessage(p *peer, message map[string]any) {
"serverReceivedAt": time.Now().UnixMilli(), "serverReceivedAt": time.Now().UnixMilli(),
}) })
case "sync:hello": case "sync:hello":
clientID := boundedSyncString(syncString(message, "clientId")) if !p.acceptsClientID(message) {
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default")) p.refuseClientID()
if clientID == "" || sessionID == "" {
return return
} }
h.updatePeer(p, clientID, sessionID) sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
if sessionID == "" {
return
}
h.updatePeer(p, sessionID)
h.Broadcast(sessionID) h.Broadcast(sessionID)
case "client:status": case "client:status":
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID)) if !p.acceptsClientID(message) {
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default")) p.refuseClientID()
if clientID == "" {
return return
} }
h.updatePeer(p, clientID, sessionID) sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
h.updatePeer(p, sessionID)
mediaID, mediaIDSet := syncMediaID(message) mediaID, mediaIDSet := syncMediaID(message)
remote, remoteSet := message["remoteControlEnabled"].(bool) remote, remoteSet := message["remoteControlEnabled"].(bool)
h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote) h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
@@ -372,10 +478,14 @@ func (h *Hub) handleMessage(p *peer, message map[string]any) {
} }
func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) { func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) {
requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID)) if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
requesterID := p.clientID
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default")) sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
targetID := boundedSyncString(syncString(message, "targetClientId")) targetID := boundedSyncString(syncString(message, "targetClientId"))
if requesterID == "" || targetID == "" || requesterID != p.clientID { if targetID == "" {
return return
} }
@@ -422,11 +532,12 @@ func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any)
} }
func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) { func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID)) if !p.acceptsClientID(message) {
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default")) p.refuseClientID()
if clientID == "" || clientID != p.clientID {
return return
} }
clientID := p.clientID
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
mediaID, _ := syncMediaID(message) mediaID, _ := syncMediaID(message)
paused := syncBool(message, "paused") paused := syncBool(message, "paused")
state := map[string]any{ state := map[string]any{
@@ -490,7 +601,7 @@ func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
if toClientID != "" { if toClientID != "" {
for _, target := range peers { for _, target := range peers {
if err := target.send(messageOut); err != nil { if err := target.send(messageOut); err != nil {
_ = target.conn.Close(websocket.StatusGoingAway, "write failed") target.drop(websocket.StatusGoingAway, "write failed")
} }
} }
return return
+272
View File
@@ -1,8 +1,17 @@
package syncsocket package syncsocket
import ( import (
"context"
"encoding/json"
"fmt" "fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing" "testing"
"time"
"github.com/coder/websocket"
) )
// TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the // TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the
@@ -44,3 +53,266 @@ func TestHubRefusesPeersBeyondTheConnectionCap(t *testing.T) {
t.Fatal("add accepted a peer beyond maxSyncConnections") t.Fatal("add accepted a peer beyond maxSyncConnections")
} }
} }
// TestWildcardOriginKeepsOriginVerification checks that CORS_ORIGIN "*" does not disable the
// websocket origin check: only the request's own host is accepted.
func TestWildcardOriginKeepsOriginVerification(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://hub.example.com/ws", nil)
options := websocketAcceptOptions(req, "*")
if options.InsecureSkipVerify {
t.Fatal("wildcard origin disabled origin verification")
}
if want := []string{"http://hub.example.com"}; !slices.Equal(options.OriginPatterns, want) {
t.Fatalf("origin patterns = %v, want %v", options.OriginPatterns, want)
}
}
// TestExplicitOriginIsAcceptedAlongsideTheRequestHost checks that a listed origin is accepted
// without turning the check off.
func TestExplicitOriginIsAcceptedAlongsideTheRequestHost(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "https://hub.example.com/ws", nil)
options := websocketAcceptOptions(req, "https://app.example.com/")
if options.InsecureSkipVerify {
t.Fatal("explicit origin disabled origin verification")
}
for _, want := range []string{"https://app.example.com", "https://hub.example.com"} {
if !slices.Contains(options.OriginPatterns, want) {
t.Errorf("origin patterns %v missing %q", options.OriginPatterns, want)
}
}
}
// TestClientListOmitsPeerAddressAndUserAgent checks that broadcast client entries carry no peer
// IP address or user agent.
func TestClientListOmitsPeerAddressAndUserAgent(t *testing.T) {
hub := NewHub()
hub.add(&peer{clientID: "client-1", sessionID: "session-1", remoteControlEnabled: true})
clients := hub.clientsLocked("session-1")
if len(clients) != 1 {
t.Fatalf("clients = %d, want 1", len(clients))
}
for _, key := range []string{"ipAddress", "userAgent"} {
if _, ok := clients[0][key]; ok {
t.Errorf("client entry carries %q", key)
}
}
if clients[0]["clientId"] != "client-1" {
t.Errorf("clientId = %v, want client-1", clients[0]["clientId"])
}
}
// TestClientIdentityIsIssuedAtUpgradeAndEnforced checks the protocol change: each connection gets a
// server-issued clientId in its hello frame, a message naming another identity is refused with an
// error frame, and a message carrying the issued identity is applied.
func TestClientIdentityIsIssuedAtUpgradeAndEnforced(t *testing.T) {
hub := NewHub()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "")
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
url := "ws" + strings.TrimPrefix(server.URL, "http")
first := dialSyncSocket(t, ctx, url)
defer first.CloseNow()
second := dialSyncSocket(t, ctx, url)
defer second.CloseNow()
firstID := readSyncFrame(t, ctx, first, "hello")["clientId"].(string)
secondID := readSyncFrame(t, ctx, second, "hello")["clientId"].(string)
if len(firstID) != 32 || firstID == secondID {
t.Fatalf("issued identities = %q and %q, want two distinct 32-character IDs", firstID, secondID)
}
writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": secondID, "sessionId": "s1"})
refusal := readSyncFrame(t, ctx, first, "error")
if refusal["code"] != "client-id-mismatch" || refusal["clientId"] != firstID {
t.Fatalf("refusal = %v, want client-id-mismatch carrying the issued identity", refusal)
}
writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": firstID, "sessionId": "s1"})
state := readSyncFrame(t, ctx, first, "sync:state")
clients, _ := state["clients"].([]any)
found := false
for _, entry := range clients {
if client, ok := entry.(map[string]any); ok && client["clientId"] == firstID {
found = true
}
}
if !found {
t.Fatalf("clients = %v, want the issued identity %q listed", clients, firstID)
}
}
func TestAcceptsClientIDOnlyForTheIssuedIdentity(t *testing.T) {
p := &peer{clientID: "issued"}
for _, tt := range []struct {
name string
message map[string]any
want bool
}{
{"no clientId", map[string]any{}, true},
{"the issued identity", map[string]any{"clientId": "issued"}, true},
{"another identity", map[string]any{"clientId": "other"}, false},
{"an oversized identity", map[string]any{"clientId": strings.Repeat("x", maxSyncIdentifier+1)}, false},
} {
if got := p.acceptsClientID(tt.message); got != tt.want {
t.Errorf("%s: acceptsClientID = %v, want %v", tt.name, got, tt.want)
}
}
}
// TestPeerMessageRateWindow checks the per-peer limit: maxPeerMessagesPerSecond messages are
// allowed in a one-second window, the next is refused, and the count restarts with the next window.
func TestPeerMessageRateWindow(t *testing.T) {
p := &peer{}
start := time.Unix(1000, 0)
for i := 0; i < maxPeerMessagesPerSecond; i++ {
if !p.allowMessage(start.Add(time.Duration(i) * time.Millisecond)) {
t.Fatalf("message %d refused inside the limit", i+1)
}
}
if p.allowMessage(start.Add(500 * time.Millisecond)) {
t.Fatal("a message past the limit was allowed")
}
if !p.allowMessage(start.Add(time.Second)) {
t.Fatal("the count did not restart with the next window")
}
}
// TestPeerExceedingTheMessageRateIsDisconnected checks that a client flooding messages is closed
// with a policy-violation status instead of being fanned out.
func TestPeerExceedingTheMessageRateIsDisconnected(t *testing.T) {
hub := NewHub()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "")
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
conn := dialSyncSocket(t, ctx, "ws"+strings.TrimPrefix(server.URL, "http"))
defer conn.CloseNow()
readSyncFrame(t, ctx, conn, "hello")
go func() {
for i := 0; i < maxPeerMessagesPerSecond*4; i++ {
if conn.Write(ctx, websocket.MessageText, []byte(`{"type":"ws:ping"}`)) != nil {
return
}
}
}()
for {
if _, _, err := conn.Read(ctx); err != nil {
if got := websocket.CloseStatus(err); got != websocket.StatusPolicyViolation {
t.Fatalf("close status = %v (error %v), want policy violation", got, err)
}
return
}
}
}
// TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking checks that a peer that never drains its
// write queue is stopped by Broadcast, which returns at once, and that a healthy peer in the same
// session still receives the state.
func TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking(t *testing.T) {
hub := NewHub()
slowReady := make(chan *peer, 1)
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/slow" {
hub.ServeWebSocket(w, r, "")
return
}
conn, err := websocket.Accept(w, r, nil)
if err != nil {
return
}
defer conn.CloseNow()
p := &peer{
conn: conn, clientID: "slow", sessionID: "s1",
out: make(chan []byte, maxPeerWriteQueue), done: make(chan struct{}),
}
for i := 0; i < maxPeerWriteQueue; i++ {
p.out <- []byte("{}")
}
hub.mu.Lock()
hub.peers[p] = struct{}{}
hub.mu.Unlock()
slowReady <- p
<-release
}))
defer server.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
url := "ws" + strings.TrimPrefix(server.URL, "http")
fast := dialSyncSocket(t, ctx, url)
defer fast.CloseNow()
fastID := readSyncFrame(t, ctx, fast, "hello")["clientId"].(string)
writeSyncFrame(t, ctx, fast, map[string]any{"type": "sync:hello", "clientId": fastID, "sessionId": "s1"})
readSyncFrame(t, ctx, fast, "sync:state")
slowClient := dialSyncSocket(t, ctx, url+"/slow")
defer slowClient.CloseNow()
slow := <-slowReady
// Stopping a peer waits for a close frame that a stuck peer never sends, so Broadcast must not
// do it inline: it would hold up the caller (an HTTP request, or another peer's read loop).
started := time.Now()
hub.Broadcast("s1")
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("Broadcast took %v behind a stuck peer, want it to return at once", elapsed)
}
select {
case <-slow.done:
default:
t.Fatal("the peer with a full queue was not stopped")
}
state := readSyncFrame(t, ctx, fast, "sync:state")
if _, ok := state["clients"].([]any); !ok {
t.Fatalf("the healthy peer got %v, want a state with the client list", state)
}
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("the healthy peer's state took %v, want it at once", elapsed)
}
}
func dialSyncSocket(t *testing.T, ctx context.Context, url string) *websocket.Conn {
t.Helper()
conn, _, err := websocket.Dial(ctx, url, nil)
if err != nil {
t.Fatalf("dial %s: %v", url, err)
}
return conn
}
func writeSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, message map[string]any) {
t.Helper()
data, err := json.Marshal(message)
if err != nil {
t.Fatal(err)
}
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
t.Fatalf("write %v: %v", message["type"], err)
}
}
// readSyncFrame reads frames until one of the wanted type arrives, failing if the connection ends first.
func readSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) map[string]any {
t.Helper()
for {
_, data, err := conn.Read(ctx)
if err != nil {
t.Fatalf("read while waiting for %q: %v", want, err)
}
var message map[string]any
if err := json.Unmarshal(data, &message); err != nil {
t.Fatalf("decode frame: %v", err)
}
if message["type"] == want {
return message
}
}
}
+325
View File
@@ -0,0 +1,325 @@
{
"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.",
"password": {
"plaintext": "correct horse battery staple",
"wrongPassword": "not the right password",
"hashes": [
{
"name": "Node, current pbkdf2-sha256 scheme",
"hash": "pbkdf2-sha256$600000$76add00c36dafceac62928d01f706c20$f50eec2591755f169bd151369e41a4e6918c6a2816d19516cc38763bfa63c0ca",
"verifies": {
"go": false,
"node": true,
"python": false
},
"needsUpgrade": {
"node": false
}
},
{
"name": "Node, legacy salt:hex at 100000 iterations",
"hash": "0123456789abcdef0123456789abcdef:69a26fc4b1624cd29ecc2b2444aa876251575c65deb4af9effbd9eadbd4195c6",
"verifies": {
"go": false,
"node": true,
"python": false
},
"needsUpgrade": {
"node": true
}
},
{
"name": "Go and Python, bcrypt scheme prefix, cost 4",
"hash": "bcrypt$$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
"verifies": {
"go": true,
"node": false,
"python": true
},
"needsUpgrade": {
"go": true,
"python": true
}
},
{
"name": "Go and Python, unprefixed legacy bcrypt, cost 4",
"hash": "$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
"verifies": {
"go": true,
"node": false,
"python": true
},
"needsUpgrade": {
"go": true,
"python": true
}
},
{
"name": "unknown scheme",
"hash": "argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHQ$YWJj",
"verifies": {
"go": false,
"node": false,
"python": false
}
},
{
"name": "plain text stored as a hash",
"hash": "correct horse battery staple",
"verifies": {
"go": false,
"node": false,
"python": false
}
},
{
"name": "empty hash",
"hash": "",
"verifies": {
"go": false,
"node": false,
"python": false
}
}
],
"tooLongToHash": {
"bytes": 73,
"accepted": {
"go": false,
"node": true,
"python": false
},
"note": "bcrypt reads only the first 72 bytes, so Go and Python refuse a longer password; PBKDF2 has no such limit."
}
},
"totp": {
"secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
"cases": [
{
"name": "RFC 6238 T=59",
"unix": 59,
"code": "287082",
"valid": true
},
{
"name": "RFC 6238 T=1111111109",
"unix": 1111111109,
"code": "081804",
"valid": true
},
{
"name": "RFC 6238 T=1111111111",
"unix": 1111111111,
"code": "050471",
"valid": true
},
{
"name": "RFC 6238 T=1234567890",
"unix": 1234567890,
"code": "005924",
"valid": true
},
{
"name": "RFC 6238 T=2000000000",
"unix": 2000000000,
"code": "279037",
"valid": true
},
{
"name": "the next step still accepts the previous code",
"unix": 1111111139,
"code": "081804",
"valid": true
},
{
"name": "the previous step accepts the next code",
"unix": 1111111079,
"code": "081804",
"valid": true
},
{
"name": "two steps late is refused",
"unix": 1111111169,
"code": "081804",
"valid": false
},
{
"name": "two steps early is refused",
"unix": 1111111049,
"code": "081804",
"valid": false
},
{
"name": "a code is not a different code",
"unix": 59,
"code": "287083",
"valid": false
},
{
"name": "a code with a letter",
"unix": 59,
"code": "28708a",
"valid": false
},
{
"name": "five digits",
"unix": 59,
"code": "28708",
"valid": false
},
{
"name": "seven digits",
"unix": 59,
"code": "2870820",
"valid": false
},
{
"name": "empty code",
"unix": 59,
"code": "",
"valid": false
},
{
"name": "non-ASCII digits",
"unix": 59,
"code": "٢٨٧٠٨٢",
"valid": false
},
{
"name": "surrounding spaces are trimmed",
"unix": 59,
"code": " 287082 ",
"valid": true
},
{
"name": "secret in lower case with spaces and padding",
"unix": 59,
"code": "287082",
"secret": "gezd gnbv gy3t qojq gezd gnbv gy3t qojq====",
"valid": true
},
{
"name": "empty secret",
"unix": 59,
"code": "287082",
"secret": "",
"valid": false
},
{
"name": "secret that is not base32",
"unix": 59,
"code": "287082",
"secret": "not base32 !!",
"valid": false
}
]
},
"clientAddress": {
"note": "Go and Python only. The address is the TCP peer unless the peer is in the trusted list; then X-Forwarded-For is read from the right and trusted hops are skipped (owner decision 5).",
"invalidTrustedProxyLists": [
"not-an-ip",
"10.0.0.0/33",
"10.0.0.1, bogus"
],
"cases": [
{
"name": "no trusted proxies ignores the header",
"trusted": "",
"peer": "203.0.113.7",
"forwarded": [
"198.51.100.1"
],
"want": "203.0.113.7"
},
{
"name": "an unknown peer's header is ignored",
"trusted": "10.0.0.0/8",
"peer": "203.0.113.7",
"forwarded": [
"198.51.100.1"
],
"want": "203.0.113.7"
},
{
"name": "single client behind a trusted peer",
"trusted": "10.0.0.0/8, 172.16.0.0/12",
"peer": "10.0.0.2",
"forwarded": [
"198.51.100.9"
],
"want": "198.51.100.9"
},
{
"name": "second trusted hop is skipped",
"trusted": "10.0.0.0/8, 172.16.0.0/12",
"peer": "10.0.0.2",
"forwarded": [
"198.51.100.9, 172.16.4.4"
],
"want": "198.51.100.9"
},
{
"name": "a spoofed left-most entry is skipped",
"trusted": "10.0.0.0/8, 172.16.0.0/12",
"peer": "10.0.0.2",
"forwarded": [
"6.6.6.6, 198.51.100.9, 172.16.4.4"
],
"want": "198.51.100.9"
},
{
"name": "entries across header lines",
"trusted": "10.0.0.0/8, 172.16.0.0/12",
"peer": "10.0.0.2",
"forwarded": [
"6.6.6.6",
"198.51.100.9"
],
"want": "198.51.100.9"
},
{
"name": "a malformed entry falls back to the peer",
"trusted": "10.0.0.0/8, 172.16.0.0/12",
"peer": "10.0.0.2",
"forwarded": [
"198.51.100.9, not-an-ip"
],
"want": "10.0.0.2"
},
{
"name": "no header falls back to the peer",
"trusted": "10.0.0.0/8, 172.16.0.0/12",
"peer": "10.0.0.2",
"forwarded": [],
"want": "10.0.0.2"
},
{
"name": "every hop trusted uses the left-most",
"trusted": "10.0.0.0/8, 172.16.0.0/12",
"peer": "10.0.0.2",
"forwarded": [
"10.1.1.1, 172.16.4.4"
],
"want": "10.1.1.1"
},
{
"name": "a bare address is a one-host range",
"trusted": "192.168.1.5",
"peer": "192.168.1.5",
"forwarded": [
"198.51.100.9"
],
"want": "198.51.100.9"
},
{
"name": "an IPv6 proxy range",
"trusted": "fd00::/8",
"peer": "fd00::2",
"forwarded": [
"2001:db8::9"
],
"want": "2001:db8::9"
}
]
}
}
+58
View File
@@ -0,0 +1,58 @@
import js from '@eslint/js';
import { defineConfig, globalIgnores } from 'eslint/config';
import svelte from 'eslint-plugin-svelte';
import globals from 'globals';
import tseslint from 'typescript-eslint';
// An unused binding is fine when its name starts with an underscore (a prop or argument kept for
// its position or its documentation).
const unusedUnderscore = [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' },
];
// Lints the JavaScript, TypeScript and Svelte first-party code. The Go, Python and Java packages
// have their own linters (gofmt and go vet, ruff), and generated output is never linted.
export default defineConfig([
globalIgnores([
'**/dist/**',
'**/.svelte-kit/**',
'**/node_modules/**',
'backend/**',
'contract/**',
'packages/java-backend/**',
'packages/python-backend/**',
'shared-styles.css',
]),
js.configs.recommended,
{ rules: { 'no-unused-vars': unusedUnderscore } },
{
files: ['**/*.ts', '**/*.svelte'],
extends: [tseslint.configs.recommended],
rules: { 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': unusedUnderscore },
},
svelte.configs.recommended,
{
files: ['packages/node-backend/**/*.js', 'scripts/**/*.{js,mjs}', 'eslint.config.js'],
languageOptions: { globals: globals.node },
},
{
files: ['packages/web-ui/**/*.{ts,svelte}'],
languageOptions: { globals: globals.browser },
},
{
files: ['**/*.svelte', '**/*.svelte.ts'],
languageOptions: { parserOptions: { parser: tseslint.parser } },
},
{
// These three Svelte rules ask for changes to how shipped components render or hold state
// (keyed each blocks, derived state, reactive Map and Set). That changes consumer-visible
// behaviour, so it is a decision for a component change, not for the lint set-up.
files: ['packages/web-ui/**/*.{ts,svelte}'],
rules: {
'svelte/require-each-key': 'off',
'svelte/prefer-writable-derived': 'off',
'svelte/prefer-svelte-reactivity': 'off',
},
},
]);
+2389 -17
View File
File diff suppressed because it is too large. Load diff
+18 -4
View File
@@ -38,14 +38,18 @@
"check": "npm run check --workspace=@gabriel20xx/web-ui", "check": "npm run check --workspace=@gabriel20xx/web-ui",
"build": "npm run package --workspace=@gabriel20xx/web-ui", "build": "npm run package --workspace=@gabriel20xx/web-ui",
"package": "npm run package --workspace=@gabriel20xx/web-ui", "package": "npm run package --workspace=@gabriel20xx/web-ui",
"lint": "npm run check && npm run lint:node", "lint": "npm run check && npm run lint:node && npm run lint:eslint",
"lint:node": "node scripts/check-node-syntax.mjs", "lint:node": "node scripts/check-node-syntax.mjs",
"test": "npm run build && npm run test:node-backend", "lint:eslint": "eslint . --max-warnings=0",
"format:check": "prettier --check eslint.config.js packages/web-ui/vitest.config.ts packages/web-ui/tests packages/node-backend/test/authstore.test.js packages/node-backend/test/contract.test.js",
"format": "prettier --write eslint.config.js packages/web-ui/vitest.config.ts packages/web-ui/tests packages/node-backend/test/authstore.test.js packages/node-backend/test/contract.test.js",
"test": "npm run build && npm run test:node-backend && npm run test:web-ui",
"test:node-backend": "npm test --workspace=@gabriel20xx/node-backend", "test:node-backend": "npm test --workspace=@gabriel20xx/node-backend",
"test:web-ui": "npm test --workspace=@gabriel20xx/web-ui",
"prepare": "npm run build && node scripts/build-root-styles.mjs", "prepare": "npm run build && node scripts/build-root-styles.mjs",
"changeset": "changeset", "changeset": "changeset",
"version-packages": "changeset version", "version-packages": "changeset version",
"release": "npm run build && npm run test:node-backend && changeset publish", "release": "npm run build && npm run test:node-backend && npm run test:web-ui && changeset publish",
"media:audit:html-js": "node scripts/media/audit-html-js.mjs", "media:audit:html-js": "node scripts/media/audit-html-js.mjs",
"media:audit:layout": "node scripts/media/audit-inline-layout.mjs", "media:audit:layout": "node scripts/media/audit-inline-layout.mjs",
"media:audit:layout:strict": "node scripts/media/audit-inline-layout.mjs --strict", "media:audit:layout:strict": "node scripts/media/audit-inline-layout.mjs --strict",
@@ -63,6 +67,16 @@
"pg": "^8.17.2" "pg": "^8.17.2"
}, },
"devDependencies": { "devDependencies": {
"@changesets/cli": "^2.29.8" "@changesets/cli": "^2.29.8",
"@eslint/js": "^10.0.1",
"@testing-library/svelte": "^5.4.2",
"eslint": "^10.13.0",
"eslint-plugin-svelte": "^3.23.1",
"globals": "^17.13.0",
"jsdom": "^30.1.3",
"prettier": "^3.9.10",
"prettier-plugin-svelte": "^4.1.1",
"typescript-eslint": "^8.72.0",
"vitest": "^5.0.5"
} }
} }
@@ -73,24 +73,21 @@ import java.util.regex.Pattern;
* this class can be built and tested in isolation (see this package's * this class can be built and tested in isolation (see this package's
* README); it targets Java 8 for the same reason. * README); it targets Java 8 for the same reason.
* *
* <p>{@link #validate(String)} still hand-parses AuthGuard's small, fixed * <p>{@link #validate(String)} parses AuthGuard's {@code GET /api/session/validate}
* {@code GET /api/session/validate} response shape with a few targeted * response with Jackson and reads top-level fields only, so a nested object
* regular expressions rather than Jackson, keeping the minimal * with the same field names cannot change the decision. {@code ResetManager},
* validate-only surface dependency-free beyond the JDK - {@code ResetManager}, * {@code Roles}, and {@code Totp}, the other classes in this package, use only
* {@code Roles}, and {@code Totp}, the other classes in this package, stay * the JDK. The full-proxy methods added below (register/login/setup/
* that way too. The full-proxy methods added below (register/login/setup/ * reset/admin-user-management) also build and parse a handful of small JSON
* reset/admin-user-management) are a different tradeoff: they must both * request/response bodies, which would be considerably worse hand-rolled, so
* build and parse a handful of small JSON request/response bodies, which * they use Jackson ({@code jackson-databind}) too. This makes {@code jackson-databind} a compile-time dependency of
* would be considerably worse hand-rolled than {@code validate}'s
* fixed-shape parsing, so they use Jackson ({@code jackson-databind})
* instead. This makes {@code jackson-databind} a compile-time dependency of
* this whole class (Java has no way to make an import conditional on which * this whole class (Java has no way to make an import conditional on which
* methods a given consumer actually calls) - acceptable here because * methods a given consumer actually calls) - acceptable here because
* MegaBasterd, this package's only verified consumer, already depends on * MegaBasterd, this package's only verified consumer, already depends on
* Jackson for its own code. A hypothetical future consumer that only ever * Jackson for its own code. A hypothetical future consumer that only ever
* calls {@code validate}/{@code middleware} and doesn't already carry * calls {@code validate}/{@code middleware} and doesn't already carry
* Jackson would need to add it just to compile this file; that tradeoff was * Jackson would need to add it just to compile this file; that tradeoff was
* chosen deliberately over hand-rolling JSON request bodies with regex. * chosen deliberately over hand-rolling JSON with regular expressions.
*/ */
public final class AuthClient { public final class AuthClient {
@@ -106,10 +103,6 @@ public final class AuthClient {
*/ */
public static final String PROJECT_KEY_HEADER = "X-Project-Key"; public static final String PROJECT_KEY_HEADER = "X-Project-Key";
private static final Pattern VALID_PATTERN = Pattern.compile("\"valid\"\\s*:\\s*(true|false)");
private static final Pattern USER_ID_PATTERN = Pattern.compile("\"user_id\"\\s*:\\s*(-?\\d+)");
private static final Pattern USERNAME_PATTERN = Pattern.compile("\"username\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
private static final Pattern ROLE_PATTERN = Pattern.compile("\"role\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
private static final String BEARER_PREFIX = "Bearer "; private static final String BEARER_PREFIX = "Bearer ";
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */ /** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
@@ -279,7 +272,8 @@ public final class AuthClient {
User user; User user;
try { try {
user = validate(token); user = validate(token);
} catch (InvalidSessionException | IOException ex) { } catch (InvalidSessionException | IOException | IllegalStateException ex) {
// IllegalStateException is a client with no base URL yet; it fails closed like Node's middleware.
return onUnauthorized.get(); return onUnauthorized.get();
} }
return onAuthenticated.handle(user); return onAuthenticated.handle(user);
@@ -829,59 +823,43 @@ public final class AuthClient {
return buffer.toString(StandardCharsets.UTF_8.name()); return buffer.toString(StandardCharsets.UTF_8.name());
} }
/** Defensively hand-parses AuthGuard's small, fixed response shape - see the class javadoc for why. */ /**
* Parses AuthGuard's response with Jackson and reads top-level fields only, so a nested object
* with the same field names cannot stand in for the real answer.
*/
private static RawPayload parsePayload(String body) { private static RawPayload parsePayload(String body) {
if (body == null || body.isEmpty()) { if (body == null || body.isEmpty()) {
throw new IllegalArgumentException("empty AuthGuard response body"); throw new IllegalArgumentException("empty AuthGuard response body");
} }
Matcher validMatcher = VALID_PATTERN.matcher(body); JsonNode root;
if (!validMatcher.find()) { try {
root = JSON.readTree(body);
} catch (IOException ex) {
throw new IllegalArgumentException("AuthGuard response is not JSON: " + ex.getMessage(), ex);
}
if (root == null || !root.isObject()) {
throw new IllegalArgumentException("AuthGuard response is not a JSON object");
}
JsonNode validNode = root.get("valid");
if (validNode == null || !validNode.isBoolean()) {
throw new IllegalArgumentException("missing \"valid\" field in AuthGuard response"); throw new IllegalArgumentException("missing \"valid\" field in AuthGuard response");
} }
boolean valid = Boolean.parseBoolean(validMatcher.group(1));
long userId = 0L; long userId = 0L;
Matcher userIdMatcher = USER_ID_PATTERN.matcher(body); JsonNode userIdNode = root.get("user_id");
if (userIdMatcher.find()) { if (userIdNode != null && userIdNode.isIntegralNumber()) {
userId = Long.parseLong(userIdMatcher.group(1)); if (!userIdNode.canConvertToLong()) {
throw new IllegalArgumentException("user_id is out of range in AuthGuard response");
}
userId = userIdNode.longValue();
} }
return new RawPayload(valid, userId, extractString(USERNAME_PATTERN, body), extractString(ROLE_PATTERN, body)); return new RawPayload(validNode.booleanValue(), userId, textualField(root, "username"), textualField(root, "role"));
} }
private static String extractString(Pattern pattern, String body) { private static String textualField(JsonNode root, String name) {
Matcher matcher = pattern.matcher(body); JsonNode node = root.get(name);
return matcher.find() ? unescapeJson(matcher.group(1)) : ""; return node != null && node.isTextual() ? node.textValue() : "";
}
private static String unescapeJson(String raw) {
StringBuilder result = new StringBuilder(raw.length());
for (int index = 0; index < raw.length(); index++) {
char current = raw.charAt(index);
if (current != '\\' || index + 1 >= raw.length()) {
result.append(current);
continue;
}
char next = raw.charAt(++index);
switch (next) {
case '"': result.append('"'); break;
case '\\': result.append('\\'); break;
case '/': result.append('/'); break;
case 'n': result.append('\n'); break;
case 't': result.append('\t'); break;
case 'r': result.append('\r'); break;
case 'b': result.append('\b'); break;
case 'f': result.append('\f'); break;
case 'u':
if (index + 4 < raw.length()) {
result.append((char) Integer.parseInt(raw.substring(index + 1, index + 5), 16));
index += 4;
}
break;
default: result.append(next);
}
}
return result.toString();
} }
private static final class RawPayload { private static final class RawPayload {
@@ -2,6 +2,7 @@ package com.gabriel20xx.shared.auth;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.Locale; import java.util.Locale;
import javax.crypto.Mac; import javax.crypto.Mac;
@@ -77,7 +78,8 @@ public final class Totp {
| ((hash[index + 2] & 0xff) << 8) | ((hash[index + 2] & 0xff) << 8)
| (hash[index + 3] & 0xff); | (hash[index + 3] & 0xff);
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000); String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
if (candidate.equals(normalizedToken)) { if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII),
normalizedToken.getBytes(StandardCharsets.US_ASCII))) {
return true; return true;
} }
} catch (Exception ex) { } catch (Exception ex) {
@@ -278,6 +278,54 @@ class AuthClientTest {
assertEquals("user", result.role); assertEquals("user", result.role);
} }
@Test
void validateReadsTopLevelFieldsOnlyWhenNestedFieldsRepeatThem() throws Exception {
// The nested object says valid:true, but the top-level answer is valid:false, so the session is invalid.
server = fakeAuthGuard(200, "{\"session\":{\"valid\":true,\"user_id\":99,\"username\":\"evil\",\"role\":\"admin\"},\"valid\":false}");
AuthClient client = new AuthClient(baseUrl(server));
assertThrows(InvalidSessionException.class, () -> client.validate("token"));
}
@Test
void validateIgnoresANestedValidFieldWhenTheTopLevelOneIsMissing() throws Exception {
server = fakeAuthGuard(200, "{\"data\":{\"valid\":true,\"user_id\":5,\"username\":\"x\",\"role\":\"admin\"}}");
AuthClient client = new AuthClient(baseUrl(server));
assertThrows(IOException.class, () -> client.validate("token"));
}
@Test
void validateAcceptsReorderedTopLevelFields() throws Exception {
server = fakeAuthGuard(200, "{\"username\":\"gabriel\",\"role\":\"admin\",\"user_id\":7,\"valid\":true}");
AuthClient client = new AuthClient(baseUrl(server));
AuthClient.User user = client.validate("token");
assertEquals(7L, user.id);
assertEquals("gabriel", user.username);
assertEquals("admin", user.role);
}
@Test
void validateDecodesEscapedUsernames() throws Exception {
server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":3,\"username\":\"a\\\"b\\u00e9\",\"role\":\"user\"}");
AuthClient client = new AuthClient(baseUrl(server));
assertEquals("a\"b\u00e9", client.validate("token").username);
}
@Test
void middlewareFailsClosedOnAClientWithNoBaseUrlYet() throws Exception {
AuthClient client = new AuthClient("");
Function<String, String> headerLookup = name -> "Authorization".equals(name) ? "Bearer some-token" : null;
String result = client.middleware(headerLookup, null,
user -> "authenticated", () -> "unauthorized");
assertEquals("unauthorized", result);
}
/** Like fakeAuthGuard, but for one arbitrary path instead of the fixed /api/session/validate one. */ /** Like fakeAuthGuard, but for one arbitrary path instead of the fixed /api/session/validate one. */
private static HttpServer fakeEndpoint(String path, int status, String body) throws IOException { private static HttpServer fakeEndpoint(String path, int status, String body) throws IOException {
return fakeEndpointCapturingRequest(path, status, body, new String[0]); return fakeEndpointCapturingRequest(path, status, body, new String[0]);
@@ -0,0 +1,76 @@
package com.gabriel20xx.shared.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.Test;
class ResetManagerTest {
@Test
void requestReturnsAnEightDigitHexCodeAndPrintsIt() {
ResetManager manager = new ResetManager();
PrintStream original = System.out;
ByteArrayOutputStream captured = new ByteArrayOutputStream();
System.setOut(new PrintStream(captured));
String code;
try {
code = manager.request();
} finally {
System.setOut(original);
}
assertTrue(code.matches("[0-9A-F]{8}"));
assertTrue(captured.toString().contains("ADMIN RESET CODE: " + code));
}
@Test
void confirmAcceptsTheCodeOnceAndTrimsAndCase() {
ResetManager manager = new ResetManager();
String code = quietRequest(manager);
assertFalse(manager.confirm(null));
assertTrue(manager.confirm(" " + code.toLowerCase() + " "));
assertFalse(manager.confirm(code));
}
@Test
void confirmRejectsAWrongCodeButKeepsTheCodeRetryable() {
ResetManager manager = new ResetManager();
String code = quietRequest(manager);
String wrong = code.charAt(0) == '0' ? "1" + code.substring(1) : "0" + code.substring(1);
assertFalse(manager.confirm(wrong));
assertTrue(manager.confirm(code));
}
@Test
void confirmFailsWithoutARequestedCode() {
assertFalse(new ResetManager().confirm("00000000"));
}
@Test
void aNewRequestInvalidatesThePreviousCode() {
ResetManager manager = new ResetManager();
String first = quietRequest(manager);
String second = quietRequest(manager);
if (!first.equals(second)) {
assertFalse(manager.confirm(first));
}
assertTrue(manager.confirm(second));
}
private static String quietRequest(ResetManager manager) {
PrintStream original = System.out;
System.setOut(new PrintStream(new ByteArrayOutputStream()));
try {
return manager.request();
} finally {
System.setOut(original);
}
}
}
@@ -0,0 +1,36 @@
package com.gabriel20xx.shared.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class RolesTest {
@Test
void normalizeIsCaseInsensitiveAndDefaultsToUser() {
assertEquals(Roles.SUPERADMIN, Roles.normalize(" SuperAdmin "));
assertEquals(Roles.ADMIN, Roles.normalize("ADMIN"));
assertEquals(Roles.USER, Roles.normalize("moderator"));
assertEquals(Roles.USER, Roles.normalize(""));
assertEquals(Roles.USER, Roles.normalize(null));
}
@Test
void onlyAdminRolesCanManageUsers() {
assertTrue(Roles.canManageUsers(Roles.SUPERADMIN));
assertTrue(Roles.canManageUsers(Roles.ADMIN));
assertFalse(Roles.canManageUsers(Roles.USER));
assertFalse(Roles.canManageUsers("moderator"));
}
@Test
void onlySuperadminCanAssignNonSuperadminRoles() {
assertTrue(Roles.canAssignRole(Roles.SUPERADMIN, Roles.ADMIN));
assertTrue(Roles.canAssignRole(Roles.SUPERADMIN, Roles.USER));
assertFalse(Roles.canAssignRole(Roles.SUPERADMIN, Roles.SUPERADMIN));
assertFalse(Roles.canAssignRole(Roles.ADMIN, Roles.USER));
assertFalse(Roles.canAssignRole(Roles.USER, Roles.USER));
}
}
@@ -0,0 +1,76 @@
package com.gabriel20xx.shared.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class TotpTest {
// RFC 6238 SHA-1 test secret "12345678901234567890", base32-encoded.
private static final String RFC_SECRET = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
@Test
void verifyAcceptsTheRfc6238Vectors() {
// 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, "081804", 1_111_111_109_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, "279037", 2_000_000_000_000L));
}
@Test
void verifyAcceptsOneStepEitherSideOfTheCurrentTime() {
// At t=59 the counter is 1. Counter 0 (t=0) and counter 2 (t=60) are inside the window.
assertTrue(Totp.verify(RFC_SECRET, "755224", 59_000L));
assertTrue(Totp.verify(RFC_SECRET, "359152", 59_000L));
}
@Test
void verifyRejectsCodesOutsideTheWindow() {
// Counter 3 (t=90) is two steps ahead of counter 1; 2 steps behind would need a negative counter.
assertFalse(Totp.verify(RFC_SECRET, "969429", 59_000L));
}
@Test
void verifyRejectsMalformedInput() {
assertFalse(Totp.verify(RFC_SECRET, null, 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "", 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "28708", 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "28708a", 59_000L));
assertFalse(Totp.verify(RFC_SECRET, "2870821", 59_000L));
assertFalse(Totp.verify("", "287082", 59_000L));
assertFalse(Totp.verify(null, "287082", 59_000L));
assertFalse(Totp.verify("not base32!", "287082", 59_000L));
}
@Test
void verifyTrimsWhitespaceAroundTheCode() {
assertTrue(Totp.verify(RFC_SECRET, " 287082 ", 59_000L));
}
@Test
void verifyAcceptsASecretWithSpacesAndPadding() {
String spaced = "GEZD GNBV GY3T QOJQ GEZD GNBV GY3T QOJQ====";
assertTrue(Totp.verify(spaced, "287082", 59_000L));
}
@Test
void generatedSecretsAreBase32OfTheExpectedLength() {
String first = Totp.generateSecret();
String second = Totp.generateSecret();
assertEquals(32, first.length());
assertTrue(first.matches("[A-Z2-7]+"));
assertFalse(first.equals(second));
}
@Test
void provisioningUriCarriesTheSecretAndParameters() {
String uri = Totp.provisioningUri("Shared App", "gabriel", RFC_SECRET);
assertTrue(uri.startsWith("otpauth://totp/Shared%20App%3Agabriel?secret=" + RFC_SECRET));
assertTrue(uri.contains("&issuer=Shared%20App"));
assertTrue(uri.endsWith("&algorithm=SHA1&digits=6&period=30"));
}
}
+13 -6
View File
@@ -3,8 +3,8 @@
Shared Node.js backend infrastructure for services that use PostgreSQL: Shared Node.js backend infrastructure for services that use PostgreSQL:
- validated `DATABASE_URL` and pool settings; - validated `DATABASE_URL` and pool settings;
- one pool owner with startup retry, transient query retry, transactions, and shutdown; - one pool owner with startup retry, transient retry for read-only queries, transactions, and shutdown;
- PBKDF2 password hashing and secure session-token helpers; - PBKDF2 password hashing (`verifyAndUpgradePasswordAsync` returns a current-scheme hash for a login to store) and secure session-token helpers;
- short-lived, one-time admin reset codes printed to the server console; - short-lived, one-time admin reset codes printed to the server console;
- common account/session persistence; - common account/session persistence;
- transaction-locked ordered migrations. - transaction-locked ordered migrations.
@@ -20,7 +20,9 @@ share one PostgreSQL database, so their migration histories cannot collide.
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely). `250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`. Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`; `npm run lint` runs ESLint with the repository's config.
`AuthClient`'s `register`, `login`, `totpVerify`, `totpDisable`, `requestPasswordReset` and `confirmPasswordReset` take an optional trailing `{ clientIp }`, sent to AuthGuard as `X-Forwarded-For` so its per-address limits see the end user. Pass an address you have verified (for example the socket peer, or `X-Forwarded-For` only from a proxy you trust), never a raw request header. `AuthStore` refuses an empty password hash and a username containing `@`, refuses `setTotpSecret` while TOTP is enabled (error code `AUTH_TOTP_ALREADY_ENABLED`), and makes usernames unique ignoring case when no clashing pair already exists.
## `authclient`/`coreconfig`: adopting AuthGuard instead of local auth ## `authclient`/`coreconfig`: adopting AuthGuard instead of local auth
@@ -39,7 +41,7 @@ live whenever ProjectConfigurator pushes a fresh
`authClient.setBaseUrl` so a project never needs to hardcode `AUTHGUARD_URL`: `authClient.setBaseUrl` so a project never needs to hardcode `AUTHGUARD_URL`:
```js ```js
import { AuthClient, CoreConfigStore } from '@gabriel20xx/node-backend'; import { AuthClient, CoreConfigStore, internalSecretMatches } from '@gabriel20xx/node-backend';
const authClient = new AuthClient(''); const authClient = new AuthClient('');
const coreConfig = new CoreConfigStore({ authGuardUrl: '' }); const coreConfig = new CoreConfigStore({ authGuardUrl: '' });
@@ -47,10 +49,15 @@ coreConfig.onUpdate((info) => authClient.setBaseUrl(info.authGuardUrl));
// in your own route for PUT /api/core-services/internal: // in your own route for PUT /api/core-services/internal:
app.put('/api/core-services/internal', (req, res) => { app.put('/api/core-services/internal', (req, res) => {
if (req.get('X-Internal-Auth') !== process.env.SECRET) { if (!internalSecretMatches(req.get('X-Internal-Auth'), process.env.SECRET)) {
return res.status(401).json({ error: 'internal service authentication required' }); return res.status(401).json({ error: 'internal service authentication required' });
} }
const info = coreConfig.set(req.body); let info;
try {
info = coreConfig.set(req.body);
} catch (error) {
return res.status(400).json({ error: error.message });
}
res.json({ ok: true, info: info.toJSON() }); res.json({ ok: true, info: info.toJSON() });
}); });
``` ```
+2 -1
View File
@@ -22,7 +22,8 @@
"pg": "^8.17.2" "pg": "^8.17.2"
}, },
"scripts": { "scripts": {
"test": "node --test" "test": "node --test",
"lint": "eslint ."
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"
+174 -24
View File
@@ -1,8 +1,17 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import { promisify } from 'node:util';
const PASSWORD_ITERATIONS = 100000; const pbkdf2 = promisify(crypto.pbkdf2);
// Hashes written before the format recorded its parameters are `salt:hex` at
// 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 PASSWORD_ITERATIONS = 600000;
const PASSWORD_KEY_LENGTH = 32; const PASSWORD_KEY_LENGTH = 32;
const PASSWORD_DIGEST = 'sha256'; const PASSWORD_DIGEST = 'sha256';
const PASSWORD_FORMAT = 'pbkdf2-sha256';
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' });
@@ -53,33 +62,157 @@ CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id); CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
`; `;
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) { // Usernames are unique ignoring case ("Admin" and "admin" are one identity to a reader). The index
// is created only while no such pair exists, so a database that already holds one still starts and
// raises a warning; it is built on the first start after one account of each pair is renamed.
const USERNAME_CASE_INDEX = `
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM auth_users GROUP BY lower(username) HAVING count(*) > 1) THEN
RAISE WARNING 'auth_users holds usernames that differ only by case; the case-insensitive username index was not created';
ELSE
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx ON auth_users (lower(username));
END IF;
EXCEPTION WHEN unique_violation THEN
RAISE WARNING 'the case-insensitive username index was not created: a clashing username was just added';
END
$$
`;
function authError(message, code) {
const error = new Error(message);
error.code = code;
return error;
}
// Refuses a write that would leave an account without a password hash, or store a username that
// could be mistaken for another account's email. undefined means "leave unchanged".
function assertCredentials(username, passwordHash) {
if (passwordHash !== undefined && !passwordHash) {
throw authError('password hash is required', 'AUTH_EMPTY_PASSWORD_HASH');
}
if (typeof username === 'string' && username.includes('@')) {
throw authError('username cannot contain @', 'AUTH_INVALID_USERNAME');
}
}
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');
} }
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return `${salt}:${hash.toString('hex')}`;
} }
function encodePasswordHash(salt, hash, iterations) {
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);
if (text.startsWith(`${PASSWORD_FORMAT}$`)) {
const parts = text.split('$');
if (parts.length !== 4) return null;
const [, iterations, salt, expected] = parts;
return { iterations: Number(iterations), salt, expected, legacy: false };
}
if (LEGACY_PASSWORD_PATTERN.test(text)) {
const [salt, expected] = text.split(':');
return { iterations: LEGACY_PASSWORD_ITERATIONS, salt, expected, legacy: true };
}
return null;
}
function usablePasswordHash(stored) {
const parsed = parsePasswordHash(stored);
if (!parsed || !parsed.salt || !parsed.expected || !isValidIterations(parsed.iterations)) return null;
return parsed;
}
function isValidIterations(iterations) {
return Number.isSafeInteger(iterations) && iterations >= 1;
}
function passwordHashMatches(expected, actual) {
const expectedBytes = Buffer.from(expected, 'hex');
return expectedBytes.length === actual.length && crypto.timingSafeEqual(expectedBytes, actual);
}
/**
* Blocking PBKDF2 hash. Prefer hashPasswordAsync in request handlers, because
* this call holds the event loop for the whole derivation.
*/
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
assertPasswordLength(password);
const salt = crypto.randomBytes(16).toString('hex');
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. */
export async function hashPasswordAsync(password, { iterations = PASSWORD_ITERATIONS } = {}) {
assertPasswordLength(password);
return derivePasswordHashAsync(password, iterations);
}
// The length rule belongs to user-facing hashing. Upgrading an old hash must
// not refuse a password that was accepted when it was first set.
async function derivePasswordHashAsync(password, iterations) {
const salt = crypto.randomBytes(16).toString('hex');
const hash = await pbkdf2(String(password), salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return encodePasswordHash(salt, hash, iterations);
}
/** Blocking verify. Prefer verifyPasswordAsync in request handlers. */
export function verifyPassword(password, stored) { export function verifyPassword(password, stored) {
try { try {
const [salt, expected] = String(stored).split(':'); const parsed = usablePasswordHash(stored);
if (!salt || !expected) return false; if (!parsed) return false;
const actual = crypto.pbkdf2Sync( const actual = crypto.pbkdf2Sync(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
String(password), return passwordHashMatches(parsed.expected, actual);
salt,
PASSWORD_ITERATIONS,
PASSWORD_KEY_LENGTH,
PASSWORD_DIGEST
);
const expectedBytes = Buffer.from(expected, 'hex');
return expectedBytes.length === actual.length && crypto.timingSafeEqual(expectedBytes, actual);
} catch { } catch {
return false; return false;
} }
} }
/** Non-blocking variant of verifyPassword. */
export async function verifyPasswordAsync(password, stored) {
try {
const parsed = usablePasswordHash(stored);
if (!parsed) return false;
const actual = await pbkdf2(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return passwordHashMatches(parsed.expected, actual);
} catch {
return false;
}
}
/**
* True when a stored hash should be rewritten after a successful login: a
* legacy `salt:hex` hash, or a PBKDF2 hash below PASSWORD_ITERATIONS.
*/
export function passwordHashNeedsUpgrade(stored) {
const parsed = parsePasswordHash(stored);
return !parsed || parsed.legacy || parsed.iterations < PASSWORD_ITERATIONS;
}
/**
* Verifies a password and, when it matches a hash in an older scheme, returns a
* replacement in the current scheme. The caller stores upgradedHash, for example
* with AuthStore.updateUser(id, { passwordHash }). upgradedHash is null when the
* password does not match or no rewrite is needed.
*/
export async function verifyAndUpgradePasswordAsync(password, stored) {
if (!(await verifyPasswordAsync(password, stored))) {
return { valid: false, upgradedHash: null };
}
if (!passwordHashNeedsUpgrade(stored)) {
return { valid: true, upgradedHash: null };
}
return { valid: true, upgradedHash: await derivePasswordHashAsync(password, PASSWORD_ITERATIONS) };
}
export function createSessionToken() { export function createSessionToken() {
const token = crypto.randomBytes(32).toString('base64url'); const token = crypto.randomBytes(32).toString('base64url');
return { token, tokenHash: hashToken(token) }; return { token, tokenHash: hashToken(token) };
@@ -143,6 +276,7 @@ export class AuthStore {
async ensureSchema() { async ensureSchema() {
await this.database.query(AUTH_SCHEMA); await this.database.query(AUTH_SCHEMA);
await this.database.query(USERNAME_CASE_INDEX);
if (this.singleUser) { if (this.singleUser) {
await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))'); await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))');
} else { } else {
@@ -156,6 +290,7 @@ export class AuthStore {
} }
async createUser(username, email, passwordHash) { async createUser(username, email, passwordHash) {
assertCredentials(username, passwordHash ?? '');
try { try {
const result = await this.database.query( const result = await this.database.query(
`INSERT INTO auth_users (username, email, password_hash, role, updated_at) `INSERT INTO auth_users (username, email, password_hash, role, updated_at)
@@ -177,15 +312,20 @@ export class AuthStore {
} }
async findByIdentifier(identifier) { async findByIdentifier(identifier) {
const result = await this.database.query( // Usernames are tried before emails, so an identifier resolves to one account in a fixed order.
`SELECT id, username, email, password_hash, role, created_at, updated_at for (const condition of ['username = $1', 'lower(email) = lower($1)']) {
FROM auth_users WHERE username = $1 OR lower(email) = lower($1)`, const result = await this.database.query(
[identifier] `SELECT id, username, email, password_hash, role, created_at, updated_at
); FROM auth_users WHERE ${condition}`,
return result.rows[0] || null; [identifier]
);
if (result.rows[0]) return result.rows[0];
}
return null;
} }
async updateCredentials(id, username, email, passwordHash) { async updateCredentials(id, username, email, passwordHash) {
assertCredentials(username, passwordHash ?? '');
await this.database.query( await this.database.query(
`UPDATE auth_users SET username = $1, email = $2, password_hash = $3, updated_at = now() `UPDATE auth_users SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4`, WHERE id = $4`,
@@ -226,6 +366,7 @@ export class AuthStore {
} }
async createManagedUser(username, email, passwordHash, role = USER_ROLES.USER) { async createManagedUser(username, email, passwordHash, role = USER_ROLES.USER) {
assertCredentials(username, passwordHash ?? '');
try { try {
const result = await this.database.query( const result = await this.database.query(
`INSERT INTO auth_users (username, email, password_hash, role, updated_at) `INSERT INTO auth_users (username, email, password_hash, role, updated_at)
@@ -245,6 +386,7 @@ export class AuthStore {
} }
async updateUser(id, { username, email, passwordHash, role } = {}) { async updateUser(id, { username, email, passwordHash, role } = {}) {
assertCredentials(username, passwordHash);
const fields = []; const fields = [];
const values = []; const values = [];
const add = (sql, value) => { fields.push(sql); values.push(value); }; const add = (sql, value) => { fields.push(sql); values.push(value); };
@@ -276,11 +418,19 @@ export class AuthStore {
return result.rows[0] || { secret: '', enabled: false }; return result.rows[0] || { secret: '', enabled: false };
} }
/**
* Stores a pending secret without enabling two-factor auth. Throws an error with code
* AUTH_TOTP_ALREADY_ENABLED while it is enabled, so a replaced secret cannot silently switch the
* second factor off.
*/
async setTotpSecret(userId, secret) { async setTotpSecret(userId, secret) {
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', 'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled',
[secret, userId], [secret, userId],
); );
if (result.rowCount === 0 && (await this.getTotpState(userId)).enabled) {
throw authError('TOTP is already enabled; disable it before setting a new secret', 'AUTH_TOTP_ALREADY_ENABLED');
}
} }
async enableTotp(userId) { async enableTotp(userId) {
+82 -13
View File
@@ -22,8 +22,16 @@
// requestPasswordReset/confirmPasswordReset, list/create/update/delete // requestPasswordReset/confirmPasswordReset, list/create/update/delete
// ManagedUser(s), setupStatus. // ManagedUser(s), setupStatus.
import { createHash } from 'node:crypto';
import { isIP } from 'node:net';
const DEFAULT_COOKIE_NAME = 'auth_session'; const DEFAULT_COOKIE_NAME = 'auth_session';
const DEFAULT_TIMEOUT_MS = 5000; const DEFAULT_TIMEOUT_MS = 5000;
// validate() results, positive and negative, are reused for this long so a burst of requests
// with one token costs one AuthGuard call. Revocation through this client (logout) clears the
// entry at once; revocation elsewhere is seen within the TTL. Mirrors the Go client.
const VALIDATION_CACHE_TTL_MS = 2000;
const MAX_VALIDATION_CACHE_ENTRIES = 10000;
// PROJECT_KEY_HEADER is the header AuthClient attaches to every request when // PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
// constructed with a projectKey, identifying the calling project to // constructed with a projectKey, identifying the calling project to
@@ -31,6 +39,14 @@ const DEFAULT_TIMEOUT_MS = 5000;
// AuthGuard's project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader. // AuthGuard's project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
export const PROJECT_KEY_HEADER = 'X-Project-Key'; export const PROJECT_KEY_HEADER = 'X-Project-Key';
// FORWARDED_FOR_HEADER carries the end user's address on the credential calls (the `clientIp`
// option of register, login, totpVerify, totpDisable and the password-reset calls), so AuthGuard's
// per-address limits see the end user instead of this service. AuthGuard reads it only when the
// calling service's own address is in its TRUSTED_PROXIES, so sending it changes nothing for a
// deployment that has not opted in. Pass an address the caller has already verified, never a raw
// request header; anything that is not an IP address is ignored.
export const FORWARDED_FOR_HEADER = 'X-Forwarded-For';
export class InvalidSessionError extends Error { export class InvalidSessionError extends Error {
constructor(message = 'authclient: invalid or missing session') { constructor(message = 'authclient: invalid or missing session') {
super(message); super(message);
@@ -81,6 +97,40 @@ export class AuthClient {
// Normally a project's own lowercase identifier, matching the key // Normally a project's own lowercase identifier, matching the key
// ProjectConfigurator registers it under. // ProjectConfigurator registers it under.
this.projectKey = String(options.projectKey ?? '').trim().toLowerCase(); this.projectKey = String(options.projectKey ?? '').trim().toLowerCase();
this._validationCache = new Map();
}
_validationKey(token) {
return createHash('sha256').update(token).digest('hex');
}
/** Returns the cached validate() outcome for token: a user, null for a known-invalid session, or undefined on a miss. */
_cachedValidation(token) {
const key = this._validationKey(token);
const entry = this._validationCache.get(key);
if (!entry) return undefined;
if (Date.now() >= entry.expires) {
this._validationCache.delete(key);
return undefined;
}
return entry.user;
}
_cacheValidation(token, user) {
if (this._validationCache.size >= MAX_VALIDATION_CACHE_ENTRIES) {
const now = Date.now();
for (const [key, entry] of this._validationCache) {
if (now >= entry.expires) this._validationCache.delete(key);
}
if (this._validationCache.size >= MAX_VALIDATION_CACHE_ENTRIES) {
// Map keeps insertion order, so this drops the oldest entry.
this._validationCache.delete(this._validationCache.keys().next().value);
}
}
this._validationCache.set(this._validationKey(token), {
user,
expires: Date.now() + VALIDATION_CACHE_TTL_MS,
});
} }
_projectKeyHeaders() { _projectKeyHeaders() {
@@ -105,6 +155,7 @@ export class AuthClient {
const normalized = AuthClient._normalizeBaseUrl(baseUrl); const normalized = AuthClient._normalizeBaseUrl(baseUrl);
if (normalized) { if (normalized) {
this.baseUrl = normalized; this.baseUrl = normalized;
this._validationCache.clear();
} }
} }
@@ -172,6 +223,13 @@ export class AuthClient {
if (!trimmed) { if (!trimmed) {
throw new InvalidSessionError(); throw new InvalidSessionError();
} }
const cached = this._cachedValidation(trimmed);
if (cached === null) {
throw new InvalidSessionError();
}
if (cached !== undefined) {
return { ...cached };
}
const controller = new AbortController(); const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs); const timer = setTimeout(() => controller.abort(), this.timeoutMs);
@@ -192,15 +250,22 @@ export class AuthClient {
payload = await response.json(); payload = await response.json();
} catch (err) { } catch (err) {
if (response.status === 401) { if (response.status === 401) {
this._cacheValidation(trimmed, null);
throw new InvalidSessionError(); throw new InvalidSessionError();
} }
throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err }); throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err });
} }
if (response.status !== 200 || !payload?.valid) { if (response.status === 401 || (response.status === 200 && !payload?.valid)) {
this._cacheValidation(trimmed, null);
throw new InvalidSessionError(); throw new InvalidSessionError();
} }
return { id: payload.user_id, username: payload.username, role: payload.role }; if (response.status !== 200) {
throw new InvalidSessionError();
}
const user = { id: payload.user_id, username: payload.username, role: payload.role };
this._cacheValidation(trimmed, user);
return { ...user };
} }
/** /**
@@ -258,13 +323,14 @@ export class AuthClient {
* AuthClient._call exactly. * AuthClient._call exactly.
* @returns {Promise<{payload: any, cookies: string[]}>} * @returns {Promise<{payload: any, cookies: string[]}>}
*/ */
async _call(method, path, { token = '', body } = {}) { async _call(method, path, { token = '', body, clientIp } = {}) {
if (!this.baseUrl) { if (!this.baseUrl) {
throw new Error('authclient: client has no base URL'); throw new Error('authclient: client has no base URL');
} }
const headers = { ...this._projectKeyHeaders() }; const headers = { ...this._projectKeyHeaders() };
if (body !== undefined) headers['Content-Type'] = 'application/json'; if (body !== undefined) headers['Content-Type'] = 'application/json';
if (token) headers.Authorization = `Bearer ${token}`; if (token) headers.Authorization = `Bearer ${token}`;
if (typeof clientIp === 'string' && isIP(clientIp.trim())) headers[FORWARDED_FOR_HEADER] = clientIp.trim();
const controller = new AbortController(); const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs); const timer = setTimeout(() => controller.abort(), this.timeoutMs);
@@ -353,9 +419,10 @@ export class AuthClient {
* starting a session for it. * starting a session for it.
* @returns {Promise<{user: object, cookies: string[]}>} * @returns {Promise<{user: object, cookies: string[]}>}
*/ */
async register(username, email, password) { async register(username, email, password, { clientIp } = {}) {
const { payload, cookies } = await this._call('POST', '/api/register', { const { payload, cookies } = await this._call('POST', '/api/register', {
body: { username, email, password }, body: { username, email, password },
clientIp,
}); });
return { user: AuthClient._publicUser(payload), cookies }; return { user: AuthClient._publicUser(payload), cookies };
} }
@@ -366,10 +433,10 @@ export class AuthClient {
* enabled and no valid code was supplied. * enabled and no valid code was supplied.
* @returns {Promise<{user: object, cookies: string[]}>} * @returns {Promise<{user: object, cookies: string[]}>}
*/ */
async login(usernameOrEmail, password, totpToken = '') { async login(usernameOrEmail, password, totpToken = '', { clientIp } = {}) {
const body = { username_or_email: usernameOrEmail, password }; const body = { username_or_email: usernameOrEmail, password };
if (totpToken) body.totp_token = totpToken; if (totpToken) body.totp_token = totpToken;
const { payload, cookies } = await this._call('POST', '/api/login', { body }); const { payload, cookies } = await this._call('POST', '/api/login', { body, clientIp });
return { user: AuthClient._publicUser(payload), cookies }; return { user: AuthClient._publicUser(payload), cookies };
} }
@@ -381,6 +448,7 @@ export class AuthClient {
*/ */
async logout(token) { async logout(token) {
const { cookies } = await this._call('POST', '/api/logout', { token }); const { cookies } = await this._call('POST', '/api/logout', { token });
this._validationCache.delete(this._validationKey(String(token ?? '').trim()));
return cookies; return cookies;
} }
@@ -411,8 +479,8 @@ export class AuthClient {
* Calls POST /api/totp/verify, confirming code against the pending * Calls POST /api/totp/verify, confirming code against the pending
* secret totpEnable provisioned and activating two-factor auth. * secret totpEnable provisioned and activating two-factor auth.
*/ */
async totpVerify(token, code) { async totpVerify(token, code, { clientIp } = {}) {
await this._call('POST', '/api/totp/verify', { token, body: { token: code } }); await this._call('POST', '/api/totp/verify', { token, body: { token: code }, clientIp });
} }
/** /**
@@ -420,8 +488,8 @@ export class AuthClient {
* account. AuthGuard requires code to be one last valid TOTP code as * account. AuthGuard requires code to be one last valid TOTP code as
* proof of possession. * proof of possession.
*/ */
async totpDisable(token, code) { async totpDisable(token, code, { clientIp } = {}) {
await this._call('POST', '/api/totp/disable', { token, body: { token: code } }); await this._call('POST', '/api/totp/disable', { token, body: { token: code }, clientIp });
} }
// --- password reset ("break glass", console-only - see AuthGuard's README) -- // --- password reset ("break glass", console-only - see AuthGuard's README) --
@@ -434,9 +502,9 @@ export class AuthClient {
* the intended place to drive this, not an individual project (see * the intended place to drive this, not an individual project (see
* AuthGuard's README's "Web UI" section). * AuthGuard's README's "Web UI" section).
*/ */
async requestPasswordReset(usernameOrEmail = '') { async requestPasswordReset(usernameOrEmail = '', { clientIp } = {}) {
const body = usernameOrEmail ? { username_or_email: usernameOrEmail } : {}; const body = usernameOrEmail ? { username_or_email: usernameOrEmail } : {};
await this._call('POST', '/api/password-reset/request', { body }); await this._call('POST', '/api/password-reset/request', { body, clientIp });
} }
/** /**
@@ -444,9 +512,10 @@ export class AuthClient {
* relayed out-of-band and a new password, and invalidates every * relayed out-of-band and a new password, and invalidates every
* existing session for that account. * existing session for that account.
*/ */
async confirmPasswordReset(code, newPassword) { async confirmPasswordReset(code, newPassword, { clientIp } = {}) {
await this._call('POST', '/api/password-reset/confirm', { await this._call('POST', '/api/password-reset/confirm', {
body: { code, password: newPassword }, body: { code, password: newPassword },
clientIp,
}); });
} }
+41 -3
View File
@@ -18,6 +18,8 @@
* example. * example.
*/ */
import crypto from 'node:crypto';
/** /**
* @typedef {{authGuardUrl?: string, carrierNodeUrl?: string, carrierNodeUrls?: string[]}} InfoLike * @typedef {{authGuardUrl?: string, carrierNodeUrl?: string, carrierNodeUrls?: string[]}} InfoLike
*/ */
@@ -58,6 +60,29 @@ export class Info {
} }
} }
/**
* True when the X-Internal-Auth value equals the configured secret. An unset
* or empty secret never matches, and the comparison is constant-time.
* @param {unknown} provided
* @param {unknown} secret
* @returns {boolean}
*/
export function internalSecretMatches(provided, secret) {
const expected = Buffer.from(String(secret ?? ''));
if (expected.length === 0) return false;
const actual = Buffer.from(String(provided ?? ''));
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
}
function isServiceUrl(value) {
try {
const url = new URL(value);
return (url.protocol === 'http:' || url.protocol === 'https:') && url.host !== '';
} catch {
return false;
}
}
function normalize(info) { function normalize(info) {
let cleaned = (info.carrierNodeUrls ?? []).map((u) => String(u ?? '').trim()).filter(Boolean); let cleaned = (info.carrierNodeUrls ?? []).map((u) => String(u ?? '').trim()).filter(Boolean);
if (cleaned.length === 0 && String(info.carrierNodeUrl ?? '').trim()) { if (cleaned.length === 0 && String(info.carrierNodeUrl ?? '').trim()) {
@@ -115,13 +140,20 @@ export class Store {
/** /**
* Replaces the current Info, field by field, ignoring a blank/empty field * Replaces the current Info, field by field, ignoring a blank/empty field
* so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers * so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers
* the other value. Returns the resulting Info. Minimal Express usage: * the other value. Every URL must be an http or https URL with a host;
* otherwise nothing is changed and an error is thrown. Returns the resulting
* Info. Minimal Express usage:
* *
* app.put('/api/core-services/internal', (req, res) => { * app.put('/api/core-services/internal', (req, res) => {
* if (req.get('X-Internal-Auth') !== process.env.SECRET) { * if (!internalSecretMatches(req.get('X-Internal-Auth'), process.env.SECRET)) {
* return res.status(401).json({ error: 'internal service authentication required' }); * return res.status(401).json({ error: 'internal service authentication required' });
* } * }
* const info = coreConfigStore.set(Info.fromJSON(req.body)); * let info;
* try {
* info = coreConfigStore.set(Info.fromJSON(req.body));
* } catch (error) {
* return res.status(400).json({ error: error.message });
* }
* res.json({ ok: true, info: info.toJSON() }); * res.json({ ok: true, info: info.toJSON() });
* }); * });
* *
@@ -130,6 +162,12 @@ export class Store {
*/ */
set(nextInfo) { set(nextInfo) {
const next = normalize(nextInfo instanceof Info ? nextInfo : new Info(nextInfo)); const next = normalize(nextInfo instanceof Info ? nextInfo : new Info(nextInfo));
const badUrl = [next.authGuardUrl, ...next.carrierNodeUrls].find(
(url) => url && !isServiceUrl(url)
);
if (badUrl !== undefined) {
throw new TypeError(`core service URL must be an http or https URL with a host: ${badUrl}`);
}
if (next.authGuardUrl) { if (next.authGuardUrl) {
this._info.authGuardUrl = next.authGuardUrl; this._info.authGuardUrl = next.authGuardUrl;
} }
+30 -3
View File
@@ -32,6 +32,18 @@ export function isTransientConnectionError(error) {
); );
} }
const READ_ONLY_STATEMENT = /^\s*select\b/i;
const LOCKING_OR_WRITING_READ = /\bfor\s+(update|share|no\s+key\s+update|key\s+share)\b|\binto\b|\b(nextval|setval)\s*\(/i;
/**
* True for a plain SELECT that cannot change data or sequences. Only these
* statements are retried after a transient error by default.
*/
export function isReadOnlyStatement(text) {
const sql = String(text);
return READ_ONLY_STATEMENT.test(sql) && !LOCKING_OR_WRITING_READ.test(sql);
}
/** /**
* Owns one pg pool and exposes bounded startup, retry, transaction, and * Owns one pg pool and exposes bounded startup, retry, transaction, and
* shutdown behavior. Domain repositories should depend on this abstraction * shutdown behavior. Domain repositories should depend on this abstraction
@@ -39,10 +51,18 @@ export function isTransientConnectionError(error) {
*/ */
export class Database { export class Database {
constructor(options = {}) { constructor(options = {}) {
const { pool, ...poolOptions } = options; const { pool, log = console.error, ...poolOptions } = options;
this.pool = pool || new Pool(poolOptions); this.pool = pool || new Pool(poolOptions);
this.ownsPool = !pool; this.ownsPool = !pool;
this.ready = false; this.ready = false;
this.log = log;
if (typeof this.pool.on === 'function') {
// pg emits 'error' for an idle client that fails, for example after a
// database restart. With no listener the event is thrown and can end the process.
this.pool.on('error', error => {
this.log(`[database] idle pool client error: ${error?.message || error}`);
});
}
} }
static fromEnv(env = process.env) { static fromEnv(env = process.env) {
@@ -77,12 +97,19 @@ export class Database {
} }
} }
async query(text, values = []) { /**
* Runs one statement. After a transient connection error the statement is
* retried only when it is read-only, so a write that committed before the
* connection dropped is not applied twice. Pass `{ retry: true }` to opt a
* known-idempotent statement in, or `{ retry: false }` to opt a read out.
*/
async query(text, values = [], options = {}) {
await this.connect(); await this.connect();
try { try {
return await this.pool.query(text, values); return await this.pool.query(text, values);
} catch (error) { } catch (error) {
if (!isTransientConnectionError(error)) throw error; const retry = options.retry ?? isReadOnlyStatement(text);
if (!retry || !isTransientConnectionError(error)) throw error;
return this.pool.query(text, values); return this.pool.query(text, values);
} }
} }
+9 -1
View File
@@ -15,12 +15,16 @@ export {
ResetManager, ResetManager,
createSessionToken, createSessionToken,
hashPassword, hashPassword,
hashPasswordAsync,
hashToken, hashToken,
USER_ROLES, USER_ROLES,
canAssignRole, canAssignRole,
canManageUsers, canManageUsers,
normalizeRole, normalizeRole,
passwordHashNeedsUpgrade,
verifyAndUpgradePasswordAsync,
verifyPassword, verifyPassword,
verifyPasswordAsync,
} from './auth.js'; } from './auth.js';
export { export {
TOTP_DIGITS, TOTP_DIGITS,
@@ -32,4 +36,8 @@ export {
} 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 { Info as CoreConfigInfo, Store as CoreConfigStore } from './coreconfig.js'; export {
Info as CoreConfigInfo,
Store as CoreConfigStore,
internalSecretMatches,
} from './coreconfig.js';
+73
View File
@@ -1,11 +1,16 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { import {
ResetManager, ResetManager,
createSessionToken, createSessionToken,
hashPassword, hashPassword,
hashPasswordAsync,
hashToken, hashToken,
passwordHashNeedsUpgrade,
verifyAndUpgradePasswordAsync,
verifyPassword, verifyPassword,
verifyPasswordAsync,
} from '../src/auth.js'; } from '../src/auth.js';
import { totpProvisioningUri, verifyTotp } from '../src/totp.js'; import { totpProvisioningUri, verifyTotp } from '../src/totp.js';
@@ -33,6 +38,74 @@ 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', () => {
const hash = hashPassword('correct horse battery staple');
assert.match(hash, /^pbkdf2-sha256\$600000\$[0-9a-f]{32}\$[0-9a-f]{64}$/);
});
test('legacy salt:hex hashes still verify at the original iteration count', () => {
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync('legacy password', salt, 100000, 32, 'sha256').toString('hex');
assert.equal(verifyPassword('legacy password', `${salt}:${hash}`), true);
assert.equal(verifyPassword('wrong password', `${salt}:${hash}`), false);
});
test('a hash with a malformed iteration count never verifies', () => {
assert.equal(verifyPassword('correct horse battery staple', 'pbkdf2-sha256$0$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 () => {
const hash = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 });
assert.match(hash, /^pbkdf2-sha256\$1000\$/);
assert.equal(await verifyPasswordAsync('correct horse battery staple', hash), true);
assert.equal(await verifyPasswordAsync('wrong password', hash), false);
assert.equal(verifyPassword('correct horse battery staple', hash), true);
});
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']) {
assert.equal(verifyPassword('correct horse battery staple', stored), false);
}
assert.equal(passwordHashNeedsUpgrade('$2b$12$abc'), true);
});
test('a legacy salt:hex hash is rewritten in the current scheme after a successful login', async () => {
const salt = crypto.randomBytes(16).toString('hex');
const legacy = `${salt}:${crypto.pbkdf2Sync('legacy password', salt, 100000, 32, 'sha256').toString('hex')}`;
assert.equal(passwordHashNeedsUpgrade(legacy), true);
const result = await verifyAndUpgradePasswordAsync('legacy password', legacy);
assert.equal(result.valid, true);
assert.match(result.upgradedHash, /^pbkdf2-sha256\$600000\$/);
assert.equal(passwordHashNeedsUpgrade(result.upgradedHash), false);
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 () => {
const low = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 });
const lowResult = await verifyAndUpgradePasswordAsync('correct horse battery staple', low);
assert.match(lowResult.upgradedHash, /^pbkdf2-sha256\$600000\$/);
const salt = crypto.randomBytes(16).toString('hex');
const shortLegacy = `${salt}:${crypto.pbkdf2Sync('short', salt, 100000, 32, 'sha256').toString('hex')}`;
const shortResult = await verifyAndUpgradePasswordAsync('short', shortLegacy);
assert.equal(shortResult.valid, true);
assert.equal(verifyPassword('short', shortResult.upgradedHash), true);
});
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 });
assert.deepEqual(await verifyAndUpgradePasswordAsync('wrong password', hash), { valid: false, upgradedHash: null });
const current = await hashPasswordAsync('correct horse battery staple');
assert.equal(passwordHashNeedsUpgrade(current), false);
assert.deepEqual(await verifyAndUpgradePasswordAsync('correct horse battery staple', current), {
valid: true,
upgradedHash: null,
});
});
test('TOTP verifies RFC 6238 SHA-1 vectors', () => { test('TOTP verifies RFC 6238 SHA-1 vectors', () => {
const secret = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'; const secret = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
const vectors = [ const vectors = [
@@ -108,6 +108,43 @@ test('validate throws InvalidSessionError when AuthGuard reports invalid', async
await assert.rejects(() => client.validate('bad-token'), InvalidSessionError); await assert.rejects(() => client.validate('bad-token'), InvalidSessionError);
}); });
test('validate reuses a positive and a negative answer within the cache window', async () => {
const fetchImpl = recordingFetch([
{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } },
{ status: 401, body: { valid: false } },
]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
assert.deepEqual(await client.validate('good-token'), { id: 7, username: 'gabriel', role: 'admin' });
assert.deepEqual(await client.validate('good-token'), { id: 7, username: 'gabriel', role: 'admin' });
await assert.rejects(() => client.validate('bad-token'), InvalidSessionError);
await assert.rejects(() => client.validate('bad-token'), InvalidSessionError);
assert.equal(fetchImpl.calls.length, 2);
});
test('logout drops the cached answer for that token', async () => {
const fetchImpl = recordingFetch([
{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } },
{ status: 200, body: {} },
{ status: 401, body: { valid: false } },
]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.validate('good-token');
await client.logout('good-token');
await assert.rejects(() => client.validate('good-token'), InvalidSessionError);
assert.equal(fetchImpl.calls.length, 3);
});
test('setBaseUrl clears cached answers', async () => {
const fetchImpl = recordingFetch([
{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } },
]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.validate('good-token');
client.setBaseUrl('https://auth2.example.com');
await client.validate('good-token');
assert.equal(fetchImpl.calls.length, 2);
});
test('tokenFromRequest prefers the Authorization header over the cookie', () => { test('tokenFromRequest prefers the Authorization header over the cookie', () => {
const client = new AuthClient('https://auth.example.com'); const client = new AuthClient('https://auth.example.com');
const req = { const req = {
@@ -361,3 +398,32 @@ test('deleteManagedUser DELETEs /api/admin/users/{id}', async () => {
assert.equal(fetchImpl.calls[0].init.method, 'DELETE'); assert.equal(fetchImpl.calls[0].init.method, 'DELETE');
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/6'); assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/6');
}); });
test('credential calls send the end user address as X-Forwarded-For when given a clientIp', async () => {
const user = { id: 1, username: 'a', email: '', role: 'user' };
const fetchImpl = recordingFetch([{ status: 200, body: { user } }]);
const client = new AuthClient('https://authguard.example', { fetchImpl });
await client.login('a', 'secret-password', '', { clientIp: '203.0.113.9' });
await client.register('a', 'a@b.com', 'secret-password', { clientIp: '2001:db8::1' });
await client.totpVerify('tok', '123456', { clientIp: '203.0.113.9' });
await client.totpDisable('tok', '123456', { clientIp: '203.0.113.9' });
await client.requestPasswordReset('a', { clientIp: '203.0.113.9' });
await client.confirmPasswordReset('CODE', 'secret-password', { clientIp: '203.0.113.9' });
assert.deepEqual(
fetchImpl.calls.map((call) => call.init.headers['X-Forwarded-For']),
['203.0.113.9', '2001:db8::1', '203.0.113.9', '203.0.113.9', '203.0.113.9', '203.0.113.9'],
);
});
test('no X-Forwarded-For is sent without a clientIp, or for a value that is not an IP address', async () => {
const user = { id: 1, username: 'a', email: '', role: 'user' };
const fetchImpl = recordingFetch([{ status: 200, body: { user } }]);
const client = new AuthClient('https://authguard.example', { fetchImpl });
await client.login('a', 'secret-password');
await client.login('a', 'secret-password', '', { clientIp: '203.0.113.9\r\nX-Evil: 1' });
await client.login('a', 'secret-password', '', { clientIp: 'not-an-ip' });
await client.me('tok');
for (const call of fetchImpl.calls) {
assert.equal('X-Forwarded-For' in call.init.headers, false);
}
});
@@ -0,0 +1,83 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { AuthStore } from '../src/auth.js';
// A Database-like object that records every query and answers from canned results.
function fakeDatabase({ rowCount = 1, totpEnabled = false, rowsByCondition = {} } = {}) {
const queries = [];
return {
queries,
async query(text, params = []) {
queries.push({ text, params });
if (text.includes('totp_enabled, false) AS enabled')) {
return { rows: [{ secret: 'S', enabled: totpEnabled }], rowCount: 1 };
}
for (const [condition, row] of Object.entries(rowsByCondition)) {
if (text.includes(condition)) return { rows: [row], rowCount: 1 };
}
return { rows: [], rowCount };
},
};
}
test('ensureSchema requests the case-insensitive username index, only while no clashing pair exists', async () => {
const database = fakeDatabase();
await new AuthStore(database, { singleUser: false }).ensureSchema();
const statements = database.queries.map((query) => query.text).join('\n');
assert.match(statements, /auth_users_username_lower_idx/);
assert.match(statements, /lower\(username\)/);
assert.match(statements, /HAVING count\(\*\) > 1/);
});
test('setTotpSecret refuses to replace an enabled second factor', async () => {
const database = fakeDatabase({ rowCount: 0, totpEnabled: true });
const store = new AuthStore(database);
await assert.rejects(store.setTotpSecret(1, 'NEWSECRET'), { code: 'AUTH_TOTP_ALREADY_ENABLED' });
assert.match(database.queries[0].text, /NOT totp_enabled/);
});
test('setTotpSecret stores a pending secret while TOTP is off, and ignores an unknown user', async () => {
await new AuthStore(fakeDatabase()).setTotpSecret(1, 'NEWSECRET');
await new AuthStore(fakeDatabase({ rowCount: 0 })).setTotpSecret(2, 'NEWSECRET');
});
test('credential writes refuse an empty hash and a username containing @', async () => {
const database = fakeDatabase();
const store = new AuthStore(database);
const writes = [
(username, hash) => store.createUser(username, '', hash),
(username, hash) => store.createManagedUser(username, '', hash),
(username, hash) => store.updateCredentials(1, username, '', hash),
(username, hash) => store.updateUser(1, { username, passwordHash: hash }),
];
for (const write of writes) {
await assert.rejects(write('alice', ''), { code: 'AUTH_EMPTY_PASSWORD_HASH' });
await assert.rejects(write('alice@example.com', 'hash'), { code: 'AUTH_INVALID_USERNAME' });
}
assert.equal(database.queries.length, 0);
});
test('updateUser leaves unspecified fields alone', async () => {
const database = fakeDatabase();
const store = new AuthStore(database);
await store.updateUser(1, { email: 'a@b.com' });
await store.updateUser(1, { role: 'admin' });
assert.equal(database.queries.length, 2);
assert.doesNotMatch(database.queries[0].text, /password_hash|username/);
});
test('findByIdentifier tries the username before the email', async () => {
const database = fakeDatabase({
rowsByCondition: {
'username = $1': { id: 1, username: 'owner@example.com' },
'lower(email) = lower($1)': { id: 2, username: 'owner' },
},
});
const store = new AuthStore(database);
assert.equal((await store.findByIdentifier('owner@example.com')).username, 'owner@example.com');
assert.equal(database.queries.length, 1);
const emailOnly = fakeDatabase({ rowsByCondition: { 'lower(email) = lower($1)': { id: 2, username: 'owner' } } });
assert.equal((await new AuthStore(emailOnly).findByIdentifier('OWNER@example.com')).username, 'owner');
assert.equal(await new AuthStore(fakeDatabase()).findByIdentifier('nobody'), null);
});
@@ -0,0 +1,43 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { hashPassword, passwordHashNeedsUpgrade, verifyAndUpgradePasswordAsync, verifyPassword } from '../src/auth.js';
import { verifyTotp } from '../src/totp.js';
// 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 contract = existsSync(contractUrl) ? JSON.parse(readFileSync(contractUrl, 'utf8')) : null;
const skip = contract ? false : 'contract/auth-contract.json is not part of this checkout';
test('password hashes verify as the contract says for Node', { skip }, async () => {
const { plaintext, wrongPassword, hashes } = contract.password;
for (const entry of hashes) {
assert.equal(verifyPassword(plaintext, entry.hash), entry.verifies.node, entry.name);
assert.equal(verifyPassword(wrongPassword, entry.hash), false, `${entry.name}: wrong password`);
if ('node' in (entry.needsUpgrade ?? {})) {
assert.equal(passwordHashNeedsUpgrade(entry.hash), entry.needsUpgrade.node, `${entry.name}: needs upgrade`);
const { valid, upgradedHash } = await verifyAndUpgradePasswordAsync(plaintext, entry.hash);
assert.equal(valid, true, `${entry.name}: valid on upgrade`);
assert.equal(upgradedHash !== null, entry.needsUpgrade.node, `${entry.name}: upgraded hash`);
if (upgradedHash) assert.equal(verifyPassword(plaintext, upgradedHash), true);
}
}
});
test('the password length contract holds for Node', { skip }, () => {
const { bytes, accepted } = contract.password.tooLongToHash;
let didHash = true;
try {
hashPassword('a'.repeat(bytes), { iterations: 1000 });
} catch {
didHash = false;
}
assert.equal(didHash, accepted.node);
});
test('TOTP verifies as the contract says', { skip }, () => {
for (const entry of contract.totp.cases) {
const secret = entry.secret ?? contract.totp.secret;
assert.equal(verifyTotp(secret, entry.code, entry.unix * 1000), entry.valid, entry.name);
}
});
+18 -1
View File
@@ -1,6 +1,6 @@
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 } from '../src/coreconfig.js'; import { Info, Store, internalSecretMatches } 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' });
@@ -48,3 +48,20 @@ test('Info.fromJSON/toJSON round-trip the wire shape', () => {
assert.deepEqual(info.carrierNodeUrls, ['http://carrier.example.com', 'http://carrier2.example.com']); assert.deepEqual(info.carrierNodeUrls, ['http://carrier.example.com', 'http://carrier2.example.com']);
assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com'); assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com');
}); });
test('internal secret check fails closed when the secret is unset or empty', () => {
assert.equal(internalSecretMatches(undefined, undefined), false);
assert.equal(internalSecretMatches(undefined, ''), false);
assert.equal(internalSecretMatches('', ''), false);
assert.equal(internalSecretMatches(undefined, 'shared-secret'), false);
assert.equal(internalSecretMatches('shared-secreT', 'shared-secret'), false);
assert.equal(internalSecretMatches('shared-secret', 'shared-secret'), true);
});
test('set rejects a URL that is not an http or https URL and changes nothing', () => {
const store = new Store({ authGuardUrl: 'http://auth.example.com' });
assert.throws(() => store.set({ authGuardUrl: 'javascript:alert(1)' }), TypeError);
assert.throws(() => store.set({ authGuardUrl: 'auth.example.com' }), TypeError);
assert.throws(() => store.set({ carrierNodeUrls: ['ftp://carrier.example.com'] }), TypeError);
assert.equal(store.authGuardUrl, 'http://auth.example.com');
});
+62
View File
@@ -0,0 +1,62 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import { Database, isReadOnlyStatement } from '../src/db.js';
function fakePool(results) {
const pool = new EventEmitter();
pool.calls = [];
pool.query = async (text, values) => {
pool.calls.push({ text, values });
const next = results.shift();
if (next instanceof Error) throw next;
return next ?? { rows: [] };
};
return pool;
}
const transient = () => Object.assign(new Error('connection reset'), { code: 'ECONNRESET' });
test('only plain SELECT statements are treated as read-only', () => {
assert.equal(isReadOnlyStatement('SELECT id FROM auth_users'), true);
assert.equal(isReadOnlyStatement(' select 1'), true);
assert.equal(isReadOnlyStatement('INSERT INTO auth_users (id) VALUES (1)'), false);
assert.equal(isReadOnlyStatement('WITH x AS (DELETE FROM t RETURNING 1) SELECT * FROM x'), false);
assert.equal(isReadOnlyStatement('SELECT * FROM t FOR UPDATE'), false);
assert.equal(isReadOnlyStatement('SELECT nextval(\'seq\')'), false);
assert.equal(isReadOnlyStatement('SELECT * INTO copy FROM t'), false);
});
test('an idle pool error is logged instead of thrown', () => {
const logged = [];
const pool = fakePool([]);
new Database({ pool, log: message => logged.push(message) });
assert.doesNotThrow(() => pool.emit('error', new Error('terminating connection')));
assert.equal(logged.length, 1);
assert.match(logged[0], /terminating connection/);
});
test('a transient error is retried for a read-only statement', async () => {
const pool = fakePool([transient(), { rows: [{ ok: 1 }] }]);
const db = new Database({ pool, log() {} });
db.ready = true;
const result = await db.query('SELECT 1 AS ok');
assert.deepEqual(result.rows, [{ ok: 1 }]);
assert.equal(pool.calls.length, 2);
});
test('a transient error is not retried for a write', async () => {
const pool = fakePool([transient(), { rows: [] }]);
const db = new Database({ pool, log() {} });
db.ready = true;
await assert.rejects(db.query('INSERT INTO t (id) VALUES ($1)', [1]), { code: 'ECONNRESET' });
assert.equal(pool.calls.length, 1);
});
test('a write is retried only when the caller opts in', async () => {
const pool = fakePool([transient(), { rows: [] }]);
const db = new Database({ pool, log() {} });
db.ready = true;
await db.query('INSERT INTO t (id) VALUES ($1)', [1], { retry: true });
assert.equal(pool.calls.length, 2);
});
+26 -5
View File
@@ -4,7 +4,7 @@ Shared Python backend infrastructure for services using `asyncpg`:
- validated `DATABASE_URL` and pool settings; - validated `DATABASE_URL` and pool settings;
- one async pool owner with startup retry, ping, and graceful shutdown; - one async pool owner with startup retry, ping, and graceful shutdown;
- bcrypt password and secure session-token helpers; - bcrypt password helpers (`verify_and_upgrade_password_async` returns a current-scheme hash for a login to store) and secure session-token helpers;
- short-lived, one-time admin reset codes printed to the server console; - short-lived, one-time admin reset codes printed to the server console;
- common account/session persistence for the single-admin or optional multi-user model; - common account/session persistence for the single-admin or optional multi-user model;
- an `authclient` module for services that adopt AuthGuard, the centralized - an `authclient` module for services that adopt AuthGuard, the centralized
@@ -20,7 +20,25 @@ pip install "git+https://repos.gfranz.ch/Gabriel20xx/shared@v0.1.0#subdirectory=
``` ```
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely). `250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely). Only
transient connection errors are retried; bad credentials or a missing database
fail at once.
`authproxy.build_auth_router` limits login attempts (10 per account and 200 per
client address per 15 minutes) and TOTP verify/disable attempts (5 per user), in
process memory, and answers `429` beyond that. The client address is the TCP
peer; `X-Forwarded-For` is read only from peers inside `TRUSTED_PROXIES` (a
comma-separated list of CIDR ranges or IP addresses, empty by default; the
`trusted_proxies` argument overrides it, and an invalid list raises
`ValueError` at startup). The same address reaches AuthGuard as
`X-Forwarded-For` through `authclient.forwarded_client_ip`, which AuthGuard reads
only from peers in its own `TRUSTED_PROXIES`.
`AuthStore` refuses an empty password hash and a username containing `@`
(`EmptyPasswordHashError`, `InvalidUsernameError` in `shared_backend.auth`),
refuses `set_totp_secret` while TOTP is enabled (`TotpAlreadyEnabledError`), and
makes usernames unique ignoring case when no clashing pair already exists.
`hash_password` refuses a password longer than 72 bytes, the most bcrypt reads.
## `authclient`: adopting AuthGuard instead of local auth ## `authclient`: adopting AuthGuard instead of local auth
@@ -92,7 +110,7 @@ give it, and updated live whenever ProjectConfigurator pushes a fresh
`PUT /api/core-services/internal`. A service wires the actual route itself: `PUT /api/core-services/internal`. A service wires the actual route itself:
```python ```python
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, internal_secret_matches
auth_client = AuthClient("") # pending: no URL yet, still safe to use auth_client = AuthClient("") # pending: no URL yet, still safe to use
core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url="")) core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url=""))
@@ -101,10 +119,13 @@ core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url)
# in your framework's route for PUT /api/core-services/internal: # in your framework's route for PUT /api/core-services/internal:
async def push_core_services(request): async def push_core_services(request):
if request.headers.get("X-Internal-Auth") != SECRET: if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET):
raise HTTPException(status_code=401) raise HTTPException(status_code=401)
body = await request.json() body = await request.json()
info = core_config.set(CoreConfigInfo.from_json(body)) try:
info = core_config.set(CoreConfigInfo.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()} return {"ok": True, "info": info.to_json()}
``` ```
@@ -11,8 +11,13 @@ from .auth import (
can_assign_role, can_assign_role,
can_manage_users, can_manage_users,
hash_password, hash_password,
hash_password_async,
normalize_role, normalize_role,
password_hash_needs_upgrade,
verify_and_upgrade_password,
verify_and_upgrade_password_async,
verify_password, verify_password,
verify_password_async,
) )
from .authclient import ( from .authclient import (
AuthClient, AuthClient,
@@ -25,6 +30,7 @@ from .authclient import (
from .config import DatabaseConfig, database_url_from_env from .config import DatabaseConfig, database_url_from_env
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
@@ -40,6 +46,7 @@ __all__ = [
"token_from_request", "token_from_request",
"CoreConfigInfo", "CoreConfigInfo",
"CoreConfigStore", "CoreConfigStore",
"internal_secret_matches",
"ROLE_ADMIN", "ROLE_ADMIN",
"ROLE_SUPERADMIN", "ROLE_SUPERADMIN",
"ROLE_USER", "ROLE_USER",
@@ -52,10 +59,15 @@ __all__ = [
"database_url_from_env", "database_url_from_env",
"generate_totp_secret", "generate_totp_secret",
"hash_password", "hash_password",
"hash_password_async",
"hash_token", "hash_token",
"new_session_token", "new_session_token",
"normalize_role", "normalize_role",
"password_hash_needs_upgrade",
"totp_provisioning_uri", "totp_provisioning_uri",
"verify_and_upgrade_password",
"verify_and_upgrade_password_async",
"verify_password", "verify_password",
"verify_password_async",
"verify_totp", "verify_totp",
] ]
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import secrets import secrets
import threading import threading
from dataclasses import dataclass from dataclasses import dataclass
@@ -30,9 +31,6 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAUL
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 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'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> ''; ON auth_users (lower(email)) WHERE email <> '';
CREATE TABLE IF NOT EXISTS auth_sessions ( CREATE TABLE IF NOT EXISTS auth_sessions (
@@ -46,6 +44,39 @@ CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id); CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
""" """
# Usernames are unique ignoring case ("Admin" and "admin" are one identity to a reader). The index
# is created only while no such pair exists, so a database that already holds one still starts and
# raises a warning; it is built on the first start after one account of each pair is renamed.
_USERNAME_CASE_INDEX = """
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM auth_users GROUP BY lower(username) HAVING count(*) > 1) THEN
RAISE WARNING 'auth_users holds usernames that differ only by case; '
'the case-insensitive username index was not created';
ELSE
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx
ON auth_users (lower(username));
END IF;
EXCEPTION WHEN unique_violation THEN
RAISE WARNING 'the case-insensitive username index was not created: a clashing username was '
'just added';
END
$$
"""
_ROLE_COLUMN_MISSING = """
SELECT NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = 'auth_users' AND column_name = 'role'
)
"""
_PROMOTE_OLDEST_SUPERADMIN = """
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin')
"""
RESET_CODE_TTL = timedelta(minutes=5) RESET_CODE_TTL = timedelta(minutes=5)
ROLE_SUPERADMIN = "superadmin" ROLE_SUPERADMIN = "superadmin"
@@ -107,10 +138,12 @@ class ResetManager:
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
class AuthUser: class AuthUser:
"""A stored account. Only the lookups that verify credentials fill password_hash."""
id: int id: int
username: str username: str
email: str email: str
password_hash: str password_hash: str = ""
role: str = ROLE_USER role: str = ROLE_USER
created_at: datetime | None = None created_at: datetime | None = None
updated_at: datetime | None = None updated_at: datetime | None = None
@@ -120,26 +153,129 @@ class UserExistsError(Exception):
"""Raised when a user violates a unique or single-user constraint.""" """Raised when a user violates a unique or single-user constraint."""
class TotpAlreadyEnabledError(Exception):
"""Raised by set_totp_secret while two-factor auth is enabled."""
class EmptyPasswordHashError(ValueError):
"""Raised when a credential write carries no password hash."""
class InvalidUsernameError(ValueError):
"""Raised for a username containing "@", which would be read as an email."""
def _validate_credentials(username: str | None, password_hash: str | None) -> None:
"""Refuse a write that would leave an account without a password hash, or store a username
that could be mistaken for another account's email. None means "leave unchanged"."""
if password_hash is not None and not password_hash:
raise EmptyPasswordHashError("password hash is required")
if username is not None and "@" in username:
raise InvalidUsernameError("username cannot contain @")
# Every hash this module writes starts with this scheme prefix, so verification
# picks the algorithm from the stored value. The bcrypt string follows unchanged,
# 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.
_BCRYPT_SCHEME = "bcrypt$"
_LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$")
BCRYPT_ROUNDS = 12
def _new_bcrypt_hash(password: str) -> str:
hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=BCRYPT_ROUNDS))
return _BCRYPT_SCHEME + hashed.decode("utf-8")
# bcrypt reads only the first 72 bytes. Older bcrypt releases drop the rest silently, so the limit
# is enforced here instead of depending on the installed version.
MAX_PASSWORD_BYTES = 72
def hash_password(password: str) -> str: def hash_password(password: str) -> str:
if len(password) < 8: if len(password) < 8:
raise ValueError("Password must be at least 8 characters") raise ValueError("Password must be at least 8 characters")
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
raise ValueError(f"Password must be at most {MAX_PASSWORD_BYTES} bytes")
return _new_bcrypt_hash(password)
def _bcrypt_string_of(stored_hash: str) -> str | None:
if stored_hash.startswith(_BCRYPT_SCHEME):
return stored_hash[len(_BCRYPT_SCHEME) :]
if stored_hash.startswith(_LEGACY_BCRYPT_PREFIXES):
return stored_hash
return None
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)
if bcrypt_hash is None:
return False
try: try:
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8")) return bcrypt.checkpw(password.encode("utf-8"), bcrypt_hash.encode("utf-8"))
except (ValueError, TypeError): except (ValueError, TypeError):
return False return False
def password_hash_needs_upgrade(stored_hash: str) -> bool:
"""True for an unprefixed legacy hash, or a bcrypt cost below BCRYPT_ROUNDS."""
if not stored_hash.startswith(_BCRYPT_SCHEME):
return True
# The bcrypt string after the prefix is "$2b$<cost>$<salt+hash>".
parts = stored_hash[len(_BCRYPT_SCHEME) :].split("$")
try:
return int(parts[2]) < BCRYPT_ROUNDS
except (IndexError, ValueError):
return True
def verify_and_upgrade_password(password: str, stored_hash: str) -> tuple[bool, str | None]:
"""Check a password and, on a match against an older scheme, return a replacement hash.
Returns (valid, upgraded_hash). upgraded_hash is None when the password does not match or
the stored hash is already current. Store upgraded_hash, for example with
AuthStore.update_user(user_id, password_hash=...).
"""
if not verify_password(password, stored_hash):
return False, None
if not password_hash_needs_upgrade(stored_hash):
return True, None
# The length rule applies when a password is first set, not when an old hash is upgraded.
return True, _new_bcrypt_hash(password)
async def hash_password_async(password: str) -> str:
"""Non-blocking hash_password: bcrypt runs in a worker thread."""
return await asyncio.to_thread(hash_password, password)
async def verify_password_async(password: str, stored_hash: str) -> bool:
"""Non-blocking verify_password: bcrypt runs in a worker thread."""
return await asyncio.to_thread(verify_password, password, stored_hash)
async def verify_and_upgrade_password_async(
password: str, stored_hash: str
) -> tuple[bool, str | None]:
"""Non-blocking verify_and_upgrade_password: bcrypt runs in a worker thread."""
return await asyncio.to_thread(verify_and_upgrade_password, password, stored_hash)
class AuthStore: class AuthStore:
def __init__(self, database: Database, *, single_user: bool = True) -> None: def __init__(self, database: Database, *, single_user: bool = True) -> None:
self.database = database self.database = database
self.single_user = single_user self.single_user = single_user
async def ensure_schema(self) -> None: async def ensure_schema(self) -> None:
# Only a table that predates the role column needs its oldest account promoted, so the
# promotion runs once, in the migration that adds the column.
role_column_missing = await self.database.fetchval(_ROLE_COLUMN_MISSING)
await self.database.execute(_SCHEMA) await self.database.execute(_SCHEMA)
await self.database.execute(_USERNAME_CASE_INDEX)
if role_column_missing:
await self.database.execute(_PROMOTE_OLDEST_SUPERADMIN)
if self.single_user: if self.single_user:
await self.database.execute( await self.database.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))" "CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))"
@@ -151,6 +287,7 @@ class AuthStore:
return int(await self.database.fetchval("SELECT count(*) FROM auth_users")) return int(await self.database.fetchval("SELECT count(*) FROM auth_users"))
async def create_user(self, username: str, email: str, password_hash: str) -> AuthUser: async def create_user(self, username: str, email: str, password_hash: str) -> AuthUser:
_validate_credentials(username, password_hash or "")
try: try:
row = await self.database.fetchrow( row = await self.database.fetchrow(
""" """
@@ -159,7 +296,7 @@ class AuthStore:
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user'
ELSE 'superadmin' END, ELSE 'superadmin' END,
now()) now())
RETURNING id, username, email, password_hash, role, created_at, updated_at RETURNING id, username, email, role, created_at, updated_at
""", """,
username, username,
email, email,
@@ -171,19 +308,25 @@ class AuthStore:
return AuthUser(**dict(row)) return AuthUser(**dict(row))
async def find_by_identifier(self, identifier: str) -> AuthUser | None: async def find_by_identifier(self, identifier: str) -> AuthUser | None:
row = await self.database.fetchrow( # Usernames are tried before emails, so an identifier resolves to one account in a
""" # fixed order.
SELECT id, username, email, password_hash, role, created_at, updated_at for condition in ("username = $1", "lower(email) = lower($1)"):
FROM auth_users row = await self.database.fetchrow(
WHERE username = $1 OR lower(email) = lower($1) f"""
""", SELECT id, username, email, password_hash, role, created_at, updated_at
identifier, FROM auth_users
) WHERE {condition}
return AuthUser(**dict(row)) if row else None """,
identifier,
)
if row:
return AuthUser(**dict(row))
return None
async def update_credentials( async def update_credentials(
self, user_id: int, username: str, email: str, password_hash: str self, user_id: int, username: str, email: str, password_hash: str
) -> None: ) -> None:
_validate_credentials(username, password_hash or "")
await self.database.execute( await self.database.execute(
""" """
UPDATE auth_users UPDATE auth_users
@@ -224,7 +367,7 @@ class AuthStore:
async def list_users(self) -> list[AuthUser]: async def list_users(self) -> list[AuthUser]:
rows = await self.database.fetch( rows = await self.database.fetch(
"SELECT id, username, email, role, password_hash, created_at, updated_at " "SELECT id, username, email, role, created_at, updated_at "
"FROM auth_users ORDER BY created_at, id" "FROM auth_users ORDER BY created_at, id"
) )
return [AuthUser(**dict(row)) for row in rows] return [AuthUser(**dict(row)) for row in rows]
@@ -232,12 +375,13 @@ class AuthStore:
async def create_managed_user( async def create_managed_user(
self, username: str, email: str, password_hash: str, role: str = ROLE_USER self, username: str, email: str, password_hash: str, role: str = ROLE_USER
) -> AuthUser: ) -> AuthUser:
_validate_credentials(username, password_hash or "")
try: try:
row = await self.database.fetchrow( row = await self.database.fetchrow(
""" """
INSERT INTO auth_users (username, email, password_hash, role, updated_at) INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, $4, now()) VALUES ($1, $2, $3, $4, now())
RETURNING id, username, email, password_hash, role, created_at, updated_at RETURNING id, username, email, role, created_at, updated_at
""", """,
username, username,
email, email,
@@ -258,6 +402,7 @@ class AuthStore:
password_hash: str | None = None, password_hash: str | None = None,
role: str | None = None, role: str | None = None,
) -> None: ) -> None:
_validate_credentials(username, password_hash)
fields: list[str] = [] fields: list[str] = []
values: list[object] = [] values: list[object] = []
for column, value in ( for column, value in (
@@ -293,12 +438,17 @@ class AuthStore:
return dict(row) if row else {"secret": "", "enabled": False} return dict(row) if row else {"secret": "", "enabled": False}
async def set_totp_secret(self, user_id: int, secret: str) -> None: async def set_totp_secret(self, user_id: int, secret: str) -> None:
await self.database.execute( """Stores a pending secret without enabling two-factor auth. Raises
TotpAlreadyEnabledError while it is enabled, so a replaced secret cannot silently switch
the second factor off."""
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, "
"updated_at = now() WHERE id = $2", "updated_at = now() WHERE id = $2 AND NOT totp_enabled",
secret, secret,
user_id, user_id,
) )
if status == "UPDATE 0" and (await self.get_totp_state(user_id))["enabled"]:
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) -> None:
await self.database.execute( await self.database.execute(
@@ -49,15 +49,26 @@ concrete Response object and knows how to attach headers to it.
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import contextlib
import contextvars
import hashlib
import ipaddress import ipaddress
import json import json
import threading
import time
import urllib.error import urllib.error
import urllib.request import urllib.request
from collections.abc import Iterator
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Mapping 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
# requests with one token costs one AuthGuard call. Revocation through this client (logout)
# clears the entry at once; revocation elsewhere is seen within the TTL. Mirrors the Go client.
VALIDATION_CACHE_TTL = 2.0
MAX_VALIDATION_CACHE_ENTRIES = 10000
_BEARER_PREFIX = "Bearer " _BEARER_PREFIX = "Bearer "
@@ -66,6 +77,34 @@ _BEARER_PREFIX = "Bearer "
# so it can enforce per-user project-access restriction (see AuthGuard's # so it can enforce per-user project-access restriction (see AuthGuard's
# project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader. # project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
PROJECT_KEY_HEADER = "X-Project-Key" PROJECT_KEY_HEADER = "X-Project-Key"
# Carries the end user's address on every AuthGuard call made inside a `forwarded_client_ip`
# block, so AuthGuard's per-address limits see the end user instead of this service. AuthGuard
# reads the header only when the calling service's own address is in its TRUSTED_PROXIES, so
# sending it changes nothing for a deployment that has not opted in.
FORWARDED_FOR_HEADER = "X-Forwarded-For"
_forwarded_client_ip: contextvars.ContextVar[str | None] = contextvars.ContextVar(
"authclient_forwarded_client_ip", default=None
)
@contextlib.contextmanager
def forwarded_client_ip(ip: str | None) -> Iterator[None]:
"""Makes AuthClient calls awaited inside the block send `ip` as X-Forwarded-For. Pass an
address the caller has already verified (see shared_backend.clientip.client_address), never a
raw request header. Anything that is not an IP address is ignored."""
token = _forwarded_client_ip.set(ip)
try:
yield
finally:
_forwarded_client_ip.reset(token)
def _valid_ip(value: str | None) -> str:
"""The canonical form of an IP address, or "" for anything else (no header injection)."""
try:
return str(ipaddress.ip_address((value or "").strip()))
except ValueError:
return ""
def _normalize_base_url(base_url: str) -> str: def _normalize_base_url(base_url: str) -> str:
@@ -233,6 +272,43 @@ class AuthClient:
# restriction. Normally a project's own lowercase identifier, # restriction. Normally a project's own lowercase identifier,
# matching the key ProjectConfigurator registers it under. # matching the key ProjectConfigurator registers it under.
self.project_key = (project_key or "").strip().lower() self.project_key = (project_key or "").strip().lower()
self._validation_lock = threading.Lock()
self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {}
@staticmethod
def _validation_key(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def _cached_validation(self, token: str) -> tuple[bool, AuthGuardUser | None]:
"""Returns (hit, user); user is None for a cached invalid session."""
key = self._validation_key(token)
with self._validation_lock:
entry = self._validation_cache.get(key)
if entry is None:
return False, None
expires, user = entry
if time.monotonic() >= expires:
del self._validation_cache[key]
return False, None
return True, user
def _cache_validation(self, token: str, user: AuthGuardUser | None) -> None:
with self._validation_lock:
if len(self._validation_cache) >= MAX_VALIDATION_CACHE_ENTRIES:
now = time.monotonic()
for key in [k for k, entry in self._validation_cache.items() if now >= entry[0]]:
del self._validation_cache[key]
if len(self._validation_cache) >= MAX_VALIDATION_CACHE_ENTRIES:
# dicts keep insertion order, so this drops the oldest entry.
del self._validation_cache[next(iter(self._validation_cache))]
self._validation_cache[self._validation_key(token)] = (
time.monotonic() + VALIDATION_CACHE_TTL,
user,
)
def _forget_validation(self, token: str) -> None:
with self._validation_lock:
self._validation_cache.pop(self._validation_key(token), None)
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,
@@ -248,6 +324,8 @@ class AuthClient:
normalized = _normalize_base_url(base_url) normalized = _normalize_base_url(base_url)
if normalized: if normalized:
self.base_url = normalized self.base_url = normalized
with self._validation_lock:
self._validation_cache.clear()
# --- session validation (the original, minimal surface) ---------------- # --- session validation (the original, minimal surface) ----------------
@@ -262,6 +340,11 @@ class AuthClient:
trimmed = (token or "").strip() trimmed = (token or "").strip()
if not trimmed: if not trimmed:
raise InvalidSessionError() raise InvalidSessionError()
hit, cached = self._cached_validation(trimmed)
if hit:
if cached is None:
raise InvalidSessionError()
return cached
return await asyncio.to_thread(self._validate_sync, trimmed) return await asyncio.to_thread(self._validate_sync, trimmed)
def _validate_sync(self, token: str) -> AuthGuardUser: def _validate_sync(self, token: str) -> AuthGuardUser:
@@ -293,17 +376,23 @@ class AuthClient:
raise TypeError(f"expected a JSON object, got {type(payload).__name__}") raise TypeError(f"expected a JSON object, got {type(payload).__name__}")
except (ValueError, TypeError, UnicodeDecodeError) as exc: except (ValueError, TypeError, UnicodeDecodeError) as exc:
if status == 401: if status == 401:
self._cache_validation(token, None)
raise InvalidSessionError() from exc raise InvalidSessionError() from exc
raise AuthClientError(f"authclient: decode AuthGuard response: {exc}") from exc raise AuthClientError(f"authclient: decode AuthGuard response: {exc}") from exc
if status != 200 or not payload.get("valid"): if status == 401 or (status == 200 and not payload.get("valid")):
self._cache_validation(token, None)
raise InvalidSessionError()
if status != 200:
raise InvalidSessionError() raise InvalidSessionError()
return AuthGuardUser( user = AuthGuardUser(
id=int(payload.get("user_id") or 0), id=int(payload.get("user_id") or 0),
username=str(payload.get("username") or ""), username=str(payload.get("username") or ""),
role=str(payload.get("role") or ""), role=str(payload.get("role") or ""),
) )
self._cache_validation(token, user)
return user
# --- shared request/response plumbing for everything below ------------- # --- shared request/response plumbing for everything below -------------
@@ -333,6 +422,11 @@ class AuthClient:
headers: dict[str, str] = {} headers: dict[str, str] = {}
if self.project_key: if self.project_key:
headers[PROJECT_KEY_HEADER] = self.project_key headers[PROJECT_KEY_HEADER] = self.project_key
# asyncio.to_thread runs this in a copy of the caller's context, so the address set by
# forwarded_client_ip is visible here.
address = _valid_ip(_forwarded_client_ip.get())
if address:
headers[FORWARDED_FOR_HEADER] = address
if body is not None: if body is not None:
data = json.dumps(body).encode() data = json.dumps(body).encode()
headers["Content-Type"] = "application/json" headers["Content-Type"] = "application/json"
@@ -435,6 +529,7 @@ class AuthClient:
server-side. Returns the (cookie-clearing) Set-Cookie header server-side. Returns the (cookie-clearing) Set-Cookie header
value(s) AuthGuard's response carried.""" value(s) AuthGuard's response carried."""
_, cookies = await self._call("POST", "/api/logout", token=token) _, cookies = await self._call("POST", "/api/logout", token=token)
self._forget_validation((token or "").strip())
return cookies return cookies
async def me(self, token: str) -> PublicUser: async def me(self, token: str) -> PublicUser:
@@ -61,7 +61,7 @@ from typing import Any, Callable, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel from pydantic import BaseModel
from .auth import ROLE_SUPERADMIN, can_manage_users, normalize_role from .auth import MAX_PASSWORD_BYTES, ROLE_SUPERADMIN, can_manage_users, normalize_role
from .authclient import ( from .authclient import (
DEFAULT_COOKIE_NAME, DEFAULT_COOKIE_NAME,
APIError, APIError,
@@ -69,11 +69,20 @@ from .authclient import (
AuthClientError, AuthClientError,
ManagedUser, ManagedUser,
PublicUser, PublicUser,
forwarded_client_ip,
) )
from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env
from .ratelimit import AttemptLimiter
__all__ = ["ProxyStore", "build_auth_router"] __all__ = ["ProxyStore", "build_auth_router"]
MIN_PASSWORD_LEN = 8 MIN_PASSWORD_LEN = 8
# Attempt limits for login and the TOTP verify/disable routes, the same numbers as the Go proxy
# (backend/auth/ratelimit.go): each key may make `limit` attempts per window.
ATTEMPT_WINDOW_SECONDS = 15 * 60
LOGIN_ACCOUNT_LIMIT = 10
LOGIN_CLIENT_LIMIT = 200
TOTP_ATTEMPT_LIMIT = 5
MAX_USERNAME_LEN = 64 MAX_USERNAME_LEN = 64
MAX_EMAIL_LEN = 254 MAX_EMAIL_LEN = 254
@@ -81,6 +90,7 @@ ERR_AUTH_REQUIRED = "Authentication required."
ERR_SETUP_COMPLETE = "Setup has already been completed." ERR_SETUP_COMPLETE = "Setup has already been completed."
ERR_INVALID_CREDENTIALS = "Invalid username or password." ERR_INVALID_CREDENTIALS = "Invalid username or password."
ERR_INVALID_INPUT = "Invalid authentication input." ERR_INVALID_INPUT = "Invalid authentication input."
ERR_TOO_MANY_ATTEMPTS = "Too many attempts. Try again later."
ERR_SELF_SERVICE_PROFILE = ( ERR_SELF_SERVICE_PROFILE = (
"Self-service profile editing is only available to administrator accounts; " "Self-service profile editing is only available to administrator accounts; "
"ask an administrator to update this account." "ask an administrator to update this account."
@@ -93,6 +103,7 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
# never this error - so every caller can safely report this same message # never this error - so every caller can safely report this same message
# 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_SECRET_NOT_SET = "SECRET environment variable is not set." ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
ERR_ADMIN_REQUIRED = "Administrator access required." ERR_ADMIN_REQUIRED = "Administrator access required."
@@ -202,6 +213,11 @@ def _normalize_email(email: str) -> str:
def _validate_password(password: str) -> None: def _validate_password(password: str) -> None:
if len(password or "") < MIN_PASSWORD_LEN: if len(password or "") < MIN_PASSWORD_LEN:
raise HTTPException(status_code=400, detail="Password must be at least 8 characters.") raise HTTPException(status_code=400, detail="Password must be at least 8 characters.")
# bcrypt reads only the first 72 bytes, so a longer password could not be stored faithfully.
if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
raise HTTPException(
status_code=400, detail=f"Password must be at most {MAX_PASSWORD_BYTES} bytes."
)
def _raise_authguard_error(err: Exception, fallback: str) -> None: def _raise_authguard_error(err: Exception, fallback: str) -> None:
@@ -246,14 +262,38 @@ def build_auth_router(
cookie_name: str = DEFAULT_COOKIE_NAME, cookie_name: str = DEFAULT_COOKIE_NAME,
configuration_error: str | None = None, configuration_error: str | None = None,
internal_secret: str | None = None, internal_secret: str | None = None,
local_profile_without_authguard: bool = False,
trusted_proxies: str | None = None,
) -> APIRouter: ) -> APIRouter:
"""Builds a ready-to-mount APIRouter implementing the full standardized """Builds a ready-to-mount APIRouter implementing the full standardized
AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth", AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth",
matching every existing consumer). See the module docstring for the matching every existing consumer). See the module docstring for the
`get_client`/`get_store` contract.""" `get_client`/`get_store` contract.
When `get_client` returns None (AUTHGUARD_URL unset) the guarded routes
refuse requests with a 500 unless `local_profile_without_authguard` is
True. Pass True only for a deployment that is meant to run without
AuthGuard; otherwise a missing environment variable would silently make
every guarded route run as the local superadmin.
Login and the TOTP routes refuse further attempts with 429: per account and per client
address for login (10 and 200 per 15 minutes), per user for TOTP verify and disable (5 per 15
minutes). The counters live in this process. The client address is the TCP peer;
`trusted_proxies` (default: the TRUSTED_PROXIES environment variable, a comma-separated list
of CIDR ranges or IP addresses, empty by default) names the reverse proxies whose
X-Forwarded-For is believed. An invalid list raises ValueError here, at startup. The address
is also sent to AuthGuard as X-Forwarded-For, which AuthGuard reads only from peers in its own
TRUSTED_PROXIES."""
router = APIRouter() router = APIRouter()
login_required_override: bool | None = None trusted_networks = (
trusted_proxies_from_env()
if trusted_proxies is None
else parse_trusted_proxies(trusted_proxies)
)
login_account_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, LOGIN_ACCOUNT_LIMIT)
login_client_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, LOGIN_CLIENT_LIMIT)
totp_attempts = AttemptLimiter(ATTEMPT_WINDOW_SECONDS, TOTP_ATTEMPT_LIMIT)
configured_internal_secret = ( configured_internal_secret = (
os.environ.get("SECRET", "") if internal_secret is None else internal_secret os.environ.get("SECRET", "") if internal_secret is None else internal_secret
).strip() ).strip()
@@ -265,6 +305,21 @@ def build_auth_router(
def _enabled(client: Optional[AuthClient]) -> bool: def _enabled(client: Optional[AuthClient]) -> bool:
return client is not None return client is not None
def _configured_client(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> Optional[AuthClient]:
"""Resolves the route's AuthClient. A missing client fails closed with a
500 unless running without AuthGuard was opted into."""
if client is None and not local_profile_without_authguard:
raise HTTPException(
status_code=500, detail=configuration_error or ERR_AUTHGUARD_NOT_CONFIGURED
)
return client
def _client_address(request: Request) -> str:
peer = request.client.host if request.client else ""
return client_address(peer, request.headers.getlist("x-forwarded-for"), trusted_networks)
def _session_token(request: Request) -> str: def _session_token(request: Request) -> str:
return request.cookies.get(cookie_name, "") or "" return request.cookies.get(cookie_name, "") or ""
@@ -307,14 +362,12 @@ def build_auth_router(
return profile, token return profile, token
async def _login_required(store: ProxyStore) -> bool: async def _login_required(store: ProxyStore) -> bool:
if login_required_override is not None:
return login_required_override
return await store.login_required() return await store.login_required()
async def require_session( async def require_session(
request: Request, request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> PublicUser: ) -> PublicUser:
"""FastAPI dependency gating a route behind a valid session.""" """FastAPI dependency gating a route behind a valid session."""
if not _enabled(client) or not await _login_required(store): if not _enabled(client) or not await _login_required(store):
@@ -326,7 +379,7 @@ def build_auth_router(
async def _require_user_manager( async def _require_user_manager(
request: Request, request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> str: ) -> str:
"""Returns the caller's session token, or "" in auth-disabled mode """Returns the caller's session token, or "" in auth-disabled mode
(each handler decides its own auth-disabled response). Authorization (each handler decides its own auth-disabled response). Authorization
@@ -341,7 +394,7 @@ def build_auth_router(
async def require_admin( async def require_admin(
request: Request, request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> PublicUser: ) -> PublicUser:
"""FastAPI dependency gating a route behind an administrator session """FastAPI dependency gating a route behind an administrator session
(the Python counterpart of Go's RequireAdmin). Unlike require_session it (the Python counterpart of Go's RequireAdmin). Unlike require_session it
@@ -362,7 +415,7 @@ def build_auth_router(
async def get_me( async def get_me(
request: Request, request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
_ensure_configured() _ensure_configured()
login_required = await _login_required(store) login_required = await _login_required(store)
@@ -383,7 +436,7 @@ def build_auth_router(
@router.get("/admin-needed") @router.get("/admin-needed")
async def get_admin_needed( async def get_admin_needed(
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]: ) -> dict[str, bool]:
if not _enabled(client): if not _enabled(client):
return {"adminNeeded": False} return {"adminNeeded": False}
@@ -402,7 +455,7 @@ def build_auth_router(
async def get_status( async def get_status(
request: Request, request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
_ensure_configured() _ensure_configured()
if not _enabled(client): if not _enabled(client):
@@ -444,9 +497,10 @@ def build_auth_router(
@router.post("/setup", status_code=201) @router.post("/setup", status_code=201)
async def setup( async def setup(
req: SetupRequest, req: SetupRequest,
request: Request,
response: Response, response: Response,
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
if not _enabled(client): if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)} return {"user": _user_payload(_LOCAL_PROFILE)}
@@ -468,7 +522,8 @@ def build_auth_router(
raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE) raise HTTPException(status_code=409, detail=ERR_SETUP_COMPLETE)
try: try:
result = await client.register(username, email, req.password) with forwarded_client_ip(_client_address(request)):
result = await client.register(username, email, req.password)
except AuthClientError as exc: except AuthClientError as exc:
await store.unclaim_setup() await store.unclaim_setup()
_raise_authguard_error(exc, "Could not create account.") _raise_authguard_error(exc, "Could not create account.")
@@ -480,8 +535,9 @@ def build_auth_router(
@router.post("/login") @router.post("/login")
async def login( async def login(
req: LoginRequest, req: LoginRequest,
request: Request,
response: Response, response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
if not _enabled(client): if not _enabled(client):
return {"user": _user_payload(_LOCAL_PROFILE)} return {"user": _user_payload(_LOCAL_PROFILE)}
@@ -489,8 +545,13 @@ def build_auth_router(
identifier = (req.identifier or req.username or req.email or "").strip() identifier = (req.identifier or req.username or req.email or "").strip()
if not identifier or len(identifier) > MAX_EMAIL_LEN: if not identifier or len(identifier) > MAX_EMAIL_LEN:
raise HTTPException(status_code=401, detail=ERR_INVALID_CREDENTIALS) raise HTTPException(status_code=401, detail=ERR_INVALID_CREDENTIALS)
address = _client_address(request)
account_ok = login_account_attempts.allow(identifier.lower())
if not (account_ok and login_client_attempts.allow(address)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
try: try:
result = await client.login(identifier, req.password, req.totpToken) with forwarded_client_ip(address):
result = await client.login(identifier, req.password, req.totpToken)
except APIError as exc: except APIError as exc:
if exc.totp_required: if exc.totp_required:
raise HTTPException( raise HTTPException(
@@ -513,7 +574,7 @@ def build_auth_router(
async def logout( async def logout(
request: Request, request: Request,
response: Response, response: Response,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]: ) -> dict[str, bool]:
if _enabled(client): if _enabled(client):
assert client is not None assert client is not None
@@ -537,7 +598,7 @@ def build_auth_router(
async def update_me( async def update_me(
req: UpdateMeRequest, req: UpdateMeRequest,
request: Request, request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
if not _enabled(client): if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD) raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
@@ -581,9 +642,7 @@ def build_auth_router(
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
_admin: PublicUser = Depends(require_admin), # noqa: B008 _admin: PublicUser = Depends(require_admin), # noqa: B008
) -> dict[str, bool]: ) -> dict[str, bool]:
nonlocal login_required_override
await store.set_login_required(req.loginRequired) await store.set_login_required(req.loginRequired)
login_required_override = req.loginRequired
return {"loginRequired": req.loginRequired} return {"loginRequired": req.loginRequired}
@router.put("/access/internal") @router.put("/access/internal")
@@ -592,21 +651,19 @@ 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]:
nonlocal login_required_override
if ( if (
not configured_internal_secret not configured_internal_secret
or 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)
login_required_override = req.loginRequired
return {"loginRequired": req.loginRequired} return {"loginRequired": req.loginRequired}
# --- admin user management ---------------------------------------------- # --- admin user management ----------------------------------------------
@router.get("/users") @router.get("/users")
async def list_users( async def list_users(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008 token: str = Depends(_require_user_manager), # noqa: B008
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
if not _enabled(client): if not _enabled(client):
@@ -622,7 +679,7 @@ def build_auth_router(
@router.post("/users", status_code=201) @router.post("/users", status_code=201)
async def create_managed_user( async def create_managed_user(
req: ManagedUserRequest, req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008 token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
if not _enabled(client): if not _enabled(client):
@@ -642,7 +699,7 @@ def build_auth_router(
async def update_managed_user( async def update_managed_user(
user_id: int, user_id: int,
req: ManagedUserRequest, req: ManagedUserRequest,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008 token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
if not _enabled(client): if not _enabled(client):
@@ -673,7 +730,7 @@ def build_auth_router(
@router.delete("/users/{user_id}") @router.delete("/users/{user_id}")
async def delete_managed_user( async def delete_managed_user(
user_id: int, user_id: int,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
token: str = Depends(_require_user_manager), # noqa: B008 token: str = Depends(_require_user_manager), # noqa: B008
) -> dict[str, bool]: ) -> dict[str, bool]:
if not _enabled(client): if not _enabled(client):
@@ -691,7 +748,7 @@ def build_auth_router(
@router.get("/totp/status") @router.get("/totp/status")
async def get_totp_status( async def get_totp_status(
request: Request, request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, bool]: ) -> dict[str, bool]:
if not _enabled(client): if not _enabled(client):
return {"enabled": False, "mfaEnabled": False} return {"enabled": False, "mfaEnabled": False}
@@ -702,7 +759,7 @@ def build_auth_router(
@router.post("/totp/initiate") @router.post("/totp/initiate")
async def initiate_totp( async def initiate_totp(
request: Request, request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
if not _enabled(client): if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD) raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
@@ -730,15 +787,18 @@ def build_auth_router(
async def verify_totp( async def verify_totp(
req: TotpTokenRequest, req: TotpTokenRequest,
request: Request, request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
if not _enabled(client): if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD) raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None assert client is not None
_, token = await _current_profile_or_401(request, client) profile, token = await _current_profile_or_401(request, client)
if not totp_attempts.allow(str(profile.id)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
code = req.totpToken or req.token code = req.totpToken or req.token
try: try:
await client.totp_verify(token, code) with forwarded_client_ip(_client_address(request)):
await client.totp_verify(token, code)
except Exception as exc: except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": True, "enabled": True, "backupCodes": []}} return {"data": {"mfaEnabled": True, "enabled": True, "backupCodes": []}}
@@ -747,15 +807,18 @@ def build_auth_router(
async def disable_totp( async def disable_totp(
req: TotpTokenRequest, req: TotpTokenRequest,
request: Request, request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(_configured_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
if not _enabled(client): if not _enabled(client):
raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD) raise HTTPException(status_code=409, detail=ERR_FEATURE_REQUIRES_AUTHGUARD)
assert client is not None assert client is not None
_, token = await _current_profile_or_401(request, client) profile, token = await _current_profile_or_401(request, client)
if not totp_attempts.allow(str(profile.id)):
raise HTTPException(status_code=429, detail=ERR_TOO_MANY_ATTEMPTS)
code = req.totpToken or req.token code = req.totpToken or req.token
try: try:
await client.totp_disable(token, code) with forwarded_client_ip(_client_address(request)):
await client.totp_disable(token, code)
except Exception as exc: except Exception as exc:
raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc raise HTTPException(status_code=401, detail="Invalid authenticator code.") from exc
return {"data": {"mfaEnabled": False, "enabled": False}} return {"data": {"mfaEnabled": False, "enabled": False}}
@@ -0,0 +1,76 @@
"""Trusted-proxy-aware client address, the Python counterpart of backend/auth/clientip.go.
The address used for attempt limits and forwarded to AuthGuard is the TCP peer. X-Forwarded-For is
read only when that peer is inside a configured trusted-proxy list (the TRUSTED_PROXIES setting),
and is then walked from the right to the first hop that is not itself a trusted proxy. The list is
empty by default, so a client can never choose its own address.
"""
from __future__ import annotations
import ipaddress
import os
from collections.abc import Iterable, Mapping, Sequence
__all__ = ["client_address", "parse_trusted_proxies", "trusted_proxies_from_env"]
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
def parse_trusted_proxies(value: str | None) -> list[IPNetwork]:
"""Parses a comma-separated list of CIDR ranges or bare IP addresses. An empty value trusts no
proxy. Raises ValueError for an entry that is neither."""
networks: list[IPNetwork] = []
for entry in (value or "").split(","):
entry = entry.strip()
if not entry:
continue
try:
networks.append(ipaddress.ip_network(entry, strict=False))
except ValueError as exc:
raise ValueError(
f"trusted proxy {entry!r} is neither an IP address nor a CIDR range"
) from exc
return networks
def trusted_proxies_from_env(env: Mapping[str, str] | None = None) -> list[IPNetwork]:
"""Reads the TRUSTED_PROXIES setting."""
source = os.environ if env is None else env
return parse_trusted_proxies(source.get("TRUSTED_PROXIES", ""))
def _parse_ip(value: str) -> IPAddress | None:
try:
ip = ipaddress.ip_address(value)
except ValueError:
return None
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
return ip.ipv4_mapped
return ip
def _is_trusted(ip: IPAddress, trusted: Sequence[IPNetwork]) -> bool:
return any(ip.version == network.version and ip in network for network in trusted)
def client_address(peer: str, forwarded_for: Iterable[str], trusted: Sequence[IPNetwork]) -> str:
"""Returns the address a request is counted against. peer is the TCP peer's host and
forwarded_for the values of every X-Forwarded-For header line. A malformed entry makes the peer
the answer, so a bad header can never choose the key."""
peer_ip = _parse_ip(peer)
if peer_ip is None or not _is_trusted(peer_ip, trusted):
return peer
hops = [part.strip() for line in forwarded_for for part in line.split(",") if part.strip()]
if not hops:
return peer
for hop in reversed(hops):
ip = _parse_ip(hop)
if ip is None:
return peer
if not _is_trusted(ip, trusted):
return str(ip)
# Every hop is a trusted proxy, so the left-most one is closest to the client.
first = _parse_ip(hops[0])
return str(first) if first is not None else peer
@@ -19,9 +19,29 @@ for a minimal FastAPI example.
from __future__ import annotations from __future__ import annotations
import hmac
import threading import threading
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Callable, Optional from typing import Callable, Optional
from urllib.parse import urlsplit
def internal_secret_matches(provided: Optional[str], secret: Optional[str]) -> bool:
"""True when the X-Internal-Auth value equals the configured secret. An
unset or empty secret never matches, and the comparison is constant-time."""
expected = (secret or "").encode("utf-8")
if not expected:
return False
return hmac.compare_digest(expected, (provided or "").encode("utf-8"))
def _is_service_url(value: str) -> bool:
try:
parts = urlsplit(value)
parts.port # noqa: B018 - raises ValueError for an invalid port
except ValueError:
return False
return parts.scheme in ("http", "https") and bool(parts.hostname)
@dataclass @dataclass
@@ -104,17 +124,26 @@ class Store:
"""Replaces the current Info, field by field, ignoring a """Replaces the current Info, field by field, ignoring a
blank/empty field so a partial push (e.g. only carrierNodeUrl(s) blank/empty field so a partial push (e.g. only carrierNodeUrl(s)
changed) never clobbers the other value. Returns the resulting changed) never clobbers the other value. Returns the resulting
Info. Minimal FastAPI usage: Info. Every URL must be an http or https URL with a host; otherwise
nothing is changed and ValueError is raised. Minimal FastAPI usage:
@app.put("/api/core-services/internal") @app.put("/api/core-services/internal")
async def push_core_services(request: Request): async def push_core_services(request: Request):
if request.headers.get("X-Internal-Auth") != SECRET: if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET):
raise HTTPException(status_code=401) raise HTTPException(status_code=401)
body = await request.json() body = await request.json()
info = core_config_store.set(Info.from_json(body)) try:
info = core_config_store.set(Info.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()} return {"ok": True, "info": info.to_json()}
""" """
next_info = _normalize(next_info) next_info = _normalize(next_info)
for url in [next_info.auth_guard_url, *next_info.carrier_node_urls]:
if url and not _is_service_url(url):
raise ValueError(
f"core service URL must be an http or https URL with a host: {url}"
)
with self._lock: with self._lock:
if next_info.auth_guard_url: if next_info.auth_guard_url:
self._info.auth_guard_url = next_info.auth_guard_url self._info.auth_guard_url = next_info.auth_guard_url
@@ -15,6 +15,24 @@ from .config import DatabaseConfig
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
# The same connection failures that database.js treats as transient: refused,
# reset and broken sockets, an administrative shutdown, a dropped connection
# (SQLSTATE class 08) and a connect timeout. Other errors, such as bad
# credentials or a missing database, are raised at once instead of retried.
_TRANSIENT_CONNECTION_ERRORS = (
ConnectionRefusedError,
ConnectionResetError,
BrokenPipeError,
TimeoutError,
asyncpg.exceptions.AdminShutdownError,
asyncpg.exceptions.PostgresConnectionError,
)
def is_transient_connection_error(exc: BaseException) -> bool:
"""Return True for connection failures that a startup retry can recover from."""
return isinstance(exc, _TRANSIENT_CONNECTION_ERRORS)
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
class StartupRetryOptions: class StartupRetryOptions:
@@ -50,7 +68,11 @@ async def retry_startup(
operation: Callable[[], Awaitable[Any]], operation: Callable[[], Awaitable[Any]],
options: StartupRetryOptions | None = None, options: StartupRetryOptions | None = None,
) -> Any: ) -> Any:
"""Retry a startup operation until it succeeds or the context is cancelled.""" """Retry a startup operation on transient connection errors only.
Any other exception is raised immediately, so a wrong password or a missing
database does not spin until the process is stopped.
"""
policy = options or startup_retry_options_from_env() policy = options or startup_retry_options_from_env()
attempt = 0 attempt = 0
@@ -61,6 +83,8 @@ async def retry_startup(
except asyncio.CancelledError: except asyncio.CancelledError:
raise raise
except Exception as exc: except Exception as exc:
if not is_transient_connection_error(exc):
raise
if policy.max_attempts and attempt >= policy.max_attempts: if policy.max_attempts and attempt >= policy.max_attempts:
raise raise
_logger.warning( _logger.warning(
@@ -0,0 +1,47 @@
"""Fixed-window attempt counters for credential endpoints, the Python counterpart of
backend/auth/ratelimit.go. Counters live in this process; AuthGuard's own limits apply on top."""
from __future__ import annotations
import threading
import time
from collections.abc import Callable
__all__ = ["AttemptLimiter"]
MAX_TRACKED_ATTEMPT_KEYS = 10000
class AttemptLimiter:
"""Each key may make `limit` attempts per `window` seconds; further attempts are refused until
the window ends. When the table is full of live keys a new key is refused rather than tracked,
so flooding distinct keys cannot grow memory without bound."""
def __init__(
self, window: float, limit: int, *, clock: Callable[[], float] = time.monotonic
) -> None:
self._window = window
self._limit = limit
self._clock = clock
self._lock = threading.Lock()
self._counts: dict[str, tuple[float, int]] = {}
def allow(self, key: str) -> bool:
"""Records one attempt for key and reports whether it is within the limit."""
now = self._clock()
with self._lock:
tracked = key in self._counts
if not tracked and len(self._counts) >= MAX_TRACKED_ATTEMPT_KEYS:
self._counts = {
existing: state
for existing, state in self._counts.items()
if now - state[0] < self._window
}
if len(self._counts) >= MAX_TRACKED_ATTEMPT_KEYS:
return False
start, count = self._counts.get(key, (now, 0))
if now - start >= self._window:
start, count = now, 0
count += 1
self._counts[key] = (start, count)
return count <= self._limit
@@ -72,4 +72,5 @@ def _normalize_secret(value: str) -> str:
def _normalize_token(value: str) -> str: def _normalize_token(value: str) -> str:
token = str(value or "").strip() token = str(value or "").strip()
return token if len(token) == TOTP_DIGITS and token.isdigit() else "" # str.isdigit() accepts other scripts' digits too, and hmac.compare_digest refuses those.
return token if len(token) == TOTP_DIGITS and token.isascii() and token.isdigit() else ""
@@ -0,0 +1,81 @@
import unittest
from shared_backend.clientip import client_address, parse_trusted_proxies
from shared_backend.ratelimit import MAX_TRACKED_ATTEMPT_KEYS, AttemptLimiter
class ParseTrustedProxiesTests(unittest.TestCase):
def test_accepts_cidrs_and_bare_addresses(self) -> None:
networks = parse_trusted_proxies(" 10.0.0.0/8, 192.168.1.5 ,fd00::/8,, ::1 ")
self.assertEqual(
[str(network) for network in networks],
["10.0.0.0/8", "192.168.1.5/32", "fd00::/8", "::1/128"],
)
def test_empty_trusts_no_proxy(self) -> None:
self.assertEqual(parse_trusted_proxies(" "), [])
self.assertEqual(parse_trusted_proxies(None), [])
def test_rejects_invalid_entries(self) -> None:
for value in ("not-an-ip", "10.0.0.0/33", "10.0.0.1, bogus"):
with self.assertRaises(ValueError, msg=value):
parse_trusted_proxies(value)
class ClientAddressTests(unittest.TestCase):
def test_forwarded_for_is_ignored_without_trusted_proxies(self) -> None:
self.assertEqual(client_address("203.0.113.7", ["198.51.100.1"], []), "203.0.113.7")
def test_forwarded_for_is_ignored_from_an_unknown_peer(self) -> None:
trusted = parse_trusted_proxies("10.0.0.0/8")
self.assertEqual(client_address("203.0.113.7", ["198.51.100.1"], trusted), "203.0.113.7")
def test_a_trusted_peer_has_its_header_honoured(self) -> None:
trusted = parse_trusted_proxies("10.0.0.0/8, 172.16.0.0/12")
cases = [
("single client", ["198.51.100.9"], "198.51.100.9"),
("second trusted hop", ["198.51.100.9, 172.16.4.4"], "198.51.100.9"),
("spoofed left-most entry", ["6.6.6.6, 198.51.100.9, 172.16.4.4"], "198.51.100.9"),
("entries across header lines", ["6.6.6.6", "198.51.100.9"], "198.51.100.9"),
("malformed entry", ["198.51.100.9, not-an-ip"], "10.0.0.2"),
("no header", [], "10.0.0.2"),
("every hop trusted", ["10.1.1.1, 172.16.4.4"], "10.1.1.1"),
]
for name, forwarded, want in cases:
with self.subTest(name):
self.assertEqual(client_address("10.0.0.2", forwarded, trusted), want)
def test_an_ipv4_mapped_peer_matches_an_ipv4_range(self) -> None:
trusted = parse_trusted_proxies("10.0.0.0/8")
self.assertEqual(
client_address("::ffff:10.0.0.2", ["198.51.100.9"], trusted), "198.51.100.9"
)
def test_a_non_ip_peer_is_returned_as_is(self) -> None:
self.assertEqual(client_address("testclient", ["198.51.100.9"], []), "testclient")
class AttemptLimiterTests(unittest.TestCase):
def test_window_and_limit(self) -> None:
now = [1000.0]
limiter = AttemptLimiter(60, 2, clock=lambda: now[0])
self.assertTrue(limiter.allow("k"))
self.assertTrue(limiter.allow("k"))
self.assertFalse(limiter.allow("k"))
self.assertTrue(limiter.allow("other"))
now[0] += 60
self.assertTrue(limiter.allow("k"))
def test_the_table_is_bounded(self) -> None:
now = [0.0]
limiter = AttemptLimiter(3600, 1, clock=lambda: now[0])
for i in range(MAX_TRACKED_ATTEMPT_KEYS):
limiter.allow(str(i))
self.assertFalse(limiter.allow("new-key"))
self.assertFalse(limiter.allow("0")) # a tracked key keeps its own count
now[0] += 3600 # every window has ended, so stale keys are dropped to make room
self.assertTrue(limiter.allow("new-key"))
if __name__ == "__main__":
unittest.main()
@@ -13,6 +13,7 @@ from shared_backend.authclient import (
InvalidSessionError, InvalidSessionError,
ManagedUser, ManagedUser,
PublicUser, PublicUser,
forwarded_client_ip,
resolve_user, resolve_user,
token_from_request, token_from_request,
) )
@@ -49,6 +50,37 @@ def _fake_http_error(status: int, payload: dict) -> urllib.error.HTTPError:
) )
class AuthClientForwardedClientIpTests(unittest.IsolatedAsyncioTestCase):
"""forwarded_client_ip makes credential calls carry the end user's address (S-009)."""
async def _login_request(self, address):
client = AuthClient("https://authguard.example")
payload = {"user": {"id": 1, "username": "a", "email": "", "role": "user"}}
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_FakeResponse(200, payload),
) as urlopen:
if address is None:
await client.login("a", "secret-password")
else:
with forwarded_client_ip(address):
await client.login("a", "secret-password")
return urlopen.call_args.args[0]
async def test_the_address_is_sent_as_x_forwarded_for(self) -> None:
request = await self._login_request("203.0.113.9")
self.assertEqual(request.get_header("X-forwarded-for"), "203.0.113.9")
async def test_no_header_is_sent_outside_the_block(self) -> None:
request = await self._login_request(None)
self.assertIsNone(request.get_header("X-forwarded-for"))
async def test_a_value_that_is_not_an_ip_address_is_dropped(self) -> None:
for value in ("203.0.113.9\r\nX-Evil: 1", "not-an-ip", ""):
request = await self._login_request(value)
self.assertIsNone(request.get_header("X-forwarded-for"), repr(value))
class AuthClientBaseUrlTests(unittest.TestCase): class AuthClientBaseUrlTests(unittest.TestCase):
def test_bare_public_host_assumes_https(self) -> None: def test_bare_public_host_assumes_https(self) -> None:
self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com") self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com")
@@ -155,6 +187,57 @@ class AuthClientValidateTests(unittest.IsolatedAsyncioTestCase):
await self.client.validate("a-token") await self.client.validate("a-token")
class AuthClientValidationCacheTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.client = AuthClient("https://authguard.example")
payload = {"valid": True, "user_id": 42, "username": "alice", "role": "admin"}
self.valid = _FakeResponse(200, payload)
async def test_repeated_validate_reuses_the_answer(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
) as urlopen:
first = await self.client.validate("a-token")
second = await self.client.validate("a-token")
self.assertEqual(first, second)
urlopen.assert_called_once()
async def test_invalid_session_is_cached_too(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_FakeResponse(401, {"valid": False}),
) as urlopen:
with self.assertRaises(InvalidSessionError):
await self.client.validate("bad-token")
with self.assertRaises(InvalidSessionError):
await self.client.validate("bad-token")
urlopen.assert_called_once()
async def test_logout_drops_the_cached_answer(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen",
side_effect=[self.valid, _FakeResponse(200, {}), _FakeResponse(401, {"valid": False})],
) as urlopen:
await self.client.validate("a-token")
await self.client.logout("a-token")
with self.assertRaises(InvalidSessionError):
await self.client.validate("a-token")
self.assertEqual(urlopen.call_count, 3)
async def test_set_base_url_clears_the_cache(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
) as urlopen:
await self.client.validate("a-token")
self.client.set_base_url("https://authguard2.example")
await self.client.validate("a-token")
self.assertEqual(urlopen.call_count, 2)
class TokenFromRequestTests(unittest.TestCase): class TokenFromRequestTests(unittest.TestCase):
def test_prefers_authorization_header_over_cookie(self) -> None: def test_prefers_authorization_header_over_cookie(self) -> None:
headers = {"Authorization": "Bearer header-token"} headers = {"Authorization": "Bearer header-token"}
+166 -6
View File
@@ -10,6 +10,7 @@ from shared_backend.authclient import (
AuthClient, AuthClient,
PublicUser, PublicUser,
SessionResult, SessionResult,
_forwarded_client_ip,
) )
@@ -44,6 +45,8 @@ def _build_app(
client: AuthClient | None = None, client: AuthClient | None = None,
*, *,
internal_secret: str | None = None, internal_secret: str | None = None,
local_profile_without_authguard: bool = False,
trusted_proxies: str = "",
) -> FastAPI: ) -> FastAPI:
def get_client(request: Request) -> AuthClient | None: def get_client(request: Request) -> AuthClient | None:
return client return client
@@ -53,15 +56,23 @@ def _build_app(
app = FastAPI() app = FastAPI()
app.include_router( app.include_router(
ap.build_auth_router(get_client, get_store, internal_secret=internal_secret), ap.build_auth_router(
get_client,
get_store,
internal_secret=internal_secret,
local_profile_without_authguard=local_profile_without_authguard,
trusted_proxies=trusted_proxies,
),
prefix="/api/auth", prefix="/api/auth",
) )
return app return app
class AuthDisabledModeTests(unittest.TestCase): class AuthDisabledModeTests(unittest.TestCase):
"""client=None (AUTHGUARD_URL unset) - every route reports the fixed """client=None (AUTHGUARD_URL unset) with the local-mode opt-in - every
placeholder superadmin identity and nothing is gated. This is also a route reports the fixed placeholder superadmin identity and nothing is
gated. Without the opt-in the same deployment fails closed; see
UnconfiguredAuthGuardTests. This is also a
regression test for a real bug this module had: request/response models regression test for a real bug this module had: request/response models
declared *inside* build_auth_router, combined with `from __future__ declared *inside* build_auth_router, combined with `from __future__
import annotations`, made FastAPI silently misparse every JSON body as a import annotations`, made FastAPI silently misparse every JSON body as a
@@ -69,7 +80,7 @@ class AuthDisabledModeTests(unittest.TestCase):
bug).""" bug)."""
def setUp(self) -> None: def setUp(self) -> None:
self.client = TestClient(_build_app(_FakeStore())) self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
def test_status_reports_local_superadmin(self) -> None: def test_status_reports_local_superadmin(self) -> None:
response = self.client.get("/api/auth/status") response = self.client.get("/api/auth/status")
@@ -118,6 +129,25 @@ class AuthDisabledModeTests(unittest.TestCase):
self.assertEqual(self.client.put("/api/auth/me", json={}).status_code, 409) self.assertEqual(self.client.put("/api/auth/me", json={}).status_code, 409)
class UnconfiguredAuthGuardTests(unittest.TestCase):
"""client=None without local_profile_without_authguard: a missing
AUTHGUARD_URL must not turn guarded routes into the local superadmin."""
def setUp(self) -> None:
self.client = TestClient(
_build_app(_FakeStore(login_required=True)), raise_server_exceptions=False
)
def test_guarded_routes_fail_closed(self) -> None:
self.assertEqual(self.client.get("/api/auth/status").status_code, 500)
self.assertEqual(self.client.get("/api/auth/me").status_code, 500)
self.assertEqual(self.client.get("/api/auth/users").status_code, 500)
self.assertEqual(self.client.post("/api/auth/logout").status_code, 500)
def test_login_flag_read_is_still_public(self) -> None:
self.assertEqual(self.client.get("/api/auth/access").json(), {"loginRequired": True})
class AccessSettingsTests(unittest.TestCase): class AccessSettingsTests(unittest.TestCase):
def test_get_is_public_and_put_requires_an_admin_session(self) -> None: def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
store = _FakeStore(login_required=True) store = _FakeStore(login_required=True)
@@ -142,7 +172,7 @@ class AccessSettingsTests(unittest.TestCase):
store = _FakeStore(login_required=True) store = _FakeStore(login_required=True)
client = TestClient(_build_app(store)) client = TestClient(_build_app(store))
response = client.put("/api/auth/access", json={"loginRequired": False}) response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 401) 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_disables_login_and_uses_admin_identity(self) -> None: def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
@@ -275,12 +305,142 @@ class EnabledModeSetupAndLoginTests(unittest.TestCase):
self.assertIsNone(body["user"]) self.assertIsNone(body["user"])
class _AddressRecordingClient(_RoleClient):
"""Records the address AuthClient would send as X-Forwarded-For for each credential call, and
counts the calls that reached AuthGuard."""
def __init__(self) -> None:
super().__init__()
self.forwarded: list[str | None] = []
self.login_calls = 0
self.totp_calls = 0
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
self.login_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
return await super().login(username_or_email, password, totp_token)
async def register(self, username: str, email: str, password: str) -> SessionResult:
self.forwarded.append(_forwarded_client_ip.get())
return await super().register(username, email, password)
async def totp_verify(self, token: str, code: str) -> None:
self.totp_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
if code != "123456":
raise APIError(401, "bad code")
async def totp_disable(self, token: str, code: str) -> None:
self.totp_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
raise APIError(401, "bad code")
class AttemptLimitTests(unittest.TestCase):
"""Login and the TOTP routes refuse further attempts with 429 (S-009)."""
def _login(self, client: TestClient, identifier: str = "Victim") -> int:
response = client.post(
"/api/auth/login", json={"identifier": identifier, "password": "wrong"}
)
return response.status_code
def test_login_is_limited_per_account_before_authguard_is_called(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake))
for attempt in range(ap.LOGIN_ACCOUNT_LIMIT):
self.assertEqual(self._login(client), 401, f"attempt {attempt + 1}")
self.assertEqual(self._login(client), 429)
self.assertEqual(self._login(client, "VICTIM"), 429) # the account key ignores case
self.assertEqual(fake.login_calls, ap.LOGIN_ACCOUNT_LIMIT)
self.assertEqual(self._login(client, "someone-else"), 401)
def test_login_is_limited_per_client_address(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake), client=("203.0.113.7", 40000))
statuses = [self._login(client, f"user{i}") for i in range(ap.LOGIN_CLIENT_LIMIT + 1)]
self.assertEqual(statuses[:-1], [401] * ap.LOGIN_CLIENT_LIMIT)
self.assertEqual(statuses[-1], 429)
def test_totp_verify_and_disable_share_a_per_user_limit(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake))
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
for _ in range(ap.TOTP_ATTEMPT_LIMIT - 1):
response = client.post("/api/auth/totp/verify", json={"totpToken": "000000"})
self.assertEqual(response.status_code, 401)
self.assertEqual(
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 401
)
self.assertEqual(
client.post("/api/auth/totp/verify", json={"totpToken": "123456"}).status_code, 429
)
self.assertEqual(
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 429
)
self.assertEqual(fake.totp_calls, ap.TOTP_ATTEMPT_LIMIT)
class ClientAddressForwardingTests(unittest.TestCase):
"""The client address is the TCP peer unless the peer is a trusted proxy (decision 5), and it
reaches AuthGuard as X-Forwarded-For through forwarded_client_ip."""
def _login_address(self, *, peer: str, trusted: str, forwarded: str | None) -> str | None:
fake = _AddressRecordingClient()
client = TestClient(
_build_app(_FakeStore(), fake, trusted_proxies=trusted), client=(peer, 40000)
)
headers = {"X-Forwarded-For": forwarded} if forwarded is not None else {}
response = client.post(
"/api/auth/login",
json={"identifier": "a@b.com", "password": "correct"},
headers=headers,
)
self.assertEqual(response.status_code, 200)
return fake.forwarded[-1]
def test_the_tcp_peer_is_forwarded_without_trusted_proxies(self) -> None:
got = self._login_address(peer="203.0.113.7", trusted="", forwarded="6.6.6.6")
self.assertEqual(got, "203.0.113.7")
def test_a_spoofed_header_from_an_untrusted_peer_is_ignored(self) -> None:
got = self._login_address(peer="203.0.113.7", trusted="10.0.0.0/8", forwarded="6.6.6.6")
self.assertEqual(got, "203.0.113.7")
def test_a_trusted_peer_has_its_header_walked_right_to_left(self) -> None:
got = self._login_address(
peer="10.0.0.2", trusted="10.0.0.0/8", forwarded="6.6.6.6, 198.51.100.9, 10.0.0.1"
)
self.assertEqual(got, "198.51.100.9")
def test_setup_and_totp_forward_the_address_too(self) -> None:
fake = _AddressRecordingClient()
fake.setup_required = True
client = TestClient(_build_app(_FakeStore(), fake), client=("198.51.100.20", 40000))
client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
client.post("/api/auth/totp/verify", json={"totpToken": "123456"})
client.post("/api/auth/totp/disable", json={"totpToken": "123456"})
self.assertEqual(fake.forwarded, ["198.51.100.20"] * 3)
def test_the_forwarded_address_does_not_leak_outside_the_call(self) -> None:
self._login_address(peer="203.0.113.7", trusted="", forwarded=None)
self.assertIsNone(_forwarded_client_ip.get())
def test_an_invalid_trusted_proxy_list_fails_at_startup(self) -> None:
with self.assertRaises(ValueError):
_build_app(_FakeStore(), trusted_proxies="10.0.0.0/8, not-an-ip")
class RequestValidationTests(unittest.TestCase): class RequestValidationTests(unittest.TestCase):
"""Every JSON-body route must actually parse its body (see the docstring """Every JSON-body route must actually parse its body (see the docstring
on AuthDisabledModeTests for the regression this guards against).""" on AuthDisabledModeTests for the regression this guards against)."""
def setUp(self) -> None: def setUp(self) -> None:
self.client = TestClient(_build_app(_FakeStore())) self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
def test_setup_rejects_missing_fields_with_422_not_500(self) -> None: def test_setup_rejects_missing_fields_with_422_not_500(self) -> None:
response = self.client.post("/api/auth/setup", json={}) response = self.client.post("/api/auth/setup", json={})
@@ -0,0 +1,77 @@
import json
import unittest
from pathlib import Path
from shared_backend.auth import (
hash_password,
password_hash_needs_upgrade,
verify_and_upgrade_password,
verify_password,
)
from shared_backend.clientip import client_address, parse_trusted_proxies
from shared_backend.totp import verify_totp
# 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"
@unittest.skipUnless(
CONTRACT_PATH.exists(), "contract/auth-contract.json is not part of this checkout"
)
class AuthContractTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.contract = json.loads(CONTRACT_PATH.read_text(encoding="utf-8"))
def test_password_hashes_verify_as_the_contract_says_for_python(self) -> None:
password = self.contract["password"]
for entry in password["hashes"]:
with self.subTest(entry["name"]):
self.assertEqual(
verify_password(password["plaintext"], entry["hash"]),
entry["verifies"]["python"],
)
self.assertFalse(verify_password(password["wrongPassword"], entry["hash"]))
if "python" in entry.get("needsUpgrade", {}):
want = entry["needsUpgrade"]["python"]
self.assertEqual(password_hash_needs_upgrade(entry["hash"]), want)
valid, upgraded = verify_and_upgrade_password(
password["plaintext"], entry["hash"]
)
self.assertTrue(valid)
self.assertEqual(upgraded is not None, want)
if upgraded is not None:
self.assertTrue(upgraded.startswith("bcrypt$"))
self.assertTrue(verify_password(password["plaintext"], upgraded))
def test_the_password_length_contract_holds_for_python(self) -> None:
too_long = self.contract["password"]["tooLongToHash"]
try:
hash_password("a" * too_long["bytes"])
accepted = True
except ValueError:
accepted = False
self.assertEqual(accepted, too_long["accepted"]["python"])
def test_totp_verifies_as_the_contract_says(self) -> None:
totp = self.contract["totp"]
for entry in totp["cases"]:
with self.subTest(entry["name"]):
secret = entry.get("secret", totp["secret"])
self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"])
def test_client_address_follows_the_contract(self) -> None:
section = self.contract["clientAddress"]
for entry in section["cases"]:
with self.subTest(entry["name"]):
trusted = parse_trusted_proxies(entry["trusted"])
self.assertEqual(
client_address(entry["peer"], entry["forwarded"], trusted), entry["want"]
)
for value in section["invalidTrustedProxyLists"]:
with self.subTest(value), self.assertRaises(ValueError):
parse_trusted_proxies(value)
if __name__ == "__main__":
unittest.main()
+107 -1
View File
@@ -1,9 +1,26 @@
import asyncio
import os import os
import unittest import unittest
from datetime import timedelta from datetime import timedelta
from shared_backend.auth import ResetManager, hash_password, verify_password import bcrypt
from shared_backend.auth import (
ResetManager,
hash_password,
hash_password_async,
password_hash_needs_upgrade,
verify_and_upgrade_password,
verify_and_upgrade_password_async,
verify_password,
verify_password_async,
)
from shared_backend.config import DatabaseConfig from shared_backend.config import DatabaseConfig
from shared_backend.postgres import (
StartupRetryOptions,
is_transient_connection_error,
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
@@ -14,6 +31,95 @@ class SharedBackendTests(unittest.TestCase):
self.assertTrue(verify_password("correct horse battery staple", password_hash)) self.assertTrue(verify_password("correct horse battery staple", password_hash))
self.assertFalse(verify_password("wrong password", password_hash)) self.assertFalse(verify_password("wrong password", password_hash))
def test_async_password_helpers_match_the_sync_ones(self):
async def run():
password_hash = await hash_password_async("correct horse battery staple")
self.assertTrue(verify_password("correct horse battery staple", password_hash))
self.assertTrue(
await verify_password_async("correct horse battery staple", password_hash)
)
self.assertFalse(await verify_password_async("wrong password", password_hash))
asyncio.run(run())
def test_new_hashes_carry_the_scheme_prefix_and_the_current_cost(self):
password_hash = hash_password("correct horse battery staple")
self.assertTrue(password_hash.startswith("bcrypt$$2b$12$"))
self.assertFalse(password_hash_needs_upgrade(password_hash))
def test_unprefixed_legacy_bcrypt_hashes_still_verify_and_are_upgraded(self):
legacy = bcrypt.hashpw(
b"correct horse battery staple", bcrypt.gensalt(rounds=12)
).decode()
self.assertTrue(verify_password("correct horse battery staple", legacy))
self.assertFalse(verify_password("wrong password", legacy))
self.assertTrue(password_hash_needs_upgrade(legacy))
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", legacy)
self.assertTrue(valid)
self.assertTrue(upgraded.startswith("bcrypt$$2b$12$"))
self.assertTrue(verify_password("correct horse battery staple", upgraded))
self.assertFalse(password_hash_needs_upgrade(upgraded))
def test_a_cost_below_the_current_policy_is_upgraded(self):
low_cost = "bcrypt$" + bcrypt.hashpw(
b"correct horse battery staple", bcrypt.gensalt(rounds=4)
).decode()
self.assertTrue(password_hash_needs_upgrade(low_cost))
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", low_cost)
self.assertTrue(valid)
self.assertIsNotNone(upgraded)
def test_a_wrong_password_and_a_current_hash_are_not_rewritten(self):
current = hash_password("correct horse battery staple")
password = "correct horse battery staple"
self.assertEqual(verify_and_upgrade_password(password, current), (True, None))
self.assertEqual(verify_and_upgrade_password("wrong password", current), (False, None))
def test_unknown_formats_fail_closed(self):
unknown = [
"",
"bcrypt$",
"bcrypt$not-a-bcrypt-string",
"pbkdf2-sha256$600000$00$00",
"$1$abc",
]
for stored in unknown:
self.assertFalse(verify_password("correct horse battery staple", stored), stored)
def test_async_upgrade_matches_the_sync_one(self):
password = "correct horse battery staple"
legacy = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12)).decode()
async def run():
valid, upgraded = await verify_and_upgrade_password_async(password, legacy)
self.assertTrue(valid)
self.assertTrue(await verify_password_async(password, upgraded))
asyncio.run(run())
def test_startup_retry_only_retries_transient_connection_errors(self):
import asyncpg
async def retry_with(error):
attempts = []
async def operation():
attempts.append(1)
raise error
policy = StartupRetryOptions(interval_seconds=0.001, max_attempts=3)
with self.assertRaises(type(error)):
await retry_startup(operation, policy)
return len(attempts)
self.assertTrue(is_transient_connection_error(ConnectionRefusedError()))
self.assertTrue(is_transient_connection_error(asyncpg.exceptions.ConnectionDoesNotExistError("closed")))
self.assertFalse(is_transient_connection_error(asyncpg.exceptions.InvalidPasswordError("bad")))
self.assertFalse(is_transient_connection_error(ValueError("bad")))
self.assertEqual(asyncio.run(retry_with(ValueError("bad"))), 1)
self.assertEqual(asyncio.run(retry_with(ConnectionRefusedError())), 3)
def test_session_token_hash(self): def test_session_token_hash(self):
token, token_hash = new_session_token() token, token_hash = new_session_token()
self.assertNotEqual(token, token_hash) self.assertNotEqual(token, token_hash)
@@ -1,6 +1,6 @@
import unittest import unittest
from shared_backend.coreconfig import Info, Store from shared_backend.coreconfig import Info, Store, internal_secret_matches
class StoreDefaultsTests(unittest.TestCase): class StoreDefaultsTests(unittest.TestCase):
@@ -62,5 +62,29 @@ class StoreSetTests(unittest.TestCase):
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com") self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
class InternalSecretTests(unittest.TestCase):
def test_unset_or_empty_secret_never_matches(self):
self.assertFalse(internal_secret_matches(None, None))
self.assertFalse(internal_secret_matches(None, ""))
self.assertFalse(internal_secret_matches("", ""))
self.assertFalse(internal_secret_matches("", None))
def test_compares_the_whole_secret(self):
self.assertTrue(internal_secret_matches("shared-secret", "shared-secret"))
self.assertFalse(internal_secret_matches("shared-secreT", "shared-secret"))
self.assertFalse(internal_secret_matches(None, "shared-secret"))
class UrlValidationTests(unittest.TestCase):
def test_rejects_urls_that_are_not_http_or_https_with_a_host(self):
store = Store(Info(auth_guard_url="http://auth.example.com"))
for bad in ["javascript:alert(1)", "auth.example.com", "ftp://carrier.example.com", "http://"]:
with self.subTest(url=bad), self.assertRaises(ValueError):
store.set(Info(auth_guard_url=bad))
with self.assertRaises(ValueError):
store.set(Info(carrier_node_urls=["http://carrier.example.com:99999"]))
self.assertEqual(store.auth_guard_url, "http://auth.example.com")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+120
View File
@@ -0,0 +1,120 @@
import unittest
from shared_backend.auth import (
AuthStore,
EmptyPasswordHashError,
InvalidUsernameError,
TotpAlreadyEnabledError,
hash_password,
)
class _FakeDatabase:
"""Records queries and answers them from canned results."""
def __init__(self) -> None:
self.executed: list[tuple[str, tuple]] = []
self.fetched: list[tuple[str, tuple]] = []
self.execute_status = "UPDATE 1"
self.totp_enabled = False
self.rows_by_condition: dict[str, dict] = {}
async def execute(self, query: str, *args) -> str:
self.executed.append((query, args))
return self.execute_status
async def fetchval(self, query: str, *args):
return False
async def fetchrow(self, query: str, *args):
self.fetched.append((query, args))
if "totp_enabled" in query:
return {"secret": "S", "enabled": self.totp_enabled}
for condition, row in self.rows_by_condition.items():
if condition in query:
return row
return None
def _user_row(username: str, email: str = "") -> dict:
return {
"id": 1,
"username": username,
"email": email,
"password_hash": "h",
"role": "user",
"created_at": None,
"updated_at": None,
}
class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.db = _FakeDatabase()
self.store = AuthStore(self.db, single_user=False) # type: ignore[arg-type]
async def test_ensure_schema_requests_the_case_insensitive_username_index(self) -> None:
await self.store.ensure_schema()
statements = " ".join(query for query, _ in self.db.executed)
self.assertIn("auth_users_username_lower_idx", statements)
self.assertIn("lower(username)", statements)
# The index is created only while no clashing pair exists.
self.assertIn("HAVING count(*) > 1", statements)
async def test_set_totp_secret_refuses_while_enabled(self) -> None:
self.db.execute_status = "UPDATE 0"
self.db.totp_enabled = True
with self.assertRaises(TotpAlreadyEnabledError):
await self.store.set_totp_secret(1, "NEWSECRET")
self.assertIn("NOT totp_enabled", self.db.executed[0][0])
async def test_set_totp_secret_succeeds_while_disabled(self) -> None:
await self.store.set_totp_secret(1, "NEWSECRET")
self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse
await self.store.set_totp_secret(2, "NEWSECRET")
async def test_credential_writes_refuse_an_empty_hash_and_an_at_username(self) -> None:
writes = [
lambda u, h: self.store.create_user(u, "", h),
lambda u, h: self.store.create_managed_user(u, "", h),
lambda u, h: self.store.update_credentials(1, u, "", h),
lambda u, h: self.store.update_user(1, username=u, password_hash=h),
]
for write in writes:
with self.assertRaises(EmptyPasswordHashError):
await write("alice", "")
with self.assertRaises(InvalidUsernameError):
await write("alice@example.com", "hash")
self.assertEqual(self.db.executed, [])
self.assertEqual(self.db.fetched, [])
async def test_update_user_leaves_unspecified_fields_alone(self) -> None:
await self.store.update_user(1, email="a@b.com")
await self.store.update_user(1, role="admin")
self.assertEqual(len(self.db.executed), 2)
async def test_find_by_identifier_tries_the_username_before_the_email(self) -> None:
self.db.rows_by_condition = {
"username = $1": _user_row("owner@example.com", "second@example.com"),
"lower(email) = lower($1)": _user_row("owner", "owner@example.com"),
}
found = await self.store.find_by_identifier("owner@example.com")
self.assertEqual(found.username, "owner@example.com")
self.assertEqual(len(self.db.fetched), 1)
del self.db.rows_by_condition["username = $1"]
found = await self.store.find_by_identifier("owner@example.com")
self.assertEqual(found.username, "owner")
class PasswordLengthTests(unittest.TestCase):
def test_hash_password_refuses_more_than_72_bytes(self) -> None:
with self.assertRaises(ValueError):
hash_password("a" * 73)
with self.assertRaises(ValueError):
hash_password("é" * 37) # 74 bytes
self.assertTrue(hash_password("a" * 72).startswith("bcrypt$"))
if __name__ == "__main__":
unittest.main()
+3 -1
View File
@@ -27,7 +27,9 @@
}, },
"scripts": { "scripts": {
"check": "svelte-check --tsconfig ./tsconfig.json", "check": "svelte-check --tsconfig ./tsconfig.json",
"package": "svelte-package" "lint": "eslint .",
"package": "svelte-package",
"test": "vitest run"
}, },
"svelte": "./dist/index.js", "svelte": "./dist/index.js",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
+166
View File
@@ -0,0 +1,166 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { afterEach, describe, expect, it, vi } from 'vitest';
import AuthPage from '../src/lib/components/AuthPage.svelte';
afterEach(cleanup);
const input = (name: string): HTMLInputElement => {
const element = document.querySelector<HTMLInputElement>(`input[name="${name}"]`);
if (!element) throw new Error(`no input named ${name}`);
return element;
};
async function fill(name: string, value: string): Promise<void> {
await fireEvent.input(input(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('AuthPage login', () => {
it('shows the login form and passes the trimmed credentials to onLogin', async () => {
const onLogin = vi.fn().mockResolvedValue(undefined);
render(AuthPage, { props: { brand: 'Demo', onLogin } });
expect(screen.getByRole('heading', { name: 'Welcome back' })).toBeTruthy();
expect(document.querySelector('input[name="confirmPassword"]')).toBeNull();
await fill('identifier', 'alice@example.com');
await fill('password', 'correct horse');
await submit();
await waitFor(() => expect(onLogin).toHaveBeenCalledTimes(1));
expect(onLogin).toHaveBeenCalledWith({
identifier: 'alice@example.com',
password: 'correct horse',
totpToken: '',
});
});
it('shows the error from a failed login and lets the user retry', async () => {
const onLogin = vi
.fn()
.mockRejectedValueOnce(new Error('Invalid username or password.'))
.mockResolvedValue(undefined);
render(AuthPage, { props: { onLogin } });
await fill('identifier', 'alice');
await fill('password', 'wrong password');
await submit();
await waitFor(() => expect(screen.getByText('Invalid username or password.')).toBeTruthy());
await submit();
await waitFor(() => expect(onLogin).toHaveBeenCalledTimes(2));
await waitFor(() => expect(screen.queryByText('Invalid username or password.')).toBeNull());
});
it('asks for the authenticator code after a two-factor challenge and sends it on the next try', async () => {
const onLogin = vi
.fn()
.mockRejectedValueOnce(new Error('Two-factor authentication code required.'))
.mockResolvedValue(undefined);
render(AuthPage, { props: { onLogin } });
await fill('identifier', 'alice');
await fill('password', 'correct horse');
expect(document.querySelector('input[name="totpToken"]')).toBeNull();
await submit();
await waitFor(() => expect(input('totpToken')).toBeTruthy());
expect(screen.getByText('Enter the six-digit authenticator code to continue.')).toBeTruthy();
await submit(); // an empty code is not sent
expect(onLogin).toHaveBeenCalledTimes(1);
await fill('totpToken', ' 123456 ');
await submit();
await waitFor(() => expect(onLogin).toHaveBeenCalledTimes(2));
expect(onLogin).toHaveBeenLastCalledWith({ identifier: 'alice', password: 'correct horse', totpToken: '123456' });
});
it('does not offer the authenticator field when showTotp is off', async () => {
const onLogin = vi.fn().mockRejectedValue(new Error('Two-factor authentication code required.'));
render(AuthPage, { props: { onLogin, showTotp: false } });
await fill('identifier', 'alice');
await submit();
await waitFor(() => expect(screen.getByText('Two-factor authentication code required.')).toBeTruthy());
expect(document.querySelector('input[name="totpToken"]')).toBeNull();
});
it('reports a missing login handler instead of failing silently', async () => {
render(AuthPage);
await submit();
await waitFor(() => expect(screen.getByText('The application has not configured its login handler.')).toBeTruthy());
});
it('shows only the loading heading while loading', () => {
render(AuthPage, { props: { loading: true } });
expect(screen.getByRole('heading', { name: 'Loading...' })).toBeTruthy();
expect(document.querySelector('form')).toBeNull();
});
it('falls back to the login view when the status check failed, whatever setupRequired says', () => {
render(AuthPage, { props: { setupRequired: true, error: 'Could not reach the server.' } });
expect(screen.getByRole('heading', { name: 'Welcome back' })).toBeTruthy();
expect(screen.getByText('Could not reach the server.')).toBeTruthy();
});
});
describe('AuthPage setup', () => {
it('refuses mismatched passwords without calling onSetup', async () => {
const onSetup = vi.fn();
render(AuthPage, { props: { setupRequired: true, onSetup } });
expect(screen.getByRole('heading', { name: 'Create your account' })).toBeTruthy();
await fill('username', 'root');
await fill('email', 'root@example.com');
await fill('password', 'password one');
await fill('confirmPassword', 'password two');
await submit();
await waitFor(() => expect(screen.getByText('Passwords do not match.')).toBeTruthy());
expect(onSetup).not.toHaveBeenCalled();
});
it('passes the new account to onSetup when the passwords match', async () => {
const onSetup = vi.fn().mockResolvedValue(undefined);
render(AuthPage, { props: { setupRequired: true, onSetup } });
await fill('username', 'root');
await fill('email', 'root@example.com');
await fill('password', 'password one');
await fill('confirmPassword', 'password one');
await submit();
await waitFor(() =>
expect(onSetup).toHaveBeenCalledWith({ username: 'root', email: 'root@example.com', password: 'password one' }),
);
});
});
describe('AuthPage account reset', () => {
it('offers the reset link only when both handlers are given', () => {
render(AuthPage, { props: { onRequestReset: vi.fn() } });
expect(screen.queryByText('Reset admin account')).toBeNull();
cleanup();
render(AuthPage, { props: { onRequestReset: vi.fn(), onConfirmReset: vi.fn() } });
expect(screen.getByText('Reset admin account')).toBeTruthy();
});
it('requests a code, then confirms the trimmed code the user types', async () => {
const onRequestReset = vi.fn().mockResolvedValue(undefined);
const onConfirmReset = vi.fn().mockResolvedValue(undefined);
render(AuthPage, { props: { onRequestReset, onConfirmReset } });
await fireEvent.click(screen.getByText('Reset admin account'));
await waitFor(() => expect(onRequestReset).toHaveBeenCalledTimes(1));
expect(screen.getByText('A reset code has been printed to the server console.')).toBeTruthy();
await fireEvent.click(screen.getByText('Confirm reset'));
await waitFor(() => expect(screen.getByText('Enter the code printed in the server console.')).toBeTruthy());
expect(onConfirmReset).not.toHaveBeenCalled();
await fireEvent.input(screen.getByLabelText('Reset code'), { target: { value: ' ABCD1234 ' } });
await fireEvent.click(screen.getByText('Confirm reset'));
await waitFor(() => expect(onConfirmReset).toHaveBeenCalledWith('ABCD1234'));
});
it('shows the error when the reset request fails', async () => {
const onRequestReset = vi.fn().mockRejectedValue(new Error('AuthGuard is not reachable.'));
render(AuthPage, { props: { onRequestReset, onConfirmReset: vi.fn() } });
await fireEvent.click(screen.getByText('Reset admin account'));
await waitFor(() => expect(screen.getByText('AuthGuard is not reachable.')).toBeTruthy());
});
});
@@ -0,0 +1,38 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { afterEach, describe, expect, it, vi } from 'vitest';
import NotificationStack from '../src/lib/components/NotificationStack.svelte';
import { notifications, notify } from '../src/lib/notifications.svelte';
// The icon library compiles over a thousand components on import; the icons are not under test.
vi.mock('@lucide/svelte', () => {
const Icon = (): void => {};
return { CircleAlert: Icon, CircleCheck: Icon, Info: Icon, OctagonAlert: Icon, X: Icon };
});
afterEach(() => {
cleanup();
for (const entry of [...notifications.entries]) notifications.dismiss(entry.id);
});
describe('NotificationStack', () => {
it('renders each notification with its variant and message', async () => {
render(NotificationStack);
notify.success('Saved', 0);
notify.error('Failed', 0);
await waitFor(() => expect(screen.getByText('Saved')).toBeTruthy());
expect(screen.getByText('Failed')).toBeTruthy();
const variants = [...document.querySelectorAll('.sc-notification')].map((node) =>
node.getAttribute('data-variant'),
);
expect(variants).toEqual(['success', 'error']);
expect(screen.getByRole('status').getAttribute('aria-live')).toBe('polite');
});
it('dismisses a notification from its close button', async () => {
render(NotificationStack);
notify.info('Dismiss me', 0);
await waitFor(() => expect(screen.getByText('Dismiss me')).toBeTruthy());
await fireEvent.click(screen.getByLabelText('Dismiss notification'));
expect(notifications.entries).toHaveLength(0);
});
});
@@ -0,0 +1,59 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { notifications, notify } from '../src/lib/notifications.svelte';
function clear(): void {
for (const entry of [...notifications.entries]) notifications.dismiss(entry.id);
}
describe('notification store', () => {
beforeEach(() => {
vi.useFakeTimers();
clear();
});
afterEach(() => {
clear();
vi.useRealTimers();
});
it('adds an entry per variant with increasing ids', () => {
const ids = [notify.success('saved'), notify.error('failed'), notify.warning('careful'), notify.info('fyi')];
expect(new Set(ids).size).toBe(4);
expect([...ids].sort((a, b) => a - b)).toEqual(ids);
expect(notifications.entries.map((entry) => [entry.variant, entry.message])).toEqual([
['success', 'saved'],
['error', 'failed'],
['warning', 'careful'],
['info', 'fyi'],
]);
});
it('removes an entry once its duration has passed, and only that entry', () => {
notify.info('short', 1000);
notify.info('long', 5000);
vi.advanceTimersByTime(999);
expect(notifications.entries).toHaveLength(2);
vi.advanceTimersByTime(1);
expect(notifications.entries.map((entry) => entry.message)).toEqual(['long']);
vi.advanceTimersByTime(4000);
expect(notifications.entries).toHaveLength(0);
});
it('uses a five second default and keeps an entry with duration 0 until it is dismissed', () => {
const timed = notify.success('default duration');
const sticky = notify.error('sticky', 0);
expect(notifications.entries.find((entry) => entry.id === timed)?.duration).toBe(5000);
vi.advanceTimersByTime(60_000);
expect(notifications.entries.map((entry) => entry.id)).toEqual([sticky]);
notify.dismiss(sticky);
expect(notifications.entries).toHaveLength(0);
});
it('dismissing early cancels the timer, and dismissing an unknown id is harmless', () => {
const id = notify.info('dismissed early', 1000);
notifications.dismiss(id);
expect(vi.getTimerCount()).toBe(0);
expect(() => notifications.dismiss(9999)).not.toThrow();
expect(notifications.entries).toHaveLength(0);
});
});
+117
View File
@@ -0,0 +1,117 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
PRIMARY_COLOR_PALETTE,
applyPrimaryColor,
initPrimaryColor,
primaryColorByName,
setPrimaryColor,
setPrimaryColorUser,
storedPrimaryColor,
} from '../src/lib/primary-color.svelte';
const styleText = (): string => document.getElementById('sc-primary-color')?.textContent ?? '';
function reset(): void {
document.getElementById('sc-primary-color')?.remove();
document.documentElement.removeAttribute('data-primary-color-user');
localStorage.clear();
}
describe('primary color palette', () => {
it('has unique names and valid colors', () => {
const names = PRIMARY_COLOR_PALETTE.map((color) => color.name);
expect(new Set(names).size).toBe(names.length);
for (const color of PRIMARY_COLOR_PALETTE) {
for (const value of [color.dark, color.light, color.darkFg]) {
expect(value, `${color.name} ${value}`).toMatch(/^#[0-9a-f]{6}$/);
}
}
});
it('finds a color by name and nothing for an unknown name', () => {
expect(primaryColorByName('Vermilion')?.light).toBe('#db3e24');
expect(primaryColorByName('Not a color')).toBeUndefined();
});
});
describe('primary color', () => {
beforeEach(reset);
afterEach(reset);
it('writes the light and dark declarations into one stylesheet, and replaces them on a change', () => {
applyPrimaryColor('app', 'Vermilion');
const css = styleText();
expect(css).toContain('--color-primary: #db3e24 !important;');
expect(css).toContain("[data-theme='dark']");
expect(css).toContain('--color-primary: #f59080 !important;');
expect(css).toContain('--sc-primary-fg: #ffffff !important;');
expect(css).toContain('--sc-primary-fg: #2b110d !important;');
expect(css).toMatch(/--sc-primary-hover: #[0-9a-f]{6} !important;/);
applyPrimaryColor('app', 'Cyan');
expect(document.querySelectorAll('#sc-primary-color')).toHaveLength(1);
expect(styleText()).toContain('#249edb');
expect(styleText()).not.toContain('#db3e24');
});
it('makes the hover lighter on dark and darker on light', () => {
applyPrimaryColor('app', 'Clover');
const [light, dark] = styleText().split("[data-theme='dark']");
const hover = (css: string): number => {
const hex = /--sc-primary-hover: #([0-9a-f]{6})/.exec(css)?.[1] ?? '';
return [0, 2, 4].reduce((sum, start) => sum + parseInt(hex.slice(start, start + 2), 16), 0);
};
const base = (hexValue: string): number =>
[1, 3, 5].reduce((sum, start) => sum + parseInt(hexValue.slice(start, start + 2), 16), 0);
expect(hover(light)).toBeLessThan(base('#16a34a'));
expect(hover(dark)).toBeGreaterThan(base('#22c55e'));
});
it('removes the stylesheet for an unknown or empty color', () => {
applyPrimaryColor('app', 'Vermilion');
applyPrimaryColor('app', 'Not a color');
expect(document.getElementById('sc-primary-color')).toBeNull();
applyPrimaryColor('app', '');
expect(document.getElementById('sc-primary-color')).toBeNull();
});
it('stores the choice per project and user, and clears it', () => {
setPrimaryColorUser('Alice');
setPrimaryColor('My App', 'Violet');
expect(localStorage.getItem('primary-color:my%20app:alice')).toBe('Violet');
expect(storedPrimaryColor('my app')).toBe('Violet');
expect(styleText()).toContain('#6d24db');
setPrimaryColorUser('bob');
expect(storedPrimaryColor('my app')).toBe('');
setPrimaryColorUser('alice');
expect(storedPrimaryColor('my app')).toBe('Violet');
setPrimaryColor('my app', '');
expect(storedPrimaryColor('my app')).toBe('');
expect(localStorage.getItem('primary-color:my%20app:alice')).toBeNull();
expect(document.getElementById('sc-primary-color')).toBeNull();
});
it('ignores a stored name that is not in the palette', () => {
localStorage.setItem('primary-color:app:anonymous', 'Chartreuse-ish');
expect(storedPrimaryColor('app')).toBe('');
});
it('applies the stored color on init and re-applies it when the user changes', () => {
localStorage.setItem('primary-color:shop:carol', 'Rose');
initPrimaryColor('shop', 'Carol');
expect(styleText()).toContain('#db2474');
localStorage.setItem('primary-color:shop:dave', 'Lime');
setPrimaryColorUser('dave');
expect(styleText()).toContain('#72b814');
setPrimaryColorUser('someone-without-a-choice');
expect(document.getElementById('sc-primary-color')).toBeNull();
});
it('treats a blank user as anonymous', () => {
setPrimaryColor('app', 'Gold');
expect(localStorage.getItem('primary-color:app:anonymous')).toBe('Gold');
});
});
+19
View File
@@ -0,0 +1,19 @@
// jsdom has no Web Animations API, which Svelte's transitions call. This stand-in finishes at once,
// so an element that leaves with a transition is removed straight away.
if (typeof Element.prototype.animate !== 'function') {
Element.prototype.animate = function animate(): Animation {
const animation = {
currentTime: 0,
onfinish: null as (() => void) | null,
cancel() {},
finish() {
animation.onfinish?.();
},
pause() {},
play() {},
finished: Promise.resolve(),
};
queueMicrotask(() => animation.onfinish?.());
return animation as unknown as Animation;
};
}
+14
View File
@@ -0,0 +1,14 @@
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { svelteTesting } from '@testing-library/svelte/vite';
import { defineConfig } from 'vitest/config';
// Component and store tests run in jsdom. They live in tests/, outside src/lib, so svelte-package
// never ships them.
export default defineConfig({
plugins: [svelte(), svelteTesting()],
test: {
environment: 'jsdom',
include: ['tests/**/*.test.ts'],
setupFiles: ['tests/setup.ts'],
},
});
+3 -2
View File
@@ -1,10 +1,11 @@
import { readFile, writeFile } from 'node:fs/promises'; import { readFile, writeFile } from 'node:fs/promises';
const source = await readFile(new URL('../packages/web-ui/dist/styles.css', import.meta.url), 'utf8'); const source = await readFile(new URL('../packages/web-ui/dist/styles.css', import.meta.url), 'utf8');
const tokenImport = "@import '@gabriel20xx/design-tokens/theme.css';"; // The token import may be written with single or double quotes, and with or without the semicolon.
const tokenImport = /^@import\s+(['"])@gabriel20xx\/design-tokens\/theme\.css\1\s*;?$/;
const componentStyles = source const componentStyles = source
.split(/\r?\n/) .split(/\r?\n/)
.filter((line) => line.trim() !== tokenImport) .filter((line) => !tokenImport.test(line.trim()))
.join('\n') .join('\n')
.trimStart(); .trimStart();
+1 -1
View File
@@ -10,4 +10,4 @@ if ($LASTEXITCODE -ne 0) {
throw 'Could not configure the shared Git hooks path.' throw 'Could not configure the shared Git hooks path.'
} }
Write-Host "Installed shared post-commit synchronization hook in $repositoryRoot." Write-Host "Installed shared post-commit synchronization hook in $repositoryRoot. It runs only for commits made with SHARED_SYNC_COMMIT=1."
+12 -11
View File
@@ -6,21 +6,18 @@ import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..'); const repoRoot = path.resolve(__dirname, '..', '..');
// The monorepo kept its canonical JS/TS test sources under a single repo-root tests/ dir, which // Scan the JS/TS test locations that exist in this repo: the web-ui tests (packages/web-ui/tests,
// doesn't exist in this repo. Scan the real locations JS/TS test files can currently live in // plus anything under its source) and the Node package's test directory. repoRoot/tests is kept as a
// this repo instead: webui/src (SvelteKit app) and shared/packages/*/test(s) (vendored from the // forward-compatible root. A scan that finds no test files fails, so the check cannot pass
// shared repo). repoRoot/tests is kept as a forward-compatible root in case one is added later. // vacuously.
// As of this repo's extraction, none of these contain vitest/mocha/jest-style test files yet
// (shared/packages/node-backend/test/auth.test.js uses plain `node --test`, which shares the same
// describe/it/test .skip API surface these patterns already match), so this currently passes
// trivially rather than being a dead check.
const testsRoots = [ const testsRoots = [
path.join(repoRoot, 'tests'), path.join(repoRoot, 'tests'),
path.join(repoRoot, 'webui', 'src'), path.join(repoRoot, 'packages', 'web-ui', 'src'),
path.join(repoRoot, 'shared', 'packages'), path.join(repoRoot, 'packages', 'web-ui', 'tests'),
path.join(repoRoot, 'packages', 'node-backend', 'test'),
]; ];
const TEST_FILE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs']); const TEST_FILE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.ts']);
const DISALLOWED_LINE_PATTERNS = [ const DISALLOWED_LINE_PATTERNS = [
{ {
name: 'skip/todo/runIf declaration', name: 'skip/todo/runIf declaration',
@@ -79,6 +76,10 @@ function collectViolations(filePath) {
} }
const files = testsRoots.flatMap(listTestFiles).sort(); const files = testsRoots.flatMap(listTestFiles).sort();
if (files.length === 0) {
console.error('[enforce-no-skipped-tests] No test files were found in the scanned roots; refusing to report success.');
process.exit(1);
}
const failures = []; const failures = [];
for (const filePath of files) { for (const filePath of files) {
+3 -3
View File
@@ -12,13 +12,13 @@
*/ */
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { dirname, resolve, join } from 'node:path'; import { dirname, resolve } from 'node:path';
import { existsSync } from 'node:fs'; import { existsSync } from 'node:fs';
const __dirname = dirname(fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..', '..'); const root = resolve(__dirname, '..', '..');
const packages = [{ name: 'webui', path: 'webui' }]; const packages = [{ name: 'web-ui', path: 'packages/web-ui' }];
function resolveEslintInvocation({ pkgDir }) { function resolveEslintInvocation({ pkgDir }) {
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js'); const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
@@ -65,7 +65,7 @@ for (const pkg of packages) {
continue; continue;
} }
let parsed = []; let parsed;
try { try {
parsed = JSON.parse(result.stdout || '[]'); parsed = JSON.parse(result.stdout || '[]');
} catch (e) { } catch (e) {
+17 -26
View File
@@ -1,19 +1,18 @@
#!/usr/bin/env node #!/usr/bin/env node
/** /**
* Lint all JS/TS packages sequentially with clear section headers, plus a repo-wide Prettier * Lint all JS/TS packages sequentially with clear section headers, plus the Prettier format check.
* format check.
* Exits non‑zero if any package fails its lint step. * Exits non‑zero if any package fails its lint step.
* *
* Shared extraction note: the monorepo version of this script discovered the monorepo root * Shared extraction note: the monorepo version of this script discovered the monorepo root
* by walking up for a MediaShared/package.json marker, iterated nine sibling Media* packages * by walking up for a MediaShared/package.json marker, iterated nine sibling Media* packages
* against a shared root eslint.config.mjs/.stylelintrc.json, and ran Prettier/Stylelint out of * against a shared root eslint.config.mjs/.stylelintrc.json, and ran Prettier/Stylelint out of
* MediaShared/node_modules (npm workspace hoisting). None of that exists in this repo: there is * MediaShared/node_modules (npm workspace hoisting). Here the only JS/TS package with a lint
* no root package.json, no shared devDependency hoisting, and webui/ is the only JS/TS package — * target is packages/web-ui, linted with the root eslint.config.js (ESLint is a root
* it already ships its own local eslint.config.js and prettier.config.js. The Stylelint section * devDependency, so `npx eslint` resolves it). Prettier is checked through the root
* has been dropped entirely rather than pointed at a nonexistent .stylelintrc.json: webui has no * `format:check` script, which covers only the files written to the Prettier style (see
* stylelint devDependency and its CSS is Tailwind-authored, so there was nothing equivalent to * .prettierrc.json): the older sources were never formatted with it. The Stylelint section has
* carry over. If CSS linting is wanted later, it would need its own stylelint config added to * been dropped entirely rather than pointed at a nonexistent .stylelintrc.json: web-ui's CSS is
* webui/ (or a new root package.json) first. * Tailwind-authored, so there was nothing equivalent to carry over.
*/ */
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
@@ -23,7 +22,7 @@ import { existsSync } from 'node:fs';
const __dirname = dirname(fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..', '..'); const root = resolve(__dirname, '..', '..');
const packages = [{ name: 'webui', path: 'webui' }]; const packages = [{ name: 'web-ui', path: 'packages/web-ui' }];
function resolveEslintInvocation({ pkgDir }) { function resolveEslintInvocation({ pkgDir }) {
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js'); const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
@@ -80,23 +79,15 @@ for (const pkg of packages) {
} }
} }
// ===== webui: Prettier format check ===== // ===== Prettier format check (the files covered by the root format:check script) =====
console.log('\n===== FORMAT CHECK (Prettier, webui) ====='); console.log('\n===== FORMAT CHECK (Prettier) =====');
{ {
const webuiDir = resolve(root, 'webui'); const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const prettierBin = resolve(webuiDir, 'node_modules', 'prettier', 'bin', 'prettier.cjs'); const fmtResult = spawnCrossPlatform(npmCmd, ['run', 'format:check'], {
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx'; cwd: root,
const fmtResult = existsSync(prettierBin) stdio: 'inherit',
? spawnCrossPlatform(process.execPath, [prettierBin, '--check', '.'], { env: process.env,
cwd: webuiDir, });
stdio: 'inherit',
env: process.env,
})
: spawnCrossPlatform(npxCmd, ['prettier', '--check', '.'], {
cwd: webuiDir,
stdio: 'inherit',
env: process.env,
});
if (fmtResult.error || fmtResult.status !== 0) { if (fmtResult.error || fmtResult.status !== 0) {
failures++; failures++;
console.error('✖ Format check failed'); console.error('✖ Format check failed');
-1
View File
@@ -48,7 +48,6 @@ child.stdout.on('data', d => {
// Capture last JSON object emitted by vitest reporter (it prints progress lines + final JSON) // Capture last JSON object emitted by vitest reporter (it prints progress lines + final JSON)
jsonBlock += text; jsonBlock += text;
}); });
// eslint-disable-next-line no-unused-vars
child.on('close', _code => { child.on('close', _code => {
// Attempt to find the final JSON object (Vitest prints *only* JSON in our current mode but be defensive) // Attempt to find the final JSON object (Vitest prints *only* JSON in our current mode but be defensive)
const match = jsonBlock.match(/(\{[\s\S]*\})\s*$/); const match = jsonBlock.match(/(\{[\s\S]*\})\s*$/);
+5 -7
View File
@@ -100,13 +100,11 @@ async function updatePackageJson(packageJsonPath) {
return { changed, changes }; return { changed, changes };
} }
// this repo has no root package.json / npm workspaces (unlike the monorepo this was extracted // The root package.json declares npm workspaces (packages/*). The local packages whose dependency
// from), so there's no "workspaces" array to discover packages from. webui/ is the only local npm // versions this repo owns and bumps directly are listed here. Vendored copies of this library in
// package whose dependency versions this repo owns and should bump directly. shared/package.json // other repositories are not listed: any local edit to them would be overwritten by the next sync,
// is intentionally excluded: it's a vendored, byte-for-byte copy synced in from the separate // so bumps for them belong upstream.
// shared repo (see scripts/sync-shared.mjs) and any local edit to it would just be overwritten by const LOCAL_PACKAGE_DIRS = ['packages/web-ui', 'packages/node-backend'];
// the next sync — dependency bumps for shared/ belong upstream in that repo instead.
const LOCAL_PACKAGE_DIRS = ['webui'];
async function main() { async function main() {
const packageJsonPaths = LOCAL_PACKAGE_DIRS.map(dir => path.join(repoRoot, dir, 'package.json')); const packageJsonPaths = LOCAL_PACKAGE_DIRS.map(dir => path.join(repoRoot, dir, 'package.json'));
+11 -1
View File
@@ -270,9 +270,19 @@ foreach ($consumerProject in $consumerProjects) {
$dirtyDestination = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', $destination)) $dirtyDestination = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', $destination))
$dirtyLegacy = if ($isLegacyEligible) { @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', $legacyDirectoryName)) } else { @() } $dirtyLegacy = if ($isLegacyEligible) { @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', $legacyDirectoryName)) } else { @() }
if (($dirtyDestination.Count -gt 0 -or $dirtyLegacy.Count -gt 0) -and -not $Force) { $hasLocalChanges = $dirtyDestination.Count -gt 0 -or $dirtyLegacy.Count -gt 0
if ($hasLocalChanges -and -not $Force) {
throw "$destination has local changes. Commit them or rerun with -Force." throw "$destination has local changes. Commit them or rerun with -Force."
} }
if ($hasLocalChanges) {
# -Force replaces the snapshot, so keep a copy of what it replaces first.
$backupRoot = Join-Path ([IO.Path]::GetTempPath()) ('shared-sync-backup-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Force -Path $backupRoot | Out-Null
foreach ($existingEntry in @($destinationEntry, $legacyEntry) | Where-Object { $null -ne $_ }) {
Copy-Item -LiteralPath $existingEntry.FullName -Destination (Join-Path $backupRoot $existingEntry.Name) -Recurse -Force
}
Write-Host " Backed up the local $destination changes in $relativeProject to $backupRoot before overwriting."
}
if ($null -ne $legacyEntry) { if ($null -ne $legacyEntry) {
$temporaryRenamePath = Join-Path $projectRoot ('.shared-sync-rename-' + [Guid]::NewGuid().ToString('N')) $temporaryRenamePath = Join-Path $projectRoot ('.shared-sync-rename-' + [Guid]::NewGuid().ToString('N'))
+21 -2
View File
@@ -1,7 +1,5 @@
@import './packages/design-tokens/theme.css'; @import './packages/design-tokens/theme.css';
@import "@gabriel20xx/design-tokens/theme.css";
:where(.sc-root, .sc-root *) { :where(.sc-root, .sc-root *) {
box-sizing: border-box; box-sizing: border-box;
} }
@@ -705,6 +703,27 @@ html[data-wide-layout='true'] .sc-header {
box-shadow: 0 0 0 3px color-mix(in srgb, var(--sc-ring) 22%, transparent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--sc-ring) 22%, transparent);
} }
/* Checkboxes and radios share one look across apps. The box takes each app's primary color,
so it follows that app's light and dark theme. Sizes match the legacy shared sheet. The rule
sits in the base layer so Tailwind utilities (size-*, accent-*) still override it per element. */
@layer base {
input[type='checkbox'],
input[type='radio'] {
accent-color: var(--sc-primary);
width: 1.05rem;
height: 1.05rem;
flex: 0 0 auto;
}
input[type='checkbox'] {
border-radius: 4px;
}
input[type='radio'] {
border-radius: 9999px;
}
}
.sc-form-actions, .sc-form-actions,
.sc-dialog-footer { .sc-dialog-footer {
display: flex; display: flex;