Fix high audit findings and port the hidden-media rule
Fixed findings from the audit reports (SECURITY, QUALITY, PERFORMANCE): - P-001 · Unbounded per-session timing maps and no connection cap in the sync hub - S-001 · Anonymous `PUT /access` switches off login for every guarded route - S-002 · Malformed cookies crash the Node middleware and fail requests in Java - S-004 · Anonymous `PUT /sync` writes unvalidated JSON into shared session state Also includes the pre-existing uncommitted changes in web-ui, README, shared-styles and the .changeset files, as the owner asked. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7fd2f14f91
commit
199a5efaef
12 files changed
+443
-40
No files matched your search
+10
-8
@@ -7,26 +7,28 @@
|
|||||||
- **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).
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
| Severity | Count |
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|---|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 0 |
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
| High | 1 |
|
| High | 1 | 1 | 0 | 0 |
|
||||||
| Medium | 4 |
|
| Medium | 4 | 0 | 0 | 4 |
|
||||||
| Low | 4 |
|
| Low | 4 | 0 | 0 | 4 |
|
||||||
| Info | 1 |
|
| Info | 1 | 0 | 0 | 1 |
|
||||||
|
|
||||||
The auth code has no obvious SQL N+1 outside the playlist reorder path, and most outbound calls have timeouts. The main performance risks are unbounded in-memory state in the sync websocket hub, a per-request AuthGuard round trip with no caching, blocking CPU work (password hashing) on event loops, and a media lookup that defeats its index.
|
The auth code has no obvious SQL N+1 outside the playlist reorder path, and most outbound calls have timeouts. The main performance risks are unbounded in-memory state in the sync websocket hub, a per-request AuthGuard round trip with no caching, blocking CPU work (password hashing) on event loops, and a media lookup that defeats its index.
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
### P-001 · Unbounded per-session timing maps and no connection cap in the sync hub · **High**
|
### P-001 · Unbounded per-session timing maps and no connection cap in the sync hub · **High** · Fixed
|
||||||
- **Location:** `backend/syncsocket/syncsocket.go:443` (sync:update handler), `backend/syncsocket/syncsocket.go:446-455` (writes to `playAt`, `playAtLocalMs`, `capturedAtMs` keyed by session ID), `backend/syncsocket/syncsocket.go:457-463` (eviction covers only `states`), `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts unlimited connections)
|
- **Location:** `backend/syncsocket/syncsocket.go:443` (sync:update handler), `backend/syncsocket/syncsocket.go:446-455` (writes to `playAt`, `playAtLocalMs`, `capturedAtMs` keyed by session ID), `backend/syncsocket/syncsocket.go:457-463` (eviction covers only `states`), `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts unlimited connections)
|
||||||
- **Description:** The three timing maps are written per session ID and are cleared only in narrow branches. The 1000-session cap on `states` does not touch them, so the maps grow for every new session ID ever seen. `ServeWebSocket` has no peer or connection limit, and each connection holds a goroutine and buffers.
|
- **Description:** The three timing maps are written per session ID and are cleared only in narrow branches. The 1000-session cap on `states` does not touch them, so the maps grow for every new session ID ever seen. `ServeWebSocket` has no peer or connection limit, and each connection holds a goroutine and buffers.
|
||||||
- **Impact:** Memory grows without bound in a long-running process, and one client sending `sync:update` with fresh session IDs can drive that growth. Exposure depends on whether consumers gate `/ws` with authentication (see Security S-003; needs verification in consumers).
|
- **Impact:** Memory grows without bound in a long-running process, and one client sending `sync:update` with fresh session IDs can drive that growth. Exposure depends on whether consumers gate `/ws` with authentication (see Security S-003; needs verification in consumers).
|
||||||
- **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`.
|
||||||
|
|
||||||
### 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**
|
||||||
- **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)
|
||||||
|
|||||||
+18
-12
@@ -7,44 +7,49 @@
|
|||||||
- **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).
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
| Severity | Count |
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|---|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 1 |
|
| Critical | 1 | 1 | 0 | 0 |
|
||||||
| High | 3 |
|
| High | 3 | 2 | 0 | 1 |
|
||||||
| Medium | 13 |
|
| Medium | 13 | 0 | 0 | 13 |
|
||||||
| Low | 5 |
|
| Low | 5 | 0 | 0 | 5 |
|
||||||
| Info | 0 |
|
| Info | 0 | 0 | 0 | 0 |
|
||||||
|
|
||||||
The most serious issue is a Python router route that lets an anonymous caller switch off login for everything guarded by `require_session`. Beyond it, the common themes are fail-open defaults, a websocket hub with no identity, credential endpoints with no throttling, and weaker-than-intended hashing and second-factor controls. No live secrets were found in the current tree or in git history. Most findings that depend on AuthGuard need confirmation against that service.
|
The most serious issue is a Python router route that lets an anonymous caller switch off login for everything guarded by `require_session`. Beyond it, the common themes are fail-open defaults, a websocket hub with no identity, credential endpoints with no throttling, and weaker-than-intended hashing and second-factor controls. No live secrets were found in the current tree or in git history. Most findings that depend on AuthGuard need confirmation against that service.
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
### S-001 · Anonymous `PUT /access` switches off login for every guarded route · **Critical**
|
### S-001 · Anonymous `PUT /access` switches off login for every guarded route · **Critical** · Fixed
|
||||||
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:561-569` (`PUT /access` has no session or role dependency; `GET /access` at `:557-559` is also open), `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns the local superadmin profile once login is not required), `packages/python-backend/src/shared_backend/authproxy.py:103-105` (`_LOCAL_PROFILE`), `packages/python-backend/tests/test_authproxy.py:116-122` (asserts the unauthenticated PUT succeeds)
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:561-569` (`PUT /access` has no session or role dependency; `GET /access` at `:557-559` is also open), `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns the local superadmin profile once login is not required), `packages/python-backend/src/shared_backend/authproxy.py:103-105` (`_LOCAL_PROFILE`), `packages/python-backend/tests/test_authproxy.py:116-122` (asserts the unauthenticated PUT succeeds)
|
||||||
- **Description:** The public `PUT /access` only depends on the store, so any anonymous request with `{"loginRequired": false}` disables authentication. Once the flag is off, `require_session` returns the superadmin profile for every request. The internal variant at `authproxy.py:570-584` correctly requires `X-Internal-Auth`; the public one does not. The Go equivalent, `backend/auth/proxy.go:781`, is documented as manager-only (`proxy.go:796`).
|
- **Description:** The public `PUT /access` only depends on the store, so any anonymous request with `{"loginRequired": false}` disables authentication. Once the flag is off, `require_session` returns the superadmin profile for every request. The internal variant at `authproxy.py:570-584` correctly requires `X-Internal-Auth`; the public one does not. The Go equivalent, `backend/auth/proxy.go:781`, is documented as manager-only (`proxy.go:796`).
|
||||||
- **Impact:** Anyone who can reach a service that mounts `build_auth_router` can remove authentication from every route guarded by `require_session`. This is the documented usage (`packages/python-backend/README.md:123-133`), so exposure is likely in consumers. Consumer wiring was not reviewed.
|
- **Impact:** Anyone who can reach a service that mounts `build_auth_router` can remove authentication from every route guarded by `require_session`. This is the documented usage (`packages/python-backend/README.md:123-133`), so exposure is likely in consumers. Consumer wiring was not reviewed.
|
||||||
- **Recommendation:** Require a user-manager session for `PUT /access`, and for `GET` unless the value is intentionally public. Add a `require_admin` dependency, mirroring the Go `RequireAdmin`. Change the test at `test_authproxy.py:116-122` to expect 401 without a session, and confirm no consumer exposes the router without this change.
|
- **Recommendation:** Require a user-manager session for `PUT /access`, and for `GET` unless the value is intentionally public. Add a `require_admin` dependency, mirroring the Go `RequireAdmin`. Change the test at `test_authproxy.py:116-122` to expect 401 without a session, and confirm no consumer exposes the router without this change.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `PUT /access` now depends on a new `require_admin` dependency that needs a session whose role can manage users (401 without a session or AuthGuard, 403 for other roles), so an anonymous caller can no longer clear the login flag. `GET /access` stays public for the login screen, and the internal route keeps its shared-secret check; the tests now assert 401 and 403 and that an admin session can still toggle. Files: `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`.
|
||||||
|
|
||||||
### S-002 · Malformed cookies crash the Node middleware and fail requests in Java · **High**
|
### S-002 · Malformed cookies crash the Node middleware and fail requests in Java · **High** · Fixed
|
||||||
- **Location:** `packages/node-backend/src/authclient.js:214` (`tokenFromRequest` runs before the `try` block), `packages/node-backend/src/authclient.js:239` (`decodeURIComponent` on the cookie value), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:718-721` (`URLDecoder.decode` with only an `UnsupportedEncodingException` catch), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:278` (`extractToken` called from `middleware`)
|
- **Location:** `packages/node-backend/src/authclient.js:214` (`tokenFromRequest` runs before the `try` block), `packages/node-backend/src/authclient.js:239` (`decodeURIComponent` on the cookie value), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:718-721` (`URLDecoder.decode` with only an `UnsupportedEncodingException` catch), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:278` (`extractToken` called from `middleware`)
|
||||||
- **Description:** In Node, the async middleware calls `tokenFromRequest` before its `try`. `decodeURIComponent` throws `URIError` on a malformed escape such as a bare `%`, so the middleware rejects. Express 4 does not catch async rejections, and Node's default unhandled-rejection mode terminates the process. In Java, `URLDecoder.decode` throws `IllegalArgumentException` on a malformed escape; the only catch is for a different exception type, so the request fails with an error rather than a 401. `URLDecoder` also turns `+` into a space, which alters valid tokens.
|
- **Description:** In Node, the async middleware calls `tokenFromRequest` before its `try`. `decodeURIComponent` throws `URIError` on a malformed escape such as a bare `%`, so the middleware rejects. Express 4 does not catch async rejections, and Node's default unhandled-rejection mode terminates the process. In Java, `URLDecoder.decode` throws `IllegalArgumentException` on a malformed escape; the only catch is for a different exception type, so the request fails with an error rather than a 401. `URLDecoder` also turns `+` into a space, which alters valid tokens.
|
||||||
- **Impact:** A single unauthenticated request with a crafted cookie can crash a Node service (the package requires Node 20 or newer, `packages/node-backend/package.json` `engines`). Java returns server errors instead of 401 and can mangle tokens containing `+`.
|
- **Impact:** A single unauthenticated request with a crafted cookie can crash a Node service (the package requires Node 20 or newer, `packages/node-backend/package.json` `engines`). Java returns server errors instead of 401 and can mangle tokens containing `+`.
|
||||||
- **Recommendation:** Move token extraction inside the `try` in Node, and make `tokenFromRequest` return `''` on decode errors. In Java, catch `IllegalArgumentException` and percent-decode without treating `+` as a space. Add tests for malformed cookies in both packages.
|
- **Recommendation:** Move token extraction inside the `try` in Node, and make `tokenFromRequest` return `''` on decode errors. In Java, catch `IllegalArgumentException` and percent-decode without treating `+` as a space. Add tests for malformed cookies in both packages.
|
||||||
|
- **Status:** Fixed 2026-10-19 — in Node, `middleware()` now calls `tokenFromRequest` inside its `try`, and a malformed cookie escape yields `''`, so the request gets a 401 instead of an unhandled rejection. In Java, `extractCookieToken` escapes a literal `+` before `URLDecoder` so it is kept, and a malformed escape returns `""` instead of throwing. Tests were added in both packages; the Java tests were not compiled or run because no JDK is installed here, so they were checked by reading only. Files: `packages/node-backend/src/authclient.js`, `packages/node-backend/test/authclient.test.js`, `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-003 · The websocket sync hub has no identity, and self-asserted client IDs gate remote control · **High**
|
### S-003 · The websocket sync hub has no identity, and self-asserted client IDs gate remote control · **High** · Open
|
||||||
- **Location:** `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts any connection), `backend/syncsocket/syncsocket.go:109` (client ID assigned from the message), `backend/syncsocket/syncsocket.go:366-369` (`control:claim` and `control:release` compare the requester against the same self-asserted ID), `backend/syncsocket/syncsocket.go:146-150` (every peer's ID and `remoteControlEnabled` is broadcast to all members)
|
- **Location:** `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts any connection), `backend/syncsocket/syncsocket.go:109` (client ID assigned from the message), `backend/syncsocket/syncsocket.go:366-369` (`control:claim` and `control:release` compare the requester against the same self-asserted ID), `backend/syncsocket/syncsocket.go:146-150` (every peer's ID and `remoteControlEnabled` is broadcast to all members)
|
||||||
- **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.
|
||||||
|
|
||||||
### S-004 · Anonymous `PUT /sync` writes unvalidated JSON into shared session state · **High**
|
### 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)
|
||||||
- **Description:** The route uses `Optional`, so anonymous callers reach `putSyncState`, which never checks who they are. Any caller can overwrite any session's playback state, including the shared `"default"` session. Values are stored without the type checks that the websocket path applies (`syncsocket.go:489-498`). This assumes `Optional` admits anonymous requests; `backend/auth` was not read in this pass (needs verification).
|
- **Description:** The route uses `Optional`, so anonymous callers reach `putSyncState`, which never checks who they are. Any caller can overwrite any session's playback state, including the shared `"default"` session. Values are stored without the type checks that the websocket path applies (`syncsocket.go:489-498`). This assumes `Optional` admits anonymous requests; `backend/auth` was not read in this pass (needs verification).
|
||||||
- **Impact:** Anonymous clients can overwrite shared playback state, and can pin substantial memory by filling many sessions with large bodies.
|
- **Impact:** Anonymous clients can overwrite shared playback state, and can pin substantial memory by filling many sessions with large bodies.
|
||||||
- **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`.
|
||||||
|
|
||||||
### 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**
|
||||||
- **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).
|
||||||
@@ -148,11 +153,12 @@ The most serious issue is a Python router route that lets an anonymous caller sw
|
|||||||
- **Impact:** Supply-chain exposure from tag changes, credential exposure to other processes on a shared runner, and a higher chance of future secret commits.
|
- **Impact:** Supply-chain exposure from tag changes, credential exposure to other processes on a shared runner, and a higher chance of future secret commits.
|
||||||
- **Recommendation:** Pin actions to commit SHAs. Pass registry credentials through a netrc or header file rather than argv. Add `.env*`, `*.pem`, `*.key` and `.npmrc` to `.gitignore`. Confirm that the historical credential is not live, and rotate it if it is.
|
- **Recommendation:** Pin actions to commit SHAs. Pass registry credentials through a netrc or header file rather than argv. Add `.env*`, `*.pem`, `*.key` and `.npmrc` to `.gitignore`. Confirm that the historical credential is not live, and rotate it if it is.
|
||||||
|
|
||||||
### S-022 · Media stream and thumbnail routes are unauthenticated, and upstream content types reach the app origin unchecked · **Low**
|
### S-022 · Media stream and thumbnail routes are unauthenticated, and upstream content types reach the app origin unchecked · **Low** · Open
|
||||||
- **Location:** `backend/mediacore/mediacore.go:95-97` (`/media/stream` and `/media/thumb` registered without an auth wrapper, unlike the other media routes), `backend/carriernodeclient/carriernodeclient.go:202-206` (upstream `Content-Type` and `Content-Disposition` copied, with no `X-Content-Type-Options` or CSP), `backend/mediacore/mediacore.go:957-960` (`ServeFile` maps extensions such as `.html` and `.svg` to active types)
|
- **Location:** `backend/mediacore/mediacore.go:95-97` (`/media/stream` and `/media/thumb` registered without an auth wrapper, unlike the other media routes), `backend/carriernodeclient/carriernodeclient.go:202-206` (upstream `Content-Type` and `Content-Disposition` copied, with no `X-Content-Type-Options` or CSP), `backend/mediacore/mediacore.go:957-960` (`ServeFile` maps extensions such as `.html` and `.svg` to active types)
|
||||||
- **Description:** Anyone who knows a media key can download the file, and the list endpoints return those keys. Proxied responses keep the upstream content type without `nosniff` or a restrictive CSP, so a file stored with an HTML or SVG type would render on the application origin. This module has no upload handler, so whether such files can exist depends on CarrierNode and its writers (needs verification).
|
- **Description:** Anyone who knows a media key can download the file, and the list endpoints return those keys. Proxied responses keep the upstream content type without `nosniff` or a restrictive CSP, so a file stored with an HTML or SVG type would render on the application origin. This module has no upload handler, so whether such files can exist depends on CarrierNode and its writers (needs verification).
|
||||||
- **Impact:** Public access to media if the library is meant to be private, and stored XSS if active content can be placed under a media path.
|
- **Impact:** Public access to media if the library is meant to be private, and stored XSS if active content can be placed under a media path.
|
||||||
- **Recommendation:** Add `Optional` or `Require` to these routes unless public access is intended, and document the choice. Set `X-Content-Type-Options: nosniff` and a restrictive CSP on proxied and served media, and force attachment or an allowlisted type for non-media extensions. Also check `backend/mediacore/mediacore.go:723`, which returns the full `*sharedauth.User` struct from the request context; whether that exposes secrets depends on its JSON tags in `backend/auth` (not reviewed).
|
- **Recommendation:** Add `Optional` or `Require` to these routes unless public access is intended, and document the choice. Set `X-Content-Type-Options: nosniff` and a restrictive CSP on proxied and served media, and force attachment or an allowlisted type for non-media extensions. Also check `backend/mediacore/mediacore.go:723`, which returns the full `*sharedauth.User` struct from the request context; whether that exposes secrets depends on its JSON tags in `backend/auth` (not reviewed).
|
||||||
|
- **Status:** Open 2026-10-19 — the access part is fixed: `/media/stream` (GET and HEAD) and `/media/thumb` now sit behind `RequireIfLoginRequired`, so anonymous requests get 401 while login is required and are served while it is off (applied from the vendored ContentScanner change). Hidden media (`active = FALSE`) returns 404 to non-moderators on the stream, thumb and original-image lookups, and a database error in that check counts as hidden (ported from the ModerationHub change); the caller rule has a unit test, the SQL filter does not, because the test suite has no database. Other media routes (state, tags, playlists) are not covered by this rule. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/mediacore_test.go`. Still open: the `X-Content-Type-Options: nosniff` and restrictive CSP on proxied and served media (`backend/carriernodeclient/carriernodeclient.go`), the active-type mapping in `ServeFile` (`backend/mediacore/mediacore.go`, `.html` and `.svg`), and the `*sharedauth.User` JSON-tag question. Those need a header and content-type change in CarrierNode and the media server, and a decision on whether active types are allowed under media paths.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- **Positive checks:** No live credentials were found in the current tracked files. The only credential-shaped matches are identifiers (fields named `password`, `secret` or `token`), environment-variable references in `.gitea/workflows/publish-python.yml`, and test fixtures: `packages/node-backend/test/auth.test.js:37` uses the public RFC 6238 test secret, and `packages/python-backend/tests/test_core.py:38` and `backend/coreconfig/coreconfig_test.go:38,132-133` use short placeholder values. In git history, about twenty commits matched credential-shaped patterns; all were code identifiers or test fixtures, except the example file described in S-021. Values were masked during the review and are not reproduced here.
|
- **Positive checks:** No live credentials were found in the current tracked files. The only credential-shaped matches are identifiers (fields named `password`, `secret` or `token`), environment-variable references in `.gitea/workflows/publish-python.yml`, and test fixtures: `packages/node-backend/test/auth.test.js:37` uses the public RFC 6238 test secret, and `packages/python-backend/tests/test_core.py:38` and `backend/coreconfig/coreconfig_test.go:38,132-133` use short placeholder values. In git history, about twenty commits matched credential-shaped patterns; all were code identifiers or test fixtures, except the example file described in S-021. Values were masked during the review and are not reproduced here.
|
||||||
|
|||||||
@@ -85,16 +85,16 @@ func (c *Core) Mount(r chi.Router) {
|
|||||||
r.With(c.auth.Require).Post("/security/totp/verify", c.auth.TOTPVerify)
|
r.With(c.auth.Require).Post("/security/totp/verify", c.auth.TOTPVerify)
|
||||||
r.With(c.auth.Require).Post("/security/totp/disable", c.auth.TOTPDisable)
|
r.With(c.auth.Require).Post("/security/totp/disable", c.auth.TOTPDisable)
|
||||||
r.With(c.auth.Optional).Get("/sync", c.getSyncState)
|
r.With(c.auth.Optional).Get("/sync", c.getSyncState)
|
||||||
r.With(c.auth.Optional).Put("/sync", c.putSyncState)
|
r.With(c.auth.Require).Put("/sync", c.putSyncState)
|
||||||
r.With(c.auth.Optional).Get("/media/state", c.mediaState)
|
r.With(c.auth.Optional).Get("/media/state", c.mediaState)
|
||||||
r.With(c.auth.Require).Post("/media/like", c.mediaLike)
|
r.With(c.auth.Require).Post("/media/like", c.mediaLike)
|
||||||
r.With(c.auth.Require).Post("/media/save", c.mediaSave)
|
r.With(c.auth.Require).Post("/media/save", c.mediaSave)
|
||||||
r.With(c.auth.Optional).Post("/media/view", c.mediaView)
|
r.With(c.auth.Optional).Post("/media/view", c.mediaView)
|
||||||
r.With(c.auth.Optional).Post("/media/view-session", c.mediaViewSession)
|
r.With(c.auth.Optional).Post("/media/view-session", c.mediaViewSession)
|
||||||
r.With(c.auth.Require).Get("/media/liked", c.mediaLiked)
|
r.With(c.auth.Require).Get("/media/liked", c.mediaLiked)
|
||||||
r.Get("/media/stream", c.streamMediaByQuery)
|
r.With(c.auth.RequireIfLoginRequired).Get("/media/stream", c.streamMediaByQuery)
|
||||||
r.Head("/media/stream", c.streamMediaByQuery)
|
r.With(c.auth.RequireIfLoginRequired).Head("/media/stream", c.streamMediaByQuery)
|
||||||
r.Get("/media/thumb", c.thumbnailMediaByQuery)
|
r.With(c.auth.RequireIfLoginRequired).Get("/media/thumb", c.thumbnailMediaByQuery)
|
||||||
|
|
||||||
r.With(c.auth.Optional).Get("/media/{id}/tags", c.mediaTags)
|
r.With(c.auth.Optional).Get("/media/{id}/tags", c.mediaTags)
|
||||||
r.With(c.auth.Require).Post("/media/{id}/tags", c.addMediaTag)
|
r.With(c.auth.Require).Post("/media/{id}/tags", c.addMediaTag)
|
||||||
@@ -132,10 +132,15 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusBadRequest, "clientId is required")
|
writeError(w, http.StatusBadRequest, "clientId is required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
mediaID, ok := syncScalar(input["mediaId"])
|
||||||
|
if !ok {
|
||||||
|
writeError(w, http.StatusBadRequest, "mediaId must be a string, a number or null")
|
||||||
|
return
|
||||||
|
}
|
||||||
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
|
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
|
||||||
state := map[string]any{
|
state := map[string]any{
|
||||||
"sessionId": sessionID,
|
"sessionId": sessionID,
|
||||||
"mediaId": input["mediaId"],
|
"mediaId": mediaID,
|
||||||
"timeMs": syncInt(input, "timeMs", 0),
|
"timeMs": syncInt(input, "timeMs", 0),
|
||||||
"paused": syncBool(input, "paused"),
|
"paused": syncBool(input, "paused"),
|
||||||
"fps": syncFPS(input),
|
"fps": syncFPS(input),
|
||||||
@@ -144,7 +149,12 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
|
|||||||
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
|
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
|
||||||
}
|
}
|
||||||
if value, ok := input["playAt"]; ok {
|
if value, ok := input["playAt"]; ok {
|
||||||
state["playAt"] = value
|
playAt, valid := syncScalar(value)
|
||||||
|
if !valid {
|
||||||
|
writeError(w, http.StatusBadRequest, "playAt must be a string, a number or null")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state["playAt"] = playAt
|
||||||
}
|
}
|
||||||
c.sync.SetHTTPState(sessionID, state)
|
c.sync.SetHTTPState(sessionID, state)
|
||||||
c.sync.Broadcast(sessionID)
|
c.sync.Broadcast(sessionID)
|
||||||
@@ -179,7 +189,7 @@ func (c *Core) streamMediaByQuery(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) {
|
func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) {
|
||||||
record, err := c.findMedia(r.Context(), identifier)
|
record, err := c.findMedia(r.Context(), identifier, canSeeHidden(r))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusNotFound, "media not found")
|
writeError(w, http.StatusNotFound, "media not found")
|
||||||
return
|
return
|
||||||
@@ -197,6 +207,11 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
|
|||||||
writeError(w, http.StatusBadRequest, "invalid media id")
|
writeError(w, http.StatusBadRequest, "invalid media id")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
includeHidden := canSeeHidden(r)
|
||||||
|
if !includeHidden && c.isHiddenMedia(r.Context(), id) {
|
||||||
|
writeError(w, http.StatusNotFound, "thumbnail not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
|
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
|
||||||
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, id) {
|
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, id) {
|
||||||
return
|
return
|
||||||
@@ -216,7 +231,7 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
record, err := c.findMedia(r.Context(), id)
|
record, err := c.findMedia(r.Context(), id, includeHidden)
|
||||||
if err != nil || !isImagePath(record.FilePath) {
|
if err != nil || !isImagePath(record.FilePath) {
|
||||||
writeError(w, http.StatusNotFound, "thumbnail not found")
|
writeError(w, http.StatusNotFound, "thumbnail not found")
|
||||||
return
|
return
|
||||||
@@ -723,7 +738,25 @@ func (c *Core) profile(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, map[string]any{"user": user})
|
writeJSON(w, http.StatusOK, map[string]any{"user": user})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, error) {
|
// canSeeHidden reports whether the caller is a moderator, who may stream and view media that has
|
||||||
|
// been hidden (active = FALSE). Everyone else gets hidden media as not found.
|
||||||
|
func canSeeHidden(r *http.Request) bool {
|
||||||
|
return sharedauth.IsAdmin(sharedauth.UserFromContext(r.Context()))
|
||||||
|
}
|
||||||
|
|
||||||
|
// isHiddenMedia reports whether identifier names a media item that has been hidden. A lookup
|
||||||
|
// error counts as hidden, so a database fault never exposes hidden media.
|
||||||
|
func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
|
||||||
|
var hidden bool
|
||||||
|
err := c.db.QueryRow(ctx, `
|
||||||
|
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR CAST(id AS TEXT)=$1))`,
|
||||||
|
strings.TrimSpace(identifier)).Scan(&hidden)
|
||||||
|
return err != nil || hidden
|
||||||
|
}
|
||||||
|
|
||||||
|
// findMedia looks up one media item by media key or numeric id. Hidden media is only returned
|
||||||
|
// when includeHidden is set.
|
||||||
|
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
|
||||||
identifier = strings.TrimSpace(identifier)
|
identifier = strings.TrimSpace(identifier)
|
||||||
var record MediaRecord
|
var record MediaRecord
|
||||||
row := c.db.QueryRow(ctx, `
|
row := c.db.QueryRow(ctx, `
|
||||||
@@ -732,7 +765,7 @@ func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, e
|
|||||||
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 LIMIT 1`, identifier)
|
FROM media WHERE (media_key=$1 OR CAST(id AS TEXT)=$1) AND (active OR $2) LIMIT 1`, 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
|
||||||
@@ -1084,6 +1117,20 @@ func syncBool(message map[string]any, key string) bool {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// syncScalar keeps a client-supplied sync value to what sync state holds: null, a number or a
|
||||||
|
// bounded string. Objects, arrays and booleans are refused so arbitrary JSON is never stored as
|
||||||
|
// shared session state.
|
||||||
|
func syncScalar(value any) (any, bool) {
|
||||||
|
switch typed := value.(type) {
|
||||||
|
case nil, float64:
|
||||||
|
return typed, true
|
||||||
|
case string:
|
||||||
|
return boundedSyncString(typed), true
|
||||||
|
default:
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func syncInt(message map[string]any, key string, fallback int64) int64 {
|
func syncInt(message map[string]any, key string, fallback int64) int64 {
|
||||||
value, ok := message[key].(float64)
|
value, ok := message[key].(float64)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package mediacore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||||
|
)
|
||||||
|
|
||||||
|
// loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be
|
||||||
|
// exercised without a database.
|
||||||
|
type loginRequiredStore struct{}
|
||||||
|
|
||||||
|
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
|
||||||
|
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
|
||||||
|
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
|
||||||
|
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
|
||||||
|
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
|
||||||
|
|
||||||
|
// loginOffStore is loginRequiredStore with login switched off for the whole application.
|
||||||
|
type loginOffStore struct{ loginRequiredStore }
|
||||||
|
|
||||||
|
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
|
||||||
|
|
||||||
|
// TestMediaStreamAndThumbnailRequireLogin checks that anonymous requests to the media stream and
|
||||||
|
// thumbnail routes are refused when login is required, before any database lookup or CarrierNode
|
||||||
|
// call. The Core in this test has no database and no CarrierNode client, so reaching either would
|
||||||
|
// panic.
|
||||||
|
func TestMediaStreamAndThumbnailRequireLogin(t *testing.T) {
|
||||||
|
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
|
||||||
|
router := chi.NewRouter()
|
||||||
|
New(Config{Auth: auth}).Mount(router)
|
||||||
|
|
||||||
|
for _, request := range []struct{ method, target string }{
|
||||||
|
{http.MethodGet, "/media/stream?mediaKey=1"},
|
||||||
|
{http.MethodHead, "/media/stream?mediaKey=1"},
|
||||||
|
{http.MethodGet, "/media/thumb?mediaKey=1"},
|
||||||
|
} {
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(response, httptest.NewRequest(request.method, request.target, nil))
|
||||||
|
if response.Code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("%s %s status = %d, want %d", request.method, request.target, response.Code, http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMediaGateAllowsAnonymousWhenLoginIsOff checks the gate the media stream and thumbnail routes
|
||||||
|
// use: with login disabled an anonymous request reaches the handler, as it does for the rest of
|
||||||
|
// the application. The handler here is a stub, so no database or CarrierNode call is made.
|
||||||
|
func TestMediaGateAllowsAnonymousWhenLoginIsOff(t *testing.T) {
|
||||||
|
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject")
|
||||||
|
reached := false
|
||||||
|
gate := auth.RequireIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
reached = true
|
||||||
|
}))
|
||||||
|
for _, target := range []string{"/media/stream?mediaKey=1", "/media/thumb?mediaKey=1"} {
|
||||||
|
reached = false
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
gate.ServeHTTP(response, httptest.NewRequest(http.MethodGet, target, nil))
|
||||||
|
if !reached || response.Code != http.StatusOK {
|
||||||
|
t.Errorf("GET %s with login off: reached = %v, status = %d; want reached and 200", target, reached, response.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newRoleAuthGuard stands in for AuthGuard's GET /api/me. Each bearer token maps to one role, so a
|
||||||
|
// test can act as a viewer, a moderator or an admin without a database.
|
||||||
|
func newRoleAuthGuard(t *testing.T) *httptest.Server {
|
||||||
|
t.Helper()
|
||||||
|
roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
role, ok := roles[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":1,"username":"tester","role":%q}}`, role)
|
||||||
|
}))
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
return server
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOnlyModeratorsCanSeeHiddenMedia checks which callers get hidden media looked up at all.
|
||||||
|
// Anonymous callers and viewers may not; moderators and admins may. With login off every caller
|
||||||
|
// is the placeholder superadmin, as for the rest of the application. The active = FALSE filter
|
||||||
|
// itself needs a database and is not exercised here.
|
||||||
|
func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) {
|
||||||
|
guard := newRoleAuthGuard(t)
|
||||||
|
login := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
|
||||||
|
loginOff := sharedauth.NewWithStore(loginOffStore{}, "session", false, guard.URL, "testproject")
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
auth *sharedauth.Service
|
||||||
|
token string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"anonymous with login required", login, "", "false"},
|
||||||
|
{"viewer", login, "viewer-token", "false"},
|
||||||
|
{"moderator", login, "moderator-token", "true"},
|
||||||
|
{"admin", login, "admin-token", "true"},
|
||||||
|
{"anonymous with login off", loginOff, "", "true"},
|
||||||
|
} {
|
||||||
|
router := chi.NewRouter()
|
||||||
|
router.With(tc.auth.Optional).Get("/probe", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, canSeeHidden(r))
|
||||||
|
})
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||||
|
if tc.token != "" {
|
||||||
|
request.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: tc.token})
|
||||||
|
}
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(response, request)
|
||||||
|
if got := response.Body.String(); got != tc.want {
|
||||||
|
t.Errorf("%s: canSeeHidden = %q, want %q", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSyncWriteRequiresLogin checks that an anonymous PUT /sync is refused before it can change
|
||||||
|
// shared playback state. The Core has no sync hub, so reaching the handler would panic.
|
||||||
|
func TestSyncWriteRequiresLogin(t *testing.T) {
|
||||||
|
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
|
||||||
|
router := chi.NewRouter()
|
||||||
|
New(Config{Auth: auth}).Mount(router)
|
||||||
|
|
||||||
|
request := httptest.NewRequest(http.MethodPut, "/sync", strings.NewReader(`{"clientId":"c1","mediaId":"m1"}`))
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(response, request)
|
||||||
|
if response.Code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("PUT /sync status = %d, want %d", response.Code, http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSyncScalarKeepsOnlyScalars checks that sync values are limited to null, numbers and
|
||||||
|
// bounded strings, so objects, arrays and booleans are never stored as session state.
|
||||||
|
func TestSyncScalarKeepsOnlyScalars(t *testing.T) {
|
||||||
|
if value, ok := syncScalar(nil); !ok || value != nil {
|
||||||
|
t.Errorf("syncScalar(nil) = %v, %v; want nil, true", value, ok)
|
||||||
|
}
|
||||||
|
if value, ok := syncScalar(float64(7)); !ok || value != float64(7) {
|
||||||
|
t.Errorf("syncScalar(7) = %v, %v; want 7, true", value, ok)
|
||||||
|
}
|
||||||
|
if value, ok := syncScalar(" media-1 "); !ok || value != "media-1" {
|
||||||
|
t.Errorf("syncScalar(string) = %v, %v; want media-1, true", value, ok)
|
||||||
|
}
|
||||||
|
long, ok := syncScalar(strings.Repeat("x", 500))
|
||||||
|
if text, isText := long.(string); !ok || !isText || len(text) != 128 {
|
||||||
|
t.Errorf("syncScalar(long string) = %v, %v; want a 128-byte string, true", long, ok)
|
||||||
|
}
|
||||||
|
for _, refused := range []any{map[string]any{"a": 1}, []any{1}, true} {
|
||||||
|
if _, ok := syncScalar(refused); ok {
|
||||||
|
t.Errorf("syncScalar(%#v) accepted a non-scalar value", refused)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -33,6 +33,7 @@ import (
|
|||||||
const (
|
const (
|
||||||
maxSyncIdentifier = 128
|
maxSyncIdentifier = 128
|
||||||
maxSyncSessions = 1000
|
maxSyncSessions = 1000
|
||||||
|
maxSyncConnections = 1000
|
||||||
)
|
)
|
||||||
|
|
||||||
type peer struct {
|
type peer struct {
|
||||||
@@ -73,10 +74,15 @@ func NewHub() *Hub {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hub) add(p *peer) {
|
// add registers a peer, or reports false when the hub already holds maxSyncConnections peers.
|
||||||
|
func (h *Hub) add(p *peer) bool {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
if len(h.peers) >= maxSyncConnections {
|
||||||
|
return false
|
||||||
|
}
|
||||||
h.peers[p] = struct{}{}
|
h.peers[p] = struct{}{}
|
||||||
h.mu.Unlock()
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hub) remove(p *peer) string {
|
func (h *Hub) remove(p *peer) string {
|
||||||
@@ -300,7 +306,10 @@ func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrig
|
|||||||
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
|
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
|
||||||
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
|
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
|
||||||
}
|
}
|
||||||
h.add(p)
|
if !h.add(p) {
|
||||||
|
_ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections")
|
||||||
|
return
|
||||||
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
sessionID := h.remove(p)
|
sessionID := h.remove(p)
|
||||||
_ = conn.Close(websocket.StatusNormalClosure, "")
|
_ = conn.Close(websocket.StatusNormalClosure, "")
|
||||||
@@ -453,6 +462,9 @@ func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
|
|||||||
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
|
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
|
||||||
h.capturedAtMs[sessionID] = captured
|
h.capturedAtMs[sessionID] = captured
|
||||||
}
|
}
|
||||||
|
trimSessionMap(h.playAt)
|
||||||
|
trimSessionMap(h.playAtLocalMs)
|
||||||
|
trimSessionMap(h.capturedAtMs)
|
||||||
if toClientID == "" {
|
if toClientID == "" {
|
||||||
h.states[sessionID] = cloneMap(state)
|
h.states[sessionID] = cloneMap(state)
|
||||||
if len(h.states) > maxSyncSessions {
|
if len(h.states) > maxSyncSessions {
|
||||||
@@ -571,6 +583,18 @@ func cloneMap(value map[string]any) map[string]any {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// trimSessionMap keeps a per-session map within maxSyncSessions by dropping entries, the same
|
||||||
|
// bound the states map uses. Session IDs come from clients, so without it each map would grow
|
||||||
|
// for every ID ever seen.
|
||||||
|
func trimSessionMap[V any](values map[string]V) {
|
||||||
|
for len(values) > maxSyncSessions {
|
||||||
|
for key := range values {
|
||||||
|
delete(values, key)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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) != "" {
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package syncsocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the
|
||||||
|
// per-session timing maps past maxSyncSessions.
|
||||||
|
func TestSessionTimingMapsStayBounded(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
p := &peer{clientID: "client-1"}
|
||||||
|
for i := 0; i < maxSyncSessions+100; i++ {
|
||||||
|
hub.handleSyncUpdate(p, map[string]any{
|
||||||
|
"clientId": "client-1",
|
||||||
|
"sessionId": fmt.Sprintf("session-%d", i),
|
||||||
|
"paused": false,
|
||||||
|
"playAt": "2026-10-19T10:00:00Z",
|
||||||
|
"playAtLocalMs": float64(1),
|
||||||
|
"capturedAtLocalMs": float64(1),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if n := len(hub.playAt); n > maxSyncSessions {
|
||||||
|
t.Errorf("playAt holds %d sessions, want at most %d", n, maxSyncSessions)
|
||||||
|
}
|
||||||
|
if n := len(hub.playAtLocalMs); n > maxSyncSessions {
|
||||||
|
t.Errorf("playAtLocalMs holds %d sessions, want at most %d", n, maxSyncSessions)
|
||||||
|
}
|
||||||
|
if n := len(hub.capturedAtMs); n > maxSyncSessions {
|
||||||
|
t.Errorf("capturedAtMs holds %d sessions, want at most %d", n, maxSyncSessions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestHubRefusesPeersBeyondTheConnectionCap checks that the hub stops registering connections
|
||||||
|
// once it holds maxSyncConnections peers.
|
||||||
|
func TestHubRefusesPeersBeyondTheConnectionCap(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
for i := 0; i < maxSyncConnections; i++ {
|
||||||
|
if !hub.add(&peer{}) {
|
||||||
|
t.Fatalf("add refused peer %d, below the cap", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if hub.add(&peer{}) {
|
||||||
|
t.Fatal("add accepted a peer beyond maxSyncConnections")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -715,9 +715,13 @@ public final class AuthClient {
|
|||||||
if (candidate.startsWith(prefix)) {
|
if (candidate.startsWith(prefix)) {
|
||||||
String value = candidate.substring(prefix.length());
|
String value = candidate.substring(prefix.length());
|
||||||
try {
|
try {
|
||||||
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
|
// URLDecoder would turn a literal "+" into a space; escape it first so it survives, as in Node.
|
||||||
|
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8.name());
|
||||||
} catch (UnsupportedEncodingException ex) {
|
} catch (UnsupportedEncodingException ex) {
|
||||||
return value;
|
return value;
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
|
||||||
|
return "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -218,6 +218,34 @@ class AuthClientTest {
|
|||||||
assertEquals("right", token);
|
assertEquals("right", token);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void extractTokenKeepsALiteralPlusSignInTheCookieValue() {
|
||||||
|
AuthClient client = new AuthClient("https://auth.example.com");
|
||||||
|
|
||||||
|
String token = client.extractToken(name -> null, "auth_session=ab+cd%2Bef");
|
||||||
|
|
||||||
|
assertEquals("ab+cd+ef", token);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void extractTokenTreatsAMalformedCookieEscapeAsNoToken() {
|
||||||
|
AuthClient client = new AuthClient("https://auth.example.com");
|
||||||
|
|
||||||
|
String token = client.extractToken(name -> null, "auth_session=bad%zz; other=1");
|
||||||
|
|
||||||
|
assertEquals("", token);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void middlewareFailsClosedOnAMalformedCookieInsteadOfThrowing() throws Exception {
|
||||||
|
AuthClient client = new AuthClient("https://auth.example.com");
|
||||||
|
|
||||||
|
String result = client.middleware(name -> null, "auth_session=100%",
|
||||||
|
user -> "authenticated", () -> "unauthorized");
|
||||||
|
|
||||||
|
assertEquals("unauthorized", result);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void middlewareFailsClosedAndDoesNotInvokeTheHandlerOnAnInvalidSession() throws Exception {
|
void middlewareFailsClosedAndDoesNotInvokeTheHandlerOnAnInvalidSession() throws Exception {
|
||||||
server = fakeAuthGuard(401, "{\"valid\":false}");
|
server = fakeAuthGuard(401, "{\"valid\":false}");
|
||||||
|
|||||||
@@ -211,9 +211,8 @@ export class AuthClient {
|
|||||||
*/
|
*/
|
||||||
middleware() {
|
middleware() {
|
||||||
return async (req, res, next) => {
|
return async (req, res, next) => {
|
||||||
const token = this.tokenFromRequest(req);
|
|
||||||
try {
|
try {
|
||||||
req.authUser = await this.validate(token);
|
req.authUser = await this.validate(this.tokenFromRequest(req));
|
||||||
next();
|
next();
|
||||||
} catch {
|
} catch {
|
||||||
// Fail closed on both an invalid session and a transport/decoding
|
// Fail closed on both an invalid session and a transport/decoding
|
||||||
@@ -236,7 +235,14 @@ export class AuthClient {
|
|||||||
.split(';')
|
.split(';')
|
||||||
.map(part => part.trim())
|
.map(part => part.trim())
|
||||||
.find(part => part.startsWith(`${this.cookieName}=`));
|
.find(part => part.startsWith(`${this.cookieName}=`));
|
||||||
if (match) return decodeURIComponent(match.slice(this.cookieName.length + 1));
|
if (match) {
|
||||||
|
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(match.slice(this.cookieName.length + 1));
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -125,6 +125,29 @@ test('tokenFromRequest falls back to the auth_session cookie', () => {
|
|||||||
assert.equal(client.tokenFromRequest(req), 'cookie-token');
|
assert.equal(client.tokenFromRequest(req), 'cookie-token');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('tokenFromRequest treats a malformed cookie escape as no token', () => {
|
||||||
|
const client = new AuthClient('https://auth.example.com');
|
||||||
|
const req = { headers: { cookie: 'auth_session=bad%zz; other=1' } };
|
||||||
|
assert.equal(client.tokenFromRequest(req), '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('middleware answers 401 instead of rejecting on a malformed cookie', async () => {
|
||||||
|
const client = new AuthClient('https://auth.example.com', {
|
||||||
|
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
|
||||||
|
});
|
||||||
|
let statusCode = null;
|
||||||
|
const res = {
|
||||||
|
status(code) {
|
||||||
|
statusCode = code;
|
||||||
|
return { json: () => {} };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await client.middleware()({ headers: { cookie: 'auth_session=100%' } }, res, () => {
|
||||||
|
throw new Error('next should not be called');
|
||||||
|
});
|
||||||
|
assert.equal(statusCode, 401);
|
||||||
|
});
|
||||||
|
|
||||||
test('middleware attaches authUser on success and 401s on failure', async () => {
|
test('middleware attaches authUser on success and 401s on failure', async () => {
|
||||||
const okClient = new AuthClient('https://auth.example.com', {
|
const okClient = new AuthClient('https://auth.example.com', {
|
||||||
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]),
|
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]),
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
|
|||||||
# rather than a generic "internal error" indistinguishable from any other bug.
|
# rather than a generic "internal error" indistinguishable from any other bug.
|
||||||
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
|
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
|
||||||
ERR_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."
|
||||||
|
|
||||||
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
|
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
|
||||||
# authentication is disabled, either because AUTHGUARD_URL is disabled or
|
# authentication is disabled, either because AUTHGUARD_URL is disabled or
|
||||||
@@ -338,6 +339,23 @@ def build_auth_router(
|
|||||||
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
|
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
|
||||||
return token
|
return token
|
||||||
|
|
||||||
|
async def require_admin(
|
||||||
|
request: Request,
|
||||||
|
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
|
||||||
|
) -> PublicUser:
|
||||||
|
"""FastAPI dependency gating a route behind an administrator session
|
||||||
|
(the Python counterpart of Go's RequireAdmin). Unlike require_session it
|
||||||
|
never falls back to _LOCAL_PROFILE, so a route that changes the
|
||||||
|
login-required flag cannot be called anonymously, even while login is
|
||||||
|
already disabled."""
|
||||||
|
if not _enabled(client):
|
||||||
|
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
|
||||||
|
assert client is not None
|
||||||
|
profile, _ = await _current_profile_or_401(request, client)
|
||||||
|
if not can_manage_users(profile.role):
|
||||||
|
raise HTTPException(status_code=403, detail=ERR_ADMIN_REQUIRED)
|
||||||
|
return profile
|
||||||
|
|
||||||
# --- status / me -------------------------------------------------------
|
# --- status / me -------------------------------------------------------
|
||||||
|
|
||||||
@router.get("/me")
|
@router.get("/me")
|
||||||
@@ -561,6 +579,7 @@ def build_auth_router(
|
|||||||
async def update_access_settings(
|
async def update_access_settings(
|
||||||
req: UpdateAccessRequest,
|
req: UpdateAccessRequest,
|
||||||
store: ProxyStore = Depends(get_store), # noqa: B008
|
store: ProxyStore = Depends(get_store), # noqa: B008
|
||||||
|
_admin: PublicUser = Depends(require_admin), # noqa: B008
|
||||||
) -> dict[str, bool]:
|
) -> dict[str, bool]:
|
||||||
nonlocal login_required_override
|
nonlocal login_required_override
|
||||||
await store.set_login_required(req.loginRequired)
|
await store.set_login_required(req.loginRequired)
|
||||||
|
|||||||
@@ -4,7 +4,13 @@ from fastapi import FastAPI, Request
|
|||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
from shared_backend import authproxy as ap
|
from shared_backend import authproxy as ap
|
||||||
from shared_backend.authclient import APIError, AuthClient, PublicUser, SessionResult
|
from shared_backend.authclient import (
|
||||||
|
DEFAULT_COOKIE_NAME,
|
||||||
|
APIError,
|
||||||
|
AuthClient,
|
||||||
|
PublicUser,
|
||||||
|
SessionResult,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class _FakeStore(ap.ProxyStore):
|
class _FakeStore(ap.ProxyStore):
|
||||||
@@ -113,14 +119,32 @@ class AuthDisabledModeTests(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
class AccessSettingsTests(unittest.TestCase):
|
class AccessSettingsTests(unittest.TestCase):
|
||||||
def test_get_and_put_round_trip_through_the_store(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)
|
||||||
client = TestClient(_build_app(store))
|
client = TestClient(_build_app(store, _RoleClient()))
|
||||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||||
|
|
||||||
|
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||||
|
self.assertEqual(response.status_code, 401)
|
||||||
|
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||||
|
|
||||||
|
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
|
||||||
|
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||||
|
self.assertEqual(response.status_code, 403)
|
||||||
|
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||||
|
|
||||||
|
client.cookies.set(DEFAULT_COOKIE_NAME, "admin-token")
|
||||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||||
self.assertEqual(response.json(), {"loginRequired": False})
|
self.assertEqual(response.json(), {"loginRequired": False})
|
||||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False})
|
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False})
|
||||||
|
|
||||||
|
def test_anonymous_put_is_refused_when_authguard_is_not_configured(self) -> None:
|
||||||
|
store = _FakeStore(login_required=True)
|
||||||
|
client = TestClient(_build_app(store))
|
||||||
|
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||||
|
self.assertEqual(response.status_code, 401)
|
||||||
|
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||||
|
|
||||||
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
||||||
store = _FakeStore(login_required=True)
|
store = _FakeStore(login_required=True)
|
||||||
client = TestClient(
|
client = TestClient(
|
||||||
@@ -180,6 +204,16 @@ class _FakeClient(AuthClient):
|
|||||||
return ["auth_session=; Path=/; Max-Age=0"]
|
return ["auth_session=; Path=/; Max-Age=0"]
|
||||||
|
|
||||||
|
|
||||||
|
class _RoleClient(_FakeClient):
|
||||||
|
"""Resolves two fixed session tokens to an administrator and an ordinary user."""
|
||||||
|
|
||||||
|
async def me(self, token: str) -> PublicUser:
|
||||||
|
roles = {"admin-token": "superadmin", "user-token": "user"}
|
||||||
|
if token not in roles:
|
||||||
|
raise APIError(401, "unauthenticated")
|
||||||
|
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
|
||||||
|
|
||||||
|
|
||||||
class EnabledModeSetupAndLoginTests(unittest.TestCase):
|
class EnabledModeSetupAndLoginTests(unittest.TestCase):
|
||||||
"""Exercises the real (client is not None) path, including the
|
"""Exercises the real (client is not None) path, including the
|
||||||
setup-claim flag's interaction with the store."""
|
setup-claim flag's interaction with the store."""
|
||||||
|
|||||||
Reference in new issue
Block a user