From f7819904b9aa51b3c30cebbedaf43b1bb2a3dfd1 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Tue, 20 Oct 2026 15:26:58 +0000 Subject: [PATCH] docs: record auth hash alignment and validation results --- PERFORMANCE_REPORT.md | 8 +- QUALITY_REPORT.md | 12 +- README.md | 8 +- SECURITY_REPORT.md | 18 +- backend/auth/contract_test.go | 49 +++- backend/auth/password.go | 78 +++++- backend/auth/proxy.go | 75 ++++- backend/auth/proxy_handlers_test.go | 43 ++- backend/auth/store.go | 64 ++++- backend/auth/store_integration_test.go | 4 +- backend/auth/totp.go | 17 +- backend/auth/totp_test.go | 5 +- backend/authclient/client.go | 20 ++ backend/authclient/validation_cache.go | 54 ++++ .../carriernodeclient/carriernodeclient.go | 122 +++++++- .../carriernodeclient_test.go | 264 +----------------- backend/carriernodeclient/thumbnails_test.go | 37 ++- backend/coreconfig/contract_test.go | 52 ++++ backend/coreconfig/coreconfig.go | 33 ++- backend/coreconfig/coreconfig_test.go | 28 +- backend/mediacore/mediacore.go | 97 +++++-- backend/mediacore/mediacore_test.go | 17 ++ backend/mediacore/migrate.go | 2 +- contract/auth-contract.json | 129 ++++++++- package-lock.json | 10 + .../com/gabriel20xx/shared/auth/Totp.java | 21 +- .../com/gabriel20xx/shared/auth/TotpTest.java | 1 + packages/node-backend/package.json | 1 + packages/node-backend/src/auth.js | 172 ++++++++---- packages/node-backend/src/coreconfig.js | 30 +- packages/node-backend/src/index.js | 4 + packages/node-backend/src/totp.js | 17 +- packages/node-backend/test/auth.test.js | 37 ++- packages/node-backend/test/authstore.test.js | 36 ++- packages/node-backend/test/contract.test.js | 34 ++- packages/node-backend/test/coreconfig.test.js | 32 ++- packages/python-backend/README.md | 5 + .../src/shared_backend/__init__.py | 7 +- .../python-backend/src/shared_backend/auth.py | 134 +++++++-- .../src/shared_backend/authclient.py | 67 ++++- .../src/shared_backend/authproxy.py | 74 ++++- .../src/shared_backend/coreconfig.py | 24 +- .../python-backend/src/shared_backend/totp.py | 17 +- .../python-backend/tests/test_authproxy.py | 112 +++++++- .../python-backend/tests/test_contract.py | 35 ++- packages/python-backend/tests/test_core.py | 17 +- .../python-backend/tests/test_coreconfig.py | 34 ++- packages/python-backend/tests/test_store.py | 51 +++- .../src/lib/components/ProfileDialog.svelte | 56 +++- packages/web-ui/src/lib/types.ts | 2 + packages/web-ui/tests/ProfileDialog.test.ts | 68 +++++ 51 files changed, 1792 insertions(+), 542 deletions(-) create mode 100644 backend/coreconfig/contract_test.go create mode 100644 packages/web-ui/tests/ProfileDialog.test.ts diff --git a/PERFORMANCE_REPORT.md b/PERFORMANCE_REPORT.md index f2f20d5..3973c54 100644 --- a/PERFORMANCE_REPORT.md +++ b/PERFORMANCE_REPORT.md @@ -3,11 +3,11 @@ - **Project:** shared - **Path:** /workspace/Personal/Web/shared - **Analyzed:** 2026-10-16 -- **Commit:** 5216031 on main -- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. Findings reflect the working tree. +- **Commit:** 22887fe on main +- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed. - **Stack:** Go 1.25 (`backend/`, module `repos.gfranz.ch/Gabriel20xx/shared/backend`, pgx, chi, coder/websocket, goose); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; PowerShell and Node scripts; Gitea and GitHub Actions. No Dockerfile, compose file or `.dockerignore` exists in the repo. - **Scope:** This is a shared library consumed by other projects (vendored snapshot), not an application. Read: all first-party Go packages except `backend/auth/*` and `backend/config` (reviewed in a separate pass), the Node, Python and Java AuthGuard clients and stores, the web-ui components that perform I/O or timers, root manifests, `.github` and `.gitea` workflows, and `scripts/`. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies (used only for coverage notes). Paths below are relative to the repo root. Backend findings come from read-only static review passes; the highest-severity citations were re-checked in the code. Nothing was built, run or profiled. -- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). Second Medium pass: P-002 fixed. +- **Updated:** 2026-10-20 — the two-second session-validation cache remains enabled by owner decision; code comments and README now state its revocation window and same-client logout behavior. ## Summary @@ -92,5 +92,5 @@ The auth code has no obvious SQL N+1 outside the playlist reorder path, and most - **Docker:** No Dockerfile, compose file or `.dockerignore` exists in this repository, so image size, multi-stage builds and base-image checks do not apply here. Consumer projects that build images from the vendored snapshot should be reviewed separately. - **Frontend checks:** No whole-library imports were found; `@lucide/svelte` is imported by name in every component. No `{@html}`, unbounded caches or leaked intervals were found in the web-ui, and the timers and listeners in `MediaPlayer`, `MediaPlayerControls`, `StatusWidget`, `AppShell` and `notifications.svelte.ts` are cleaned up. `shared-styles.css` (1134 lines, about 21 KB) is loaded in full by consumers. As a component library it has no route-level code-splitting, which is expected rather than a defect. Four of seven `{#each}` blocks in the components are keyed; the remaining ones are listed under quality findings. - **HTTP caching and compression:** Not applicable to the library code; the backends are API services and the static styles are shipped to consumers' own build pipelines. -- **Not verified:** No query plans (no database access), no benchmarks or profiling, no build or test runs. Counts and ordering are based on code reading only. +- **Not verified:** No query plans (no database access), benchmarks or profiling. Node, Python, web-ui and Go checks passed; Java checks were unavailable because no JDK or Maven is installed. - **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (used for versions only). diff --git a/QUALITY_REPORT.md b/QUALITY_REPORT.md index 866064a..48b6d91 100644 --- a/QUALITY_REPORT.md +++ b/QUALITY_REPORT.md @@ -3,11 +3,11 @@ - **Project:** shared - **Path:** /workspace/Personal/Web/shared - **Analyzed:** 2026-10-16 -- **Commit:** 5216031 on main -- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. Findings reflect the working tree (for example, README component count, Q-014). +- **Commit:** 22887fe on main +- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed. - **Stack:** Go 1.25 (`backend/`); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`, ruff configured); Java 8 target with Jackson and JUnit 5 (`packages/java-backend`); Svelte 5 and TypeScript with svelte-check (`packages/web-ui`); PowerShell and Node build and sync scripts; Gitea and GitHub Actions. -- **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. +- **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings came from read-only static review passes; the highest-impact citations were re-checked in the code. The shared Node, Python, web-ui and Go suites/checks, web-ui package build and checks were run during this continuation; Java tools remain unavailable. +- **Updated:** 2026-10-20 — Q-008 fixed in the working tree: all password writers use bcrypt cost 12, legacy PBKDF2 verifies and upgrades after a successful login, and shared contract fixtures cover all runtimes. Node tests, web-ui tests, package build, Svelte check and Node syntax check passed. ## Summary @@ -77,7 +77,7 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te - **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately. - **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. -- **Status:** Open 2026-10-19 — partly fixed: Python list and create payloads no longer return `password_hash`, Python startup retries only transient connection errors like Node, the Java middleware answers 401 when no base URL is set, and Java `Totp` compares with `MessageDigest.isEqual`. Node, Python and Go version their password hashes and rewrite older ones on login (see S-013). New in this pass: `contract/auth-contract.json` holds shared fixtures (password hashes per runtime, RFC 6238 TOTP cases, client-address cases) that the Go, Node and Python suites all load (`backend/auth/contract_test.go`, `packages/node-backend/test/contract.test.js`, `packages/python-backend/tests/test_contract.py`); it records the remaining hash divergence on purpose. Running it found Python `verify_totp` raising `TypeError` on a six-digit token written in non-ASCII digits where Go and Node answer false, fixed in `totp.py`. The Node and Python stores now share Go's guards (see S-016), and Python refuses passwords over 72 bytes like Go. Still open: Node (PBKDF2) writes a different hash format into `auth_users.password_hash` than Python and Go (bcrypt); Node cannot verify bcrypt, and Python and Go cannot verify Node's. Decision needed: pick one write scheme for all runtimes (or accept a new bcrypt dependency in Node), because letting one runtime verify another's format would make a shared database ping-pong between schemes on re-key. The Java client is not in the contract tests: no JDK or Maven is available here to compile them. Files: `contract/auth-contract.json`, `backend/auth/contract_test.go`, `packages/node-backend/test/contract.test.js`, `packages/python-backend/tests/test_contract.py`, `packages/python-backend/src/shared_backend/totp.py`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/src/shared_backend/postgres.py`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java`, `packages/node-backend/src/auth.js`, `backend/auth/password.go`. +- **Status:** Fixed 2026-10-20 — Node now writes the same prefixed bcrypt cost-12 scheme as Go and Python, and each runtime verifies current/legacy bcrypt plus both legacy Node PBKDF2 formats. Successful legacy verification returns an upgraded hash; AuthGuard conditionally persists that upgrade after a successful login. Long legacy PBKDF2 passwords use the explicit `bcrypt-sha256$` scheme to avoid bcrypt truncation, while new passwords over 72 bytes are rejected. The Java AuthClient does not create or verify stored password hashes. Node also depends on `bcryptjs` to share the scheme. The shared contract covers current, low-cost, malformed, legacy and over-limit cases. Files: `backend/auth/password.go`, `backend/auth/contract_test.go`, `Central/AuthGuard/internal/httpapi/{auth.go,server.go,server_test.go}`, `packages/node-backend/{package.json,src/auth.js,test/auth.test.js,test/contract.test.js}`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/tests/{test_core.py,test_contract.py}`, `contract/auth-contract.json`. ### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium** · Fixed - **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script) @@ -132,6 +132,6 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te - **Checked, clean:** No `TODO`, `FIXME`, `HACK` or `XXX` markers in first-party non-test code. No `any`, `@ts-ignore`, `@ts-expect-error` or `svelte-ignore` in `packages/web-ui/src`. No `{@html}`, `innerHTML`, `eval` or `new Function` in the web-ui or scripts. External links use `rel="noreferrer"`. Timers and document listeners are cleaned up in `StatusWidget`, `MediaPlayer`, `MediaPlayerControls`, `PrimaryColorPicker` and `notifications.svelte.ts`. - **Checked, consistent:** Go code is gofmt-checked and `go vet`-checked in CI. Python code is ruff-checked (`E`, `F`, `I`). Node syntax is checked for `packages/node-backend`. Parameterised SQL is used across the Go, Node and Python stores. - **Duplication by design:** The AuthGuard client exists in four languages on purpose. Q-008 covers where the behaviour has drifted. -- **Not run:** No lint, build, test, `go vet`, `ruff`, `svelte-check` or `npm` command was executed. All findings are from reading the code. +- **Verification:** Node backend: 73 tests passed. Python backend: 122 tests and Ruff passed. Web-ui: 29 tests, package build, `svelte-check`, `npm run lint`, and `format:check` passed. Go: `gofmt -l`, `go test ./...` and `go vet ./...` passed. Java tests were not run because no JDK or Maven is available. No database-backed integration test ran. - **Not verified:** Whether consumers depend on the removed `UserManagement` export or the `MediaPlayerControls` barrel removal (the changeset says only AuthGuard used it). Whether the `packages/media-shared-assets` and `media-backend` paths in history were ever shipped. - **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies beyond coverage notes. diff --git a/README.md b/README.md index 9b375f2..9f5d275 100644 --- a/README.md +++ b/README.md @@ -82,13 +82,17 @@ These are the complete Svelte component exports from `packages/web-ui/src/lib/in | Component | Includes | |---|---| | `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. | -| `ProfileDialog` | Profile username/email/password editing and TOTP settings. | +| `ProfileDialog` | Profile username/email/password editing and TOTP settings. Changing a password asks for the current password and, when TOTP is enabled, a current authenticator code; `onSave` receives both proofs in `ProfileUpdateInput`. | | `TotpSettings` | TOTP status, setup, enable, and disable controls. | This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update the matching category table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the tables aligned with that barrel file, place each component in the category that matches its primary purpose, and do not add internal or generated components to them. The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks. +### AuthGuard session validation + +The Go and Python `AuthClient.validate()` helpers cache both valid and invalid session results for two seconds. If a session is revoked directly in AuthGuard, a service using that cache may accept it for up to two more seconds. Calling logout through the same client clears its cached result immediately. + --- ## How consumers actually use this @@ -134,7 +138,7 @@ go vet ./... Go tests that need PostgreSQL skip themselves unless a scratch database is named: `DATABASE_URL` for the auth store tests, `SHARED_TEST_DATABASE_URL` for the platform-user, mediacore and migrate tests. They create tables and delete rows, so never point either at a real database. CI runs them against a throwaway PostgreSQL service (`go test -p 1 ./...`). -`contract/auth-contract.json` holds fixtures (password hashes, TOTP codes, client addresses) that the Go, Node and Python test suites all load, so the runtimes cannot drift apart unnoticed. +`contract/auth-contract.json` holds fixtures (password hashes, TOTP codes, client addresses, and the internal-secret rule: minimum length and example placeholders) that the Go, Node and Python test suites all load, so the runtimes cannot drift apart unnoticed. --- diff --git a/SECURITY_REPORT.md b/SECURITY_REPORT.md index 765b784..cd3e41d 100644 --- a/SECURITY_REPORT.md +++ b/SECURITY_REPORT.md @@ -3,11 +3,11 @@ - **Project:** shared - **Path:** /workspace/Personal/Web/shared - **Analyzed:** 2026-10-16 -- **Commit:** 5216031 on main -- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. None of them touches authentication code. +- **Commit:** 22887fe on main +- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed. - **Stack:** Go 1.25 (`backend/`: session proxy, AuthGuard client, websocket sync hub, media core, CarrierNode client, log shipper, Postgres helpers, goose migrations); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; Gitea and GitHub Actions. No Dockerfile is present. -- **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, 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. +- **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings came from read-only static review passes, and the highest-severity citations were re-checked in the code. Available checks run during this continuation: shared Node/Python/Go/web-ui suites, Svelte check, Node lint, Ruff, formatting and web-ui package build. Java tools remain unavailable; no production service or real database was used. +- **Updated:** 2026-10-20 — shared decisions implemented in the working tree: S-011 fixed; S-010 partly fixed with its undecided session-revocation portion left open. Available Node and web-ui checks pass; Python, Go and Java verification limits are recorded below. ## Summary @@ -15,7 +15,7 @@ |---|---:|---:|---:|---:| | Critical | 1 | 1 | 0 | 0 | | High | 3 | 2 | 0 | 1 | -| Medium | 13 | 11 | 0 | 2 | +| Medium | 13 | 12 | 0 | 1 | | Low | 5 | 0 | 0 | 5 | | Info | 0 | 0 | 0 | 0 | @@ -91,14 +91,14 @@ The most serious issue is a Python router route that lets an anonymous caller sw - **Description:** A new password is validated and forwarded to AuthGuard without asking for the current password or a TOTP code. - **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. -- **Status:** Open 2026-10-19 — re-verified, not changed: `UpdateMe` (`backend/auth/proxy.go`) and `update_me` (`authproxy.py`) still forward a new password on the session cookie alone. Decisions needed: (1) require `currentPassword` (and `totpToken` when TOTP is on) whenever `password` is set, checked through an AuthGuard login call or a new AuthGuard endpoint; this changes the request shape that web-ui and every consumer client send; (2) whether a password change revokes the account's other sessions, which AuthGuard owns. +- **Status:** Partly fixed 2026-10-20 — the decided rule is implemented: Go and Python self-service profile updates require `currentPassword` for a password change and a TOTP code when enabled; both reauthenticate through AuthGuard, omit proof fields from the managed-user update, and attempt to clear the temporary session. The shared web-ui prompts for and sends those values. No self-service `UpdateMe` route exists in the shared Node or Java clients. Still open: revoking other sessions after a password change is controlled by AuthGuard and has no owner decision. Files: `backend/auth/proxy.go`, `backend/auth/proxy_handlers_test.go`, `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`, `packages/web-ui/src/lib/components/ProfileDialog.svelte`, `packages/web-ui/tests/ProfileDialog.test.ts`. ### S-011 · TOTP codes can be replayed within their validity window in every runtime · **Medium** · Open -- **Location:** `backend/auth/totp.go:56` (`VerifyTOTP` returns only a bool and does not report the matched step), `backend/auth/store.go:70-84` (no last-used-step column), `packages/node-backend/src/totp.js:26-53`, `packages/python-backend/src/shared_backend/totp.py:38-66`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:44-88` (per review) +- **Location:** `backend/auth/totp.go` and `packages/{node-backend/src/totp.js,python-backend/src/shared_backend/totp.py,java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}` return the matched time step; Go, Node and Python auth stores persist it. - **Description:** Verification accepts the current and adjacent 30-second steps and records nothing about use. A code that an attacker observes stays valid for about 90 seconds and can be submitted repeatedly within that window. - **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. -- **Status:** Open 2026-10-19 — re-verified, not changed. AuthGuard calls the shared `VerifyTOTP` for login, verify and disable (`Central/AuthGuard/internal/httpapi/auth.go`, `totp.go`) and keeps TOTP state in the shared `auth.Store`, so the fix spans this library and AuthGuard. It needs the verifiers to return the matched time step, a `last_used_step` column on `auth_users` (an additive `ADD COLUMN IF NOT EXISTS` in each runtime's schema) advanced atomically with a `WHERE last_used_step < $step` guard, and AuthGuard calling the new API. Decision needed: approve the new column and the semantics change (a code already used inside its window is refused at login), after which the three stores and AuthGuard change together. +- **Status:** Fixed 2026-10-20 — verifiers return the matched time step; Go, Node and Python stores add `last_used_step` through additive schema changes and atomically advance it only when the step is newer. AuthGuard consumes steps for login, enrollment and disable, so a code already used in its validity window is refused. Files: `backend/auth/{totp.go,store.go}`, `Central/AuthGuard/internal/httpapi/{auth.go,totp.go,server.go}`, `packages/{node-backend/src/{auth.js,totp.js},python-backend/src/shared_backend/{auth.py,totp.py},java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}`. Go, Node, Python and web-ui checks passed; Java tests could not run because no JDK or Maven is available. ### 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) @@ -178,5 +178,5 @@ The most serious issue is a Python router route that lets an anonymous caller sw - **Web UI:** No `{@html}`, `innerHTML`, `eval` or `new Function` was found. External links use `rel="noreferrer"`. `fetch` is used only in `StatusWidget.svelte` (same-origin relative paths with credentials included); auth requests are delegated to the consuming application through callbacks, so CSRF and session handling live in the backend. The primary-color writer builds CSS only from palette values. - **Checked, no issue found:** SQL is parameterised in the Go, Node and Python stores and in the mediacore queries; dynamic `SET` fragments use fixed column names. Tokens and secrets come from `crypto/rand`, `crypto.randomBytes`, Python `secrets` and `SecureRandom`; no `math/rand`, `Math.random`, `random.` or `java.util.Random` was found. Session tokens are 256-bit and stored as SHA-256 hashes, and no JWT is used. No `eval`, `pickle`, `yaml.load`, `shell=True`, `os.system` or `exec.Command` appears in scope. No `InsecureSkipVerify` on any TLS configuration; the only use is the websocket origin option (S-014). The Go request bodies are capped (512 KB for mediacore, 4 KB for coreconfig, 128 KB for the proxy). Outbound clients have timeouts. Logout clears cookies with `HttpOnly` and `SameSite` in the Python proxy. No CORS configuration or debug mode was found. - **Dependencies (not audited):** No known-vulnerable version is asserted in this report, since no audit tool or network access was used. Versions to confirm: Go `coder/websocket` v1.8.15, `go-chi/chi` v5.3.1, `pgx` v5.10.0, `goose` v3.27.3, `golang.org/x/crypto` v0.54.0 (`backend/go.mod`); Node `pg` 8.22.0 (locked in `package-lock.json`, declared `^8.17.2`); Python `bcrypt>=4.2` and `asyncpg>=0.30` with no upper bounds (`packages/python-backend/pyproject.toml`); Java Jackson 2.18.6, JUnit 5.10.2 (`packages/java-backend/pom.xml`). Run `govulncheck`, `npm audit`, `pip-audit` and an OWASP dependency check. -- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. Test bodies were not run, and no server was started. +- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. The shared Node (73 tests), Python (122 tests), and web-ui (29 tests) suites plus Go `go test ./...`, `go vet ./...` and `gofmt -l` passed; Java tests were unavailable because no JDK or Maven is installed. No server was started. - **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and `node_modules`. diff --git a/backend/auth/contract_test.go b/backend/auth/contract_test.go index 6bcc496..0fb06a6 100644 --- a/backend/auth/contract_test.go +++ b/backend/auth/contract_test.go @@ -19,10 +19,12 @@ type authContract 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"` + Name string `json:"name"` + Hash string `json:"hash"` + Password string `json:"password"` + WrongPassword string `json:"wrongPassword"` + Verifies map[string]bool `json:"verifies"` + NeedsUpgrade map[string]bool `json:"needsUpgrade"` } `json:"hashes"` TooLongToHash struct { Bytes int `json:"bytes"` @@ -32,11 +34,12 @@ type authContract struct { 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"` + Name string `json:"name"` + Unix int64 `json:"unix"` + Code string `json:"code"` + Secret *string `json:"secret"` + MatchedStep *int64 `json:"matchedStep"` + Valid bool `json:"valid"` } `json:"cases"` } `json:"totp"` ClientAddress struct { @@ -71,21 +74,29 @@ 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"] { + password := entry.Password + if password == "" { + password = contract.Password.Plaintext + } + wrongPassword := entry.WrongPassword + if wrongPassword == "" { + wrongPassword = contract.Password.WrongPassword + } + if got := VerifyPassword(entry.Hash, password); got != entry.Verifies["go"] { t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"]) } - if VerifyPassword(entry.Hash, contract.Password.WrongPassword) { + if VerifyPassword(entry.Hash, 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) + valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, password) 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)) { + if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) && !strings.HasPrefix(upgraded, bcryptSHA256Scheme) || !VerifyPassword(upgraded, password)) { t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded) } } @@ -109,9 +120,19 @@ func TestContractTOTP(t *testing.T) { if entry.Secret != nil { secret = *entry.Secret } - if got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0)); got != entry.Valid { + step, got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0)) + if got != entry.Valid { t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid) } + if got { + want := entry.Unix / 30 + if entry.MatchedStep != nil { + want = *entry.MatchedStep + } + if step != want { + t.Errorf("VerifyTOTP matched step %d, want %d", step, want) + } + } }) } } diff --git a/backend/auth/password.go b/backend/auth/password.go index 0926ec7..3ef9c4d 100644 --- a/backend/auth/password.go +++ b/backend/auth/password.go @@ -1,9 +1,15 @@ package auth import ( + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "errors" + "strconv" "strings" "golang.org/x/crypto/bcrypt" + "golang.org/x/crypto/pbkdf2" ) // BcryptCost is kept in one place so all services use the same password @@ -17,9 +23,19 @@ const BcryptCost = 12 // with "$"). Unprefixed bcrypt hashes from before the prefix still verify and // are upgraded on login. const bcryptScheme = "bcrypt$" +const bcryptSHA256Scheme = "bcrypt-sha256$" + +const ( + maxPasswordBytes = 72 + legacyPBKDF2Iterations = 100000 + maxPBKDF2Iterations = 10000000 +) // HashPassword returns a versioned password hash suitable for storage. func HashPassword(password string) (string, error) { + if len([]byte(password)) > maxPasswordBytes { + return "", errors.New("password must be at most 72 bytes") + } hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost) if err != nil { return "", err @@ -27,20 +43,38 @@ func HashPassword(password string) (string, error) { return bcryptScheme + string(hash), nil } -// VerifyPassword checks a plaintext password against a stored hash. It accepts -// hashes from HashPassword and unprefixed bcrypt hashes; any other format -// fails closed. +// VerifyPassword checks a plaintext password against bcrypt and legacy Node +// PBKDF2 hashes. A valid legacy hash is rewritten by VerifyAndUpgradePassword. func VerifyPassword(hash, password string) bool { + if bcryptHash, ok := strings.CutPrefix(hash, bcryptSHA256Scheme); ok { + digest := sha256.Sum256([]byte(password)) + return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(hex.EncodeToString(digest[:]))) == nil + } + if iterations, salt, expected, ok := parsePBKDF2Hash(hash); ok { + actual := pbkdf2.Key([]byte(password), []byte(salt), iterations, 32, sha256.New) + expectedBytes, err := hex.DecodeString(expected) + return err == nil && subtle.ConstantTimeCompare(expectedBytes, actual) == 1 + } bcryptHash, ok := bcryptHashOf(hash) if !ok { return false } + if len([]byte(password)) > maxPasswordBytes { + 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 { + if bcryptHash, prefixed := strings.CutPrefix(hash, bcryptSHA256Scheme); prefixed { + cost, err := bcrypt.Cost([]byte(bcryptHash)) + return err != nil || cost < BcryptCost + } + if _, _, _, ok := parsePBKDF2Hash(hash); ok { + return true + } bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme) if !prefixed { return true @@ -61,6 +95,15 @@ func VerifyAndUpgradePassword(hash, password string) (valid bool, upgraded strin if !PasswordHashNeedsUpgrade(hash) { return true, "", nil } + if len([]byte(password)) > maxPasswordBytes { + digest := sha256.Sum256([]byte(password)) + var hashBytes []byte + hashBytes, err = bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(digest[:])), BcryptCost) + if err == nil { + upgraded = bcryptSHA256Scheme + string(hashBytes) + } + return true, upgraded, err + } upgraded, err = HashPassword(password) if err != nil { return true, "", err @@ -78,3 +121,32 @@ func bcryptHashOf(stored string) (string, bool) { } return "", false } + +func parsePBKDF2Hash(stored string) (iterations int, salt, expected string, ok bool) { + if strings.HasPrefix(stored, "pbkdf2-sha256$") { + parts := strings.Split(stored, "$") + if len(parts) != 4 { + return 0, "", "", false + } + parsedIterations, err := strconv.Atoi(parts[1]) + if err != nil { + return 0, "", "", false + } + iterations, salt, expected = parsedIterations, parts[2], parts[3] + } else if strings.Count(stored, ":") == 1 { + parts := strings.SplitN(stored, ":", 2) + iterations, salt, expected = legacyPBKDF2Iterations, parts[0], parts[1] + } else { + return 0, "", "", false + } + if iterations < 1 || iterations > maxPBKDF2Iterations || len(salt) != 32 || len(expected) != 64 { + return 0, "", "", false + } + if _, err := hex.DecodeString(salt); err != nil { + return 0, "", "", false + } + if _, err := hex.DecodeString(expected); err != nil { + return 0, "", "", false + } + return iterations, salt, expected, true +} diff --git a/backend/auth/proxy.go b/backend/auth/proxy.go index 4a018b6..d16e441 100644 --- a/backend/auth/proxy.go +++ b/backend/auth/proxy.go @@ -165,9 +165,9 @@ package auth import ( "context" - "crypto/subtle" "encoding/json" "errors" + "fmt" "io" "mime" "net" @@ -183,6 +183,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" "repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy" + "repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig" ) // ProxyUser is this service's own /auth/... response shape - UNCHANGED from @@ -223,7 +224,7 @@ var ( // message rather than a generic "internal error" that would be // indistinguishable from any other server bug. errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.") - errSecretNotSet = errors.New("SECRET environment variable is not set.") + errSecretNotUsable = fmt.Errorf("SECRET environment variable is unset, shorter than %d characters, or an example placeholder.", coreconfig.MinInternalSecretLength) errTooManyAttempts = errors.New("Too many attempts. Try again later.") 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") @@ -286,6 +287,10 @@ type Service struct { // real base URL. authGuard *authclient.Client configurationError error + // reauthenticateEmailChanges is opt-in because older consumers historically + // allowed email-only edits without the current password. Password changes + // always require current credentials in UpdateMe. + reauthenticateEmailChanges bool loginCacheMu sync.Mutex loginCacheValue bool loginCacheSet bool @@ -305,9 +310,10 @@ type Service struct { type ServiceOption func(*serviceOptions) type serviceOptions struct { - disabled bool - requireSecret bool - trustedProxies []*net.IPNet + disabled bool + requireSecret bool + reauthenticateEmailChanges bool + trustedProxies []*net.IPNet } // Disabled explicitly builds a Service in auth-disabled mode (see the @@ -329,6 +335,14 @@ func RequireSecret() ServiceOption { return func(o *serviceOptions) { o.requireSecret = true } } +// ReauthenticateEmailChanges requires current-password proof, and TOTP when +// enabled, for email changes through UpdateMe. Password changes already +// require the same proof. This is opt-in to preserve existing consumers that +// have not adopted the matching profile-dialog flow. +func ReauthenticateEmailChanges() ServiceOption { + return func(o *serviceOptions) { o.reauthenticateEmailChanges = true } +} + // WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is // honoured when a login's client address is taken. Build the list from the // TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer @@ -379,8 +393,8 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey)) } var configurationError error - if options.requireSecret && !options.disabled && strings.TrimSpace(os.Getenv("SECRET")) == "" { - configurationError = errSecretNotSet + if options.requireSecret && !options.disabled && !coreconfig.InternalSecretUsable(strings.TrimSpace(os.Getenv("SECRET"))) { + configurationError = errSecretNotUsable } return &Service{ store: store, @@ -388,6 +402,7 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG secureCookies: secureCookies, authGuard: client, configurationError: configurationError, + reauthenticateEmailChanges: options.reauthenticateEmailChanges, loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit), loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit), totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit), @@ -694,9 +709,11 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { } var input struct { - Email string `json:"email"` - Username string `json:"username"` - Password string `json:"password"` + Email string `json:"email"` + Username string `json:"username"` + Password string `json:"password"` + CurrentPassword string `json:"currentPassword"` + TOTPToken string `json:"totpToken"` } if err := decodeProxyJSON(r, &input); err != nil { writeProxyError(w, http.StatusBadRequest, "invalid JSON body") @@ -719,7 +736,29 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { writeProxyError(w, http.StatusBadRequest, err.Error()) return } - managedInput.Password = input.Password + } + if input.Password != "" || (s.reauthenticateEmailChanges && email != current.Email) { + if input.CurrentPassword == "" { + writeProxyError(w, http.StatusBadRequest, "currentPassword is required to change email or password") + return + } + if current.MFAEnabled && strings.TrimSpace(input.TOTPToken) == "" { + writeProxyError(w, http.StatusBadRequest, "totpToken is required to change email or password") + return + } + reauthenticated, err := s.authGuard.Login(r.Context(), current.Username, input.CurrentPassword, input.TOTPToken) + if err != nil { + writeAuthGuardError(w, err, "current credentials could not be verified") + return + } + if token := temporarySessionToken(reauthenticated); token != "" { + defer func() { + _, _ = s.authGuard.Logout(context.WithoutCancel(r.Context()), token) + }() + } + if input.Password != "" { + managedInput.Password = input.Password + } } token := s.sessionToken(r) @@ -736,6 +775,18 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { writeProxyJSON(w, http.StatusOK, map[string]any{"user": updated}) } +func temporarySessionToken(session *authclient.SessionResult) string { + if session == nil { + return "" + } + for _, cookie := range session.Cookies { + if cookie != nil && cookie.Name == authclient.DefaultCookieName { + return cookie.Value + } + } + return "" +} + // AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc // comment's "Setup flow" section. func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) { @@ -856,7 +907,7 @@ func (s *Service) SetLoginRequired(ctx context.Context, required bool) error { // expose the same propagation endpoint without duplicating its JSON handling. func (s *Service) SetLoginRequiredInternal(secret string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if strings.TrimSpace(secret) == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 { + if !coreconfig.InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) { writeProxyError(w, http.StatusUnauthorized, "internal service authentication required") return } diff --git a/backend/auth/proxy_handlers_test.go b/backend/auth/proxy_handlers_test.go index 79ed84e..ac35141 100644 --- a/backend/auth/proxy_handlers_test.go +++ b/backend/auth/proxy_handlers_test.go @@ -406,6 +406,12 @@ func TestTOTPInitiateAndStatus(t *testing.T) { func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) { guard := newFakeAuthGuard(t) + guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) { + w.Header().Add("Set-Cookie", authclient.DefaultCookieName+"=reauth-token; Path=/; HttpOnly") + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}}) + }) + guard.reply("POST /api/logout", http.StatusOK, map[string]any{"ok": true}) guard.reply("PUT /api/admin/users/7", http.StatusOK, map[string]any{}) guard.reply("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) @@ -418,7 +424,7 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) { service.UpdateMe(rec, req) return rec } - manager := &ProxyUser{ID: 7, Role: "admin"} + manager := &ProxyUser{ID: 7, Username: "boss", Role: "admin", MFAEnabled: true} if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized { t.Fatalf("no session user: status = %d, want 401", rec.Code) @@ -427,11 +433,13 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) { 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`, + "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) + `"}`, + "missing current password": `{"email":"a@b.com","username":"boss","password":"new-password"}`, + "missing current totp": `{"email":"a@b.com","username":"boss","password":"new-password","currentPassword":"current-password"}`, + "not JSON": `nope`, } { if rec := update(manager, body); rec.Code != http.StatusBadRequest { t.Errorf("%s: status = %d, want 400", name, rec.Code) @@ -452,6 +460,29 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) { if _, sent := calls[0].Body["password"]; sent { t.Fatal("an update without a password sent one to AuthGuard") } + + rec = update(manager, `{"email":"boss@example.com","username":"boss","password":"new-password","currentPassword":"current-password","totpToken":"123456"}`) + if rec.Code != http.StatusOK { + t.Fatalf("password update status = %d, body %s", rec.Code, rec.Body.String()) + } + loginCalls := guard.callsTo("POST /api/login") + if len(loginCalls) != 1 || loginCalls[0].Body["username_or_email"] != "boss" || loginCalls[0].Body["password"] != "current-password" || loginCalls[0].Body["totp_token"] != "123456" { + t.Fatalf("reauthentication request = %+v", loginCalls) + } + calls = guard.callsTo("PUT /api/admin/users/7") + if len(calls) != 2 || calls[1].Body["password"] != "new-password" { + t.Fatalf("password update request = %+v", calls) + } + if _, sent := calls[1].Body["currentPassword"]; sent { + t.Fatal("current password was forwarded to the managed-user API") + } + if _, sent := calls[1].Body["totpToken"]; sent { + t.Fatal("TOTP code was forwarded to the managed-user API") + } + logoutCalls := guard.callsTo("POST /api/logout") + if len(logoutCalls) != 1 || logoutCalls[0].Authorization != "Bearer reauth-token" { + t.Fatalf("temporary login session was not removed: %+v", logoutCalls) + } if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" { t.Fatalf("response user = %v", user) } diff --git a/backend/auth/store.go b/backend/auth/store.go index 88ecf0e..d6eed40 100644 --- a/backend/auth/store.go +++ b/backend/auth/store.go @@ -87,6 +87,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions role TEXT NOT NULL DEFAULT 'user', totp_secret TEXT NOT NULL DEFAULT '', totp_enabled BOOLEAN NOT NULL DEFAULT FALSE, + last_used_step BIGINT NOT NULL DEFAULT -1, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), last_login_at TIMESTAMPTZ @@ -95,6 +96,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user'; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT ''; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE; + ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); -- last_login_at is nullable (NULL means "never logged in" - registration @@ -220,8 +222,9 @@ func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error { // TOTPState is the private provisioning state for one account. Secret must // never be included in an API response. type TOTPState struct { - Secret string - Enabled bool + Secret string + Enabled bool + LastUsedStep int64 } // GetTOTPState reads the stored TOTP provisioning state for an account. @@ -230,7 +233,7 @@ func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, erro return TOTPState{}, err } var state TOTPState - err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled) + err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false), COALESCE(last_used_step, -1) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled, &state.LastUsedStep) if errors.Is(err, pgx.ErrNoRows) { return TOTPState{}, nil } @@ -246,7 +249,7 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) if err := s.validate(); err != nil { return err } - tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID) + tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID) if err != nil { return fmt.Errorf("set TOTP secret: %w", err) } @@ -262,16 +265,39 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) return nil } -// EnableTOTP marks a previously provisioned secret as active. -func (s *Store) EnableTOTP(ctx context.Context, userID int64) error { +// EnableTOTP marks a previously provisioned secret as active and records the +// step used to confirm it, preventing that code from being reused at login. +func (s *Store) EnableTOTP(ctx context.Context, userID int64, secret string, step int64) (bool, error) { if err := s.validate(); err != nil { - return err + return false, err } - _, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID) + tag, err := s.pool.Exec(ctx, ` + UPDATE auth_users + SET totp_enabled = true, last_used_step = $1, updated_at = now() + WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1 + `, step, userID, secret) if err != nil { - return fmt.Errorf("enable TOTP: %w", err) + return false, fmt.Errorf("enable TOTP: %w", err) } - return nil + return tag.RowsAffected() == 1, nil +} + +// ConsumeTOTPStep advances an account's accepted TOTP step only once. The +// expected secret and enabled flag are part of the update so a concurrent +// disable or re-enrollment cannot consume a code against stale state. +func (s *Store) ConsumeTOTPStep(ctx context.Context, userID int64, secret string, step int64) (bool, error) { + if err := s.validate(); err != nil { + return false, err + } + tag, err := s.pool.Exec(ctx, ` + UPDATE auth_users + SET last_used_step = $1, updated_at = now() + WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1 + `, step, userID, secret) + if err != nil { + return false, fmt.Errorf("consume TOTP step: %w", err) + } + return tag.RowsAffected() == 1, nil } // DisableTOTP clears both the active and pending TOTP secret. @@ -279,7 +305,7 @@ func (s *Store) DisableTOTP(ctx context.Context, userID int64) error { if err := s.validate(); err != nil { return err } - _, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID) + _, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1`, userID) if err != nil { return fmt.Errorf("disable TOTP: %w", err) } @@ -382,6 +408,22 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email return nil } +// UpgradePasswordHash replaces an old verifier only if it is still current, +// so a concurrent password change cannot be overwritten by a login rehash. +func (s *Store) UpgradePasswordHash(ctx context.Context, id int64, oldHash, newHash string) (bool, error) { + if err := s.validate(); err != nil { + return false, err + } + tag, err := s.pool.Exec(ctx, ` + UPDATE auth_users SET password_hash = $1, updated_at = now() + WHERE id = $2 AND password_hash = $3 + `, newHash, id, oldHash) + if err != nil { + return false, fmt.Errorf("upgrade password hash: %w", err) + } + return tag.RowsAffected() == 1, nil +} + // ListUsers returns the non-secret account fields used by the shared user // management screen. func (s *Store) ListUsers(ctx context.Context) ([]User, error) { diff --git a/backend/auth/store_integration_test.go b/backend/auth/store_integration_test.go index d55158b..cadafd9 100644 --- a/backend/auth/store_integration_test.go +++ b/backend/auth/store_integration_test.go @@ -230,8 +230,8 @@ func TestStoreTOTPAndIdentifierPrimitives(t *testing.T) { 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 enabled, err := store.EnableTOTP(ctx, owner.ID, "JBSWY3DPEHPK3PXP", 123); err != nil || !enabled { + t.Fatalf("EnableTOTP() = %v, %v; want enabled", enabled, err) } if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) { t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err) diff --git a/backend/auth/totp.go b/backend/auth/totp.go index 6ded413..175ba0e 100644 --- a/backend/auth/totp.go +++ b/backend/auth/totp.go @@ -52,19 +52,22 @@ func TOTPProvisioningURI(issuer, account, secret string) string { return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode() } -// VerifyTOTP checks a six-digit token with a one-period clock-skew window. -func VerifyTOTP(secret, token string, now time.Time) bool { +// VerifyTOTP checks a six-digit token with a one-period clock-skew window and +// returns the matching time step. A caller must atomically record that step +// before accepting the code so it cannot be used twice. +func VerifyTOTP(secret, token string, now time.Time) (int64, bool) { secret = normalizeTOTPSecret(secret) token = normalizeTOTPToken(token) if secret == "" || len(token) != TOTPDigits { - return false + return -1, false } key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret) if err != nil || len(key) == 0 { - return false + return -1, false } period := now.Unix() / int64(TOTPPeriod/time.Second) - for offset := int64(-TOTPWindow); offset <= TOTPWindow; offset++ { + // Prefer the current step if a six-digit collision occurs in the window. + for _, offset := range [...]int64{0, -1, 1} { if period+offset < 0 { continue } @@ -80,10 +83,10 @@ func VerifyTOTP(secret, token string, now time.Time) bool { uint32(digest[index+3]) candidate := fmt.Sprintf("%06d", value%1000000) if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 { - return true + return period + offset, true } } - return false + return -1, false } func normalizeTOTPSecret(value string) string { diff --git a/backend/auth/totp_test.go b/backend/auth/totp_test.go index 9e2623d..87369db 100644 --- a/backend/auth/totp_test.go +++ b/backend/auth/totp_test.go @@ -18,8 +18,11 @@ func TestVerifyTOTPRFC6238SHA1Vectors(t *testing.T) { {unix: 2000000000, code: "279037"}, } for _, testCase := range cases { - if !VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0)) { + step, valid := VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0)) + if !valid { t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code) + } else if want := testCase.unix / int64(TOTPPeriod/time.Second); step != want { + t.Errorf("VerifyTOTP(%d, %q) matched step %d, want %d", testCase.unix, testCase.code, step, want) } } } diff --git a/backend/authclient/client.go b/backend/authclient/client.go index d449949..fe5ff3c 100644 --- a/backend/authclient/client.go +++ b/backend/authclient/client.go @@ -71,6 +71,7 @@ type Client struct { projectKey string validationMu sync.Mutex validationCache map[[32]byte]validationCacheEntry + profileCache map[[32]byte]profileCacheEntry } // ProjectKeyHeader is the header Client attaches to every request identifying @@ -118,6 +119,7 @@ func New(baseURL string, opts ...Option) *Client { httpClient: &http.Client{Timeout: 5 * time.Second}, cookieName: DefaultCookieName, validationCache: make(map[[32]byte]validationCacheEntry), + profileCache: make(map[[32]byte]profileCacheEntry), } for _, opt := range opts { opt(c) @@ -583,12 +585,24 @@ func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, erro // Me calls GET /api/me, resolving token to its account. func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) { + token = strings.TrimSpace(token) + if token == "" { + return nil, ErrInvalidSession + } + if profile, ok := c.cachedProfile(token); ok { + return profile, nil + } var out struct { User PublicUser `json:"user"` } if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil { + var apiErr *APIError + if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized { + c.invalidateValidation(token) + } return nil, err } + c.cacheProfile(token, &out.User) return &out.User, nil } @@ -607,6 +621,9 @@ func (c *Client) TOTPEnable(ctx context.Context, token string) (*TOTPEnableResul // pending secret TOTPEnable provisioned and activating two-factor auth. func (c *Client) TOTPVerify(ctx context.Context, token, code string) error { _, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil) + if err == nil { + c.invalidateValidation(token) + } return err } @@ -615,6 +632,9 @@ func (c *Client) TOTPVerify(ctx context.Context, token, code string) error { // as proof of possession. func (c *Client) TOTPDisable(ctx context.Context, token, code string) error { _, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil) + if err == nil { + c.invalidateValidation(token) + } return err } diff --git a/backend/authclient/validation_cache.go b/backend/authclient/validation_cache.go index 75753a1..a0691b1 100644 --- a/backend/authclient/validation_cache.go +++ b/backend/authclient/validation_cache.go @@ -10,12 +10,20 @@ const ( maxValidationCacheSize = 10000 ) +// A session revoked directly in AuthGuard may remain accepted by this client +// for up to two seconds. Logout through this Client clears the cached result. + type validationCacheEntry struct { user User valid bool expires time.Time } +type profileCacheEntry struct { + profile PublicUser + expires time.Time +} + func (c *Client) cachedValidation(token string) (*User, error, bool) { key := sha256.Sum256([]byte(token)) now := time.Now() @@ -64,15 +72,61 @@ func (c *Client) cacheValidation(token string, user *User, valid bool) { c.validationCache[key] = entry } +func (c *Client) cachedProfile(token string) (*PublicUser, bool) { + key := sha256.Sum256([]byte(token)) + now := time.Now() + c.validationMu.Lock() + defer c.validationMu.Unlock() + entry, ok := c.profileCache[key] + if !ok { + return nil, false + } + if !now.Before(entry.expires) { + delete(c.profileCache, key) + return nil, false + } + profile := entry.profile + return &profile, true +} + +func (c *Client) cacheProfile(token string, profile *PublicUser) { + if profile == nil { + return + } + key := sha256.Sum256([]byte(token)) + now := time.Now() + c.validationMu.Lock() + defer c.validationMu.Unlock() + if c.profileCache == nil { + c.profileCache = make(map[[32]byte]profileCacheEntry) + } + if len(c.profileCache) >= maxValidationCacheSize { + for existing, entry := range c.profileCache { + if !now.Before(entry.expires) { + delete(c.profileCache, existing) + } + } + if len(c.profileCache) >= maxValidationCacheSize { + for existing := range c.profileCache { + delete(c.profileCache, existing) + break + } + } + } + c.profileCache[key] = profileCacheEntry{profile: *profile, expires: now.Add(validationCacheTTL)} +} + func (c *Client) invalidateValidation(token string) { key := sha256.Sum256([]byte(token)) c.validationMu.Lock() delete(c.validationCache, key) + delete(c.profileCache, key) c.validationMu.Unlock() } func (c *Client) clearValidationCache() { c.validationMu.Lock() c.validationCache = make(map[[32]byte]validationCacheEntry) + c.profileCache = make(map[[32]byte]profileCacheEntry) c.validationMu.Unlock() } diff --git a/backend/carriernodeclient/carriernodeclient.go b/backend/carriernodeclient/carriernodeclient.go index 6fa1fbb..a2c0a18 100644 --- a/backend/carriernodeclient/carriernodeclient.go +++ b/backend/carriernodeclient/carriernodeclient.go @@ -22,12 +22,25 @@ import ( "os" "strconv" "strings" + "sync" "time" ) -// httpClient has no blanket timeout since it streams large media files; -// callers bound individual calls with a context deadline instead. -var httpClient = &http.Client{} +// httpClient has no total timeout since it streams large media files. The +// transport still bounds how long a request may wait for response headers; +// callers that need a shorter bound add a context deadline as well. +var httpClient = newHTTPClient() + +func newHTTPClient() *http.Client { + var transport *http.Transport + if defaultTransport, ok := http.DefaultTransport.(*http.Transport); ok { + transport = defaultTransport.Clone() + } else { + transport = &http.Transport{Proxy: http.ProxyFromEnvironment} + } + transport.ResponseHeaderTimeout = 10 * time.Second + return &http.Client{Transport: transport} +} var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"} var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"} @@ -69,6 +82,17 @@ type Client struct { // multiple candidates are actually used (union for discovery, first-match // for reads, primary-only for writes). BaseURLs func(ctx context.Context) []string + + thumbnailMu sync.Mutex + thumbnailPaths map[string]thumbnailPathEntry +} + +const thumbnailPathCacheTTL = 5 * time.Minute +const thumbnailPathCacheLimit = 2048 + +type thumbnailPathEntry struct { + path string + expires time.Time } // New returns a Client backed by a single CarrierNode instance. baseURL is @@ -536,15 +560,103 @@ func (c *Client) ProxyThumbnail(w http.ResponseWriter, r *http.Request, project, if err != nil { return false } + cacheKey := project + "\x00" + id + cachedPath := c.cachedThumbnailPath(cacheKey) + if cachedPath != "" { + ordered := make([]string, 0, len(paths)) + ordered = append(ordered, cachedPath) + for _, path := range paths { + if path != cachedPath { + ordered = append(ordered, path) + } + } + paths = ordered + } for _, path := range paths { - if exists, _, _, probeErr := c.Probe(r.Context(), path); probeErr == nil && exists { - c.Proxy(w, r, path) + for _, baseURL := range c.candidateBaseURLs(r.Context()) { + request, err := c.newRequest(r.Context(), baseURL, r.Method, path, nil) + if err != nil { + continue + } + for _, header := range forwardRequestHeaders { + if value := r.Header.Get(header); value != "" { + request.Header.Set(header, value) + } + } + response, err := httpClient.Do(request) + if err != nil { + continue + } + if response.StatusCode >= http.StatusBadRequest { + response.Body.Close() + if path == cachedPath { + c.forgetThumbnailPath(cacheKey) + } + continue + } + for _, header := range forwardResponseHeaders { + if value := response.Header.Get(header); value != "" { + w.Header().Set(header, value) + } + } + w.WriteHeader(response.StatusCode) + if r.Method != http.MethodHead { + _, _ = io.Copy(w, response.Body) + } + response.Body.Close() + c.rememberThumbnailPath(cacheKey, path) return true } } return false } +func (c *Client) cachedThumbnailPath(key string) string { + c.thumbnailMu.Lock() + defer c.thumbnailMu.Unlock() + entry, ok := c.thumbnailPaths[key] + if !ok { + return "" + } + if !time.Now().Before(entry.expires) { + delete(c.thumbnailPaths, key) + return "" + } + return entry.path +} + +func (c *Client) rememberThumbnailPath(key, path string) { + c.thumbnailMu.Lock() + defer c.thumbnailMu.Unlock() + if c.thumbnailPaths == nil { + c.thumbnailPaths = make(map[string]thumbnailPathEntry) + } + now := time.Now() + for cacheKey, entry := range c.thumbnailPaths { + if !now.Before(entry.expires) { + delete(c.thumbnailPaths, cacheKey) + } + } + if len(c.thumbnailPaths) >= thumbnailPathCacheLimit { + var oldestKey string + var oldest time.Time + first := true + for cacheKey, entry := range c.thumbnailPaths { + if first || entry.expires.Before(oldest) { + oldestKey, oldest, first = cacheKey, entry.expires, false + } + } + delete(c.thumbnailPaths, oldestKey) + } + c.thumbnailPaths[key] = thumbnailPathEntry{path: path, expires: now.Add(thumbnailPathCacheTTL)} +} + +func (c *Client) forgetThumbnailPath(key string) { + c.thumbnailMu.Lock() + delete(c.thumbnailPaths, key) + c.thumbnailMu.Unlock() +} + // FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking // in the project's thumbnails mount and then the legacy root. Callers must invoke the returned // cleanup once done. diff --git a/backend/carriernodeclient/carriernodeclient_test.go b/backend/carriernodeclient/carriernodeclient_test.go index 1fe24b7..71efef8 100644 --- a/backend/carriernodeclient/carriernodeclient_test.go +++ b/backend/carriernodeclient/carriernodeclient_test.go @@ -1,265 +1,21 @@ package carriernodeclient import ( - "context" - "errors" "net/http" - "net/http/httptest" "testing" + "time" ) -func TestListFilesMergesAcrossInstances(t *testing.T) { - first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`)) - })) - defer first.Close() - second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"files":[{"rel":"b.mp4"}]}`)) - })) - defer second.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} }) - - files, err := client.ListFiles(context.Background(), "", false, 0) - if err != nil { - t.Fatalf("ListFiles error: %v", err) +func TestHTTPClientBoundsResponseHeaderWaitWithoutLimitingStreams(t *testing.T) { + client := newHTTPClient() + if client.Timeout != 0 { + t.Fatalf("client total timeout = %s, want no total timeout for media streams", client.Timeout) } - if len(files) != 2 { - t.Fatalf("ListFiles returned %d files, want 2: %+v", len(files), files) + transport, ok := client.Transport.(*http.Transport) + if !ok { + t.Fatalf("transport type = %T, want *http.Transport", client.Transport) } -} - -func TestRequestsCarryProjectAttribution(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got := r.Header.Get("X-Internal-Auth"); got != "secret" { - t.Fatalf("X-Internal-Auth = %q, want secret", got) - } - if got := r.Header.Get("X-Project-Key"); got != "ContentScanner" { - t.Fatalf("X-Project-Key = %q, want ContentScanner", got) - } - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"files":[]}`)) - })) - defer server.Close() - - client := New("secret", func(ctx context.Context) string { return server.URL }) - client.ProjectKey = "ContentScanner" - if _, err := client.ListFiles(context.Background(), "", false, 0); err != nil { - t.Fatalf("ListFiles error: %v", err) - } -} - -func TestListFilesSkipsUnreachableInstance(t *testing.T) { - up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`)) - })) - defer up.Close() - down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusInternalServerError) - })) - down.Close() // closed immediately so requests to it fail outright - - client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL, up.URL} }) - - files, err := client.ListFiles(context.Background(), "", false, 0) - if err != nil { - t.Fatalf("ListFiles error: %v", err) - } - if len(files) != 1 || files[0].Rel != "a.mp4" { - t.Fatalf("ListFiles = %+v, want just the reachable instance's file", files) - } -} - -func TestListFilesErrorsWhenNoInstanceReachable(t *testing.T) { - down := httptest.NewServer(nil) - down.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL} }) - - if _, err := client.ListFiles(context.Background(), "", false, 0); err == nil { - t.Fatal("ListFiles error = nil, want an error when every instance is unreachable") - } -} - -func TestProbeFallsBackToNextInstance(t *testing.T) { - notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotFound) - })) - defer notFound.Close() - found := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Length", "42") - w.WriteHeader(http.StatusOK) - })) - defer found.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, found.URL} }) - - exists, size, _, err := client.Probe(context.Background(), "/media/a.mp4") - if err != nil { - t.Fatalf("Probe error: %v", err) - } - if !exists { - t.Fatal("Probe exists = false, want true (second instance has it)") - } - if size != 42 { - t.Fatalf("Probe size = %d, want 42", size) - } -} - -func TestProbeExistsFalseWhenNoInstanceHasFile(t *testing.T) { - notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotFound) - })) - defer notFound.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} }) - - exists, _, _, err := client.Probe(context.Background(), "/media/missing.mp4") - if err != nil { - t.Fatalf("Probe error: %v", err) - } - if exists { - t.Fatal("Probe exists = true, want false") - } -} - -func TestProxyPrefersPrimaryInstanceWhenItHasTheFile(t *testing.T) { - var primaryHit, secondaryHit bool - primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - primaryHit = true - w.WriteHeader(http.StatusOK) - })) - defer primary.Close() - secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - secondaryHit = true - w.WriteHeader(http.StatusOK) - })) - defer secondary.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} }) - - req := httptest.NewRequest(http.MethodGet, "/thumbnails/x.jpg", nil) - rec := httptest.NewRecorder() - client.Proxy(rec, req, "/thumbnails/x.jpg") - - if !primaryHit { - t.Fatal("Proxy did not hit the primary instance") - } - if secondaryHit { - t.Fatal("Proxy hit the secondary instance even though the primary had the file") - } -} - -func TestProxyFallsBackToSecondaryInstanceWhenPrimaryMisses(t *testing.T) { - primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotFound) - })) - defer primary.Close() - secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "video/mp4") - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte("video bytes")) - })) - defer secondary.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} }) - - req := httptest.NewRequest(http.MethodGet, "/media/a.mp4", nil) - rec := httptest.NewRecorder() - client.Proxy(rec, req, "/media/a.mp4") - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200 from the secondary instance", rec.Code) - } - if rec.Body.String() != "video bytes" { - t.Fatalf("body = %q, want secondary instance's bytes", rec.Body.String()) - } -} - -func TestProxyForwardsLastInstanceErrorWhenNoneHaveTheFile(t *testing.T) { - notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotFound) - })) - defer notFound.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} }) - - req := httptest.NewRequest(http.MethodGet, "/media/missing.mp4", nil) - rec := httptest.NewRecorder() - client.Proxy(rec, req, "/media/missing.mp4") - - if rec.Code != http.StatusNotFound { - t.Fatalf("status = %d, want 404 forwarded from the last instance", rec.Code) - } -} - -func mountListingServer(status int, body string) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - _, _ = w.Write([]byte(body)) - })) -} - -func TestListMountFilesReportsNotFoundWhenEveryInstanceMisses(t *testing.T) { - first := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`) - defer first.Close() - second := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`) - defer second.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} }) - - _, err := client.ListMountFiles(context.Background(), "autocode", "repos", "gone") - if !errors.Is(err, ErrMountNotFound) { - t.Fatalf("ListMountFiles error = %v, want ErrMountNotFound", err) - } -} - -func TestListMountFilesDoesNotReportNotFoundWhenAnInstanceIsUnreachable(t *testing.T) { - missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`) - defer missing.Close() - down := httptest.NewServer(nil) - down.Close() // closed immediately so requests to it fail outright - - client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, down.URL} }) - - _, err := client.ListMountFiles(context.Background(), "autocode", "repos", "maybe-on-the-down-instance") - if err == nil { - t.Fatal("ListMountFiles succeeded, want an error") - } - if errors.Is(err, ErrMountNotFound) { - t.Fatalf("ListMountFiles error = %v, must not claim the directory is missing when an instance could not be checked", err) - } -} - -func TestListMountFilesDoesNotReportNotFoundOnServerError(t *testing.T) { - broken := mountListingServer(http.StatusInternalServerError, `{"error":"boom"}`) - defer broken.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{broken.URL} }) - - _, err := client.ListMountFiles(context.Background(), "autocode", "repos", "") - if err == nil || errors.Is(err, ErrMountNotFound) { - t.Fatalf("ListMountFiles error = %v, want a non-ErrMountNotFound failure", err) - } -} - -func TestListMountFilesUsesTheInstanceThatHasTheDirectory(t *testing.T) { - missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`) - defer missing.Close() - present := mountListingServer(http.StatusOK, `{"files":[{"name":"repo","path":"repo","directory":true}]}`) - defer present.Close() - - client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, present.URL} }) - - files, err := client.ListMountFiles(context.Background(), "autocode", "repos", "") - if err != nil { - t.Fatalf("ListMountFiles error: %v", err) - } - if len(files) != 1 || files[0].Name != "repo" || !files[0].Directory { - t.Fatalf("ListMountFiles = %+v, want the one directory from the instance that has it", files) + if transport.ResponseHeaderTimeout != 10*time.Second { + t.Fatalf("response header timeout = %s, want 10s", transport.ResponseHeaderTimeout) } } diff --git a/backend/carriernodeclient/thumbnails_test.go b/backend/carriernodeclient/thumbnails_test.go index 37aac27..c074986 100644 --- a/backend/carriernodeclient/thumbnails_test.go +++ b/backend/carriernodeclient/thumbnails_test.go @@ -8,7 +8,6 @@ import ( "os" "path/filepath" "slices" - "strings" "sync" "testing" ) @@ -94,16 +93,15 @@ func TestProxyThumbnailPrefersProjectMount(t *testing.T) { if rec.Body.String() != "from mount" { t.Fatalf("body = %q, want the mount copy", rec.Body.String()) } - for _, request := range node.seen() { - if !strings.Contains(request, "/api/mount/") { - t.Fatalf("legacy root was consulted although the mount had the thumbnail: %v", node.seen()) - } + want := []string{"GET " + mount} + if got := node.seen(); !slices.Equal(got, want) { + t.Fatalf("requests = %v, want one direct GET to the mount", got) } } func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) { legacy := "/thumbnails/" + testThumbnailID + ".jpg" - client, _ := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"}) + client, node := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"}) rec := httptest.NewRecorder() if !client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) { @@ -112,10 +110,28 @@ func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) { if rec.Body.String() != "from legacy" { t.Fatalf("body = %q, want the legacy copy", rec.Body.String()) } + want := []string{"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg", "GET " + legacy} + if got := node.seen(); !slices.Equal(got, want) { + t.Fatalf("requests = %v, want mount miss followed by legacy GET", got) + } +} + +func TestProxyThumbnailCachesResolvedPath(t *testing.T) { + mount := "/api/mount/MediaViewer/thumbnails/" + testThumbnailID + ".jpg" + client, node := newThumbnailTestClient(t, map[string]string{mount: "from mount"}) + for range 2 { + if !client.ProxyThumbnail(httptest.NewRecorder(), thumbnailRequest(), "MediaViewer", testThumbnailID) { + t.Fatal("ProxyThumbnail missed although the mount holds the thumbnail") + } + } + want := []string{"GET " + mount, "GET " + mount} + if got := node.seen(); !slices.Equal(got, want) { + t.Fatalf("requests = %v, want one direct GET per request to the cached path", got) + } } func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) { - client, _ := newThumbnailTestClient(t, nil) + client, node := newThumbnailTestClient(t, nil) rec := httptest.NewRecorder() if client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) { @@ -124,6 +140,13 @@ func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) { if rec.Body.Len() != 0 { t.Fatalf("ProxyThumbnail wrote %q on a miss; the caller needs a clean fallback", rec.Body.String()) } + want := []string{ + "GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg", + "GET /thumbnails/" + testThumbnailID + ".jpg", + } + if got := node.seen(); !slices.Equal(got, want) { + t.Fatalf("requests = %v, want one GET for each candidate path", got) + } } func TestFetchThumbnailToScratchFallsBackToLegacyRoot(t *testing.T) { diff --git a/backend/coreconfig/contract_test.go b/backend/coreconfig/contract_test.go new file mode 100644 index 0000000..3db2156 --- /dev/null +++ b/backend/coreconfig/contract_test.go @@ -0,0 +1,52 @@ +package coreconfig + +import ( + "encoding/json" + "os" + "testing" +) + +// contractFile holds the fixtures the Go, Node and Python internal-secret checks must agree on. The +// Node and Python suites load the same file; see the "description" field in it. +const contractFile = "../../contract/auth-contract.json" + +type internalSecretContract struct { + InternalSecret struct { + MinLength int `json:"minLength"` + Placeholders []string `json:"placeholders"` + Cases []struct { + Name string `json:"name"` + Secret string `json:"secret"` + Provided string `json:"provided"` + Matches bool `json:"matches"` + } `json:"cases"` + } `json:"internalSecret"` +} + +func TestContractInternalSecret(t *testing.T) { + data, err := os.ReadFile(contractFile) + if os.IsNotExist(err) { + t.Skipf("%s is not part of this checkout", contractFile) + } + if err != nil { + t.Fatal(err) + } + var contract internalSecretContract + if err := json.Unmarshal(data, &contract); err != nil { + t.Fatalf("decode %s: %v", contractFile, err) + } + rule := contract.InternalSecret + if MinInternalSecretLength != rule.MinLength { + t.Fatalf("MinInternalSecretLength = %d, contract says %d", MinInternalSecretLength, rule.MinLength) + } + for _, placeholder := range rule.Placeholders { + if InternalSecretUsable(placeholder) { + t.Errorf("placeholder %q is usable, contract says it never gates a route", placeholder) + } + } + for _, entry := range rule.Cases { + if got := InternalSecretMatches(entry.Provided, entry.Secret); got != entry.Matches { + t.Errorf("%s: InternalSecretMatches = %v, contract says %v", entry.Name, got, entry.Matches) + } + } +} diff --git a/backend/coreconfig/coreconfig.go b/backend/coreconfig/coreconfig.go index b1fa901..487bb4d 100644 --- a/backend/coreconfig/coreconfig.go +++ b/backend/coreconfig/coreconfig.go @@ -18,8 +18,35 @@ import ( "net/url" "strings" "sync" + "unicode/utf8" ) +// MinInternalSecretLength is the shortest SECRET a service accepts for its internal routes. +const MinInternalSecretLength = 16 + +// exampleInternalSecrets are the placeholders shipped in .env.example files, plus the bare variable +// name. They are public, so they never gate a route. +var exampleInternalSecrets = map[string]bool{ + "SECRET": true, + "change-me-to-a-long-random-value": true, +} + +// InternalSecretUsable reports whether secret is strong enough to gate an internal route: at least +// MinInternalSecretLength characters and not an example placeholder. Length counts characters, as +// the Python and Node helpers do, not bytes. +func InternalSecretUsable(secret string) bool { + return utf8.RuneCountInString(secret) >= MinInternalSecretLength && !exampleInternalSecrets[secret] +} + +// InternalSecretMatches reports whether presented is the configured secret. A secret that is not +// usable (see InternalSecretUsable) never matches, and the comparison is constant-time. +func InternalSecretMatches(presented, secret string) bool { + if !InternalSecretUsable(secret) { + return false + } + return subtle.ConstantTimeCompare([]byte(presented), []byte(secret)) == 1 +} + // Info is AuthGuard's, CarrierNode's, and ProjectConfigurator's current base URL(s), as pushed by // ProjectConfigurator. type Info struct { @@ -178,11 +205,11 @@ func normalizeInfo(info Info) Info { // ProjectConfigurator calls to push a fresh Info: mount it at that path (see // ProjectConfigurator/README.md) behind a secret check for this service's own // SECRET (the same value ProjectConfigurator and CarrierNode were configured -// with - an empty secret refuses every caller, the same fail-closed default ProjectConfigurator's -// own internal-auth-gated routes use). +// with - a secret that is not usable (see InternalSecretUsable) refuses every caller, the same +// fail-closed default ProjectConfigurator's own internal-auth-gated routes use). func Handler(secret string, store *Store) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if secret == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 { + if !InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) { writeError(w, http.StatusUnauthorized, "internal service authentication required") return } diff --git a/backend/coreconfig/coreconfig_test.go b/backend/coreconfig/coreconfig_test.go index 69b160d..5c7337b 100644 --- a/backend/coreconfig/coreconfig_test.go +++ b/backend/coreconfig/coreconfig_test.go @@ -67,7 +67,7 @@ func TestStoreOnUpdateFiresWithNewInfo(t *testing.T) { func TestHandlerRejectsMissingOrWrongSecret(t *testing.T) { store := NewStore(Info{}) - handler := Handler("s3cret", store) + handler := Handler("test-internal-secret", store) body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"}) cases := []string{"", "wrong"} @@ -127,14 +127,14 @@ func equalStrings(got, want []string) bool { func TestHandlerAppliesPushedInfo(t *testing.T) { store := NewStore(Info{}) - handler := Handler("s3cret", store) + handler := Handler("test-internal-secret", store) body, _ := json.Marshal(Info{ AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com", CarrierNodeSecret: "carrier-secret", ContentScannerURL: "http://scanner.example.com/", ContentScannerSecret: "scanner-secret", }) req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body)) - req.Header.Set("X-Internal-Auth", "s3cret") + req.Header.Set("X-Internal-Auth", "test-internal-secret") rec := httptest.NewRecorder() handler(rec, req) @@ -152,7 +152,7 @@ func TestHandlerAppliesPushedInfo(t *testing.T) { func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) { store := NewStore(Info{AuthGuardURL: "http://auth.example.com"}) - handler := Handler("s3cret", store) + handler := Handler("test-internal-secret", store) for _, bad := range []Info{ {AuthGuardURL: "javascript:alert(1)"}, {AuthGuardURL: "auth.example.com"}, @@ -161,7 +161,7 @@ func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) { } { body, _ := json.Marshal(bad) req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body)) - req.Header.Set("X-Internal-Auth", "s3cret") + req.Header.Set("X-Internal-Auth", "test-internal-secret") rec := httptest.NewRecorder() handler(rec, req) if rec.Code != http.StatusBadRequest { @@ -172,3 +172,21 @@ func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) { t.Fatalf("store changed by a rejected push: %+v", got) } } + +func TestHandlerRefusesAnUnusableSecret(t *testing.T) { + for _, secret := range []string{"short", "SECRET", "change-me-to-a-long-random-value"} { + store := NewStore(Info{}) + handler := Handler(secret, store) + body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"}) + req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body)) + req.Header.Set("X-Internal-Auth", secret) + rec := httptest.NewRecorder() + handler(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("secret %q: status = %d, want %d", secret, rec.Code, http.StatusUnauthorized) + } + if store.Get().AuthGuardURL != "" { + t.Fatalf("secret %q: store changed despite a refused push", secret) + } + } +} diff --git a/backend/mediacore/mediacore.go b/backend/mediacore/mediacore.go index 97cd9e2..72ef275 100644 --- a/backend/mediacore/mediacore.go +++ b/backend/mediacore/mediacore.go @@ -43,6 +43,7 @@ import ( "time" "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" @@ -335,13 +336,25 @@ func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) { MediaKey string `json:"mediaKey"` } if r.Body != nil && r.ContentLength != 0 { - _ = decodeRequestJSON(r, &input) + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } } key := strings.TrimSpace(firstNonEmpty(input.MediaKey, r.URL.Query().Get("mediaKey"))) if key == "" { writeError(w, http.StatusBadRequest, "missing mediaKey") return } + exists, err := c.mediaExists(r.Context(), key) + if err != nil { + writeError(w, http.StatusInternalServerError, "media lookup failed") + return + } + if !exists { + writeError(w, http.StatusNotFound, "media not found") + return + } var userID any if user != nil { userID = user.ID @@ -368,15 +381,25 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) { if duration <= 0 { duration = input.Duration } - if strings.TrimSpace(input.MediaKey) == "" || duration <= 0 { - writeError(w, http.StatusBadRequest, "mediaKey and positive duration are required") + key := strings.TrimSpace(input.MediaKey) + if key == "" || duration <= 0 || duration > maxViewSessionDurationMs { + writeError(w, http.StatusBadRequest, "mediaKey and duration between 1ms and 24h are required") + return + } + exists, err := c.mediaExists(r.Context(), key) + if err != nil { + writeError(w, http.StatusInternalServerError, "media lookup failed") + return + } + if !exists { + writeError(w, http.StatusNotFound, "media not found") return } var userID any if user != nil { userID = user.ID } - _, err := c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, strings.TrimSpace(input.MediaKey), userID, duration) + _, err = c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, key, userID, duration) if err != nil { writeError(w, http.StatusInternalServerError, "view session could not be recorded") return @@ -384,6 +407,15 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}}) } +const maxViewSessionDurationMs int64 = 24 * 60 * 60 * 1000 + +func (c *Core) mediaExists(ctx context.Context, identifier string) (bool, error) { + var exists bool + err := c.db.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM media WHERE media_key=$1 OR id=$2)`, + identifier, mediaIDArg(identifier)).Scan(&exists) + return exists, err +} + func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID) @@ -793,9 +825,18 @@ func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool { 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) { +// MediaLookupOptions controls which otherwise-hidden records a media lookup may return. +type MediaLookupOptions struct { + // IncludeHidden lets moderators look up media with active = FALSE. + IncludeHidden bool + // RequireContentScannerProcessed limits the result to items imported by ContentScanner. + RequireContentScannerProcessed bool +} + +// FindMedia looks up one media item by media key or numeric id. Shared media routes +// preserve moderator access to hidden items; ContentScanner-backed consumers can also +// request the same processed-only filtering used by MediaViewer's library routes. +func (c *Core) FindMedia(ctx context.Context, identifier string, options MediaLookupOptions) (MediaRecord, error) { identifier = strings.TrimSpace(identifier) var record MediaRecord row := c.db.QueryRow(ctx, ` @@ -804,7 +845,8 @@ func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden b COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0), COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count, funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at) - FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) LIMIT 1`, identifier, mediaIDArg(identifier), includeHidden) + FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) AND (NOT $4 OR content_scanner_processed) LIMIT 1`, + identifier, mediaIDArg(identifier), options.IncludeHidden, options.RequireContentScannerProcessed) var title, description string var width, height int var duration, size int64 @@ -850,6 +892,12 @@ func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden b return record, nil } +// findMedia keeps the shared routes on the same lookup implementation used by +// media-family applications that need ContentScanner's processed-only filter. +func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) { + return c.FindMedia(ctx, identifier, MediaLookupOptions{IncludeHidden: includeHidden}) +} + // ToJSON is the shared wire shape for a media record, matching every // mediacore route's own response shape (id/mediaKey/filename/url/thumbnail/ // etc.) - services with their own media listing routes (e.g. MediaViewer's @@ -875,11 +923,28 @@ func (record MediaRecord) ToJSON() map[string]any { } } -// SettingValue reads one key from the shared `settings` table, returning -// fallback if it is unset or the read fails. -func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) string { +// SettingValue reads one key from the shared `settings` table. An absent or empty +// setting returns fallback; database errors are returned to the caller. +func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) (string, error) { var value string - if err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value); err != nil || value == "" { + err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value) + if errors.Is(err, pgx.ErrNoRows) { + return fallback, nil + } + if err != nil { + return "", err + } + if value == "" { + return fallback, nil + } + return value, nil +} + +// SettingValueOrFallback preserves the old fallback-on-error behavior for callers +// whose API cannot return a read error. New request paths should use SettingValue. +func SettingValueOrFallback(ctx context.Context, db *pgxpool.Pool, key, fallback string) string { + value, err := SettingValue(ctx, db, key, fallback) + if err != nil { return fallback } return value @@ -888,7 +953,7 @@ func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) s // SettingBool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true, // anything else is fallback). func SettingBool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool { - value := strings.ToLower(strings.TrimSpace(SettingValue(ctx, db, key, ""))) + value := strings.ToLower(strings.TrimSpace(SettingValueOrFallback(ctx, db, key, ""))) if value == "" { return fallback } @@ -922,19 +987,19 @@ var carrierNodeInstancePattern = regexp.MustCompile(`^carriernode(_\d+)?$`) // Returns fallback if no carriernode* instance is registered (or none has a URL) yet. func CarrierNodeURLs(ctx context.Context, db *pgxpool.Pool, fallback []string) []string { var registered []string - _ = json.Unmarshal([]byte(SettingValue(ctx, db, "configured_central", "")), ®istered) + _ = json.Unmarshal([]byte(SettingValueOrFallback(ctx, db, "configured_central", "")), ®istered) var urls []string for _, project := range registered { key := strings.ToLower(strings.TrimSpace(project)) if !carrierNodeInstancePattern.MatchString(key) { continue } - if url := strings.TrimSpace(SettingValue(ctx, db, key+"_url", "")); url != "" { + if url := strings.TrimSpace(SettingValueOrFallback(ctx, db, key+"_url", "")); url != "" { urls = append(urls, url) } } if len(urls) == 0 { - if url := strings.TrimSpace(SettingValue(ctx, db, "carriernode_url", "")); url != "" { + if url := strings.TrimSpace(SettingValueOrFallback(ctx, db, "carriernode_url", "")); url != "" { urls = []string{url} } } diff --git a/backend/mediacore/mediacore_test.go b/backend/mediacore/mediacore_test.go index 37a97df..a41b10d 100644 --- a/backend/mediacore/mediacore_test.go +++ b/backend/mediacore/mediacore_test.go @@ -9,11 +9,28 @@ import ( "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/authclient" ) +func TestSettingValueReturnsDatabaseErrors(t *testing.T) { + db, err := pgxpool.New(context.Background(), "postgres://nobody@127.0.0.1:1/none?sslmode=disable&connect_timeout=1") + if err != nil { + t.Fatalf("pgxpool.New: %v", err) + } + defer db.Close() + + value, err := SettingValue(context.Background(), db, "example", "fallback") + if err == nil || value != "" { + t.Fatalf("SettingValue() = %q, %v; want empty value and database error", value, err) + } + if got := SettingValueOrFallback(context.Background(), db, "example", "fallback"); got != "fallback" { + t.Fatalf("SettingValueOrFallback() = %q, want fallback on error", got) + } +} + // loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be // exercised without a database. type loginRequiredStore struct{} diff --git a/backend/mediacore/migrate.go b/backend/mediacore/migrate.go index eac783c..8e57d93 100644 --- a/backend/mediacore/migrate.go +++ b/backend/mediacore/migrate.go @@ -31,6 +31,7 @@ func (c *Core) Migrate(ctx context.Context) error { var migrationStatements = []string{ `CREATE EXTENSION IF NOT EXISTS pgcrypto`, `CREATE EXTENSION IF NOT EXISTS pg_trgm`, + `DROP INDEX IF EXISTS media_search_idx`, `CREATE TABLE IF NOT EXISTS users ( id BIGSERIAL PRIMARY KEY, @@ -85,7 +86,6 @@ var migrationStatements = []string{ `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`, `CREATE INDEX IF NOT EXISTS media_active_idx ON media (active)`, `CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path)`, - `CREATE INDEX IF NOT EXISTS media_search_idx ON media USING GIN (to_tsvector('simple', COALESCE(title, '') || ' ' || COALESCE(original_filename, '') || ' ' || COALESCE(file_path, '')))`, `CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`, `CREATE TABLE IF NOT EXISTS media_stats ( diff --git a/contract/auth-contract.json b/contract/auth-contract.json index 70490e3..27be056 100644 --- a/contract/auth-contract.json +++ b/contract/auth-contract.json @@ -1,31 +1,60 @@ { - "description": "Fixtures that the Go, Node and Python auth helpers must agree on. Each runtime's test suite loads this file and checks its own column; a value that differs between runtimes is a known divergence (Q-008) and is written down here rather than hidden. Change a value only together with the code that changes the behaviour.", + "description": "Fixtures that the Go, Node and Python auth helpers must agree on. Each runtime's test suite loads this file and checks its own column. Change a value only together with the code that changes the behavior.", "password": { "plaintext": "correct horse battery staple", "wrongPassword": "not the right password", "hashes": [ { - "name": "Node, current pbkdf2-sha256 scheme", + "name": "Legacy PBKDF2 scheme with recorded iteration count", "hash": "pbkdf2-sha256$600000$76add00c36dafceac62928d01f706c20$f50eec2591755f169bd151369e41a4e6918c6a2816d19516cc38763bfa63c0ca", "verifies": { - "go": false, + "go": true, "node": true, - "python": false + "python": true }, "needsUpgrade": { - "node": false + "go": true, + "node": true, + "python": true } }, { - "name": "Node, legacy salt:hex at 100000 iterations", + "name": "Legacy salt:hex PBKDF2 at 100000 iterations", "hash": "0123456789abcdef0123456789abcdef:69a26fc4b1624cd29ecc2b2444aa876251575c65deb4af9effbd9eadbd4195c6", "verifies": { - "go": false, + "go": true, "node": true, - "python": false + "python": true }, "needsUpgrade": { - "node": true + "go": true, + "node": true, + "python": true + } + }, + { + "name": "Legacy PBKDF2 password over bcrypt's input limit", + "hash": "0123456789abcdef0123456789abcdef:a8a80395df31b48bfb1dc4fabb6457dc61a50aae0c8d469f618303f0cea367b2", + "password": "legacy:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "wrongPassword": "legacy:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy", + "verifies": { + "go": true, + "node": true, + "python": true + }, + "needsUpgrade": { + "go": true, + "node": true, + "python": true + } + }, + { + "name": "Current bcrypt scheme with cost 12", + "hash": "bcrypt$$2b$12$NExB1DALH97MOTr6ZSUjYOb4gc.2g/uWCqbUX1d/c450damk1A9r2", + "verifies": { + "go": true, + "node": true, + "python": true } }, { @@ -33,11 +62,12 @@ "hash": "bcrypt$$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2", "verifies": { "go": true, - "node": false, + "node": true, "python": true }, "needsUpgrade": { "go": true, + "node": true, "python": true } }, @@ -46,11 +76,12 @@ "hash": "$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2", "verifies": { "go": true, - "node": false, + "node": true, "python": true }, "needsUpgrade": { "go": true, + "node": true, "python": true } }, @@ -86,10 +117,10 @@ "bytes": 73, "accepted": { "go": false, - "node": true, + "node": false, "python": false }, - "note": "bcrypt reads only the first 72 bytes, so Go and Python refuse a longer password; PBKDF2 has no such limit." + "note": "New passwords over 72 bytes are refused. Existing longer PBKDF2 passwords still verify and migrate to the marked bcrypt-sha256 scheme without truncation." } }, "totp": { @@ -129,12 +160,14 @@ "name": "the next step still accepts the previous code", "unix": 1111111139, "code": "081804", + "matchedStep": 37037036, "valid": true }, { "name": "the previous step accepts the next code", "unix": 1111111079, "code": "081804", + "matchedStep": 37037036, "valid": true }, { @@ -321,5 +354,75 @@ "want": "2001:db8::9" } ] + }, + "internalSecret": { + "note": "The SECRET that gates a service's internal routes (X-Internal-Auth). Length counts characters (code points), not bytes. Every runtime reads minLength and placeholders from here.", + "minLength": 16, + "placeholders": [ + "SECRET", + "change-me-to-a-long-random-value" + ], + "cases": [ + { + "name": "unset secret never matches", + "secret": "", + "provided": "", + "matches": false + }, + { + "name": "missing header never matches", + "secret": "0123456789abcdef", + "provided": "", + "matches": false + }, + { + "name": "secret one character under the minimum never matches", + "secret": "0123456789abcde", + "provided": "0123456789abcde", + "matches": false + }, + { + "name": "secret at the minimum matches itself", + "secret": "0123456789abcdef", + "provided": "0123456789abcdef", + "matches": true + }, + { + "name": "a prefix of the secret does not match", + "secret": "0123456789abcdef", + "provided": "0123456789abcde", + "matches": false + }, + { + "name": "comparison is exact", + "secret": "0123456789abcdef", + "provided": "0123456789abcdeF", + "matches": false + }, + { + "name": "length counts characters, not bytes", + "secret": "éééééééééééééééé", + "provided": "éééééééééééééééé", + "matches": true + }, + { + "name": "fifteen multibyte characters are too short", + "secret": "ééééééééééééééé", + "provided": "ééééééééééééééé", + "matches": false + }, + { + "name": "the example placeholder never matches", + "secret": "change-me-to-a-long-random-value", + "provided": "change-me-to-a-long-random-value", + "matches": false + }, + { + "name": "the bare variable name never matches", + "secret": "SECRET", + "provided": "SECRET", + "matches": false + } + ] } } diff --git a/package-lock.json b/package-lock.json index 5a31987..e133d5f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2491,6 +2491,15 @@ "node": "18 || 20 || >=22" } }, + "node_modules/bcryptjs": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz", + "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==", + "license": "BSD-3-Clause", + "bin": { + "bcrypt": "bin/bcrypt" + } + }, "node_modules/better-path-resolve": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/better-path-resolve/-/better-path-resolve-1.0.0.tgz", @@ -5482,6 +5491,7 @@ "version": "0.1.1", "license": "MIT", "dependencies": { + "bcryptjs": "^3.0.3", "pg": "^8.17.2" }, "engines": { diff --git a/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java index 6b19ee5..3cc5f45 100644 --- a/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java +++ b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java @@ -13,7 +13,6 @@ public final class Totp { private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; private static final int SECRET_BYTES = 20; private static final int PERIOD_SECONDS = 30; - private static final int WINDOW = 1; private static final int DIGITS = 6; private static final SecureRandom RANDOM = new SecureRandom(); @@ -43,22 +42,28 @@ public final class Totp { } public static boolean verify(String secret, String token, long nowMillis) { + return verifyStep(secret, token, nowMillis) >= 0; + } + + /** Returns the matching 30-second step, or {@code -1} when no code matches. */ + public static long verifyStep(String secret, String token, long nowMillis) { String normalizedSecret = normalizeSecret(secret); String normalizedToken = token == null ? "" : token.trim(); if (normalizedSecret.isEmpty() || !normalizedToken.matches("\\d{" + DIGITS + "}")) { - return false; + return -1; } byte[] key; try { key = decodeBase32(normalizedSecret); } catch (IllegalArgumentException ex) { - return false; + return -1; } if (key.length == 0) { - return false; + return -1; } long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L); - for (long offset = -WINDOW; offset <= WINDOW; offset++) { + // Prefer the current step if a six-digit collision occurs in the window. + for (long offset : new long[] {0, -1, 1}) { if (counter + offset < 0) { continue; } @@ -80,13 +85,13 @@ public final class Totp { String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000); if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII), normalizedToken.getBytes(StandardCharsets.US_ASCII))) { - return true; + return counter + offset; } } catch (Exception ex) { - return false; + return -1; } } - return false; + return -1; } private static String normalizeSecret(String value) { diff --git a/packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/TotpTest.java b/packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/TotpTest.java index 04f3c2f..f0724ad 100644 --- a/packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/TotpTest.java +++ b/packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/TotpTest.java @@ -15,6 +15,7 @@ class TotpTest { void verifyAcceptsTheRfc6238Vectors() { // The RFC lists 8-digit codes; these are their last six digits. assertTrue(Totp.verify(RFC_SECRET, "287082", 59_000L)); + assertEquals(1L, Totp.verifyStep(RFC_SECRET, "287082", 59_000L)); assertTrue(Totp.verify(RFC_SECRET, "081804", 1_111_111_109_000L)); assertTrue(Totp.verify(RFC_SECRET, "050471", 1_111_111_111_000L)); assertTrue(Totp.verify(RFC_SECRET, "005924", 1_234_567_890_000L)); diff --git a/packages/node-backend/package.json b/packages/node-backend/package.json index d9f3551..d007303 100644 --- a/packages/node-backend/package.json +++ b/packages/node-backend/package.json @@ -19,6 +19,7 @@ "./package.json": "./package.json" }, "dependencies": { + "bcryptjs": "^3.0.3", "pg": "^8.17.2" }, "scripts": { diff --git a/packages/node-backend/src/auth.js b/packages/node-backend/src/auth.js index 6ce9beb..b0d1527 100644 --- a/packages/node-backend/src/auth.js +++ b/packages/node-backend/src/auth.js @@ -1,16 +1,20 @@ import crypto from 'node:crypto'; import { promisify } from 'node:util'; +import bcrypt from 'bcryptjs'; +import { verifyTotpStep } from './totp.js'; 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. +// Node's old formats remain readable so successful logins can migrate them. const LEGACY_PASSWORD_ITERATIONS = 100000; -const PASSWORD_ITERATIONS = 600000; +const MAX_PBKDF2_ITERATIONS = 10000000; const PASSWORD_KEY_LENGTH = 32; const PASSWORD_DIGEST = 'sha256'; const PASSWORD_FORMAT = 'pbkdf2-sha256'; +const BCRYPT_SCHEME = 'bcrypt$'; +const BCRYPT_SHA256_SCHEME = 'bcrypt-sha256$'; +const BCRYPT_ROUNDS = 12; +const BCRYPT_MAX_PASSWORD_BYTES = 72; const LEGACY_PASSWORD_PATTERN = /^[0-9a-f]+:[0-9a-f]+$/; export const RESET_CODE_TTL_MS = 5 * 60 * 1000; export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' }); @@ -38,6 +42,7 @@ CREATE TABLE IF NOT EXISTS auth_users ( role TEXT NOT NULL DEFAULT 'user', totp_secret TEXT NOT NULL DEFAULT '', totp_enabled BOOLEAN NOT NULL DEFAULT FALSE, + last_used_step BIGINT NOT NULL DEFAULT -1, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); @@ -45,6 +50,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT ''; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user'; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT ''; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); UPDATE auth_users SET role = 'superadmin' @@ -100,38 +106,47 @@ function assertPasswordLength(password) { if (typeof password !== 'string' || password.length < 8) { throw new Error('Password must be at least 8 characters'); } + if (Buffer.byteLength(password, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) { + throw new Error(`Password must be at most ${BCRYPT_MAX_PASSWORD_BYTES} bytes`); + } } -function encodePasswordHash(salt, hash, iterations) { - 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) { +function parsePbkdf2Hash(stored) { const text = String(stored); + let iterations = LEGACY_PASSWORD_ITERATIONS; + let salt; + let expected; 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 }; + [, iterations, salt, expected] = parts; + iterations = Number(iterations); + } else if (LEGACY_PASSWORD_PATTERN.test(text)) { + [salt, expected] = text.split(':'); + } else { + return null; } + if (!/^[0-9a-f]{32}$/.test(salt) || !/^[0-9a-f]{64}$/.test(expected)) return null; + if (!Number.isSafeInteger(iterations) || iterations < 1 || iterations > MAX_PBKDF2_ITERATIONS) return null; + return { iterations, salt, expected }; +} + +function parseBcryptHash(stored) { + const text = String(stored); + if (text.startsWith(BCRYPT_SHA256_SCHEME)) return { hash: text.slice(BCRYPT_SHA256_SCHEME.length), prehashed: true }; + if (text.startsWith(BCRYPT_SCHEME)) return { hash: text.slice(BCRYPT_SCHEME.length), prehashed: false }; + if (/^\$2[aby]\$/.test(text)) return { hash: text, prehashed: false, legacy: true }; return null; } -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 validBcryptHash(parsed) { + if (!parsed?.hash) return false; + try { + bcrypt.getRounds(parsed.hash); + return true; + } catch { + return false; + } } function passwordHashMatches(expected, actual) { @@ -140,34 +155,52 @@ function passwordHashMatches(expected, actual) { } /** - * Blocking PBKDF2 hash. Prefer hashPasswordAsync in request handlers, because + * Blocking bcrypt hash. Prefer hashPasswordAsync in request handlers, because * this call holds the event loop for the whole derivation. */ -export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) { +export function hashPassword(password) { 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); + return BCRYPT_SCHEME + bcrypt.hashSync(password, BCRYPT_ROUNDS); } -/** Non-blocking variant of hashPassword with the same output format. */ -export async function hashPasswordAsync(password, { iterations = PASSWORD_ITERATIONS } = {}) { +/** Non-blocking variant of hashPassword with the same bcrypt format. */ +export async function hashPasswordAsync(password) { assertPasswordLength(password); - return derivePasswordHashAsync(password, iterations); + return BCRYPT_SCHEME + await bcrypt.hash(password, BCRYPT_ROUNDS); } -// The length rule belongs to user-facing hashing. Upgrading an old hash must -// 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); +// A legacy PBKDF2 password can exceed bcrypt's 72-byte input limit. Preserve +// the full password by hashing its UTF-8 bytes before bcrypt and marking that +// representation explicitly in the stored scheme. +function bcryptInputForLegacyPassword(password) { + const text = String(password); + if (Buffer.byteLength(text, 'utf8') <= BCRYPT_MAX_PASSWORD_BYTES) { + return { scheme: BCRYPT_SCHEME, input: text }; + } + return { + scheme: BCRYPT_SHA256_SCHEME, + input: crypto.createHash('sha256').update(text, 'utf8').digest('hex'), + }; +} + +async function derivePasswordHashAsync(password) { + const { scheme, input } = bcryptInputForLegacyPassword(password); + return scheme + await bcrypt.hash(input, BCRYPT_ROUNDS); } /** Blocking verify. Prefer verifyPasswordAsync in request handlers. */ export function verifyPassword(password, stored) { try { - const parsed = usablePasswordHash(stored); + const bcryptHash = parseBcryptHash(stored); + if (bcryptHash) { + if (!validBcryptHash(bcryptHash)) return false; + const input = bcryptHash.prehashed + ? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex') + : String(password); + if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false; + return bcrypt.compareSync(input, bcryptHash.hash); + } + const parsed = parsePbkdf2Hash(stored); if (!parsed) return false; const actual = crypto.pbkdf2Sync(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST); return passwordHashMatches(parsed.expected, actual); @@ -179,7 +212,16 @@ export function verifyPassword(password, stored) { /** Non-blocking variant of verifyPassword. */ export async function verifyPasswordAsync(password, stored) { try { - const parsed = usablePasswordHash(stored); + const bcryptHash = parseBcryptHash(stored); + if (bcryptHash) { + if (!validBcryptHash(bcryptHash)) return false; + const input = bcryptHash.prehashed + ? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex') + : String(password); + if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false; + return await bcrypt.compare(input, bcryptHash.hash); + } + const parsed = parsePbkdf2Hash(stored); if (!parsed) return false; const actual = await pbkdf2(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST); return passwordHashMatches(parsed.expected, actual); @@ -189,12 +231,15 @@ export async function verifyPasswordAsync(password, stored) { } /** - * True when a stored hash should be rewritten after a successful login: a - * legacy `salt:hex` hash, or a PBKDF2 hash below PASSWORD_ITERATIONS. + * True when a stored hash should be rewritten after a successful login. */ export function passwordHashNeedsUpgrade(stored) { - const parsed = parsePasswordHash(stored); - return !parsed || parsed.legacy || parsed.iterations < PASSWORD_ITERATIONS; + const bcryptHash = parseBcryptHash(stored); + if (bcryptHash) { + if (!validBcryptHash(bcryptHash)) return true; + return Boolean(bcryptHash.legacy) || bcrypt.getRounds(bcryptHash.hash) < BCRYPT_ROUNDS; + } + return true; } /** @@ -210,7 +255,7 @@ export async function verifyAndUpgradePasswordAsync(password, stored) { if (!passwordHashNeedsUpgrade(stored)) { return { valid: true, upgradedHash: null }; } - return { valid: true, upgradedHash: await derivePasswordHashAsync(password, PASSWORD_ITERATIONS) }; + return { valid: true, upgradedHash: await derivePasswordHashAsync(password) }; } export function createSessionToken() { @@ -412,10 +457,10 @@ export class AuthStore { async getTotpState(userId) { const result = await this.database.query( - 'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled FROM auth_users WHERE id = $1', + 'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled, COALESCE(last_used_step, -1) AS last_used_step FROM auth_users WHERE id = $1', [userId], ); - return result.rows[0] || { secret: '', enabled: false }; + return result.rows[0] || { secret: '', enabled: false, last_used_step: -1 }; } /** @@ -425,7 +470,7 @@ export class AuthStore { */ async setTotpSecret(userId, secret) { const result = await this.database.query( - 'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled', + 'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled', [secret, userId], ); if (result.rowCount === 0 && (await this.getTotpState(userId)).enabled) { @@ -433,16 +478,33 @@ export class AuthStore { } } - async enableTotp(userId) { - await this.database.query( - "UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''", - [userId], + async enableTotp(userId, token, now = Date.now()) { + const state = await this.getTotpState(userId); + if (!state.secret || state.enabled) return false; + const step = verifyTotpStep(state.secret, token, now); + if (step === null) return false; + const result = await this.database.query( + "UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1", + [step, userId, state.secret], ); + return result.rowCount === 1; + } + + async consumeTotpCode(userId, token, now = Date.now()) { + const state = await this.getTotpState(userId); + if (!state.secret || !state.enabled) return false; + const step = verifyTotpStep(state.secret, token, now); + if (step === null) return false; + const result = await this.database.query( + 'UPDATE auth_users SET last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1', + [step, userId, state.secret], + ); + return result.rowCount === 1; } async disableTotp(userId) { await this.database.query( - "UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1", + "UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1", [userId], ); } diff --git a/packages/node-backend/src/coreconfig.js b/packages/node-backend/src/coreconfig.js index 554c656..9eae4e6 100644 --- a/packages/node-backend/src/coreconfig.js +++ b/packages/node-backend/src/coreconfig.js @@ -60,16 +60,38 @@ export class Info { } } +/** Shortest SECRET a service accepts for its internal routes. */ +export const MIN_INTERNAL_SECRET_LENGTH = 16; + /** - * True when the X-Internal-Auth value equals the configured secret. An unset - * or empty secret never matches, and the comparison is constant-time. + * Placeholders from .env.example files and the bare variable name. They are + * public, so they never gate a route. + */ +export const EXAMPLE_INTERNAL_SECRETS = new Set(['SECRET', 'change-me-to-a-long-random-value']); + +/** + * True when the configured secret is strong enough to gate an internal route: + * at least MIN_INTERNAL_SECRET_LENGTH characters and not an example + * placeholder. Length counts characters, as the Python and Go helpers do. + * @param {unknown} secret + * @returns {boolean} + */ +export function internalSecretUsable(secret) { + const value = String(secret ?? ''); + return [...value].length >= MIN_INTERNAL_SECRET_LENGTH && !EXAMPLE_INTERNAL_SECRETS.has(value); +} + +/** + * True when the X-Internal-Auth value equals the configured secret. A secret + * that is not usable (see internalSecretUsable) never matches, and the + * comparison is constant-time. * @param {unknown} provided * @param {unknown} secret * @returns {boolean} */ export function internalSecretMatches(provided, secret) { - const expected = Buffer.from(String(secret ?? '')); - if (expected.length === 0) return false; + if (!internalSecretUsable(secret)) return false; + const expected = Buffer.from(String(secret)); const actual = Buffer.from(String(provided ?? '')); return expected.length === actual.length && crypto.timingSafeEqual(expected, actual); } diff --git a/packages/node-backend/src/index.js b/packages/node-backend/src/index.js index 70f9cfa..30f1691 100644 --- a/packages/node-backend/src/index.js +++ b/packages/node-backend/src/index.js @@ -33,11 +33,15 @@ export { generateTotpSecret, totpProvisioningUri, verifyTotp, + verifyTotpStep, } from './totp.js'; export { runMigrations } from './migrate.js'; export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js'; export { + EXAMPLE_INTERNAL_SECRETS, Info as CoreConfigInfo, + MIN_INTERNAL_SECRET_LENGTH, Store as CoreConfigStore, internalSecretMatches, + internalSecretUsable, } from './coreconfig.js'; diff --git a/packages/node-backend/src/totp.js b/packages/node-backend/src/totp.js index f9ec2ba..1c3740b 100644 --- a/packages/node-backend/src/totp.js +++ b/packages/node-backend/src/totp.js @@ -24,19 +24,24 @@ export function totpProvisioningUri(issuer, account, secret) { } export function verifyTotp(secret, token, now = Date.now()) { + return verifyTotpStep(secret, token, now) !== null; +} + +export function verifyTotpStep(secret, token, now = Date.now()) { const normalizedSecret = normalizeSecret(secret); const normalizedToken = normalizeToken(token); - if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return false; + if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return null; let key; try { key = decodeBase32(normalizedSecret); } catch { - return false; + return null; } - if (key.length === 0) return false; + if (key.length === 0) return null; const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS); - for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset += 1) { + // Prefer the current step if a six-digit collision occurs in the window. + for (const offset of [0, -1, 1]) { if (period + offset < 0) continue; const counter = Buffer.alloc(8); counter.writeBigUInt64BE(BigInt(period + offset)); @@ -47,9 +52,9 @@ export function verifyTotp(secret, token, now = Date.now()) { | (digest[index + 2] << 8) | digest[index + 3]; const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0'); - if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return true; + if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return period + offset; } - return false; + return null; } function normalizeSecret(value) { diff --git a/packages/node-backend/test/auth.test.js b/packages/node-backend/test/auth.test.js index ef573fc..d812308 100644 --- a/packages/node-backend/test/auth.test.js +++ b/packages/node-backend/test/auth.test.js @@ -12,7 +12,7 @@ import { verifyPassword, verifyPasswordAsync, } from '../src/auth.js'; -import { totpProvisioningUri, verifyTotp } from '../src/totp.js'; +import { totpProvisioningUri, verifyTotp, verifyTotpStep } from '../src/totp.js'; test('reset codes are printed, case-insensitive, expiring, and one-time', () => { const messages = []; @@ -38,9 +38,9 @@ test('password hashes verify and reject a different password', () => { assert.equal(verifyPassword('wrong password', hash), false); }); -test('new password hashes record their iteration count', () => { +test('new password hashes use the shared bcrypt scheme and cost', () => { const hash = hashPassword('correct horse battery staple'); - assert.match(hash, /^pbkdf2-sha256\$600000\$[0-9a-f]{32}\$[0-9a-f]{64}$/); + assert.match(hash, /^bcrypt\$\$2b\$12\$/); }); test('legacy salt:hex hashes still verify at the original iteration count', () => { @@ -55,16 +55,16 @@ test('a hash with a malformed iteration count never verifies', () => { assert.equal(verifyPassword('correct horse battery staple', 'pbkdf2-sha256$x$aa$bb'), false); }); -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\$/); +test('async password helpers produce and verify the same bcrypt format', async () => { + const hash = await hashPasswordAsync('correct horse battery staple'); + assert.match(hash, /^bcrypt\$\$2b\$12\$/); 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']) { + for (const stored of ['', '$2b$12$abc', 'bcrypt$$2a$12$abc', 'bcrypt-sha256$$2b$12$abc', 'pbkdf2-sha256$600000$00$00$extra']) { assert.equal(verifyPassword('correct horse battery staple', stored), false); } assert.equal(passwordHashNeedsUpgrade('$2b$12$abc'), true); @@ -77,15 +77,27 @@ test('a legacy salt:hex hash is rewritten in the current scheme after a successf const result = await verifyAndUpgradePasswordAsync('legacy password', legacy); assert.equal(result.valid, true); - assert.match(result.upgradedHash, /^pbkdf2-sha256\$600000\$/); + assert.match(result.upgradedHash, /^bcrypt\$\$2b\$12\$/); assert.equal(passwordHashNeedsUpgrade(result.upgradedHash), false); assert.equal(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 }); +test('a long legacy PBKDF2 password is migrated without truncation', async () => { + const longPassword = 'a'.repeat(80); + const salt = crypto.randomBytes(16).toString('hex'); + const legacy = `pbkdf2-sha256$600000$${salt}$${crypto.pbkdf2Sync(longPassword, salt, 600000, 32, 'sha256').toString('hex')}`; + const result = await verifyAndUpgradePasswordAsync(longPassword, legacy); + assert.equal(result.valid, true); + assert.match(result.upgradedHash, /^bcrypt-sha256\$\$2b\$12\$/); + assert.equal(await verifyPasswordAsync(longPassword, result.upgradedHash), true); + assert.equal(await verifyPasswordAsync(`${longPassword}x`, result.upgradedHash), false); +}); + +test('a low-cost bcrypt hash is rewritten, and a short legacy password still upgrades', async () => { + const bcrypt = (await import('bcryptjs')).default; + const low = `bcrypt$${await bcrypt.hash('correct horse battery staple', 4)}`; const lowResult = await verifyAndUpgradePasswordAsync('correct horse battery staple', low); - assert.match(lowResult.upgradedHash, /^pbkdf2-sha256\$600000\$/); + assert.match(lowResult.upgradedHash, /^bcrypt\$\$2b\$12\$/); const salt = crypto.randomBytes(16).toString('hex'); const shortLegacy = `${salt}:${crypto.pbkdf2Sync('short', salt, 100000, 32, 'sha256').toString('hex')}`; @@ -95,7 +107,7 @@ test('a hash below the current iteration count is rewritten, and a short legacy }); test('a wrong password neither verifies nor upgrades, and a current hash is not rewritten', async () => { - const hash = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 }); + const hash = await hashPasswordAsync('correct horse battery staple'); assert.deepEqual(await verifyAndUpgradePasswordAsync('wrong password', hash), { valid: false, upgradedHash: null }); const current = await hashPasswordAsync('correct horse battery staple'); @@ -117,6 +129,7 @@ test('TOTP verifies RFC 6238 SHA-1 vectors', () => { ]; for (const [seconds, code] of vectors) { assert.equal(verifyTotp(secret, code, seconds * 1000), true); + assert.equal(verifyTotpStep(secret, code, seconds * 1000), Math.floor(seconds / 30)); } assert.match(totpProvisioningUri('Example App', 'admin@example.com', secret), /^otpauth:\/\/totp\//); }); diff --git a/packages/node-backend/test/authstore.test.js b/packages/node-backend/test/authstore.test.js index ba8e1a5..ba3490c 100644 --- a/packages/node-backend/test/authstore.test.js +++ b/packages/node-backend/test/authstore.test.js @@ -10,7 +10,7 @@ function fakeDatabase({ rowCount = 1, totpEnabled = false, rowsByCondition = {} async query(text, params = []) { queries.push({ text, params }); if (text.includes('totp_enabled, false) AS enabled')) { - return { rows: [{ secret: 'S', enabled: totpEnabled }], rowCount: 1 }; + return { rows: [{ secret: 'S', enabled: totpEnabled, last_used_step: -1 }], rowCount: 1 }; } for (const [condition, row] of Object.entries(rowsByCondition)) { if (text.includes(condition)) return { rows: [row], rowCount: 1 }; @@ -27,6 +27,7 @@ test('ensureSchema requests the case-insensitive username index, only while no c assert.match(statements, /auth_users_username_lower_idx/); assert.match(statements, /lower\(username\)/); assert.match(statements, /HAVING count\(\*\) > 1/); + assert.match(statements, /ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1/); }); test('setTotpSecret refuses to replace an enabled second factor', async () => { @@ -41,6 +42,39 @@ test('setTotpSecret stores a pending secret while TOTP is off, and ignores an un await new AuthStore(fakeDatabase({ rowCount: 0 })).setTotpSecret(2, 'NEWSECRET'); }); +test('TOTP enrollment records its code step and a replay is rejected atomically', async () => { + const state = { secret: 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', enabled: false, last_used_step: -1 }; + const database = { + async query(text, params = []) { + if (text.startsWith('SELECT COALESCE(totp_secret')) { + return { rows: [{ ...state }], rowCount: 1 }; + } + const [step, , secret] = params; + if (text.includes('SET totp_enabled = true')) { + if (!state.enabled && secret === state.secret && state.last_used_step < step) { + state.enabled = true; + state.last_used_step = step; + return { rows: [], rowCount: 1 }; + } + return { rows: [], rowCount: 0 }; + } + if (text.includes('SET last_used_step = $1')) { + if (state.enabled && secret === state.secret && state.last_used_step < step) { + state.last_used_step = step; + return { rows: [], rowCount: 1 }; + } + return { rows: [], rowCount: 0 }; + } + throw new Error(`unexpected query: ${text}`); + }, + }; + const store = new AuthStore(database); + assert.equal(await store.enableTotp(1, '287082', 59000), true); + assert.equal(state.last_used_step, 1); + assert.equal(await store.consumeTotpCode(1, '287082', 59000), false); + assert.equal(state.last_used_step, 1); +}); + test('credential writes refuse an empty hash and a username containing @', async () => { const database = fakeDatabase(); const store = new AuthStore(database); diff --git a/packages/node-backend/test/contract.test.js b/packages/node-backend/test/contract.test.js index c7b3077..01d8c6b 100644 --- a/packages/node-backend/test/contract.test.js +++ b/packages/node-backend/test/contract.test.js @@ -2,7 +2,12 @@ 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'; +import { verifyTotp, verifyTotpStep } from '../src/totp.js'; +import { + EXAMPLE_INTERNAL_SECRETS, + MIN_INTERNAL_SECRET_LENGTH, + internalSecretMatches, +} from '../src/coreconfig.js'; // The Go, Node and Python auth helpers load the same fixtures; see "description" in the file. const contractUrl = new URL('../../../contract/auth-contract.json', import.meta.url); @@ -12,14 +17,16 @@ const skip = contract ? false : 'contract/auth-contract.json is not part of this test('password hashes verify as the contract says for Node', { skip }, async () => { 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`); + const password = entry.password ?? plaintext; + const rejectedPassword = entry.wrongPassword ?? wrongPassword; + assert.equal(verifyPassword(password, entry.hash), entry.verifies.node, entry.name); + assert.equal(verifyPassword(rejectedPassword, entry.hash), false, `${entry.name}: wrong password`); if ('node' in (entry.needsUpgrade ?? {})) { assert.equal(passwordHashNeedsUpgrade(entry.hash), entry.needsUpgrade.node, `${entry.name}: needs upgrade`); - const { valid, upgradedHash } = await verifyAndUpgradePasswordAsync(plaintext, entry.hash); + const { valid, upgradedHash } = await verifyAndUpgradePasswordAsync(password, entry.hash); assert.equal(valid, true, `${entry.name}: valid on upgrade`); assert.equal(upgradedHash !== null, entry.needsUpgrade.node, `${entry.name}: upgraded hash`); - if (upgradedHash) assert.equal(verifyPassword(plaintext, upgradedHash), true); + if (upgradedHash) assert.equal(verifyPassword(password, upgradedHash), true); } } }); @@ -28,7 +35,7 @@ test('the password length contract holds for Node', { skip }, () => { const { bytes, accepted } = contract.password.tooLongToHash; let didHash = true; try { - hashPassword('a'.repeat(bytes), { iterations: 1000 }); + hashPassword('a'.repeat(bytes)); } catch { didHash = false; } @@ -39,5 +46,20 @@ 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); + if (entry.valid) + assert.equal( + verifyTotpStep(secret, entry.code, entry.unix * 1000), + entry.matchedStep ?? Math.floor(entry.unix / 30), + entry.name, + ); + } +}); + +test('the internal secret gate matches the contract for Node', { skip }, () => { + const rule = contract.internalSecret; + assert.equal(MIN_INTERNAL_SECRET_LENGTH, rule.minLength); + assert.deepEqual([...EXAMPLE_INTERNAL_SECRETS].sort(), [...rule.placeholders].sort()); + for (const entry of rule.cases) { + assert.equal(internalSecretMatches(entry.provided, entry.secret), entry.matches, entry.name); } }); diff --git a/packages/node-backend/test/coreconfig.test.js b/packages/node-backend/test/coreconfig.test.js index 03fa609..3bcf476 100644 --- a/packages/node-backend/test/coreconfig.test.js +++ b/packages/node-backend/test/coreconfig.test.js @@ -1,6 +1,13 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { Info, Store, internalSecretMatches } from '../src/coreconfig.js'; +import { + EXAMPLE_INTERNAL_SECRETS, + Info, + MIN_INTERNAL_SECRET_LENGTH, + Store, + internalSecretMatches, + internalSecretUsable, +} from '../src/coreconfig.js'; test('store seeds from the fallback Info', () => { const store = new Store({ authGuardUrl: 'http://auth.example.com', carrierNodeUrl: 'http://carrier.example.com' }); @@ -49,13 +56,30 @@ test('Info.fromJSON/toJSON round-trip the wire shape', () => { assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com'); }); +const LONG_SECRET = 'shared-secret-value'; + 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); + assert.equal(internalSecretMatches(undefined, LONG_SECRET), false); + assert.equal(internalSecretMatches('shared-secret-valuE', LONG_SECRET), false); + assert.equal(internalSecretMatches(LONG_SECRET, LONG_SECRET), true); +}); + +test('internal secret check refuses a short or placeholder secret', () => { + const short = 'x'.repeat(MIN_INTERNAL_SECRET_LENGTH - 1); + assert.equal(internalSecretMatches(short, short), false); + for (const placeholder of EXAMPLE_INTERNAL_SECRETS) { + assert.equal(internalSecretMatches(placeholder, placeholder), false, placeholder); + } +}); + +test('internal secret usability needs the minimum length and no placeholder', () => { + assert.equal(internalSecretUsable('x'.repeat(MIN_INTERNAL_SECRET_LENGTH - 1)), false); + assert.equal(internalSecretUsable('x'.repeat(MIN_INTERNAL_SECRET_LENGTH)), true); + assert.equal(internalSecretUsable('change-me-to-a-long-random-value'), false); + assert.equal(internalSecretUsable(undefined), false); }); test('set rejects a URL that is not an http or https URL and changes nothing', () => { diff --git a/packages/python-backend/README.md b/packages/python-backend/README.md index 03df748..31454c6 100644 --- a/packages/python-backend/README.md +++ b/packages/python-backend/README.md @@ -129,6 +129,11 @@ async def push_core_services(request): return {"ok": True, "info": info.to_json()} ``` +`internal_secret_matches` also refuses a SECRET shorter than `MIN_INTERNAL_SECRET_LENGTH` +(16 characters) or equal to an example placeholder (`EXAMPLE_INTERNAL_SECRETS`), so every +internal route gated by it rejects all callers until the secret is set properly. Call +`internal_secret_usable(SECRET)` at startup to log a warning for that case. + ## `authproxy`: a ready-to-mount FastAPI router (optional) Wiring up `authclient` still leaves each service reimplementing the same diff --git a/packages/python-backend/src/shared_backend/__init__.py b/packages/python-backend/src/shared_backend/__init__.py index 9315e14..381a86e 100644 --- a/packages/python-backend/src/shared_backend/__init__.py +++ b/packages/python-backend/src/shared_backend/__init__.py @@ -28,12 +28,12 @@ from .authclient import ( token_from_request, ) from .config import DatabaseConfig, database_url_from_env +from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches, internal_secret_usable from .coreconfig import Info as CoreConfigInfo from .coreconfig import Store as CoreConfigStore -from .coreconfig import internal_secret_matches from .postgres import Database from .tokens import hash_token, new_session_token -from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp +from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp, verify_totp_step __all__ = [ "AuthStore", @@ -47,6 +47,8 @@ __all__ = [ "CoreConfigInfo", "CoreConfigStore", "internal_secret_matches", + "internal_secret_usable", + "MIN_INTERNAL_SECRET_LENGTH", "ROLE_ADMIN", "ROLE_SUPERADMIN", "ROLE_USER", @@ -70,4 +72,5 @@ __all__ = [ "verify_password", "verify_password_async", "verify_totp", + "verify_totp_step", ] diff --git a/packages/python-backend/src/shared_backend/auth.py b/packages/python-backend/src/shared_backend/auth.py index 99555e7..c2e28d4 100644 --- a/packages/python-backend/src/shared_backend/auth.py +++ b/packages/python-backend/src/shared_backend/auth.py @@ -3,6 +3,9 @@ from __future__ import annotations import asyncio +import hashlib +import hmac +import re import secrets import threading from dataclasses import dataclass @@ -12,6 +15,7 @@ import asyncpg import bcrypt from .postgres import Database +from .totp import verify_totp_step _SCHEMA = """ CREATE TABLE IF NOT EXISTS auth_users ( @@ -22,6 +26,7 @@ CREATE TABLE IF NOT EXISTS auth_users ( role TEXT NOT NULL DEFAULT 'user', totp_secret TEXT NOT NULL DEFAULT '', totp_enabled BOOLEAN NOT NULL DEFAULT FALSE, + last_used_step BIGINT NOT NULL DEFAULT -1, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); @@ -29,6 +34,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT ''; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user'; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT ''; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx @@ -179,7 +185,12 @@ def _validate_credentials(username: str | None, password_hash: str | None) -> No # so a stored value reads "bcrypt$$2b$12$...". Unprefixed bcrypt hashes written # before the prefix still verify and are rewritten on the next successful login. _BCRYPT_SCHEME = "bcrypt$" +_BCRYPT_SHA256_SCHEME = "bcrypt-sha256$" _LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$") +_PBKDF2_SCHEME = "pbkdf2-sha256" +BCRYPT_MAX_PASSWORD_BYTES = 72 +_LEGACY_PBKDF2_ITERATIONS = 100_000 +_MAX_PBKDF2_ITERATIONS = 10_000_000 BCRYPT_ROUNDS = 12 @@ -188,9 +199,9 @@ def _new_bcrypt_hash(password: str) -> str: 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 +# bcrypt reads only the first 72 bytes, so new passwords are refused above this limit. Legacy +# PBKDF2 passwords over the limit are migrated with an explicitly marked SHA-256 pre-hash. +MAX_PASSWORD_BYTES = BCRYPT_MAX_PASSWORD_BYTES def hash_password(password: str) -> str: @@ -209,24 +220,75 @@ def _bcrypt_string_of(stored_hash: str) -> str | None: return None +def _bcrypt_hash_info(stored_hash: str) -> tuple[str, bool, bool] | None: + if stored_hash.startswith(_BCRYPT_SHA256_SCHEME): + return stored_hash[len(_BCRYPT_SHA256_SCHEME) :], True, False + if stored_hash.startswith(_BCRYPT_SCHEME): + return stored_hash[len(_BCRYPT_SCHEME) :], False, False + if stored_hash.startswith(_LEGACY_BCRYPT_PREFIXES): + return stored_hash, False, True + return None + + +def _pbkdf2_hash_info(stored_hash: str) -> tuple[int, str, str] | None: + if stored_hash.startswith(f"{_PBKDF2_SCHEME}$"): + parts = stored_hash.split("$") + if len(parts) != 4: + return None + _, raw_iterations, salt, expected = parts + try: + iterations = int(raw_iterations) + except ValueError: + return None + elif re.fullmatch(r"[0-9a-f]+:[0-9a-f]+", stored_hash): + salt, expected = stored_hash.split(":", 1) + iterations = _LEGACY_PBKDF2_ITERATIONS + else: + return None + if len(salt) != 32 or len(expected) != 64 or not (1 <= iterations <= _MAX_PBKDF2_ITERATIONS): + return None + return iterations, salt, expected + + +def _new_bcrypt_sha256_hash(password: str) -> str: + digest = hashlib.sha256(password.encode("utf-8")).hexdigest() + hashed = bcrypt.hashpw(digest.encode("ascii"), bcrypt.gensalt(rounds=BCRYPT_ROUNDS)) + return _BCRYPT_SHA256_SCHEME + hashed.decode("utf-8") + + def verify_password(password: str, stored_hash: str) -> bool: - bcrypt_hash = _bcrypt_string_of(stored_hash) - if bcrypt_hash is None: - return False - try: - return bcrypt.checkpw(password.encode("utf-8"), bcrypt_hash.encode("utf-8")) - except (ValueError, TypeError): + bcrypt_info = _bcrypt_hash_info(stored_hash) + if bcrypt_info is not None: + bcrypt_hash, prehashed, _ = bcrypt_info + raw_password = password.encode("utf-8") + if prehashed: + raw_password = hashlib.sha256(raw_password).hexdigest().encode("ascii") + elif len(raw_password) > BCRYPT_MAX_PASSWORD_BYTES: + return False + try: + return bcrypt.checkpw(raw_password, bcrypt_hash.encode("utf-8")) + except (ValueError, TypeError): + return False + + parsed = _pbkdf2_hash_info(stored_hash) + if parsed is None: return False + iterations, salt, expected = parsed + actual = hashlib.pbkdf2_hmac( + "sha256", password.encode("utf-8"), salt.encode("ascii"), iterations + ) + return hmac.compare_digest(actual.hex(), expected) def password_hash_needs_upgrade(stored_hash: str) -> bool: - """True for an unprefixed legacy hash, or a bcrypt cost below BCRYPT_ROUNDS.""" - if not stored_hash.startswith(_BCRYPT_SCHEME): + """True for legacy PBKDF2/bcrypt formats or a bcrypt cost below policy.""" + bcrypt_info = _bcrypt_hash_info(stored_hash) + if bcrypt_info is None: return True - # The bcrypt string after the prefix is "$2b$$". - parts = stored_hash[len(_BCRYPT_SCHEME) :].split("$") + bcrypt_hash, _, legacy = bcrypt_info + parts = bcrypt_hash.split("$") try: - return int(parts[2]) < BCRYPT_ROUNDS + return legacy or int(parts[2]) < BCRYPT_ROUNDS except (IndexError, ValueError): return True @@ -243,6 +305,8 @@ def verify_and_upgrade_password(password: str, stored_hash: str) -> tuple[bool, if not password_hash_needs_upgrade(stored_hash): return True, None # The length rule applies when a password is first set, not when an old hash is upgraded. + if len(password.encode("utf-8")) > BCRYPT_MAX_PASSWORD_BYTES: + return True, _new_bcrypt_sha256_hash(password) return True, _new_bcrypt_hash(password) @@ -431,18 +495,19 @@ class AuthStore: async def get_totp_state(self, user_id: int) -> dict[str, object]: row = await self.database.fetchrow( - "SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled " + "SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled, " + "COALESCE(last_used_step, -1) AS last_used_step " "FROM auth_users WHERE id = $1", user_id, ) - return dict(row) if row else {"secret": "", "enabled": False} + return dict(row) if row else {"secret": "", "enabled": False, "last_used_step": -1} async def set_totp_secret(self, user_id: int, secret: str) -> None: """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, last_used_step = -1, " "updated_at = now() WHERE id = $2 AND NOT totp_enabled", secret, user_id, @@ -450,16 +515,41 @@ class AuthStore: 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: - await self.database.execute( - "UPDATE auth_users SET totp_enabled = true, updated_at = now() " - "WHERE id = $1 AND totp_secret <> ''", + async def enable_totp(self, user_id: int, token: str, now: float | None = None) -> bool: + state = await self.get_totp_state(user_id) + if not state["secret"] or state["enabled"]: + return False + step = verify_totp_step(str(state["secret"]), token, now) + if step is None: + return False + status = await self.database.execute( + "UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() " + "WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1", + step, user_id, + state["secret"], ) + return status == "UPDATE 1" + + async def consume_totp_code(self, user_id: int, token: str, now: float | None = None) -> bool: + state = await self.get_totp_state(user_id) + if not state["secret"] or not state["enabled"]: + return False + step = verify_totp_step(str(state["secret"]), token, now) + if step is None: + return False + status = await self.database.execute( + "UPDATE auth_users SET last_used_step = $1, updated_at = now() " + "WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1", + step, + user_id, + state["secret"], + ) + return status == "UPDATE 1" async def disable_totp(self, user_id: int) -> None: await self.database.execute( - "UPDATE auth_users SET totp_secret = '', totp_enabled = false, " + "UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, " "updated_at = now() WHERE id = $1", user_id, ) diff --git a/packages/python-backend/src/shared_backend/authclient.py b/packages/python-backend/src/shared_backend/authclient.py index 5fb4ef2..805006f 100644 --- a/packages/python-backend/src/shared_backend/authclient.py +++ b/packages/python-backend/src/shared_backend/authclient.py @@ -64,11 +64,14 @@ from typing import Any, Mapping DEFAULT_COOKIE_NAME = "auth_session" 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. +# validate() results (positive and negative) and /api/me profiles are reused for this many +# seconds so a burst of requests with one token costs one AuthGuard call. Revocation through +# this client (logout) and token-authenticated writes clear both entries at once; changes made +# directly in AuthGuard may take up to two seconds to reach consumers. VALIDATION_CACHE_TTL = 2.0 MAX_VALIDATION_CACHE_ENTRIES = 10000 +PROFILE_CACHE_TTL = VALIDATION_CACHE_TTL +MAX_PROFILE_CACHE_ENTRIES = MAX_VALIDATION_CACHE_ENTRIES _BEARER_PREFIX = "Bearer " @@ -274,6 +277,7 @@ class AuthClient: self.project_key = (project_key or "").strip().lower() self._validation_lock = threading.Lock() self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {} + self._profile_cache: dict[str, tuple[float, PublicUser]] = {} @staticmethod def _validation_key(token: str) -> str: @@ -307,8 +311,36 @@ class AuthClient: ) def _forget_validation(self, token: str) -> None: + """Clears cached validation and /api/me data for this token.""" with self._validation_lock: - self._validation_cache.pop(self._validation_key(token), None) + key = self._validation_key(token) + self._validation_cache.pop(key, None) + self._profile_cache.pop(key, None) + + def _cached_profile(self, token: str) -> tuple[bool, PublicUser | None]: + key = self._validation_key(token) + with self._validation_lock: + entry = self._profile_cache.get(key) + if entry is None: + return False, None + expires, profile = entry + if time.monotonic() >= expires: + del self._profile_cache[key] + return False, None + return True, profile + + def _cache_profile(self, token: str, profile: PublicUser) -> None: + with self._validation_lock: + if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES: + now = time.monotonic() + for key in [k for k, entry in self._profile_cache.items() if now >= entry[0]]: + del self._profile_cache[key] + if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES: + del self._profile_cache[next(iter(self._profile_cache))] + self._profile_cache[self._validation_key(token)] = ( + time.monotonic() + PROFILE_CACHE_TTL, + profile, + ) def set_base_url(self, base_url: str) -> None: """Atomically replaces the AuthGuard base URL this client calls, @@ -326,6 +358,7 @@ class AuthClient: self.base_url = normalized with self._validation_lock: self._validation_cache.clear() + self._profile_cache.clear() # --- session validation (the original, minimal surface) ---------------- @@ -465,6 +498,9 @@ class AuthClient: message = str(payload.get("error") or f"request failed ({status})") raise APIError(status, message, totp_required=bool(payload.get("totp_required"))) + if token and method.upper() not in {"GET", "HEAD"}: + self._forget_validation(token) + return payload, list(cookies) @staticmethod @@ -533,9 +569,26 @@ class AuthClient: return cookies async def me(self, token: str) -> PublicUser: - """Calls GET /api/me, resolving token to its account.""" - payload, _ = await self._call("GET", "/api/me", token=token) - return self._public_user(payload) + """Calls GET /api/me, resolving token to its account. + + Successful profiles are cached by the SHA-256 token digest for the + same short window as validate(). This keeps protected API calls from + blocking on one AuthGuard round trip each while bounding how long an + external profile change or session revocation can remain stale. + """ + if not self.base_url: + raise AuthClientError("authclient: client has no base URL") + trimmed = (token or "").strip() + if trimmed: + hit, cached = self._cached_profile(trimmed) + if hit: + assert cached is not None + return cached + payload, _ = await self._call("GET", "/api/me", token=trimmed) + profile = self._public_user(payload) + if trimmed: + self._cache_profile(trimmed, profile) + return profile # --- TOTP ------------------------------------------------------------------ diff --git a/packages/python-backend/src/shared_backend/authproxy.py b/packages/python-backend/src/shared_backend/authproxy.py index 84f483c..d37fe8f 100644 --- a/packages/python-backend/src/shared_backend/authproxy.py +++ b/packages/python-backend/src/shared_backend/authproxy.py @@ -56,6 +56,7 @@ from __future__ import annotations import abc import os +from http.cookies import CookieError, SimpleCookie from typing import Any, Callable, Optional from fastapi import APIRouter, Depends, HTTPException, Request, Response @@ -72,6 +73,7 @@ from .authclient import ( forwarded_client_ip, ) from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env +from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches from .ratelimit import AttemptLimiter __all__ = ["ProxyStore", "build_auth_router"] @@ -104,7 +106,10 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf # rather than a generic "internal error" indistinguishable from any other bug. 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 unset, shorter than " + f"{MIN_INTERNAL_SECRET_LENGTH} characters, or an example placeholder." +) ERR_ADMIN_REQUIRED = "Administrator access required." # _LOCAL_PROFILE is the fixed placeholder identity every handler reports when @@ -175,6 +180,8 @@ class UpdateMeRequest(BaseModel): email: str = "" username: str = "" password: str = "" + currentPassword: str = "" + totpToken: str = "" class UpdateAccessRequest(BaseModel): @@ -333,8 +340,30 @@ def build_auth_router( ) def _forward_cookies(response: Response, cookies: list[str]) -> None: - for cookie in cookies: - response.headers.append("set-cookie", cookie) + for header in cookies: + parsed = SimpleCookie() + try: + parsed.load(header) + except CookieError: + continue + for morsel in parsed.values(): + morsel["httponly"] = True + morsel["samesite"] = "lax" + if secure_cookie: + morsel["secure"] = True + response.headers.append("set-cookie", morsel.OutputString()) + + def _temporary_session_token(cookies: list[str]) -> str: + for header in cookies: + parsed = SimpleCookie() + try: + parsed.load(header) + except CookieError: + continue + morsel = parsed.get(cookie_name) + if morsel is not None and morsel.value: + return morsel.value + return "" async def _current_profile( request: Request, client: AuthClient @@ -610,14 +639,42 @@ def build_auth_router( email = _normalize_email(req.email) username = _normalize_username(req.username) password = None + temporary_token = "" if req.password: _validate_password(req.password) + if not req.currentPassword: + raise HTTPException( + status_code=400, + detail="Current password is required to change the password.", + ) + if current.totp_enabled and not req.totpToken.strip(): + raise HTTPException( + status_code=400, + detail="A current authenticator code is required to change the password.", + ) + try: + reauthenticated = await client.login( + current.username, + req.currentPassword, + req.totpToken, + ) + except AuthClientError as exc: + _raise_authguard_error(exc, "Current credentials could not be verified.") + raise # unreachable + temporary_token = _temporary_session_token(reauthenticated.cookies) password = req.password try: - await client.update_managed_user( - token, current.id, username=username, email=email, password=password - ) + try: + await client.update_managed_user( + token, current.id, username=username, email=email, password=password + ) + finally: + if password is not None and temporary_token: + try: + await client.logout(temporary_token) + except AuthClientError: + pass except AuthClientError as exc: _raise_authguard_error(exc, "Profile could not be updated.") raise # unreachable @@ -651,9 +708,8 @@ def build_auth_router( request: Request, store: ProxyStore = Depends(get_store), # noqa: B008 ) -> dict[str, bool]: - if ( - not configured_internal_secret - or request.headers.get("X-Internal-Auth") != configured_internal_secret + if not internal_secret_matches( + request.headers.get("X-Internal-Auth"), configured_internal_secret ): raise HTTPException(status_code=401, detail="internal service authentication required") await store.set_login_required(req.loginRequired) diff --git a/packages/python-backend/src/shared_backend/coreconfig.py b/packages/python-backend/src/shared_backend/coreconfig.py index 04444ac..89bba75 100644 --- a/packages/python-backend/src/shared_backend/coreconfig.py +++ b/packages/python-backend/src/shared_backend/coreconfig.py @@ -25,13 +25,29 @@ from dataclasses import dataclass, field from typing import Callable, Optional from urllib.parse import urlsplit +MIN_INTERNAL_SECRET_LENGTH = 16 +"""Shortest SECRET a service accepts for its internal routes.""" + +EXAMPLE_INTERNAL_SECRETS = frozenset({"SECRET", "change-me-to-a-long-random-value"}) +"""Placeholders from .env.example files and the bare variable name. They are +public, so they never gate a route.""" + + +def internal_secret_usable(secret: Optional[str]) -> bool: + """True when the configured secret is strong enough to gate an internal + route: at least MIN_INTERNAL_SECRET_LENGTH characters and not an example + placeholder. A route whose secret is not usable rejects every caller.""" + value = secret or "" + return len(value) >= MIN_INTERNAL_SECRET_LENGTH and value not in EXAMPLE_INTERNAL_SECRETS + def internal_secret_matches(provided: Optional[str], secret: Optional[str]) -> bool: - """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: + """True when the X-Internal-Auth value equals the configured secret. A + secret that is not usable (see internal_secret_usable) never matches, and + the comparison is constant-time.""" + if not internal_secret_usable(secret): return False + expected = (secret or "").encode("utf-8") return hmac.compare_digest(expected, (provided or "").encode("utf-8")) diff --git a/packages/python-backend/src/shared_backend/totp.py b/packages/python-backend/src/shared_backend/totp.py index 76a5a95..361c411 100644 --- a/packages/python-backend/src/shared_backend/totp.py +++ b/packages/python-backend/src/shared_backend/totp.py @@ -36,19 +36,24 @@ def totp_provisioning_uri(issuer: str, account: str, secret: str) -> str: def verify_totp(secret: str, token: str, now: float | None = None) -> bool: + return verify_totp_step(secret, token, now) is not None + + +def verify_totp_step(secret: str, token: str, now: float | None = None) -> int | None: normalized_secret = _normalize_secret(secret) normalized_token = _normalize_token(token) if not normalized_secret or len(normalized_token) != TOTP_DIGITS: - return False + return None try: key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8)) except (ValueError, binascii.Error): - return False + return None if not key: - return False + return None period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS) - for offset in range(-TOTP_WINDOW, TOTP_WINDOW + 1): + # Prefer the current step if a six-digit collision occurs in the window. + for offset in (0, -1, 1): counter = period + offset if counter < 0: continue @@ -62,8 +67,8 @@ def verify_totp(secret: str, token: str, now: float | None = None) -> bool: ) candidate = f"{value % 1_000_000:06d}" if hmac.compare_digest(candidate, normalized_token): - return True - return False + return counter + return None def _normalize_secret(value: str) -> str: diff --git a/packages/python-backend/tests/test_authproxy.py b/packages/python-backend/tests/test_authproxy.py index 07c21ef..d87a312 100644 --- a/packages/python-backend/tests/test_authproxy.py +++ b/packages/python-backend/tests/test_authproxy.py @@ -175,15 +175,32 @@ class AccessSettingsTests(unittest.TestCase): self.assertEqual(response.status_code, 500) self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True}) + def test_internal_update_refuses_a_short_or_placeholder_secret(self) -> None: + for secret in ("short", "change-me-to-a-long-random-value"): + with self.subTest(secret=secret): + store = _FakeStore(login_required=True) + client = TestClient( + _build_app(store, _FakeClient(setup_required=False), internal_secret=secret) + ) + response = client.put( + "/api/auth/access/internal", + headers={"X-Internal-Auth": secret}, + json={"loginRequired": False}, + ) + self.assertEqual(response.status_code, 401) + self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True}) + def test_internal_update_disables_login_and_uses_admin_identity(self) -> None: store = _FakeStore(login_required=True) client = TestClient( - _build_app(store, _FakeClient(setup_required=False), internal_secret="secret") + _build_app( + store, _FakeClient(setup_required=False), internal_secret="internal-test-secret" + ) ) response = client.put( "/api/auth/access/internal", - headers={"X-Internal-Auth": "secret"}, + headers={"X-Internal-Auth": "internal-test-secret"}, json={"loginRequired": False}, ) self.assertEqual(response.status_code, 200) @@ -244,6 +261,97 @@ class _RoleClient(_FakeClient): return PublicUser(id=1, username="a", email="a@b.com", role=roles[token]) +class _ProfileClient(_RoleClient): + def __init__(self, *, totp_enabled: bool = False) -> None: + super().__init__() + self.totp_enabled = totp_enabled + self.login_calls: list[tuple[str, str, str]] = [] + self.update_calls: list[dict[str, object]] = [] + + async def me(self, token: str) -> PublicUser: + if token != "admin-token": + raise APIError(401, "unauthenticated") + return PublicUser( + id=1, + username="admin", + email="admin@example.com", + role="superadmin", + totp_enabled=self.totp_enabled, + ) + + async def login(self, username_or_email: str, password: str, totp_token: str = ""): + self.login_calls.append((username_or_email, password, totp_token)) + if password != "current-password": + raise APIError(401, "invalid credentials") + return SessionResult( + user=PublicUser(id=1, username="admin", email="admin@example.com", role="superadmin"), + cookies=["auth_session=reauth-token; Path=/; HttpOnly"], + ) + + async def update_managed_user(self, token: str, user_id: int, **kwargs) -> None: + self.update_calls.append({"token": token, "user_id": user_id, **kwargs}) + + +class ProfileReauthenticationTests(unittest.TestCase): + def _put(self, fake: _ProfileClient, body: dict[str, str]): + client = TestClient(_build_app(_FakeStore(), fake)) + return client.put( + "/api/auth/me", + headers={"Cookie": f"{DEFAULT_COOKIE_NAME}=admin-token"}, + json=body, + ) + + def test_password_update_requires_current_password_and_totp_when_enabled(self) -> None: + no_totp = _ProfileClient() + response = self._put( + no_totp, + {"username": "admin", "email": "admin@example.com", "password": "new-password"}, + ) + self.assertEqual(response.status_code, 400) + self.assertEqual(no_totp.login_calls, []) + + totp = _ProfileClient(totp_enabled=True) + response = self._put( + totp, + { + "username": "admin", + "email": "admin@example.com", + "password": "new-password", + "currentPassword": "current-password", + }, + ) + self.assertEqual(response.status_code, 400) + self.assertEqual(totp.login_calls, []) + + def test_password_update_reauthenticates_and_cleans_up_temporary_session(self) -> None: + fake = _ProfileClient(totp_enabled=True) + response = self._put( + fake, + { + "username": "admin", + "email": "admin@example.com", + "password": "new-password", + "currentPassword": "current-password", + "totpToken": "123456", + }, + ) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(fake.login_calls, [("admin", "current-password", "123456")]) + self.assertEqual( + fake.update_calls, + [ + { + "token": "admin-token", + "user_id": 1, + "username": "admin", + "email": "admin@example.com", + "password": "new-password", + } + ], + ) + self.assertIn("reauth-token", fake.logged_out) + + class EnabledModeSetupAndLoginTests(unittest.TestCase): """Exercises the real (client is not None) path, including the setup-claim flag's interaction with the store.""" diff --git a/packages/python-backend/tests/test_contract.py b/packages/python-backend/tests/test_contract.py index 99bf88f..eace12a 100644 --- a/packages/python-backend/tests/test_contract.py +++ b/packages/python-backend/tests/test_contract.py @@ -9,7 +9,12 @@ from shared_backend.auth import ( verify_password, ) from shared_backend.clientip import client_address, parse_trusted_proxies -from shared_backend.totp import verify_totp +from shared_backend.coreconfig import ( + EXAMPLE_INTERNAL_SECRETS, + MIN_INTERNAL_SECRET_LENGTH, + internal_secret_matches, +) +from shared_backend.totp import verify_totp, verify_totp_step # The Go, Node and Python auth helpers load the same fixtures; see "description" in the file. CONTRACT_PATH = Path(__file__).resolve().parents[3] / "contract" / "auth-contract.json" @@ -27,22 +32,24 @@ class AuthContractTests(unittest.TestCase): password = self.contract["password"] for entry in password["hashes"]: with self.subTest(entry["name"]): + plaintext = entry.get("password", password["plaintext"]) + wrong_password = entry.get("wrongPassword", password["wrongPassword"]) self.assertEqual( - verify_password(password["plaintext"], entry["hash"]), + verify_password(plaintext, entry["hash"]), entry["verifies"]["python"], ) - self.assertFalse(verify_password(password["wrongPassword"], entry["hash"])) + self.assertFalse(verify_password(wrong_password, entry["hash"])) if "python" in entry.get("needsUpgrade", {}): want = entry["needsUpgrade"]["python"] self.assertEqual(password_hash_needs_upgrade(entry["hash"]), want) valid, upgraded = verify_and_upgrade_password( - password["plaintext"], entry["hash"] + 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)) + self.assertTrue(upgraded.startswith(("bcrypt$", "bcrypt-sha256$"))) + self.assertTrue(verify_password(plaintext, upgraded)) def test_the_password_length_contract_holds_for_python(self) -> None: too_long = self.contract["password"]["tooLongToHash"] @@ -59,6 +66,11 @@ class AuthContractTests(unittest.TestCase): with self.subTest(entry["name"]): secret = entry.get("secret", totp["secret"]) self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"]) + if entry["valid"]: + self.assertEqual( + verify_totp_step(secret, entry["code"], entry["unix"]), + entry.get("matchedStep", entry["unix"] // 30), + ) def test_client_address_follows_the_contract(self) -> None: section = self.contract["clientAddress"] @@ -72,6 +84,17 @@ class AuthContractTests(unittest.TestCase): with self.subTest(value), self.assertRaises(ValueError): parse_trusted_proxies(value) + def test_internal_secret_gate_follows_the_contract(self) -> None: + rule = self.contract["internalSecret"] + self.assertEqual(MIN_INTERNAL_SECRET_LENGTH, rule["minLength"]) + self.assertEqual(EXAMPLE_INTERNAL_SECRETS, frozenset(rule["placeholders"])) + for entry in rule["cases"]: + with self.subTest(entry["name"]): + self.assertEqual( + internal_secret_matches(entry["provided"], entry["secret"]), + entry["matches"], + ) + if __name__ == "__main__": unittest.main() diff --git a/packages/python-backend/tests/test_core.py b/packages/python-backend/tests/test_core.py index 0a58ada..e196b97 100644 --- a/packages/python-backend/tests/test_core.py +++ b/packages/python-backend/tests/test_core.py @@ -22,7 +22,7 @@ from shared_backend.postgres import ( retry_startup, ) from shared_backend.tokens import hash_token, new_session_token -from shared_backend.totp import totp_provisioning_uri, verify_totp +from shared_backend.totp import totp_provisioning_uri, verify_totp, verify_totp_step class SharedBackendTests(unittest.TestCase): @@ -61,6 +61,19 @@ class SharedBackendTests(unittest.TestCase): self.assertTrue(verify_password("correct horse battery staple", upgraded)) self.assertFalse(password_hash_needs_upgrade(upgraded)) + def test_long_legacy_pbkdf2_password_migrates_without_truncation(self): + import hashlib + + password = "legacy:" + "x" * 80 + salt = "0123456789abcdef0123456789abcdef" + expected = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 100_000).hex() + legacy = f"{salt}:{expected}" + valid, upgraded = verify_and_upgrade_password(password, legacy) + self.assertTrue(valid) + self.assertTrue(upgraded.startswith("bcrypt-sha256$$2b$12$")) + self.assertTrue(verify_password(password, upgraded)) + self.assertFalse(verify_password(password + "x", upgraded)) + def test_a_cost_below_the_current_policy_is_upgraded(self): low_cost = "bcrypt$" + bcrypt.hashpw( b"correct horse battery staple", bcrypt.gensalt(rounds=4) @@ -151,6 +164,8 @@ class SharedBackendTests(unittest.TestCase): ] for timestamp, code in vectors: self.assertTrue(verify_totp(secret, code, timestamp)) + self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30) + self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30) self.assertTrue( totp_provisioning_uri("Example App", "admin@example.com", secret).startswith( "otpauth://totp/" diff --git a/packages/python-backend/tests/test_coreconfig.py b/packages/python-backend/tests/test_coreconfig.py index eb3db50..8aef2a1 100644 --- a/packages/python-backend/tests/test_coreconfig.py +++ b/packages/python-backend/tests/test_coreconfig.py @@ -1,6 +1,12 @@ import unittest -from shared_backend.coreconfig import Info, Store, internal_secret_matches +from shared_backend.coreconfig import ( + MIN_INTERNAL_SECRET_LENGTH, + Info, + Store, + internal_secret_matches, + internal_secret_usable, +) class StoreDefaultsTests(unittest.TestCase): @@ -62,6 +68,9 @@ class StoreSetTests(unittest.TestCase): self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com") +LONG_SECRET = "shared-secret-value" + + class InternalSecretTests(unittest.TestCase): def test_unset_or_empty_secret_never_matches(self): self.assertFalse(internal_secret_matches(None, None)) @@ -70,9 +79,26 @@ class InternalSecretTests(unittest.TestCase): 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")) + self.assertTrue(internal_secret_matches(LONG_SECRET, LONG_SECRET)) + self.assertFalse(internal_secret_matches("shared-secret-valuE", LONG_SECRET)) + self.assertFalse(internal_secret_matches(None, LONG_SECRET)) + + def test_short_secret_never_matches(self): + short = "x" * (MIN_INTERNAL_SECRET_LENGTH - 1) + self.assertFalse(internal_secret_matches(short, short)) + + def test_placeholder_secret_never_matches(self): + for placeholder in ("SECRET", "change-me-to-a-long-random-value"): + with self.subTest(placeholder=placeholder): + self.assertFalse(internal_secret_matches(placeholder, placeholder)) + + def test_usable_requires_minimum_length_and_no_placeholder(self): + self.assertFalse(internal_secret_usable(None)) + self.assertFalse(internal_secret_usable("")) + self.assertFalse(internal_secret_usable("x" * (MIN_INTERNAL_SECRET_LENGTH - 1))) + self.assertTrue(internal_secret_usable("x" * MIN_INTERNAL_SECRET_LENGTH)) + self.assertFalse(internal_secret_usable("change-me-to-a-long-random-value")) + self.assertTrue(internal_secret_usable(LONG_SECRET)) class UrlValidationTests(unittest.TestCase): diff --git a/packages/python-backend/tests/test_store.py b/packages/python-backend/tests/test_store.py index b8af5b9..8b42248 100644 --- a/packages/python-backend/tests/test_store.py +++ b/packages/python-backend/tests/test_store.py @@ -29,7 +29,7 @@ class _FakeDatabase: async def fetchrow(self, query: str, *args): self.fetched.append((query, args)) if "totp_enabled" in query: - return {"secret": "S", "enabled": self.totp_enabled} + return {"secret": "S", "enabled": self.totp_enabled, "last_used_step": -1} for condition, row in self.rows_by_condition.items(): if condition in query: return row @@ -60,6 +60,9 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase): self.assertIn("lower(username)", statements) # The index is created only while no clashing pair exists. self.assertIn("HAVING count(*) > 1", statements) + self.assertIn( + "ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1", statements + ) async def test_set_totp_secret_refuses_while_enabled(self) -> None: self.db.execute_status = "UPDATE 0" @@ -73,6 +76,52 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase): self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse await self.store.set_totp_secret(2, "NEWSECRET") + async def test_totp_enrollment_records_its_step_and_replay_is_rejected(self) -> None: + class ReplayDatabase(_FakeDatabase): + def __init__(self) -> None: + super().__init__() + self.state = { + "secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", + "enabled": False, + "last_used_step": -1, + } + + async def fetchrow(self, query: str, *args): + if "FROM auth_users WHERE id = $1" in query and "totp_enabled" in query: + return dict(self.state) + return await super().fetchrow(query, *args) + + async def execute(self, query: str, *args) -> str: + self.executed.append((query, args)) + step, _, secret = args + if "SET totp_enabled = true" in query: + if ( + not self.state["enabled"] + and secret == self.state["secret"] + and self.state["last_used_step"] < step + ): + self.state["enabled"] = True + self.state["last_used_step"] = step + return "UPDATE 1" + return "UPDATE 0" + if "SET last_used_step = $1" in query: + if ( + self.state["enabled"] + and secret == self.state["secret"] + and self.state["last_used_step"] < step + ): + self.state["last_used_step"] = step + return "UPDATE 1" + return "UPDATE 0" + return await super().execute(query, *args) + + database = ReplayDatabase() + store = AuthStore(database) # type: ignore[arg-type] + self.assertTrue(await store.enable_totp(1, "287082", 59.0)) + self.assertEqual(database.state["last_used_step"], 1) + self.assertFalse(await store.consume_totp_code(1, "287082", 59.0)) + self.assertEqual(database.state["last_used_step"], 1) + async def test_credential_writes_refuse_an_empty_hash_and_an_at_username(self) -> None: writes = [ lambda u, h: self.store.create_user(u, "", h), diff --git a/packages/web-ui/src/lib/components/ProfileDialog.svelte b/packages/web-ui/src/lib/components/ProfileDialog.svelte index dead8d5..4f9c9c9 100644 --- a/packages/web-ui/src/lib/components/ProfileDialog.svelte +++ b/packages/web-ui/src/lib/components/ProfileDialog.svelte @@ -13,6 +13,7 @@ onTotpSetup, onTotpStatus, totpEnabled = false, + requireCredentialsForEmailChange = false, open = $bindable(false) }: { currentEmail?: string; @@ -23,6 +24,7 @@ onTotpSetup?: TotpSetupRequest; onTotpStatus?: TotpStatusRequest; totpEnabled?: boolean; + requireCredentialsForEmailChange?: boolean; open?: boolean; } = $props(); @@ -30,8 +32,13 @@ let email = $state(''); let password = $state(''); let confirmPassword = $state(''); + let currentPassword = $state(''); + let totpToken = $state(''); let error = $state(''); let saving = $state(false); + let requiresCurrentCredentials = $derived( + !!password || (requireCredentialsForEmailChange && email.trim() !== currentEmail.trim()) + ); $effect(() => { if (open) { @@ -39,6 +46,8 @@ email = currentEmail; password = ''; confirmPassword = ''; + currentPassword = ''; + totpToken = ''; error = ''; } }); @@ -52,6 +61,16 @@ return; } + if (requiresCurrentCredentials && !currentPassword) { + error = 'Enter your current password to change your email or password.'; + return; + } + + if (requiresCurrentCredentials && totpEnabled && !totpToken) { + error = 'Enter a current authenticator code to change your email or password.'; + return; + } + if (!onSave) { error = 'The application has not configured its profile update handler.'; return; @@ -59,7 +78,13 @@ saving = true; try { - await onSave({ username, email, password: password || undefined }); + const input: ProfileUpdateInput = { username, email }; + if (requiresCurrentCredentials) { + input.currentPassword = currentPassword; + if (totpEnabled) input.totpToken = totpToken; + } + if (password) input.password = password; + await onSave(input); open = false; } catch (caught) { error = caught instanceof Error ? caught.message : 'Profile update failed.'; @@ -100,6 +125,35 @@ /> + {#if requiresCurrentCredentials} + + + {#if totpEnabled} + + {/if} + {/if} + {#if password}