27 Commits
Author SHA1 Message Date
Claude Code cf19a057c5 feat(media): forward the audio copy format to CarrierNode
The stream proxy passes format=mp3 through, so an audio file browsers cannot play (WMA) can be served
as an MP3 copy that CarrierNode makes once and keeps.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-21 15:14:35 +01:00
Claude Code 5745995a34 feat(web-ui): pass the media error to MediaPlayer onError
onError now receives the element's MediaError, so an app can tell an unsupported source (code 4,
MEDIA_ERR_SRC_NOT_SUPPORTED, as with AVI, WMV or ASF) from other failures. Handlers that take no
argument are unaffected.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-21 15:14:35 +01:00
Gabriel20xx 170c7570e4 test(media): verify question marks in stored paths are escaped 2026-11-21 12:10:44 +01:00
Gabriel20xx 8701874efb feat(logshipper): support dynamic OmniLogger credentials
- Add per-service OmniLogger credentials to core config and update subscriptions.
- Follow config pushes and enforce entry and request size limits.
- Requeue batches after transient send failures.
2026-11-20 21:45:45 +01:00
Gabriel20xxandClaude Haiku 5.5 76bf5916fe fix(web-ui): fade MediaPlayer controls when the pointer is over the picture
Pointer movement and presses now count as activity anywhere inside the
player's box. The picture can sit on a canvas stacked above the frame,
where the pointer never reaches the frame's own elements, so the
controls did not fade back in. The autoHideControls doc comment now
describes the real default.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-20 21:24:40 +01:00
Gabriel20xx a8dce33dc5 feat: support controlled and customizable media playback 2026-11-19 00:03:37 +01:00
Gabriel20xx ba171a74a9 fix: omit empty video poster attribute 2026-11-18 20:09:24 +01:00
Claude Code 9e58b6db01 feat(media): forward WMV live transcode options to CarrierNode
streamMediaIdentifier now forwards only the quality and start query parameters to CarrierNode, so browser-unplayable WMV/ASF video can stream as a seekable live H.264 copy. Other query parameters are not forwarded, and audio-only playback is unchanged.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-18 13:51:54 +01:00
Gabriel20xx 7f21bb9073 Update shared package 2026-11-17 13:35:39 +01:00
Gabriel20xx fc01c93aeb feat: expand media playback and security scan options
- Add resume, speed selection, and controls-free media mode
- Run Trivy daily and secrets/code scans weekly
- Document new MediaPlayer options in README
2026-11-15 19:24:19 +01:00
Gabriel20xx d20eb96969 feat: discover consumer repositories during sync 2026-11-15 13:21:53 +01:00
Gabriel20xx 750e9b7a85 test(media): verify library-scoped tag suggestions 2026-11-13 21:20:50 +01:00
GabrielandClaude Haiku 5.5 60befcd883 feat(media): port MediaViewer ratings and visible-only tag counts
MediaViewer committed these changes to its vendored shared copy
(e83afad, ca8a89e) without upstreaming them, so the next shared sync
would have removed them from MediaViewer and broken its build.

Ported here as a three-way merge against 74942e5, the snapshot
MediaViewer last synced from:

- media.MediaRecord.Rating, read in FindMedia and returned by ToJSON,
  with the rating column added in migrate.go
- tagSuggestions counts media items through the library's visibility
  rules instead of raw media_tags rows
- MediaPlayer autoplayMuted prop (defaults to false, so existing
  callers are unaffected)

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-13 17:46:55 +01:00
Gabriel20xx 61d8da5fb3 feat: add safe CarrierNode media deletion
- Validate media paths before sending delete requests
- Treat 404 as an already-missing file
- Test removal, errors, and path validation
2026-11-13 16:56:44 +01:00
Gabriel20xx fb4274bd5c ci(security): install the latest Trivy release dynamically 2026-11-10 18:14:16 +01:00
GabrielandClaude Haiku 5.5 74942e55f9 test(python-backend): restore test typing fixes and formatting
A later vendored sync reverted the test typing fixes from 23bd5b2 and the
line-length formatting from 50461c0, which fails the ty check in consumers
that run `ty check --error-on-warning`. Restore them:

- assert the narrowed upgraded/found values before use
- suppress the intentional _FakeDatabase argument mismatches with
  `# ty: ignore[invalid-argument-type]`
- reformat the long lines to the package's line-length of 100

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 14:38:14 +01:00
Gabriel20xx 75c08beec6 refactor(backend): rename mediacore package to media 2026-11-01 21:50:47 +01:00
Gabriel20xx e8cb7c6c68 feat: support selective shared consumer sync
- Accept consumer paths or an AutoCode JSON selection file
- Remove OutdoorGames from the sync catalogue
2026-10-27 14:20:32 +00:00
Gabriel20xx b776bacd70 fix: overlay mobile navigation without shifting page content 2026-10-27 09:22:51 +00:00
Gabriel20xx 37a4a8e2ca fix: center mobile menu button in header row 2026-10-27 07:40:04 +00:00
Gabriel20xx 8ec0d89437 chore: update dependencies and exclude test fixtures from scans
- Bump Go, npm, and Jackson dependencies
- Configure Gitleaks and Semgrep to ignore test fixtures
2026-10-27 07:16:37 +00:00
Gabriel20xx 657d478d48 ci: add automated security scanning workflow 2026-10-26 21:38:50 +00:00
Gabriel20xx b9c2365bca fix: hide lone nav items and improve primary text contrast 2026-10-26 14:12:39 +00:00
Gabriel20xx cb7a899c77 fix: keep the header full width in wide layouts
- Remove the wide-layout width override for `.sc-header`
- Add a patch changeset for `@gabriel20xx/web-ui`
2026-10-26 12:57:59 +00:00
Gabriel20xx a15827fe76 ci: support dynamic Postgres ports in Gitea Actions 2026-10-21 09:45:39 +00:00
Gabriel20xx add64ff180 refactor(auth): remove obsolete project restriction APIs
- Remove legacy project restriction schema and helpers
- Install Python test extras in CI
- Update the quality report status
2026-10-20 19:32:45 +00:00
Gabriel20xx f7819904b9 docs: record auth hash alignment and validation results 2026-10-20 15:26:58 +00:00
113 changed files with 9265 additions and 1652 deletions

No files matched your search

@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": patch
---
Keep the shared header full width when the wide-page setting is on. The `data-wide-layout` rule no longer narrows `.sc-header` with `calc(100% - 2rem)` and auto margins, which left a gap on both sides of the header. Only `.sc-main` widens now, so the header looks the same in every application whether or not the page is wide.
+5
View File
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": patch
---
`Header` no longer renders the primary navigation tab, or the mobile menu toggle, when `navItems` has only one entry. A lone item is just the app's home page, so projects like OmniLogger and OutdoorGames no longer show a single "Dashboard" tab in the header.
+5
View File
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": patch
---
Fix `MediaPlayer` controls not fading away during playback when the pointer stays still. Pointer movement now counts as activity anywhere over the player, including over a picture drawn on a canvas stacked above the frame, so the controls fade after a few seconds and come back when the pointer moves over the player again. The `autoHideControls` doc comment now describes its real behavior: `true` (the default) fades the controls, `false` keeps them visible.
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": patch
---
Open the mobile navigation menu as an overlay below the header instead of inserting it into the header row. Opening the menu no longer pushes the page content down, and long menus scroll within the viewport.
+5
View File
@@ -0,0 +1,5 @@
---
"@gabriel20xx/node-backend": patch
---
Adds `LogShipper`, `createLogShipperFromEnv` and `mirrorConsole` (`src/logshipper.js`): batches log entries and sends them to OmniLogger's `/api/logs`. Shipping is enabled only when `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` are both set, and otherwise the factory returns `null`.
+5
View File
@@ -0,0 +1,5 @@
---
"@gabriel20xx/web-ui": patch
---
`Pagination` no longer adds a 1rem top margin, so it sits evenly inside whichever container holds it. Its page-size select now shows its arrow at the same text size as the count, the controls line up with the select, and on phones the count sits on its own centred line above the page size and buttons.
+155
View File
@@ -0,0 +1,155 @@
name: Security
on:
push:
branches: ['**']
pull_request:
branches: [main, master]
schedule:
# Daily, for the Trivy job, so advisories published after the last push still get reported.
- cron: '23 5 * * *'
# Weekly, for the secrets and code jobs. Each job's if: condition picks the entry that runs it.
- cron: '23 5 * * 1'
workflow_dispatch: {}
jobs:
secrets:
name: Secrets (gitleaks)
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
# Full history, so a secret that was committed and later removed is still found.
fetch-depth: 0
submodules: false
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: stable
# gitleaks runs at a pinned version. go run checks the module against the Go checksum
# database. Known false positives go in .gitleaks.toml at the repo root, which gitleaks reads
# on its own.
- name: Scan git history for secrets
run: go run github.com/zricethezav/gitleaks/v8@v8.30.1 git --no-banner --redact --exit-code 1 .
code:
name: Code (Semgrep)
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
submodules: false
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install Semgrep
run: pip install semgrep==1.182.1
# Fails on ERROR findings from Semgrep's default rules. WARNING findings are not gated.
- name: Scan code
run: semgrep scan --config p/default --severity ERROR --error --metrics=off .
dependencies:
name: Dependencies (Trivy)
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * *'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
submodules: false
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: 24
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install uv
run: pip install uv==0.13.5
- name: Install Trivy
# Always the newest Trivy release. The version is read from the release redirect when the job
# runs, and the download is checked against that release's published checksums. The
# aquasecurity/trivy-action version tags were repointed to malicious commits in March 2026,
# so that action is not used.
shell: bash
run: |
latest_url=$(curl --fail --location --silent --show-error --retry 5 --retry-delay 2 \
--output /dev/null --write-out '%{url_effective}' https://github.com/aquasecurity/trivy/releases/latest)
TRIVY_VERSION=${latest_url##*/tag/v}
if [[ ! "$TRIVY_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Could not read the latest Trivy version from $latest_url" >&2
exit 1
fi
echo "Installing Trivy $TRIVY_VERSION"
archive="trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
base_url="https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}"
curl --fail --location --retry 5 --retry-delay 2 \
--output "$RUNNER_TEMP/$archive" "$base_url/$archive"
curl --fail --location --retry 5 --retry-delay 2 \
--output "$RUNNER_TEMP/trivy_checksums.txt" "$base_url/trivy_${TRIVY_VERSION}_checksums.txt"
(cd "$RUNNER_TEMP" && grep -F " $archive" trivy_checksums.txt > trivy_checksum.txt \
&& sha256sum -c trivy_checksum.txt)
tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP" trivy
echo "$RUNNER_TEMP" >> "$GITHUB_PATH"
"$RUNNER_TEMP/trivy" --version
# Trivy audits lockfiles and skips bare manifests. For each manifest with no lockfile in its
# own folder or any parent folder, resolve one here so its dependencies get scanned. These
# lockfiles are made only for this run and are not committed.
- name: Resolve manifests that have no lockfile
shell: bash
run: |
has_lockfile() {
local dir=$1
shift
while true; do
for lockfile in "$@"; do
if [ -f "$dir/$lockfile" ]; then
return 0
fi
done
if [ "$dir" = "." ]; then
return 1
fi
dir=$(dirname "$dir")
done
}
while IFS= read -r -d '' manifest; do
dir=$(dirname "$manifest")
if ! has_lockfile "$dir" package-lock.json yarn.lock pnpm-lock.yaml; then
echo "Resolving npm dependencies in $dir"
(cd "$dir" && npm install --package-lock-only --ignore-scripts --no-audit --no-fund)
fi
done < <(find . -name node_modules -prune -o -name package.json -print0)
while IFS= read -r -d '' manifest; do
dir=$(dirname "$manifest")
if ! has_lockfile "$dir" uv.lock poetry.lock Pipfile.lock; then
echo "Resolving Python dependencies in $dir"
(cd "$dir" && uv lock)
fi
done < <(find . -name node_modules -prune -o -name .venv -prune -o -name pyproject.toml -print0)
# Fails on HIGH and CRITICAL vulnerabilities that have a fixed version. Vulnerabilities with no
# fix are left out, because nothing can be changed to clear them. Development dependencies are
# included, since build and test tooling runs in CI.
# --offline-scan: Maven Central rate-limits the lookups Trivy makes for pom.xml, so Maven
# dependencies are read from their declared versions only. Transitive ones are not resolved.
- name: Scan dependencies for known vulnerabilities
run: >-
trivy fs --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --include-dev-deps
--offline-scan --exit-code 1 --timeout 15m .
+13 -6
View File
@@ -55,7 +55,7 @@ jobs:
run: run:
working-directory: backend working-directory: backend
# A throwaway PostgreSQL for the tests that need a real database (the auth store, the # A throwaway PostgreSQL for the tests that need a real database (the auth store, the
# platform-user SQL, mediacore's routes and the migrate package). Without these two # platform-user SQL, the media routes and the migrate package). Without these two
# variables those tests skip themselves. # variables those tests skip themselves.
services: services:
postgres: postgres:
@@ -65,15 +65,15 @@ jobs:
POSTGRES_PASSWORD: postgres POSTGRES_PASSWORD: postgres
POSTGRES_DB: scratch POSTGRES_DB: scratch
ports: ports:
- 5432:5432 - 5432/tcp
options: >- options: >-
--health-cmd "pg_isready -U postgres" --health-cmd "pg_isready -U postgres"
--health-interval 5s --health-interval 5s
--health-timeout 5s --health-timeout 5s
--health-retries 10 --health-retries 10
env: env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/scratch?sslmode=disable DATABASE_URL: postgres://postgres:postgres@localhost:${{ job.services.postgres.ports['5432'] }}/scratch?sslmode=disable
SHARED_TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/scratch?sslmode=disable SHARED_TEST_DATABASE_URL: postgres://postgres:postgres@localhost:${{ job.services.postgres.ports['5432'] }}/scratch?sslmode=disable
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -84,7 +84,14 @@ jobs:
cache: true cache: true
# -p 1 runs one package at a time, because the database tests share one scratch database. # -p 1 runs one package at a time, because the database tests share one scratch database.
- name: Run Go tests - name: Run Go tests
run: go test -p 1 ./... shell: bash
run: |
# Gitea Actions runs jobs in a container, where the service is reached by its label.
if [ "${GITEA_ACTIONS:-}" = "true" ]; then
export DATABASE_URL="postgres://postgres:postgres@postgres:5432/scratch?sslmode=disable"
export SHARED_TEST_DATABASE_URL="postgres://postgres:postgres@postgres:5432/scratch?sslmode=disable"
fi
go test -p 1 ./...
python: python:
name: Test (Python) name: Test (Python)
@@ -99,7 +106,7 @@ jobs:
with: with:
python-version: '3.12' python-version: '3.12'
- name: Install package - name: Install package
run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi]" run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi,test]"
- name: Run Python tests - name: Run Python tests
run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py' run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
+16
View File
@@ -0,0 +1,16 @@
# gitleaks configuration. gitleaks reads this file from the repository root.
[extend]
useDefault = true
[allowlist]
description = "Test fixtures that contain placeholder credentials, not real secrets"
paths = [
'''(^|/)(tests?|__tests__)/''',
'''_test\.go$''',
'''\.test\.[jt]sx?$''',
'''\.spec\.[jt]sx?$''',
'''(^|/)test_[^/]*\.py$''',
'''Test\.java$''',
'''(^|/)contract/auth-contract\.json$''',
]
+14
View File
@@ -0,0 +1,14 @@
# Semgrep skips test code and fixtures. Tests hold placeholder credentials on purpose.
# auth-contract.json holds bcrypt hashes of test passwords shared by every service's tests.
auth-contract.json
test/
tests/
__tests__/
*_test.go
*.test.js
*.test.ts
*.test.tsx
*.spec.js
*.spec.ts
test_*.py
*Test.java
+4 -4
View File
@@ -3,11 +3,11 @@
- **Project:** shared - **Project:** shared
- **Path:** /workspace/Personal/Web/shared - **Path:** /workspace/Personal/Web/shared
- **Analyzed:** 2026-10-16 - **Analyzed:** 2026-10-16
- **Commit:** 5216031 on main - **Commit:** 22887fe on main
- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. Findings reflect the working tree. - **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
- **Stack:** Go 1.25 (`backend/`, module `repos.gfranz.ch/Gabriel20xx/shared/backend`, pgx, chi, coder/websocket, goose); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; PowerShell and Node scripts; Gitea and GitHub Actions. No Dockerfile, compose file or `.dockerignore` exists in the repo. - **Stack:** Go 1.25 (`backend/`, module `repos.gfranz.ch/Gabriel20xx/shared/backend`, pgx, chi, coder/websocket, goose); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; PowerShell and Node scripts; Gitea and GitHub Actions. No Dockerfile, compose file or `.dockerignore` exists in the repo.
- **Scope:** This is a shared library consumed by other projects (vendored snapshot), not an application. Read: all first-party Go packages except `backend/auth/*` and `backend/config` (reviewed in a separate pass), the Node, Python and Java AuthGuard clients and stores, the web-ui components that perform I/O or timers, root manifests, `.github` and `.gitea` workflows, and `scripts/`. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies (used only for coverage notes). Paths below are relative to the repo root. Backend findings come from read-only static review passes; the highest-severity citations were re-checked in the code. Nothing was built, run or profiled. - **Scope:** This is a shared library consumed by other projects (vendored snapshot), not an application. Read: all first-party Go packages except `backend/auth/*` and `backend/config` (reviewed in a separate pass), the Node, Python and Java AuthGuard clients and stores, the web-ui components that perform I/O or timers, root manifests, `.github` and `.gitea` workflows, and `scripts/`. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies (used only for coverage notes). Paths below are relative to the repo root. Backend findings come from read-only static review passes; the highest-severity citations were re-checked in the code. Nothing was built, run or profiled.
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). Second Medium pass: P-002 fixed. - **Updated:** 2026-10-20 — the two-second session-validation cache remains enabled by owner decision; code comments and README now state its revocation window and same-client logout behavior.
## Summary ## Summary
@@ -92,5 +92,5 @@ The auth code has no obvious SQL N+1 outside the playlist reorder path, and most
- **Docker:** No Dockerfile, compose file or `.dockerignore` exists in this repository, so image size, multi-stage builds and base-image checks do not apply here. Consumer projects that build images from the vendored snapshot should be reviewed separately. - **Docker:** No Dockerfile, compose file or `.dockerignore` exists in this repository, so image size, multi-stage builds and base-image checks do not apply here. Consumer projects that build images from the vendored snapshot should be reviewed separately.
- **Frontend checks:** No whole-library imports were found; `@lucide/svelte` is imported by name in every component. No `{@html}`, unbounded caches or leaked intervals were found in the web-ui, and the timers and listeners in `MediaPlayer`, `MediaPlayerControls`, `StatusWidget`, `AppShell` and `notifications.svelte.ts` are cleaned up. `shared-styles.css` (1134 lines, about 21 KB) is loaded in full by consumers. As a component library it has no route-level code-splitting, which is expected rather than a defect. Four of seven `{#each}` blocks in the components are keyed; the remaining ones are listed under quality findings. - **Frontend checks:** No whole-library imports were found; `@lucide/svelte` is imported by name in every component. No `{@html}`, unbounded caches or leaked intervals were found in the web-ui, and the timers and listeners in `MediaPlayer`, `MediaPlayerControls`, `StatusWidget`, `AppShell` and `notifications.svelte.ts` are cleaned up. `shared-styles.css` (1134 lines, about 21 KB) is loaded in full by consumers. As a component library it has no route-level code-splitting, which is expected rather than a defect. Four of seven `{#each}` blocks in the components are keyed; the remaining ones are listed under quality findings.
- **HTTP caching and compression:** Not applicable to the library code; the backends are API services and the static styles are shipped to consumers' own build pipelines. - **HTTP caching and compression:** Not applicable to the library code; the backends are API services and the static styles are shipped to consumers' own build pipelines.
- **Not verified:** No query plans (no database access), no benchmarks or profiling, no build or test runs. Counts and ordering are based on code reading only. - **Not verified:** No query plans (no database access), benchmarks or profiling. Node, Python, 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). - **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (used for versions only).
+9 -8
View File
@@ -3,11 +3,11 @@
- **Project:** shared - **Project:** shared
- **Path:** /workspace/Personal/Web/shared - **Path:** /workspace/Personal/Web/shared
- **Analyzed:** 2026-10-16 - **Analyzed:** 2026-10-16
- **Commit:** 5216031 on main - **Commit:** 22887fe on main
- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. Findings reflect the working tree (for example, README component count, Q-014). - **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
- **Stack:** Go 1.25 (`backend/`); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`, ruff configured); Java 8 target with Jackson and JUnit 5 (`packages/java-backend`); Svelte 5 and TypeScript with svelte-check (`packages/web-ui`); PowerShell and Node build and sync scripts; Gitea and GitHub Actions. - **Stack:** Go 1.25 (`backend/`); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`, ruff configured); Java 8 target with Jackson and JUnit 5 (`packages/java-backend`); Svelte 5 and TypeScript with svelte-check (`packages/web-ui`); PowerShell and Node build and sync scripts; Gitea and GitHub Actions.
- **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings come from read-only static review passes; the highest-impact citations were re-checked in the code. No lint, build or test was executed. - **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings came from read-only static review passes; the highest-impact citations were re-checked in the code. The shared Node, Python, web-ui and Go suites/checks, web-ui package build and checks were run during this continuation; Java tools remain unavailable.
- **Updated:** 2026-10-19 — Medium findings handled in the working tree (not committed): Q-004 and Q-009 fixed; Q-008 stays open for the cross-runtime hash-format decision. - **Updated:** 2026-10-20 — Q-008 fixed in the working tree: all password writers use bcrypt cost 12, legacy PBKDF2 verifies and upgrades after a successful login, and shared contract fixtures cover all runtimes. Node tests, web-ui tests, package build, Svelte check and Node syntax check passed.
## Summary ## Summary
@@ -77,7 +77,7 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
- **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately. - **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately.
- **Impact:** A service behaves differently depending on which runtime serves it, and a password hash can reach an API response in Python. - **Impact:** A service behaves differently depending on which runtime serves it, and a password hash can reach an API response in Python.
- **Recommendation:** Standardise the hash format (or rehash on login), strip `password_hash` from every DTO, align the retry policy and the middleware failure modes, and add cross-language contract tests that run the same fixtures against each client. - **Recommendation:** Standardise the hash format (or rehash on login), strip `password_hash` from every DTO, align the retry policy and the middleware failure modes, and add cross-language contract tests that run the same fixtures against each client.
- **Status:** Open 2026-10-19 — partly fixed: Python list and create payloads no longer return `password_hash`, Python startup retries only transient connection errors like Node, the Java middleware answers 401 when no base URL is set, and Java `Totp` compares with `MessageDigest.isEqual`. Node, Python and Go version their password hashes and rewrite older ones on login (see S-013). New in this pass: `contract/auth-contract.json` holds shared fixtures (password hashes per runtime, RFC 6238 TOTP cases, client-address cases) that the Go, Node and Python suites all load (`backend/auth/contract_test.go`, `packages/node-backend/test/contract.test.js`, `packages/python-backend/tests/test_contract.py`); it records the remaining hash divergence on purpose. Running it found Python `verify_totp` raising `TypeError` on a six-digit token written in non-ASCII digits where Go and Node answer false, fixed in `totp.py`. The Node and Python stores now share Go's guards (see S-016), and Python refuses passwords over 72 bytes like Go. Still open: Node (PBKDF2) writes a different hash format into `auth_users.password_hash` than Python and Go (bcrypt); Node cannot verify bcrypt, and Python and Go cannot verify Node's. Decision needed: pick one write scheme for all runtimes (or accept a new bcrypt dependency in Node), because letting one runtime verify another's format would make a shared database ping-pong between schemes on re-key. The Java client is not in the contract tests: no JDK or Maven is available here to compile them. Files: `contract/auth-contract.json`, `backend/auth/contract_test.go`, `packages/node-backend/test/contract.test.js`, `packages/python-backend/tests/test_contract.py`, `packages/python-backend/src/shared_backend/totp.py`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/src/shared_backend/postgres.py`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java`, `packages/node-backend/src/auth.js`, `backend/auth/password.go`. - **Status:** Fixed 2026-10-20 — Node now writes the same prefixed bcrypt cost-12 scheme as Go and Python, and each runtime verifies current/legacy bcrypt plus both legacy Node PBKDF2 formats. Successful legacy verification returns an upgraded hash; AuthGuard conditionally persists that upgrade after a successful login. Long legacy PBKDF2 passwords use the explicit `bcrypt-sha256$` scheme to avoid bcrypt truncation, while new passwords over 72 bytes are rejected. The Java AuthClient does not create or verify stored password hashes. Node also depends on `bcryptjs` to share the scheme. The shared contract covers current, low-cost, malformed, legacy and over-limit cases. Files: `backend/auth/password.go`, `backend/auth/contract_test.go`, `Central/AuthGuard/internal/httpapi/{auth.go,server.go,server_test.go}`, `packages/node-backend/{package.json,src/auth.js,test/auth.test.js,test/contract.test.js}`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/tests/{test_core.py,test_contract.py}`, `contract/auth-contract.json`.
### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium** · Fixed ### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium** · Fixed
- **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script) - **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script)
@@ -117,10 +117,11 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
- **Recommendation:** Update the component count to match `index.ts` when the removal is committed, delete the `mediaauth` references, and remove the stale ignore entry. - **Recommendation:** Update the component count to match `index.ts` when the removal is committed, delete the `mediaauth` references, and remove the stale ignore entry.
### Q-015 · Go code hygiene: dead code, an oversized file, duplicated helpers and nil-dependency constructors · **Low** ### Q-015 · Go code hygiene: dead code, an oversized file, duplicated helpers and nil-dependency constructors · **Low**
- **Location:** `backend/auth/reset.go` (`ResetManager` has no non-test consumer in this repository), `backend/auth/totp.go:23` (`TOTPSecretLength` unused), `backend/auth/proxy.go` (1525 lines mixing middleware, handlers and platform-user SQL), `backend/mediacore/mediacore.go:76-78` (`New` accepts nil CarrierNode or Sync; needs verification in the code), `backend/authclient/client.go:270-278` (two identical branches where the comment says there is a distinction), `writeJSON` and `writeError` duplicated across three packages - **Location:** `backend/auth/reset.go` (`ResetManager` is used by AuthGuard outside this repository), `backend/auth/totp.go` (`TOTPSecretLength` unused), `backend/auth/store.go` (legacy per-user project APIs and expired-session cleanup helper), `backend/auth/proxy.go` (1525 lines mixing middleware, handlers and platform-user SQL), `backend/mediacore/mediacore.go:76-78` (`New` accepts nil CarrierNode or Sync; needs verification in the code), `backend/authclient/client.go:270-278` (two identical branches where the comment says there is a distinction), `writeJSON` and `writeError` duplicated across three packages
- **Description:** Exported helpers with no in-repository callers, a 1525-line file that mixes concerns, duplicated HTTP helpers, a constructor that accepts nil dependencies (which panics on first use rather than at startup), and a branch that is meant to separate transport failures from invalid sessions but returns the same result either way. - **Description:** Exported helpers with no workspace callers, a 1525-line file that mixes concerns, duplicated HTTP helpers, a constructor that accepts nil dependencies (which panics on first use rather than at startup), and a branch that is meant to separate transport failures from invalid sessions but returns the same result either way.
- **Impact:** Maintenance cost, and a misconfigured service fails on the first request rather than at startup. - **Impact:** Maintenance cost, and a misconfigured service fails on the first request rather than at startup.
- **Recommendation:** Remove or move unused code. Split `proxy.go` into middleware, handlers and persistence files. Validate constructor arguments. Share one JSON helper package, and make the authclient branches distinct or merge them. - **Recommendation:** Remove or move unused code. Split `proxy.go` into middleware, handlers and persistence files. Validate constructor arguments. Share one JSON helper package, and make the authclient branches distinct or merge them.
- **Status:** Partly fixed 2026-10-20 — removed the unused `TOTPSecretLength` constant, legacy per-user project APIs and their schema creation, and unused `DeleteExpiredSessions` helper. No table drop was added; AuthGuard's existing migration continues to transfer legacy restriction rows into roles before clearing them from the old table. `ResetManager` remains because AuthGuard uses it; file splitting, duplicated helpers, and the remaining findings are open.
### Q-016 · Web UI: an unkeyed `{#each}` over a prop, and a login-field length rule that also applies to sign-in · **Low** ### Q-016 · Web UI: an unkeyed `{#each}` over a prop, and a login-field length rule that also applies to sign-in · **Low**
- **Location:** `packages/web-ui/src/lib/components/Header.svelte:168` (`{#each navItems as item}` with no key), `packages/web-ui/src/lib/components/AuthPage.svelte:202` (`minlength="8"` on the sign-in password field, not only on setup) - **Location:** `packages/web-ui/src/lib/components/Header.svelte:168` (`{#each navItems as item}` with no key), `packages/web-ui/src/lib/components/AuthPage.svelte:202` (`minlength="8"` on the sign-in password field, not only on setup)
@@ -132,6 +133,6 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
- **Checked, clean:** No `TODO`, `FIXME`, `HACK` or `XXX` markers in first-party non-test code. No `any`, `@ts-ignore`, `@ts-expect-error` or `svelte-ignore` in `packages/web-ui/src`. No `{@html}`, `innerHTML`, `eval` or `new Function` in the web-ui or scripts. External links use `rel="noreferrer"`. Timers and document listeners are cleaned up in `StatusWidget`, `MediaPlayer`, `MediaPlayerControls`, `PrimaryColorPicker` and `notifications.svelte.ts`. - **Checked, clean:** No `TODO`, `FIXME`, `HACK` or `XXX` markers in first-party non-test code. No `any`, `@ts-ignore`, `@ts-expect-error` or `svelte-ignore` in `packages/web-ui/src`. No `{@html}`, `innerHTML`, `eval` or `new Function` in the web-ui or scripts. External links use `rel="noreferrer"`. Timers and document listeners are cleaned up in `StatusWidget`, `MediaPlayer`, `MediaPlayerControls`, `PrimaryColorPicker` and `notifications.svelte.ts`.
- **Checked, consistent:** Go code is gofmt-checked and `go vet`-checked in CI. Python code is ruff-checked (`E`, `F`, `I`). Node syntax is checked for `packages/node-backend`. Parameterised SQL is used across the Go, Node and Python stores. - **Checked, consistent:** Go code is gofmt-checked and `go vet`-checked in CI. Python code is ruff-checked (`E`, `F`, `I`). Node syntax is checked for `packages/node-backend`. Parameterised SQL is used across the Go, Node and Python stores.
- **Duplication by design:** The AuthGuard client exists in four languages on purpose. Q-008 covers where the behaviour has drifted. - **Duplication by design:** The AuthGuard client exists in four languages on purpose. Q-008 covers where the behaviour has drifted.
- **Not run:** No lint, build, test, `go vet`, `ruff`, `svelte-check` or `npm` command was executed. All findings are from reading the code. - **Verification:** Node backend: 73 tests passed. Python backend: 122 tests and Ruff passed. Web-ui: 29 tests, package build, `svelte-check`, `npm run lint`, and `format:check` passed. Go: `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. - **Not verified:** Whether consumers depend on the removed `UserManagement` export or the `MediaPlayerControls` barrel removal (the changeset says only AuthGuard used it). Whether the `packages/media-shared-assets` and `media-backend` paths in history were ever shipped.
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies beyond coverage notes. - **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies beyond coverage notes.
+10 -6
View File
@@ -1,6 +1,6 @@
# shared # shared
The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, and backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages. Every project that consumes this repo — including the media-family services (CarrierNode, ContentScanner, CraftStudio, MediaViewer, KioskDisplay, ModerationHub, ProjectConfigurator) — is its own independent frontend/backend; none of them share a generic multi-flavor binary or app anymore. The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, and backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages. Every project that consumes this repo — for example CarrierNode, ContentScanner, CraftStudio, MediaViewer, KioskDisplay, ModerationHub and ProjectConfigurator — is its own independent frontend/backend; none of them share a generic multi-flavor binary or app anymore.
--- ---
@@ -21,7 +21,7 @@ The single source of truth for code reused across every project in this workspac
|---|---|---| |---|---|---|
| `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. | | `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. |
| `@gabriel20xx/web-ui` | Svelte | Shared application shell and reusable UI components. The complete public component inventory is documented below. | | `@gabriel20xx/web-ui` | Svelte | Shared application shell and reusable UI components. The complete public component inventory is documented below. |
| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations, and the media-family's shared route/table surface (`mediaauth`, `mediacore`, `carriernodeclient`, `syncsocket`). | | `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations, the `settings` table helpers, the `files` path-safety helpers, the `media` library routes, the `syncsocket` sync routes, the `carriernodeclient` client, and the account routes (TOTP and profile) on `auth`. |
| `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. | | `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. |
| `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. | | `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. |
| `com.gabriel20xx.shared.auth` | Java | An AuthGuard client, mirroring the Go/Node/Python ones. | | `com.gabriel20xx.shared.auth` | Java | An AuthGuard client, mirroring the Go/Node/Python ones. |
@@ -75,20 +75,24 @@ These are the complete Svelte component exports from `packages/web-ui/src/lib/in
| Component | Includes | | Component | Includes |
|---|---| |---|---|
| `MediaPlayer` | Audio/video player with playback, seeking, volume, quality, fullscreen, keyboard controls, and custom end controls. | | `MediaPlayer` | Audio/video player with playback, seeking, volume, speed, quality, fullscreen, keyboard controls, custom end controls, and optional resume from the saved position (`storageKey`, per app). With `controls={false}` it is just the element, returned through `element`, for apps that drive playback themselves and set `src` on it. |
#### Accounts and access #### Accounts and access
| Component | Includes | | Component | Includes |
|---|---| |---|---|
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. | | `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. | | `ProfileDialog` | Profile username/email/password editing and TOTP settings. Changing a password asks for the current password and, when TOTP is enabled, a current authenticator code; `onSave` receives both proofs in `ProfileUpdateInput`. |
| `TotpSettings` | TOTP status, setup, enable, and disable controls. | | `TotpSettings` | TOTP status, setup, enable, and disable controls. |
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update the matching category table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the tables aligned with that barrel file, place each component in the category that matches its primary purpose, and do not add internal or generated components to them. This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update the matching category table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the tables aligned with that barrel file, place each component in the category that matches its primary purpose, and do not add internal or generated components to them.
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks. The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
### AuthGuard session validation
The Go and Python `AuthClient.validate()` helpers cache both valid and invalid session results for two seconds. If a session is revoked directly in AuthGuard, a service using that cache may accept it for up to two more seconds. Calling logout through the same client clears its cached result immediately.
--- ---
## How consumers actually use this ## How consumers actually use this
@@ -132,9 +136,9 @@ go test ./...
go vet ./... go vet ./...
``` ```
Go tests that need PostgreSQL skip themselves unless a scratch database is named: `DATABASE_URL` for the auth store tests, `SHARED_TEST_DATABASE_URL` for the platform-user, mediacore and migrate tests. They create tables and delete rows, so never point either at a real database. CI runs them against a throwaway PostgreSQL service (`go test -p 1 ./...`). 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, media 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.
--- ---
+9 -9
View File
@@ -3,11 +3,11 @@
- **Project:** shared - **Project:** shared
- **Path:** /workspace/Personal/Web/shared - **Path:** /workspace/Personal/Web/shared
- **Analyzed:** 2026-10-16 - **Analyzed:** 2026-10-16
- **Commit:** 5216031 on main - **Commit:** 22887fe on main
- **Working tree:** 9 uncommitted change(s): `.changeset/user-management-roles.md` and `packages/web-ui/src/lib/components/UserManagement.svelte` deleted; `.changeset/remove-user-management.md` untracked; `README.md`, `MediaPlayerControls.svelte`, `packages/web-ui/src/lib/index.ts`, `packages/web-ui/src/lib/styles.css`, `packages/web-ui/src/lib/types.ts`, `shared-styles.css` modified. None of them touches authentication code. - **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
- **Stack:** Go 1.25 (`backend/`: session proxy, AuthGuard client, websocket sync hub, media core, CarrierNode client, log shipper, Postgres helpers, goose migrations); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; Gitea and GitHub Actions. No Dockerfile is present. - **Stack:** Go 1.25 (`backend/`: session proxy, AuthGuard client, websocket sync hub, media core, CarrierNode client, log shipper, Postgres helpers, goose migrations); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; Gitea and GitHub Actions. No Dockerfile is present.
- **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings come from read-only static review passes, and the highest-severity citations were re-checked in the code. Nothing was built, run, audited or sent to the network. - **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings came from read-only static review passes, and the highest-severity citations were re-checked in the code. Available checks run during this continuation: shared Node/Python/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-19 — Critical, High and Medium findings handled in the working tree (not committed). Owner decisions 5, 8 and 12 applied in the same working tree (not committed). Second Medium pass: S-009 and S-016 fixed (S-013's heading corrected to Fixed); S-010 and S-011 stay open and name the decisions they need. - **Updated:** 2026-10-20 — shared decisions implemented in the working tree: S-011 fixed; S-010 partly fixed with its undecided session-revocation portion left open. Available Node and web-ui checks pass; Python, Go and Java verification limits are recorded below.
## Summary ## Summary
@@ -15,7 +15,7 @@
|---|---:|---:|---:|---:| |---|---:|---:|---:|---:|
| Critical | 1 | 1 | 0 | 0 | | Critical | 1 | 1 | 0 | 0 |
| High | 3 | 2 | 0 | 1 | | High | 3 | 2 | 0 | 1 |
| Medium | 13 | 11 | 0 | 2 | | Medium | 13 | 12 | 0 | 1 |
| Low | 5 | 0 | 0 | 5 | | Low | 5 | 0 | 0 | 5 |
| Info | 0 | 0 | 0 | 0 | | Info | 0 | 0 | 0 | 0 |
@@ -91,14 +91,14 @@ The most serious issue is a Python router route that lets an anonymous caller sw
- **Description:** A new password is validated and forwarded to AuthGuard without asking for the current password or a TOTP code. - **Description:** A new password is validated and forwarded to AuthGuard without asking for the current password or a TOTP code.
- **Impact:** A stolen or fixated session cookie becomes permanent account takeover, because the attacker can set a new password. Needs verification of whether AuthGuard revokes other sessions on password change. - **Impact:** A stolen or fixated session cookie becomes permanent account takeover, because the attacker can set a new password. Needs verification of whether AuthGuard revokes other sessions on password change.
- **Recommendation:** Require the current password (and a TOTP code when enabled) for password or email changes, and revoke other sessions when the password changes. - **Recommendation:** Require the current password (and a TOTP code when enabled) for password or email changes, and revoke other sessions when the password changes.
- **Status:** Open 2026-10-19 — re-verified, not changed: `UpdateMe` (`backend/auth/proxy.go`) and `update_me` (`authproxy.py`) still forward a new password on the session cookie alone. Decisions needed: (1) require `currentPassword` (and `totpToken` when TOTP is on) whenever `password` is set, checked through an AuthGuard login call or a new AuthGuard endpoint; this changes the request shape that web-ui and every consumer client send; (2) whether a password change revokes the account's other sessions, which AuthGuard owns. - **Status:** Partly fixed 2026-10-20 — the decided rule is implemented: Go and Python self-service profile updates require `currentPassword` for a password change and a TOTP code when enabled; both reauthenticate through AuthGuard, omit proof fields from the managed-user update, and attempt to clear the temporary session. The shared web-ui prompts for and sends those values. No self-service `UpdateMe` route exists in the shared Node or Java clients. Still open: revoking other sessions after a password change is controlled by AuthGuard and has no owner decision. Files: `backend/auth/proxy.go`, `backend/auth/proxy_handlers_test.go`, `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`, `packages/web-ui/src/lib/components/ProfileDialog.svelte`, `packages/web-ui/tests/ProfileDialog.test.ts`.
### S-011 · TOTP codes can be replayed within their validity window in every runtime · **Medium** · Open ### S-011 · TOTP codes can be replayed within their validity window in every runtime · **Medium** · Open
- **Location:** `backend/auth/totp.go:56` (`VerifyTOTP` returns only a bool and does not report the matched step), `backend/auth/store.go:70-84` (no last-used-step column), `packages/node-backend/src/totp.js:26-53`, `packages/python-backend/src/shared_backend/totp.py:38-66`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:44-88` (per review) - **Location:** `backend/auth/totp.go` and `packages/{node-backend/src/totp.js,python-backend/src/shared_backend/totp.py,java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}` return the matched time step; Go, Node and Python auth stores persist it.
- **Description:** Verification accepts the current and adjacent 30-second steps and records nothing about use. A code that an attacker observes stays valid for about 90 seconds and can be submitted repeatedly within that window. - **Description:** Verification accepts the current and adjacent 30-second steps and records nothing about use. A code that an attacker observes stays valid for about 90 seconds and can be submitted repeatedly within that window.
- **Impact:** A phished or shoulder-surfed code can be reused. - **Impact:** A phished or shoulder-surfed code can be reused.
- **Recommendation:** Return the matched time step, persist `last_used_step` per user, and reject any step less than or equal to it, updating it atomically. - **Recommendation:** Return the matched time step, persist `last_used_step` per user, and reject any step less than or equal to it, updating it atomically.
- **Status:** Open 2026-10-19 — re-verified, not changed. AuthGuard calls the shared `VerifyTOTP` for login, verify and disable (`Central/AuthGuard/internal/httpapi/auth.go`, `totp.go`) and keeps TOTP state in the shared `auth.Store`, so the fix spans this library and AuthGuard. It needs the verifiers to return the matched time step, a `last_used_step` column on `auth_users` (an additive `ADD COLUMN IF NOT EXISTS` in each runtime's schema) advanced atomically with a `WHERE last_used_step < $step` guard, and AuthGuard calling the new API. Decision needed: approve the new column and the semantics change (a code already used inside its window is refused at login), after which the three stores and AuthGuard change together. - **Status:** Fixed 2026-10-20 — verifiers return the matched time step; Go, Node and Python stores add `last_used_step` through additive schema changes and atomically advance it only when the step is newer. AuthGuard consumes steps for login, enrollment and disable, so a code already used in its validity window is refused. Files: `backend/auth/{totp.go,store.go}`, `Central/AuthGuard/internal/httpapi/{auth.go,totp.go,server.go}`, `packages/{node-backend/src/{auth.js,totp.js},python-backend/src/shared_backend/{auth.py,totp.py},java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}`. 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 ### S-012 · The Java client parses the authentication decision with unanchored regular expressions · **Medium** · Fixed
- **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review) - **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review)
@@ -178,5 +178,5 @@ The most serious issue is a Python router route that lets an anonymous caller sw
- **Web UI:** No `{@html}`, `innerHTML`, `eval` or `new Function` was found. External links use `rel="noreferrer"`. `fetch` is used only in `StatusWidget.svelte` (same-origin relative paths with credentials included); auth requests are delegated to the consuming application through callbacks, so CSRF and session handling live in the backend. The primary-color writer builds CSS only from palette values. - **Web UI:** No `{@html}`, `innerHTML`, `eval` or `new Function` was found. External links use `rel="noreferrer"`. `fetch` is used only in `StatusWidget.svelte` (same-origin relative paths with credentials included); auth requests are delegated to the consuming application through callbacks, so CSRF and session handling live in the backend. The primary-color writer builds CSS only from palette values.
- **Checked, no issue found:** SQL is parameterised in the Go, Node and Python stores and in the mediacore queries; dynamic `SET` fragments use fixed column names. Tokens and secrets come from `crypto/rand`, `crypto.randomBytes`, Python `secrets` and `SecureRandom`; no `math/rand`, `Math.random`, `random.` or `java.util.Random` was found. Session tokens are 256-bit and stored as SHA-256 hashes, and no JWT is used. No `eval`, `pickle`, `yaml.load`, `shell=True`, `os.system` or `exec.Command` appears in scope. No `InsecureSkipVerify` on any TLS configuration; the only use is the websocket origin option (S-014). The Go request bodies are capped (512 KB for mediacore, 4 KB for coreconfig, 128 KB for the proxy). Outbound clients have timeouts. Logout clears cookies with `HttpOnly` and `SameSite` in the Python proxy. No CORS configuration or debug mode was found. - **Checked, no issue found:** SQL is parameterised in the Go, Node and Python stores and in the mediacore queries; dynamic `SET` fragments use fixed column names. Tokens and secrets come from `crypto/rand`, `crypto.randomBytes`, Python `secrets` and `SecureRandom`; no `math/rand`, `Math.random`, `random.` or `java.util.Random` was found. Session tokens are 256-bit and stored as SHA-256 hashes, and no JWT is used. No `eval`, `pickle`, `yaml.load`, `shell=True`, `os.system` or `exec.Command` appears in scope. No `InsecureSkipVerify` on any TLS configuration; the only use is the websocket origin option (S-014). The Go request bodies are capped (512 KB for mediacore, 4 KB for coreconfig, 128 KB for the proxy). Outbound clients have timeouts. Logout clears cookies with `HttpOnly` and `SameSite` in the Python proxy. No CORS configuration or debug mode was found.
- **Dependencies (not audited):** No known-vulnerable version is asserted in this report, since no audit tool or network access was used. Versions to confirm: Go `coder/websocket` v1.8.15, `go-chi/chi` v5.3.1, `pgx` v5.10.0, `goose` v3.27.3, `golang.org/x/crypto` v0.54.0 (`backend/go.mod`); Node `pg` 8.22.0 (locked in `package-lock.json`, declared `^8.17.2`); Python `bcrypt>=4.2` and `asyncpg>=0.30` with no upper bounds (`packages/python-backend/pyproject.toml`); Java Jackson 2.18.6, JUnit 5.10.2 (`packages/java-backend/pom.xml`). Run `govulncheck`, `npm audit`, `pip-audit` and an OWASP dependency check. - **Dependencies (not audited):** No known-vulnerable version is asserted in this report, since no audit tool or network access was used. Versions to confirm: Go `coder/websocket` v1.8.15, `go-chi/chi` v5.3.1, `pgx` v5.10.0, `goose` v3.27.3, `golang.org/x/crypto` v0.54.0 (`backend/go.mod`); Node `pg` 8.22.0 (locked in `package-lock.json`, declared `^8.17.2`); Python `bcrypt>=4.2` and `asyncpg>=0.30` with no upper bounds (`packages/python-backend/pyproject.toml`); Java Jackson 2.18.6, JUnit 5.10.2 (`packages/java-backend/pom.xml`). Run `govulncheck`, `npm audit`, `pip-audit` and an OWASP dependency check.
- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. Test bodies were not run, and no server was started. - **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. The shared Node (73 tests), Python (122 tests), and web-ui (29 tests) suites 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`. - **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and `node_modules`.
+1 -1
View File
@@ -10,7 +10,7 @@ services, not application-specific SQL or HTTP handlers.
- `migrate` — embedded filesystem adapter for Goose migrations. - `migrate` — embedded filesystem adapter for Goose migrations.
- `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package. - `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package.
Run `go test ./...` and `go vet ./...` from this directory. Tests that need PostgreSQL skip themselves unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` (platform users, mediacore, migrate) names a scratch database; use `go test -p 1 ./...` when both are set. The module path is Run `go test ./...` and `go vet ./...` from this directory. Tests that need PostgreSQL skip themselves unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` (platform users, media, migrate) names a scratch database; use `go test -p 1 ./...` when both are set. The module path is
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is `repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
hosted under a different repository path. hosted under a different repository path.
+35
View File
@@ -0,0 +1,35 @@
package auth
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
)
// MountAccountRoutes mounts the signed-in account routes onto r: the TOTP enrollment and
// verification routes, which require a session, and GET /profile, which reports the session's
// user or null. A project that signs users in through AuthGuard mounts these alongside its own
// routes.
func (s *Service) MountAccountRoutes(r chi.Router) {
r.With(s.Require).Get("/security/totp/status", s.TOTPStatus)
r.With(s.Require).Get("/security/totp/initiate", s.TOTPInitiate)
r.With(s.Require).Post("/security/totp/verify", s.TOTPVerify)
r.With(s.Require).Post("/security/totp/disable", s.TOTPDisable)
r.With(s.Optional).Get("/profile", profile)
}
func profile(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
writeAccountJSON(w, http.StatusOK, map[string]any{"user": nil})
return
}
writeAccountJSON(w, http.StatusOK, map[string]any{"user": user})
}
func writeAccountJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
+64
View File
@@ -0,0 +1,64 @@
package auth
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-chi/chi/v5"
)
func TestProfileReportsTheSessionUser(t *testing.T) {
guard := newRoleAuthGuard(t)
auth := NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
router := chi.NewRouter()
auth.MountAccountRoutes(router)
anonymous := httptest.NewRecorder()
router.ServeHTTP(anonymous, httptest.NewRequest(http.MethodGet, "/profile", nil))
if anonymous.Code != http.StatusOK || strings.TrimSpace(anonymous.Body.String()) != `{"user":null}` {
t.Fatalf("anonymous profile = %d %s, want a null user", anonymous.Code, anonymous.Body.String())
}
request := httptest.NewRequest(http.MethodGet, "/profile", nil)
request.AddCookie(&http.Cookie{Name: "auth_session", Value: "viewer-token"})
known := httptest.NewRecorder()
router.ServeHTTP(known, request)
var body struct{ User map[string]any }
if err := json.Unmarshal(known.Body.Bytes(), &body); err != nil || body.User["username"] != "tester" || body.User["role"] != "user" {
t.Fatalf("profile = %s, %v", known.Body.String(), err)
}
}
type loginRequiredStore struct{}
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
// loginOffStore is loginRequiredStore with login switched off for the whole application.
type loginOffStore struct{ loginRequiredStore }
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
func newRoleAuthGuard(t *testing.T) *httptest.Server {
t.Helper()
roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
role, ok := roles[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
if !ok || r.URL.Path != "/api/me" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"user":{"id":1,"username":"tester","role":%q}}`, role)
}))
t.Cleanup(server.Close)
return server
}
+35 -14
View File
@@ -19,10 +19,12 @@ type authContract struct {
Plaintext string `json:"plaintext"` Plaintext string `json:"plaintext"`
WrongPassword string `json:"wrongPassword"` WrongPassword string `json:"wrongPassword"`
Hashes []struct { Hashes []struct {
Name string `json:"name"` Name string `json:"name"`
Hash string `json:"hash"` Hash string `json:"hash"`
Verifies map[string]bool `json:"verifies"` Password string `json:"password"`
NeedsUpgrade map[string]bool `json:"needsUpgrade"` WrongPassword string `json:"wrongPassword"`
Verifies map[string]bool `json:"verifies"`
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
} `json:"hashes"` } `json:"hashes"`
TooLongToHash struct { TooLongToHash struct {
Bytes int `json:"bytes"` Bytes int `json:"bytes"`
@@ -32,11 +34,12 @@ type authContract struct {
TOTP struct { TOTP struct {
Secret string `json:"secret"` Secret string `json:"secret"`
Cases []struct { Cases []struct {
Name string `json:"name"` Name string `json:"name"`
Unix int64 `json:"unix"` Unix int64 `json:"unix"`
Code string `json:"code"` Code string `json:"code"`
Secret *string `json:"secret"` Secret *string `json:"secret"`
Valid bool `json:"valid"` MatchedStep *int64 `json:"matchedStep"`
Valid bool `json:"valid"`
} `json:"cases"` } `json:"cases"`
} `json:"totp"` } `json:"totp"`
ClientAddress struct { ClientAddress struct {
@@ -71,21 +74,29 @@ func TestContractPasswordHashes(t *testing.T) {
contract := loadContract(t) contract := loadContract(t)
for _, entry := range contract.Password.Hashes { for _, entry := range contract.Password.Hashes {
t.Run(entry.Name, func(t *testing.T) { t.Run(entry.Name, func(t *testing.T) {
if got := VerifyPassword(entry.Hash, contract.Password.Plaintext); got != entry.Verifies["go"] { password := entry.Password
if password == "" {
password = contract.Password.Plaintext
}
wrongPassword := entry.WrongPassword
if wrongPassword == "" {
wrongPassword = contract.Password.WrongPassword
}
if got := VerifyPassword(entry.Hash, password); got != entry.Verifies["go"] {
t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"]) t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"])
} }
if VerifyPassword(entry.Hash, contract.Password.WrongPassword) { if VerifyPassword(entry.Hash, wrongPassword) {
t.Error("VerifyPassword accepted the wrong password") t.Error("VerifyPassword accepted the wrong password")
} }
if want, ok := entry.NeedsUpgrade["go"]; ok { if want, ok := entry.NeedsUpgrade["go"]; ok {
if got := PasswordHashNeedsUpgrade(entry.Hash); got != want { if got := PasswordHashNeedsUpgrade(entry.Hash); got != want {
t.Errorf("PasswordHashNeedsUpgrade = %v, want %v", got, want) t.Errorf("PasswordHashNeedsUpgrade = %v, want %v", got, want)
} }
valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, contract.Password.Plaintext) valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, password)
if err != nil || !valid || (upgraded != "") != want { if err != nil || !valid || (upgraded != "") != want {
t.Errorf("VerifyAndUpgradePassword = %v, upgraded %v, %v; want valid with an upgrade = %v", valid, upgraded != "", err, want) t.Errorf("VerifyAndUpgradePassword = %v, upgraded %v, %v; want valid with an upgrade = %v", valid, upgraded != "", err, want)
} }
if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) || !VerifyPassword(upgraded, contract.Password.Plaintext)) { if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) && !strings.HasPrefix(upgraded, bcryptSHA256Scheme) || !VerifyPassword(upgraded, password)) {
t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded) t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded)
} }
} }
@@ -109,9 +120,19 @@ func TestContractTOTP(t *testing.T) {
if entry.Secret != nil { if entry.Secret != nil {
secret = *entry.Secret secret = *entry.Secret
} }
if got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0)); got != entry.Valid { step, got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0))
if got != entry.Valid {
t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid) t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid)
} }
if got {
want := entry.Unix / 30
if entry.MatchedStep != nil {
want = *entry.MatchedStep
}
if step != want {
t.Errorf("VerifyTOTP matched step %d, want %d", step, want)
}
}
}) })
} }
} }
+75 -3
View File
@@ -1,9 +1,15 @@
package auth package auth
import ( import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
"strconv"
"strings" "strings"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/pbkdf2"
) )
// BcryptCost is kept in one place so all services use the same password // BcryptCost is kept in one place so all services use the same password
@@ -17,9 +23,19 @@ const BcryptCost = 12
// with "$"). Unprefixed bcrypt hashes from before the prefix still verify and // with "$"). Unprefixed bcrypt hashes from before the prefix still verify and
// are upgraded on login. // are upgraded on login.
const bcryptScheme = "bcrypt$" const bcryptScheme = "bcrypt$"
const bcryptSHA256Scheme = "bcrypt-sha256$"
const (
maxPasswordBytes = 72
legacyPBKDF2Iterations = 100000
maxPBKDF2Iterations = 10000000
)
// HashPassword returns a versioned password hash suitable for storage. // HashPassword returns a versioned password hash suitable for storage.
func HashPassword(password string) (string, error) { func HashPassword(password string) (string, error) {
if len([]byte(password)) > maxPasswordBytes {
return "", errors.New("password must be at most 72 bytes")
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost) hash, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
if err != nil { if err != nil {
return "", err return "", err
@@ -27,20 +43,38 @@ func HashPassword(password string) (string, error) {
return bcryptScheme + string(hash), nil return bcryptScheme + string(hash), nil
} }
// VerifyPassword checks a plaintext password against a stored hash. It accepts // VerifyPassword checks a plaintext password against bcrypt and legacy Node
// hashes from HashPassword and unprefixed bcrypt hashes; any other format // PBKDF2 hashes. A valid legacy hash is rewritten by VerifyAndUpgradePassword.
// fails closed.
func VerifyPassword(hash, password string) bool { func VerifyPassword(hash, password string) bool {
if bcryptHash, ok := strings.CutPrefix(hash, bcryptSHA256Scheme); ok {
digest := sha256.Sum256([]byte(password))
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(hex.EncodeToString(digest[:]))) == nil
}
if iterations, salt, expected, ok := parsePBKDF2Hash(hash); ok {
actual := pbkdf2.Key([]byte(password), []byte(salt), iterations, 32, sha256.New)
expectedBytes, err := hex.DecodeString(expected)
return err == nil && subtle.ConstantTimeCompare(expectedBytes, actual) == 1
}
bcryptHash, ok := bcryptHashOf(hash) bcryptHash, ok := bcryptHashOf(hash)
if !ok { if !ok {
return false return false
} }
if len([]byte(password)) > maxPasswordBytes {
return false
}
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(password)) == nil return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(password)) == nil
} }
// PasswordHashNeedsUpgrade reports whether a stored hash is not in the current // PasswordHashNeedsUpgrade reports whether a stored hash is not in the current
// scheme: an unprefixed legacy hash, or a bcrypt cost below BcryptCost. // scheme: an unprefixed legacy hash, or a bcrypt cost below BcryptCost.
func PasswordHashNeedsUpgrade(hash string) bool { func PasswordHashNeedsUpgrade(hash string) bool {
if bcryptHash, prefixed := strings.CutPrefix(hash, bcryptSHA256Scheme); prefixed {
cost, err := bcrypt.Cost([]byte(bcryptHash))
return err != nil || cost < BcryptCost
}
if _, _, _, ok := parsePBKDF2Hash(hash); ok {
return true
}
bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme) bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme)
if !prefixed { if !prefixed {
return true return true
@@ -61,6 +95,15 @@ func VerifyAndUpgradePassword(hash, password string) (valid bool, upgraded strin
if !PasswordHashNeedsUpgrade(hash) { if !PasswordHashNeedsUpgrade(hash) {
return true, "", nil return true, "", nil
} }
if len([]byte(password)) > maxPasswordBytes {
digest := sha256.Sum256([]byte(password))
var hashBytes []byte
hashBytes, err = bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(digest[:])), BcryptCost)
if err == nil {
upgraded = bcryptSHA256Scheme + string(hashBytes)
}
return true, upgraded, err
}
upgraded, err = HashPassword(password) upgraded, err = HashPassword(password)
if err != nil { if err != nil {
return true, "", err return true, "", err
@@ -78,3 +121,32 @@ func bcryptHashOf(stored string) (string, bool) {
} }
return "", false return "", false
} }
func parsePBKDF2Hash(stored string) (iterations int, salt, expected string, ok bool) {
if strings.HasPrefix(stored, "pbkdf2-sha256$") {
parts := strings.Split(stored, "$")
if len(parts) != 4 {
return 0, "", "", false
}
parsedIterations, err := strconv.Atoi(parts[1])
if err != nil {
return 0, "", "", false
}
iterations, salt, expected = parsedIterations, parts[2], parts[3]
} else if strings.Count(stored, ":") == 1 {
parts := strings.SplitN(stored, ":", 2)
iterations, salt, expected = legacyPBKDF2Iterations, parts[0], parts[1]
} else {
return 0, "", "", false
}
if iterations < 1 || iterations > maxPBKDF2Iterations || len(salt) != 32 || len(expected) != 64 {
return 0, "", "", false
}
if _, err := hex.DecodeString(salt); err != nil {
return 0, "", "", false
}
if _, err := hex.DecodeString(expected); err != nil {
return 0, "", "", false
}
return iterations, salt, expected, true
}
@@ -11,7 +11,7 @@ import (
) )
// platformUsersSchema holds the test's own `users` table, so it never meets the fuller table that // platformUsersSchema holds the test's own `users` table, so it never meets the fuller table that
// mediacore's migration creates in the same database. // the media package's migration creates in the same database.
const platformUsersSchema = "platform_users_test" const platformUsersSchema = "platform_users_test"
// withSearchPath returns databaseURL with its search_path set to schema. // withSearchPath returns databaseURL with its search_path set to schema.
@@ -29,7 +29,7 @@ func withSearchPath(t *testing.T, databaseURL, schema string) string {
// TestPlatformUserSQL runs the moderatable platform-user methods (CreateUser, ListUsers, // TestPlatformUserSQL runs the moderatable platform-user methods (CreateUser, ListUsers,
// UpdateUser, SetPassword, DeleteUser) against a real database. The `users` table normally comes // UpdateUser, SetPassword, DeleteUser) against a real database. The `users` table normally comes
// from mediacore's migration, which this package cannot import, so the test creates the columns it // from the media package's migration, which this package cannot import, so the test creates the columns it
// needs in a schema of its own. It is skipped unless SHARED_TEST_DATABASE_URL points at a scratch // needs in a schema of its own. It is skipped unless SHARED_TEST_DATABASE_URL points at a scratch
// database, for example: // database, for example:
// //
+91 -45
View File
@@ -1,10 +1,7 @@
// This file holds the shared media-backend family's /auth/... and /api/auth/... // This file holds the /auth/... and /api/auth/... handlers, proxied to AuthGuard. Promoted from
// handlers, proxied to AuthGuard. Promoted from each service's own // each service's own internal/auth into this shared library so every project that signs users in
// internal/auth into this shared library so all 7 independent media-family // through AuthGuard uses one copy instead of duplicating it. It was merged here from a separate
// backends (CarrierNode, ModerationHub, ProjectConfigurator, KioskDisplay, // package (2026-09-13) since it is not specific to any one project - see "Unified
// MediaViewer, ContentScanner, CraftStudio) use one copy instead of
// duplicating it. Originally its own "mediaauth" package; merged into this
// package (2026-09-13) since it is no longer media-specific - see "Unified
// auth proxy" below - and "auth" is the more accurate name for what it now // auth proxy" below - and "auth" is the more accurate name for what it now
// is. ProxyUser/ProxyStore/Service/New/NewWithStore below are this file's // is. ProxyUser/ProxyStore/Service/New/NewWithStore below are this file's
// exports; everything else in this package (Store, User, Role, TOTP, // exports; everything else in this package (Store, User, Role, TOTP,
@@ -13,9 +10,8 @@
// //
// Unified auth proxy // Unified auth proxy
// ================== // ==================
// This file used to be its own package, specific to the 7 media-family // This file used to be its own package, built around New and wired directly to the shared
// backends (each built via New, wired directly to their own shared Postgres // Postgres `settings` table. It is now the ONE shared auth-proxy engine for every
// `settings` table). It is now the ONE shared auth-proxy engine for every
// project in this workspace that centralizes identity through AuthGuard - // project in this workspace that centralizes identity through AuthGuard -
// GameStream, Bitmagnet, and OmniLogger, which each used to independently // GameStream, Bitmagnet, and OmniLogger, which each used to independently
// reimplement this same session/login/TOTP/admin-user proxy against their // reimplement this same session/login/TOTP/admin-user proxy against their
@@ -23,7 +19,7 @@
// ProxyStore adapter over whatever local table they already used for their // ProxyStore adapter over whatever local table they already used for their
// "login required" toggle and one-time setup-claim flag (see the ProxyStore // "login required" toggle and one-time setup-claim flag (see the ProxyStore
// interface below), instead of duplicating this file's logic. New (the // interface below), instead of duplicating this file's logic. New (the
// original media-family constructor) is unchanged and is really just // original constructor) is unchanged and is really just
// NewWithStore plus pgSettingsStore, the default ProxyStore implementation // NewWithStore plus pgSettingsStore, the default ProxyStore implementation
// backed by the shared `settings` table. // backed by the shared `settings` table.
// //
@@ -44,7 +40,7 @@
// //
// It now proxies every auth operation to AuthGuard (Web/Core/AuthGuard), // It now proxies every auth operation to AuthGuard (Web/Core/AuthGuard),
// a centralized identity service other projects in this workspace share, // a centralized identity service other projects in this workspace share,
// via the `authclient` package (Web/Core/shared/backend/authclient). This // via the `authclient` package (shared/backend/authclient). This
// service's own /auth/... and /api/auth/... URL paths and JSON response // service's own /auth/... and /api/auth/... URL paths and JSON response
// shapes are UNCHANGED - the frontend (webui) was not touched - only // shapes are UNCHANGED - the frontend (webui) was not touched - only
// what backs them changed. This mirrors the migration // what backs them changed. This mirrors the migration
@@ -165,9 +161,9 @@ package auth
import ( import (
"context" "context"
"crypto/subtle"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"io" "io"
"mime" "mime"
"net" "net"
@@ -183,6 +179,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy" "repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
) )
// ProxyUser is this service's own /auth/... response shape - UNCHANGED from // ProxyUser is this service's own /auth/... response shape - UNCHANGED from
@@ -223,7 +220,7 @@ var (
// message rather than a generic "internal error" that would be // message rather than a generic "internal error" that would be
// indistinguishable from any other server bug. // indistinguishable from any other server bug.
errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.") errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.")
errSecretNotSet = errors.New("SECRET environment variable is not set.") errSecretNotUsable = fmt.Errorf("SECRET environment variable is unset, shorter than %d characters, or an example placeholder.", coreconfig.MinInternalSecretLength)
errTooManyAttempts = errors.New("Too many attempts. Try again later.") errTooManyAttempts = errors.New("Too many attempts. Try again later.")
errSetupRequiresLogin = errors.New("Account setup is only available while login is required.") errSetupRequiresLogin = errors.New("Account setup is only available while login is required.")
errNoLoginRequiredStore = errors.New("the login-required setting has no store to save to") errNoLoginRequiredStore = errors.New("the login-required setting has no store to save to")
@@ -256,7 +253,7 @@ var adminProfile = ProxyUser{ID: 0, Username: "Admin", Email: "", Role: string(R
// AuthGuard migration - see the package doc comment's second paragraph) and // AuthGuard migration - see the package doc comment's second paragraph) and
// the one-time "has this deployment's setup screen been completed" claim // the one-time "has this deployment's setup screen been completed" claim
// flag (see the "Setup flow" section below). pgSettingsStore is the // flag (see the "Setup flow" section below). pgSettingsStore is the
// implementation New builds automatically over the media family's shared // implementation New builds automatically over the shared
// `settings` table; NewWithStore accepts any other implementation, letting a // `settings` table; NewWithStore accepts any other implementation, letting a
// project with its own storage (GameStream's/Bitmagnet's/OmniLogger's own // project with its own storage (GameStream's/Bitmagnet's/OmniLogger's own
// tables) reuse this package without adopting that generic table. // tables) reuse this package without adopting that generic table.
@@ -271,7 +268,7 @@ type ProxyStore interface {
type Service struct { type Service struct {
// db backs only the "moderatable platform users" section at the bottom // db backs only the "moderatable platform users" section at the bottom
// of this file (CreateUser/ListUsers/UpdateUser/SetPassword/DeleteUser), // of this file (CreateUser/ListUsers/UpdateUser/SetPassword/DeleteUser),
// a media-family-specific concept unrelated to AuthGuard identity - see // a concept specific to the platform-users table, unrelated to AuthGuard identity - see
// that section's own doc comment. nil for a Service built via // that section's own doc comment. nil for a Service built via
// NewWithStore; those methods are simply never called by a project with // NewWithStore; those methods are simply never called by a project with
// no such local platform-user table. // no such local platform-user table.
@@ -286,10 +283,14 @@ type Service struct {
// real base URL. // real base URL.
authGuard *authclient.Client authGuard *authclient.Client
configurationError error configurationError error
loginCacheMu sync.Mutex // reauthenticateEmailChanges is opt-in because older consumers historically
loginCacheValue bool // allowed email-only edits without the current password. Password changes
loginCacheSet bool // always require current credentials in UpdateMe.
loginCacheExpires time.Time reauthenticateEmailChanges bool
loginCacheMu sync.Mutex
loginCacheValue bool
loginCacheSet bool
loginCacheExpires time.Time
// Attempt counters for the credential endpoints; see ratelimit.go. // Attempt counters for the credential endpoints; see ratelimit.go.
loginAccountAttempts *attemptLimiter loginAccountAttempts *attemptLimiter
loginClientAttempts *attemptLimiter loginClientAttempts *attemptLimiter
@@ -305,9 +306,10 @@ type Service struct {
type ServiceOption func(*serviceOptions) type ServiceOption func(*serviceOptions)
type serviceOptions struct { type serviceOptions struct {
disabled bool disabled bool
requireSecret bool requireSecret bool
trustedProxies []*net.IPNet reauthenticateEmailChanges bool
trustedProxies []*net.IPNet
} }
// Disabled explicitly builds a Service in auth-disabled mode (see the // Disabled explicitly builds a Service in auth-disabled mode (see the
@@ -329,6 +331,14 @@ func RequireSecret() ServiceOption {
return func(o *serviceOptions) { o.requireSecret = true } return func(o *serviceOptions) { o.requireSecret = true }
} }
// ReauthenticateEmailChanges requires current-password proof, and TOTP when
// enabled, for email changes through UpdateMe. Password changes already
// require the same proof. This is opt-in to preserve existing consumers that
// have not adopted the matching profile-dialog flow.
func ReauthenticateEmailChanges() ServiceOption {
return func(o *serviceOptions) { o.reauthenticateEmailChanges = true }
}
// WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is // WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is
// honoured when a login's client address is taken. Build the list from the // honoured when a login's client address is taken. Build the list from the
// TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer // TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer
@@ -337,7 +347,7 @@ func WithTrustedProxies(networks []*net.IPNet) ServiceOption {
return func(o *serviceOptions) { o.trustedProxies = networks } return func(o *serviceOptions) { o.trustedProxies = networks }
} }
// New constructs a Service backed by the media family's shared `settings` // New constructs a Service backed by the shared `settings`
// table (pgSettingsStore) for the login-required toggle and setup-claim // table (pgSettingsStore) for the login-required toggle and setup-claim
// flag, and by db directly for the unrelated "moderatable platform users" // flag, and by db directly for the unrelated "moderatable platform users"
// section. cookieName/secureCookies are retained only for clearing the // section. cookieName/secureCookies are retained only for clearing the
@@ -359,7 +369,7 @@ func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL,
// NewWithStore constructs a Service against any ProxyStore implementation, // NewWithStore constructs a Service against any ProxyStore implementation,
// for a project whose login-required toggle and setup-claim flag live in // for a project whose login-required toggle and setup-claim flag live in
// its own storage rather than the media family's shared `settings` table. // its own storage rather than the shared `settings` table.
// Its resulting Service has no db (the "moderatable platform users" section // Its resulting Service has no db (the "moderatable platform users" section
// is unavailable - a project adopting this package fresh has no such // is unavailable - a project adopting this package fresh has no such
// feature to preserve). // feature to preserve).
@@ -379,25 +389,25 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey)) client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey))
} }
var configurationError error var configurationError error
if options.requireSecret && !options.disabled && strings.TrimSpace(os.Getenv("SECRET")) == "" { if options.requireSecret && !options.disabled && !coreconfig.InternalSecretUsable(strings.TrimSpace(os.Getenv("SECRET"))) {
configurationError = errSecretNotSet configurationError = errSecretNotUsable
} }
return &Service{ return &Service{
store: store, store: store,
cookieName: cookieName, cookieName: cookieName,
secureCookies: secureCookies, secureCookies: secureCookies,
authGuard: client, authGuard: client,
configurationError: configurationError, configurationError: configurationError,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit), reauthenticateEmailChanges: options.reauthenticateEmailChanges,
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit), loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit), loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
trustedProxies: options.trustedProxies, totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
trustedProxies: options.trustedProxies,
} }
} }
// pgSettingsStore is the default ProxyStore New builds over the media // pgSettingsStore is the default ProxyStore New builds over the shared
// family's shared `settings` key/value table (see mediacore.SettingValue/ // `settings` key/value table (see settings.Value/settings.Save) - unchanged behavior from before this package accepted a
// SaveSetting) - unchanged behavior from before this package accepted a
// pluggable ProxyStore. // pluggable ProxyStore.
type pgSettingsStore struct { type pgSettingsStore struct {
db *pgxpool.Pool db *pgxpool.Pool
@@ -694,9 +704,11 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
} }
var input struct { var input struct {
Email string `json:"email"` Email string `json:"email"`
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
CurrentPassword string `json:"currentPassword"`
TOTPToken string `json:"totpToken"`
} }
if err := decodeProxyJSON(r, &input); err != nil { if err := decodeProxyJSON(r, &input); err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid JSON body") writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
@@ -719,7 +731,29 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
writeProxyError(w, http.StatusBadRequest, err.Error()) writeProxyError(w, http.StatusBadRequest, err.Error())
return 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) token := s.sessionToken(r)
@@ -736,6 +770,18 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
writeProxyJSON(w, http.StatusOK, map[string]any{"user": updated}) writeProxyJSON(w, http.StatusOK, map[string]any{"user": updated})
} }
func temporarySessionToken(session *authclient.SessionResult) string {
if session == nil {
return ""
}
for _, cookie := range session.Cookies {
if cookie != nil && cookie.Name == authclient.DefaultCookieName {
return cookie.Value
}
}
return ""
}
// AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc // AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc
// comment's "Setup flow" section. // comment's "Setup flow" section.
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) { func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
@@ -856,7 +902,7 @@ func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
// expose the same propagation endpoint without duplicating its JSON handling. // expose the same propagation endpoint without duplicating its JSON handling.
func (s *Service) SetLoginRequiredInternal(secret string) http.Handler { func (s *Service) SetLoginRequiredInternal(secret string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.TrimSpace(secret) == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 { if !coreconfig.InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) {
writeProxyError(w, http.StatusUnauthorized, "internal service authentication required") writeProxyError(w, http.StatusUnauthorized, "internal service authentication required")
return return
} }
@@ -1578,7 +1624,7 @@ func normalizePlatformRole(role string) string {
// idURLParam extracts the "{id}" path segment from ManagedUpdateUser's/ // idURLParam extracts the "{id}" path segment from ManagedUpdateUser's/
// ManagedDeleteUser's route regardless of which router mounted it: chi's // ManagedDeleteUser's route regardless of which router mounted it: chi's
// URLParam for the (7) media-family services that route through chi, or the // URLParam for services that route through chi, or the
// standard library's 1.22+ ServeMux PathValue (what GameStream, OmniLogger, // standard library's 1.22+ ServeMux PathValue (what GameStream, OmniLogger,
// and other non-chi consumers of this package use) when chi reports none. // and other non-chi consumers of this package use) when chi reports none.
func idURLParam(r *http.Request) string { func idURLParam(r *http.Request) string {
+37 -6
View File
@@ -406,6 +406,12 @@ func TestTOTPInitiateAndStatus(t *testing.T) {
func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) { func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
guard := newFakeAuthGuard(t) guard := newFakeAuthGuard(t)
guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) {
w.Header().Add("Set-Cookie", authclient.DefaultCookieName+"=reauth-token; Path=/; HttpOnly")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
})
guard.reply("POST /api/logout", http.StatusOK, map[string]any{"ok": true})
guard.reply("PUT /api/admin/users/7", http.StatusOK, map[string]any{}) guard.reply("PUT /api/admin/users/7", http.StatusOK, map[string]any{})
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}}) guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
service, _ := guard.service(t) service, _ := guard.service(t)
@@ -418,7 +424,7 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
service.UpdateMe(rec, req) service.UpdateMe(rec, req)
return rec return rec
} }
manager := &ProxyUser{ID: 7, Role: "admin"} manager := &ProxyUser{ID: 7, Username: "boss", Role: "admin", MFAEnabled: true}
if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized { if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized {
t.Fatalf("no session user: status = %d, want 401", rec.Code) t.Fatalf("no session user: status = %d, want 401", rec.Code)
@@ -427,11 +433,13 @@ func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
t.Fatalf("ordinary user: status = %d, want 403", rec.Code) t.Fatalf("ordinary user: status = %d, want 403", rec.Code)
} }
for name, body := range map[string]string{ for name, body := range map[string]string{
"bad email": `{"email":"nope","username":"boss"}`, "bad email": `{"email":"nope","username":"boss"}`,
"at in username": `{"email":"a@b.com","username":"a@b.com"}`, "at in username": `{"email":"a@b.com","username":"a@b.com"}`,
"short password": `{"email":"a@b.com","username":"boss","password":"short"}`, "short password": `{"email":"a@b.com","username":"boss","password":"short"}`,
"long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`, "long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`,
"not JSON": `nope`, "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 { if rec := update(manager, body); rec.Code != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400", name, rec.Code) 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 { if _, sent := calls[0].Body["password"]; sent {
t.Fatal("an update without a password sent one to AuthGuard") t.Fatal("an update without a password sent one to AuthGuard")
} }
rec = update(manager, `{"email":"boss@example.com","username":"boss","password":"new-password","currentPassword":"current-password","totpToken":"123456"}`)
if rec.Code != http.StatusOK {
t.Fatalf("password update status = %d, body %s", rec.Code, rec.Body.String())
}
loginCalls := guard.callsTo("POST /api/login")
if len(loginCalls) != 1 || loginCalls[0].Body["username_or_email"] != "boss" || loginCalls[0].Body["password"] != "current-password" || loginCalls[0].Body["totp_token"] != "123456" {
t.Fatalf("reauthentication request = %+v", loginCalls)
}
calls = guard.callsTo("PUT /api/admin/users/7")
if len(calls) != 2 || calls[1].Body["password"] != "new-password" {
t.Fatalf("password update request = %+v", calls)
}
if _, sent := calls[1].Body["currentPassword"]; sent {
t.Fatal("current password was forwarded to the managed-user API")
}
if _, sent := calls[1].Body["totpToken"]; sent {
t.Fatal("TOTP code was forwarded to the managed-user API")
}
logoutCalls := guard.callsTo("POST /api/logout")
if len(logoutCalls) != 1 || logoutCalls[0].Authorization != "Bearer reauth-token" {
t.Fatalf("temporary login session was not removed: %+v", logoutCalls)
}
if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" { if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" {
t.Fatalf("response user = %v", user) t.Fatalf("response user = %v", user)
} }
+55 -141
View File
@@ -48,10 +48,7 @@ type SchemaOptions struct {
SingleUser bool SingleUser bool
// APITokens creates the optional per-user API token table. // APITokens creates the optional per-user API token table.
APITokens bool APITokens bool
// ProjectScoping creates auth_known_projects/auth_user_projects, backing per-user // ProjectScoping creates auth_known_projects for AuthGuard's project catalog and admin UI.
// project-access restriction (see Store.SetUserProjects/IsProjectAllowed). Only AuthGuard
// itself needs this - every other project only ever calls AuthGuard's own API, never these
// tables directly.
ProjectScoping bool ProjectScoping bool
} }
@@ -87,6 +84,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
role TEXT NOT NULL DEFAULT 'user', role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '', totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE, totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
last_used_step BIGINT NOT NULL DEFAULT -1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ last_login_at TIMESTAMPTZ
@@ -95,6 +93,7 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user'; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT ''; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
-- last_login_at is nullable (NULL means "never logged in" - registration -- last_login_at is nullable (NULL means "never logged in" - registration
@@ -149,12 +148,6 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
label TEXT NOT NULL DEFAULT '', label TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT now() updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
); );
CREATE TABLE IF NOT EXISTS auth_user_projects (
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
project TEXT NOT NULL,
PRIMARY KEY (user_id, project)
);
CREATE INDEX IF NOT EXISTS auth_user_projects_project_idx ON auth_user_projects (project);
`); err != nil { `); err != nil {
return fmt.Errorf("ensure project-scoping schema: %w", err) return fmt.Errorf("ensure project-scoping schema: %w", err)
} }
@@ -220,8 +213,9 @@ func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error {
// TOTPState is the private provisioning state for one account. Secret must // TOTPState is the private provisioning state for one account. Secret must
// never be included in an API response. // never be included in an API response.
type TOTPState struct { type TOTPState struct {
Secret string Secret string
Enabled bool Enabled bool
LastUsedStep int64
} }
// GetTOTPState reads the stored TOTP provisioning state for an account. // GetTOTPState reads the stored TOTP provisioning state for an account.
@@ -230,7 +224,7 @@ func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, erro
return TOTPState{}, err return TOTPState{}, err
} }
var state TOTPState var state TOTPState
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled) err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false), COALESCE(last_used_step, -1) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled, &state.LastUsedStep)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return TOTPState{}, nil return TOTPState{}, nil
} }
@@ -246,7 +240,7 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string)
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return err return err
} }
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID) tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID)
if err != nil { if err != nil {
return fmt.Errorf("set TOTP secret: %w", err) return fmt.Errorf("set TOTP secret: %w", err)
} }
@@ -262,16 +256,39 @@ func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string)
return nil return nil
} }
// EnableTOTP marks a previously provisioned secret as active. // EnableTOTP marks a previously provisioned secret as active and records the
func (s *Store) EnableTOTP(ctx context.Context, userID int64) error { // step used to confirm it, preventing that code from being reused at login.
func (s *Store) EnableTOTP(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return err return false, err
} }
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID) tag, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET totp_enabled = true, last_used_step = $1, updated_at = now()
WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1
`, step, userID, secret)
if err != nil { if err != nil {
return fmt.Errorf("enable TOTP: %w", err) return false, fmt.Errorf("enable TOTP: %w", err)
} }
return nil return tag.RowsAffected() == 1, nil
}
// ConsumeTOTPStep advances an account's accepted TOTP step only once. The
// expected secret and enabled flag are part of the update so a concurrent
// disable or re-enrollment cannot consume a code against stale state.
func (s *Store) ConsumeTOTPStep(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
if err := s.validate(); err != nil {
return false, err
}
tag, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET last_used_step = $1, updated_at = now()
WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1
`, step, userID, secret)
if err != nil {
return false, fmt.Errorf("consume TOTP step: %w", err)
}
return tag.RowsAffected() == 1, nil
} }
// DisableTOTP clears both the active and pending TOTP secret. // DisableTOTP clears both the active and pending TOTP secret.
@@ -279,7 +296,7 @@ func (s *Store) DisableTOTP(ctx context.Context, userID int64) error {
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return err return err
} }
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID) _, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1`, userID)
if err != nil { if err != nil {
return fmt.Errorf("disable TOTP: %w", err) return fmt.Errorf("disable TOTP: %w", err)
} }
@@ -382,6 +399,22 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
return nil return nil
} }
// UpgradePasswordHash replaces an old verifier only if it is still current,
// so a concurrent password change cannot be overwritten by a login rehash.
func (s *Store) UpgradePasswordHash(ctx context.Context, id int64, oldHash, newHash string) (bool, error) {
if err := s.validate(); err != nil {
return false, err
}
tag, err := s.pool.Exec(ctx, `
UPDATE auth_users SET password_hash = $1, updated_at = now()
WHERE id = $2 AND password_hash = $3
`, newHash, id, oldHash)
if err != nil {
return false, fmt.Errorf("upgrade password hash: %w", err)
}
return tag.RowsAffected() == 1, nil
}
// ListUsers returns the non-secret account fields used by the shared user // ListUsers returns the non-secret account fields used by the shared user
// management screen. // management screen.
func (s *Store) ListUsers(ctx context.Context) ([]User, error) { func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
@@ -548,18 +581,6 @@ func (s *Store) DeleteAllUsers(ctx context.Context) error {
return nil return nil
} }
// DeleteExpiredSessions performs the periodic session cleanup shared by the
// services. A caller can run it from its own scheduler.
func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
return fmt.Errorf("delete expired auth sessions: %w", err)
}
return nil
}
// KnownProject is one project ProjectConfigurator has registered, pushed to AuthGuard so its // KnownProject is one project ProjectConfigurator has registered, pushed to AuthGuard so its
// admin UI can offer real, live project keys instead of free-form text - see SetKnownProjects. // admin UI can offer real, live project keys instead of free-form text - see SetKnownProjects.
type KnownProject struct { type KnownProject struct {
@@ -569,9 +590,7 @@ type KnownProject struct {
// SetKnownProjects replaces the full set of known projects (pushed by ProjectConfigurator's // SetKnownProjects replaces the full set of known projects (pushed by ProjectConfigurator's
// PUT /api/projects/internal whenever its registered-project list changes). A project no longer // PUT /api/projects/internal whenever its registered-project list changes). A project no longer
// registered is dropped, so the admin UI never offers a stale key; existing auth_user_projects // registered is dropped, so the admin UI never offers a stale key.
// rows for a removed project are left alone (harmless - IsProjectAllowed only ever compares
// against a user's own rows, never against auth_known_projects).
func (s *Store) SetKnownProjects(ctx context.Context, projects []KnownProject) error { func (s *Store) SetKnownProjects(ctx context.Context, projects []KnownProject) error {
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return err return err
@@ -623,111 +642,6 @@ func (s *Store) KnownProjects(ctx context.Context) ([]KnownProject, error) {
return projects, rows.Err() return projects, rows.Err()
} }
// SetUserProjects replaces the full set of projects userID is restricted to. An empty projects
// list means unrestricted (see IsProjectAllowed) - the default for every account until an
// administrator explicitly scopes it, so this feature is opt-in and never breaks an existing
// deployment's accounts on upgrade.
func (s *Store) SetUserProjects(ctx context.Context, userID int64, projects []string) error {
if err := s.validate(); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("set user projects: %w", err)
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `DELETE FROM auth_user_projects WHERE user_id = $1`, userID); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
seen := map[string]bool{}
for _, project := range projects {
key := strings.ToLower(strings.TrimSpace(project))
if key == "" || seen[key] {
continue
}
seen[key] = true
if _, err := tx.Exec(ctx, `INSERT INTO auth_user_projects (user_id, project) VALUES ($1, $2)`, userID, key); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
return nil
}
// UserProjects returns the projects userID is restricted to, or an empty slice when unrestricted.
func (s *Store) UserProjects(ctx context.Context, userID int64) ([]string, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `SELECT project FROM auth_user_projects WHERE user_id = $1 ORDER BY project`, userID)
if err != nil {
return nil, fmt.Errorf("list user projects: %w", err)
}
defer rows.Close()
projects := make([]string, 0)
for rows.Next() {
var project string
if err := rows.Scan(&project); err != nil {
return nil, fmt.Errorf("scan user project: %w", err)
}
projects = append(projects, project)
}
return projects, rows.Err()
}
// UserProjectsByUser bulk-loads every user's project restrictions in one query, for the admin
// user list screen (avoids one query per row).
func (s *Store) UserProjectsByUser(ctx context.Context) (map[int64][]string, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `SELECT user_id, project FROM auth_user_projects ORDER BY user_id, project`)
if err != nil {
return nil, fmt.Errorf("list user projects: %w", err)
}
defer rows.Close()
result := map[int64][]string{}
for rows.Next() {
var userID int64
var project string
if err := rows.Scan(&userID, &project); err != nil {
return nil, fmt.Errorf("scan user project: %w", err)
}
result[userID] = append(result[userID], project)
}
return result, rows.Err()
}
// IsProjectAllowed reports whether userID may authenticate against project: true when the
// account has no project restrictions at all (the default for every account), or when project is
// one of its assigned projects. An empty project (a caller that sent no project-key header - a
// service not yet migrated to identify itself, or a browser request straight to AuthGuard's own
// web UI, which is not itself a "project" another service authenticates against) is always
// allowed; restriction only ever applies once a caller actually identifies itself.
func (s *Store) IsProjectAllowed(ctx context.Context, userID int64, project string) (bool, error) {
project = strings.ToLower(strings.TrimSpace(project))
if project == "" {
return true, nil
}
if err := s.validate(); err != nil {
return false, err
}
var total int
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_user_projects WHERE user_id = $1`, userID).Scan(&total); err != nil {
return false, fmt.Errorf("count user projects: %w", err)
}
if total == 0 {
return true, nil
}
var allowed bool
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM auth_user_projects WHERE user_id = $1 AND project = $2)`, userID, project).Scan(&allowed); err != nil {
return false, fmt.Errorf("check user project: %w", err)
}
return allowed, nil
}
var ErrUserExists = errors.New("auth user already exists") var ErrUserExists = errors.New("auth user already exists")
// ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on. // ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on.
+2 -2
View File
@@ -230,8 +230,8 @@ func TestStoreTOTPAndIdentifierPrimitives(t *testing.T) {
if err := store.SetTOTPSecret(ctx, owner.ID, "JBSWY3DPEHPK3PXP"); err != nil { if err := store.SetTOTPSecret(ctx, owner.ID, "JBSWY3DPEHPK3PXP"); err != nil {
t.Fatalf("SetTOTPSecret() while disabled error = %v", err) t.Fatalf("SetTOTPSecret() while disabled error = %v", err)
} }
if err := store.EnableTOTP(ctx, owner.ID); err != nil { if enabled, err := store.EnableTOTP(ctx, owner.ID, "JBSWY3DPEHPK3PXP", 123); err != nil || !enabled {
t.Fatal(err) t.Fatalf("EnableTOTP() = %v, %v; want enabled", enabled, err)
} }
if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) { if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) {
t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err) t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err)
+14 -12
View File
@@ -16,11 +16,10 @@ import (
// TOTP follows RFC 6238's default interoperable profile. // TOTP follows RFC 6238's default interoperable profile.
const ( const (
TOTPPeriod = 30 * time.Second TOTPPeriod = 30 * time.Second
TOTPDigits = 6 TOTPDigits = 6
TOTPSecretBytes = 20 TOTPSecretBytes = 20
TOTPWindow = 1 TOTPWindow = 1
TOTPSecretLength = 32
) )
// GenerateTOTPSecret returns a base32 secret suitable for authenticator apps. // GenerateTOTPSecret returns a base32 secret suitable for authenticator apps.
@@ -52,19 +51,22 @@ func TOTPProvisioningURI(issuer, account, secret string) string {
return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode() return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode()
} }
// VerifyTOTP checks a six-digit token with a one-period clock-skew window. // VerifyTOTP checks a six-digit token with a one-period clock-skew window and
func VerifyTOTP(secret, token string, now time.Time) bool { // returns the matching time step. A caller must atomically record that step
// before accepting the code so it cannot be used twice.
func VerifyTOTP(secret, token string, now time.Time) (int64, bool) {
secret = normalizeTOTPSecret(secret) secret = normalizeTOTPSecret(secret)
token = normalizeTOTPToken(token) token = normalizeTOTPToken(token)
if secret == "" || len(token) != TOTPDigits { if secret == "" || len(token) != TOTPDigits {
return false return -1, false
} }
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret) key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
if err != nil || len(key) == 0 { if err != nil || len(key) == 0 {
return false return -1, false
} }
period := now.Unix() / int64(TOTPPeriod/time.Second) period := now.Unix() / int64(TOTPPeriod/time.Second)
for offset := int64(-TOTPWindow); offset <= TOTPWindow; offset++ { // Prefer the current step if a six-digit collision occurs in the window.
for _, offset := range [...]int64{0, -1, 1} {
if period+offset < 0 { if period+offset < 0 {
continue continue
} }
@@ -80,10 +82,10 @@ func VerifyTOTP(secret, token string, now time.Time) bool {
uint32(digest[index+3]) uint32(digest[index+3])
candidate := fmt.Sprintf("%06d", value%1000000) candidate := fmt.Sprintf("%06d", value%1000000)
if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 { if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 {
return true return period + offset, true
} }
} }
return false return -1, false
} }
func normalizeTOTPSecret(value string) string { func normalizeTOTPSecret(value string) string {
+4 -1
View File
@@ -18,8 +18,11 @@ func TestVerifyTOTPRFC6238SHA1Vectors(t *testing.T) {
{unix: 2000000000, code: "279037"}, {unix: 2000000000, code: "279037"},
} }
for _, testCase := range cases { for _, testCase := range cases {
if !VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0)) { step, valid := VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0))
if !valid {
t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code) t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code)
} else if want := testCase.unix / int64(TOTPPeriod/time.Second); step != want {
t.Errorf("VerifyTOTP(%d, %q) matched step %d, want %d", testCase.unix, testCase.code, step, want)
} }
} }
} }
+20
View File
@@ -71,6 +71,7 @@ type Client struct {
projectKey string projectKey string
validationMu sync.Mutex validationMu sync.Mutex
validationCache map[[32]byte]validationCacheEntry validationCache map[[32]byte]validationCacheEntry
profileCache map[[32]byte]profileCacheEntry
} }
// ProjectKeyHeader is the header Client attaches to every request identifying // ProjectKeyHeader is the header Client attaches to every request identifying
@@ -118,6 +119,7 @@ func New(baseURL string, opts ...Option) *Client {
httpClient: &http.Client{Timeout: 5 * time.Second}, httpClient: &http.Client{Timeout: 5 * time.Second},
cookieName: DefaultCookieName, cookieName: DefaultCookieName,
validationCache: make(map[[32]byte]validationCacheEntry), validationCache: make(map[[32]byte]validationCacheEntry),
profileCache: make(map[[32]byte]profileCacheEntry),
} }
for _, opt := range opts { for _, opt := range opts {
opt(c) opt(c)
@@ -583,12 +585,24 @@ func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, erro
// Me calls GET /api/me, resolving token to its account. // Me calls GET /api/me, resolving token to its account.
func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) { func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) {
token = strings.TrimSpace(token)
if token == "" {
return nil, ErrInvalidSession
}
if profile, ok := c.cachedProfile(token); ok {
return profile, nil
}
var out struct { var out struct {
User PublicUser `json:"user"` User PublicUser `json:"user"`
} }
if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil { if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil {
var apiErr *APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized {
c.invalidateValidation(token)
}
return nil, err return nil, err
} }
c.cacheProfile(token, &out.User)
return &out.User, nil return &out.User, nil
} }
@@ -607,6 +621,9 @@ func (c *Client) TOTPEnable(ctx context.Context, token string) (*TOTPEnableResul
// pending secret TOTPEnable provisioned and activating two-factor auth. // pending secret TOTPEnable provisioned and activating two-factor auth.
func (c *Client) TOTPVerify(ctx context.Context, token, code string) error { func (c *Client) TOTPVerify(ctx context.Context, token, code string) error {
_, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil) _, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil)
if err == nil {
c.invalidateValidation(token)
}
return err return err
} }
@@ -615,6 +632,9 @@ func (c *Client) TOTPVerify(ctx context.Context, token, code string) error {
// as proof of possession. // as proof of possession.
func (c *Client) TOTPDisable(ctx context.Context, token, code string) error { func (c *Client) TOTPDisable(ctx context.Context, token, code string) error {
_, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil) _, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil)
if err == nil {
c.invalidateValidation(token)
}
return err return err
} }
+54
View File
@@ -10,12 +10,20 @@ const (
maxValidationCacheSize = 10000 maxValidationCacheSize = 10000
) )
// A session revoked directly in AuthGuard may remain accepted by this client
// for up to two seconds. Logout through this Client clears the cached result.
type validationCacheEntry struct { type validationCacheEntry struct {
user User user User
valid bool valid bool
expires time.Time expires time.Time
} }
type profileCacheEntry struct {
profile PublicUser
expires time.Time
}
func (c *Client) cachedValidation(token string) (*User, error, bool) { func (c *Client) cachedValidation(token string) (*User, error, bool) {
key := sha256.Sum256([]byte(token)) key := sha256.Sum256([]byte(token))
now := time.Now() now := time.Now()
@@ -64,15 +72,61 @@ func (c *Client) cacheValidation(token string, user *User, valid bool) {
c.validationCache[key] = entry c.validationCache[key] = entry
} }
func (c *Client) cachedProfile(token string) (*PublicUser, bool) {
key := sha256.Sum256([]byte(token))
now := time.Now()
c.validationMu.Lock()
defer c.validationMu.Unlock()
entry, ok := c.profileCache[key]
if !ok {
return nil, false
}
if !now.Before(entry.expires) {
delete(c.profileCache, key)
return nil, false
}
profile := entry.profile
return &profile, true
}
func (c *Client) cacheProfile(token string, profile *PublicUser) {
if profile == nil {
return
}
key := sha256.Sum256([]byte(token))
now := time.Now()
c.validationMu.Lock()
defer c.validationMu.Unlock()
if c.profileCache == nil {
c.profileCache = make(map[[32]byte]profileCacheEntry)
}
if len(c.profileCache) >= maxValidationCacheSize {
for existing, entry := range c.profileCache {
if !now.Before(entry.expires) {
delete(c.profileCache, existing)
}
}
if len(c.profileCache) >= maxValidationCacheSize {
for existing := range c.profileCache {
delete(c.profileCache, existing)
break
}
}
}
c.profileCache[key] = profileCacheEntry{profile: *profile, expires: now.Add(validationCacheTTL)}
}
func (c *Client) invalidateValidation(token string) { func (c *Client) invalidateValidation(token string) {
key := sha256.Sum256([]byte(token)) key := sha256.Sum256([]byte(token))
c.validationMu.Lock() c.validationMu.Lock()
delete(c.validationCache, key) delete(c.validationCache, key)
delete(c.profileCache, key)
c.validationMu.Unlock() c.validationMu.Unlock()
} }
func (c *Client) clearValidationCache() { func (c *Client) clearValidationCache() {
c.validationMu.Lock() c.validationMu.Lock()
c.validationCache = make(map[[32]byte]validationCacheEntry) c.validationCache = make(map[[32]byte]validationCacheEntry)
c.profileCache = make(map[[32]byte]profileCacheEntry)
c.validationMu.Unlock() c.validationMu.Unlock()
} }
+1 -3
View File
@@ -6,9 +6,7 @@
// Three services independently reimplemented the same handful of pieces // Three services independently reimplemented the same handful of pieces
// below before this package existed (Fork/Bitmagnet/backend/internal/auth/service.go, // below before this package existed (Fork/Bitmagnet/backend/internal/auth/service.go,
// Original/GameStream/backend/cmd/gamestreamd/auth.go, // Original/GameStream/backend/cmd/gamestreamd/auth.go,
// this same module's own mediaauth/auth.go, formerly // this same module's own auth/proxy.go — read any one of their top-of-file
// Core/shared/media-backend/internal/auth/auth.go before that generic
// multi-service binary was split up — read any one of their top-of-file
// doc comments for the fuller AuthGuard-migration // doc comments for the fuller AuthGuard-migration
// rationale: session cookie forwarding, the local one-time setup-claim // rationale: session cookie forwarding, the local one-time setup-claim
// flag, "auth disabled" mode, etc.). Those pieces stay project-specific // flag, "auth disabled" mode, etc.). Those pieces stay project-specific
+158 -5
View File
@@ -22,12 +22,25 @@ import (
"os" "os"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
) )
// httpClient has no blanket timeout since it streams large media files; // httpClient has no total timeout since it streams large media files. The
// callers bound individual calls with a context deadline instead. // transport still bounds how long a request may wait for response headers;
var httpClient = &http.Client{} // callers that need a shorter bound add a context deadline as well.
var httpClient = newHTTPClient()
func newHTTPClient() *http.Client {
var transport *http.Transport
if defaultTransport, ok := http.DefaultTransport.(*http.Transport); ok {
transport = defaultTransport.Clone()
} else {
transport = &http.Transport{Proxy: http.ProxyFromEnvironment}
}
transport.ResponseHeaderTimeout = 10 * time.Second
return &http.Client{Transport: transport}
}
var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"} var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"} var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
@@ -69,6 +82,17 @@ type Client struct {
// multiple candidates are actually used (union for discovery, first-match // multiple candidates are actually used (union for discovery, first-match
// for reads, primary-only for writes). // for reads, primary-only for writes).
BaseURLs func(ctx context.Context) []string BaseURLs func(ctx context.Context) []string
thumbnailMu sync.Mutex
thumbnailPaths map[string]thumbnailPathEntry
}
const thumbnailPathCacheTTL = 5 * time.Minute
const thumbnailPathCacheLimit = 2048
type thumbnailPathEntry struct {
path string
expires time.Time
} }
// New returns a Client backed by a single CarrierNode instance. baseURL is // New returns a Client backed by a single CarrierNode instance. baseURL is
@@ -443,6 +467,47 @@ func (c *Client) DeleteMountFile(ctx context.Context, project, mountType, relati
return nil return nil
} }
// DeleteMedia removes one library file from the primary CarrierNode. carrierNodePath is the
// "/media/..." request path the caller probed, so the delete targets the same file the probe
// found. It reports whether CarrierNode removed a file: a 404 is a clean "not there" and returns
// false with a nil error, so a caller can tell a removal apart from a file that was already gone.
func (c *Client) DeleteMedia(ctx context.Context, carrierNodePath string) (bool, error) {
if !validMediaRequestPath(carrierNodePath) {
return false, fmt.Errorf("invalid media path")
}
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, carrierNodePath, nil)
if err != nil {
return false, err
}
response, err := httpClient.Do(request)
if err != nil {
return false, err
}
defer response.Body.Close()
switch {
case response.StatusCode == http.StatusNotFound:
return false, nil
case response.StatusCode >= 400:
return false, fmt.Errorf("carriernode media delete failed: %s", response.Status)
}
return true, nil
}
// validMediaRequestPath accepts only a /media/ request path with no ".." segment after
// unescaping, so a delete cannot name a path outside the media route.
func validMediaRequestPath(carrierNodePath string) bool {
if !strings.HasPrefix(carrierNodePath, "/media/") {
return false
}
for _, segment := range strings.Split(carrierNodePath, "/") {
decoded, err := url.PathUnescape(segment)
if err != nil || decoded == ".." {
return false
}
}
return true
}
// ThumbnailMountType is the mount type ProjectConfigurator configures for a project's // ThumbnailMountType is the mount type ProjectConfigurator configures for a project's
// generated thumbnails. Each thumbnail is one "<id>.jpg" file under that mount. // generated thumbnails. Each thumbnail is one "<id>.jpg" file under that mount.
const ThumbnailMountType = "thumbnails" const ThumbnailMountType = "thumbnails"
@@ -536,15 +601,103 @@ func (c *Client) ProxyThumbnail(w http.ResponseWriter, r *http.Request, project,
if err != nil { if err != nil {
return false return false
} }
cacheKey := project + "\x00" + id
cachedPath := c.cachedThumbnailPath(cacheKey)
if cachedPath != "" {
ordered := make([]string, 0, len(paths))
ordered = append(ordered, cachedPath)
for _, path := range paths {
if path != cachedPath {
ordered = append(ordered, path)
}
}
paths = ordered
}
for _, path := range paths { for _, path := range paths {
if exists, _, _, probeErr := c.Probe(r.Context(), path); probeErr == nil && exists { for _, baseURL := range c.candidateBaseURLs(r.Context()) {
c.Proxy(w, r, path) request, err := c.newRequest(r.Context(), baseURL, r.Method, path, nil)
if err != nil {
continue
}
for _, header := range forwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := httpClient.Do(request)
if err != nil {
continue
}
if response.StatusCode >= http.StatusBadRequest {
response.Body.Close()
if path == cachedPath {
c.forgetThumbnailPath(cacheKey)
}
continue
}
for _, header := range forwardResponseHeaders {
if value := response.Header.Get(header); value != "" {
w.Header().Set(header, value)
}
}
w.WriteHeader(response.StatusCode)
if r.Method != http.MethodHead {
_, _ = io.Copy(w, response.Body)
}
response.Body.Close()
c.rememberThumbnailPath(cacheKey, path)
return true return true
} }
} }
return false return false
} }
func (c *Client) cachedThumbnailPath(key string) string {
c.thumbnailMu.Lock()
defer c.thumbnailMu.Unlock()
entry, ok := c.thumbnailPaths[key]
if !ok {
return ""
}
if !time.Now().Before(entry.expires) {
delete(c.thumbnailPaths, key)
return ""
}
return entry.path
}
func (c *Client) rememberThumbnailPath(key, path string) {
c.thumbnailMu.Lock()
defer c.thumbnailMu.Unlock()
if c.thumbnailPaths == nil {
c.thumbnailPaths = make(map[string]thumbnailPathEntry)
}
now := time.Now()
for cacheKey, entry := range c.thumbnailPaths {
if !now.Before(entry.expires) {
delete(c.thumbnailPaths, cacheKey)
}
}
if len(c.thumbnailPaths) >= thumbnailPathCacheLimit {
var oldestKey string
var oldest time.Time
first := true
for cacheKey, entry := range c.thumbnailPaths {
if first || entry.expires.Before(oldest) {
oldestKey, oldest, first = cacheKey, entry.expires, false
}
}
delete(c.thumbnailPaths, oldestKey)
}
c.thumbnailPaths[key] = thumbnailPathEntry{path: path, expires: now.Add(thumbnailPathCacheTTL)}
}
func (c *Client) forgetThumbnailPath(key string) {
c.thumbnailMu.Lock()
delete(c.thumbnailPaths, key)
c.thumbnailMu.Unlock()
}
// FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking // FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking
// in the project's thumbnails mount and then the legacy root. Callers must invoke the returned // in the project's thumbnails mount and then the legacy root. Callers must invoke the returned
// cleanup once done. // cleanup once done.
@@ -1,265 +1,21 @@
package carriernodeclient package carriernodeclient
import ( import (
"context"
"errors"
"net/http" "net/http"
"net/http/httptest"
"testing" "testing"
"time"
) )
func TestListFilesMergesAcrossInstances(t *testing.T) { func TestHTTPClientBoundsResponseHeaderWaitWithoutLimitingStreams(t *testing.T) {
first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { client := newHTTPClient()
w.Header().Set("Content-Type", "application/json") if client.Timeout != 0 {
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`)) t.Fatalf("client total timeout = %s, want no total timeout for media streams", client.Timeout)
}))
defer first.Close()
second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"b.mp4"}]}`))
}))
defer second.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
files, err := client.ListFiles(context.Background(), "", false, 0)
if err != nil {
t.Fatalf("ListFiles error: %v", err)
} }
if len(files) != 2 { transport, ok := client.Transport.(*http.Transport)
t.Fatalf("ListFiles returned %d files, want 2: %+v", len(files), files) if !ok {
t.Fatalf("transport type = %T, want *http.Transport", client.Transport)
} }
} if transport.ResponseHeaderTimeout != 10*time.Second {
t.Fatalf("response header timeout = %s, want 10s", transport.ResponseHeaderTimeout)
func TestRequestsCarryProjectAttribution(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-Internal-Auth"); got != "secret" {
t.Fatalf("X-Internal-Auth = %q, want secret", got)
}
if got := r.Header.Get("X-Project-Key"); got != "ContentScanner" {
t.Fatalf("X-Project-Key = %q, want ContentScanner", got)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[]}`))
}))
defer server.Close()
client := New("secret", func(ctx context.Context) string { return server.URL })
client.ProjectKey = "ContentScanner"
if _, err := client.ListFiles(context.Background(), "", false, 0); err != nil {
t.Fatalf("ListFiles error: %v", err)
}
}
func TestListFilesSkipsUnreachableInstance(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"files":[{"rel":"a.mp4"}]}`))
}))
defer up.Close()
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
down.Close() // closed immediately so requests to it fail outright
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL, up.URL} })
files, err := client.ListFiles(context.Background(), "", false, 0)
if err != nil {
t.Fatalf("ListFiles error: %v", err)
}
if len(files) != 1 || files[0].Rel != "a.mp4" {
t.Fatalf("ListFiles = %+v, want just the reachable instance's file", files)
}
}
func TestListFilesErrorsWhenNoInstanceReachable(t *testing.T) {
down := httptest.NewServer(nil)
down.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{down.URL} })
if _, err := client.ListFiles(context.Background(), "", false, 0); err == nil {
t.Fatal("ListFiles error = nil, want an error when every instance is unreachable")
}
}
func TestProbeFallsBackToNextInstance(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
found := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "42")
w.WriteHeader(http.StatusOK)
}))
defer found.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, found.URL} })
exists, size, _, err := client.Probe(context.Background(), "/media/a.mp4")
if err != nil {
t.Fatalf("Probe error: %v", err)
}
if !exists {
t.Fatal("Probe exists = false, want true (second instance has it)")
}
if size != 42 {
t.Fatalf("Probe size = %d, want 42", size)
}
}
func TestProbeExistsFalseWhenNoInstanceHasFile(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
exists, _, _, err := client.Probe(context.Background(), "/media/missing.mp4")
if err != nil {
t.Fatalf("Probe error: %v", err)
}
if exists {
t.Fatal("Probe exists = true, want false")
}
}
func TestProxyPrefersPrimaryInstanceWhenItHasTheFile(t *testing.T) {
var primaryHit, secondaryHit bool
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
primaryHit = true
w.WriteHeader(http.StatusOK)
}))
defer primary.Close()
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
secondaryHit = true
w.WriteHeader(http.StatusOK)
}))
defer secondary.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
req := httptest.NewRequest(http.MethodGet, "/thumbnails/x.jpg", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/thumbnails/x.jpg")
if !primaryHit {
t.Fatal("Proxy did not hit the primary instance")
}
if secondaryHit {
t.Fatal("Proxy hit the secondary instance even though the primary had the file")
}
}
func TestProxyFallsBackToSecondaryInstanceWhenPrimaryMisses(t *testing.T) {
primary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer primary.Close()
secondary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "video/mp4")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("video bytes"))
}))
defer secondary.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{primary.URL, secondary.URL} })
req := httptest.NewRequest(http.MethodGet, "/media/a.mp4", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/media/a.mp4")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 from the secondary instance", rec.Code)
}
if rec.Body.String() != "video bytes" {
t.Fatalf("body = %q, want secondary instance's bytes", rec.Body.String())
}
}
func TestProxyForwardsLastInstanceErrorWhenNoneHaveTheFile(t *testing.T) {
notFound := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer notFound.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{notFound.URL, notFound.URL} })
req := httptest.NewRequest(http.MethodGet, "/media/missing.mp4", nil)
rec := httptest.NewRecorder()
client.Proxy(rec, req, "/media/missing.mp4")
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 forwarded from the last instance", rec.Code)
}
}
func mountListingServer(status int, body string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write([]byte(body))
}))
}
func TestListMountFilesReportsNotFoundWhenEveryInstanceMisses(t *testing.T) {
first := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer first.Close()
second := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer second.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{first.URL, second.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "gone")
if !errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, want ErrMountNotFound", err)
}
}
func TestListMountFilesDoesNotReportNotFoundWhenAnInstanceIsUnreachable(t *testing.T) {
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer missing.Close()
down := httptest.NewServer(nil)
down.Close() // closed immediately so requests to it fail outright
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, down.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "maybe-on-the-down-instance")
if err == nil {
t.Fatal("ListMountFiles succeeded, want an error")
}
if errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, must not claim the directory is missing when an instance could not be checked", err)
}
}
func TestListMountFilesDoesNotReportNotFoundOnServerError(t *testing.T) {
broken := mountListingServer(http.StatusInternalServerError, `{"error":"boom"}`)
defer broken.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{broken.URL} })
_, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
if err == nil || errors.Is(err, ErrMountNotFound) {
t.Fatalf("ListMountFiles error = %v, want a non-ErrMountNotFound failure", err)
}
}
func TestListMountFilesUsesTheInstanceThatHasTheDirectory(t *testing.T) {
missing := mountListingServer(http.StatusNotFound, `{"error":"mount directory not found"}`)
defer missing.Close()
present := mountListingServer(http.StatusOK, `{"files":[{"name":"repo","path":"repo","directory":true}]}`)
defer present.Close()
client := NewMulti("", func(ctx context.Context) []string { return []string{missing.URL, present.URL} })
files, err := client.ListMountFiles(context.Background(), "autocode", "repos", "")
if err != nil {
t.Fatalf("ListMountFiles error: %v", err)
}
if len(files) != 1 || files[0].Name != "repo" || !files[0].Directory {
t.Fatalf("ListMountFiles = %+v, want the one directory from the instance that has it", files)
} }
} }
@@ -0,0 +1,94 @@
package carriernodeclient
import (
"context"
"net/http"
"net/http/httptest"
"slices"
"sync"
"testing"
)
// mediaDeleteServer answers DELETE /media/... with the status for each path (default 404) and records
// every request so a test can see what reached CarrierNode. A path answered with 200 is removed by that
// delete, so a later request for it gets 404, as it would from a real CarrierNode.
type mediaDeleteServer struct {
mu sync.Mutex
statuses map[string]int
requests []string
}
func (n *mediaDeleteServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.EscapedPath()
n.mu.Lock()
n.requests = append(n.requests, r.Method+" "+path)
status, ok := n.statuses[path]
if !ok {
status = http.StatusNotFound
}
if r.Method == http.MethodDelete && status == http.StatusOK {
n.statuses[path] = http.StatusNotFound
}
n.mu.Unlock()
w.WriteHeader(status)
}
func (n *mediaDeleteServer) seen() []string {
n.mu.Lock()
defer n.mu.Unlock()
return append([]string(nil), n.requests...)
}
func newMediaDeleteClient(t *testing.T, statuses map[string]int) (*Client, *mediaDeleteServer) {
t.Helper()
node := &mediaDeleteServer{statuses: statuses}
server := httptest.NewServer(node)
t.Cleanup(server.Close)
return New("cn-secret", func(context.Context) string { return server.URL }), node
}
func TestDeleteMediaReportsRemovalAndAlreadyMissing(t *testing.T) {
client, node := newMediaDeleteClient(t, map[string]int{"/media/Videos/clip.mp4": http.StatusOK})
removed, err := client.DeleteMedia(context.Background(), "/media/Videos/clip.mp4")
if err != nil || !removed {
t.Fatalf("first delete = (%v, %v), want (true, nil)", removed, err)
}
removed, err = client.DeleteMedia(context.Background(), "/media/Videos/clip.mp4")
if err != nil || removed {
t.Fatalf("second delete = (%v, %v), want (false, nil) for a file already gone", removed, err)
}
want := []string{"DELETE /media/Videos/clip.mp4", "DELETE /media/Videos/clip.mp4"}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want %v", got, want)
}
}
func TestDeleteMediaReportsServerErrors(t *testing.T) {
client, _ := newMediaDeleteClient(t, map[string]int{"/media/Videos/clip.mp4": http.StatusInternalServerError})
removed, err := client.DeleteMedia(context.Background(), "/media/Videos/clip.mp4")
if err == nil || removed {
t.Fatalf("delete = (%v, %v), want (false, error) for a 500", removed, err)
}
}
func TestDeleteMediaRefusesPathsOutsideTheMediaRoute(t *testing.T) {
client, node := newMediaDeleteClient(t, nil)
for _, path := range []string{
"/api/media/Videos/clip.mp4",
"/mount/media/Videos/clip.mp4",
"media/Videos/clip.mp4",
"/media/../secret.mp4",
"/media/Videos/%2e%2e/%2e%2e/secret.mp4",
"",
} {
if removed, err := client.DeleteMedia(context.Background(), path); err == nil || removed {
t.Fatalf("DeleteMedia(%q) = (%v, %v), want (false, error)", path, removed, err)
}
}
if got := node.seen(); len(got) != 0 {
t.Fatalf("refused paths still reached CarrierNode: %v", got)
}
}
@@ -0,0 +1,55 @@
package carriernodeclient
import (
"context"
"encoding/json"
"regexp"
"strings"
"github.com/jackc/pgx/v5/pgxpool"
"repos.gfranz.ch/Gabriel20xx/shared/backend/settings"
)
// carrierNodeInstancePattern matches a registered project key naming a CarrierNode instance: the
// base "carriernode" itself, or a numbered peer like "carriernode_2" - see
// ProjectConfigurator/backend/cmd/projectconfigurator/settings.go's identical pattern (kept in
// sync manually since one is the sender's copy and this is the direct-DB-read receiver's copy of
// the same convention, not literally shared code).
var carrierNodeInstancePattern = regexp.MustCompile(`^carriernode(_\d+)?$`)
// URLsFromSettings returns every CarrierNode instance registered in ProjectConfigurator's Projects
// workspace ("carriernode_url", "carriernode_2_url", ...), read directly from the shared
// `settings` table in registration order, dropping any instance with no URL set. This is for
// CarrierNode instances that share this database directly instead of going through
// ProjectConfigurator's coreconfig push (see ProjectConfigurator/README.md's "Pushing core service
// info to other projects" section) - wire it as a carriernodeclient.Client's BaseURLs:
//
// carriernodeclient.NewMulti(secret, func(ctx context.Context) []string {
// return carriernodeclient.URLsFromSettings(ctx, db, fallback)
// })
//
// Returns fallback if no carriernode* instance is registered (or none has a URL) yet.
func URLsFromSettings(ctx context.Context, db *pgxpool.Pool, fallback []string) []string {
var registered []string
_ = json.Unmarshal([]byte(settings.ValueOrFallback(ctx, db, "configured_central", "")), &registered)
var urls []string
for _, project := range registered {
key := strings.ToLower(strings.TrimSpace(project))
if !carrierNodeInstancePattern.MatchString(key) {
continue
}
if url := strings.TrimSpace(settings.ValueOrFallback(ctx, db, key+"_url", "")); url != "" {
urls = append(urls, url)
}
}
if len(urls) == 0 {
if url := strings.TrimSpace(settings.ValueOrFallback(ctx, db, "carriernode_url", "")); url != "" {
urls = []string{url}
}
}
if len(urls) == 0 {
return fallback
}
return urls
}
+30 -7
View File
@@ -8,7 +8,6 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"slices" "slices"
"strings"
"sync" "sync"
"testing" "testing"
) )
@@ -94,16 +93,15 @@ func TestProxyThumbnailPrefersProjectMount(t *testing.T) {
if rec.Body.String() != "from mount" { if rec.Body.String() != "from mount" {
t.Fatalf("body = %q, want the mount copy", rec.Body.String()) t.Fatalf("body = %q, want the mount copy", rec.Body.String())
} }
for _, request := range node.seen() { want := []string{"GET " + mount}
if !strings.Contains(request, "/api/mount/") { if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("legacy root was consulted although the mount had the thumbnail: %v", node.seen()) t.Fatalf("requests = %v, want one direct GET to the mount", got)
}
} }
} }
func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) { func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
legacy := "/thumbnails/" + testThumbnailID + ".jpg" legacy := "/thumbnails/" + testThumbnailID + ".jpg"
client, _ := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"}) client, node := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
if !client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) { if !client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
@@ -112,10 +110,28 @@ func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
if rec.Body.String() != "from legacy" { if rec.Body.String() != "from legacy" {
t.Fatalf("body = %q, want the legacy copy", rec.Body.String()) t.Fatalf("body = %q, want the legacy copy", rec.Body.String())
} }
want := []string{"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg", "GET " + legacy}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want mount miss followed by legacy GET", got)
}
}
func TestProxyThumbnailCachesResolvedPath(t *testing.T) {
mount := "/api/mount/MediaViewer/thumbnails/" + testThumbnailID + ".jpg"
client, node := newThumbnailTestClient(t, map[string]string{mount: "from mount"})
for range 2 {
if !client.ProxyThumbnail(httptest.NewRecorder(), thumbnailRequest(), "MediaViewer", testThumbnailID) {
t.Fatal("ProxyThumbnail missed although the mount holds the thumbnail")
}
}
want := []string{"GET " + mount, "GET " + mount}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one direct GET per request to the cached path", got)
}
} }
func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) { func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
client, _ := newThumbnailTestClient(t, nil) client, node := newThumbnailTestClient(t, nil)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
if client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) { if client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
@@ -124,6 +140,13 @@ func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
if rec.Body.Len() != 0 { if rec.Body.Len() != 0 {
t.Fatalf("ProxyThumbnail wrote %q on a miss; the caller needs a clean fallback", rec.Body.String()) t.Fatalf("ProxyThumbnail wrote %q on a miss; the caller needs a clean fallback", rec.Body.String())
} }
want := []string{
"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg",
"GET /thumbnails/" + testThumbnailID + ".jpg",
}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one GET for each candidate path", got)
}
} }
func TestFetchThumbnailToScratchFallsBackToLegacyRoot(t *testing.T) { func TestFetchThumbnailToScratchFallsBackToLegacyRoot(t *testing.T) {
+52
View File
@@ -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)
}
}
}
+72 -7
View File
@@ -18,8 +18,35 @@ import (
"net/url" "net/url"
"strings" "strings"
"sync" "sync"
"unicode/utf8"
) )
// MinInternalSecretLength is the shortest SECRET a service accepts for its internal routes.
const MinInternalSecretLength = 16
// exampleInternalSecrets are the placeholders shipped in .env.example files, plus the bare variable
// name. They are public, so they never gate a route.
var exampleInternalSecrets = map[string]bool{
"SECRET": true,
"change-me-to-a-long-random-value": true,
}
// InternalSecretUsable reports whether secret is strong enough to gate an internal route: at least
// MinInternalSecretLength characters and not an example placeholder. Length counts characters, as
// the Python and Node helpers do, not bytes.
func InternalSecretUsable(secret string) bool {
return utf8.RuneCountInString(secret) >= MinInternalSecretLength && !exampleInternalSecrets[secret]
}
// InternalSecretMatches reports whether presented is the configured secret. A secret that is not
// usable (see InternalSecretUsable) never matches, and the comparison is constant-time.
func InternalSecretMatches(presented, secret string) bool {
if !InternalSecretUsable(secret) {
return false
}
return subtle.ConstantTimeCompare([]byte(presented), []byte(secret)) == 1
}
// Info is AuthGuard's, CarrierNode's, and ProjectConfigurator's current base URL(s), as pushed by // Info is AuthGuard's, CarrierNode's, and ProjectConfigurator's current base URL(s), as pushed by
// ProjectConfigurator. // ProjectConfigurator.
type Info struct { type Info struct {
@@ -51,6 +78,16 @@ type Info struct {
// ProjectConfigurator includes it so consumers with independent databases can // ProjectConfigurator includes it so consumers with independent databases can
// authenticate storage requests without falling back to their own SECRET. // authenticate storage requests without falling back to their own SECRET.
CarrierNodeSecret string `json:"carrierNodeSecret,omitempty"` CarrierNodeSecret string `json:"carrierNodeSecret,omitempty"`
// OmniLoggerURL is the OmniLogger instance that receives this service's log entries. Services
// that ship logs use it with OmniLoggerIngestToken; both are optional, so a service that does not
// ship logs ignores them.
OmniLoggerURL string `json:"omniLoggerUrl,omitempty"`
// OmniLoggerIngestToken is the ingest token ProjectConfigurator minted for this receiving service.
// OmniLogger binds it to the service's name, so it can only write this service's own entries.
// It is a per-service credential, not a SECRET, and is never echoed back in the response.
OmniLoggerIngestToken string `json:"omniLoggerIngestToken,omitempty"`
} }
// Store holds the most recently pushed Info, defaulting to whatever fallback NewStore was given // Store holds the most recently pushed Info, defaulting to whatever fallback NewStore was given
@@ -58,9 +95,10 @@ type Info struct {
// first push arrives - or forever, if this deployment isn't registered with a ProjectConfigurator // first push arrives - or forever, if this deployment isn't registered with a ProjectConfigurator
// instance at all, in which case those env vars keep working exactly as before. // instance at all, in which case those env vars keep working exactly as before.
type Store struct { type Store struct {
mu sync.RWMutex mu sync.RWMutex
info Info info Info
onUpdate func(Info) onUpdate func(Info)
listeners []func(Info)
} }
// NewStore returns a Store seeded with fallback. // NewStore returns a Store seeded with fallback.
@@ -105,6 +143,12 @@ func (s *Store) CarrierNodeURLs() []string { return s.Get().CarrierNodeURLs }
// CarrierNodeSecret is a convenience accessor for Get().CarrierNodeSecret. // CarrierNodeSecret is a convenience accessor for Get().CarrierNodeSecret.
func (s *Store) CarrierNodeSecret() string { return s.Get().CarrierNodeSecret } func (s *Store) CarrierNodeSecret() string { return s.Get().CarrierNodeSecret }
// OmniLoggerURL is a convenience accessor for Get().OmniLoggerURL.
func (s *Store) OmniLoggerURL() string { return s.Get().OmniLoggerURL }
// OmniLoggerIngestToken is a convenience accessor for Get().OmniLoggerIngestToken.
func (s *Store) OmniLoggerIngestToken() string { return s.Get().OmniLoggerIngestToken }
// OnUpdate registers fn to be called (synchronously, so keep it fast) with the new Info after // OnUpdate registers fn to be called (synchronously, so keep it fast) with the new Info after
// every Set - e.g. client.SetBaseURL for an authclient.Client that isn't already reading through // every Set - e.g. client.SetBaseURL for an authclient.Client that isn't already reading through
// Store on every call. Only one callback is kept; a second registration replaces the first, which // Store on every call. Only one callback is kept; a second registration replaces the first, which
@@ -115,6 +159,16 @@ func (s *Store) OnUpdate(fn func(Info)) {
s.mu.Unlock() s.mu.Unlock()
} }
// Subscribe registers fn to be called (synchronously, so keep it fast) with the new Info after every
// Set, in addition to OnUpdate's single callback, which it does not replace. Use it when a service
// has more than one component that follows the pushed values, such as an authclient.Client and a
// log shipper. Subscribers cannot be removed; they live as long as the Store.
func (s *Store) Subscribe(fn func(Info)) {
s.mu.Lock()
s.listeners = append(s.listeners, fn)
s.mu.Unlock()
}
// Set replaces the current Info, field by field, ignoring a blank/empty field so a partial push // Set replaces the current Info, field by field, ignoring a blank/empty field so a partial push
// (e.g. only carrierNodeUrl(s) changed) never clobbers the other value. // (e.g. only carrierNodeUrl(s) changed) never clobbers the other value.
func (s *Store) Set(next Info) { func (s *Store) Set(next Info) {
@@ -138,16 +192,26 @@ func (s *Store) Set(next Info) {
if secret := strings.TrimSpace(next.CarrierNodeSecret); secret != "" { if secret := strings.TrimSpace(next.CarrierNodeSecret); secret != "" {
s.info.CarrierNodeSecret = secret s.info.CarrierNodeSecret = secret
} }
if url := strings.TrimRight(strings.TrimSpace(next.OmniLoggerURL), "/"); url != "" {
s.info.OmniLoggerURL = url
}
if token := strings.TrimSpace(next.OmniLoggerIngestToken); token != "" {
s.info.OmniLoggerIngestToken = token
}
if len(next.CarrierNodeURLs) > 0 { if len(next.CarrierNodeURLs) > 0 {
s.info.CarrierNodeURLs = next.CarrierNodeURLs s.info.CarrierNodeURLs = next.CarrierNodeURLs
s.info.CarrierNodeURL = next.CarrierNodeURLs[0] s.info.CarrierNodeURL = next.CarrierNodeURLs[0]
} }
current := s.info current := s.info
callback := s.onUpdate callback := s.onUpdate
listeners := append([]func(Info){}, s.listeners...)
s.mu.Unlock() s.mu.Unlock()
if callback != nil { if callback != nil {
callback(current) callback(current)
} }
for _, fn := range listeners {
fn(current)
}
} }
// normalizeInfo trims/drops blank CarrierNodeURLs entries and fills in CarrierNodeURLs from a // normalizeInfo trims/drops blank CarrierNodeURLs entries and fills in CarrierNodeURLs from a
@@ -178,11 +242,11 @@ func normalizeInfo(info Info) Info {
// ProjectConfigurator calls to push a fresh Info: mount it at that path (see // ProjectConfigurator calls to push a fresh Info: mount it at that path (see
// ProjectConfigurator/README.md) behind a secret check for this service's own // ProjectConfigurator/README.md) behind a secret check for this service's own
// SECRET (the same value ProjectConfigurator and CarrierNode were configured // SECRET (the same value ProjectConfigurator and CarrierNode were configured
// with - an empty secret refuses every caller, the same fail-closed default ProjectConfigurator's // with - a secret that is not usable (see InternalSecretUsable) refuses every caller, the same
// own internal-auth-gated routes use). // fail-closed default ProjectConfigurator's own internal-auth-gated routes use).
func Handler(secret string, store *Store) http.HandlerFunc { func Handler(secret string, store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
if secret == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Internal-Auth")), []byte(secret)) != 1 { if !InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) {
writeError(w, http.StatusUnauthorized, "internal service authentication required") writeError(w, http.StatusUnauthorized, "internal service authentication required")
return return
} }
@@ -201,6 +265,7 @@ func Handler(secret string, store *Store) http.HandlerFunc {
info := store.Get() info := store.Get()
info.CarrierNodeSecret = "" info.CarrierNodeSecret = ""
info.ContentScannerSecret = "" info.ContentScannerSecret = ""
info.OmniLoggerIngestToken = ""
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "info": info}) writeJSON(w, http.StatusOK, map[string]any{"ok": true, "info": info})
} }
} }
@@ -208,7 +273,7 @@ func Handler(secret string, store *Store) http.HandlerFunc {
// validateServiceURLs refuses a pushed URL that is not an http or https URL with a host, so a push // validateServiceURLs refuses a pushed URL that is not an http or https URL with a host, so a push
// cannot point this service's clients at another scheme or at an empty host. // cannot point this service's clients at another scheme or at an empty host.
func validateServiceURLs(info Info) error { func validateServiceURLs(info Info) error {
urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL}, info.CarrierNodeURLs...) urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL, info.OmniLoggerURL}, info.CarrierNodeURLs...)
for _, raw := range urls { for _, raw := range urls {
value := strings.TrimSpace(raw) value := strings.TrimSpace(raw)
if value == "" { if value == "" {
+23 -5
View File
@@ -67,7 +67,7 @@ func TestStoreOnUpdateFiresWithNewInfo(t *testing.T) {
func TestHandlerRejectsMissingOrWrongSecret(t *testing.T) { func TestHandlerRejectsMissingOrWrongSecret(t *testing.T) {
store := NewStore(Info{}) store := NewStore(Info{})
handler := Handler("s3cret", store) handler := Handler("test-internal-secret", store)
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"}) body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"})
cases := []string{"", "wrong"} cases := []string{"", "wrong"}
@@ -127,14 +127,14 @@ func equalStrings(got, want []string) bool {
func TestHandlerAppliesPushedInfo(t *testing.T) { func TestHandlerAppliesPushedInfo(t *testing.T) {
store := NewStore(Info{}) store := NewStore(Info{})
handler := Handler("s3cret", store) handler := Handler("test-internal-secret", store)
body, _ := json.Marshal(Info{ body, _ := json.Marshal(Info{
AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com", CarrierNodeSecret: "carrier-secret", AuthGuardURL: "http://auth.example.com", CarrierNodeURL: "http://carrier.example.com", CarrierNodeSecret: "carrier-secret",
ContentScannerURL: "http://scanner.example.com/", ContentScannerSecret: "scanner-secret", ContentScannerURL: "http://scanner.example.com/", ContentScannerSecret: "scanner-secret",
}) })
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body)) req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", "s3cret") req.Header.Set("X-Internal-Auth", "test-internal-secret")
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
handler(rec, req) handler(rec, req)
@@ -152,7 +152,7 @@ func TestHandlerAppliesPushedInfo(t *testing.T) {
func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) { func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
store := NewStore(Info{AuthGuardURL: "http://auth.example.com"}) store := NewStore(Info{AuthGuardURL: "http://auth.example.com"})
handler := Handler("s3cret", store) handler := Handler("test-internal-secret", store)
for _, bad := range []Info{ for _, bad := range []Info{
{AuthGuardURL: "javascript:alert(1)"}, {AuthGuardURL: "javascript:alert(1)"},
{AuthGuardURL: "auth.example.com"}, {AuthGuardURL: "auth.example.com"},
@@ -161,7 +161,7 @@ func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
} { } {
body, _ := json.Marshal(bad) body, _ := json.Marshal(bad)
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body)) req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", "s3cret") req.Header.Set("X-Internal-Auth", "test-internal-secret")
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
handler(rec, req) handler(rec, req)
if rec.Code != http.StatusBadRequest { if rec.Code != http.StatusBadRequest {
@@ -172,3 +172,21 @@ func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
t.Fatalf("store changed by a rejected push: %+v", got) t.Fatalf("store changed by a rejected push: %+v", got)
} }
} }
func TestHandlerRefusesAnUnusableSecret(t *testing.T) {
for _, secret := range []string{"short", "SECRET", "change-me-to-a-long-random-value"} {
store := NewStore(Info{})
handler := Handler(secret, store)
body, _ := json.Marshal(Info{AuthGuardURL: "http://auth.example.com"})
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
req.Header.Set("X-Internal-Auth", secret)
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("secret %q: status = %d, want %d", secret, rec.Code, http.StatusUnauthorized)
}
if store.Get().AuthGuardURL != "" {
t.Fatalf("secret %q: store changed despite a refused push", secret)
}
}
}
@@ -0,0 +1,53 @@
package coreconfig
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const omniTestSecret = "omnilogger-fields-test-secret-0123456789"
func TestOmniLoggerFieldsKeepTheirValueAcrossPartialPushes(t *testing.T) {
store := NewStore(Info{})
store.Set(Info{OmniLoggerURL: "https://logs.example.com/", OmniLoggerIngestToken: "token-one"})
if store.OmniLoggerURL() != "https://logs.example.com" || store.OmniLoggerIngestToken() != "token-one" {
t.Fatalf("got url=%q token=%q", store.OmniLoggerURL(), store.OmniLoggerIngestToken())
}
store.Set(Info{AuthGuardURL: "https://auth.example.com"})
if store.OmniLoggerIngestToken() != "token-one" {
t.Fatal("a push without a token cleared the stored token")
}
}
func TestHandlerNeverEchoesTheOmniLoggerIngestToken(t *testing.T) {
store := NewStore(Info{})
handler := Handler(omniTestSecret, store)
request := httptest.NewRequest(http.MethodPut, "/api/core-services/internal",
strings.NewReader(`{"omniLoggerUrl":"https://logs.example.com","omniLoggerIngestToken":"token-two"}`))
request.Header.Set("X-Internal-Auth", omniTestSecret)
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status = %d: %s", response.Code, response.Body.String())
}
if strings.Contains(response.Body.String(), "token-two") {
t.Fatalf("response echoed the ingest token: %s", response.Body.String())
}
if store.OmniLoggerIngestToken() != "token-two" {
t.Fatal("the pushed token was not stored")
}
}
func TestOmniLoggerURLMustBeHTTPWithAHost(t *testing.T) {
if err := validateServiceURLs(Info{OmniLoggerURL: "ftp://logs.example.com"}); err == nil {
t.Fatal("accepted a non-http OmniLogger URL")
}
if err := validateServiceURLs(Info{OmniLoggerURL: "https://"}); err == nil {
t.Fatal("accepted an OmniLogger URL without a host")
}
if err := validateServiceURLs(Info{OmniLoggerURL: "http://omnilogger:8080"}); err != nil {
t.Fatalf("rejected a valid OmniLogger URL: %v", err)
}
}
+109
View File
@@ -0,0 +1,109 @@
// Package files holds the path-safety helpers for serving files from configured media roots:
// relative-path checks, root containment (including symlink escapes), and range-aware file serving.
package files
import (
"encoding/json"
"errors"
"mime"
"net/http"
"os"
"path/filepath"
"strings"
)
// SafeRelative reports whether value is a relative path with no `..`
// traversal or absolute-path escape (Windows drive letters included).
func SafeRelative(value string) bool {
value = strings.TrimSpace(value)
windowsAbsolute := len(value) >= 2 && value[1] == ':'
return value != "" && !strings.ContainsRune(value, 0) && !filepath.IsAbs(value) && !strings.HasPrefix(value, "/") && !strings.HasPrefix(value, `\`) && !windowsAbsolute && filepath.Clean(value) != "." && filepath.Clean(value) != ".." && !strings.HasPrefix(filepath.Clean(value), ".."+string(filepath.Separator)) && !strings.Contains(value, "../") && !strings.Contains(value, `..\`)
}
// WithinRoot reports whether candidate is (non-strictly) inside root.
func WithinRoot(root, candidate string) bool {
rel, err := filepath.Rel(root, candidate)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel)
}
// SameRealRoot reports whether candidate's symlink-resolved real path is
// still inside root's symlink-resolved real path (guards against a symlink
// planted inside root pointing outside it).
func SameRealRoot(root, candidate string) bool {
realRoot, err := filepath.EvalSymlinks(root)
if err != nil {
return false
}
realCandidate, err := filepath.EvalSymlinks(candidate)
if err != nil {
return false
}
realRoot, err = filepath.Abs(realRoot)
if err != nil {
return false
}
realCandidate, err = filepath.Abs(realCandidate)
return err == nil && WithinRoot(realRoot, realCandidate)
}
// ResolveUnderRoots resolves value (a "/media/"-prefixed or bare relative
// path) against each of roots in order, returning the first root it
// actually exists under as a real file (not a directory, and not merely a
// symlink escape - see SameRealRoot). Returns os.ErrNotExist if no root
// matches.
func ResolveUnderRoots(value string, roots []string) (string, error) {
value = strings.TrimSpace(strings.TrimPrefix(value, "/media/"))
value = strings.TrimPrefix(value, "/")
if value == "" || strings.ContainsRune(value, 0) {
return "", errors.New("empty path")
}
for _, root := range roots {
rootAbs, err := filepath.Abs(root)
if err != nil {
continue
}
candidate := value
if !filepath.IsAbs(candidate) {
candidate = filepath.Join(rootAbs, filepath.FromSlash(candidate))
}
candidate, err = filepath.Abs(candidate)
if err != nil || !WithinRoot(rootAbs, candidate) {
continue
}
info, err := os.Stat(candidate)
if err == nil && !info.IsDir() && SameRealRoot(rootAbs, candidate) {
return candidate, nil
}
}
return "", os.ErrNotExist
}
// ServeFile serves fullPath (an already-resolved, already-safety-checked
// path) with the correct Content-Type and range-request support.
func ServeFile(w http.ResponseWriter, r *http.Request, fullPath string) {
file, err := os.Open(fullPath)
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
return
}
defer file.Close()
info, err := file.Stat()
if err != nil || info.IsDir() {
writeError(w, http.StatusNotFound, "file not found")
return
}
if contentType := mime.TypeByExtension(filepath.Ext(fullPath)); contentType != "" {
w.Header().Set("Content-Type", contentType)
}
http.ServeContent(w, r, filepath.Base(fullPath), info.ModTime(), file)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message, "message": message})
}
@@ -1,4 +1,4 @@
package mediacore package files
import ( import (
"errors" "errors"
@@ -58,44 +58,3 @@ func TestResolveUnderRootsStaysInsideTheRoots(t *testing.T) {
t.Errorf("missing file error = %v, want os.ErrNotExist", err) t.Errorf("missing file error = %v, want os.ErrNotExist", err)
} }
} }
func TestUpstreamMediaPathRefusesQueryFragmentAndTraversal(t *testing.T) {
for _, stored := range []string{"x?y.mp4", "a#b.mp4", "../x.mp4", "media/../../x.mp4", `..\x.mp4`} {
if _, ok := upstreamMediaPath(stored); ok {
t.Errorf("upstreamMediaPath(%q) accepted, want refused", stored)
}
}
}
func TestUpstreamMediaPathEscapesEachSegment(t *testing.T) {
cases := map[string]string{
"clips/clip.mp4": "clips/clip.mp4",
"my clip.mp4": "my%20clip.mp4",
"100%.mp4": "100%25.mp4",
"media/a b/c.mp4": "a%20b/c.mp4",
"/leading.mp4": "leading.mp4",
}
for stored, want := range cases {
got, ok := upstreamMediaPath(stored)
if !ok || got != want {
t.Errorf("upstreamMediaPath(%q) = %q, %v; want %q", stored, got, ok, want)
}
}
}
func TestCanonicalMediaIDAcceptsOnlyCanonicalDecimals(t *testing.T) {
for _, value := range []string{"", "007", "+1", "-1", "4a", " 4", "4 ", "99999999999999999999"} {
if id, ok := canonicalMediaID(value); ok {
t.Errorf("canonicalMediaID(%q) = %d, want refused", value, id)
}
}
if id, ok := canonicalMediaID("42"); !ok || id != 42 {
t.Errorf("canonicalMediaID(42) = %d, %v; want 42, true", id, ok)
}
if mediaIDArg("abc") != nil {
t.Error("mediaIDArg(non-numeric) is not NULL")
}
if mediaIDArg("42") != int64(42) {
t.Error("mediaIDArg(42) is not 42")
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ require (
github.com/go-chi/chi/v5 v5.3.1 github.com/go-chi/chi/v5 v5.3.1
github.com/jackc/pgx/v5 v5.10.0 github.com/jackc/pgx/v5 v5.10.0
github.com/pressly/goose/v3 v3.27.3 github.com/pressly/goose/v3 v3.27.3
golang.org/x/crypto v0.54.0 golang.org/x/crypto v0.55.0
) )
require ( require (
+2 -4
View File
@@ -38,14 +38,12 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+50
View File
@@ -0,0 +1,50 @@
package logshipper
import (
"fmt"
"io"
"log"
"strings"
)
// Logger writes each line to the console exactly as the standard log package would, and ships it to
// OmniLogger at the severity the caller names. Use it where the caller knows the severity, instead of
// Writer, which has to guess the severity from the wording of the line.
//
// The console writer must be the writer the service logs to without the shipper, such as os.Stderr, so a
// line is never shipped twice. Create the Logger after the service has set its log flags and prefix, which
// NewLogger copies. A nil shipper makes the Logger console-only.
type Logger struct {
console *log.Logger
shipper *Shipper
}
// NewLogger returns a Logger that writes to console with the standard log flags and prefix in effect now.
func NewLogger(console io.Writer, shipper *Shipper) *Logger {
return &Logger{console: log.New(console, log.Prefix(), log.Flags()), shipper: shipper}
}
// output writes one line to the console and ships it. The call depth of 3 makes the console's file and line
// flags name the caller of Debugf, Infof, and the other methods, not this file.
func (l *Logger) output(sev Level, format string, args ...any) {
msg := fmt.Sprintf(format, args...)
_ = l.console.Output(3, msg)
if l.shipper != nil {
l.shipper.Ship(sev, nil, strings.TrimRight(msg, "\n"))
}
}
// Debugf logs at debug severity.
func (l *Logger) Debugf(format string, args ...any) { l.output(LevelDebug, format, args...) }
// Infof logs at info severity.
func (l *Logger) Infof(format string, args ...any) { l.output(LevelInfo, format, args...) }
// Warnf logs at warn severity.
func (l *Logger) Warnf(format string, args ...any) { l.output(LevelWarn, format, args...) }
// Errorf logs at error severity.
func (l *Logger) Errorf(format string, args ...any) { l.output(LevelError, format, args...) }
// Criticalf logs at critical severity.
func (l *Logger) Criticalf(format string, args ...any) { l.output(LevelCritical, format, args...) }
+86
View File
@@ -0,0 +1,86 @@
package logshipper
import (
"bytes"
"log"
"net/http"
"regexp"
"strings"
"testing"
"time"
)
var timestampPattern = regexp.MustCompile(`\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} `)
// The console output must match what the standard log package writes with the same flags and prefix.
func TestLoggerConsoleOutputMatchesTheStandardLogger(t *testing.T) {
oldFlags, oldPrefix := log.Flags(), log.Prefix()
log.SetFlags(log.LstdFlags)
log.SetPrefix("svc: ")
defer log.SetFlags(oldFlags)
defer log.SetPrefix(oldPrefix)
var console, reference bytes.Buffer
logger := NewLogger(&console, nil)
logger.Infof("started on %s", ":8080")
logger.Errorf("push failed: %v", "boom")
std := log.New(&reference, log.Prefix(), log.Flags())
std.Printf("started on %s", ":8080")
std.Printf("push failed: %v", "boom")
stripTimes := func(s string) string {
return timestampPattern.ReplaceAllString(s, "")
}
if stripTimes(console.String()) != stripTimes(reference.String()) {
t.Fatalf("console = %q, want the standard logger's %q (apart from timestamps)", console.String(), reference.String())
}
}
// Each method ships at its own severity, and nothing reaches the console twice.
func TestLoggerShipsEachLineAtItsSeverityOnce(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "debug"})
defer shipper.Close()
var console bytes.Buffer
logger := NewLogger(&console, shipper)
logger.Debugf("d")
logger.Infof("i")
logger.Warnf("w")
logger.Errorf("e")
logger.Criticalf("c")
shipper.Flush()
if n := strings.Count(console.String(), "\n"); n != 5 {
t.Fatalf("console got %d lines, want 5: %q", n, console.String())
}
entries := in.entries()
want := map[string]string{"d": "debug", "i": "info", "w": "warn", "e": "error", "c": "critical"}
if len(entries) != len(want) {
t.Fatalf("shipped %d entries, want %d: %+v", len(entries), len(want), entries)
}
for _, e := range entries {
if want[e.Message] != e.Level {
t.Errorf("%q shipped at %q, want %q", e.Message, e.Level, want[e.Message])
}
}
}
// A nil shipper keeps the Logger console-only, and the threshold still applies to what is shipped.
func TestLoggerWithoutShipperIsConsoleOnlyAndThresholdApplies(t *testing.T) {
var console bytes.Buffer
NewLogger(&console, nil).Debugf("still printed")
if !strings.Contains(console.String(), "still printed") {
t.Fatalf("console-only logger dropped a line: %q", console.String())
}
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"})
defer shipper.Close()
NewLogger(&bytes.Buffer{}, shipper).Warnf("below threshold")
shipper.Flush()
time.Sleep(10 * time.Millisecond)
if n := len(in.entries()); n != 0 {
t.Fatalf("shipped %d entries below the threshold", n)
}
}
+271 -23
View File
@@ -25,11 +25,16 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"net/http" "net/http"
"os" "os"
"regexp"
"strings" "strings"
"sync" "sync"
"time" "time"
"unicode/utf8"
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
) )
// Level mirrors internal/logging's severity scale in every service's local // Level mirrors internal/logging's severity scale in every service's local
@@ -95,8 +100,10 @@ type Config struct {
// BaseURL is OmniLogger's base URL, e.g. "http://omnilogger:8090". // BaseURL is OmniLogger's base URL, e.g. "http://omnilogger:8090".
// Required. // Required.
BaseURL string BaseURL string
// IngestToken is the shared INGEST_TOKEN bearer secret OmniLogger // IngestToken is this service's OmniLogger ingest token: a per-service
// requires (see OmniLogger/README.md). Required. // bearer secret an administrator creates in OmniLogger and bound to
// Service (see OmniLogger/README.md). OmniLogger rejects entries whose
// service differs from the token's bound service. Required.
IngestToken string IngestToken string
// Service is this process's service name as reported to OmniLogger, // Service is this process's service name as reported to OmniLogger,
// e.g. "playhouse" or "outdoorgames-server-go". Required. // e.g. "playhouse" or "outdoorgames-server-go". Required.
@@ -152,10 +159,14 @@ type Shipper struct {
logAll bool logAll bool
service string service string
url string
token string
client *http.Client client *http.Client
// credMu guards url and token, which SetCredentials can replace while the Shipper runs. An empty
// url means shipping is disabled.
credMu sync.RWMutex
url string
token string
maxBatch int maxBatch int
bufCap int bufCap int
@@ -201,8 +212,6 @@ func New(cfg Config) *Shipper {
threshold: levelOf(cfg.Level), threshold: levelOf(cfg.Level),
logAll: cfg.LogAll, logAll: cfg.LogAll,
service: cfg.Service, service: cfg.Service,
url: strings.TrimRight(cfg.BaseURL, "/") + "/api/logs",
token: cfg.IngestToken,
client: client, client: client,
maxBatch: maxBatch, maxBatch: maxBatch,
bufCap: bufCap, bufCap: bufCap,
@@ -211,10 +220,53 @@ func New(cfg Config) *Shipper {
doneCh: make(chan struct{}), doneCh: make(chan struct{}),
} }
s.SetCredentials(cfg.BaseURL, cfg.IngestToken)
go s.loop(flushInterval) go s.loop(flushInterval)
return s return s
} }
// SetCredentials sets where, and as which ingest token, the Shipper sends entries. It can be called at
// any time, for example when ProjectConfigurator pushes a new token, and takes effect from the next
// flush. An empty baseURL or token disables shipping: entries are no longer buffered, anything already
// buffered is discarded, and the local console output carries on as before.
func (s *Shipper) SetCredentials(baseURL, token string) {
token = strings.TrimSpace(token)
url := ""
if base := strings.TrimRight(strings.TrimSpace(baseURL), "/"); base != "" && token != "" {
url = base + "/api/logs"
}
s.credMu.Lock()
s.url = url
s.token = token
s.credMu.Unlock()
if url == "" {
s.mu.Lock()
s.buffer = nil
s.mu.Unlock()
}
}
// Follow keeps the Shipper's endpoint and ingest token in step with ProjectConfigurator's pushes. A
// push that carries both an OmniLogger URL and an ingest token replaces the endpoint and token. Any other
// push, including the first one after a restart, leaves the current settings alone, so a service that was
// configured from its environment keeps shipping until ProjectConfigurator supplies both values.
func (s *Shipper) Follow(store *coreconfig.Store) {
apply := func(info coreconfig.Info) {
if info.OmniLoggerURL != "" && info.OmniLoggerIngestToken != "" {
s.SetCredentials(info.OmniLoggerURL, info.OmniLoggerIngestToken)
}
}
apply(store.Get())
store.Subscribe(apply)
}
// credentials returns the current endpoint and token.
func (s *Shipper) credentials() (url, token string) {
s.credMu.RLock()
defer s.credMu.RUnlock()
return s.url, s.token
}
func (s *Shipper) loop(flushInterval time.Duration) { func (s *Shipper) loop(flushInterval time.Duration) {
defer close(s.doneCh) defer close(s.doneCh)
ticker := time.NewTicker(flushInterval) ticker := time.NewTicker(flushInterval)
@@ -241,11 +293,41 @@ func (s *Shipper) requestFlush() {
} }
} }
// OmniLogger rejects a whole POST /api/logs batch when any one entry breaks its limits, so every
// entry is clamped to them before it is buffered. These mirror OmniLogger's MaxMessageBytes and
// MaxContextBytes; a message is cut with a marker, and an oversized or unshippable context is dropped
// and replaced with a marker object, so the entry itself still reaches OmniLogger.
const (
maxMessageBytes = 8 * 1024
maxContextBytes = 16 * 1024
truncatedMarker = " [truncated]"
droppedContext = `{"context_dropped":true}`
)
func clampEntry(e wireEntry) wireEntry {
if len(e.Message) > maxMessageBytes {
cut := maxMessageBytes - len(truncatedMarker)
for cut > 0 && !utf8.RuneStart(e.Message[cut]) {
cut--
}
e.Message = e.Message[:cut] + truncatedMarker
}
// OmniLogger refuses a NUL in context, which json.Marshal writes as \u0000.
if len(e.Context) > maxContextBytes || bytes.Contains(e.Context, []byte(`\u0000`)) {
e.Context = json.RawMessage(droppedContext)
}
return e
}
// enqueue appends one entry to the buffer, dropping the incoming entry // enqueue appends one entry to the buffer, dropping the incoming entry
// (rather than blocking the caller or evicting older entries) once the // (rather than blocking the caller or evicting older entries) once the
// buffer is full. This is the sole non-blocking guarantee this package // buffer is full. This is the sole non-blocking guarantee this package
// makes: a caller's Debug/Info/... call never waits on network I/O. // makes: a caller's Debug/Info/... call never waits on network I/O.
func (s *Shipper) enqueue(entry wireEntry) { func (s *Shipper) enqueue(entry wireEntry) {
if url, _ := s.credentials(); url == "" {
return
}
entry = clampEntry(entry)
s.mu.Lock() s.mu.Lock()
full := len(s.buffer) >= s.bufCap full := len(s.buffer) >= s.bufCap
if !full { if !full {
@@ -268,6 +350,7 @@ func (s *Shipper) enqueue(entry wireEntry) {
// design: a host application must never fail, panic, or slow down because // design: a host application must never fail, panic, or slow down because
// its log sink is unreachable. // its log sink is unreachable.
func (s *Shipper) flush() { func (s *Shipper) flush() {
url, token := s.credentials()
s.mu.Lock() s.mu.Lock()
if len(s.buffer) == 0 { if len(s.buffer) == 0 {
s.mu.Unlock() s.mu.Unlock()
@@ -276,34 +359,129 @@ func (s *Shipper) flush() {
batch := s.buffer batch := s.buffer
s.buffer = nil s.buffer = nil
s.mu.Unlock() s.mu.Unlock()
if url == "" {
body, err := json.Marshal(batch)
if err != nil {
s.warnOnce(fmt.Errorf("logshipper: marshal batch: %w", err))
return return
} }
// A backlog can hold up to bufCap entries, far more than OmniLogger accepts in one request, so the
// buffer is sent as several requests, each within maxRequestEntries and maxRequestBytes. When a request
// fails for a reason that may pass (no connection, a server error, or too many requests), the failed
// entries and everything after them go back to the buffer and are sent again on the next flush. A request
// OmniLogger rejects outright is dropped, because sending it again would fail the same way.
for _, chunk := range encodeBatches(batch) {
if s.send(url, token, chunk.payload, chunk.entries) {
s.requeue(batch[chunk.start:])
return
}
}
}
// Request limits for one POST /api/logs. OmniLogger refuses a request with more than 1000 entries or a
// body over 2 MiB, and it refuses the whole request when one entry is out of bounds, so every request
// stays well inside both.
const (
maxRequestEntries = 100
maxRequestBytes = 1 << 20
)
type encodedBatch struct {
payload []byte
entries int
// start is the index in the flushed batch of this request's first entry.
start int
}
// encodeBatches marshals each entry once and packs the results into JSON array bodies, starting a new
// body when the current one reaches maxRequestEntries or would pass maxRequestBytes. An entry that
// cannot be marshaled is dropped, so one bad entry never blocks the rest.
func encodeBatches(batch []wireEntry) []encodedBatch {
var out []encodedBatch
var body bytes.Buffer
count := 0
start := 0
closeBody := func() {
if count == 0 {
return
}
body.WriteByte(']')
out = append(out, encodedBatch{payload: append([]byte(nil), body.Bytes()...), entries: count, start: start})
body.Reset()
count = 0
}
for i, entry := range batch {
raw, err := json.Marshal(entry)
if err != nil {
continue
}
if count > 0 && (count >= maxRequestEntries || body.Len()+len(raw)+2 > maxRequestBytes) {
closeBody()
}
if count == 0 {
body.WriteByte('[')
start = i
} else {
body.WriteByte(',')
}
body.Write(raw)
count++
}
closeBody()
return out
}
// requeue puts entries that failed to send back at the front of the buffer, so the next flush sends them
// before newer entries. The buffer stays within bufCap: when the requeued entries and the buffer do not all
// fit, the newest entries are dropped, as enqueue drops them when the buffer is full.
func (s *Shipper) requeue(entries []wireEntry) {
s.mu.Lock()
combined := make([]wireEntry, 0, len(entries)+len(s.buffer))
combined = append(combined, entries...)
combined = append(combined, s.buffer...)
dropped := 0
if len(combined) > s.bufCap {
dropped = len(combined) - s.bufCap
combined = combined[:s.bufCap]
}
s.buffer = combined
s.mu.Unlock()
if dropped > 0 {
s.warnOnce(fmt.Errorf("logshipper: buffer full while retrying, dropping %d log entries for service %q", dropped, s.service))
}
}
// send posts one encoded batch and reports whether it failed for a reason that may pass, in which case the
// caller keeps the entries for a later retry. A request OmniLogger rejects is reported and dropped. Failures are
// otherwise swallowed by design: a host application must never fail, panic, or slow down because its log sink
// is unreachable.
func (s *Shipper) send(url, token string, body []byte, entries int) (retry bool) {
ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout) ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout)
defer cancel() defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.url, bytes.NewReader(body)) req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil { if err != nil {
s.warnOnce(fmt.Errorf("logshipper: build request: %w", err)) s.warnOnce(fmt.Errorf("logshipper: build request: %w", err))
return return false
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+s.token) req.Header.Set("Authorization", "Bearer "+token)
resp, err := s.client.Do(req) resp, err := s.client.Do(req)
if err != nil { if err != nil {
s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s: %w", len(batch), s.url, err)) s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s, will retry: %w", entries, url, err))
return return true
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 { if resp.StatusCode >= 200 && resp.StatusCode < 300 {
s.warnOnce(fmt.Errorf("logshipper: OmniLogger rejected %d entries: HTTP %d", len(batch), resp.StatusCode)) return false
} }
retry = resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500
if retry {
s.warnOnce(fmt.Errorf("logshipper: OmniLogger answered HTTP %d for %d entries, will retry", resp.StatusCode, entries))
} else {
s.warnOnce(fmt.Errorf("logshipper: OmniLogger rejected %d entries: HTTP %d", entries, resp.StatusCode))
}
return retry
} }
// warnOnce prints a local stderr warning at most once per minute, no matter // warnOnce prints a local stderr warning at most once per minute, no matter
@@ -350,7 +528,7 @@ func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) {
} }
now := time.Now() now := time.Now()
msg := formatArgs(args) msg := formatArgs(args)
upper, lower := sevName(sev) upper, _ := sevName(sev)
line := fmt.Sprintf("[%s] [%s] [%s] [%s] %s", line := fmt.Sprintf("[%s] [%s] [%s] [%s] %s",
now.Format("2006-01-02"), now.Format("15:04:05.000"), upper, s.module, msg) now.Format("2006-01-02"), now.Format("15:04:05.000"), upper, s.module, msg)
@@ -368,10 +546,26 @@ func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) {
} }
} }
// Unlike the local-only verbose dump above (which scrubs IDs for s.shipEntry(sev, ctx, msg, now)
// readability), the context shipped to OmniLogger is sent unscrubbed: }
// the whole point of centralizing logs is cross-service correlation by
// request/user/entity ID, so stripping IDs here would defeat that. // Ship queues one entry for OmniLogger at severity sev without printing it locally. Use it where the host
// already prints its own lines, such as a zap or slog core that tees to OmniLogger: the console is not
// doubled, and the entry keeps its real severity, where Writer ships everything as info. The threshold
// applies. Context is sent unscrubbed, as in emit.
func (s *Shipper) Ship(sev Level, ctx map[string]any, args ...any) {
if sev < s.threshold {
return
}
s.shipEntry(sev, ctx, formatArgs(args), time.Now())
}
// shipEntry buffers one already-formatted entry for OmniLogger.
func (s *Shipper) shipEntry(sev Level, ctx map[string]any, msg string, now time.Time) {
_, lower := sevName(sev)
// The context shipped to OmniLogger is sent unscrubbed: the whole point of centralizing logs is
// cross-service correlation by request/user/entity ID, so stripping IDs here would defeat that. Only
// the local verbose dump scrubs them.
var rawCtx json.RawMessage var rawCtx json.RawMessage
if ctx != nil { if ctx != nil {
if b, err := json.Marshal(ctx); err == nil { if b, err := json.Marshal(ctx); err == nil {
@@ -383,10 +577,64 @@ func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) {
Level: lower, Level: lower,
Message: msg, Message: msg,
Context: rawCtx, Context: rawCtx,
OccurredAt: now, OccurredAt: now.UTC().Truncate(time.Millisecond),
}) })
} }
// Writer returns an io.Writer that ships every non-empty line written to it to OmniLogger for this
// Shipper's service. It prints nothing locally, so it is meant to be paired with the console writer, e.g.
// log.SetOutput(io.MultiWriter(os.Stderr, shipper.Writer())), which keeps the existing stdout/stderr
// output and mirrors the lines to OmniLogger. The standard library log package carries no severity, so
// each line's level comes from InferLevel. Where a host knows the real level, use Ship instead.
func (s *Shipper) Writer() io.Writer {
return lineWriter{s: s}
}
type lineWriter struct {
s *Shipper
}
func (w lineWriter) Write(p []byte) (int, error) {
now := time.Now()
for _, line := range strings.Split(string(p), "\n") {
line = strings.TrimRight(line, "\r")
if strings.TrimSpace(line) == "" {
continue
}
sev := InferLevel(line)
if sev < w.s.threshold {
continue
}
w.s.shipEntry(sev, nil, line, now)
}
return len(p), nil
}
// severityRules are checked in order, and the first rule whose words appear in a line sets its level.
// Each word matches as a whole word, case-insensitively.
var severityRules = []struct {
level Level
pattern *regexp.Regexp
}{
{LevelCritical, regexp.MustCompile(`(?i)\b(panic|fatal|critical)\b`)},
{LevelError, regexp.MustCompile(`(?i)\b(error|errors|failed|failure|failures|could not|cannot|unable to)\b`)},
{LevelWarn, regexp.MustCompile(`(?i)\b(warn|warning|skipped|unavailable|retry|retrying|timed out|timeout)\b`)},
}
// InferLevel guesses the severity of a plain text line from its wording, for hosts whose logging carries no
// level, such as the standard library log package. Words such as "panic" or "fatal" give critical; "error",
// "failed", "could not", and "cannot" give error; "warning", "skipped", "unavailable", "retry", and "timeout"
// give warn; any other line is info. A line that mentions an error without failing, such as "no errors
// found", is classified as an error too. Use Ship where the real level is known.
func InferLevel(line string) Level {
for _, rule := range severityRules {
if rule.pattern.MatchString(line) {
return rule.level
}
}
return LevelInfo
}
func formatArgs(args []any) string { func formatArgs(args []any) string {
parts := make([]string, 0, len(args)) parts := make([]string, 0, len(args))
for _, a := range args { for _, a := range args {
+387 -1
View File
@@ -11,6 +11,9 @@ import (
"sync" "sync"
"testing" "testing"
"time" "time"
"unicode/utf8"
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
) )
// captureStd runs fn with os.Stdout and os.Stderr redirected, and returns what it wrote to each. // captureStd runs fn with os.Stdout and os.Stderr redirected, and returns what it wrote to each.
@@ -83,6 +86,9 @@ func newTestShipper(t *testing.T, cfg Config) *Shipper {
if cfg.BaseURL == "" { if cfg.BaseURL == "" {
cfg.BaseURL = newIngest(t, http.StatusAccepted).server.URL cfg.BaseURL = newIngest(t, http.StatusAccepted).server.URL
} }
if cfg.IngestToken == "" {
cfg.IngestToken = "test-token"
}
return New(cfg) return New(cfg)
} }
@@ -274,7 +280,7 @@ func TestAFailingSinkNeverFailsTheCallerAndWarnsOnlyOnce(t *testing.T) {
shipper.Info("two") shipper.Info("two")
shipper.Flush() shipper.Flush()
}) })
if strings.Count(stderr, "OmniLogger rejected") != 1 { if strings.Count(stderr, "answered HTTP 500") != 1 {
t.Fatalf("stderr = %q, want one rate-limited warning", stderr) t.Fatalf("stderr = %q, want one rate-limited warning", stderr)
} }
@@ -298,3 +304,383 @@ func TestNewAppliesDefaults(t *testing.T) {
t.Fatalf("defaults not applied: %+v", shipper) t.Fatalf("defaults not applied: %+v", shipper)
} }
} }
func TestWriterShipsEachNonEmptyLineAsInfoWithoutPrintingLocally(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL})
defer shipper.Close()
stdout, stderr := captureStd(t, func() {
n, err := shipper.Writer().Write([]byte("first line\r\n\nsecond line\n"))
if err != nil || n != len("first line\r\n\nsecond line\n") {
t.Fatalf("Write = %d, %v", n, err)
}
shipper.Flush()
})
if stdout != "" || stderr != "" {
t.Fatalf("Writer printed locally: stdout=%q stderr=%q", stdout, stderr)
}
entries := in.entries()
if len(entries) != 2 {
t.Fatalf("shipped %d entries, want 2: %+v", len(entries), entries)
}
if entries[0].Message != "first line" || entries[1].Message != "second line" {
t.Fatalf("messages = %q, %q", entries[0].Message, entries[1].Message)
}
for _, e := range entries {
if e.Service != "svc" || e.Level != "info" {
t.Fatalf("entry = %+v, want service svc at level info", e)
}
}
}
func TestWriterRespectsTheThreshold(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"})
defer shipper.Close()
_, _ = shipper.Writer().Write([]byte("quiet line\n"))
shipper.Flush()
if n := len(in.entries()); n != 0 {
t.Fatalf("shipped %d entries below the threshold", n)
}
}
func TestClampEntryKeepsEveryEntryInsideOmniLoggerLimits(t *testing.T) {
long := strings.Repeat("é", maxMessageBytes) // 2 bytes per rune, so the cut must land on a rune boundary
got := clampEntry(wireEntry{Message: long})
if len(got.Message) > maxMessageBytes || !strings.HasSuffix(got.Message, truncatedMarker) {
t.Fatalf("message length %d, want at most %d and ending in the marker", len(got.Message), maxMessageBytes)
}
if !utf8.ValidString(got.Message) {
t.Fatal("truncation split a UTF-8 rune")
}
big := json.RawMessage(`{"blob":"` + strings.Repeat("x", maxContextBytes) + `"}`)
if string(clampEntry(wireEntry{Context: big}).Context) != droppedContext {
t.Fatal("oversized context was not replaced by the dropped marker")
}
nul := json.RawMessage(`{"s":"a\u0000b"}`)
if string(clampEntry(wireEntry{Context: nul}).Context) != droppedContext {
t.Fatal("context with a NUL escape was not replaced by the dropped marker")
}
small := json.RawMessage(`{"ok":true}`)
if string(clampEntry(wireEntry{Context: small}).Context) != `{"ok":true}` {
t.Fatal("ordinary context was changed")
}
}
func TestNoTokenMeansShippingIsDisabled(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := New(Config{Service: "svc", BaseURL: in.server.URL, FlushInterval: time.Hour})
defer shipper.Close()
shipper.Info("not shipped")
shipper.Flush()
if n := len(in.entries()); n != 0 {
t.Fatalf("shipped %d entries without a token", n)
}
}
func TestSetCredentialsEnablesAndDisablesShippingAtRuntime(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := New(Config{Service: "svc", FlushInterval: time.Hour})
defer shipper.Close()
shipper.Info("before credentials")
shipper.SetCredentials(in.server.URL+"/", "pushed-token")
shipper.Info("after credentials")
shipper.Flush()
entries := in.entries()
if len(entries) != 1 || entries[0].Message != "after credentials" {
t.Fatalf("entries after enabling = %+v, want only the one logged after SetCredentials", entries)
}
in.mu.Lock()
gotAuth := in.auth
in.mu.Unlock()
if len(gotAuth) != 1 || !strings.HasSuffix(gotAuth[0], "Bearer pushed-token") || !strings.HasPrefix(gotAuth[0], "POST /api/logs") {
t.Fatalf("request = %q, want a bearer-authenticated POST /api/logs", gotAuth)
}
shipper.SetCredentials(in.server.URL, "")
shipper.Info("after disabling")
shipper.Flush()
if n := len(in.entries()); n != 1 {
t.Fatalf("shipped %d entries after shipping was disabled, want still 1", n)
}
}
func TestFollowAppliesOnlyPushesThatCarryAToken(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
store := coreconfig.NewStore(coreconfig.Info{})
shipper := New(Config{Service: "svc", FlushInterval: time.Hour, BaseURL: in.server.URL, IngestToken: "env-token"})
defer shipper.Close()
shipper.Follow(store)
// A push that only moves other URLs must not disable the env-configured shipper.
store.Set(coreconfig.Info{AuthGuardURL: "https://auth.example.com"})
shipper.Info("still shipping")
shipper.Flush()
if n := len(in.entries()); n != 1 {
t.Fatalf("a push without a token changed shipping: %d entries", n)
}
pushed := newIngest(t, http.StatusAccepted)
store.Set(coreconfig.Info{OmniLoggerURL: pushed.server.URL, OmniLoggerIngestToken: "pushed-token"})
shipper.Info("to the pushed endpoint")
shipper.Flush()
if n := len(pushed.entries()); n != 1 {
t.Fatalf("pushed endpoint received %d entries, want 1", n)
}
if n := len(in.entries()); n != 1 {
t.Fatalf("old endpoint still received entries after the push: %d", n)
}
}
// A backlog larger than one request allows is split so no request exceeds the entry or byte cap.
func TestFlushSplitsABacklogIntoBoundedRequests(t *testing.T) {
var mu sync.Mutex
var counts []int
var sizes []int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var batch []wireEntry
body := new(strings.Builder)
_, _ = io.Copy(body, r.Body)
_ = json.Unmarshal([]byte(body.String()), &batch)
mu.Lock()
counts = append(counts, len(batch))
sizes = append(sizes, body.Len())
mu.Unlock()
w.WriteHeader(http.StatusAccepted)
}))
t.Cleanup(server.Close)
shipper := New(Config{Service: "svc", BaseURL: server.URL, IngestToken: "t", FlushInterval: time.Hour, BufferCapacity: 2000, MaxBatchSize: 2000})
defer shipper.Close()
big := strings.Repeat("y", maxMessageBytes)
for i := 0; i < 300; i++ {
shipper.Info("small")
}
for i := 0; i < 200; i++ {
shipper.Info(big)
}
shipper.Flush()
mu.Lock()
defer mu.Unlock()
total := 0
for i, n := range counts {
total += n
if n > maxRequestEntries {
t.Fatalf("request %d carried %d entries, want at most %d", i, n, maxRequestEntries)
}
if sizes[i] > maxRequestBytes {
t.Fatalf("request %d was %d bytes, want at most %d", i, sizes[i], maxRequestBytes)
}
}
if total != 500 {
t.Fatalf("shipped %d entries, want all 500", total)
}
}
// Ship sends at the given severity and prints nothing locally, so a host that already prints its own lines
// is not doubled.
func TestShipKeepsTheSeverityAndPrintsNothingLocally(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "info"})
defer shipper.Close()
stdout, stderr := captureStd(t, func() {
shipper.Ship(LevelError, map[string]any{"request_id": "r1"}, "boom")
shipper.Ship(LevelDebug, nil, "below the threshold")
shipper.Flush()
})
if stdout != "" || stderr != "" {
t.Fatalf("Ship printed locally: stdout=%q stderr=%q", stdout, stderr)
}
entries := in.entries()
if len(entries) != 1 || entries[0].Level != "error" || entries[0].Message != "boom" {
t.Fatalf("entries = %+v, want one error entry", entries)
}
if !strings.Contains(string(entries[0].Context), `"request_id":"r1"`) {
t.Fatalf("context = %s, want the request id", entries[0].Context)
}
}
func TestFollowIgnoresAPushWithATokenButNoURL(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
store := coreconfig.NewStore(coreconfig.Info{})
shipper := New(Config{Service: "svc", FlushInterval: time.Hour, BaseURL: in.server.URL, IngestToken: "env-token"})
defer shipper.Close()
shipper.Follow(store)
store.Set(coreconfig.Info{OmniLoggerIngestToken: "orphan-token"})
shipper.Info("still configured from the environment")
shipper.Flush()
if n := len(in.entries()); n != 1 {
t.Fatalf("a token without a URL disabled the env-configured shipper: %d entries", n)
}
}
func TestInferLevelReadsTheWordingOfPlainLines(t *testing.T) {
cases := map[string]Level{
"listening on :8080": LevelInfo,
"minted an OmniLogger ingest token for mediaviewer": LevelInfo,
"push login-required to x failed: status 401": LevelError,
"ERROR: database unreachable": LevelError,
"could not open the fixture": LevelError,
"push core service info to x skipped: unreadable": LevelWarn,
"WARNING: disk nearly full": LevelWarn,
"retrying in 5s after a timeout": LevelWarn,
"panic: runtime error": LevelCritical,
"fatal: cannot start": LevelCritical,
"warning: request failed": LevelError,
}
for line, want := range cases {
if got := InferLevel(line); got != want {
t.Errorf("InferLevel(%q) = %v, want %v", line, got, want)
}
}
}
// Writer keeps each line's inferred severity, so an error line is not shipped as info.
func TestWriterKeepsTheInferredSeverityOfEachLine(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL})
defer shipper.Close()
_, _ = shipper.Writer().Write([]byte("listening on :8080\npush to x failed: boom\nretry skipped\n"))
shipper.Flush()
entries := in.entries()
if len(entries) != 3 {
t.Fatalf("shipped %d entries, want 3", len(entries))
}
want := []string{"info", "error", "warn"}
for i, e := range entries {
if e.Level != want[i] {
t.Errorf("entry %d (%q) level = %s, want %s", i, e.Message, e.Level, want[i])
}
}
}
// Writer respects the threshold per line: warnings are dropped when the threshold is error.
func TestWriterDropsLinesBelowTheThreshold(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"})
defer shipper.Close()
_, _ = shipper.Writer().Write([]byte("hello\nfailed hard\n"))
shipper.Flush()
entries := in.entries()
if len(entries) != 1 || entries[0].Level != "error" {
t.Fatalf("entries = %+v, want only the error line", entries)
}
}
// flakyIngest fails its first `failures` requests with the given status, then accepts every request, and
// counts the entries it accepted.
type flakyIngest struct {
mu sync.Mutex
failures int
status int
accepted []string
server *httptest.Server
}
func newFlakyIngest(t *testing.T, failures, status int) *flakyIngest {
t.Helper()
in := &flakyIngest{failures: failures, status: status}
in.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var batch []wireEntry
_ = json.NewDecoder(r.Body).Decode(&batch)
in.mu.Lock()
defer in.mu.Unlock()
if in.failures > 0 {
in.failures--
w.WriteHeader(in.status)
return
}
for _, e := range batch {
in.accepted = append(in.accepted, e.Message)
}
w.WriteHeader(http.StatusAccepted)
}))
t.Cleanup(in.server.Close)
return in
}
func (in *flakyIngest) messages() []string {
in.mu.Lock()
defer in.mu.Unlock()
return append([]string(nil), in.accepted...)
}
// A server error is retried on a later flush, and each entry is delivered exactly once.
func TestRetriesAServerErrorAndDeliversEachEntryOnce(t *testing.T) {
in := newFlakyIngest(t, 1, http.StatusServiceUnavailable)
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, IngestToken: "t"})
defer shipper.Close()
captureStd(t, func() {
shipper.Info("a")
shipper.Info("b")
shipper.Flush() // refused with 503: kept for retry
shipper.Flush() // accepted
shipper.Flush() // nothing left to send
})
got := in.messages()
if len(got) != 2 || got[0] != "a" || got[1] != "b" {
t.Fatalf("delivered %v, want a and b exactly once, in order", got)
}
}
// A request OmniLogger rejects with 4xx is dropped, not retried, because it would fail the same way again.
func TestDropsARejectedRequestWithoutRetrying(t *testing.T) {
in := newFlakyIngest(t, 1, http.StatusBadRequest)
shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, IngestToken: "t"})
defer shipper.Close()
captureStd(t, func() {
shipper.Info("rejected")
shipper.Flush()
shipper.Flush()
})
if got := in.messages(); len(got) != 0 {
t.Fatalf("accepted %v after a 400, want nothing", got)
}
shipper.mu.Lock()
pending := len(shipper.buffer)
shipper.mu.Unlock()
if pending != 0 {
t.Fatalf("a rejected request stayed in the buffer: %d entries", pending)
}
}
// Entries that cannot be sent while OmniLogger is unreachable wait in the buffer, and the buffer never grows
// past its capacity.
func TestRetryKeepsTheBufferWithinItsCapacity(t *testing.T) {
in := newFlakyIngest(t, 0, http.StatusAccepted)
url := in.server.URL
in.server.Close()
shipper := New(Config{Service: "svc", BaseURL: url, IngestToken: "t", FlushInterval: time.Hour, BufferCapacity: 3, MaxBatchSize: 100})
defer shipper.Close()
captureStd(t, func() {
for _, m := range []string{"a", "b", "c"} {
shipper.Info(m)
}
shipper.Flush() // unreachable: kept
for _, m := range []string{"d", "e"} {
shipper.Info(m)
}
shipper.Flush() // still unreachable; the buffer holds at most three entries
})
shipper.mu.Lock()
defer shipper.mu.Unlock()
if len(shipper.buffer) > 3 {
t.Fatalf("buffer holds %d entries, capacity is 3", len(shipper.buffer))
}
if len(shipper.buffer) != 3 || shipper.buffer[0].Message != "a" {
t.Fatalf("buffer = %+v, want the oldest three entries first", shipper.buffer)
}
}
@@ -1,43 +1,30 @@
// Package mediacore is the media-backend family's cross-service HTTP surface: // Package media is the shared media library API: media likes, saves and view stats, tags and tag
// media like/save/view stats, tags, playlists, cross-device playback sync // votes, playlists, and the stream and thumbnail routes. A service that serves media from its own
// state, and profile - the routes every media-family service mounts // library mounts these routes with Mount. A service without a media library mounts none of them.
// regardless of its own specialty (MediaViewer's own library/browse routes,
// CraftStudio's generator/downloader/converter, ContentScanner's AI
// pipeline, etc. are NOT here; each service owns those itself).
//
// Promoted from each service's own internal/server mountSharedRoutes/media.go
// into this shared library so all 7 independent media-family backends use
// one copy instead of duplicating it. Behavior is unchanged from the
// pre-split monolith - this is a mechanical extraction, not a rewrite.
// //
// A service wires this up as: // A service wires this up as:
// //
// core := mediacore.New(mediacore.Config{ // svc := media.New(media.Config{
// DB: pool, // DB: pool,
// Auth: authService, // Auth: authService,
// Sync: syncsocket.NewHub(),
// CarrierNode: carrierNodeClient, // CarrierNode: carrierNodeClient,
// ServiceName: "CarrierNode", // cfg.ServiceName // ServiceName: "CarrierNode", // cfg.ServiceName
// MediaRoots: func(ctx context.Context) []string { return cfg.MediaRoots },
// }) // })
// if err := core.Migrate(ctx); err != nil { ... } // if err := svc.Migrate(ctx); err != nil { ... }
// router.Route("/api", func(r chi.Router) { // router.Route("/api", func(r chi.Router) {
// core.Mount(r) // svc.Mount(r)
// // ... the service's own routes ... // // ... the service's own routes ...
// }) // })
package mediacore package media
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"io" "io"
"mime" "math"
"net/http" "net/http"
"net/url" "net/url"
"os"
"path/filepath" "path/filepath"
"regexp"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -48,48 +35,39 @@ import (
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient" "repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket" "repos.gfranz.ch/Gabriel20xx/shared/backend/files"
) )
// maxPlaylistReorderItems caps one reorder request. The reorder runs as a single statement, so the // maxPlaylistReorderItems caps one reorder request. The reorder runs as a single statement, so the
// cap bounds its size; a playlist longer than this is reordered in more than one request. // cap bounds its size; a playlist longer than this is reordered in more than one request.
const maxPlaylistReorderItems = 10000 const maxPlaylistReorderItems = 10000
// Config wires a Core to the rest of one service's dependencies. // Config wires a Service to the rest of one service's dependencies.
type Config struct { type Config struct {
DB *pgxpool.Pool DB *pgxpool.Pool
Auth *sharedauth.Service Auth *sharedauth.Service
Sync *syncsocket.Hub
CarrierNode *carriernodeclient.Client CarrierNode *carriernodeclient.Client
// ServiceName is recorded on mutations that track which app produced // ServiceName is recorded on mutations that track which app produced
// them (e.g. media_stats.app) - a service's own cfg.ServiceName. // them (e.g. media_stats.app) - a service's own cfg.ServiceName.
ServiceName string ServiceName string
} }
// Core mounts the shared media/tags/playlists/sync/profile routes and holds // Service mounts the shared media routes and holds what they need to run.
// what they need to run. type Service struct {
type Core struct {
db *pgxpool.Pool db *pgxpool.Pool
auth *sharedauth.Service auth *sharedauth.Service
sync *syncsocket.Hub
carrierNode *carriernodeclient.Client carrierNode *carriernodeclient.Client
serviceName string serviceName string
} }
// New returns a Core ready to Mount and Migrate. // New returns a Service ready to Mount and Migrate.
func New(cfg Config) *Core { func New(cfg Config) *Service {
return &Core{db: cfg.DB, auth: cfg.Auth, sync: cfg.Sync, carrierNode: cfg.CarrierNode, serviceName: cfg.ServiceName} return &Service{db: cfg.DB, auth: cfg.Auth, carrierNode: cfg.CarrierNode, serviceName: cfg.ServiceName}
} }
// Mount wires the shared routes onto r, exactly matching the pre-split // Mount wires the media routes onto r. Sync, profile and the TOTP routes are not media routes:
// monolith's mountSharedRoutes route table. // mount them with syncsocket.MountRoutes and auth.Service.MountAccountRoutes.
func (c *Core) Mount(r chi.Router) { func (c *Service) Mount(r chi.Router) {
r.With(c.auth.Require).Get("/security/totp/status", c.auth.TOTPStatus)
r.With(c.auth.Require).Get("/security/totp/initiate", c.auth.TOTPInitiate)
r.With(c.auth.Require).Post("/security/totp/verify", c.auth.TOTPVerify)
r.With(c.auth.Require).Post("/security/totp/disable", c.auth.TOTPDisable)
r.With(c.auth.Optional).Get("/sync", c.getSyncState)
r.With(c.auth.Require).Put("/sync", c.putSyncState)
r.With(c.auth.Optional).Get("/media/state", c.mediaState) r.With(c.auth.Optional).Get("/media/state", c.mediaState)
r.With(c.auth.Require).Post("/media/like", c.mediaLike) r.With(c.auth.Require).Post("/media/like", c.mediaLike)
r.With(c.auth.Require).Post("/media/save", c.mediaSave) r.With(c.auth.Require).Post("/media/save", c.mediaSave)
@@ -116,55 +94,6 @@ func (c *Core) Mount(r chi.Router) {
r.With(c.auth.Require).Delete("/playlists/{id}/items", c.deletePlaylistItem) r.With(c.auth.Require).Delete("/playlists/{id}/items", c.deletePlaylistItem)
r.With(c.auth.Optional).Get("/playlists/{id}/random", c.randomPlaylistItem) r.With(c.auth.Optional).Get("/playlists/{id}/random", c.randomPlaylistItem)
r.With(c.auth.Require).Patch("/playlists/{id}/items/reorder", c.reorderPlaylist) r.With(c.auth.Require).Patch("/playlists/{id}/items/reorder", c.reorderPlaylist)
r.With(c.auth.Optional).Get("/profile", c.profile)
}
func (c *Core) getSyncState(w http.ResponseWriter, r *http.Request) {
sessionID := boundedSyncString(firstNonEmpty(r.URL.Query().Get("sessionId"), "default"))
writeJSON(w, http.StatusOK, c.sync.HTTPState(sessionID))
}
func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
var input map[string]any
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
clientID := boundedSyncString(syncString(input, "clientId"))
if clientID == "" {
writeError(w, http.StatusBadRequest, "clientId is required")
return
}
mediaID, ok := syncScalar(input["mediaId"])
if !ok {
writeError(w, http.StatusBadRequest, "mediaId must be a string, a number or null")
return
}
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
state := map[string]any{
"sessionId": sessionID,
"mediaId": mediaID,
"timeMs": syncInt(input, "timeMs", 0),
"paused": syncBool(input, "paused"),
"fps": syncFPS(input),
"frame": syncInt(input, "frame", 0),
"fromClientId": clientID,
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
}
if value, ok := input["playAt"]; ok {
playAt, valid := syncScalar(value)
if !valid {
writeError(w, http.StatusBadRequest, "playAt must be a string, a number or null")
return
}
state["playAt"] = playAt
}
c.sync.SetHTTPState(sessionID, state)
// Broadcast queues immutable messages without waiting for network writes, so a slow
// websocket peer does not hold this response or create one goroutine per request.
c.sync.Broadcast(sessionID)
writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state})
} }
// MediaRecord is one row of the shared `media` table. // MediaRecord is one row of the shared `media` table.
@@ -188,13 +117,14 @@ type MediaRecord struct {
FunscriptMaxSpeed *float32 FunscriptMaxSpeed *float32
Speed *float32 Speed *float32
ModifiedAt time.Time ModifiedAt time.Time
Rating string
} }
func (c *Core) streamMediaByQuery(w http.ResponseWriter, r *http.Request) { func (c *Service) streamMediaByQuery(w http.ResponseWriter, r *http.Request) {
c.streamMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) c.streamMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id")))
} }
func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { func (c *Service) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) {
record, err := c.findMedia(r.Context(), identifier, canSeeHidden(r)) record, err := c.findMedia(r.Context(), identifier, canSeeHidden(r))
if err != nil { if err != nil {
writeError(w, http.StatusNotFound, "media not found") writeError(w, http.StatusNotFound, "media not found")
@@ -205,16 +135,33 @@ func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, ide
writeError(w, http.StatusNotFound, "media not found") writeError(w, http.StatusNotFound, "media not found")
return return
} }
c.carrierNode.Proxy(w, r, "/media/"+upstream) c.carrierNode.Proxy(w, r, streamUpstreamPath(upstream, r.URL.Query()))
} }
func (c *Core) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) { // streamUpstreamPath is the CarrierNode request path for a stream. CarrierNode answers with a live
// H.264 copy when the query carries quality (a height) and start (seconds), which is how browsers get
// containers they cannot decode, and with an MP3 copy of an audio file when it carries format=mp3.
// Those parameters are the only ones forwarded.
func streamUpstreamPath(upstream string, query url.Values) string {
forward := url.Values{}
for _, key := range []string{"quality", "start", "format"} {
if value := strings.TrimSpace(query.Get(key)); value != "" {
forward.Set(key, value)
}
}
if len(forward) == 0 {
return "/media/" + upstream
}
return "/media/" + upstream + "?" + forward.Encode()
}
func (c *Service) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) {
c.thumbnailMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) c.thumbnailMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id")))
} }
func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { func (c *Service) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) {
id := identifier id := identifier
if !SafeRelative(id) { if !files.SafeRelative(id) {
writeError(w, http.StatusBadRequest, "invalid media id") writeError(w, http.StatusBadRequest, "invalid media id")
return return
} }
@@ -235,7 +182,7 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE m.media_key=$1 OR m.id=$2 WHERE m.media_key=$1 OR m.id=$2
ORDER BY t.created_at DESC ORDER BY t.created_at DESC
LIMIT 1`, id, mediaIDArg(id)).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) { LIMIT 1`, id, mediaIDArg(id)).Scan(&thumbnailID); err == nil && files.SafeRelative(thumbnailID) {
// A row whose file CarrierNode no longer has falls through to the original image below, // A row whose file CarrierNode no longer has falls through to the original image below,
// rather than proxying CarrierNode's 404. // rather than proxying CarrierNode's 404.
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, thumbnailID) { if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, thumbnailID) {
@@ -255,7 +202,7 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
c.carrierNode.Proxy(w, r, "/media/"+upstream) c.carrierNode.Proxy(w, r, "/media/"+upstream)
} }
func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) { func (c *Service) mediaState(w http.ResponseWriter, r *http.Request) {
key := strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("mediaKey"), chi.URLParam(r, "id"))) key := strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("mediaKey"), chi.URLParam(r, "id")))
if key == "" { if key == "" {
writeError(w, http.StatusBadRequest, "missing mediaKey") writeError(w, http.StatusBadRequest, "missing mediaKey")
@@ -278,15 +225,15 @@ func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": data, "mediaKey": key, "likes": likes, "saves": saves, "views": views}) writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": data, "mediaKey": key, "likes": likes, "saves": saves, "views": views})
} }
func (c *Core) mediaLike(w http.ResponseWriter, r *http.Request) { func (c *Service) mediaLike(w http.ResponseWriter, r *http.Request) {
c.mediaStatMutation(w, r, "like") c.mediaStatMutation(w, r, "like")
} }
func (c *Core) mediaSave(w http.ResponseWriter, r *http.Request) { func (c *Service) mediaSave(w http.ResponseWriter, r *http.Request) {
c.mediaStatMutation(w, r, "save") c.mediaStatMutation(w, r, "save")
} }
func (c *Core) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) { func (c *Service) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
if user == nil { if user == nil {
writeError(w, http.StatusUnauthorized, "not authenticated") writeError(w, http.StatusUnauthorized, "not authenticated")
@@ -329,19 +276,31 @@ func (c *Core) mediaStatMutation(w http.ResponseWriter, r *http.Request, statTyp
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"mediaKey": key, "enabled": enabled}}) writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"mediaKey": key, "enabled": enabled}})
} }
func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) { func (c *Service) mediaView(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
var input struct { var input struct {
MediaKey string `json:"mediaKey"` MediaKey string `json:"mediaKey"`
} }
if r.Body != nil && r.ContentLength != 0 { if r.Body != nil && r.ContentLength != 0 {
_ = decodeRequestJSON(r, &input) if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
} }
key := strings.TrimSpace(firstNonEmpty(input.MediaKey, r.URL.Query().Get("mediaKey"))) key := strings.TrimSpace(firstNonEmpty(input.MediaKey, r.URL.Query().Get("mediaKey")))
if key == "" { if key == "" {
writeError(w, http.StatusBadRequest, "missing mediaKey") writeError(w, http.StatusBadRequest, "missing mediaKey")
return return
} }
exists, err := c.mediaExists(r.Context(), key)
if err != nil {
writeError(w, http.StatusInternalServerError, "media lookup failed")
return
}
if !exists {
writeError(w, http.StatusNotFound, "media not found")
return
}
var userID any var userID any
if user != nil { if user != nil {
userID = user.ID userID = user.ID
@@ -353,7 +312,7 @@ func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}}) writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}})
} }
func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) { func (c *Service) mediaViewSession(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
var input struct { var input struct {
MediaKey string `json:"mediaKey"` MediaKey string `json:"mediaKey"`
@@ -368,15 +327,25 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) {
if duration <= 0 { if duration <= 0 {
duration = input.Duration duration = input.Duration
} }
if strings.TrimSpace(input.MediaKey) == "" || duration <= 0 { key := strings.TrimSpace(input.MediaKey)
writeError(w, http.StatusBadRequest, "mediaKey and positive duration are required") if key == "" || duration <= 0 || duration > maxViewSessionDurationMs {
writeError(w, http.StatusBadRequest, "mediaKey and duration between 1ms and 24h are required")
return
}
exists, err := c.mediaExists(r.Context(), key)
if err != nil {
writeError(w, http.StatusInternalServerError, "media lookup failed")
return
}
if !exists {
writeError(w, http.StatusNotFound, "media not found")
return return
} }
var userID any var userID any
if user != nil { if user != nil {
userID = user.ID userID = user.ID
} }
_, err := c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, strings.TrimSpace(input.MediaKey), userID, duration) _, err = c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, key, userID, duration)
if err != nil { if err != nil {
writeError(w, http.StatusInternalServerError, "view session could not be recorded") writeError(w, http.StatusInternalServerError, "view session could not be recorded")
return return
@@ -384,7 +353,16 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}}) writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}})
} }
func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) { const maxViewSessionDurationMs int64 = 24 * 60 * 60 * 1000
func (c *Service) 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 *Service) mediaLiked(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID) rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID)
if err != nil { if err != nil {
@@ -403,7 +381,7 @@ func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": items, "items": items}) writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": items, "items": items})
} }
func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) { func (c *Service) mediaTags(w http.ResponseWriter, r *http.Request) {
key := strings.TrimSpace(chi.URLParam(r, "id")) key := strings.TrimSpace(chi.URLParam(r, "id"))
rows, err := c.db.Query(r.Context(), ` rows, err := c.db.Query(r.Context(), `
SELECT mt.tag, COALESCE(SUM(mv.vote), 0) AS score SELECT mt.tag, COALESCE(SUM(mv.vote), 0) AS score
@@ -425,7 +403,7 @@ func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"tags": tags}) writeJSON(w, http.StatusOK, map[string]any{"tags": tags})
} }
func (c *Core) addMediaTag(w http.ResponseWriter, r *http.Request) { func (c *Service) addMediaTag(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
var input struct { var input struct {
Tag string `json:"tag"` Tag string `json:"tag"`
@@ -448,7 +426,7 @@ func (c *Core) addMediaTag(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, map[string]any{"tag": tag}) writeJSON(w, http.StatusCreated, map[string]any{"tag": tag})
} }
func (c *Core) voteMediaTag(w http.ResponseWriter, r *http.Request) { func (c *Service) voteMediaTag(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
var input struct { var input struct {
Vote int `json:"vote"` Vote int `json:"vote"`
@@ -474,9 +452,22 @@ func (c *Core) voteMediaTag(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"tag": tag, "vote": input.Vote}) writeJSON(w, http.StatusOK, map[string]any{"tag": tag, "vote": input.Vote})
} }
func (c *Core) tagSuggestions(w http.ResponseWriter, r *http.Request) { func (c *Service) tagSuggestions(w http.ResponseWriter, r *http.Request) {
limit := optionalInt(r.URL.Query().Get("limit"), 50, 1, 1000) // Without a limit every tag comes back. A NULL LIMIT is no limit in Postgres.
rows, err := c.db.Query(r.Context(), `SELECT tag, COUNT(*) AS frequency FROM media_tags GROUP BY tag ORDER BY frequency DESC, LOWER(tag) LIMIT $1`, limit) var limit any
if value := r.URL.Query().Get("limit"); value != "" {
limit = optionalInt(value, 50, 1, math.MaxInt)
}
// Match the library's visibility rules and count media items rather than tag rows:
// a tag can have contributions from multiple users, and old tags may outlive media.
rows, err := c.db.Query(r.Context(), `
SELECT MIN(mt.tag) AS tag, COUNT(DISTINCT m.media_key) AS frequency
FROM media_tags mt
JOIN media m ON m.media_key = mt.media_key
WHERE m.active = TRUE AND m.content_scanner_processed = TRUE
GROUP BY LOWER(mt.tag)
ORDER BY frequency DESC, LOWER(MIN(mt.tag))
LIMIT $1`, limit)
if err != nil { if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}}) writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}})
return return
@@ -493,12 +484,22 @@ func (c *Core) tagSuggestions(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"tags": tags}) writeJSON(w, http.StatusOK, map[string]any{"tags": tags})
} }
func (c *Core) tagMedia(w http.ResponseWriter, r *http.Request) { func (c *Service) tagMedia(w http.ResponseWriter, r *http.Request) {
tag := strings.ToLower(strings.TrimSpace(chi.URLParam(r, "tag"))) tag := strings.ToLower(strings.TrimSpace(chi.URLParam(r, "tag")))
pageNumber := optionalInt(r.URL.Query().Get("page"), 1, 1, 1000000) pageNumber := optionalInt(r.URL.Query().Get("page"), 1, 1, 1000000)
limit := optionalInt(r.URL.Query().Get("limit"), 24, 1, 100) limit := optionalInt(r.URL.Query().Get("limit"), 24, 1, 100)
offset := (pageNumber - 1) * limit offset := (pageNumber - 1) * limit
rows, err := c.db.Query(r.Context(), `SELECT DISTINCT media_key FROM media_tags WHERE LOWER(tag) = $1 ORDER BY media_key LIMIT $2 OFFSET $3`, tag, limit, offset) // Only media the library lists. A tag keeps its rows after its media is hidden or leaves the
// library, and a hidden item's thumbnail is not found for a viewer, so those would show as
// broken tag examples.
const libraryMedia = `FROM media_tags mt JOIN media m ON m.media_key = mt.media_key
WHERE LOWER(mt.tag) = $1 AND m.active AND m.content_scanner_processed`
var total int64
if err := c.db.QueryRow(r.Context(), `SELECT COUNT(DISTINCT m.media_key) `+libraryMedia, tag).Scan(&total); err != nil {
writeError(w, http.StatusInternalServerError, "tag media unavailable")
return
}
rows, err := c.db.Query(r.Context(), `SELECT DISTINCT m.media_key `+libraryMedia+` ORDER BY m.media_key LIMIT $2 OFFSET $3`, tag, limit, offset)
if err != nil { if err != nil {
writeError(w, http.StatusInternalServerError, "tag media unavailable") writeError(w, http.StatusInternalServerError, "tag media unavailable")
return return
@@ -511,10 +512,12 @@ func (c *Core) tagMedia(w http.ResponseWriter, r *http.Request) {
items = append(items, map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key), "name": filepath.Base(urlPath(key))}) items = append(items, map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key), "name": filepath.Base(urlPath(key))})
} }
} }
writeJSON(w, http.StatusOK, map[string]any{"data": items, "items": items, "media": items, "page": pageNumber}) totalPages := max(1, int((total+int64(limit)-1)/int64(limit)))
pagination := map[string]any{"page": pageNumber, "pageSize": limit, "total": total, "totalPages": totalPages}
writeJSON(w, http.StatusOK, map[string]any{"data": items, "items": items, "media": items, "page": pageNumber, "pagination": pagination})
} }
func (c *Core) playlists(w http.ResponseWriter, r *http.Request) { func (c *Service) playlists(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
rows, err := c.db.Query(r.Context(), `SELECT id, name, created_at FROM playlists WHERE user_id=$1 ORDER BY created_at DESC`, user.ID) rows, err := c.db.Query(r.Context(), `SELECT id, name, created_at FROM playlists WHERE user_id=$1 ORDER BY created_at DESC`, user.ID)
if err != nil { if err != nil {
@@ -534,7 +537,7 @@ func (c *Core) playlists(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists")) writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists"))
} }
func (c *Core) playlistSummary(w http.ResponseWriter, r *http.Request) { func (c *Service) playlistSummary(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
if user == nil { if user == nil {
writeJSON(w, http.StatusOK, success(map[string]any{"playlists": []any{}}, "No playlists")) writeJSON(w, http.StatusOK, success(map[string]any{"playlists": []any{}}, "No playlists"))
@@ -558,7 +561,7 @@ func (c *Core) playlistSummary(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists summary")) writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists summary"))
} }
func (c *Core) playlist(w http.ResponseWriter, r *http.Request) { func (c *Service) playlist(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || user == nil { if err != nil || user == nil {
@@ -574,7 +577,7 @@ func (c *Core) playlist(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist")) writeJSON(w, http.StatusOK, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist"))
} }
func (c *Core) createPlaylist(w http.ResponseWriter, r *http.Request) { func (c *Service) createPlaylist(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
var input struct { var input struct {
Name string `json:"name"` Name string `json:"name"`
@@ -598,7 +601,7 @@ func (c *Core) createPlaylist(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist created")) writeJSON(w, http.StatusCreated, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist created"))
} }
func (c *Core) deletePlaylist(w http.ResponseWriter, r *http.Request) { func (c *Service) deletePlaylist(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil { if err != nil {
@@ -613,7 +616,7 @@ func (c *Core) deletePlaylist(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist deleted")) writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist deleted"))
} }
func (c *Core) playlistItems(w http.ResponseWriter, r *http.Request) { func (c *Service) playlistItems(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || user == nil { if err != nil || user == nil {
@@ -644,7 +647,7 @@ func (c *Core) playlistItems(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, success(map[string]any{"items": items}, "Playlist items")) writeJSON(w, http.StatusOK, success(map[string]any{"items": items}, "Playlist items"))
} }
func (c *Core) addPlaylistItem(w http.ResponseWriter, r *http.Request) { func (c *Service) addPlaylistItem(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil { if err != nil {
@@ -677,7 +680,7 @@ func (c *Core) addPlaylistItem(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, success(map[string]any{"mediaKey": key}, "Playlist item added")) writeJSON(w, http.StatusCreated, success(map[string]any{"mediaKey": key}, "Playlist item added"))
} }
func (c *Core) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { func (c *Service) deletePlaylistItem(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil { if err != nil {
@@ -701,7 +704,7 @@ func (c *Core) deletePlaylistItem(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist item deleted")) writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist item deleted"))
} }
func (c *Core) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { func (c *Service) randomPlaylistItem(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
if user == nil { if user == nil {
writeError(w, http.StatusNotFound, "playlist not found") writeError(w, http.StatusNotFound, "playlist not found")
@@ -720,7 +723,7 @@ func (c *Core) randomPlaylistItem(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, success(map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key)}, "Random playlist media")) writeJSON(w, http.StatusOK, success(map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key)}, "Random playlist media"))
} }
func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) { func (c *Service) reorderPlaylist(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context()) user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil { if err != nil {
@@ -768,15 +771,6 @@ func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered")) writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered"))
} }
func (c *Core) profile(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
if user == nil {
writeJSON(w, http.StatusOK, map[string]any{"user": nil})
return
}
writeJSON(w, http.StatusOK, map[string]any{"user": user})
}
// canSeeHidden reports whether the caller is a moderator, who may stream and view media that has // canSeeHidden reports whether the caller is a moderator, who may stream and view media that has
// been hidden (active = FALSE). Everyone else gets hidden media as not found. // been hidden (active = FALSE). Everyone else gets hidden media as not found.
func canSeeHidden(r *http.Request) bool { func canSeeHidden(r *http.Request) bool {
@@ -785,7 +779,7 @@ func canSeeHidden(r *http.Request) bool {
// isHiddenMedia reports whether identifier names a media item that has been hidden. A lookup // isHiddenMedia reports whether identifier names a media item that has been hidden. A lookup
// error counts as hidden, so a database fault never exposes hidden media. // error counts as hidden, so a database fault never exposes hidden media.
func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool { func (c *Service) isHiddenMedia(ctx context.Context, identifier string) bool {
var hidden bool var hidden bool
err := c.db.QueryRow(ctx, ` err := c.db.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR id=$2))`, SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR id=$2))`,
@@ -793,9 +787,18 @@ func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
return err != nil || hidden return err != nil || hidden
} }
// findMedia looks up one media item by media key or numeric id. Hidden media is only returned // MediaLookupOptions controls which otherwise-hidden records a media lookup may return.
// when includeHidden is set. type MediaLookupOptions struct {
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) { // IncludeHidden lets moderators look up media with active = FALSE.
IncludeHidden bool
// RequireContentScannerProcessed limits the result to items imported by ContentScanner.
RequireContentScannerProcessed bool
}
// FindMedia looks up one media item by media key or numeric id. Shared media routes
// preserve moderator access to hidden items; ContentScanner-backed consumers can also
// request the same processed-only filtering used by MediaViewer's library routes.
func (c *Service) FindMedia(ctx context.Context, identifier string, options MediaLookupOptions) (MediaRecord, error) {
identifier = strings.TrimSpace(identifier) identifier = strings.TrimSpace(identifier)
var record MediaRecord var record MediaRecord
row := c.db.QueryRow(ctx, ` row := c.db.QueryRow(ctx, `
@@ -803,15 +806,17 @@ func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden b
COALESCE(NULLIF(file_path, ''), media_key), COALESCE(original_filename, ''), COALESCE(source, 'Filesystem'), COALESCE(NULLIF(file_path, ''), media_key), COALESCE(original_filename, ''), COALESCE(source, 'Filesystem'),
COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0), COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0),
COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count, COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count,
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at) funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at),
FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) LIMIT 1`, identifier, mediaIDArg(identifier), includeHidden) COALESCE(rating, '')
FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) AND (NOT $4 OR content_scanner_processed) LIMIT 1`,
identifier, mediaIDArg(identifier), options.IncludeHidden, options.RequireContentScannerProcessed)
var title, description string var title, description string
var width, height int var width, height int
var duration, size int64 var duration, size int64
var funscriptActionCount pgtype.Int4 var funscriptActionCount pgtype.Int4
var funscriptAvgSpeed, funscriptMaxSpeed pgtype.Float4 var funscriptAvgSpeed, funscriptMaxSpeed pgtype.Float4
var speed float32 var speed float32
if err := row.Scan(&record.ID, &record.MediaKey, &record.MediaType, &title, &description, &record.FilePath, &record.OriginalName, &record.Source, &width, &height, &duration, &size, &record.IsVR, &record.HasFunscript, &funscriptActionCount, &funscriptAvgSpeed, &funscriptMaxSpeed, &speed, &record.ModifiedAt); err != nil { if err := row.Scan(&record.ID, &record.MediaKey, &record.MediaType, &title, &description, &record.FilePath, &record.OriginalName, &record.Source, &width, &height, &duration, &size, &record.IsVR, &record.HasFunscript, &funscriptActionCount, &funscriptAvgSpeed, &funscriptMaxSpeed, &speed, &record.ModifiedAt, &record.Rating); err != nil {
return MediaRecord{}, err return MediaRecord{}, err
} }
if funscriptActionCount.Valid { if funscriptActionCount.Valid {
@@ -850,8 +855,14 @@ func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden b
return record, nil return record, nil
} }
// findMedia keeps the media routes on the same lookup implementation used by
// applications that need ContentScanner's processed-only filter.
func (c *Service) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
return c.FindMedia(ctx, identifier, MediaLookupOptions{IncludeHidden: includeHidden})
}
// ToJSON is the shared wire shape for a media record, matching every // ToJSON is the shared wire shape for a media record, matching every
// mediacore route's own response shape (id/mediaKey/filename/url/thumbnail/ // media route's own response shape (id/mediaKey/filename/url/thumbnail/
// etc.) - services with their own media listing routes (e.g. MediaViewer's // etc.) - services with their own media listing routes (e.g. MediaViewer's
// mountViewerRoutes) should use this too, for a consistent shape. // mountViewerRoutes) should use this too, for a consistent shape.
func (record MediaRecord) ToJSON() map[string]any { func (record MediaRecord) ToJSON() map[string]any {
@@ -863,7 +874,7 @@ func (record MediaRecord) ToJSON() map[string]any {
if mediaType == "unknown" || mediaType == "" { if mediaType == "unknown" || mediaType == "" {
mediaType = InferMediaType(filename) mediaType = InferMediaType(filename)
} }
return map[string]any{ result := map[string]any{
"id": record.MediaKey, "numericId": record.ID, "mediaKey": record.MediaKey, "id": record.MediaKey, "numericId": record.ID, "mediaKey": record.MediaKey,
"filename": filename, "name": filename, "title": record.Title, "description": record.Description, "filename": filename, "name": filename, "title": record.Title, "description": record.Description,
"relPath": urlPath(record.FilePath), "mediaType": mediaType, "source": record.Source, "relPath": urlPath(record.FilePath), "mediaType": mediaType, "source": record.Source,
@@ -873,165 +884,14 @@ func (record MediaRecord) ToJSON() map[string]any {
"funscriptActionCount": intValue(record.FunscriptActionCount), "funscriptAvgSpeed": floatValue(record.FunscriptAvgSpeed), "funscriptMaxSpeed": floatValue(record.FunscriptMaxSpeed), "funscriptActionCount": intValue(record.FunscriptActionCount), "funscriptAvgSpeed": floatValue(record.FunscriptAvgSpeed), "funscriptMaxSpeed": floatValue(record.FunscriptMaxSpeed),
"modifiedAt": record.ModifiedAt, "modifiedAt": record.ModifiedAt,
} }
} if record.Rating != "" {
result["rating"] = record.Rating
// 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 {
var value string
if err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value); err != nil || value == "" {
return fallback
} }
return value return result
}
// 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, "")))
if value == "" {
return fallback
}
return value == "1" || value == "true" || value == "yes" || value == "on"
}
// SaveSetting upserts one key in the shared `settings` table.
func SaveSetting(ctx context.Context, db *pgxpool.Pool, key, value string) error {
_, err := db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, value)
return err
}
// carrierNodeInstancePattern matches a registered project key naming a CarrierNode instance: the
// base "carriernode" itself, or a numbered peer like "carriernode_2" - see
// ProjectConfigurator/backend/cmd/projectconfigurator/settings.go's identical pattern (kept in
// sync manually since one is the sender's copy and this is the direct-DB-read receiver's copy of
// the same convention, not literally shared code).
var carrierNodeInstancePattern = regexp.MustCompile(`^carriernode(_\d+)?$`)
// CarrierNodeURLs returns every CarrierNode instance registered in ProjectConfigurator's Projects
// workspace ("carriernode_url", "carriernode_2_url", ...), read directly from the shared
// `settings` table in registration order, dropping any instance with no URL set. This is for the
// 7 MEDIA_SERVICE instances that share this database directly instead of going through
// ProjectConfigurator's coreconfig push (see ProjectConfigurator/README.md's "Pushing core service
// info to other projects" section) - wire it as a carriernodeclient.Client's BaseURLs:
//
// carriernodeclient.NewMulti(secret, func(ctx context.Context) []string {
// return mediacore.CarrierNodeURLs(ctx, db, fallback)
// })
//
// 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", "")), &registered)
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 != "" {
urls = append(urls, url)
}
}
if len(urls) == 0 {
if url := strings.TrimSpace(SettingValue(ctx, db, "carriernode_url", "")); url != "" {
urls = []string{url}
}
}
if len(urls) == 0 {
return fallback
}
return urls
} }
// --- path-safety helpers (generic, no Core dependency) --- // --- path-safety helpers (generic, no Core dependency) ---
// SafeRelative reports whether value is a relative path with no `..`
// traversal or absolute-path escape (Windows drive letters included).
func SafeRelative(value string) bool {
value = strings.TrimSpace(value)
windowsAbsolute := len(value) >= 2 && value[1] == ':'
return value != "" && !strings.ContainsRune(value, 0) && !filepath.IsAbs(value) && !strings.HasPrefix(value, "/") && !strings.HasPrefix(value, `\`) && !windowsAbsolute && filepath.Clean(value) != "." && filepath.Clean(value) != ".." && !strings.HasPrefix(filepath.Clean(value), ".."+string(filepath.Separator)) && !strings.Contains(value, "../") && !strings.Contains(value, `..\`)
}
// WithinRoot reports whether candidate is (non-strictly) inside root.
func WithinRoot(root, candidate string) bool {
rel, err := filepath.Rel(root, candidate)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel)
}
// SameRealRoot reports whether candidate's symlink-resolved real path is
// still inside root's symlink-resolved real path (guards against a symlink
// planted inside root pointing outside it).
func SameRealRoot(root, candidate string) bool {
realRoot, err := filepath.EvalSymlinks(root)
if err != nil {
return false
}
realCandidate, err := filepath.EvalSymlinks(candidate)
if err != nil {
return false
}
realRoot, err = filepath.Abs(realRoot)
if err != nil {
return false
}
realCandidate, err = filepath.Abs(realCandidate)
return err == nil && WithinRoot(realRoot, realCandidate)
}
// ResolveUnderRoots resolves value (a "/media/"-prefixed or bare relative
// path) against each of roots in order, returning the first root it
// actually exists under as a real file (not a directory, and not merely a
// symlink escape - see SameRealRoot). Returns os.ErrNotExist if no root
// matches.
func ResolveUnderRoots(value string, roots []string) (string, error) {
value = strings.TrimSpace(strings.TrimPrefix(value, "/media/"))
value = strings.TrimPrefix(value, "/")
if value == "" || strings.ContainsRune(value, 0) {
return "", errors.New("empty path")
}
for _, root := range roots {
rootAbs, err := filepath.Abs(root)
if err != nil {
continue
}
candidate := value
if !filepath.IsAbs(candidate) {
candidate = filepath.Join(rootAbs, filepath.FromSlash(candidate))
}
candidate, err = filepath.Abs(candidate)
if err != nil || !WithinRoot(rootAbs, candidate) {
continue
}
info, err := os.Stat(candidate)
if err == nil && !info.IsDir() && SameRealRoot(rootAbs, candidate) {
return candidate, nil
}
}
return "", os.ErrNotExist
}
// ServeFile serves fullPath (an already-resolved, already-safety-checked
// path) with the correct Content-Type and range-request support.
func ServeFile(w http.ResponseWriter, r *http.Request, fullPath string) {
file, err := os.Open(fullPath)
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
return
}
defer file.Close()
info, err := file.Stat()
if err != nil || info.IsDir() {
writeError(w, http.StatusNotFound, "file not found")
return
}
if contentType := mime.TypeByExtension(filepath.Ext(fullPath)); contentType != "" {
w.Header().Set("Content-Type", contentType)
}
http.ServeContent(w, r, filepath.Base(fullPath), info.ModTime(), file)
}
// InferMediaType guesses a media type from a filename's extension. // InferMediaType guesses a media type from a filename's extension.
func InferMediaType(value string) string { func InferMediaType(value string) string {
switch strings.ToLower(filepath.Ext(value)) { switch strings.ToLower(filepath.Ext(value)) {
@@ -1068,21 +928,19 @@ func urlPath(value string) string {
return value return value
} }
// upstreamMediaPath returns the escaped CarrierNode path for a stored file path. It reports false // upstreamMediaPath returns the CarrierNode path for a stored file path. It reports false only when
// when the stored path is not a safe relative path, or when it contains a query or fragment marker // the stored path is not a safe relative path.
// that CarrierNode would read as the end of the path. //
// url.PathEscape would write a comma as %2C, and the request then keeps that escape as a raw path.
// CarrierNode's router matches a raw path literally, so "Hello, World.mp4" would never be found. A
// URL built from Path alone leaves no raw path, so the name reaches CarrierNode decoded. Query and
// fragment markers are escaped the same way, so they no longer need refusing.
func upstreamMediaPath(filePath string) (string, bool) { func upstreamMediaPath(filePath string) (string, bool) {
relative := urlPath(filePath) relative := urlPath(filePath)
if !SafeRelative(relative) || strings.ContainsAny(relative, "?#") { if !files.SafeRelative(relative) {
return "", false return "", false
} }
// Escape each segment so percent-escapes and other reserved characters in a stored name return (&url.URL{Path: relative}).EscapedPath(), true
// reach CarrierNode as literal text, not as an escape or a traversal it decodes later.
segments := strings.Split(relative, "/")
for i, segment := range segments {
segments[i] = url.PathEscape(segment)
}
return strings.Join(segments, "/"), true
} }
// canonicalMediaID returns the numeric media id that identifier spells exactly. Leading zeros, signs // canonicalMediaID returns the numeric media id that identifier spells exactly. Leading zeros, signs
@@ -1172,62 +1030,3 @@ func writeJSON(w http.ResponseWriter, status int, value any) {
func writeError(w http.ResponseWriter, status int, message string) { func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message, "message": message}) writeJSON(w, status, map[string]string{"error": message, "message": message})
} }
// --- sync-message helpers (shared with syncsocket's own copies; duplicated
// here rather than exported from syncsocket, since these are trivially small
// and this keeps mediacore and syncsocket independently buildable) ---
func syncString(message map[string]any, key string) string {
value, _ := message[key].(string)
return strings.TrimSpace(value)
}
func boundedSyncString(value string) string {
const maxSyncIdentifier = 128
value = strings.TrimSpace(value)
if len(value) > maxSyncIdentifier {
return value[:maxSyncIdentifier]
}
return value
}
func syncBool(message map[string]any, key string) bool {
value, _ := message[key].(bool)
return value
}
// syncScalar keeps a client-supplied sync value to what sync state holds: null, a number or a
// bounded string. Objects, arrays and booleans are refused so arbitrary JSON is never stored as
// shared session state.
func syncScalar(value any) (any, bool) {
switch typed := value.(type) {
case nil, float64:
return typed, true
case string:
return boundedSyncString(typed), true
default:
return nil, false
}
}
func syncInt(message map[string]any, key string, fallback int64) int64 {
value, ok := message[key].(float64)
if !ok {
return fallback
}
if value < 0 {
return 0
}
return int64(value)
}
func syncFPS(message map[string]any) int64 {
fps := syncInt(message, "fps", 30)
if fps < 1 {
return 1
}
if fps > 240 {
return 240
}
return fps
}
@@ -1,10 +1,11 @@
package mediacore package media
import ( import (
"context" "context"
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url"
"strings" "strings"
"testing" "testing"
@@ -125,40 +126,20 @@ func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) {
} }
} }
// TestSyncWriteRequiresLogin checks that an anonymous PUT /sync is refused before it can change func TestStreamUpstreamPathForwardsOnlyLiveTranscodeOptions(t *testing.T) {
// shared playback state. The Core has no sync hub, so reaching the handler would panic. for _, tc := range []struct {
func TestSyncWriteRequiresLogin(t *testing.T) { name string
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject") query url.Values
router := chi.NewRouter() want string
New(Config{Auth: auth}).Mount(router) }{
{"plain stream", url.Values{"mediaKey": {"abc"}}, "/media/Videos/clip.mp4"},
request := httptest.NewRequest(http.MethodPut, "/sync", strings.NewReader(`{"clientId":"c1","mediaId":"m1"}`)) {"blank options are dropped", url.Values{"quality": {" "}, "start": {""}}, "/media/Videos/clip.mp4"},
response := httptest.NewRecorder() {"quality and start are forwarded", url.Values{"mediaKey": {"abc"}, "quality": {"1080"}, "start": {" 12.5 "}}, "/media/Videos/clip.mp4?quality=1080&start=12.5"},
router.ServeHTTP(response, request) {"quality alone", url.Values{"quality": {"720"}}, "/media/Videos/clip.mp4?quality=720"},
if response.Code != http.StatusUnauthorized { {"format is forwarded for audio copies", url.Values{"mediaKey": {"abc"}, "format": {"mp3"}}, "/media/Videos/clip.mp4?format=mp3"},
t.Errorf("PUT /sync status = %d, want %d", response.Code, http.StatusUnauthorized) } {
} if got := streamUpstreamPath("Videos/clip.mp4", tc.query); got != tc.want {
} t.Errorf("%s: streamUpstreamPath() = %q, want %q", tc.name, got, tc.want)
// TestSyncScalarKeepsOnlyScalars checks that sync values are limited to null, numbers and
// bounded strings, so objects, arrays and booleans are never stored as session state.
func TestSyncScalarKeepsOnlyScalars(t *testing.T) {
if value, ok := syncScalar(nil); !ok || value != nil {
t.Errorf("syncScalar(nil) = %v, %v; want nil, true", value, ok)
}
if value, ok := syncScalar(float64(7)); !ok || value != float64(7) {
t.Errorf("syncScalar(7) = %v, %v; want 7, true", value, ok)
}
if value, ok := syncScalar(" media-1 "); !ok || value != "media-1" {
t.Errorf("syncScalar(string) = %v, %v; want media-1, true", value, ok)
}
long, ok := syncScalar(strings.Repeat("x", 500))
if text, isText := long.(string); !ok || !isText || len(text) != 128 {
t.Errorf("syncScalar(long string) = %v, %v; want a 128-byte string, true", long, ok)
}
for _, refused := range []any{map[string]any{"a": 1}, []any{1}, true} {
if _, ok := syncScalar(refused); ok {
t.Errorf("syncScalar(%#v) accepted a non-scalar value", refused)
} }
} }
} }
@@ -1,25 +1,24 @@
package mediacore package media
import "context" import (
"context"
// Migrate creates every table (and its indexes) mediacore's shared routes "repos.gfranz.ch/Gabriel20xx/shared/backend/settings"
// read or write, using CREATE TABLE/INDEX IF NOT EXISTS so whichever )
// media-family service starts first against a fresh database creates them
// and every other service's own startup is a no-op. Statements are copied // Migrate creates the settings table, then every table (and index) the media routes read or
// verbatim from the pre-split monolith's // write. Statements use CREATE TABLE/INDEX IF NOT EXISTS, so whichever service starts first
// internal/database/migrations/001_initial.sql, limited to the tables // against a fresh database creates them and every other service's own startup is a no-op.
// mediacore itself owns (media, media_stats, media_view_sessions,
// media_tags, media_tag_votes, settings, playlists, playlist_items,
// workflow_jobs, thumbnails) plus `users`, which several of those
// reference via foreign key even though identity itself now lives in
// AuthGuard (see mediaauth's package doc comment) - the column is kept for
// FK integrity, not queried by mediacore.
// //
// Each per-service backend additionally runs its own migration for tables // users is created because several media tables reference it by foreign key. Identity itself lives
// it exclusively owns (e.g. ContentScanner's media_worker_jobs/ // in AuthGuard, so the column is kept for foreign-key integrity and is not queried here.
// media_analysis_tasks, CraftStudio's generated_media/downloaded_media, //
// ProjectConfigurator's mount_paths) - those are NOT run here. // A service runs its own migration for any tables it alone owns (for example ContentScanner's
func (c *Core) Migrate(ctx context.Context) error { // media_worker_jobs and CraftStudio's generated_media); those are not run here.
func (c *Service) Migrate(ctx context.Context) error {
if err := settings.Migrate(ctx, c.db); err != nil {
return err
}
for _, statement := range migrationStatements { for _, statement := range migrationStatements {
if _, err := c.db.Exec(ctx, statement); err != nil { if _, err := c.db.Exec(ctx, statement); err != nil {
return err return err
@@ -31,6 +30,7 @@ func (c *Core) Migrate(ctx context.Context) error {
var migrationStatements = []string{ var migrationStatements = []string{
`CREATE EXTENSION IF NOT EXISTS pgcrypto`, `CREATE EXTENSION IF NOT EXISTS pgcrypto`,
`CREATE EXTENSION IF NOT EXISTS pg_trgm`, `CREATE EXTENSION IF NOT EXISTS pg_trgm`,
`DROP INDEX IF EXISTS media_search_idx`,
`CREATE TABLE IF NOT EXISTS users ( `CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
@@ -66,6 +66,7 @@ var migrationStatements = []string{
file_path TEXT, file_path TEXT,
original_filename TEXT, original_filename TEXT,
active BOOLEAN NOT NULL DEFAULT TRUE, active BOOLEAN NOT NULL DEFAULT TRUE,
content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb, metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
width INT, width INT,
height INT, height INT,
@@ -73,6 +74,7 @@ var migrationStatements = []string{
size_bytes BIGINT, size_bytes BIGINT,
is_vr BOOLEAN NOT NULL DEFAULT FALSE, is_vr BOOLEAN NOT NULL DEFAULT FALSE,
has_funscript BOOLEAN NOT NULL DEFAULT FALSE, has_funscript BOOLEAN NOT NULL DEFAULT FALSE,
rating TEXT,
funscript_action_count INT, funscript_action_count INT,
funscript_avg_speed REAL, funscript_avg_speed REAL,
funscript_max_speed REAL, funscript_max_speed REAL,
@@ -80,12 +82,13 @@ var migrationStatements = []string{
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW() modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`, )`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS rating TEXT`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_action_count INT`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_action_count INT`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_avg_speed REAL`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_avg_speed REAL`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`,
`CREATE INDEX IF NOT EXISTS media_active_idx ON media (active)`, `CREATE INDEX IF NOT EXISTS media_active_idx ON media (active)`,
`CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path)`, `CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path)`,
`CREATE INDEX IF NOT EXISTS media_search_idx ON media USING GIN (to_tsvector('simple', COALESCE(title, '') || ' ' || COALESCE(original_filename, '') || ' ' || COALESCE(file_path, '')))`,
`CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`, `CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`,
`CREATE TABLE IF NOT EXISTS media_stats ( `CREATE TABLE IF NOT EXISTS media_stats (
@@ -152,29 +155,6 @@ var migrationStatements = []string{
UNIQUE (playlist_id, media_key) UNIQUE (playlist_id, media_key)
)`, )`,
`CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`INSERT INTO settings (key, value) VALUES ('auth_required', 'true') ON CONFLICT (key) DO NOTHING`,
`CREATE TABLE IF NOT EXISTS workflow_jobs (
id TEXT PRIMARY KEY,
service TEXT NOT NULL,
tool TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
progress INT NOT NULL DEFAULT 0,
request JSONB NOT NULL DEFAULT '{}'::jsonb,
result JSONB NOT NULL DEFAULT '{}'::jsonb,
error_message TEXT,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ
)`,
`CREATE INDEX IF NOT EXISTS workflow_jobs_service_idx ON workflow_jobs (service, created_at DESC)`,
`CREATE TABLE IF NOT EXISTS thumbnails ( `CREATE TABLE IF NOT EXISTS thumbnails (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL, media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
+72
View File
@@ -0,0 +1,72 @@
package media
import (
"net/http"
"testing"
)
func TestUpstreamMediaPathRefusesTraversal(t *testing.T) {
for _, stored := range []string{"../x.mp4", "media/../../x.mp4", `..\x.mp4`} {
if _, ok := upstreamMediaPath(stored); ok {
t.Errorf("upstreamMediaPath(%q) accepted, want refused", stored)
}
}
}
// CarrierNode's router matches a raw request path literally, so a name must reach it with no raw path:
// a %2C for a comma would never match "Hello, World.mp4". Query and fragment markers are escaped, not refused.
func TestUpstreamMediaPathReachesCarrierNodeAsTheLiteralName(t *testing.T) {
for _, stored := range []string{"Hello, World.mp4", "a;b.mp4", "x?y.mp4", "a#b.mp4", "100%.mp4", "dir one/x y.mp4"} {
upstream, ok := upstreamMediaPath(stored)
if !ok {
t.Fatalf("upstreamMediaPath(%q) refused", stored)
}
request, err := http.NewRequest(http.MethodGet, "http://carrier.example/media/"+upstream, nil)
if err != nil {
t.Fatalf("NewRequest for %q: %v", stored, err)
}
if request.URL.RawPath != "" {
t.Errorf("%q produced raw path %q; CarrierNode would match that instead of the name", stored, request.URL.RawPath)
}
if want := "/media/" + urlPath(stored); request.URL.Path != want {
t.Errorf("%q decodes to %q, want %q", stored, request.URL.Path, want)
}
}
}
func TestUpstreamMediaPathEscapesEachSegment(t *testing.T) {
cases := map[string]string{
"clips/clip.mp4": "clips/clip.mp4",
"my clip.mp4": "my%20clip.mp4",
"100%.mp4": "100%25.mp4",
"media/a b/c.mp4": "a%20b/c.mp4",
"/leading.mp4": "leading.mp4",
"Hello, World.mp4": "Hello,%20World.mp4",
"a;b.mp4": "a;b.mp4",
"x?y.mp4": "x%3Fy.mp4",
"a#b.mp4": "a%23b.mp4",
}
for stored, want := range cases {
got, ok := upstreamMediaPath(stored)
if !ok || got != want {
t.Errorf("upstreamMediaPath(%q) = %q, %v; want %q", stored, got, ok, want)
}
}
}
func TestCanonicalMediaIDAcceptsOnlyCanonicalDecimals(t *testing.T) {
for _, value := range []string{"", "007", "+1", "-1", "4a", " 4", "4 ", "99999999999999999999"} {
if id, ok := canonicalMediaID(value); ok {
t.Errorf("canonicalMediaID(%q) = %d, want refused", value, id)
}
}
if id, ok := canonicalMediaID("42"); !ok || id != 42 {
t.Errorf("canonicalMediaID(42) = %d, %v; want 42, true", id, ok)
}
if mediaIDArg("abc") != nil {
t.Error("mediaIDArg(non-numeric) is not NULL")
}
if mediaIDArg("42") != int64(42) {
t.Error("mediaIDArg(42) is not 42")
}
}
@@ -1,4 +1,4 @@
package mediacore package media
import ( import (
"context" "context"
@@ -25,7 +25,7 @@ import (
// CarrierNode. They create the media tables and a few rows, so they are skipped unless // CarrierNode. They create the media tables and a few rows, so they are skipped unless
// SHARED_TEST_DATABASE_URL points at a scratch database, for example: // SHARED_TEST_DATABASE_URL points at a scratch database, for example:
// //
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./mediacore/ // SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./media/
const ( const (
aliceID = 9101 aliceID = 9101
@@ -108,7 +108,6 @@ func newDBHarness(t *testing.T) *dbHarness {
core := New(Config{ core := New(Config{
DB: pool, DB: pool,
Auth: auth, Auth: auth,
Sync: hub,
CarrierNode: carriernodeclient.New("", func(context.Context) string { return carrierServer.URL }), CarrierNode: carriernodeclient.New("", func(context.Context) string { return carrierServer.URL }),
ServiceName: "routes-test", ServiceName: "routes-test",
}) })
@@ -218,7 +217,7 @@ func TestMediaStreamAndThumbnailAgainstPostgres(t *testing.T) {
t.Run("unsafe stored paths and unknown keys are not found, and never reach CarrierNode", func(t *testing.T) { t.Run("unsafe stored paths and unknown keys are not found, and never reach CarrierNode", func(t *testing.T) {
before := len(h.carrier.seen()) before := len(h.carrier.seen())
for _, key := range []string{"rt-escape", "rt-query", "rt-missing", ""} { for _, key := range []string{"rt-escape", "rt-missing", ""} {
if code := h.do(http.MethodGet, "/media/stream?mediaKey="+key, "alice-token", "").Code; code != http.StatusNotFound { if code := h.do(http.MethodGet, "/media/stream?mediaKey="+key, "alice-token", "").Code; code != http.StatusNotFound {
t.Errorf("stream of %q status = %d, want 404", key, code) t.Errorf("stream of %q status = %d, want 404", key, code)
} }
@@ -228,6 +227,18 @@ func TestMediaStreamAndThumbnailAgainstPostgres(t *testing.T) {
} }
}) })
t.Run("question marks in stored paths are escaped as filename characters", func(t *testing.T) {
before := len(h.carrier.seen())
response := h.do(http.MethodGet, "/media/stream?mediaKey=rt-query", "alice-token", "")
if response.Code != http.StatusOK || response.Body.String() != "BYTES" {
t.Fatalf("stream of rt-query = %d %q, want the proxied bytes", response.Code, response.Body.String())
}
got := h.carrier.seen()
if len(got) != before+1 || got[len(got)-1] != "GET /media/a%3Fb.mp4" {
t.Fatalf("CarrierNode requests after streaming rt-query = %v, want one GET of /media/a%%3Fb.mp4", got[before:])
}
})
t.Run("hidden media is visible to moderators only", func(t *testing.T) { t.Run("hidden media is visible to moderators only", func(t *testing.T) {
for _, target := range []string{"/media/stream?mediaKey=rt-hidden", "/media/thumb?mediaKey=rt-hidden"} { for _, target := range []string{"/media/stream?mediaKey=rt-hidden", "/media/thumb?mediaKey=rt-hidden"} {
if code := h.do(http.MethodGet, target, "alice-token", "").Code; code != http.StatusNotFound { if code := h.do(http.MethodGet, target, "alice-token", "").Code; code != http.StatusNotFound {
@@ -255,6 +266,7 @@ func TestMediaStreamAndThumbnailAgainstPostgres(t *testing.T) {
func TestMediaStatsAndViewsAgainstPostgres(t *testing.T) { func TestMediaStatsAndViewsAgainstPostgres(t *testing.T) {
h := newDBHarness(t) h := newDBHarness(t)
h.insertMedia(t, "rt-stats", "video", "rt-stats.mp4", true)
state := func(token string) map[string]any { state := func(token string) map[string]any {
return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, "")) return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, ""))
} }
@@ -348,13 +360,52 @@ func TestTagsAgainstPostgres(t *testing.T) {
t.Fatalf("tags = %v, want Funny at 1 ahead of Quiet at -1", tags) t.Fatalf("tags = %v, want Funny at 1 ahead of Quiet at -1", tags)
} }
suggestions := decode(t, h.do(http.MethodGet, "/tags/suggestions?limit=5", "", ""))["tags"].([]any) // A tag keeps its rows after its media is hidden or leaves the library. Only the library's
if len(suggestions) == 0 { // media is listed for the tag, so a tag's examples never point at a thumbnail that is not found.
t.Fatal("suggestions are empty") h.insertMedia(t, "rt-tags", "video", "tagged/clip.mp4", true)
h.insertMedia(t, "rt-tags-hidden", "video", "tagged/hidden.mp4", false)
h.insertMedia(t, "rt-tags-new", "video", "tagged/new.mp4", true)
if _, err := h.pool.Exec(context.Background(), `UPDATE media SET content_scanner_processed = TRUE WHERE media_key IN ('rt-tags', 'rt-tags-hidden')`); err != nil {
t.Fatalf("mark media processed: %v", err)
} }
h.do(http.MethodPost, "/media/rt-tags-hidden/tags", "alice-token", `{"tag":"Funny"}`)
h.do(http.MethodPost, "/media/rt-tags-new/tags", "alice-token", `{"tag":"Funny"}`)
listed := decode(t, h.do(http.MethodGet, "/tags/funny/media?limit=10", "", ""))["items"].([]any) listed := decode(t, h.do(http.MethodGet, "/tags/funny/media?limit=10", "", ""))["items"].([]any)
if len(listed) != 1 || listed[0].(map[string]any)["mediaKey"] != "rt-tags" { if len(listed) != 1 || listed[0].(map[string]any)["mediaKey"] != "rt-tags" {
t.Fatalf("media for the tag = %v, want rt-tags (the tag matches ignoring case)", listed) t.Fatalf("media for the tag = %v, want only rt-tags (the hidden and unprocessed items are not listed)", listed)
}
// Suggestions count the library's media, so Funny and Quiet count rt-tags only: the hidden and
// unprocessed items above are not in the library.
suggestions := decode(t, h.do(http.MethodGet, "/tags/suggestions?limit=5", "", ""))["tags"].([]any)
if len(suggestions) != 2 || suggestions[0].(map[string]any)["tag"] != "Funny" || suggestions[0].(map[string]any)["count"] != float64(1) || suggestions[1].(map[string]any)["tag"] != "Quiet" || suggestions[1].(map[string]any)["count"] != float64(1) {
t.Fatalf("suggestions = %v, want Funny and Quiet at 1 each", suggestions)
}
// Without a limit, suggestions list every tag, not only the first 1000. The bulk tags sit on a
// library item, because a tag on media that is not in the library is not suggested.
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media (media_key, media_type, file_path, active, content_scanner_processed) VALUES ('rt-many', 'video', 'many/clip.mp4', TRUE, TRUE)`); err != nil {
t.Fatalf("insert many media: %v", err)
}
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media_tags (media_key, tag, user_id) SELECT 'rt-many', 'bulk ' || g, NULL FROM generate_series(1, 1001) AS g`); err != nil {
t.Fatalf("insert many tags: %v", err)
}
every := decode(t, h.do(http.MethodGet, "/tags/suggestions", "", ""))["tags"].([]any)
if len(every) <= 1000 {
t.Fatalf("suggestions without a limit = %d tags, want every tag (more than 1000)", len(every))
}
// The tag's media is paged, and the pagination reports the whole count so the page can reach every page.
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media (media_key, media_type, file_path, active, content_scanner_processed) SELECT 'rt-page-' || g, 'video', 'paged/' || g || '.mp4', TRUE, TRUE FROM generate_series(1, 30) AS g`); err != nil {
t.Fatalf("insert paged media: %v", err)
}
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media_tags (media_key, tag, user_id) SELECT 'rt-page-' || g, 'Paged', NULL FROM generate_series(1, 30) AS g`); err != nil {
t.Fatalf("tag paged media: %v", err)
}
pageTwo := decode(t, h.do(http.MethodGet, "/tags/paged/media?page=2&limit=24", "", ""))
pagination, _ := pageTwo["pagination"].(map[string]any)
if items := pageTwo["items"].([]any); len(items) != 6 || pagination["total"] != float64(30) || pagination["totalPages"] != float64(2) || pagination["page"] != float64(2) {
t.Fatalf("page 2 at 24 per page = %d items, pagination %v; want 6 items on page 2 of 2, total 30", len(items), pagination)
} }
} }
+41
View File
@@ -0,0 +1,41 @@
package media
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-chi/chi/v5"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
)
// TestMediaRoutesRefuseAnonymousRequests walks the media route table: every route mounted behind
// Require answers 401 to a caller with no session, before any handler runs. The Service has no
// database or CarrierNode client, so a request that got past the gate would panic.
func TestMediaRoutesRefuseAnonymousRequests(t *testing.T) {
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
for _, route := range []struct{ method, target string }{
{http.MethodPost, "/media/like"},
{http.MethodPost, "/media/save"},
{http.MethodGet, "/media/liked"},
{http.MethodPost, "/media/7/tags"},
{http.MethodPost, "/media/7/tags/funny/vote"},
{http.MethodGet, "/playlists"},
{http.MethodPost, "/playlists"},
{http.MethodDelete, "/playlists/3"},
{http.MethodPost, "/playlists/3/items"},
{http.MethodDelete, "/playlists/3/items"},
{http.MethodPatch, "/playlists/3/items/reorder"},
} {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(route.method, route.target, strings.NewReader(`{}`)))
if response.Code != http.StatusUnauthorized {
t.Errorf("%s %s status = %d, want 401", route.method, route.target, response.Code)
}
}
}
+74
View File
@@ -0,0 +1,74 @@
// Package settings reads and writes the shared `settings` key/value table, which holds small
// per-deployment values such as the login-required toggle.
package settings
import (
"context"
"errors"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// Value reads one key from the shared `settings` table. An absent or empty
// setting returns fallback; database errors are returned to the caller.
func Value(ctx context.Context, db *pgxpool.Pool, key, fallback string) (string, error) {
var value string
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
}
// ValueOrFallback preserves the old fallback-on-error behavior for callers
// whose API cannot return a read error. New request paths should use Value.
func ValueOrFallback(ctx context.Context, db *pgxpool.Pool, key, fallback string) string {
value, err := Value(ctx, db, key, fallback)
if err != nil {
return fallback
}
return value
}
// Bool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true,
// anything else is fallback).
func Bool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool {
value := strings.ToLower(strings.TrimSpace(ValueOrFallback(ctx, db, key, "")))
if value == "" {
return fallback
}
return value == "1" || value == "true" || value == "yes" || value == "on"
}
// Save upserts one key in the shared `settings` table.
func Save(ctx context.Context, db *pgxpool.Pool, key, value string) error {
_, err := db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, value)
return err
}
// Migrate creates the settings table and its default login-required row. It is idempotent.
func Migrate(ctx context.Context, db *pgxpool.Pool) error {
for _, statement := range migrationStatements {
if _, err := db.Exec(ctx, statement); err != nil {
return err
}
}
return nil
}
var migrationStatements = []string{
`CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`INSERT INTO settings (key, value) VALUES ('auth_required', 'true') ON CONFLICT (key) DO NOTHING`,
}
+24
View File
@@ -0,0 +1,24 @@
package settings
import (
"context"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
)
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 := Value(context.Background(), db, "example", "fallback")
if err == nil || value != "" {
t.Fatalf("Value() = %q, %v; want empty value and database error", value, err)
}
if got := ValueOrFallback(context.Background(), db, "example", "fallback"); got != "fallback" {
t.Fatalf("ValueOrFallback() = %q, want fallback on error", got)
}
}
+87
View File
@@ -0,0 +1,87 @@
package syncsocket
import (
"encoding/json"
"io"
"net/http"
"time"
"github.com/go-chi/chi/v5"
)
// MountRoutes wires the cross-device sync HTTP routes onto r. GET /sync returns a session's
// current state and PUT /sync replaces it and broadcasts the change to that session's websocket
// peers. optional and required are the caller's auth middleware (an auth.Service's Optional and
// Require): GET runs with optional and PUT with required.
func MountRoutes(r chi.Router, hub *Hub, optional, required func(http.Handler) http.Handler) {
r.With(optional).Get("/sync", func(w http.ResponseWriter, r *http.Request) {
getState(hub, w, r)
})
r.With(required).Put("/sync", func(w http.ResponseWriter, r *http.Request) {
putState(hub, w, r)
})
}
func getState(hub *Hub, w http.ResponseWriter, r *http.Request) {
sessionID := boundedSyncString(firstNonEmpty(r.URL.Query().Get("sessionId"), "default"))
writeJSON(w, http.StatusOK, hub.HTTPState(sessionID))
}
func putState(hub *Hub, w http.ResponseWriter, r *http.Request) {
var input map[string]any
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
clientID := boundedSyncString(syncString(input, "clientId"))
if clientID == "" {
writeError(w, http.StatusBadRequest, "clientId is required")
return
}
mediaID, ok := syncScalar(input["mediaId"])
if !ok {
writeError(w, http.StatusBadRequest, "mediaId must be a string, a number or null")
return
}
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
state := map[string]any{
"sessionId": sessionID,
"mediaId": mediaID,
"timeMs": syncInt(input, "timeMs", 0),
"paused": syncBool(input, "paused"),
"fps": syncFPS(input),
"frame": syncInt(input, "frame", 0),
"fromClientId": clientID,
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
}
if value, ok := input["playAt"]; ok {
playAt, valid := syncScalar(value)
if !valid {
writeError(w, http.StatusBadRequest, "playAt must be a string, a number or null")
return
}
state["playAt"] = playAt
}
hub.SetHTTPState(sessionID, state)
// Broadcast queues immutable messages without waiting for network writes, so a slow
// websocket peer does not hold this response or create one goroutine per request.
hub.Broadcast(sessionID)
writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state})
}
func decodeRequestJSON(r *http.Request, target any) error {
defer r.Body.Close()
decoder := json.NewDecoder(io.LimitReader(r.Body, 512*1024))
decoder.DisallowUnknownFields()
return decoder.Decode(target)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message, "message": message})
}
+50
View File
@@ -0,0 +1,50 @@
package syncsocket
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-chi/chi/v5"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
)
// TestSyncWriteRequiresLogin checks that an anonymous PUT /sync is refused before it can change
// shared playback state.
func TestSyncWriteRequiresLogin(t *testing.T) {
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
router := chi.NewRouter()
MountRoutes(router, NewHub(), auth.Optional, auth.Require)
request := httptest.NewRequest(http.MethodPut, "/sync", strings.NewReader(`{"clientId":"c1","mediaId":"m1"}`))
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusUnauthorized {
t.Errorf("PUT /sync status = %d, want %d", response.Code, http.StatusUnauthorized)
}
}
// TestSyncScalarKeepsOnlyScalars checks that sync values are limited to null, numbers and
// bounded strings, so objects, arrays and booleans are never stored as session state.
func TestSyncScalarKeepsOnlyScalars(t *testing.T) {
if value, ok := syncScalar(nil); !ok || value != nil {
t.Errorf("syncScalar(nil) = %v, %v; want nil, true", value, ok)
}
if value, ok := syncScalar(float64(7)); !ok || value != float64(7) {
t.Errorf("syncScalar(7) = %v, %v; want 7, true", value, ok)
}
if value, ok := syncScalar(" media-1 "); !ok || value != "media-1" {
t.Errorf("syncScalar(string) = %v, %v; want media-1, true", value, ok)
}
long, ok := syncScalar(strings.Repeat("x", 500))
if text, isText := long.(string); !ok || !isText || len(text) != 128 {
t.Errorf("syncScalar(long string) = %v, %v; want a 128-byte string, true", long, ok)
}
for _, refused := range []any{map[string]any{"a": 1}, []any{1}, true} {
if _, ok := syncScalar(refused); ok {
t.Errorf("syncScalar(%#v) accepted a non-scalar value", refused)
}
}
}
+18
View File
@@ -0,0 +1,18 @@
package syncsocket
import (
"context"
)
type loginRequiredStore struct{}
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
// loginOffStore is loginRequiredStore with login switched off for the whole application.
type loginOffStore struct{ loginRequiredStore }
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
@@ -1,4 +1,4 @@
package mediacore package syncsocket
import ( import (
"context" "context"
@@ -13,49 +13,14 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
) )
// TestSessionRoutesRefuseAnonymousRequests walks the route table: every route mounted behind // syncRouter mounts the sync routes on hub. Auth is disabled, so every caller is the placeholder
// Require answers 401 to a caller with no session, before any handler runs. The Core has no // administrator.
// database, sync hub or CarrierNode client, so a request that got past the gate would panic. func syncRouter(hub *Hub) chi.Router {
func TestSessionRoutesRefuseAnonymousRequests(t *testing.T) {
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
for _, route := range []struct{ method, target string }{
{http.MethodGet, "/security/totp/status"},
{http.MethodGet, "/security/totp/initiate"},
{http.MethodPost, "/security/totp/verify"},
{http.MethodPost, "/security/totp/disable"},
{http.MethodPut, "/sync"},
{http.MethodPost, "/media/like"},
{http.MethodPost, "/media/save"},
{http.MethodGet, "/media/liked"},
{http.MethodPost, "/media/7/tags"},
{http.MethodPost, "/media/7/tags/funny/vote"},
{http.MethodGet, "/playlists"},
{http.MethodPost, "/playlists"},
{http.MethodDelete, "/playlists/3"},
{http.MethodPost, "/playlists/3/items"},
{http.MethodDelete, "/playlists/3/items"},
{http.MethodPatch, "/playlists/3/items/reorder"},
} {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(route.method, route.target, strings.NewReader(`{}`)))
if response.Code != http.StatusUnauthorized {
t.Errorf("%s %s status = %d, want 401", route.method, route.target, response.Code)
}
}
}
// syncRouter mounts the sync routes on a Core with no database. Auth is disabled, so every caller
// is the placeholder administrator.
func syncRouter(hub *syncsocket.Hub) chi.Router {
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject", sharedauth.Disabled()) auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject", sharedauth.Disabled())
router := chi.NewRouter() router := chi.NewRouter()
New(Config{Auth: auth, Sync: hub}).Mount(router) MountRoutes(router, hub, auth.Optional, auth.Require)
return router return router
} }
@@ -66,7 +31,7 @@ func putSync(router http.Handler, target, body string) *httptest.ResponseRecorde
} }
func TestPutSyncRejectsBadInput(t *testing.T) { func TestPutSyncRejectsBadInput(t *testing.T) {
router := syncRouter(syncsocket.NewHub()) router := syncRouter(NewHub())
for name, body := range map[string]string{ for name, body := range map[string]string{
"not JSON": `nope`, "not JSON": `nope`,
"missing clientId": `{"mediaId":"m1"}`, "missing clientId": `{"mediaId":"m1"}`,
@@ -84,7 +49,7 @@ func TestPutSyncRejectsBadInput(t *testing.T) {
} }
func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) { func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) {
hub := syncsocket.NewHub() hub := NewHub()
router := syncRouter(hub) router := syncRouter(hub)
response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"c1","mediaId":42,"timeMs":-5,"paused":true,"fps":100000,"frame":9,"playAt":"2026-10-19T10:00:00Z"}`) response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"c1","mediaId":42,"timeMs":-5,"paused":true,"fps":100000,"frame":9,"playAt":"2026-10-19T10:00:00Z"}`)
@@ -122,7 +87,7 @@ func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) {
} }
func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) { func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) {
router := syncRouter(syncsocket.NewHub()) router := syncRouter(NewHub())
long := strings.Repeat("s", 300) long := strings.Repeat("s", 300)
response := putSync(router, "/sync", `{"clientId":"`+strings.Repeat("c", 300)+`","mediaId":null,"sessionId":"`+long+`"}`) response := putSync(router, "/sync", `{"clientId":"`+strings.Repeat("c", 300)+`","mediaId":null,"sessionId":"`+long+`"}`)
if response.Code != http.StatusOK { if response.Code != http.StatusOK {
@@ -143,7 +108,7 @@ func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) {
// TestPutSyncBroadcastsToThePeersOfThatSession checks the HTTP write reaches websocket peers in // TestPutSyncBroadcastsToThePeersOfThatSession checks the HTTP write reaches websocket peers in
// the session, and only those. // the session, and only those.
func TestPutSyncBroadcastsToThePeersOfThatSession(t *testing.T) { func TestPutSyncBroadcastsToThePeersOfThatSession(t *testing.T) {
hub := syncsocket.NewHub() hub := NewHub()
router := syncRouter(hub) router := syncRouter(hub)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "") hub.ServeWebSocket(w, r, "")
@@ -203,25 +168,3 @@ func readFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want str
} }
} }
} }
func TestProfileReportsTheSessionUser(t *testing.T) {
guard := newRoleAuthGuard(t)
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
anonymous := httptest.NewRecorder()
router.ServeHTTP(anonymous, httptest.NewRequest(http.MethodGet, "/profile", nil))
if anonymous.Code != http.StatusOK || strings.TrimSpace(anonymous.Body.String()) != `{"user":null}` {
t.Fatalf("anonymous profile = %d %s, want a null user", anonymous.Code, anonymous.Body.String())
}
request := httptest.NewRequest(http.MethodGet, "/profile", nil)
request.AddCookie(&http.Cookie{Name: "auth_session", Value: "viewer-token"})
known := httptest.NewRecorder()
router.ServeHTTP(known, request)
var body struct{ User map[string]any }
if err := json.Unmarshal(known.Body.Bytes(), &body); err != nil || body.User["username"] != "tester" || body.User["role"] != "user" {
t.Fatalf("profile = %s, %v", known.Body.String(), err)
}
}
+15
View File
@@ -0,0 +1,15 @@
package syncsocket
// syncScalar keeps a client-supplied sync value to what sync state holds: null, a number or a
// bounded string. Objects, arrays and booleans are refused so arbitrary JSON is never stored as
// shared session state.
func syncScalar(value any) (any, bool) {
switch typed := value.(type) {
case nil, float64:
return typed, true
case string:
return boundedSyncString(typed), true
default:
return nil, false
}
}
+7 -9
View File
@@ -1,9 +1,7 @@
// Package syncsocket is the media-backend family's cross-device playback-sync // Package syncsocket is a cross-device playback-sync websocket hub: multiple clients viewing the
// websocket hub: multiple clients viewing the same media session (identified // same media session (identified by a caller-chosen sessionId) see each other's
// by a caller-chosen sessionId) see each other's play/pause/seek/remote-control // play/pause/seek/remote-control state live. It is shared so every project that offers live sync
// state live. Promoted unchanged from each service's own internal sync.go into // uses one copy instead of duplicating it.
// this shared library so the 6 media-family backends that mount it (every one
// except KioskDisplay) use one copy instead of duplicating it.
// //
// A service wires this up as: // A service wires this up as:
// //
@@ -12,7 +10,7 @@
// hub.ServeWebSocket(w, r, cfg.AllowedOrigin) // hub.ServeWebSocket(w, r, cfg.AllowedOrigin)
// }) // })
// //
// and mediacore's shared GET/PUT /sync HTTP routes call hub.HTTPState/ // and MountRoutes' GET/PUT /sync HTTP routes call hub.HTTPState/
// SetHTTPState/Broadcast to read and mutate the same session state the // SetHTTPState/Broadcast to read and mutate the same session state the
// websocket peers see. // websocket peers see.
package syncsocket package syncsocket
@@ -204,7 +202,7 @@ func (h *Hub) stateLocked(sessionID string) map[string]any {
} }
// HTTPState returns the current playback state for a session, as seen by the // HTTPState returns the current playback state for a session, as seen by the
// GET /sync HTTP endpoint (mounted by mediacore). // GET /sync HTTP endpoint (mounted by MountRoutes).
func (h *Hub) HTTPState(sessionID string) map[string]any { func (h *Hub) HTTPState(sessionID string) map[string]any {
h.mu.Lock() h.mu.Lock()
defer h.mu.Unlock() defer h.mu.Unlock()
@@ -212,7 +210,7 @@ func (h *Hub) HTTPState(sessionID string) map[string]any {
} }
// SetHTTPState overwrites a session's playback state, as driven by the // SetHTTPState overwrites a session's playback state, as driven by the
// PUT /sync HTTP endpoint (mounted by mediacore) - callers should follow this // PUT /sync HTTP endpoint (mounted by MountRoutes) - callers should follow this
// with Broadcast to notify connected websocket peers. // with Broadcast to notify connected websocket peers.
func (h *Hub) SetHTTPState(sessionID string, state map[string]any) { func (h *Hub) SetHTTPState(sessionID string, state map[string]any) {
h.mu.Lock() h.mu.Lock()
+116 -13
View File
@@ -1,31 +1,60 @@
{ {
"description": "Fixtures that the Go, Node and Python auth helpers must agree on. Each runtime's test suite loads this file and checks its own column; a value that differs between runtimes is a known divergence (Q-008) and is written down here rather than hidden. Change a value only together with the code that changes the behaviour.", "description": "Fixtures that the Go, Node and Python auth helpers must agree on. Each runtime's test suite loads this file and checks its own column. Change a value only together with the code that changes the behavior.",
"password": { "password": {
"plaintext": "correct horse battery staple", "plaintext": "correct horse battery staple",
"wrongPassword": "not the right password", "wrongPassword": "not the right password",
"hashes": [ "hashes": [
{ {
"name": "Node, current pbkdf2-sha256 scheme", "name": "Legacy PBKDF2 scheme with recorded iteration count",
"hash": "pbkdf2-sha256$600000$76add00c36dafceac62928d01f706c20$f50eec2591755f169bd151369e41a4e6918c6a2816d19516cc38763bfa63c0ca", "hash": "pbkdf2-sha256$600000$76add00c36dafceac62928d01f706c20$f50eec2591755f169bd151369e41a4e6918c6a2816d19516cc38763bfa63c0ca",
"verifies": { "verifies": {
"go": false, "go": true,
"node": true, "node": true,
"python": false "python": true
}, },
"needsUpgrade": { "needsUpgrade": {
"node": false "go": true,
"node": true,
"python": true
} }
}, },
{ {
"name": "Node, legacy salt:hex at 100000 iterations", "name": "Legacy salt:hex PBKDF2 at 100000 iterations",
"hash": "0123456789abcdef0123456789abcdef:69a26fc4b1624cd29ecc2b2444aa876251575c65deb4af9effbd9eadbd4195c6", "hash": "0123456789abcdef0123456789abcdef:69a26fc4b1624cd29ecc2b2444aa876251575c65deb4af9effbd9eadbd4195c6",
"verifies": { "verifies": {
"go": false, "go": true,
"node": true, "node": true,
"python": false "python": true
}, },
"needsUpgrade": { "needsUpgrade": {
"node": true "go": true,
"node": true,
"python": true
}
},
{
"name": "Legacy PBKDF2 password over bcrypt's input limit",
"hash": "0123456789abcdef0123456789abcdef:a8a80395df31b48bfb1dc4fabb6457dc61a50aae0c8d469f618303f0cea367b2",
"password": "legacy:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"wrongPassword": "legacy:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy",
"verifies": {
"go": true,
"node": true,
"python": true
},
"needsUpgrade": {
"go": true,
"node": true,
"python": true
}
},
{
"name": "Current bcrypt scheme with cost 12",
"hash": "bcrypt$$2b$12$NExB1DALH97MOTr6ZSUjYOb4gc.2g/uWCqbUX1d/c450damk1A9r2",
"verifies": {
"go": true,
"node": true,
"python": true
} }
}, },
{ {
@@ -33,11 +62,12 @@
"hash": "bcrypt$$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2", "hash": "bcrypt$$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
"verifies": { "verifies": {
"go": true, "go": true,
"node": false, "node": true,
"python": true "python": true
}, },
"needsUpgrade": { "needsUpgrade": {
"go": true, "go": true,
"node": true,
"python": true "python": true
} }
}, },
@@ -46,11 +76,12 @@
"hash": "$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2", "hash": "$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
"verifies": { "verifies": {
"go": true, "go": true,
"node": false, "node": true,
"python": true "python": true
}, },
"needsUpgrade": { "needsUpgrade": {
"go": true, "go": true,
"node": true,
"python": true "python": true
} }
}, },
@@ -86,10 +117,10 @@
"bytes": 73, "bytes": 73,
"accepted": { "accepted": {
"go": false, "go": false,
"node": true, "node": false,
"python": false "python": false
}, },
"note": "bcrypt reads only the first 72 bytes, so Go and Python refuse a longer password; PBKDF2 has no such limit." "note": "New passwords over 72 bytes are refused. Existing longer PBKDF2 passwords still verify and migrate to the marked bcrypt-sha256 scheme without truncation."
} }
}, },
"totp": { "totp": {
@@ -129,12 +160,14 @@
"name": "the next step still accepts the previous code", "name": "the next step still accepts the previous code",
"unix": 1111111139, "unix": 1111111139,
"code": "081804", "code": "081804",
"matchedStep": 37037036,
"valid": true "valid": true
}, },
{ {
"name": "the previous step accepts the next code", "name": "the previous step accepts the next code",
"unix": 1111111079, "unix": 1111111079,
"code": "081804", "code": "081804",
"matchedStep": 37037036,
"valid": true "valid": true
}, },
{ {
@@ -321,5 +354,75 @@
"want": "2001:db8::9" "want": "2001:db8::9"
} }
] ]
},
"internalSecret": {
"note": "The SECRET that gates a service's internal routes (X-Internal-Auth). Length counts characters (code points), not bytes. Every runtime reads minLength and placeholders from here.",
"minLength": 16,
"placeholders": [
"SECRET",
"change-me-to-a-long-random-value"
],
"cases": [
{
"name": "unset secret never matches",
"secret": "",
"provided": "",
"matches": false
},
{
"name": "missing header never matches",
"secret": "0123456789abcdef",
"provided": "",
"matches": false
},
{
"name": "secret one character under the minimum never matches",
"secret": "0123456789abcde",
"provided": "0123456789abcde",
"matches": false
},
{
"name": "secret at the minimum matches itself",
"secret": "0123456789abcdef",
"provided": "0123456789abcdef",
"matches": true
},
{
"name": "a prefix of the secret does not match",
"secret": "0123456789abcdef",
"provided": "0123456789abcde",
"matches": false
},
{
"name": "comparison is exact",
"secret": "0123456789abcdef",
"provided": "0123456789abcdeF",
"matches": false
},
{
"name": "length counts characters, not bytes",
"secret": "éééééééééééééééé",
"provided": "éééééééééééééééé",
"matches": true
},
{
"name": "fifteen multibyte characters are too short",
"secret": "ééééééééééééééé",
"provided": "ééééééééééééééé",
"matches": false
},
{
"name": "the example placeholder never matches",
"secret": "change-me-to-a-long-random-value",
"provided": "change-me-to-a-long-random-value",
"matches": false
},
{
"name": "the bare variable name never matches",
"secret": "SECRET",
"provided": "SECRET",
"matches": false
}
]
} }
} }
+28 -18
View File
@@ -2491,6 +2491,15 @@
"node": "18 || 20 || >=22" "node": "18 || 20 || >=22"
} }
}, },
"node_modules/bcryptjs": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz",
"integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==",
"license": "BSD-3-Clause",
"bin": {
"bcrypt": "bin/bcrypt"
}
},
"node_modules/better-path-resolve": { "node_modules/better-path-resolve": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/better-path-resolve/-/better-path-resolve-1.0.0.tgz", "resolved": "https://registry.npmjs.org/better-path-resolve/-/better-path-resolve-1.0.0.tgz",
@@ -2722,9 +2731,9 @@
} }
}, },
"node_modules/devalue": { "node_modules/devalue": {
"version": "5.9.0", "version": "5.9.4",
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.0.tgz", "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz",
"integrity": "sha512-RWrqdArjvPbsATEhOPUo6Wndc/iWnkWKlhIrdlF3zMMYo/c3CVtoaVAyLtWxz5h8nSlkHzxnzV2uLydPXmtF+A==", "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/dir-glob": { "node_modules/dir-glob": {
@@ -3555,9 +3564,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/js-yaml": { "node_modules/js-yaml": {
"version": "4.3.1", "version": "4.3.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
"integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
@@ -3825,9 +3834,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/nanoid": { "node_modules/nanoid": {
"version": "3.3.17", "version": "3.3.20",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.17.tgz", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
"integrity": "sha512-xQLf0A3HOMlgHq0n247/LRuAOYmB7dXJ/DvAxGvsSBij45XtBSmQycu+F8ODbHwns/XyFZagyL1+J0Offw1E0g==", "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
@@ -4456,9 +4465,9 @@
} }
}, },
"node_modules/read-yaml-file/node_modules/js-yaml": { "node_modules/read-yaml-file/node_modules/js-yaml": {
"version": "3.15.1", "version": "3.15.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.1.tgz", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz",
"integrity": "sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==", "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -4685,9 +4694,9 @@
} }
}, },
"node_modules/source-map-js": { "node_modules/source-map-js": {
"version": "1.2.1", "version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
"dev": true, "dev": true,
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"engines": { "engines": {
@@ -5138,9 +5147,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/vite": { "node_modules/vite": {
"version": "7.3.6", "version": "7.3.7",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.7.tgz",
"integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==", "integrity": "sha512-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true, "peer": true,
@@ -5482,6 +5491,7 @@
"version": "0.1.1", "version": "0.1.1",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"bcryptjs": "^3.0.3",
"pg": "^8.17.2" "pg": "^8.17.2"
}, },
"engines": { "engines": {
+1
View File
@@ -6,6 +6,7 @@ Shared account-management, TOTP, admin reset-code, and AuthGuard client primitiv
- `Totp` - RFC 6238 TOTP secret generation, provisioning URIs, and verification; - `Totp` - RFC 6238 TOTP secret generation, provisioning URIs, and verification;
- `ResetManager` - a short-lived, one-time admin reset-code primitive printed to the server console; - `ResetManager` - a short-lived, one-time admin reset-code primitive printed to the server console;
- `AuthClient` - a client for a centralized AuthGuard instance's `GET /api/session/validate`, for services that want one shared identity instead of their own local user table. Mirrors `shared/backend/authclient` (Go) and `shared/packages/node-backend/src/authclient.js` (Node) - keep the three in sync if any of them changes shape. Additive: no project is wired up to use it just because this class exists. `setBaseUrl(url)` retargets an existing client's AuthGuard URL in place - the natural target for a ProjectConfigurator core-services push handler - so a client can be constructed with `new AuthClient("")` (usable right away, failing closed with `IllegalStateException` until a real URL arrives) rather than needing one known up front. Unlike the Go/Python/Node siblings, this package has no `coreconfig` module of its own: MegaBasterd, its only consumer, wires the `PUT /api/core-services/internal` route directly against a plain field holding the current `AuthGuardUrl`. - `AuthClient` - a client for a centralized AuthGuard instance's `GET /api/session/validate`, for services that want one shared identity instead of their own local user table. Mirrors `shared/backend/authclient` (Go) and `shared/packages/node-backend/src/authclient.js` (Node) - keep the three in sync if any of them changes shape. Additive: no project is wired up to use it just because this class exists. `setBaseUrl(url)` retargets an existing client's AuthGuard URL in place - the natural target for a ProjectConfigurator core-services push handler - so a client can be constructed with `new AuthClient("")` (usable right away, failing closed with `IllegalStateException` until a real URL arrives) rather than needing one known up front. Unlike the Go/Python/Node siblings, this package has no `coreconfig` module of its own: MegaBasterd, its only consumer, wires the `PUT /api/core-services/internal` route directly against a plain field holding the current `AuthGuardUrl`.
- `LogShipper` (`com.gabriel20xx.shared.logs`) - the client shipper for OmniLogger, the central log sink. It batches entries and POSTs them to `{OMNILOGGER_URL}/api/logs` from a daemon thread. `LogShipper.fromEnv(service)` returns null unless both `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` are set, so shipping stays off by default. Mirrors `shared/backend/logshipper` (Go) - keep the two in sync. Additive: it never prints, so the consumer's own logger remains the console output. JDK only (Java 8, `HttpURLConnection`).
## How this package is actually consumed ## How this package is actually consumed
+1 -1
View File
@@ -29,7 +29,7 @@
<!-- Pinned to match MegaBasterd/pom.xml's jackson-databind version - both <!-- Pinned to match MegaBasterd/pom.xml's jackson-databind version - both
poms compile the exact same AuthClient.java, which now builds/parses poms compile the exact same AuthClient.java, which now builds/parses
JSON via Jackson for its full (non-validate-only) method surface. --> JSON via Jackson for its full (non-validate-only) method surface. -->
<jackson.version>2.18.6</jackson.version> <jackson.version>2.18.11</jackson.version>
</properties> </properties>
<dependencies> <dependencies>
@@ -13,7 +13,6 @@ public final class Totp {
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
private static final int SECRET_BYTES = 20; private static final int SECRET_BYTES = 20;
private static final int PERIOD_SECONDS = 30; private static final int PERIOD_SECONDS = 30;
private static final int WINDOW = 1;
private static final int DIGITS = 6; private static final int DIGITS = 6;
private static final SecureRandom RANDOM = new SecureRandom(); private static final SecureRandom RANDOM = new SecureRandom();
@@ -43,22 +42,28 @@ public final class Totp {
} }
public static boolean verify(String secret, String token, long nowMillis) { public static boolean verify(String secret, String token, long nowMillis) {
return verifyStep(secret, token, nowMillis) >= 0;
}
/** Returns the matching 30-second step, or {@code -1} when no code matches. */
public static long verifyStep(String secret, String token, long nowMillis) {
String normalizedSecret = normalizeSecret(secret); String normalizedSecret = normalizeSecret(secret);
String normalizedToken = token == null ? "" : token.trim(); String normalizedToken = token == null ? "" : token.trim();
if (normalizedSecret.isEmpty() || !normalizedToken.matches("\\d{" + DIGITS + "}")) { if (normalizedSecret.isEmpty() || !normalizedToken.matches("\\d{" + DIGITS + "}")) {
return false; return -1;
} }
byte[] key; byte[] key;
try { try {
key = decodeBase32(normalizedSecret); key = decodeBase32(normalizedSecret);
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return false; return -1;
} }
if (key.length == 0) { if (key.length == 0) {
return false; return -1;
} }
long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L); long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L);
for (long offset = -WINDOW; offset <= WINDOW; offset++) { // Prefer the current step if a six-digit collision occurs in the window.
for (long offset : new long[] {0, -1, 1}) {
if (counter + offset < 0) { if (counter + offset < 0) {
continue; continue;
} }
@@ -80,13 +85,13 @@ public final class Totp {
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000); String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII), if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII),
normalizedToken.getBytes(StandardCharsets.US_ASCII))) { normalizedToken.getBytes(StandardCharsets.US_ASCII))) {
return true; return counter + offset;
} }
} catch (Exception ex) { } catch (Exception ex) {
return false; return -1;
} }
} }
return false; return -1;
} }
private static String normalizeSecret(String value) { private static String normalizeSecret(String value) {
@@ -0,0 +1,752 @@
package com.gabriel20xx.shared.logs;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
/**
* Client-side shipper for OmniLogger, the workspace's central log sink.
*
* <p>This is the Java port of {@code shared/backend/logshipper/shipper.go}. Keep the two in sync: the
* limits, the wire format and the level names all come from the shared OmniLogger log-shipping contract.
* The class batches entries in memory and POSTs them to {@code {OMNILOGGER_URL}/api/logs} from a daemon
* thread. It never writes to the console, so a service keeps its existing logger and mirrors each line
* into {@link #log(Level, String)}. Nothing here throws, blocks the caller on the network, or exits the
* process because OmniLogger is unreachable or misconfigured.
*
* <p>Deliberate differences from the Go reference:
* <ul>
* <li>No local printing, and no Audit/Ctx/Writer surface. Shipping is additive, so the consumer's own
* console output stays as it was.</li>
* <li>A flush sends at most 1000 entries and a body under 2 MiB, split across requests when needed. The
* contract's limits require this. The Go reference sends the whole buffer in one request.</li>
* <li>Targets Java 8: it uses {@link HttpURLConnection} (java.net.http needs Java 11), and the JSON is
* hand-encoded so the module needs no JSON library on the classpath.</li>
* <li>The 5-second timeout applies to the connect and to the read separately. Go applies one total
* deadline per request.</li>
* </ul>
*/
public final class LogShipper implements AutoCloseable {
/** Environment variable holding OmniLogger's base URL, for example {@code http://omnilogger:8080}. */
public static final String ENV_URL = "OMNILOGGER_URL";
/** Environment variable holding this service's OmniLogger ingest bearer token. */
public static final String ENV_TOKEN = "OMNILOGGER_INGEST_TOKEN";
static final int MAX_MESSAGE_BYTES = 8 * 1024;
static final int MAX_CONTEXT_BYTES = 16 * 1024;
static final int MAX_BATCH_ENTRIES = 1000;
/** A request body must stay under 2 MiB, so the limit is one byte below that. */
static final int MAX_BODY_BYTES = 2 * 1024 * 1024 - 1;
static final String TRUNCATED_MARKER = " [truncated]";
static final String DROPPED_CONTEXT = "{\"context_dropped\":true}";
private static final long DEFAULT_FLUSH_INTERVAL_MILLIS = 2_000L;
private static final int DEFAULT_MAX_BATCH_SIZE = 100;
private static final int DEFAULT_BUFFER_CAPACITY = 2_000;
private static final int HTTP_TIMEOUT_MILLIS = 5_000;
private static final int HTTP_TOO_MANY_REQUESTS = 429;
private static final long WARN_INTERVAL_MILLIS = 60_000L;
private static final int MAX_CONTEXT_DEPTH = 32;
private static final int MAX_DRAINED_RESPONSE_BYTES = 64 * 1024;
private static final DateTimeFormatter TIMESTAMP =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT).withZone(ZoneOffset.UTC);
private static final DateTimeFormatter WARN_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT);
private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
/** Severity scale. Names and aliases follow the shared LOG vocabulary; the wire names are OmniLogger's. */
public enum Level {
DEBUG(10, "debug"),
INFO(20, "info"),
WARN(30, "warn"),
ERROR(40, "error"),
CRITICAL(50, "critical"),
/** Threshold only: suppresses everything. An entry is never logged at this level. */
SILENT(100, null);
private final int severity;
private final String wireName;
Level(int severity, String wireName) {
this.severity = severity;
this.wireName = wireName;
}
/** The lowercase level name OmniLogger's ingest API expects, or null for {@link #SILENT}. */
public String wireName() {
return wireName;
}
/**
* Parses a threshold such as a LOG env value. Matching is trimmed and case-insensitive. Unknown or
* empty input means {@link #INFO}.
*/
public static Level parse(String value) {
String normalized = value == null ? "" : value.trim().toLowerCase(Locale.ROOT);
switch (normalized) {
case "debug":
return DEBUG;
case "warn":
case "warning":
return WARN;
case "error":
return ERROR;
case "critical":
return CRITICAL;
case "silent":
case "none":
case "off":
return SILENT;
default:
return INFO;
}
}
/**
* Maps a java.util.logging level: SEVERE becomes error, WARNING becomes warn, INFO becomes info, and
* anything finer becomes debug. JUL has no critical level, so nothing maps to critical.
*/
public static Level fromJavaUtilLogging(java.util.logging.Level level) {
if (level == null) {
return INFO;
}
int value = level.intValue();
if (value >= java.util.logging.Level.SEVERE.intValue()) {
return ERROR;
}
if (value >= java.util.logging.Level.WARNING.intValue()) {
return WARN;
}
if (value >= java.util.logging.Level.INFO.intValue()) {
return INFO;
}
return DEBUG;
}
}
/**
* Builds a shipper from {@code OMNILOGGER_URL} and {@code OMNILOGGER_INGEST_TOKEN}, with threshold INFO.
*
* @return the shipper, or null when either variable is unset or blank. A null result means shipping is
* disabled, and the service must behave exactly as it did without it.
*/
public static LogShipper fromEnv(String service) {
return fromEnv(service, Level.INFO);
}
/** Like {@link #fromEnv(String)}, with an explicit threshold. */
public static LogShipper fromEnv(String service, Level threshold) {
return fromEnv(service, threshold, name -> System.getenv(name));
}
/**
* Like {@link #fromEnv(String, Level)}, but reads the variables through {@code environment}. Pass a
* lookup such as {@code name -> map.get(name)} to make the disabled path testable.
*/
public static LogShipper fromEnv(String service, Level threshold, Function<String, String> environment) {
String url = trimOrEmpty(environment.apply(ENV_URL));
String token = trimOrEmpty(environment.apply(ENV_TOKEN));
if (url.isEmpty() || token.isEmpty()) {
return null;
}
return new LogShipper(url, token, service, threshold);
}
/** Creates a shipper that sends entries at INFO and above, flushing every 2 seconds. */
public LogShipper(String baseUrl, String ingestToken, String service) {
this(baseUrl, ingestToken, service, Level.INFO);
}
/** Creates a shipper with the given threshold. It starts its background flush thread immediately. */
public LogShipper(String baseUrl, String ingestToken, String service, Level threshold) {
this(baseUrl, ingestToken, service, threshold, DEFAULT_FLUSH_INTERVAL_MILLIS,
DEFAULT_MAX_BATCH_SIZE, DEFAULT_BUFFER_CAPACITY);
}
LogShipper(String baseUrl, String ingestToken, String service, Level threshold,
long flushIntervalMillis, int maxBatchSize, int bufferCapacity) {
this.credentials = credentialsFor(baseUrl, ingestToken);
this.service = service == null ? "" : service;
this.threshold = threshold == null ? Level.INFO : threshold;
this.maxBatchSize = maxBatchSize > 0 ? maxBatchSize : DEFAULT_MAX_BATCH_SIZE;
this.bufferCapacity = bufferCapacity > 0 ? bufferCapacity : DEFAULT_BUFFER_CAPACITY;
this.executor = Executors.newSingleThreadScheduledExecutor(daemonThreads("logshipper-" + this.service));
long interval = flushIntervalMillis > 0 ? flushIntervalMillis : DEFAULT_FLUSH_INTERVAL_MILLIS;
this.executor.scheduleWithFixedDelay(this::runScheduledFlush, interval, interval, TimeUnit.MILLISECONDS);
}
/** The endpoint and bearer token in use, or null while shipping is disabled. See {@link #setCredentials}. */
private volatile Credentials credentials;
private final Object credentialsLock = new Object();
private final String service;
private final Level threshold;
private final int maxBatchSize;
private final int bufferCapacity;
/** Encoded entries waiting to be sent, oldest first. Guarded by bufferLock, which is never held across I/O. */
private final ArrayDeque<byte[]> buffer = new ArrayDeque<>();
private final Object bufferLock = new Object();
private final ScheduledExecutorService executor;
private final AtomicBoolean flushQueued = new AtomicBoolean(false);
private final AtomicBoolean closed = new AtomicBoolean(false);
private final Object warnLock = new Object();
private boolean warned;
private long lastWarnAtMillis;
/** Logs {@code message} at {@code level}. Never blocks on the network. */
public void log(Level level, String message) {
log(level, message, null);
}
/**
* Logs {@code message} with an optional structured {@code context}. The context must be a map of
* strings to plain values (strings, numbers, booleans, null, maps, iterables and arrays). Other values
* are sent as their {@code toString()}. The context is not scrubbed.
*/
public void log(Level level, String message, Map<String, ?> context) {
if (level == null || level == Level.SILENT || level.severity < threshold.severity || closed.get()
|| credentials == null) {
return;
}
try {
String clampedMessage = clampMessage(String.valueOf(message));
String entry = encodeEntry(service, level.wireName(), clampedMessage, clampContext(context),
TIMESTAMP.format(Instant.now()));
byte[] bytes = entry.getBytes(StandardCharsets.UTF_8);
boolean full;
int size;
synchronized (bufferLock) {
full = buffer.size() >= bufferCapacity;
if (!full) {
buffer.addLast(bytes);
}
size = buffer.size();
}
if (full) {
warnOnce("buffer full (cap=" + bufferCapacity + "), dropping log entries for service \""
+ service + "\"");
return;
}
if (size >= maxBatchSize) {
requestFlush();
}
} catch (RuntimeException ex) {
// Logging must never fail the caller.
warnOnce("could not queue an entry: " + ex);
}
}
public void debug(String message) {
log(Level.DEBUG, message, null);
}
public void info(String message) {
log(Level.INFO, message, null);
}
public void warn(String message) {
log(Level.WARN, message, null);
}
public void error(String message) {
log(Level.ERROR, message, null);
}
public void critical(String message) {
log(Level.CRITICAL, message, null);
}
/**
* Synchronously sends everything buffered when the call starts, in requests of at most 1000 entries and 2 MiB.
* When a request fails for a reason that may pass, its entries and every later entry of this flush go back to
* the front of the buffer, and the rest of the flush waits for the next one. A request OmniLogger rejects is
* dropped. Failures never reach the caller, only a rate-limited warning on stderr. Calls are serialized with the
* background flush.
*/
public synchronized void flush() {
Credentials target = credentials;
List<byte[]> batch = takeBuffered();
if (target == null || batch.isEmpty()) {
return;
}
int start = 0;
while (start < batch.size()) {
int end = batchEnd(batch, start);
if (post(target, batch.subList(start, end))) {
requeue(batch.subList(start, batch.size()));
return;
}
start = end;
}
}
/**
* Replaces the OmniLogger base URL and ingest token, as ProjectConfigurator pushes them. The next flush uses the new
* values. A blank base URL or token disables shipping: nothing more is buffered, and anything already buffered is
* dropped. The background flusher keeps running in every case, so this never restarts it. Safe to call from any
* thread, and it never waits for a flush in progress.
*/
public void setCredentials(String baseUrl, String ingestToken) {
synchronized (credentialsLock) {
Credentials next = credentialsFor(baseUrl, ingestToken);
credentials = next;
if (next == null) {
synchronized (bufferLock) {
buffer.clear();
}
}
}
}
/**
* Stops the background thread after a final flush of whatever is buffered. Call it during graceful
* shutdown. Closing again is a no-op, and entries logged after close are discarded.
*/
@Override
public void close() {
if (!closed.compareAndSet(false, true)) {
return;
}
executor.shutdown();
flush();
}
private void runScheduledFlush() {
try {
flush();
} catch (RuntimeException ex) {
// Never let one failed flush cancel the periodic task.
warnOnce("flush failed: " + ex);
}
}
/** Asks the background thread to flush soon. The request is dropped if one is already pending. */
private void requestFlush() {
if (!flushQueued.compareAndSet(false, true)) {
return;
}
try {
executor.execute(() -> {
flushQueued.set(false);
runScheduledFlush();
});
} catch (RejectedExecutionException ex) {
flushQueued.set(false);
}
}
/** Removes and returns every buffered entry, oldest first. */
private List<byte[]> takeBuffered() {
synchronized (bufferLock) {
List<byte[]> taken = new ArrayList<>(buffer);
buffer.clear();
return taken;
}
}
/**
* Returns the index just past the last entry of the request that starts at {@code start}. A request holds at
* most MAX_BATCH_ENTRIES entries and a body of at most MAX_BODY_BYTES, and always at least one entry.
*/
private static int batchEnd(List<byte[]> entries, int start) {
int bodyBytes = 2;
int end = start;
while (end < entries.size() && end - start < MAX_BATCH_ENTRIES) {
int added = entries.get(end).length + (end == start ? 0 : 1);
if (end > start && bodyBytes + added > MAX_BODY_BYTES) {
break;
}
bodyBytes += added;
end++;
}
return end;
}
/**
* Puts entries that failed to send back at the front of the buffer, so the next flush sends them before newer
* entries. The buffer stays within its capacity: when the entries and the buffer do not all fit, the newest are
* dropped, as {@link #log(Level, String, Map)} drops them when the buffer is full.
*/
private void requeue(List<byte[]> entries) {
int dropped = 0;
synchronized (bufferLock) {
for (int i = entries.size() - 1; i >= 0; i--) {
buffer.addFirst(entries.get(i));
}
while (buffer.size() > bufferCapacity) {
buffer.removeLast();
dropped++;
}
}
if (dropped > 0) {
warnOnce("buffer full while retrying, dropping " + dropped + " log entries for service \""
+ service + "\"");
}
}
/**
* Sends one request and reports whether it failed for a reason that may pass, in which case the caller keeps
* the entries for a later flush. An IO error, HTTP 429 or any 5xx is retried. Any other non-2xx status is a
* rejection, which is warned about and dropped without a retry.
*/
private boolean post(Credentials target, List<byte[]> entries) {
byte[] body = joinJsonArray(entries);
try {
HttpURLConnection connection = (HttpURLConnection) new URL(target.endpoint).openConnection();
connection.setRequestMethod("POST");
connection.setInstanceFollowRedirects(false);
connection.setUseCaches(false);
connection.setConnectTimeout(HTTP_TIMEOUT_MILLIS);
connection.setReadTimeout(HTTP_TIMEOUT_MILLIS);
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(body.length);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + target.token);
try (OutputStream out = connection.getOutputStream()) {
out.write(body);
}
int status = connection.getResponseCode();
drain(connection, status);
if (status >= 200 && status < 300) {
return false;
}
if (status == HTTP_TOO_MANY_REQUESTS || status >= 500) {
warnOnce("OmniLogger answered HTTP " + status + " for " + entries.size() + " entries, will retry");
return true;
}
warnOnce("OmniLogger rejected " + entries.size() + " entries: HTTP " + status);
return false;
} catch (MalformedURLException ex) {
// The request cannot be built, and sending it again would fail the same way.
warnOnce("could not build the request for " + entries.size() + " entries: " + ex);
return false;
} catch (IOException ex) {
warnOnce("send " + entries.size() + " entries to " + target.endpoint + ", will retry: " + ex);
return true;
} catch (RuntimeException ex) {
warnOnce("send " + entries.size() + " entries to " + target.endpoint + ": " + ex);
return false;
}
}
/**
* Reads a bounded part of the response so the connection can be reused, then closes it. This is best effort:
* the status is already known, so a failed read must not turn an accepted request into a retry.
*/
private static void drain(HttpURLConnection connection, int status) {
try {
InputStream in = status >= 200 && status < 300 ? connection.getInputStream() : connection.getErrorStream();
if (in == null) {
return;
}
try (InputStream stream = in) {
byte[] buffer = new byte[1024];
int remaining = MAX_DRAINED_RESPONSE_BYTES;
while (remaining > 0 && stream.read(buffer) != -1) {
remaining -= buffer.length;
}
}
} catch (IOException ignored) {
// Nothing more to do: the status has already been read.
}
}
/** Prints a local stderr warning at most once a minute, so an unreachable OmniLogger cannot spam logs. */
private void warnOnce(String message) {
synchronized (warnLock) {
long now = System.currentTimeMillis();
if (warned && now - lastWarnAtMillis < WARN_INTERVAL_MILLIS) {
return;
}
warned = true;
lastWarnAtMillis = now;
}
System.err.println("[" + WARN_TIME.format(LocalDateTime.now()) + "] [logshipper] " + message);
}
// ---- Limits and encoding. Package-private so the tests can check them directly. ----
/**
* Cuts a message longer than 8192 UTF-8 bytes on a code point boundary and appends the truncation marker.
* The result is at most 8192 bytes.
*/
static String clampMessage(String message) {
if (utf8Length(message) <= MAX_MESSAGE_BYTES) {
return message;
}
int budget = MAX_MESSAGE_BYTES - TRUNCATED_MARKER.length();
int used = 0;
int end = 0;
while (end < message.length()) {
int codePoint = message.codePointAt(end);
int bytes = utf8Bytes(codePoint);
if (used + bytes > budget) {
break;
}
used += bytes;
end += Character.charCount(codePoint);
}
return message.substring(0, end) + TRUNCATED_MARKER;
}
/**
* Serializes the context to JSON. It is replaced by {@link #DROPPED_CONTEXT} when it is over 16384 bytes
* or contains an escaped NUL. It is omitted (null) when it cannot be encoded at all, for example because it
* holds NaN or is nested too deeply.
*/
static String clampContext(Map<String, ?> context) {
if (context == null) {
return null;
}
String json;
try {
StringBuilder builder = new StringBuilder();
writeValue(builder, context, 0);
json = builder.toString();
} catch (RuntimeException ex) {
return null;
}
if (utf8Length(json) > MAX_CONTEXT_BYTES || json.contains("\\u0000")) {
return DROPPED_CONTEXT;
}
return json;
}
/** Encodes one OmniLogger entry. The field order matches the Go reference's wire struct. */
static String encodeEntry(String service, String level, String message, String contextJson, String occurredAt) {
StringBuilder builder = new StringBuilder(message.length() + 128);
builder.append("{\"service\":");
writeString(builder, service);
builder.append(",\"level\":");
writeString(builder, level);
builder.append(",\"message\":");
writeString(builder, message);
if (contextJson != null) {
builder.append(",\"context\":").append(contextJson);
}
builder.append(",\"occurred_at\":");
writeString(builder, occurredAt);
return builder.append('}').toString();
}
static byte[] joinJsonArray(List<byte[]> entries) {
int size = 2 + Math.max(0, entries.size() - 1);
for (byte[] entry : entries) {
size += entry.length;
}
byte[] body = new byte[size];
int position = 0;
body[position++] = '[';
for (int i = 0; i < entries.size(); i++) {
if (i > 0) {
body[position++] = ',';
}
byte[] entry = entries.get(i);
System.arraycopy(entry, 0, body, position, entry.length);
position += entry.length;
}
body[position] = ']';
return body;
}
/**
* Counts UTF-8 bytes the way the encoder writes them. A lone surrogate is written as U+FFFD, which is three
* bytes.
*/
static int utf8Length(String value) {
int length = 0;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c < 0x80) {
length += 1;
} else if (c < 0x800) {
length += 2;
} else if (Character.isHighSurrogate(c) && i + 1 < value.length()
&& Character.isLowSurrogate(value.charAt(i + 1))) {
length += 4;
i++;
} else {
length += 3;
}
}
return length;
}
private static int utf8Bytes(int codePoint) {
if (codePoint < 0x80) {
return 1;
}
if (codePoint < 0x800) {
return 2;
}
return codePoint < 0x10000 ? 3 : 4;
}
/**
* Writes a JSON string literal. Quotes, backslashes and control characters are escaped, and so are lone
* surrogates (written as U+FFFD). Everything else is written as-is, so the output is valid UTF-8 JSON.
*/
private static void writeString(StringBuilder out, String value) {
out.append('"');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '"':
out.append("\\\"");
break;
case '\\':
out.append("\\\\");
break;
case '\n':
out.append("\\n");
break;
case '\r':
out.append("\\r");
break;
case '\t':
out.append("\\t");
break;
case '\b':
out.append("\\b");
break;
case '\f':
out.append("\\f");
break;
default:
if (c < 0x20) {
out.append("\\u00").append(HEX_DIGITS[c >> 4]).append(HEX_DIGITS[c & 0xF]);
} else if (Character.isHighSurrogate(c)) {
if (i + 1 < value.length() && Character.isLowSurrogate(value.charAt(i + 1))) {
out.append(c).append(value.charAt(++i));
} else {
out.append("\\ufffd");
}
} else if (Character.isLowSurrogate(c)) {
out.append("\\ufffd");
} else {
out.append(c);
}
}
}
out.append('"');
}
private static void writeValue(StringBuilder out, Object value, int depth) {
if (depth > MAX_CONTEXT_DEPTH) {
throw new IllegalArgumentException("context is nested too deeply");
}
if (value == null) {
out.append("null");
} else if (value instanceof String) {
writeString(out, (String) value);
} else if (value instanceof Boolean || value instanceof Integer || value instanceof Long
|| value instanceof Short || value instanceof Byte
|| value instanceof BigInteger || value instanceof BigDecimal) {
out.append(value.toString());
} else if (value instanceof Double || value instanceof Float) {
double number = ((Number) value).doubleValue();
if (Double.isNaN(number) || Double.isInfinite(number)) {
throw new IllegalArgumentException("non-finite number in context");
}
out.append(value.toString());
} else if (value instanceof Map) {
out.append('{');
boolean first = true;
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
if (!first) {
out.append(',');
}
first = false;
writeString(out, String.valueOf(entry.getKey()));
out.append(':');
writeValue(out, entry.getValue(), depth + 1);
}
out.append('}');
} else if (value instanceof Iterable) {
writeArray(out, ((Iterable<?>) value).iterator(), depth);
} else if (value instanceof Object[]) {
writeArray(out, Arrays.asList((Object[]) value).iterator(), depth);
} else {
writeString(out, value.toString());
}
}
private static void writeArray(StringBuilder out, Iterator<?> items, int depth) {
out.append('[');
boolean first = true;
while (items.hasNext()) {
if (!first) {
out.append(',');
}
first = false;
writeValue(out, items.next(), depth + 1);
}
out.append(']');
}
private static ThreadFactory daemonThreads(String name) {
return runnable -> {
Thread thread = new Thread(runnable, name);
thread.setDaemon(true);
return thread;
};
}
private static String trimOrEmpty(String value) {
return value == null ? "" : value.trim();
}
private static String trimTrailingSlashes(String value) {
int end = value.length();
while (end > 0 && value.charAt(end - 1) == '/') {
end--;
}
return value.substring(0, end);
}
/** The credentials for a base URL and token, or null when either is blank, which disables shipping. */
private static Credentials credentialsFor(String baseUrl, String ingestToken) {
String base = trimTrailingSlashes(trimOrEmpty(baseUrl));
String token = trimOrEmpty(ingestToken);
if (base.isEmpty() || token.isEmpty()) {
return null;
}
return new Credentials(base + "/api/logs", token);
}
/** An endpoint and bearer token, read together so one flush never pairs an old URL with a new token. */
private static final class Credentials {
final String endpoint;
final String token;
Credentials(String endpoint, String token) {
this.endpoint = endpoint;
this.token = token;
}
}
}
@@ -15,6 +15,7 @@ class TotpTest {
void verifyAcceptsTheRfc6238Vectors() { void verifyAcceptsTheRfc6238Vectors() {
// The RFC lists 8-digit codes; these are their last six digits. // The RFC lists 8-digit codes; these are their last six digits.
assertTrue(Totp.verify(RFC_SECRET, "287082", 59_000L)); assertTrue(Totp.verify(RFC_SECRET, "287082", 59_000L));
assertEquals(1L, Totp.verifyStep(RFC_SECRET, "287082", 59_000L));
assertTrue(Totp.verify(RFC_SECRET, "081804", 1_111_111_109_000L)); assertTrue(Totp.verify(RFC_SECRET, "081804", 1_111_111_109_000L));
assertTrue(Totp.verify(RFC_SECRET, "050471", 1_111_111_111_000L)); assertTrue(Totp.verify(RFC_SECRET, "050471", 1_111_111_111_000L));
assertTrue(Totp.verify(RFC_SECRET, "005924", 1_234_567_890_000L)); assertTrue(Totp.verify(RFC_SECRET, "005924", 1_234_567_890_000L));
@@ -0,0 +1,833 @@
package com.gabriel20xx.shared.logs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gabriel20xx.shared.logs.LogShipper.Level;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Covers LogShipper against a local com.sun.net.httpserver.HttpServer standing in for OmniLogger. Nothing here
* talks to a real OmniLogger. Mirrors the behaviour the Go reference's shipper_test.go checks.
*/
class LogShipperTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String OCCURRED_AT_PATTERN = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z";
/** Large enough that the 1-hour interval and the batch trigger never fire on their own in a test. */
private static final long NEVER_MILLIS = 3_600_000L;
private static final int NO_AUTO_BATCH = 5_000;
private static final int DEFAULT_CAPACITY = 2_000;
private final List<LogShipper> shippers = new ArrayList<>();
private FakeOmniLogger fake;
@AfterEach
void tearDown() {
for (LogShipper shipper : shippers) {
shipper.close();
}
shippers.clear();
if (fake != null) {
fake.stop();
fake = null;
}
}
@Test
void levelParseAcceptsTheSharedLogVocabulary() {
assertEquals(Level.DEBUG, Level.parse("debug"));
assertEquals(Level.DEBUG, Level.parse(" DEBUG "));
assertEquals(Level.INFO, Level.parse("info"));
assertEquals(Level.INFO, Level.parse(""));
assertEquals(Level.INFO, Level.parse(null));
assertEquals(Level.INFO, Level.parse("bogus"));
assertEquals(Level.WARN, Level.parse("warn"));
assertEquals(Level.WARN, Level.parse("warning"));
assertEquals(Level.ERROR, Level.parse("error"));
assertEquals(Level.CRITICAL, Level.parse("critical"));
assertEquals(Level.SILENT, Level.parse("silent"));
assertEquals(Level.SILENT, Level.parse("none"));
assertEquals(Level.SILENT, Level.parse("off"));
}
@Test
void wireNamesAreTheLowercaseNamesOmniLoggerExpects() {
assertEquals("debug", Level.DEBUG.wireName());
assertEquals("info", Level.INFO.wireName());
assertEquals("warn", Level.WARN.wireName());
assertEquals("error", Level.ERROR.wireName());
assertEquals("critical", Level.CRITICAL.wireName());
assertNull(Level.SILENT.wireName());
}
@Test
void javaUtilLoggingLevelsMapOntoTheWireScale() {
assertEquals(Level.ERROR, Level.fromJavaUtilLogging(java.util.logging.Level.SEVERE));
assertEquals(Level.WARN, Level.fromJavaUtilLogging(java.util.logging.Level.WARNING));
assertEquals(Level.INFO, Level.fromJavaUtilLogging(java.util.logging.Level.INFO));
assertEquals(Level.DEBUG, Level.fromJavaUtilLogging(java.util.logging.Level.CONFIG));
assertEquals(Level.DEBUG, Level.fromJavaUtilLogging(java.util.logging.Level.FINE));
assertEquals(Level.DEBUG, Level.fromJavaUtilLogging(java.util.logging.Level.FINEST));
assertEquals(Level.INFO, Level.fromJavaUtilLogging(null));
}
@Test
void fromEnvIsDisabledUnlessBothVariablesAreNonBlank() {
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env(null, null)::get));
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env("http://omni:8080", null)::get));
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env(null, "token")::get));
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env(" ", "token")::get));
assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env("http://omni:8080", " ")::get));
LogShipper shipper = LogShipper.fromEnv("megabasterd", Level.INFO, env("http://omni:8080/", "token")::get);
assertNotNull(shipper);
shipper.close();
}
@Test
void disabledModeWritesNothingToTheConsole() {
// With shipping disabled there is no shipper at all, so there is nothing that could print. A shipper
// created but pointed at a dead sink must still leave the console alone on every call.
String stderr = captureStderr(() -> {
LogShipper shipper = shipper("http://127.0.0.1:1", Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
shipper.info("quiet");
});
assertEquals("", stderr);
}
@Test
void entriesAreBatchedAndSentWithBearerAuthToTheIngestPath() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl() + "/", Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
captureStdout(() -> captureStderr(() -> {
shipper.info("one");
shipper.warn("two");
shipper.error("three");
shipper.critical("four");
}));
shipper.flush();
assertEquals(1, fake.requests().size(), "one flush of four entries is one request");
Request request = fake.requests().get(0);
assertEquals("POST", request.method);
assertEquals("/api/logs", request.path);
assertEquals("Bearer secret", request.authorization);
assertEquals("application/json", request.contentType);
List<JsonNode> entries = fake.entries();
assertEquals(4, entries.size());
assertEquals("one", entries.get(0).get("message").asText());
assertEquals("info", entries.get(0).get("level").asText());
assertEquals("warn", entries.get(1).get("level").asText());
assertEquals("error", entries.get(2).get("level").asText());
assertEquals("critical", entries.get(3).get("level").asText());
for (JsonNode entry : entries) {
assertEquals("megabasterd", entry.get("service").asText());
assertTrue(entry.get("occurred_at").asText().matches(OCCURRED_AT_PATTERN),
"occurred_at must be RFC 3339 UTC with milliseconds: " + entry.get("occurred_at").asText());
}
}
@Test
void flushWithNothingBufferedSendsNoSecondRequest() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
shipper.info("only");
shipper.flush();
shipper.flush();
assertEquals(1, fake.requests().size());
}
@Test
void theBackgroundThreadFlushesOnItsOwnInterval() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, 50L, NO_AUTO_BATCH, DEFAULT_CAPACITY);
shipper.info("without an explicit flush");
waitUntil(() -> fake.entries().size() == 1);
}
@Test
void reachingTheBatchSizeFlushesWithoutWaitingForTheInterval() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, 2, DEFAULT_CAPACITY);
shipper.info("a");
shipper.info("b");
waitUntil(() -> fake.entries().size() == 2);
}
@Test
void closeDrainsTheBufferAndIsIdempotent() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
shipper.info("last words");
shipper.close();
shipper.close();
shipper.info("after close is discarded");
shipper.flush();
List<JsonNode> entries = fake.entries();
assertEquals(1, entries.size());
assertEquals("last words", entries.get(0).get("message").asText());
}
@Test
void thresholdFiltersEntriesBelowIt() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.WARN, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
shipper.info("below");
shipper.warn("at");
shipper.flush();
List<JsonNode> entries = fake.entries();
assertEquals(1, entries.size());
assertEquals("at", entries.get(0).get("message").asText());
}
@Test
void silentThresholdShipsNothing() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.SILENT, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
shipper.critical("never shipped");
shipper.flush();
assertTrue(fake.requests().isEmpty());
}
@Test
void loggingNeverWritesToTheLocalConsole() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.DEBUG, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
String stdout = captureStdout(() -> captureStderr(() -> {
shipper.debug("d");
shipper.info("i");
shipper.warn("w");
shipper.error("e");
shipper.critical("c");
}));
shipper.flush();
assertEquals("", stdout);
assertEquals(5, fake.entries().size());
}
@Test
void messagesWithSpecialCharactersStayValidJson() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
String message = "quote \" backslash \\ newline \n cr \r tab \t bell \u0007 nul \u0000 "
+ "unit \u0001 unicode é emoji 😀 end";
shipper.info(message);
shipper.flush();
assertEquals(message, fake.entries().get(0).get("message").asText());
}
@Test
void structuredContextRoundTrips() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
Map<String, Object> context = new LinkedHashMap<>();
context.put("userId", 7);
context.put("path", "/x\"y");
context.put("ok", true);
context.put("ratio", 1.5);
context.put("none", null);
context.put("tags", java.util.Arrays.asList("a", "b"));
Map<String, Object> nested = new LinkedHashMap<>();
nested.put("k", "v");
context.put("nested", nested);
shipper.log(Level.INFO, "with context", context);
shipper.flush();
JsonNode entryContext = fake.entries().get(0).get("context");
assertEquals(7, entryContext.get("userId").asInt());
assertEquals("/x\"y", entryContext.get("path").asText());
assertTrue(entryContext.get("ok").asBoolean());
assertEquals(1.5, entryContext.get("ratio").asDouble());
assertTrue(entryContext.get("none").isNull());
assertEquals("b", entryContext.get("tags").get(1).asText());
assertEquals("v", entryContext.get("nested").get("k").asText());
}
@Test
void anUnencodableContextIsOmittedAndTheEntryStillShips() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
Map<String, Object> context = new HashMap<>();
context.put("bad", Double.NaN);
shipper.log(Level.INFO, "still here", context);
shipper.flush();
JsonNode entry = fake.entries().get(0);
assertEquals("still here", entry.get("message").asText());
assertFalse(entry.has("context"));
}
@Test
void anOversizedMessageIsClampedWithTheMarker() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
shipper.info(repeat("a", 10_000));
shipper.flush();
String message = fake.entries().get(0).get("message").asText();
assertTrue(message.getBytes(StandardCharsets.UTF_8).length <= 8192);
assertTrue(message.endsWith(" [truncated]"));
}
@Test
void aMultiByteMessageIsCutOnACharacterBoundary() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
// Two bytes per character, so the 8180-byte cut lands exactly on a character boundary here.
shipper.info(repeat("é", 8192));
shipper.flush();
String message = fake.entries().get(0).get("message").asText();
assertTrue(message.getBytes(StandardCharsets.UTF_8).length <= 8192);
assertTrue(message.endsWith(" [truncated]"));
assertFalse(message.contains("�"), "truncation must not split a UTF-8 character");
}
@Test
void clampMessageLeavesAShortMessageUntouched() {
assertEquals("short", LogShipper.clampMessage("short"));
String exactlyLimit = repeat("b", 8192);
assertEquals(exactlyLimit, LogShipper.clampMessage(exactlyLimit));
}
@Test
void anOversizedContextIsReplacedWithTheDroppedMarker() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
Map<String, Object> context = new HashMap<>();
context.put("blob", repeat("x", 17_000));
shipper.log(Level.INFO, "big", context);
shipper.flush();
JsonNode entry = fake.entries().get(0);
assertEquals("big", entry.get("message").asText());
assertTrue(entry.get("context").get("context_dropped").asBoolean());
assertEquals(1, entry.get("context").size());
}
@Test
void aContextWithAnEscapedNulIsReplacedWithTheDroppedMarker() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
Map<String, Object> context = new HashMap<>();
context.put("s", "a\u0000b");
shipper.log(Level.INFO, "nul", context);
shipper.flush();
assertTrue(fake.entries().get(0).get("context").get("context_dropped").asBoolean());
}
@Test
void clampContextKeepsAnOrdinaryContextAsItIs() {
Map<String, Object> context = new LinkedHashMap<>();
context.put("ok", true);
assertEquals("{\"ok\":true}", LogShipper.clampContext(context));
assertNull(LogShipper.clampContext(null));
}
@Test
void batchesNeverExceedOneThousandEntries() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3_000);
for (int i = 0; i < 1_500; i++) {
shipper.info("entry " + i);
}
shipper.flush();
assertEquals(1_500, fake.entries().size());
for (Request request : fake.requests()) {
assertTrue(JSON.readTree(request.body).size() <= 1_000);
}
}
@Test
void batchesStayUnderTheRequestBodyLimit() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
// Control characters are escaped to six bytes each, so every entry is about 48 KiB on the wire.
String largeMessage = repeat("\u0001", 8192);
for (int i = 0; i < 60; i++) {
shipper.info(largeMessage);
}
shipper.flush();
assertEquals(60, fake.entries().size());
assertTrue(fake.requests().size() > 1, "60 entries of this size cannot fit one body under 2 MiB");
for (Request request : fake.requests()) {
assertTrue(request.body.length < 2 * 1024 * 1024, "body is " + request.body.length + " bytes");
}
assertEquals(8192, fake.entries().get(0).get("message").asText().length());
}
@Test
void anUnreachableOmniLoggerNeverThrowsAndWarnsOnce() throws Exception {
LogShipper shipper = shipper("http://127.0.0.1:1", Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
shipper.info("one");
String stderr = captureStderr(() -> {
shipper.flush();
shipper.info("two");
shipper.flush();
});
assertEquals(1, countOccurrences(stderr, "[logshipper]"));
}
@Test
void aRejectedBatchIsDroppedAndWarnedAboutOnce() throws Exception {
fake = new FakeOmniLogger();
fake.setStatus(400);
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
String stderr = captureStderr(() -> {
shipper.info("one");
shipper.flush();
shipper.info("two");
shipper.flush();
});
assertEquals(1, countOccurrences(stderr, "OmniLogger rejected"));
assertEquals(2, fake.requests().size(), "rejected batches are not retried");
}
@Test
void aServerErrorIsRetriedAndEachEntryArrivesOnceInOrder() throws Exception {
fake = new FakeOmniLogger();
fake.respondNext(503);
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY);
String stderr = captureStderr(() -> {
shipper.info("a");
shipper.info("b");
shipper.flush(); // refused with 503: kept for the next flush
shipper.flush(); // accepted
shipper.flush(); // nothing left to send
});
assertEquals(1, countOccurrences(stderr, "will retry"));
assertEquals(2, fake.requests().size(), "the refused request is sent again, and nothing else is");
List<JsonNode> entries = fake.entries();
assertEquals(2, entries.size());
assertEquals("a", entries.get(0).get("message").asText());
assertEquals("b", entries.get(1).get("message").asText());
}
@Test
void aFailedRequestEndsTheFlushAndTheRestWaitsForTheNextFlush() throws Exception {
fake = new FakeOmniLogger();
fake.respondNext(202, 503);
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3_000);
for (int i = 0; i < 1_500; i++) {
shipper.info("entry " + i);
}
captureStderr(shipper::flush); // 1000 accepted, then 500 refused: the flush stops there
assertEquals(2, fake.requests().size());
assertEquals(1_000, fake.entries().size());
shipper.flush();
assertEquals(3, fake.requests().size());
List<JsonNode> entries = fake.entries();
assertEquals(1_500, entries.size());
for (int i = 0; i < entries.size(); i++) {
assertEquals("entry " + i, entries.get(i).get("message").asText());
}
}
@Test
void duringAnOutageTheBufferKeepsTheOldestEntriesUpToItsCapacity() throws Exception {
fake = new FakeOmniLogger();
fake.setStatus(503);
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3);
captureStderr(() -> {
for (String message : new String[] {"a", "b", "c"}) {
shipper.info(message);
}
shipper.flush(); // refused with 503: kept for retry
shipper.info("d"); // the buffer is full, so d is dropped
shipper.info("e"); // and e is dropped
shipper.flush(); // still refused
});
fake.setStatus(202);
shipper.flush();
List<JsonNode> entries = fake.entries();
assertEquals(3, entries.size(), "the buffer held only its capacity");
assertEquals("a", entries.get(0).get("message").asText());
assertEquals("b", entries.get(1).get("message").asText());
assertEquals("c", entries.get(2).get("message").asText());
}
@Test
void aFullBufferDropsTheNewestEntryAndWarnsOnce() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3);
String stderr = captureStderr(() -> {
for (int i = 0; i < 10; i++) {
shipper.info("m" + i);
}
});
shipper.flush();
List<JsonNode> entries = fake.entries();
assertEquals(3, entries.size());
assertEquals("m0", entries.get(0).get("message").asText());
assertEquals("m2", entries.get(2).get("message").asText());
assertEquals(1, countOccurrences(stderr, "buffer full"));
}
@Test
void fromEnvShipsToTheConfiguredServiceAndToken() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = LogShipper.fromEnv("gamestream", Level.INFO,
env(fake.baseUrl(), "env-token")::get);
assertNotNull(shipper);
shippers.add(shipper);
shipper.error("boom");
shipper.flush();
assertEquals("Bearer env-token", fake.requests().get(0).authorization);
assertEquals("gamestream", fake.entries().get(0).get("service").asText());
}
@Test
void setCredentialsSendsTheNextFlushToTheNewEndpointAndToken() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = neverFlushing("http://127.0.0.1:1", "old-token");
shipper.setCredentials(fake.baseUrl() + "/", "new-token");
shipper.info("after the push");
shipper.flush();
assertEquals(1, fake.requests().size());
assertEquals("/api/logs", fake.requests().get(0).path);
assertEquals("Bearer new-token", fake.requests().get(0).authorization);
assertEquals("after the push", fake.entries().get(0).get("message").asText());
}
@Test
void aBlankCredentialDisablesShippingAndDropsTheBuffer() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = neverFlushing(fake.baseUrl(), "token");
shipper.info("buffered before the disable");
shipper.setCredentials("", "token");
shipper.info("logged while disabled");
shipper.flush();
assertTrue(fake.requests().isEmpty());
shipper.setCredentials(fake.baseUrl(), " ");
shipper.info("logged with a blank token");
shipper.flush();
assertTrue(fake.requests().isEmpty());
shipper.setCredentials(fake.baseUrl(), "token");
shipper.info("after re-enabling");
shipper.flush();
assertEquals(1, fake.requests().size());
assertEquals("after re-enabling", fake.entries().get(0).get("message").asText());
}
@Test
void aShipperBuiltWithoutCredentialsStartsDisabled() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = neverFlushing(null, "token");
shipper.info("dropped");
shipper.flush();
assertTrue(fake.requests().isEmpty());
}
@Test
void theBackgroundFlusherKeepsRunningAcrossCredentialChanges() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = new LogShipper("http://127.0.0.1:1", "token", "megabasterd", Level.INFO,
50L, NO_AUTO_BATCH, DEFAULT_CAPACITY);
shippers.add(shipper);
shipper.setCredentials("", "");
shipper.setCredentials(fake.baseUrl(), "token");
shipper.info("sent by the interval, with no explicit flush");
waitUntil(() -> !fake.requests().isEmpty());
assertEquals("sent by the interval, with no explicit flush",
fake.entries().get(0).get("message").asText());
}
@Test
void concurrentCredentialChangesAreSafeAndTheLastValuesWin() throws Exception {
fake = new FakeOmniLogger();
LogShipper shipper = neverFlushing(fake.baseUrl(), "token");
ExecutorService pool = Executors.newFixedThreadPool(4);
try {
List<Future<?>> writers = new ArrayList<>();
for (int t = 0; t < 4; t++) {
writers.add(pool.submit(() -> {
for (int i = 0; i < 200; i++) {
shipper.setCredentials(i % 2 == 0 ? "" : fake.baseUrl(), "token");
shipper.info("noise");
}
}));
}
for (Future<?> writer : writers) {
writer.get(10, TimeUnit.SECONDS);
}
} finally {
pool.shutdownNow();
}
shipper.setCredentials(fake.baseUrl(), "final-token");
shipper.info("final");
shipper.flush();
List<Request> requests = fake.requests();
assertFalse(requests.isEmpty());
assertEquals("Bearer final-token", requests.get(requests.size() - 1).authorization);
List<JsonNode> entries = fake.entries();
assertEquals("final", entries.get(entries.size() - 1).get("message").asText());
}
private LogShipper neverFlushing(String baseUrl, String token) {
LogShipper shipper = new LogShipper(baseUrl, token, "megabasterd", Level.INFO, NEVER_MILLIS,
NO_AUTO_BATCH, DEFAULT_CAPACITY);
shippers.add(shipper);
return shipper;
}
private static Map<String, String> env(String url, String token) {
Map<String, String> values = new HashMap<>();
if (url != null) {
values.put(LogShipper.ENV_URL, url);
}
if (token != null) {
values.put(LogShipper.ENV_TOKEN, token);
}
return values;
}
private LogShipper shipper(String baseUrl, Level threshold, long intervalMillis, int maxBatch, int capacity) {
LogShipper shipper = new LogShipper(baseUrl, "secret", "megabasterd", threshold, intervalMillis, maxBatch, capacity);
shippers.add(shipper);
return shipper;
}
private static String repeat(String unit, int times) {
StringBuilder builder = new StringBuilder(unit.length() * times);
for (int i = 0; i < times; i++) {
builder.append(unit);
}
return builder.toString();
}
private static int countOccurrences(String haystack, String needle) {
int count = 0;
int index = haystack.indexOf(needle);
while (index >= 0) {
count++;
index = haystack.indexOf(needle, index + needle.length());
}
return count;
}
private static void waitUntil(BooleanSupplier condition) throws InterruptedException {
long deadline = System.currentTimeMillis() + 5_000L;
while (!condition.getAsBoolean()) {
if (System.currentTimeMillis() > deadline) {
fail("condition not met within 5 seconds");
}
Thread.sleep(10L);
}
}
private static String captureStderr(Runnable action) {
return capture(action, true);
}
private static String captureStdout(Runnable action) {
return capture(action, false);
}
private static String capture(Runnable action, boolean stderr) {
PrintStream original = stderr ? System.err : System.out;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PrintStream replacement = new PrintStream(buffer, true);
if (stderr) {
System.setErr(replacement);
} else {
System.setOut(replacement);
}
try {
action.run();
} finally {
if (stderr) {
System.setErr(original);
} else {
System.setOut(original);
}
}
return new String(buffer.toByteArray(), StandardCharsets.UTF_8);
}
/** One request received by the fake OmniLogger, and the status it answered with. */
private static final class Request {
final String method;
final String path;
final String authorization;
final String contentType;
final byte[] body;
final int status;
Request(String method, String path, String authorization, String contentType, byte[] body, int status) {
this.method = method;
this.path = path;
this.authorization = authorization;
this.contentType = contentType;
this.body = body;
this.status = status;
}
}
/** A stand-in OmniLogger that records every POST to it. */
private static final class FakeOmniLogger {
private final HttpServer server;
private final List<Request> requests = Collections.synchronizedList(new ArrayList<Request>());
private final Deque<Integer> nextStatuses = new ArrayDeque<>();
private volatile int status = 202;
FakeOmniLogger() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
byte[] body = readAll(exchange.getRequestBody());
int answer = nextStatus();
requests.add(new Request(exchange.getRequestMethod(), exchange.getRequestURI().getPath(),
exchange.getRequestHeaders().getFirst("Authorization"),
exchange.getRequestHeaders().getFirst("Content-Type"), body, answer));
exchange.sendResponseHeaders(answer, -1);
exchange.close();
});
server.start();
}
String baseUrl() {
return "http://127.0.0.1:" + server.getAddress().getPort();
}
/** The status answered to every request that respondNext does not script. */
void setStatus(int status) {
this.status = status;
}
/** Answers the next requests with these statuses, in order, before the status from setStatus applies. */
void respondNext(int... statuses) {
synchronized (nextStatuses) {
for (int answer : statuses) {
nextStatuses.addLast(answer);
}
}
}
private int nextStatus() {
synchronized (nextStatuses) {
Integer scripted = nextStatuses.pollFirst();
return scripted != null ? scripted : status;
}
}
void stop() {
server.stop(0);
}
List<Request> requests() {
synchronized (requests) {
return new ArrayList<>(requests);
}
}
/** Every entry from every batch OmniLogger accepted so far, in arrival order. */
List<JsonNode> entries() {
List<JsonNode> all = new ArrayList<>();
for (Request request : requests()) {
if (request.status < 200 || request.status >= 300) {
continue;
}
try {
for (JsonNode entry : JSON.readTree(request.body)) {
all.add(entry);
}
} catch (IOException ex) {
throw new IllegalStateException("request body is not JSON: " + ex.getMessage(), ex);
}
}
return all;
}
private static byte[] readAll(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
return out.toByteArray();
}
}
}
+3 -2
View File
@@ -7,11 +7,12 @@ Shared Node.js backend infrastructure for services that use PostgreSQL:
- PBKDF2 password hashing (`verifyAndUpgradePasswordAsync` returns a current-scheme hash for a login to store) and secure session-token helpers; - PBKDF2 password hashing (`verifyAndUpgradePasswordAsync` returns a current-scheme hash for a login to store) and secure session-token helpers;
- short-lived, one-time admin reset codes printed to the server console; - short-lived, one-time admin reset codes printed to the server console;
- common account/session persistence; - common account/session persistence;
- transaction-locked ordered migrations. - transaction-locked ordered migrations;
- OmniLogger log shipping: `createLogShipperFromEnv` (off unless `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` are both set), `LogShipper`, and `mirrorConsole`.
The package does not depend on Express. Each service keeps its own routes, The package does not depend on Express. Each service keeps its own routes,
cookies, roles, validation policy, and domain repositories. Existing cookies, roles, validation policy, and domain repositories. Existing
`MediaShared` code can be migrated into this package incrementally; keep the media-related code can be migrated into this package incrementally; keep the
legacy package as a compatibility layer until every consumer has moved. legacy package as a compatibility layer until every consumer has moved.
Pass a service-specific `tableName` to `runMigrations` when multiple services Pass a service-specific `tableName` to `runMigrations` when multiple services
+1
View File
@@ -19,6 +19,7 @@
"./package.json": "./package.json" "./package.json": "./package.json"
}, },
"dependencies": { "dependencies": {
"bcryptjs": "^3.0.3",
"pg": "^8.17.2" "pg": "^8.17.2"
}, },
"scripts": { "scripts": {
+117 -55
View File
@@ -1,16 +1,20 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import { promisify } from 'node:util'; import { promisify } from 'node:util';
import bcrypt from 'bcryptjs';
import { verifyTotpStep } from './totp.js';
const pbkdf2 = promisify(crypto.pbkdf2); const pbkdf2 = promisify(crypto.pbkdf2);
// Hashes written before the format recorded its parameters are `salt:hex` at // Node's old formats remain readable so successful logins can migrate them.
// this count. They still verify and are rewritten on the next successful login.
// New hashes use PASSWORD_ITERATIONS and carry the scheme prefix PASSWORD_FORMAT.
const LEGACY_PASSWORD_ITERATIONS = 100000; const LEGACY_PASSWORD_ITERATIONS = 100000;
const PASSWORD_ITERATIONS = 600000; const MAX_PBKDF2_ITERATIONS = 10000000;
const PASSWORD_KEY_LENGTH = 32; const PASSWORD_KEY_LENGTH = 32;
const PASSWORD_DIGEST = 'sha256'; const PASSWORD_DIGEST = 'sha256';
const PASSWORD_FORMAT = 'pbkdf2-sha256'; const PASSWORD_FORMAT = 'pbkdf2-sha256';
const BCRYPT_SCHEME = 'bcrypt$';
const BCRYPT_SHA256_SCHEME = 'bcrypt-sha256$';
const BCRYPT_ROUNDS = 12;
const BCRYPT_MAX_PASSWORD_BYTES = 72;
const LEGACY_PASSWORD_PATTERN = /^[0-9a-f]+:[0-9a-f]+$/; const LEGACY_PASSWORD_PATTERN = /^[0-9a-f]+:[0-9a-f]+$/;
export const RESET_CODE_TTL_MS = 5 * 60 * 1000; export const RESET_CODE_TTL_MS = 5 * 60 * 1000;
export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' }); export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' });
@@ -38,6 +42,7 @@ CREATE TABLE IF NOT EXISTS auth_users (
role TEXT NOT NULL DEFAULT 'user', role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '', totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE, totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
last_used_step BIGINT NOT NULL DEFAULT -1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now() updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
); );
@@ -45,6 +50,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user'; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT ''; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
UPDATE auth_users SET role = 'superadmin' UPDATE auth_users SET role = 'superadmin'
@@ -100,38 +106,47 @@ function assertPasswordLength(password) {
if (typeof password !== 'string' || password.length < 8) { if (typeof password !== 'string' || password.length < 8) {
throw new Error('Password must be at least 8 characters'); throw new Error('Password must be at least 8 characters');
} }
if (Buffer.byteLength(password, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) {
throw new Error(`Password must be at most ${BCRYPT_MAX_PASSWORD_BYTES} bytes`);
}
} }
function encodePasswordHash(salt, hash, iterations) { function parsePbkdf2Hash(stored) {
return [PASSWORD_FORMAT, iterations, salt, hash.toString('hex')].join('$');
}
// Returns the salt, expected hash and iteration count recorded in a stored hash,
// or null for a format this module does not verify (such as bcrypt written by
// the Python or Go packages).
function parsePasswordHash(stored) {
const text = String(stored); const text = String(stored);
let iterations = LEGACY_PASSWORD_ITERATIONS;
let salt;
let expected;
if (text.startsWith(`${PASSWORD_FORMAT}$`)) { if (text.startsWith(`${PASSWORD_FORMAT}$`)) {
const parts = text.split('$'); const parts = text.split('$');
if (parts.length !== 4) return null; if (parts.length !== 4) return null;
const [, iterations, salt, expected] = parts; [, iterations, salt, expected] = parts;
return { iterations: Number(iterations), salt, expected, legacy: false }; iterations = Number(iterations);
} } else if (LEGACY_PASSWORD_PATTERN.test(text)) {
if (LEGACY_PASSWORD_PATTERN.test(text)) { [salt, expected] = text.split(':');
const [salt, expected] = text.split(':'); } else {
return { iterations: LEGACY_PASSWORD_ITERATIONS, salt, expected, legacy: true }; return null;
} }
if (!/^[0-9a-f]{32}$/.test(salt) || !/^[0-9a-f]{64}$/.test(expected)) return null;
if (!Number.isSafeInteger(iterations) || iterations < 1 || iterations > MAX_PBKDF2_ITERATIONS) return null;
return { iterations, salt, expected };
}
function parseBcryptHash(stored) {
const text = String(stored);
if (text.startsWith(BCRYPT_SHA256_SCHEME)) return { hash: text.slice(BCRYPT_SHA256_SCHEME.length), prehashed: true };
if (text.startsWith(BCRYPT_SCHEME)) return { hash: text.slice(BCRYPT_SCHEME.length), prehashed: false };
if (/^\$2[aby]\$/.test(text)) return { hash: text, prehashed: false, legacy: true };
return null; return null;
} }
function usablePasswordHash(stored) { function validBcryptHash(parsed) {
const parsed = parsePasswordHash(stored); if (!parsed?.hash) return false;
if (!parsed || !parsed.salt || !parsed.expected || !isValidIterations(parsed.iterations)) return null; try {
return parsed; bcrypt.getRounds(parsed.hash);
} return true;
} catch {
function isValidIterations(iterations) { return false;
return Number.isSafeInteger(iterations) && iterations >= 1; }
} }
function passwordHashMatches(expected, actual) { function passwordHashMatches(expected, actual) {
@@ -140,34 +155,52 @@ function passwordHashMatches(expected, actual) {
} }
/** /**
* Blocking PBKDF2 hash. Prefer hashPasswordAsync in request handlers, because * Blocking bcrypt hash. Prefer hashPasswordAsync in request handlers, because
* this call holds the event loop for the whole derivation. * this call holds the event loop for the whole derivation.
*/ */
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) { export function hashPassword(password) {
assertPasswordLength(password); assertPasswordLength(password);
const salt = crypto.randomBytes(16).toString('hex'); return BCRYPT_SCHEME + bcrypt.hashSync(password, BCRYPT_ROUNDS);
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return encodePasswordHash(salt, hash, iterations);
} }
/** Non-blocking variant of hashPassword with the same output format. */ /** Non-blocking variant of hashPassword with the same bcrypt format. */
export async function hashPasswordAsync(password, { iterations = PASSWORD_ITERATIONS } = {}) { export async function hashPasswordAsync(password) {
assertPasswordLength(password); assertPasswordLength(password);
return derivePasswordHashAsync(password, iterations); return BCRYPT_SCHEME + await bcrypt.hash(password, BCRYPT_ROUNDS);
} }
// The length rule belongs to user-facing hashing. Upgrading an old hash must // A legacy PBKDF2 password can exceed bcrypt's 72-byte input limit. Preserve
// not refuse a password that was accepted when it was first set. // the full password by hashing its UTF-8 bytes before bcrypt and marking that
async function derivePasswordHashAsync(password, iterations) { // representation explicitly in the stored scheme.
const salt = crypto.randomBytes(16).toString('hex'); function bcryptInputForLegacyPassword(password) {
const hash = await pbkdf2(String(password), salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST); const text = String(password);
return encodePasswordHash(salt, hash, iterations); if (Buffer.byteLength(text, 'utf8') <= BCRYPT_MAX_PASSWORD_BYTES) {
return { scheme: BCRYPT_SCHEME, input: text };
}
return {
scheme: BCRYPT_SHA256_SCHEME,
input: crypto.createHash('sha256').update(text, 'utf8').digest('hex'),
};
}
async function derivePasswordHashAsync(password) {
const { scheme, input } = bcryptInputForLegacyPassword(password);
return scheme + await bcrypt.hash(input, BCRYPT_ROUNDS);
} }
/** Blocking verify. Prefer verifyPasswordAsync in request handlers. */ /** Blocking verify. Prefer verifyPasswordAsync in request handlers. */
export function verifyPassword(password, stored) { export function verifyPassword(password, stored) {
try { try {
const parsed = usablePasswordHash(stored); const bcryptHash = parseBcryptHash(stored);
if (bcryptHash) {
if (!validBcryptHash(bcryptHash)) return false;
const input = bcryptHash.prehashed
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
: String(password);
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
return bcrypt.compareSync(input, bcryptHash.hash);
}
const parsed = parsePbkdf2Hash(stored);
if (!parsed) return false; if (!parsed) return false;
const actual = crypto.pbkdf2Sync(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST); const actual = crypto.pbkdf2Sync(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return passwordHashMatches(parsed.expected, actual); return passwordHashMatches(parsed.expected, actual);
@@ -179,7 +212,16 @@ export function verifyPassword(password, stored) {
/** Non-blocking variant of verifyPassword. */ /** Non-blocking variant of verifyPassword. */
export async function verifyPasswordAsync(password, stored) { export async function verifyPasswordAsync(password, stored) {
try { try {
const parsed = usablePasswordHash(stored); const bcryptHash = parseBcryptHash(stored);
if (bcryptHash) {
if (!validBcryptHash(bcryptHash)) return false;
const input = bcryptHash.prehashed
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
: String(password);
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
return await bcrypt.compare(input, bcryptHash.hash);
}
const parsed = parsePbkdf2Hash(stored);
if (!parsed) return false; if (!parsed) return false;
const actual = await pbkdf2(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST); const actual = await pbkdf2(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
return passwordHashMatches(parsed.expected, actual); return passwordHashMatches(parsed.expected, actual);
@@ -189,12 +231,15 @@ export async function verifyPasswordAsync(password, stored) {
} }
/** /**
* True when a stored hash should be rewritten after a successful login: a * True when a stored hash should be rewritten after a successful login.
* legacy `salt:hex` hash, or a PBKDF2 hash below PASSWORD_ITERATIONS.
*/ */
export function passwordHashNeedsUpgrade(stored) { export function passwordHashNeedsUpgrade(stored) {
const parsed = parsePasswordHash(stored); const bcryptHash = parseBcryptHash(stored);
return !parsed || parsed.legacy || parsed.iterations < PASSWORD_ITERATIONS; if (bcryptHash) {
if (!validBcryptHash(bcryptHash)) return true;
return Boolean(bcryptHash.legacy) || bcrypt.getRounds(bcryptHash.hash) < BCRYPT_ROUNDS;
}
return true;
} }
/** /**
@@ -210,7 +255,7 @@ export async function verifyAndUpgradePasswordAsync(password, stored) {
if (!passwordHashNeedsUpgrade(stored)) { if (!passwordHashNeedsUpgrade(stored)) {
return { valid: true, upgradedHash: null }; return { valid: true, upgradedHash: null };
} }
return { valid: true, upgradedHash: await derivePasswordHashAsync(password, PASSWORD_ITERATIONS) }; return { valid: true, upgradedHash: await derivePasswordHashAsync(password) };
} }
export function createSessionToken() { export function createSessionToken() {
@@ -412,10 +457,10 @@ export class AuthStore {
async getTotpState(userId) { async getTotpState(userId) {
const result = await this.database.query( const result = await this.database.query(
'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled FROM auth_users WHERE id = $1', 'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled, COALESCE(last_used_step, -1) AS last_used_step FROM auth_users WHERE id = $1',
[userId], [userId],
); );
return result.rows[0] || { secret: '', enabled: false }; return result.rows[0] || { secret: '', enabled: false, last_used_step: -1 };
} }
/** /**
@@ -425,7 +470,7 @@ export class AuthStore {
*/ */
async setTotpSecret(userId, secret) { async setTotpSecret(userId, secret) {
const result = await this.database.query( const result = await this.database.query(
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled', 'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled',
[secret, userId], [secret, userId],
); );
if (result.rowCount === 0 && (await this.getTotpState(userId)).enabled) { if (result.rowCount === 0 && (await this.getTotpState(userId)).enabled) {
@@ -433,16 +478,33 @@ export class AuthStore {
} }
} }
async enableTotp(userId) { async enableTotp(userId, token, now = Date.now()) {
await this.database.query( const state = await this.getTotpState(userId);
"UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''", if (!state.secret || state.enabled) return false;
[userId], const step = verifyTotpStep(state.secret, token, now);
if (step === null) return false;
const result = await this.database.query(
"UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1",
[step, userId, state.secret],
); );
return result.rowCount === 1;
}
async consumeTotpCode(userId, token, now = Date.now()) {
const state = await this.getTotpState(userId);
if (!state.secret || !state.enabled) return false;
const step = verifyTotpStep(state.secret, token, now);
if (step === null) return false;
const result = await this.database.query(
'UPDATE auth_users SET last_used_step = $1, updated_at = now() WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1',
[step, userId, state.secret],
);
return result.rowCount === 1;
} }
async disableTotp(userId) { async disableTotp(userId) {
await this.database.query( await this.database.query(
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1", "UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1",
[userId], [userId],
); );
} }
+26 -4
View File
@@ -60,16 +60,38 @@ export class Info {
} }
} }
/** Shortest SECRET a service accepts for its internal routes. */
export const MIN_INTERNAL_SECRET_LENGTH = 16;
/** /**
* True when the X-Internal-Auth value equals the configured secret. An unset * Placeholders from .env.example files and the bare variable name. They are
* or empty secret never matches, and the comparison is constant-time. * public, so they never gate a route.
*/
export const EXAMPLE_INTERNAL_SECRETS = new Set(['SECRET', 'change-me-to-a-long-random-value']);
/**
* True when the configured secret is strong enough to gate an internal route:
* at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
* placeholder. Length counts characters, as the Python and Go helpers do.
* @param {unknown} secret
* @returns {boolean}
*/
export function internalSecretUsable(secret) {
const value = String(secret ?? '');
return [...value].length >= MIN_INTERNAL_SECRET_LENGTH && !EXAMPLE_INTERNAL_SECRETS.has(value);
}
/**
* True when the X-Internal-Auth value equals the configured secret. A secret
* that is not usable (see internalSecretUsable) never matches, and the
* comparison is constant-time.
* @param {unknown} provided * @param {unknown} provided
* @param {unknown} secret * @param {unknown} secret
* @returns {boolean} * @returns {boolean}
*/ */
export function internalSecretMatches(provided, secret) { export function internalSecretMatches(provided, secret) {
const expected = Buffer.from(String(secret ?? '')); if (!internalSecretUsable(secret)) return false;
if (expected.length === 0) return false; const expected = Buffer.from(String(secret));
const actual = Buffer.from(String(provided ?? '')); const actual = Buffer.from(String(provided ?? ''));
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual); return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
} }
+5
View File
@@ -33,11 +33,16 @@ export {
generateTotpSecret, generateTotpSecret,
totpProvisioningUri, totpProvisioningUri,
verifyTotp, verifyTotp,
verifyTotpStep,
} from './totp.js'; } from './totp.js';
export { runMigrations } from './migrate.js'; export { runMigrations } from './migrate.js';
export { LOG_LEVELS, LogShipper, createLogShipperFromEnv, mirrorConsole } from './logshipper.js';
export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js'; export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js';
export { export {
EXAMPLE_INTERNAL_SECRETS,
Info as CoreConfigInfo, Info as CoreConfigInfo,
MIN_INTERNAL_SECRET_LENGTH,
Store as CoreConfigStore, Store as CoreConfigStore,
internalSecretMatches, internalSecretMatches,
internalSecretUsable,
} from './coreconfig.js'; } from './coreconfig.js';
+361
View File
@@ -0,0 +1,361 @@
// logshipper.js is the Node equivalent of shared/backend/logshipper (Go) and follows the same
// OmniLogger contract: it batches log entries and POSTs them to OmniLogger's /api/logs with the
// service's ingest token, so a service's existing logs also reach the central sink.
//
// It is a sink, not a logger. It never writes to the console itself: callers keep their
// console.* lines exactly as they are, and mirrorConsole() forwards each of those lines here as
// well. Shipping is off unless both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are set;
// createLogShipperFromEnv returns null otherwise, and nothing here ever throws into the caller.
import { format } from 'node:util';
export const LOG_LEVELS = Object.freeze(['debug', 'info', 'warn', 'error', 'critical']);
// Thresholds use the same numeric scale as internal/logging in the Go services.
const LEVEL_RANK = new Map([
['debug', 10],
['info', 20],
['warn', 30],
['error', 40],
['critical', 50],
['silent', 100],
]);
const LEVEL_ALIASES = new Map([
['warning', 'warn'],
['none', 'silent'],
['off', 'silent'],
]);
const DEFAULT_FLUSH_INTERVAL_MS = 2000;
const DEFAULT_MAX_BATCH_SIZE = 100;
const DEFAULT_BUFFER_CAPACITY = 2000;
const DEFAULT_TIMEOUT_MS = 5000;
const DEFAULT_WARN_INTERVAL_MS = 60_000;
// OmniLogger rejects a whole batch when any entry breaks a limit, so each entry is clamped before
// it is buffered. It also caps a batch at 1000 entries and a request body under 2 MiB.
const MAX_MESSAGE_BYTES = 8 * 1024;
const MAX_CONTEXT_BYTES = 16 * 1024;
const MAX_BATCH_ENTRIES = 1000;
const MAX_BODY_BYTES = 1024 * 1024; // packing budget, well under OmniLogger's 2 MiB limit
const TRUNCATED_MARKER = ' [truncated]';
const DROPPED_CONTEXT = '{"context_dropped":true}';
// The console methods that are mirrored, and the level each one ships at. console.log has no level
// of its own, so it ships at info.
const CONSOLE_LEVELS = [
['debug', 'debug'],
['log', 'info'],
['info', 'info'],
['warn', 'warn'],
['error', 'error'],
];
function canonicalLevel(name) {
const key = String(name ?? '')
.trim()
.toLowerCase();
return LEVEL_ALIASES.get(key) ?? key;
}
function positiveOr(value, fallback) {
return Number.isFinite(value) && value > 0 ? value : fallback;
}
function clampMessage(message) {
if (Buffer.byteLength(message, 'utf8') <= MAX_MESSAGE_BYTES) return message;
const bytes = Buffer.from(message, 'utf8');
let cut = MAX_MESSAGE_BYTES - Buffer.byteLength(TRUNCATED_MARKER);
// Cut on a UTF-8 character boundary: a continuation byte (10xxxxxx) starts no character.
while (cut > 0 && (bytes[cut] & 0xc0) === 0x80) cut -= 1;
return bytes.subarray(0, cut).toString('utf8') + TRUNCATED_MARKER;
}
// serializeContext returns the context as JSON text, or undefined when there is none to send.
// A context that cannot be serialized is omitted; one that breaks a limit is replaced by a marker,
// so the entry itself still reaches OmniLogger.
function serializeContext(context) {
if (Object.prototype.toString.call(context) !== '[object Object]') return undefined;
let json;
try {
json = JSON.stringify(context);
} catch {
return undefined;
}
if (json === undefined) return undefined;
if (Buffer.byteLength(json, 'utf8') > MAX_CONTEXT_BYTES || json.includes('\\u0000')) return DROPPED_CONTEXT;
return json;
}
// packBatches splits serialized entries into request bodies of at most maxEntries entries and
// MAX_BODY_BYTES bytes each. A flush can hold more than one batch's worth of entries when
// OmniLogger was slow, so the split keeps every request inside OmniLogger's limits.
function packBatches(entries, maxEntries) {
const batches = [];
let batch = [];
let bytes = 2; // the enclosing brackets
for (const entry of entries) {
const entryBytes = Buffer.byteLength(entry, 'utf8');
const separator = batch.length === 0 ? 0 : 1;
if (batch.length > 0 && (batch.length >= maxEntries || bytes + separator + entryBytes > MAX_BODY_BYTES)) {
batches.push(batch);
batch = [];
bytes = 2;
}
bytes += (batch.length === 0 ? 0 : 1) + entryBytes;
batch.push(entry);
}
if (batch.length > 0) batches.push(batch);
return batches;
}
function defaultWarning(text) {
process.stderr.write(`[${new Date().toISOString()}] ${text}\n`);
}
// LogShipper batches entries in memory and sends them to OmniLogger in the background. Its methods
// never throw and never wait on the network, and it never prints anything itself except a
// rate-limited warning when OmniLogger cannot be reached.
export class LogShipper {
#service;
#url;
#token;
#threshold;
#flushIntervalMs;
#maxBatchSize;
#bufferCapacity;
#timeoutMs;
#warnIntervalMs;
#onWarning;
#buffer = []; // serialized wire entries, oldest first
#timer;
#chain = Promise.resolve(); // sends run one at a time, in the order they were requested
#flushRequested = false;
#closed = false;
#lastWarnAt = null;
constructor({
baseUrl = '',
ingestToken = '',
service = '',
level = 'info',
flushIntervalMs = DEFAULT_FLUSH_INTERVAL_MS,
maxBatchSize = DEFAULT_MAX_BATCH_SIZE,
bufferCapacity = DEFAULT_BUFFER_CAPACITY,
timeoutMs = DEFAULT_TIMEOUT_MS,
warnIntervalMs = DEFAULT_WARN_INTERVAL_MS,
onWarning = defaultWarning,
} = {}) {
this.#service = String(service);
this.#url = `${String(baseUrl).replace(/\/+$/, '')}/api/logs`;
this.#token = String(ingestToken);
this.#threshold = LEVEL_RANK.get(canonicalLevel(level)) ?? LEVEL_RANK.get('info');
this.#flushIntervalMs = positiveOr(flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS);
this.#maxBatchSize = Math.min(
MAX_BATCH_ENTRIES,
Math.max(1, Math.floor(positiveOr(maxBatchSize, DEFAULT_MAX_BATCH_SIZE))),
);
this.#bufferCapacity = Math.max(1, Math.floor(positiveOr(bufferCapacity, DEFAULT_BUFFER_CAPACITY)));
this.#timeoutMs = positiveOr(timeoutMs, DEFAULT_TIMEOUT_MS);
this.#warnIntervalMs = positiveOr(warnIntervalMs, DEFAULT_WARN_INTERVAL_MS);
this.#onWarning = typeof onWarning === 'function' ? onWarning : defaultWarning;
this.#timer = setInterval(() => this.#requestFlush(), this.#flushIntervalMs);
this.#timer.unref();
}
debug(...args) {
this.#emit('debug', args);
}
info(...args) {
this.#emit('info', args);
}
warn(...args) {
this.#emit('warn', args);
}
error(...args) {
this.#emit('error', args);
}
critical(...args) {
this.#emit('critical', args);
}
// log queues one entry. An optional context object is sent as the entry's context.
log(level, message, context) {
try {
this.#record(level, String(message), context);
} catch {
// Shipping must never fail the caller.
}
}
// flush sends everything buffered so far. It resolves once those sends have finished, and it
// never rejects.
flush() {
return this.#send();
}
// close drains the buffer and stops the periodic flush. Entries logged after close are dropped.
async close() {
this.#closed = true;
clearInterval(this.#timer);
await this.#send();
}
#emit(level, args) {
try {
this.#record(level, format(...args));
} catch {
// Shipping must never fail the caller.
}
}
#record(level, message, context) {
if (this.#closed) return;
const name = LOG_LEVELS.includes(canonicalLevel(level)) ? canonicalLevel(level) : 'info';
if (LEVEL_RANK.get(name) < this.#threshold) return;
if (this.#buffer.length >= this.#bufferCapacity) {
this.#warnOnce(`buffer full (cap=${this.#bufferCapacity}), dropping log entries for service "${this.#service}"`);
return;
}
// Each field is serialized on its own so the context can be spliced in as raw JSON.
const fields = [
`"service":${JSON.stringify(this.#service)}`,
`"level":${JSON.stringify(name)}`,
`"message":${JSON.stringify(clampMessage(message))}`,
];
const contextJson = serializeContext(context);
if (contextJson !== undefined) fields.push(`"context":${contextJson}`);
fields.push(`"occurred_at":${JSON.stringify(new Date().toISOString())}`);
this.#buffer.push(`{${fields.join(',')}}`);
if (this.#buffer.length >= this.#maxBatchSize) this.#requestFlush();
}
// requestFlush asks for a flush without waiting for it. A request made while one is already
// pending is dropped, so a burst of log calls queues at most one extra send.
#requestFlush() {
if (this.#flushRequested) return;
this.#flushRequested = true;
void this.#send();
}
#send() {
this.#chain = this.#chain.then(() => this.#sendBuffered()).catch(() => {});
return this.#chain;
}
async #sendBuffered() {
this.#flushRequested = false;
if (this.#buffer.length === 0) return;
const entries = this.#buffer;
this.#buffer = [];
let settled = 0; // entries of this flush that were sent or dropped
for (const batch of packBatches(entries, this.#maxBatchSize)) {
const retry = await this.#post(batch);
// A batch that may pass on a later attempt keeps itself and every later entry for the next
// flush. The rest of this flush is not sent now, so the entries still go out in order.
if (retry) {
this.#requeue(entries.slice(settled));
return;
}
settled += batch.length;
}
}
// requeue puts entries that failed to send back at the front of the buffer, so the next flush
// sends them before anything logged since. The buffer never grows past its capacity: when the
// waiting entries and the buffer do not all fit, the newest entries are dropped.
#requeue(entries) {
const combined = [...entries, ...this.#buffer];
const dropped = Math.max(0, combined.length - this.#bufferCapacity);
this.#buffer = combined.slice(0, this.#bufferCapacity);
if (dropped > 0) {
this.#warnOnce(`buffer full while retrying, dropping ${dropped} log entries for service "${this.#service}"`);
}
}
// post sends one batch and reports whether it must be sent again. That is true when no HTTP
// response came back, or the response was 429 or 5xx: those failures may pass. Any other non-2xx
// response is OmniLogger rejecting the batch, which a retry would not change, so it is warned
// about and dropped.
async #post(batch) {
const count = batch.length;
let response;
try {
response = await globalThis.fetch(this.#url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.#token}`,
},
body: `[${batch.join(',')}]`,
signal: AbortSignal.timeout(this.#timeoutMs),
});
} catch (err) {
const detail = err?.cause?.code ?? err?.message ?? String(err);
this.#warnOnce(`send ${count} entries to ${this.#url}, will retry: ${detail}`);
return true;
}
// Read the body so the connection can be reused. A failure here does not change the outcome.
await response.arrayBuffer().catch(() => {});
const { status } = response;
if (status >= 200 && status < 300) return false;
if (status === 429 || status >= 500) {
this.#warnOnce(`OmniLogger answered HTTP ${status} for ${count} entries, will retry`);
return true;
}
this.#warnOnce(`OmniLogger rejected ${count} entries: HTTP ${status}`);
return false;
}
#warnOnce(text) {
const now = Date.now();
if (this.#lastWarnAt !== null && now - this.#lastWarnAt < this.#warnIntervalMs) return;
this.#lastWarnAt = now;
try {
this.#onWarning(`[logshipper] ${text}`);
} catch {
// A broken warning sink must not fail the caller either.
}
}
}
// createLogShipperFromEnv returns a LogShipper for service when both OMNILOGGER_URL and
// OMNILOGGER_INGEST_TOKEN are set and non-empty, and null otherwise. A null result means shipping
// is disabled: no shipper, no network calls, and no extra output. Options other than env are passed
// to the LogShipper constructor.
export function createLogShipperFromEnv(service, { env = process.env, ...options } = {}) {
const baseUrl = String(env.OMNILOGGER_URL ?? '').trim();
const ingestToken = String(env.OMNILOGGER_INGEST_TOKEN ?? '').trim();
if (!baseUrl || !ingestToken) return null;
return new LogShipper({ ...options, baseUrl, ingestToken, service });
}
// mirrorConsole forwards each console.debug/log/info/warn/error call to the shipper at its level,
// after printing the line exactly as before. It returns a function that restores the original
// console methods. Call it once per shipper, or lines ship twice.
export function mirrorConsole(shipper, target = globalThis.console) {
const originals = new Map();
for (const [method, level] of CONSOLE_LEVELS) {
const original = target[method];
if (typeof original !== 'function') continue;
originals.set(method, original);
target[method] = function mirrored(...args) {
const result = original.apply(target, args);
shipper[level](...args);
return result;
};
}
return function restoreConsole() {
for (const [method, original] of originals) target[method] = original;
};
}
+11 -6
View File
@@ -24,19 +24,24 @@ export function totpProvisioningUri(issuer, account, secret) {
} }
export function verifyTotp(secret, token, now = Date.now()) { export function verifyTotp(secret, token, now = Date.now()) {
return verifyTotpStep(secret, token, now) !== null;
}
export function verifyTotpStep(secret, token, now = Date.now()) {
const normalizedSecret = normalizeSecret(secret); const normalizedSecret = normalizeSecret(secret);
const normalizedToken = normalizeToken(token); const normalizedToken = normalizeToken(token);
if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return false; if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return null;
let key; let key;
try { try {
key = decodeBase32(normalizedSecret); key = decodeBase32(normalizedSecret);
} catch { } catch {
return false; return null;
} }
if (key.length === 0) return false; if (key.length === 0) return null;
const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS); const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS);
for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset += 1) { // Prefer the current step if a six-digit collision occurs in the window.
for (const offset of [0, -1, 1]) {
if (period + offset < 0) continue; if (period + offset < 0) continue;
const counter = Buffer.alloc(8); const counter = Buffer.alloc(8);
counter.writeBigUInt64BE(BigInt(period + offset)); counter.writeBigUInt64BE(BigInt(period + offset));
@@ -47,9 +52,9 @@ export function verifyTotp(secret, token, now = Date.now()) {
| (digest[index + 2] << 8) | (digest[index + 2] << 8)
| digest[index + 3]; | digest[index + 3];
const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0'); const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0');
if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return true; if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return period + offset;
} }
return false; return null;
} }
function normalizeSecret(value) { function normalizeSecret(value) {
+25 -12
View File
@@ -12,7 +12,7 @@ import {
verifyPassword, verifyPassword,
verifyPasswordAsync, verifyPasswordAsync,
} from '../src/auth.js'; } from '../src/auth.js';
import { totpProvisioningUri, verifyTotp } from '../src/totp.js'; import { totpProvisioningUri, verifyTotp, verifyTotpStep } from '../src/totp.js';
test('reset codes are printed, case-insensitive, expiring, and one-time', () => { test('reset codes are printed, case-insensitive, expiring, and one-time', () => {
const messages = []; const messages = [];
@@ -38,9 +38,9 @@ test('password hashes verify and reject a different password', () => {
assert.equal(verifyPassword('wrong password', hash), false); assert.equal(verifyPassword('wrong password', hash), false);
}); });
test('new password hashes record their iteration count', () => { test('new password hashes use the shared bcrypt scheme and cost', () => {
const hash = hashPassword('correct horse battery staple'); const hash = hashPassword('correct horse battery staple');
assert.match(hash, /^pbkdf2-sha256\$600000\$[0-9a-f]{32}\$[0-9a-f]{64}$/); assert.match(hash, /^bcrypt\$\$2b\$12\$/);
}); });
test('legacy salt:hex hashes still verify at the original iteration count', () => { test('legacy salt:hex hashes still verify at the original iteration count', () => {
@@ -55,16 +55,16 @@ test('a hash with a malformed iteration count never verifies', () => {
assert.equal(verifyPassword('correct horse battery staple', 'pbkdf2-sha256$x$aa$bb'), false); assert.equal(verifyPassword('correct horse battery staple', 'pbkdf2-sha256$x$aa$bb'), false);
}); });
test('async password helpers produce and verify the same format', async () => { test('async password helpers produce and verify the same bcrypt format', async () => {
const hash = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 }); const hash = await hashPasswordAsync('correct horse battery staple');
assert.match(hash, /^pbkdf2-sha256\$1000\$/); assert.match(hash, /^bcrypt\$\$2b\$12\$/);
assert.equal(await verifyPasswordAsync('correct horse battery staple', hash), true); assert.equal(await verifyPasswordAsync('correct horse battery staple', hash), true);
assert.equal(await verifyPasswordAsync('wrong password', hash), false); assert.equal(await verifyPasswordAsync('wrong password', hash), false);
assert.equal(verifyPassword('correct horse battery staple', hash), true); assert.equal(verifyPassword('correct horse battery staple', hash), true);
}); });
test('formats this module does not verify fail closed', () => { test('formats this module does not verify fail closed', () => {
for (const stored of ['', '$2b$12$abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQ', 'bcrypt$$2a$12$abc', 'pbkdf2-sha256$600000$00$00$extra']) { for (const stored of ['', '$2b$12$abc', 'bcrypt$$2a$12$abc', 'bcrypt-sha256$$2b$12$abc', 'pbkdf2-sha256$600000$00$00$extra']) {
assert.equal(verifyPassword('correct horse battery staple', stored), false); assert.equal(verifyPassword('correct horse battery staple', stored), false);
} }
assert.equal(passwordHashNeedsUpgrade('$2b$12$abc'), true); assert.equal(passwordHashNeedsUpgrade('$2b$12$abc'), true);
@@ -77,15 +77,27 @@ test('a legacy salt:hex hash is rewritten in the current scheme after a successf
const result = await verifyAndUpgradePasswordAsync('legacy password', legacy); const result = await verifyAndUpgradePasswordAsync('legacy password', legacy);
assert.equal(result.valid, true); assert.equal(result.valid, true);
assert.match(result.upgradedHash, /^pbkdf2-sha256\$600000\$/); assert.match(result.upgradedHash, /^bcrypt\$\$2b\$12\$/);
assert.equal(passwordHashNeedsUpgrade(result.upgradedHash), false); assert.equal(passwordHashNeedsUpgrade(result.upgradedHash), false);
assert.equal(verifyPassword('legacy password', result.upgradedHash), true); assert.equal(verifyPassword('legacy password', result.upgradedHash), true);
}); });
test('a hash below the current iteration count is rewritten, and a short legacy password still upgrades', async () => { test('a long legacy PBKDF2 password is migrated without truncation', async () => {
const low = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 }); const longPassword = 'a'.repeat(80);
const salt = crypto.randomBytes(16).toString('hex');
const legacy = `pbkdf2-sha256$600000$${salt}$${crypto.pbkdf2Sync(longPassword, salt, 600000, 32, 'sha256').toString('hex')}`;
const result = await verifyAndUpgradePasswordAsync(longPassword, legacy);
assert.equal(result.valid, true);
assert.match(result.upgradedHash, /^bcrypt-sha256\$\$2b\$12\$/);
assert.equal(await verifyPasswordAsync(longPassword, result.upgradedHash), true);
assert.equal(await verifyPasswordAsync(`${longPassword}x`, result.upgradedHash), false);
});
test('a low-cost bcrypt hash is rewritten, and a short legacy password still upgrades', async () => {
const bcrypt = (await import('bcryptjs')).default;
const low = `bcrypt$${await bcrypt.hash('correct horse battery staple', 4)}`;
const lowResult = await verifyAndUpgradePasswordAsync('correct horse battery staple', low); const lowResult = await verifyAndUpgradePasswordAsync('correct horse battery staple', low);
assert.match(lowResult.upgradedHash, /^pbkdf2-sha256\$600000\$/); assert.match(lowResult.upgradedHash, /^bcrypt\$\$2b\$12\$/);
const salt = crypto.randomBytes(16).toString('hex'); const salt = crypto.randomBytes(16).toString('hex');
const shortLegacy = `${salt}:${crypto.pbkdf2Sync('short', salt, 100000, 32, 'sha256').toString('hex')}`; const shortLegacy = `${salt}:${crypto.pbkdf2Sync('short', salt, 100000, 32, 'sha256').toString('hex')}`;
@@ -95,7 +107,7 @@ test('a hash below the current iteration count is rewritten, and a short legacy
}); });
test('a wrong password neither verifies nor upgrades, and a current hash is not rewritten', async () => { test('a wrong password neither verifies nor upgrades, and a current hash is not rewritten', async () => {
const hash = await hashPasswordAsync('correct horse battery staple', { iterations: 1000 }); const hash = await hashPasswordAsync('correct horse battery staple');
assert.deepEqual(await verifyAndUpgradePasswordAsync('wrong password', hash), { valid: false, upgradedHash: null }); assert.deepEqual(await verifyAndUpgradePasswordAsync('wrong password', hash), { valid: false, upgradedHash: null });
const current = await hashPasswordAsync('correct horse battery staple'); const current = await hashPasswordAsync('correct horse battery staple');
@@ -117,6 +129,7 @@ test('TOTP verifies RFC 6238 SHA-1 vectors', () => {
]; ];
for (const [seconds, code] of vectors) { for (const [seconds, code] of vectors) {
assert.equal(verifyTotp(secret, code, seconds * 1000), true); assert.equal(verifyTotp(secret, code, seconds * 1000), true);
assert.equal(verifyTotpStep(secret, code, seconds * 1000), Math.floor(seconds / 30));
} }
assert.match(totpProvisioningUri('Example App', 'admin@example.com', secret), /^otpauth:\/\/totp\//); assert.match(totpProvisioningUri('Example App', 'admin@example.com', secret), /^otpauth:\/\/totp\//);
}); });
+35 -1
View File
@@ -10,7 +10,7 @@ function fakeDatabase({ rowCount = 1, totpEnabled = false, rowsByCondition = {}
async query(text, params = []) { async query(text, params = []) {
queries.push({ text, params }); queries.push({ text, params });
if (text.includes('totp_enabled, false) AS enabled')) { if (text.includes('totp_enabled, false) AS enabled')) {
return { rows: [{ secret: 'S', enabled: totpEnabled }], rowCount: 1 }; return { rows: [{ secret: 'S', enabled: totpEnabled, last_used_step: -1 }], rowCount: 1 };
} }
for (const [condition, row] of Object.entries(rowsByCondition)) { for (const [condition, row] of Object.entries(rowsByCondition)) {
if (text.includes(condition)) return { rows: [row], rowCount: 1 }; if (text.includes(condition)) return { rows: [row], rowCount: 1 };
@@ -27,6 +27,7 @@ test('ensureSchema requests the case-insensitive username index, only while no c
assert.match(statements, /auth_users_username_lower_idx/); assert.match(statements, /auth_users_username_lower_idx/);
assert.match(statements, /lower\(username\)/); assert.match(statements, /lower\(username\)/);
assert.match(statements, /HAVING count\(\*\) > 1/); assert.match(statements, /HAVING count\(\*\) > 1/);
assert.match(statements, /ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1/);
}); });
test('setTotpSecret refuses to replace an enabled second factor', async () => { test('setTotpSecret refuses to replace an enabled second factor', async () => {
@@ -41,6 +42,39 @@ test('setTotpSecret stores a pending secret while TOTP is off, and ignores an un
await new AuthStore(fakeDatabase({ rowCount: 0 })).setTotpSecret(2, 'NEWSECRET'); await new AuthStore(fakeDatabase({ rowCount: 0 })).setTotpSecret(2, 'NEWSECRET');
}); });
test('TOTP enrollment records its code step and a replay is rejected atomically', async () => {
const state = { secret: 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', enabled: false, last_used_step: -1 };
const database = {
async query(text, params = []) {
if (text.startsWith('SELECT COALESCE(totp_secret')) {
return { rows: [{ ...state }], rowCount: 1 };
}
const [step, , secret] = params;
if (text.includes('SET totp_enabled = true')) {
if (!state.enabled && secret === state.secret && state.last_used_step < step) {
state.enabled = true;
state.last_used_step = step;
return { rows: [], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
}
if (text.includes('SET last_used_step = $1')) {
if (state.enabled && secret === state.secret && state.last_used_step < step) {
state.last_used_step = step;
return { rows: [], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
}
throw new Error(`unexpected query: ${text}`);
},
};
const store = new AuthStore(database);
assert.equal(await store.enableTotp(1, '287082', 59000), true);
assert.equal(state.last_used_step, 1);
assert.equal(await store.consumeTotpCode(1, '287082', 59000), false);
assert.equal(state.last_used_step, 1);
});
test('credential writes refuse an empty hash and a username containing @', async () => { test('credential writes refuse an empty hash and a username containing @', async () => {
const database = fakeDatabase(); const database = fakeDatabase();
const store = new AuthStore(database); const store = new AuthStore(database);
+24 -6
View File
@@ -2,7 +2,8 @@ import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs'; import { existsSync, readFileSync } from 'node:fs';
import { hashPassword, passwordHashNeedsUpgrade, verifyAndUpgradePasswordAsync, verifyPassword } from '../src/auth.js'; import { hashPassword, passwordHashNeedsUpgrade, verifyAndUpgradePasswordAsync, verifyPassword } from '../src/auth.js';
import { verifyTotp } from '../src/totp.js'; import { verifyTotp, verifyTotpStep } from '../src/totp.js';
import { EXAMPLE_INTERNAL_SECRETS, MIN_INTERNAL_SECRET_LENGTH, internalSecretMatches } from '../src/coreconfig.js';
// The Go, Node and Python auth helpers load the same fixtures; see "description" in the file. // The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
const contractUrl = new URL('../../../contract/auth-contract.json', import.meta.url); const contractUrl = new URL('../../../contract/auth-contract.json', import.meta.url);
@@ -12,14 +13,16 @@ const skip = contract ? false : 'contract/auth-contract.json is not part of this
test('password hashes verify as the contract says for Node', { skip }, async () => { test('password hashes verify as the contract says for Node', { skip }, async () => {
const { plaintext, wrongPassword, hashes } = contract.password; const { plaintext, wrongPassword, hashes } = contract.password;
for (const entry of hashes) { for (const entry of hashes) {
assert.equal(verifyPassword(plaintext, entry.hash), entry.verifies.node, entry.name); const password = entry.password ?? plaintext;
assert.equal(verifyPassword(wrongPassword, entry.hash), false, `${entry.name}: wrong password`); const rejectedPassword = entry.wrongPassword ?? wrongPassword;
assert.equal(verifyPassword(password, entry.hash), entry.verifies.node, entry.name);
assert.equal(verifyPassword(rejectedPassword, entry.hash), false, `${entry.name}: wrong password`);
if ('node' in (entry.needsUpgrade ?? {})) { if ('node' in (entry.needsUpgrade ?? {})) {
assert.equal(passwordHashNeedsUpgrade(entry.hash), entry.needsUpgrade.node, `${entry.name}: needs upgrade`); assert.equal(passwordHashNeedsUpgrade(entry.hash), entry.needsUpgrade.node, `${entry.name}: needs upgrade`);
const { valid, upgradedHash } = await verifyAndUpgradePasswordAsync(plaintext, entry.hash); const { valid, upgradedHash } = await verifyAndUpgradePasswordAsync(password, entry.hash);
assert.equal(valid, true, `${entry.name}: valid on upgrade`); assert.equal(valid, true, `${entry.name}: valid on upgrade`);
assert.equal(upgradedHash !== null, entry.needsUpgrade.node, `${entry.name}: upgraded hash`); assert.equal(upgradedHash !== null, entry.needsUpgrade.node, `${entry.name}: upgraded hash`);
if (upgradedHash) assert.equal(verifyPassword(plaintext, upgradedHash), true); if (upgradedHash) assert.equal(verifyPassword(password, upgradedHash), true);
} }
} }
}); });
@@ -28,7 +31,7 @@ test('the password length contract holds for Node', { skip }, () => {
const { bytes, accepted } = contract.password.tooLongToHash; const { bytes, accepted } = contract.password.tooLongToHash;
let didHash = true; let didHash = true;
try { try {
hashPassword('a'.repeat(bytes), { iterations: 1000 }); hashPassword('a'.repeat(bytes));
} catch { } catch {
didHash = false; didHash = false;
} }
@@ -39,5 +42,20 @@ test('TOTP verifies as the contract says', { skip }, () => {
for (const entry of contract.totp.cases) { for (const entry of contract.totp.cases) {
const secret = entry.secret ?? contract.totp.secret; const secret = entry.secret ?? contract.totp.secret;
assert.equal(verifyTotp(secret, entry.code, entry.unix * 1000), entry.valid, entry.name); assert.equal(verifyTotp(secret, entry.code, entry.unix * 1000), entry.valid, entry.name);
if (entry.valid)
assert.equal(
verifyTotpStep(secret, entry.code, entry.unix * 1000),
entry.matchedStep ?? Math.floor(entry.unix / 30),
entry.name,
);
}
});
test('the internal secret gate matches the contract for Node', { skip }, () => {
const rule = contract.internalSecret;
assert.equal(MIN_INTERNAL_SECRET_LENGTH, rule.minLength);
assert.deepEqual([...EXAMPLE_INTERNAL_SECRETS].sort(), [...rule.placeholders].sort());
for (const entry of rule.cases) {
assert.equal(internalSecretMatches(entry.provided, entry.secret), entry.matches, entry.name);
} }
}); });
+28 -4
View File
@@ -1,6 +1,13 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { Info, Store, internalSecretMatches } from '../src/coreconfig.js'; import {
EXAMPLE_INTERNAL_SECRETS,
Info,
MIN_INTERNAL_SECRET_LENGTH,
Store,
internalSecretMatches,
internalSecretUsable,
} from '../src/coreconfig.js';
test('store seeds from the fallback Info', () => { test('store seeds from the fallback Info', () => {
const store = new Store({ authGuardUrl: 'http://auth.example.com', carrierNodeUrl: 'http://carrier.example.com' }); const store = new Store({ authGuardUrl: 'http://auth.example.com', carrierNodeUrl: 'http://carrier.example.com' });
@@ -49,13 +56,30 @@ test('Info.fromJSON/toJSON round-trip the wire shape', () => {
assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com'); assert.equal(info.toJSON().carrierNodeUrl, 'http://carrier.example.com');
}); });
const LONG_SECRET = 'shared-secret-value';
test('internal secret check fails closed when the secret is unset or empty', () => { test('internal secret check fails closed when the secret is unset or empty', () => {
assert.equal(internalSecretMatches(undefined, undefined), false); assert.equal(internalSecretMatches(undefined, undefined), false);
assert.equal(internalSecretMatches(undefined, ''), false); assert.equal(internalSecretMatches(undefined, ''), false);
assert.equal(internalSecretMatches('', ''), false); assert.equal(internalSecretMatches('', ''), false);
assert.equal(internalSecretMatches(undefined, 'shared-secret'), false); assert.equal(internalSecretMatches(undefined, LONG_SECRET), false);
assert.equal(internalSecretMatches('shared-secreT', 'shared-secret'), false); assert.equal(internalSecretMatches('shared-secret-valuE', LONG_SECRET), false);
assert.equal(internalSecretMatches('shared-secret', 'shared-secret'), true); assert.equal(internalSecretMatches(LONG_SECRET, LONG_SECRET), true);
});
test('internal secret check refuses a short or placeholder secret', () => {
const short = 'x'.repeat(MIN_INTERNAL_SECRET_LENGTH - 1);
assert.equal(internalSecretMatches(short, short), false);
for (const placeholder of EXAMPLE_INTERNAL_SECRETS) {
assert.equal(internalSecretMatches(placeholder, placeholder), false, placeholder);
}
});
test('internal secret usability needs the minimum length and no placeholder', () => {
assert.equal(internalSecretUsable('x'.repeat(MIN_INTERNAL_SECRET_LENGTH - 1)), false);
assert.equal(internalSecretUsable('x'.repeat(MIN_INTERNAL_SECRET_LENGTH)), true);
assert.equal(internalSecretUsable('change-me-to-a-long-random-value'), false);
assert.equal(internalSecretUsable(undefined), false);
}); });
test('set rejects a URL that is not an http or https URL and changes nothing', () => { test('set rejects a URL that is not an http or https URL and changes nothing', () => {
@@ -0,0 +1,544 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { createServer } from 'node:http';
import { createLogShipperFromEnv, LogShipper, mirrorConsole } from '../src/logshipper.js';
// startSink runs a local stand-in for OmniLogger that records every request it receives. The first
// requests get the answers in `statuses`, in order: a status code, or null to drop the connection
// without answering. Later requests get `status`. When `gate` is given, each answer waits for it.
async function startSink({ status = 202, statuses = [], gate } = {}) {
const requests = [];
const server = createServer((req, res) => {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', async () => {
const answer = statuses.length > 0 ? statuses.shift() : status;
requests.push({
method: req.method,
path: req.url,
authorization: req.headers.authorization,
contentType: req.headers['content-type'],
status: answer,
accepted: answer >= 200 && answer < 300,
body: JSON.parse(Buffer.concat(chunks).toString('utf8')),
});
await gate;
if (answer === null) {
req.socket.destroy();
return;
}
res.writeHead(answer, { 'Content-Type': 'text/plain' });
res.end('ok');
});
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
return {
url: `http://127.0.0.1:${server.address().port}`,
requests,
// entries returns what OmniLogger accepted, in the order it was sent.
entries: () => requests.filter((request) => request.accepted).flatMap((request) => request.body),
close: async () => {
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
},
};
}
async function waitFor(check) {
const deadline = Date.now() + 5000;
while (!check()) {
if (Date.now() > deadline) assert.fail('condition not met within 5s');
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
function shipperFor(sink, options = {}) {
return new LogShipper({
baseUrl: sink.url,
ingestToken: 'secret',
service: 'svc',
flushIntervalMs: 60_000,
onWarning: () => {},
...options,
});
}
test('shipping is disabled unless both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are non-empty', async (t) => {
const sink = await startSink();
t.after(() => sink.close());
const envs = [
{},
{ OMNILOGGER_URL: sink.url },
{ OMNILOGGER_INGEST_TOKEN: 'secret' },
{ OMNILOGGER_URL: '', OMNILOGGER_INGEST_TOKEN: 'secret' },
{ OMNILOGGER_URL: sink.url, OMNILOGGER_INGEST_TOKEN: ' ' },
];
for (const env of envs) {
assert.equal(createLogShipperFromEnv('svc', { env }), null, JSON.stringify(env));
}
});
test('a disabled service makes no calls and prints nothing extra', async (t) => {
const sink = await startSink();
t.after(() => sink.close());
const local = [];
const target = { log: (...args) => local.push(args) };
const shipper = createLogShipperFromEnv('svc', { env: { OMNILOGGER_URL: sink.url } });
if (shipper) mirrorConsole(shipper, target);
target.log('still local');
await new Promise((resolve) => setTimeout(resolve, 20));
assert.equal(shipper, null);
assert.deepEqual(local, [['still local']]);
assert.equal(sink.requests.length, 0);
});
test('createLogShipperFromEnv ships to the trimmed URL with the token and service name', async (t) => {
const sink = await startSink();
const shipper = createLogShipperFromEnv('mediadesktop', {
env: { OMNILOGGER_URL: ` ${sink.url}/ `, OMNILOGGER_INGEST_TOKEN: ' secret-token ' },
flushIntervalMs: 60_000,
onWarning: () => {},
});
t.after(async () => {
await shipper.close();
await sink.close();
});
assert.ok(shipper instanceof LogShipper);
shipper.info('from env');
await shipper.flush();
assert.equal(sink.requests.length, 1);
assert.equal(sink.requests[0].authorization, 'Bearer secret-token');
assert.equal(sink.requests[0].body[0].service, 'mediadesktop');
});
test('posts to /api/logs with the ingest token as a bearer credential', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { baseUrl: `${sink.url}///`, ingestToken: 'secret-token' });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.warn('hello');
await shipper.flush();
const [request] = sink.requests;
assert.equal(request.method, 'POST');
assert.equal(request.path, '/api/logs');
assert.equal(request.authorization, 'Bearer secret-token');
assert.equal(request.contentType, 'application/json');
});
test('every entry carries the service name, a level and an RFC 3339 UTC timestamp', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { service: 'mediadesktop', level: 'debug' });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.debug('d');
shipper.critical('c');
await shipper.flush();
const entries = sink.entries();
assert.deepEqual(
entries.map((e) => [e.service, e.level]),
[
['mediadesktop', 'debug'],
['mediadesktop', 'critical'],
],
);
for (const entry of entries) {
assert.match(entry.occurred_at, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
}
});
test('flush sends everything buffered in one request, in order', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('one');
shipper.info('two');
shipper.info('three');
await shipper.flush();
await shipper.flush(); // nothing left, so no second request
assert.equal(sink.requests.length, 1);
assert.deepEqual(
sink.requests[0].body.map((e) => e.message),
['one', 'two', 'three'],
);
});
test('the periodic interval sends entries without an explicit flush', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { flushIntervalMs: 20 });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('tick');
await waitFor(() => sink.entries().length === 1);
assert.equal(sink.entries()[0].message, 'tick');
});
test('reaching the batch size flushes ahead of the interval', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { maxBatchSize: 3 });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('a');
shipper.info('b');
await new Promise((resolve) => setTimeout(resolve, 50));
assert.equal(sink.requests.length, 0, 'two entries are below the batch size');
shipper.info('c');
await waitFor(() => sink.requests.length === 1);
assert.deepEqual(
sink.requests[0].body.map((e) => e.message),
['a', 'b', 'c'],
);
});
test('a backlog larger than one batch is split into requests of at most the batch size', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { maxBatchSize: 2 });
t.after(async () => {
await shipper.close();
await sink.close();
});
for (let i = 0; i < 5; i += 1) shipper.info(`m${i}`);
await shipper.flush();
assert.ok(sink.requests.every((request) => request.body.length <= 2));
assert.deepEqual(
sink.entries().map((e) => e.message),
['m0', 'm1', 'm2', 'm3', 'm4'],
);
});
test('the level threshold gates entries, and its aliases and unknown names resolve', async (t) => {
const sink = await startSink();
t.after(() => sink.close());
const cases = [
{ service: 'warning-alias', level: 'warning', kept: ['warn', 'error', 'critical'] },
{ service: 'silent-alias', level: 'off', kept: [] },
{ service: 'unknown-name', level: 'bogus', kept: ['info', 'warn', 'error', 'critical'] },
];
for (const { service, level, kept } of cases) {
const shipper = shipperFor(sink, { service, level });
shipper.debug('debug');
shipper.info('info');
shipper.warn('warn');
shipper.error('error');
shipper.critical('critical');
await shipper.close();
const messages = sink
.entries()
.filter((e) => e.service === service)
.map((e) => e.message);
assert.deepEqual(messages, kept, `level ${level}`);
}
});
test('console calls are mirrored at their levels and still printed locally', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink, { level: 'debug' });
t.after(async () => {
await shipper.close();
await sink.close();
});
const local = [];
const target = {};
for (const method of ['debug', 'log', 'info', 'warn', 'error']) {
target[method] = (...args) => local.push([method, ...args]);
}
const originals = { ...target };
const restore = mirrorConsole(shipper, target);
target.debug('d');
target.log('l', 1);
target.info('i');
target.warn('w');
target.error('e', { a: 1 });
restore();
assert.deepEqual(target, originals, 'restore puts the original methods back');
await shipper.flush();
assert.deepEqual(local, [
['debug', 'd'],
['log', 'l', 1],
['info', 'i'],
['warn', 'w'],
['error', 'e', { a: 1 }],
]);
assert.deepEqual(
sink.entries().map((e) => [e.level, e.message]),
[
['debug', 'd'],
['info', 'l 1'],
['info', 'i'],
['warn', 'w'],
['error', 'e { a: 1 }'],
],
);
});
test('a message over 8192 bytes is cut on a character boundary and marked', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
// Four-byte characters after one ASCII byte: the cut position falls inside a character.
const long = `a${'\u{1F600}'.repeat(3000)}`;
shipper.info(long);
shipper.info('short');
await shipper.flush();
const [clamped, short] = sink.entries().map((e) => e.message);
assert.ok(Buffer.byteLength(clamped, 'utf8') <= 8192);
assert.ok(clamped.endsWith(' [truncated]'));
assert.ok(!clamped.includes('�'), 'the cut split a character');
assert.ok(long.startsWith(clamped.slice(0, -' [truncated]'.length)));
assert.equal(short, 'short');
});
test('an oversized context or one with a NUL escape is replaced by the dropped marker', async (t) => {
const sink = await startSink();
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
const fits = { blob: 'x'.repeat(16 * 1024 - JSON.stringify({ blob: '' }).length) };
shipper.log('info', 'fits', fits);
shipper.log('info', 'too big', { blob: 'x'.repeat(16 * 1024) });
shipper.log('info', 'nul', { s: 'a\u0000b' });
shipper.log('info', 'small', { ok: true, n: 1 });
shipper.log('info', 'no context');
await shipper.flush();
const [a, b, c, d, e] = sink.entries();
assert.deepEqual(a.context, fits);
assert.deepEqual(b.context, { context_dropped: true });
assert.deepEqual(c.context, { context_dropped: true });
assert.deepEqual(d.context, { ok: true, n: 1 });
assert.equal('context' in e, false);
assert.equal(b.message, 'too big');
});
test('a full buffer drops new entries with one warning instead of blocking', async (t) => {
const sink = await startSink();
const warnings = [];
const shipper = shipperFor(sink, { bufferCapacity: 3, onWarning: (text) => warnings.push(text) });
t.after(async () => {
await shipper.close();
await sink.close();
});
for (let i = 0; i < 10; i += 1) shipper.info(`m${i}`);
await shipper.flush();
assert.deepEqual(
sink.entries().map((e) => e.message),
['m0', 'm1', 'm2'],
);
assert.equal(warnings.length, 1);
assert.match(warnings[0], /buffer full/);
});
test('a 503 on the first send is retried, and each entry arrives exactly once and in order', async (t) => {
const sink = await startSink({ statuses: [503] });
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('a');
shipper.info('b');
await shipper.flush(); // refused with 503, so both entries stay buffered
await shipper.flush(); // accepted
await shipper.flush(); // nothing left to send
assert.deepEqual(
sink.requests.map((request) => request.status),
[503, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['a', 'b'],
);
});
test('a dropped connection is retried like a server error', async (t) => {
const sink = await startSink({ statuses: [null] });
const shipper = shipperFor(sink);
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('a');
await shipper.flush(); // no response at all, so the entry stays buffered
await shipper.flush();
assert.deepEqual(
sink.requests.map((request) => request.status),
[null, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['a'],
);
});
test('a 400 is dropped and not retried', async (t) => {
const sink = await startSink({ statuses: [400] });
const warnings = [];
const shipper = shipperFor(sink, { onWarning: (text) => warnings.push(text) });
t.after(async () => {
await shipper.close();
await sink.close();
});
shipper.info('rejected');
await shipper.flush();
await shipper.flush(); // nothing was kept, so nothing is sent again
shipper.info('next');
await shipper.flush();
assert.deepEqual(
sink.requests.map((request) => request.status),
[400, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['next'],
);
assert.equal(warnings.length, 1);
assert.match(warnings[0], /rejected 1 entries: HTTP 400/);
});
test('a failed batch holds back the rest of its flush, and they are sent again in order', async (t) => {
const sink = await startSink({ statuses: [202, 503] });
const shipper = shipperFor(sink, { maxBatchSize: 2 });
t.after(async () => {
await shipper.close();
await sink.close();
});
for (let i = 0; i < 5; i += 1) shipper.info(`m${i}`);
// Reaching the batch size starts a background flush of all five entries: [m0, m1] is accepted,
// [m2, m3] is refused, and [m4] must not be attempted.
await waitFor(() => sink.requests.length === 2);
await new Promise((resolve) => setTimeout(resolve, 50));
assert.equal(sink.requests.length, 2, 'm4 waits for the next flush');
await shipper.flush(); // [m2, m3], then [m4]
assert.deepEqual(
sink.requests.map((request) => request.status),
[202, 503, 202, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['m0', 'm1', 'm2', 'm3', 'm4'],
);
});
test('during an outage the buffer holds at most its capacity, keeping the oldest entries', async (t) => {
const sink = await startSink({ statuses: [503, 503] });
const shipper = shipperFor(sink, { bufferCapacity: 3 });
t.after(async () => {
await shipper.close();
await sink.close();
});
for (const m of ['a', 'b', 'c']) shipper.info(m);
await shipper.flush(); // refused, so a, b and c stay buffered
for (const m of ['d', 'e']) shipper.info(m); // the buffer is full, so these are dropped
await shipper.flush(); // still refused
await shipper.flush(); // the outage is over
assert.ok(sink.requests.every((request) => request.body.length <= 3));
assert.deepEqual(
sink.requests.map((request) => request.status),
[503, 503, 202],
);
assert.deepEqual(
sink.entries().map((e) => e.message),
['a', 'b', 'c'],
);
});
test('a retry that does not fit beside new entries drops the newest ones', async (t) => {
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
const sink = await startSink({ statuses: [503], gate });
const shipper = shipperFor(sink, { bufferCapacity: 3 });
t.after(async () => {
release();
await shipper.close();
await sink.close();
});
shipper.info('a');
shipper.info('b');
const sending = shipper.flush();
await waitFor(() => sink.requests.length === 1);
// While a and b are in flight, x, y and z fill the buffer. When the refusal arrives, a and b go back
// in front of them, so only a, b and x fit and y and z are dropped.
for (const m of ['x', 'y', 'z']) shipper.info(m);
release();
await sending;
await shipper.flush();
assert.deepEqual(
sink.entries().map((e) => e.message),
['a', 'b', 'x'],
);
});
test('a rejecting or unreachable OmniLogger never throws, and warnings are rate-limited', async (t) => {
const rejecting = await startSink({ status: 400 });
const warnings = [];
const shipper = shipperFor(rejecting, { onWarning: (text) => warnings.push(text) });
t.after(async () => {
await shipper.close();
await rejecting.close();
});
shipper.info('one');
await shipper.flush();
shipper.info('two');
await shipper.flush();
assert.equal(warnings.filter((text) => text.includes('rejected')).length, 1);
const unreachable = shipperFor({ url: 'http://127.0.0.1:1' }, { onWarning: (text) => warnings.push(text) });
unreachable.info('lost');
await unreachable.flush();
await unreachable.close();
assert.ok(warnings.some((text) => text.includes('send 1 entries')));
const malformed = shipperFor({ url: 'not a url' }, { onWarning: (text) => warnings.push(text) });
malformed.info('lost');
await malformed.flush();
await malformed.close();
});
test('close sends what is left, and entries logged after it are dropped', async (t) => {
const sink = await startSink();
t.after(() => sink.close());
const shipper = shipperFor(sink);
shipper.info('last');
await shipper.close();
assert.deepEqual(
sink.entries().map((e) => e.message),
['last'],
);
shipper.info('after close');
await shipper.flush();
await shipper.close();
assert.equal(sink.entries().length, 1);
});
test('the periodic flush timer does not keep the process alive', () => {
const moduleUrl = new URL('../src/logshipper.js', import.meta.url).href;
const script = `
import { LogShipper } from ${JSON.stringify(moduleUrl)};
new LogShipper({ baseUrl: 'http://127.0.0.1:1', ingestToken: 't', service: 's', flushIntervalMs: 3600000 });
`;
const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
encoding: 'utf8',
timeout: 10_000,
});
assert.equal(result.signal, null, 'the process was kept alive by the timer');
assert.equal(result.status, 0, result.stderr);
});
+87 -9
View File
@@ -110,7 +110,8 @@ give it, and updated live whenever ProjectConfigurator pushes a fresh
`PUT /api/core-services/internal`. A service wires the actual route itself: `PUT /api/core-services/internal`. A service wires the actual route itself:
```python ```python
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, internal_secret_matches from fastapi.responses import JSONResponse
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, handle_core_services_push
auth_client = AuthClient("") # pending: no URL yet, still safe to use auth_client = AuthClient("") # pending: no URL yet, still safe to use
core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url="")) core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url=""))
@@ -118,17 +119,47 @@ core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url)
# in your framework's route for PUT /api/core-services/internal: # in your framework's route for PUT /api/core-services/internal:
@app.put("/api/core-services/internal")
async def push_core_services(request): async def push_core_services(request):
if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET): status, body = handle_core_services_push(
raise HTTPException(status_code=401) core_config, SECRET, request.headers.get("X-Internal-Auth"), await request.body()
body = await request.json() )
try: return JSONResponse(body, status_code=status)
info = core_config.set(CoreConfigInfo.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()}
``` ```
`handle_core_services_push` is the framework-neutral body of the route. It returns
`(status, body)`, so any framework can send it, and it does the checks in this order:
- `X-Internal-Auth` must equal SECRET, compared in constant time, or the response is
401 `{"error": "internal service authentication required"}`. A SECRET that is not usable
(see below) gets 401 for every caller.
- A body over 4096 bytes, or one that is not a JSON object, gets 400
`{"error": "invalid JSON body"}`.
- A non-empty `omniLoggerUrl`, `authGuardUrl` or `carrierNodeUrl(s)` that is not an http or
https URL with a host gets 400 `{"error": "core service URL must be an http or https URL with a host"}`.
- Otherwise it returns 200 `{"ok": true}`. The response never includes the ingest token.
Other fields are ignored.
The store keeps the last non-empty value of each field, so a partial push never clears a stored
one. OmniLogger's URL and this service's ingest token (`CoreConfigInfo.omni_logger_url` and
`omni_logger_ingest_token`) are not used by the store's AuthGuard or CarrierNode logic. A
log shipper follows them through `follow_omnilogger`:
```python
shipper = Shipper.from_env("myservice") or Shipper(base_url="", ingest_token="", service="myservice")
follow_omnilogger(core_config, shipper) # once, at startup; later pushes call shipper.set_credentials
```
`follow_omnilogger` calls `shipper.set_credentials(url, token)` after a push, but only once
both values are stored, so a token-only push never disables or re-points the shipper.
Don't seed the store with `OMNILOGGER_*` values from the environment. Those belong to the
shipper, and seeding them would make a token-only push re-point it.
`internal_secret_matches` also refuses a SECRET shorter than `MIN_INTERNAL_SECRET_LENGTH`
(16 characters) or equal to an example placeholder (`EXAMPLE_INTERNAL_SECRETS`), so every
internal route gated by it rejects all callers until the secret is set properly. Call
`internal_secret_usable(SECRET)` at startup to log a warning for that case.
## `authproxy`: a ready-to-mount FastAPI router (optional) ## `authproxy`: a ready-to-mount FastAPI router (optional)
Wiring up `authclient` still leaves each service reimplementing the same Wiring up `authclient` still leaves each service reimplementing the same
@@ -186,3 +217,50 @@ This mounts `/status`, `/me` (GET/PUT), `/admin-needed`, `/setup`, `/login`,
— the same URL paths and JSON response shapes as `shared/backend/auth` — the same URL paths and JSON response shapes as `shared/backend/auth`
(Go)'s `Service`, so a project migrating onto this module gets the same (Go)'s `Service`, so a project migrating onto this module gets the same
standardized wire format that Go consumers of that engine already have. standardized wire format that Go consumers of that engine already have.
## `logshipper`: mirroring logs to OmniLogger
`shared_backend.logshipper` is the Python counterpart of `shared/backend/logshipper`
(Go): it sends log entries to the workspace's central OmniLogger, and it is additive.
A service keeps its console logging as it is and adds an `OmniLoggerHandler` beside
its existing handlers, so each record also reaches OmniLogger:
```python
import logging
from shared_backend import OmniLoggerHandler, Shipper
shipper = Shipper.from_env("myservice", level="info") # None unless both env vars are set
if shipper is not None:
logging.getLogger().addHandler(OmniLoggerHandler(shipper))
...
if shipper is not None:
shipper.close() # on graceful shutdown; also runs at interpreter exit
```
`from_env` reads `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` and returns `None` when
either is unset or empty, so a disabled service makes no network calls and logs
exactly as before. The `level` argument is the threshold (`debug`, `info`, `warn`,
`error`, `critical`, or `silent`); it defaults to `info`.
`set_credentials(base_url, token)` changes where entries are sent, and the ingest token
used, while the service runs. It is thread-safe and takes effect from the next flush, and
the background thread keeps running. An empty base URL or token disables shipping: entries
are no longer buffered, anything already buffered is dropped, and console output is
unchanged. `Shipper(base_url="", ingest_token="", service=...)` builds a disabled shipper
up front, so a push from ProjectConfigurator can enable it later (see `coreconfig` above).
The handler maps `DEBUG`, `INFO`, `WARNING`, `ERROR` and `CRITICAL` to `debug`, `info`,
`warn`, `error` and `critical`. Entries are batched in a daemon thread and sent every 2
seconds, or as soon as 100 are buffered, with a 5-second HTTP timeout and bearer auth.
The buffer holds 2000 entries and drops new ones when full. Failures and drops are
reported on stderr at most once a minute and never raise into the caller.
Entries are clamped before buffering, because OmniLogger rejects a whole batch when
one entry breaks a limit. A message over 8192 bytes is cut on a character boundary
and given a ` [truncated]` suffix. A context over 16384 bytes, or one containing a NUL,
becomes `{"context_dropped":true}`. A NUL in a message is written as the text `\u0000`.
Batches are split to stay within 1000 entries and under 2 MiB per request. `Shipper`
never prints, so the service's own console output is unchanged.
+1
View File
@@ -22,6 +22,7 @@ dependencies = [
# consumer does) satisfies this from its own requirements regardless. # consumer does) satisfies this from its own requirements regardless.
[project.optional-dependencies] [project.optional-dependencies]
fastapi = ["fastapi>=0.100", "pydantic>=2"] fastapi = ["fastapi>=0.100", "pydantic>=2"]
test = ["httpx2>=2"]
[tool.setuptools.packages.find] [tool.setuptools.packages.find]
where = ["src"] where = ["src"]
@@ -28,12 +28,19 @@ from .authclient import (
token_from_request, token_from_request,
) )
from .config import DatabaseConfig, database_url_from_env from .config import DatabaseConfig, database_url_from_env
from .coreconfig import (
MIN_INTERNAL_SECRET_LENGTH,
follow_omnilogger,
handle_core_services_push,
internal_secret_matches,
internal_secret_usable,
)
from .coreconfig import Info as CoreConfigInfo from .coreconfig import Info as CoreConfigInfo
from .coreconfig import Store as CoreConfigStore from .coreconfig import Store as CoreConfigStore
from .coreconfig import internal_secret_matches from .logshipper import OmniLoggerHandler, Shipper
from .postgres import Database from .postgres import Database
from .tokens import hash_token, new_session_token from .tokens import hash_token, new_session_token
from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp, verify_totp_step
__all__ = [ __all__ = [
"AuthStore", "AuthStore",
@@ -46,7 +53,11 @@ __all__ = [
"token_from_request", "token_from_request",
"CoreConfigInfo", "CoreConfigInfo",
"CoreConfigStore", "CoreConfigStore",
"follow_omnilogger",
"handle_core_services_push",
"internal_secret_matches", "internal_secret_matches",
"internal_secret_usable",
"MIN_INTERNAL_SECRET_LENGTH",
"ROLE_ADMIN", "ROLE_ADMIN",
"ROLE_SUPERADMIN", "ROLE_SUPERADMIN",
"ROLE_USER", "ROLE_USER",
@@ -63,6 +74,8 @@ __all__ = [
"hash_token", "hash_token",
"new_session_token", "new_session_token",
"normalize_role", "normalize_role",
"OmniLoggerHandler",
"Shipper",
"password_hash_needs_upgrade", "password_hash_needs_upgrade",
"totp_provisioning_uri", "totp_provisioning_uri",
"verify_and_upgrade_password", "verify_and_upgrade_password",
@@ -70,4 +83,5 @@ __all__ = [
"verify_password", "verify_password",
"verify_password_async", "verify_password_async",
"verify_totp", "verify_totp",
"verify_totp_step",
] ]
@@ -3,6 +3,9 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import hashlib
import hmac
import re
import secrets import secrets
import threading import threading
from dataclasses import dataclass from dataclasses import dataclass
@@ -12,6 +15,7 @@ import asyncpg
import bcrypt import bcrypt
from .postgres import Database from .postgres import Database
from .totp import verify_totp_step
_SCHEMA = """ _SCHEMA = """
CREATE TABLE IF NOT EXISTS auth_users ( CREATE TABLE IF NOT EXISTS auth_users (
@@ -22,6 +26,7 @@ CREATE TABLE IF NOT EXISTS auth_users (
role TEXT NOT NULL DEFAULT 'user', role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '', totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE, totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
last_used_step BIGINT NOT NULL DEFAULT -1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now() updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
); );
@@ -29,6 +34,7 @@ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user'; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT ''; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
@@ -179,7 +185,12 @@ def _validate_credentials(username: str | None, password_hash: str | None) -> No
# so a stored value reads "bcrypt$$2b$12$...". Unprefixed bcrypt hashes written # so a stored value reads "bcrypt$$2b$12$...". Unprefixed bcrypt hashes written
# before the prefix still verify and are rewritten on the next successful login. # before the prefix still verify and are rewritten on the next successful login.
_BCRYPT_SCHEME = "bcrypt$" _BCRYPT_SCHEME = "bcrypt$"
_BCRYPT_SHA256_SCHEME = "bcrypt-sha256$"
_LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$") _LEGACY_BCRYPT_PREFIXES = ("$2a$", "$2b$", "$2y$")
_PBKDF2_SCHEME = "pbkdf2-sha256"
BCRYPT_MAX_PASSWORD_BYTES = 72
_LEGACY_PBKDF2_ITERATIONS = 100_000
_MAX_PBKDF2_ITERATIONS = 10_000_000
BCRYPT_ROUNDS = 12 BCRYPT_ROUNDS = 12
@@ -188,9 +199,9 @@ def _new_bcrypt_hash(password: str) -> str:
return _BCRYPT_SCHEME + hashed.decode("utf-8") return _BCRYPT_SCHEME + hashed.decode("utf-8")
# bcrypt reads only the first 72 bytes. Older bcrypt releases drop the rest silently, so the limit # bcrypt reads only the first 72 bytes, so new passwords are refused above this limit. Legacy
# is enforced here instead of depending on the installed version. # PBKDF2 passwords over the limit are migrated with an explicitly marked SHA-256 pre-hash.
MAX_PASSWORD_BYTES = 72 MAX_PASSWORD_BYTES = BCRYPT_MAX_PASSWORD_BYTES
def hash_password(password: str) -> str: def hash_password(password: str) -> str:
@@ -209,24 +220,75 @@ def _bcrypt_string_of(stored_hash: str) -> str | None:
return None return None
def _bcrypt_hash_info(stored_hash: str) -> tuple[str, bool, bool] | None:
if stored_hash.startswith(_BCRYPT_SHA256_SCHEME):
return stored_hash[len(_BCRYPT_SHA256_SCHEME) :], True, False
if stored_hash.startswith(_BCRYPT_SCHEME):
return stored_hash[len(_BCRYPT_SCHEME) :], False, False
if stored_hash.startswith(_LEGACY_BCRYPT_PREFIXES):
return stored_hash, False, True
return None
def _pbkdf2_hash_info(stored_hash: str) -> tuple[int, str, str] | None:
if stored_hash.startswith(f"{_PBKDF2_SCHEME}$"):
parts = stored_hash.split("$")
if len(parts) != 4:
return None
_, raw_iterations, salt, expected = parts
try:
iterations = int(raw_iterations)
except ValueError:
return None
elif re.fullmatch(r"[0-9a-f]+:[0-9a-f]+", stored_hash):
salt, expected = stored_hash.split(":", 1)
iterations = _LEGACY_PBKDF2_ITERATIONS
else:
return None
if len(salt) != 32 or len(expected) != 64 or not (1 <= iterations <= _MAX_PBKDF2_ITERATIONS):
return None
return iterations, salt, expected
def _new_bcrypt_sha256_hash(password: str) -> str:
digest = hashlib.sha256(password.encode("utf-8")).hexdigest()
hashed = bcrypt.hashpw(digest.encode("ascii"), bcrypt.gensalt(rounds=BCRYPT_ROUNDS))
return _BCRYPT_SHA256_SCHEME + hashed.decode("utf-8")
def verify_password(password: str, stored_hash: str) -> bool: def verify_password(password: str, stored_hash: str) -> bool:
bcrypt_hash = _bcrypt_string_of(stored_hash) bcrypt_info = _bcrypt_hash_info(stored_hash)
if bcrypt_hash is None: if bcrypt_info is not None:
return False bcrypt_hash, prehashed, _ = bcrypt_info
try: raw_password = password.encode("utf-8")
return bcrypt.checkpw(password.encode("utf-8"), bcrypt_hash.encode("utf-8")) if prehashed:
except (ValueError, TypeError): 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 return False
iterations, salt, expected = parsed
actual = hashlib.pbkdf2_hmac(
"sha256", password.encode("utf-8"), salt.encode("ascii"), iterations
)
return hmac.compare_digest(actual.hex(), expected)
def password_hash_needs_upgrade(stored_hash: str) -> bool: def password_hash_needs_upgrade(stored_hash: str) -> bool:
"""True for an unprefixed legacy hash, or a bcrypt cost below BCRYPT_ROUNDS.""" """True for legacy PBKDF2/bcrypt formats or a bcrypt cost below policy."""
if not stored_hash.startswith(_BCRYPT_SCHEME): bcrypt_info = _bcrypt_hash_info(stored_hash)
if bcrypt_info is None:
return True return True
# The bcrypt string after the prefix is "$2b$<cost>$<salt+hash>". bcrypt_hash, _, legacy = bcrypt_info
parts = stored_hash[len(_BCRYPT_SCHEME) :].split("$") parts = bcrypt_hash.split("$")
try: try:
return int(parts[2]) < BCRYPT_ROUNDS return legacy or int(parts[2]) < BCRYPT_ROUNDS
except (IndexError, ValueError): except (IndexError, ValueError):
return True return True
@@ -243,6 +305,8 @@ def verify_and_upgrade_password(password: str, stored_hash: str) -> tuple[bool,
if not password_hash_needs_upgrade(stored_hash): if not password_hash_needs_upgrade(stored_hash):
return True, None return True, None
# The length rule applies when a password is first set, not when an old hash is upgraded. # The length rule applies when a password is first set, not when an old hash is upgraded.
if len(password.encode("utf-8")) > BCRYPT_MAX_PASSWORD_BYTES:
return True, _new_bcrypt_sha256_hash(password)
return True, _new_bcrypt_hash(password) return True, _new_bcrypt_hash(password)
@@ -431,18 +495,19 @@ class AuthStore:
async def get_totp_state(self, user_id: int) -> dict[str, object]: async def get_totp_state(self, user_id: int) -> dict[str, object]:
row = await self.database.fetchrow( row = await self.database.fetchrow(
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled " "SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled, "
"COALESCE(last_used_step, -1) AS last_used_step "
"FROM auth_users WHERE id = $1", "FROM auth_users WHERE id = $1",
user_id, user_id,
) )
return dict(row) if row else {"secret": "", "enabled": False} return dict(row) if row else {"secret": "", "enabled": False, "last_used_step": -1}
async def set_totp_secret(self, user_id: int, secret: str) -> None: async def set_totp_secret(self, user_id: int, secret: str) -> None:
"""Stores a pending secret without enabling two-factor auth. Raises """Stores a pending secret without enabling two-factor auth. Raises
TotpAlreadyEnabledError while it is enabled, so a replaced secret cannot silently switch TotpAlreadyEnabledError while it is enabled, so a replaced secret cannot silently switch
the second factor off.""" the second factor off."""
status = await self.database.execute( status = await self.database.execute(
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, " "UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, "
"updated_at = now() WHERE id = $2 AND NOT totp_enabled", "updated_at = now() WHERE id = $2 AND NOT totp_enabled",
secret, secret,
user_id, user_id,
@@ -450,16 +515,41 @@ class AuthStore:
if status == "UPDATE 0" and (await self.get_totp_state(user_id))["enabled"]: if status == "UPDATE 0" and (await self.get_totp_state(user_id))["enabled"]:
raise TotpAlreadyEnabledError("TOTP is already enabled; disable it first") raise TotpAlreadyEnabledError("TOTP is already enabled; disable it first")
async def enable_totp(self, user_id: int) -> None: async def enable_totp(self, user_id: int, token: str, now: float | None = None) -> bool:
await self.database.execute( state = await self.get_totp_state(user_id)
"UPDATE auth_users SET totp_enabled = true, updated_at = now() " if not state["secret"] or state["enabled"]:
"WHERE id = $1 AND totp_secret <> ''", return False
step = verify_totp_step(str(state["secret"]), token, now)
if step is None:
return False
status = await self.database.execute(
"UPDATE auth_users SET totp_enabled = true, last_used_step = $1, updated_at = now() "
"WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1",
step,
user_id, user_id,
state["secret"],
) )
return status == "UPDATE 1"
async def consume_totp_code(self, user_id: int, token: str, now: float | None = None) -> bool:
state = await self.get_totp_state(user_id)
if not state["secret"] or not state["enabled"]:
return False
step = verify_totp_step(str(state["secret"]), token, now)
if step is None:
return False
status = await self.database.execute(
"UPDATE auth_users SET last_used_step = $1, updated_at = now() "
"WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1",
step,
user_id,
state["secret"],
)
return status == "UPDATE 1"
async def disable_totp(self, user_id: int) -> None: async def disable_totp(self, user_id: int) -> None:
await self.database.execute( await self.database.execute(
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, " "UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, "
"updated_at = now() WHERE id = $1", "updated_at = now() WHERE id = $1",
user_id, user_id,
) )
@@ -64,11 +64,14 @@ from typing import Any, Mapping
DEFAULT_COOKIE_NAME = "auth_session" DEFAULT_COOKIE_NAME = "auth_session"
DEFAULT_TIMEOUT = 5.0 DEFAULT_TIMEOUT = 5.0
# validate() results, positive and negative, are reused for this many seconds so a burst of # validate() results (positive and negative) and /api/me profiles are reused for this many
# requests with one token costs one AuthGuard call. Revocation through this client (logout) # seconds so a burst of requests with one token costs one AuthGuard call. Revocation through
# clears the entry at once; revocation elsewhere is seen within the TTL. Mirrors the Go client. # this client (logout) and token-authenticated writes clear both entries at once; changes made
# directly in AuthGuard may take up to two seconds to reach consumers.
VALIDATION_CACHE_TTL = 2.0 VALIDATION_CACHE_TTL = 2.0
MAX_VALIDATION_CACHE_ENTRIES = 10000 MAX_VALIDATION_CACHE_ENTRIES = 10000
PROFILE_CACHE_TTL = VALIDATION_CACHE_TTL
MAX_PROFILE_CACHE_ENTRIES = MAX_VALIDATION_CACHE_ENTRIES
_BEARER_PREFIX = "Bearer " _BEARER_PREFIX = "Bearer "
@@ -274,6 +277,7 @@ class AuthClient:
self.project_key = (project_key or "").strip().lower() self.project_key = (project_key or "").strip().lower()
self._validation_lock = threading.Lock() self._validation_lock = threading.Lock()
self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {} self._validation_cache: dict[str, tuple[float, AuthGuardUser | None]] = {}
self._profile_cache: dict[str, tuple[float, PublicUser]] = {}
@staticmethod @staticmethod
def _validation_key(token: str) -> str: def _validation_key(token: str) -> str:
@@ -307,8 +311,36 @@ class AuthClient:
) )
def _forget_validation(self, token: str) -> None: def _forget_validation(self, token: str) -> None:
"""Clears cached validation and /api/me data for this token."""
with self._validation_lock: with self._validation_lock:
self._validation_cache.pop(self._validation_key(token), None) key = self._validation_key(token)
self._validation_cache.pop(key, None)
self._profile_cache.pop(key, None)
def _cached_profile(self, token: str) -> tuple[bool, PublicUser | None]:
key = self._validation_key(token)
with self._validation_lock:
entry = self._profile_cache.get(key)
if entry is None:
return False, None
expires, profile = entry
if time.monotonic() >= expires:
del self._profile_cache[key]
return False, None
return True, profile
def _cache_profile(self, token: str, profile: PublicUser) -> None:
with self._validation_lock:
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
now = time.monotonic()
for key in [k for k, entry in self._profile_cache.items() if now >= entry[0]]:
del self._profile_cache[key]
if len(self._profile_cache) >= MAX_PROFILE_CACHE_ENTRIES:
del self._profile_cache[next(iter(self._profile_cache))]
self._profile_cache[self._validation_key(token)] = (
time.monotonic() + PROFILE_CACHE_TTL,
profile,
)
def set_base_url(self, base_url: str) -> None: def set_base_url(self, base_url: str) -> None:
"""Atomically replaces the AuthGuard base URL this client calls, """Atomically replaces the AuthGuard base URL this client calls,
@@ -326,6 +358,7 @@ class AuthClient:
self.base_url = normalized self.base_url = normalized
with self._validation_lock: with self._validation_lock:
self._validation_cache.clear() self._validation_cache.clear()
self._profile_cache.clear()
# --- session validation (the original, minimal surface) ---------------- # --- session validation (the original, minimal surface) ----------------
@@ -465,6 +498,9 @@ class AuthClient:
message = str(payload.get("error") or f"request failed ({status})") message = str(payload.get("error") or f"request failed ({status})")
raise APIError(status, message, totp_required=bool(payload.get("totp_required"))) raise APIError(status, message, totp_required=bool(payload.get("totp_required")))
if token and method.upper() not in {"GET", "HEAD"}:
self._forget_validation(token)
return payload, list(cookies) return payload, list(cookies)
@staticmethod @staticmethod
@@ -533,9 +569,26 @@ class AuthClient:
return cookies return cookies
async def me(self, token: str) -> PublicUser: async def me(self, token: str) -> PublicUser:
"""Calls GET /api/me, resolving token to its account.""" """Calls GET /api/me, resolving token to its account.
payload, _ = await self._call("GET", "/api/me", token=token)
return self._public_user(payload) Successful profiles are cached by the SHA-256 token digest for the
same short window as validate(). This keeps protected API calls from
blocking on one AuthGuard round trip each while bounding how long an
external profile change or session revocation can remain stale.
"""
if not self.base_url:
raise AuthClientError("authclient: client has no base URL")
trimmed = (token or "").strip()
if trimmed:
hit, cached = self._cached_profile(trimmed)
if hit:
assert cached is not None
return cached
payload, _ = await self._call("GET", "/api/me", token=trimmed)
profile = self._public_user(payload)
if trimmed:
self._cache_profile(trimmed, profile)
return profile
# --- TOTP ------------------------------------------------------------------ # --- TOTP ------------------------------------------------------------------
@@ -56,6 +56,7 @@ from __future__ import annotations
import abc import abc
import os import os
from http.cookies import CookieError, SimpleCookie
from typing import Any, Callable, Optional from typing import Any, Callable, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response from fastapi import APIRouter, Depends, HTTPException, Request, Response
@@ -72,6 +73,7 @@ from .authclient import (
forwarded_client_ip, forwarded_client_ip,
) )
from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env from .clientip import client_address, parse_trusted_proxies, trusted_proxies_from_env
from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches
from .ratelimit import AttemptLimiter from .ratelimit import AttemptLimiter
__all__ = ["ProxyStore", "build_auth_router"] __all__ = ["ProxyStore", "build_auth_router"]
@@ -104,7 +106,10 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
# rather than a generic "internal error" indistinguishable from any other bug. # rather than a generic "internal error" indistinguishable from any other bug.
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly." ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
ERR_AUTHGUARD_NOT_CONFIGURED = "AUTHGUARD_URL is not configured, so sessions cannot be verified." ERR_AUTHGUARD_NOT_CONFIGURED = "AUTHGUARD_URL is not configured, so sessions cannot be verified."
ERR_SECRET_NOT_SET = "SECRET environment variable is not set." ERR_SECRET_NOT_SET = (
"SECRET environment variable is unset, shorter than "
f"{MIN_INTERNAL_SECRET_LENGTH} characters, or an example placeholder."
)
ERR_ADMIN_REQUIRED = "Administrator access required." ERR_ADMIN_REQUIRED = "Administrator access required."
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when # _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
@@ -175,6 +180,8 @@ class UpdateMeRequest(BaseModel):
email: str = "" email: str = ""
username: str = "" username: str = ""
password: str = "" password: str = ""
currentPassword: str = ""
totpToken: str = ""
class UpdateAccessRequest(BaseModel): class UpdateAccessRequest(BaseModel):
@@ -333,8 +340,30 @@ def build_auth_router(
) )
def _forward_cookies(response: Response, cookies: list[str]) -> None: def _forward_cookies(response: Response, cookies: list[str]) -> None:
for cookie in cookies: for header in cookies:
response.headers.append("set-cookie", cookie) parsed = SimpleCookie()
try:
parsed.load(header)
except CookieError:
continue
for morsel in parsed.values():
morsel["httponly"] = True
morsel["samesite"] = "lax"
if secure_cookie:
morsel["secure"] = True
response.headers.append("set-cookie", morsel.OutputString())
def _temporary_session_token(cookies: list[str]) -> str:
for header in cookies:
parsed = SimpleCookie()
try:
parsed.load(header)
except CookieError:
continue
morsel = parsed.get(cookie_name)
if morsel is not None and morsel.value:
return morsel.value
return ""
async def _current_profile( async def _current_profile(
request: Request, client: AuthClient request: Request, client: AuthClient
@@ -610,14 +639,42 @@ def build_auth_router(
email = _normalize_email(req.email) email = _normalize_email(req.email)
username = _normalize_username(req.username) username = _normalize_username(req.username)
password = None password = None
temporary_token = ""
if req.password: if req.password:
_validate_password(req.password) _validate_password(req.password)
if not req.currentPassword:
raise HTTPException(
status_code=400,
detail="Current password is required to change the password.",
)
if current.totp_enabled and not req.totpToken.strip():
raise HTTPException(
status_code=400,
detail="A current authenticator code is required to change the password.",
)
try:
reauthenticated = await client.login(
current.username,
req.currentPassword,
req.totpToken,
)
except AuthClientError as exc:
_raise_authguard_error(exc, "Current credentials could not be verified.")
raise # unreachable
temporary_token = _temporary_session_token(reauthenticated.cookies)
password = req.password password = req.password
try: try:
await client.update_managed_user( try:
token, current.id, username=username, email=email, password=password 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: except AuthClientError as exc:
_raise_authguard_error(exc, "Profile could not be updated.") _raise_authguard_error(exc, "Profile could not be updated.")
raise # unreachable raise # unreachable
@@ -651,9 +708,8 @@ def build_auth_router(
request: Request, request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
) -> dict[str, bool]: ) -> dict[str, bool]:
if ( if not internal_secret_matches(
not configured_internal_secret request.headers.get("X-Internal-Auth"), configured_internal_secret
or request.headers.get("X-Internal-Auth") != configured_internal_secret
): ):
raise HTTPException(status_code=401, detail="internal service authentication required") raise HTTPException(status_code=401, detail="internal service authentication required")
await store.set_login_required(req.loginRequired) await store.set_login_required(req.loginRequired)
@@ -7,31 +7,53 @@ ProjectConfigurator/README.md's "Pushing core service info to other
projects" section for the wire contract this module implements the projects" section for the wire contract this module implements the
receiving end of. receiving end of.
It also carries OmniLogger's URL and this service's ingest token (see `Info`).
`follow_omnilogger` keeps a log shipper's credentials in step with those pushes,
and `handle_core_services_push` is the framework-neutral body of the
PUT /api/core-services/internal route.
Framework-agnostic, like the rest of this package (see the top-level Framework-agnostic, like the rest of this package (see the top-level
README's "HTTP framework adapters stay in each service" note): this module README's "HTTP framework adapters stay in each service" note): this module
has no HTTP server of its own. A service wires the actual has no HTTP server of its own. A service mounts the actual
PUT /api/core-services/internal route in its own framework (FastAPI, PUT /api/core-services/internal route in its own framework (FastAPI,
aiohttp, ...), gated behind its own SECRET check the same aiohttp, ...) and passes the raw body to `handle_core_services_push`, which
way its other internal-service routes already are, decodes the JSON body returns (status, body) for the service to send -- see that function's doc
into an `Info`, and calls `Store.set(info)` -- see `Store.set`'s doc comment comment for a minimal FastAPI example.
for a minimal FastAPI example.
""" """
from __future__ import annotations from __future__ import annotations
import dataclasses
import hmac import hmac
import json
import threading import threading
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Callable, Optional from typing import Callable, Optional, Protocol
from urllib.parse import urlsplit from urllib.parse import urlsplit
MIN_INTERNAL_SECRET_LENGTH = 16
"""Shortest SECRET a service accepts for its internal routes."""
EXAMPLE_INTERNAL_SECRETS = frozenset({"SECRET", "change-me-to-a-long-random-value"})
"""Placeholders from .env.example files and the bare variable name. They are
public, so they never gate a route."""
def internal_secret_usable(secret: Optional[str]) -> bool:
"""True when the configured secret is strong enough to gate an internal
route: at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
placeholder. A route whose secret is not usable rejects every caller."""
value = secret or ""
return len(value) >= MIN_INTERNAL_SECRET_LENGTH and value not in EXAMPLE_INTERNAL_SECRETS
def internal_secret_matches(provided: Optional[str], secret: Optional[str]) -> bool: def internal_secret_matches(provided: Optional[str], secret: Optional[str]) -> bool:
"""True when the X-Internal-Auth value equals the configured secret. An """True when the X-Internal-Auth value equals the configured secret. A
unset or empty secret never matches, and the comparison is constant-time.""" secret that is not usable (see internal_secret_usable) never matches, and
expected = (secret or "").encode("utf-8") the comparison is constant-time."""
if not expected: if not internal_secret_usable(secret):
return False return False
expected = (secret or "").encode("utf-8")
return hmac.compare_digest(expected, (provided or "").encode("utf-8")) return hmac.compare_digest(expected, (provided or "").encode("utf-8"))
@@ -60,6 +82,12 @@ class Info:
# registered, in priority order (the first entry is the same as # registered, in priority order (the first entry is the same as
# carrier_node_url). # carrier_node_url).
carrier_node_urls: list = field(default_factory=list) carrier_node_urls: list = field(default_factory=list)
# omni_logger_url is OmniLogger's base URL, the instance that receives this
# service's log entries (Go: coreconfig.Info.OmniLoggerURL).
omni_logger_url: str = ""
# omni_logger_ingest_token is this service's OmniLogger ingest token. repr=False
# keeps it out of logs and reprs. to_json never includes it (see below).
omni_logger_ingest_token: str = field(default="", repr=False)
@classmethod @classmethod
def from_json(cls, data: dict) -> "Info": def from_json(cls, data: dict) -> "Info":
@@ -72,13 +100,18 @@ class Info:
auth_guard_url=str(data.get("authGuardUrl") or "").strip(), auth_guard_url=str(data.get("authGuardUrl") or "").strip(),
carrier_node_url=urls[0] if urls else "", carrier_node_url=urls[0] if urls else "",
carrier_node_urls=urls, carrier_node_urls=urls,
omni_logger_url=str(data.get("omniLoggerUrl") or "").strip(),
omni_logger_ingest_token=str(data.get("omniLoggerIngestToken") or "").strip(),
) )
def to_json(self) -> dict: def to_json(self) -> dict:
# omniLoggerIngestToken is deliberately left out: a to_json result may be sent back
# to a caller, and the token must never be echoed.
return { return {
"authGuardUrl": self.auth_guard_url, "authGuardUrl": self.auth_guard_url,
"carrierNodeUrl": self.carrier_node_url, "carrierNodeUrl": self.carrier_node_url,
"carrierNodeUrls": list(self.carrier_node_urls), "carrierNodeUrls": list(self.carrier_node_urls),
"omniLoggerUrl": self.omni_logger_url,
} }
@@ -94,6 +127,7 @@ class Store:
self._lock = threading.Lock() self._lock = threading.Lock()
self._info = _normalize(fallback or Info()) self._info = _normalize(fallback or Info())
self._on_update: Optional[Callable[[Info], None]] = None self._on_update: Optional[Callable[[Info], None]] = None
self._subscribers: list[Callable[[Info], None]] = []
def get(self) -> Info: def get(self) -> Info:
with self._lock: with self._lock:
@@ -120,26 +154,25 @@ class Store:
with self._lock: with self._lock:
self._on_update = fn self._on_update = fn
def subscribe(self, fn: Callable[[Info], None]) -> None:
"""Registers fn to be called (synchronously, so keep it fast) with the new Info after every
set(), in addition to on_update's single callback, which it does not replace. Use it when
more than one component follows the pushed values, such as an AuthClient and a log shipper
(see follow_omnilogger). Subscribers cannot be removed; they live as long as the Store."""
with self._lock:
self._subscribers.append(fn)
def set(self, next_info: Info) -> Info: def set(self, next_info: Info) -> Info:
"""Replaces the current Info, field by field, ignoring a """Replaces the current Info, field by field, ignoring a
blank/empty field so a partial push (e.g. only carrierNodeUrl(s) blank/empty field so a partial push (e.g. only carrierNodeUrl(s)
changed) never clobbers the other value. Returns the resulting changed) never clobbers the other value. Returns the resulting
Info. Every URL must be an http or https URL with a host; otherwise Info (a copy). Every URL must be an http or https URL with a host;
nothing is changed and ValueError is raised. Minimal FastAPI usage: otherwise nothing is changed and ValueError is raised. The receiving
route is normally handle_core_services_push, which calls this; see its
@app.put("/api/core-services/internal") doc comment for the FastAPI wiring."""
async def push_core_services(request: Request):
if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET):
raise HTTPException(status_code=401)
body = await request.json()
try:
info = core_config_store.set(Info.from_json(body))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"ok": True, "info": info.to_json()}
"""
next_info = _normalize(next_info) next_info = _normalize(next_info)
for url in [next_info.auth_guard_url, *next_info.carrier_node_urls]: urls = [next_info.auth_guard_url, next_info.omni_logger_url, *next_info.carrier_node_urls]
for url in urls:
if url and not _is_service_url(url): if url and not _is_service_url(url):
raise ValueError( raise ValueError(
f"core service URL must be an http or https URL with a host: {url}" f"core service URL must be an http or https URL with a host: {url}"
@@ -150,10 +183,19 @@ class Store:
if next_info.carrier_node_urls: if next_info.carrier_node_urls:
self._info.carrier_node_urls = next_info.carrier_node_urls self._info.carrier_node_urls = next_info.carrier_node_urls
self._info.carrier_node_url = next_info.carrier_node_urls[0] self._info.carrier_node_url = next_info.carrier_node_urls[0]
current = self._info if next_info.omni_logger_url:
self._info.omni_logger_url = next_info.omni_logger_url
if next_info.omni_logger_ingest_token:
self._info.omni_logger_ingest_token = next_info.omni_logger_ingest_token
current = dataclasses.replace(
self._info, carrier_node_urls=list(self._info.carrier_node_urls)
)
callback = self._on_update callback = self._on_update
subscribers = list(self._subscribers)
if callback is not None: if callback is not None:
callback(current) callback(current)
for fn in subscribers:
fn(current)
return current return current
@@ -165,4 +207,89 @@ def _normalize(info: Info) -> Info:
auth_guard_url=info.auth_guard_url.strip(), auth_guard_url=info.auth_guard_url.strip(),
carrier_node_url=cleaned[0] if cleaned else "", carrier_node_url=cleaned[0] if cleaned else "",
carrier_node_urls=cleaned, carrier_node_urls=cleaned,
omni_logger_url=info.omni_logger_url.strip().rstrip("/"),
omni_logger_ingest_token=info.omni_logger_ingest_token.strip(),
) )
class SupportsSetCredentials(Protocol):
"""What follow_omnilogger needs from a log shipper: logshipper.Shipper satisfies it."""
def set_credentials(self, base_url: str, token: str) -> None: ...
def follow_omnilogger(store: Store, shipper: SupportsSetCredentials) -> None:
"""Keeps shipper's OmniLogger endpoint and ingest token in step with pushes, as Go's
logshipper.Shipper.Follow does. Whenever a set() leaves both omniLoggerUrl and
omniLoggerIngestToken non-empty in the store, shipper.set_credentials(url, token) is called.
Until both are stored, the shipper is left alone, so a push with a token but no URL never
disables or re-points an environment-configured shipper.
Call it once at startup, after creating the shipper. The Store must not be seeded with
OmniLogger values from the environment: those belong to the shipper, and seeding them would
make a token-only push re-point it."""
def apply(info: Info) -> None:
if info.omni_logger_url and info.omni_logger_ingest_token:
shipper.set_credentials(info.omni_logger_url, info.omni_logger_ingest_token)
apply(store.get())
store.subscribe(apply)
MAX_PUSH_BODY_BYTES = 4096
"""Largest PUT /api/core-services/internal body that handle_core_services_push reads."""
PUSH_AUTH_ERROR = "internal service authentication required"
PUSH_INVALID_JSON_ERROR = "invalid JSON body"
PUSH_INVALID_URL_ERROR = "core service URL must be an http or https URL with a host"
def handle_core_services_push(
store: Store,
secret: Optional[str],
provided_auth: Optional[str],
body: bytes,
) -> tuple[int, dict]:
"""The framework-neutral body of PUT /api/core-services/internal, the route
ProjectConfigurator pushes to. It returns (status, json_body) for the service to send.
- provided_auth is the X-Internal-Auth header (None when absent). A provided value that does
not equal secret, or any secret that is not usable (see internal_secret_usable), gets 401.
- body is the raw request body. Over MAX_PUSH_BODY_BYTES, or not a JSON object, gets 400.
- A non-empty omniLoggerUrl, authGuardUrl or carrierNodeUrl(s) value that is not an http or
https URL with a host gets 400 (Store.set validates them). Other fields are ignored.
- Success is 200 {"ok": True}. The response never includes the ingest token.
Mount it at PUT /api/core-services/internal, for example in FastAPI:
@app.put("/api/core-services/internal")
async def push_core_services(request: Request):
status, body = handle_core_services_push(
core_config_store, SECRET, request.headers.get("X-Internal-Auth"),
await request.body(),
)
return JSONResponse(body, status_code=status)
"""
if not internal_secret_matches(provided_auth, secret):
return 401, {"error": PUSH_AUTH_ERROR}
if len(body) > MAX_PUSH_BODY_BYTES:
return 400, {"error": PUSH_INVALID_JSON_ERROR}
try:
data = json.loads(body)
except (ValueError, RecursionError): # JSONDecodeError and UnicodeDecodeError are ValueErrors
return 400, {"error": PUSH_INVALID_JSON_ERROR}
if not isinstance(data, dict):
return 400, {"error": PUSH_INVALID_JSON_ERROR}
# Info.from_json reads these fields; a wrong type gets 400 here instead of an error inside it.
for key in ("authGuardUrl", "carrierNodeUrl", "omniLoggerUrl", "omniLoggerIngestToken"):
if data.get(key) is not None and not isinstance(data[key], str):
return 400, {"error": PUSH_INVALID_JSON_ERROR}
urls = data.get("carrierNodeUrls")
if urls is not None and not isinstance(urls, list):
return 400, {"error": PUSH_INVALID_JSON_ERROR}
try:
store.set(Info.from_json(data))
except ValueError:
return 400, {"error": PUSH_INVALID_URL_ERROR}
return 200, {"ok": True}
@@ -0,0 +1,415 @@
"""Client-side adapter for OmniLogger, the workspace's central log sink. Python counterpart of
shared/backend/logshipper (Go), and it follows the same wire contract.
Shipping is additive. A service keeps its own console logging unchanged and adds an
`OmniLoggerHandler` next to its existing handlers, so each record also reaches OmniLogger.
`Shipper` never prints anything itself.
Shipping is enabled only when both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are set; see
`Shipper.from_env`, which returns None otherwise.
Entries are clamped to OmniLogger's limits before they are buffered, because OmniLogger rejects
a whole batch when any one entry breaks a limit. A batch that fails with a network error, an HTTP
5xx or 429 is kept and sent again on a later flush, while any other rejection is dropped. Nothing
here raises into the caller or blocks it: failures and a full buffer are reported with a
rate-limited line on stderr.
"""
from __future__ import annotations
import atexit
import json
import logging
import os
import sys
import threading
import time
import urllib.error
import urllib.request
from collections.abc import Iterator, Mapping
from datetime import datetime, timezone
from typing import Any
__all__ = ["OmniLoggerHandler", "Shipper", "to_omnilogger_level"]
ENV_URL = "OMNILOGGER_URL"
ENV_TOKEN = "OMNILOGGER_INGEST_TOKEN"
FLUSH_INTERVAL = 2.0 # seconds between background flushes
MAX_BATCH_SIZE = 100 # buffering this many entries flushes early
BUFFER_CAPACITY = 2000 # beyond this, new entries are dropped
HTTP_TIMEOUT = 5.0
WARN_INTERVAL = 60.0 # at most one stderr warning per this many seconds
# OmniLogger's limits (Central/OmniLogger/internal/httpapi/validate.go).
MAX_BATCH_ENTRIES = 1000
MAX_BODY_BYTES = 2 * 1024 * 1024
MAX_MESSAGE_BYTES = 8 * 1024
MAX_CONTEXT_BYTES = 16 * 1024
TRUNCATED_MARKER = " [truncated]"
DROPPED_CONTEXT = '{"context_dropped":true}'
# Severity ranks, matching the Go shipper's scale (debug 10 ... critical 50).
_RANKS = {"debug": 10, "info": 20, "warn": 30, "error": 40, "critical": 50}
_SILENT = 100
_LEVEL_NAMES = {
"debug": "debug",
"info": "info",
"warn": "warn",
"warning": "warn",
"error": "error",
"critical": "critical",
}
_THRESHOLD_RANKS = {**_RANKS, "silent": _SILENT, "none": _SILENT, "off": _SILENT}
def to_omnilogger_level(levelno: int) -> str:
"""Maps a standard-library logging level number to OmniLogger's level name.
DEBUG, INFO, WARNING, ERROR and CRITICAL map to debug, info, warn, error and critical. A level
between two of them takes the name of the lower one, and anything below INFO is debug.
"""
if levelno >= logging.CRITICAL:
return "critical"
if levelno >= logging.ERROR:
return "error"
if levelno >= logging.WARNING:
return "warn"
if levelno >= logging.INFO:
return "info"
return "debug"
class _NoRedirect(urllib.request.HTTPRedirectHandler):
"""Refuses redirects, so the bearer token only ever goes to the configured URL."""
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001, ARG002
return None
_OPENER = urllib.request.build_opener(_NoRedirect)
def _json_text(value: str) -> str:
return json.dumps(value, ensure_ascii=False)
def _clean_message(message: object) -> str:
# OmniLogger rejects a message with a NUL byte (PostgreSQL cannot store it) and then rejects the
# whole batch, so NUL is written as its escape text. Lone surrogates cannot be encoded as UTF-8.
text = message if isinstance(message, str) else str(message)
text = text.replace("\x00", "\\u0000")
return text.encode("utf-8", "replace").decode("utf-8")
def _clamp_message(text: str) -> str:
data = text.encode("utf-8")
if len(data) <= MAX_MESSAGE_BYTES:
return text
cut = MAX_MESSAGE_BYTES - len(TRUNCATED_MARKER.encode("utf-8"))
# Decoding with "ignore" drops a character that the cut split in half, so the cut lands on a
# character boundary.
return data[:cut].decode("utf-8", "ignore") + TRUNCATED_MARKER
def _clamp_context(context: Mapping[str, Any]) -> str:
try:
raw = json.dumps(
dict(context), ensure_ascii=False, separators=(",", ":"), default=str, allow_nan=False
)
except (TypeError, ValueError, RecursionError):
return DROPPED_CONTEXT
# json.dumps writes a NUL as the escape \u0000, which OmniLogger refuses in context.
if "\\u0000" in raw or len(raw.encode("utf-8", "replace")) > MAX_CONTEXT_BYTES:
return DROPPED_CONTEXT
return raw
def _timestamp() -> str:
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def _encode_entry(
service: str, level: str, message: object, context: Mapping[str, Any] | None
) -> bytes:
fields = [
f'"service":{_json_text(service)}',
f'"level":"{level}"',
f'"message":{_json_text(_clamp_message(_clean_message(message)))}',
]
if context is not None:
fields.append(f'"context":{_clamp_context(context)}')
fields.append(f'"occurred_at":"{_timestamp()}"')
return ("{" + ",".join(fields) + "}").encode("utf-8", "replace")
def _batch_bodies(entries: list[bytes]) -> Iterator[tuple[bytes, int]]:
"""Groups encoded entries into request bodies of at most MAX_BATCH_ENTRIES entries and under
MAX_BODY_BYTES bytes each. Yields (body, entry count)."""
group: list[bytes] = []
size = 2 # the enclosing brackets
for entry in entries:
extra = len(entry) + (1 if group else 0) # the comma before it, if any
if group and (len(group) >= MAX_BATCH_ENTRIES or size + extra >= MAX_BODY_BYTES):
yield b"[" + b",".join(group) + b"]", len(group)
group, size, extra = [], 2, len(entry)
group.append(entry)
size += extra
if group:
yield b"[" + b",".join(group) + b"]", len(group)
class Shipper:
"""Buffers log entries and sends them to OmniLogger in batches from a background thread.
Create one at startup with `Shipper.from_env(service)` and call `close()` on graceful shutdown.
`close()` also runs at interpreter exit (atexit), so a final flush happens even without it.
A Shipper is safe to use from many threads.
"""
def __init__(
self,
*,
base_url: str,
ingest_token: str,
service: str,
level: str | None = None,
flush_interval: float = FLUSH_INTERVAL,
max_batch_size: int = MAX_BATCH_SIZE,
buffer_capacity: int = BUFFER_CAPACITY,
http_timeout: float = HTTP_TIMEOUT,
) -> None:
"""`level` is the threshold, using the same names as the services' LOG setting (debug, info,
warn, error, critical, silent). It defaults to info."""
self._service = service
self._threshold = _THRESHOLD_RANKS.get((level or "info").strip().lower(), _RANKS["info"])
self._flush_interval = flush_interval if flush_interval > 0 else FLUSH_INTERVAL
self._max_batch_size = max_batch_size
self._buffer_capacity = buffer_capacity
self._http_timeout = http_timeout
self._buffer: list[bytes] = []
self._buffer_lock = threading.Lock()
self._cred_lock = threading.Lock()
self._url: str | None = None # None while shipping is disabled
self._token = ""
self.set_credentials(base_url, ingest_token)
self._wake = threading.Event()
self._stop = threading.Event()
self._close_lock = threading.Lock()
self._closed = False
self._warn_lock = threading.Lock()
self._last_warn: float | None = None
self._thread = threading.Thread(target=self._run, name=f"logshipper-{service}", daemon=True)
self._thread.start()
atexit.register(self.close)
@classmethod
def from_env(
cls,
service: str,
*,
level: str | None = None,
environ: Mapping[str, str] | None = None,
) -> Shipper | None:
"""Returns a Shipper configured from OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN, or None
when either is unset or empty, which leaves the service with no shipping at all."""
env = os.environ if environ is None else environ
url = (env.get(ENV_URL) or "").strip()
token = (env.get(ENV_TOKEN) or "").strip()
if not url or not token:
return None
return cls(base_url=url, ingest_token=token, service=service, level=level)
def handler(self, level: int = logging.NOTSET) -> OmniLoggerHandler:
"""Returns a logging handler that ships records to this Shipper."""
return OmniLoggerHandler(self, level)
def set_credentials(self, base_url: str, token: str) -> None:
"""Sets where, and as which ingest token, entries are sent. It is thread-safe, takes effect
from the next flush, and does not restart the background thread.
An empty base URL or token disables shipping: entries are no longer buffered, anything
already buffered is dropped, and the service's own console output carries on unchanged.
Otherwise entries go to `base_url` + "/api/logs" with `token` as the bearer token."""
base = (base_url or "").strip().rstrip("/")
token = (token or "").strip()
url = base + "/api/logs" if base and token else None
with self._cred_lock:
self._url = url
self._token = token
if url is None:
with self._buffer_lock:
self._buffer = []
def _enabled(self) -> bool:
with self._cred_lock:
return self._url is not None
def log(self, level: str, message: str, context: Mapping[str, Any] | None = None) -> None:
"""Queues one entry. `level` is debug, info, warn (or warning), error or critical; any
other value is sent as info. `context` is an optional mapping sent as JSON."""
name = _LEVEL_NAMES.get(str(level).strip().lower(), "info")
if _RANKS[name] < self._threshold or not self._enabled():
return
try:
entry = _encode_entry(self._service, name, message, context)
except Exception: # noqa: BLE001 - a log sink must never fail its host
return
self._buffer_entry(entry)
def debug(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("debug", message, context)
def info(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("info", message, context)
def warning(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("warn", message, context)
def error(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("error", message, context)
def critical(self, message: str, context: Mapping[str, Any] | None = None) -> None:
self.log("critical", message, context)
def flush(self) -> None:
"""Sends everything buffered now, in the calling thread. A batch that fails for a reason
that may pass (no connection, HTTP 5xx or 429) stays in the buffer with every later entry of
this flush, in order, and the rest of the flush waits for the next one. Other failures are
only reported on stderr, and at most once a minute."""
with self._buffer_lock:
if not self._buffer:
return
pending, self._buffer = self._buffer, []
sent = 0
for body, count in _batch_bodies(pending):
if self._post(body, count):
self._requeue(pending[sent:])
return
sent += count
def _requeue(self, entries: list[bytes]) -> None:
"""Puts entries that failed to send back at the front of the buffer, so the next flush
sends them before newer entries. The buffer stays within its capacity: when the waiting
entries and the buffer do not all fit, the newest entries are dropped, as _buffer_entry
drops them."""
with self._buffer_lock:
if not self._enabled():
return # shipping was disabled during the flush, so these go with the buffer
combined = entries + self._buffer
dropped = max(0, len(combined) - self._buffer_capacity)
self._buffer = combined[: self._buffer_capacity]
if dropped:
self._warn(
f"buffer full while retrying, dropping {dropped} log entries for service "
f"{self._service!r}"
)
def close(self) -> None:
"""Stops the background thread after a final flush of whatever is buffered. Safe to call
more than once."""
with self._close_lock:
if self._closed:
return
self._closed = True
self._stop.set()
self._wake.set()
if threading.current_thread() is not self._thread:
self._thread.join()
self.flush()
atexit.unregister(self.close)
def _buffer_entry(self, entry: bytes) -> None:
if self._closed or not self._enabled():
return
with self._buffer_lock:
full = len(self._buffer) >= self._buffer_capacity
if not full:
self._buffer.append(entry)
ready = len(self._buffer) >= self._max_batch_size
if full:
self._warn(
f"buffer full (cap={self._buffer_capacity}), dropping log entries for service "
f"{self._service!r}"
)
elif ready:
self._wake.set()
def _run(self) -> None:
while not self._stop.is_set():
self._wake.wait(self._flush_interval)
# Cleared before the flush takes its snapshot, so an entry that arrives during the
# flush sets the event again and is not left waiting for the next interval.
self._wake.clear()
if self._stop.is_set():
break
try:
self.flush()
except Exception: # noqa: BLE001 - keep the background thread alive
pass
def _post(self, body: bytes, count: int) -> bool:
"""Sends one request body. Returns True when it failed for a reason that may pass (no
connection, HTTP 5xx or 429), so the caller keeps its entries for a later flush. A request
OmniLogger rejects with any other status is reported and dropped, and returns False."""
with self._cred_lock:
url, token = self._url, self._token
if url is None:
return False # shipping was disabled after these entries were taken for a flush
request = urllib.request.Request(
url,
data=body,
method="POST",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
},
)
try:
with _OPENER.open(request, timeout=self._http_timeout):
return False
except urllib.error.HTTPError as exc:
exc.close()
if exc.code == 429 or exc.code >= 500:
self._warn(f"OmniLogger answered HTTP {exc.code} for {count} entries, will retry")
return True
self._warn(f"OmniLogger rejected {count} entries: HTTP {exc.code}")
return False
except Exception as exc: # noqa: BLE001 - unreachable or misconfigured sink
self._warn(f"send {count} entries to {url}: {exc}")
return True
def _warn(self, detail: str) -> None:
now = time.monotonic()
with self._warn_lock:
if self._last_warn is not None and now - self._last_warn < WARN_INTERVAL:
return
self._last_warn = now
try:
stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
sys.stderr.write(f"[{stamp}] [logshipper] logshipper: {detail}\n")
sys.stderr.flush()
except Exception: # noqa: BLE001 - stderr may be closed or missing
pass
class OmniLoggerHandler(logging.Handler):
"""A logging handler that ships each record to a Shipper and writes nothing locally.
Keep the service's own console handler and add this one beside it, so the console output is
unchanged. The shipped message is the record's formatted message, with any traceback appended.
The record's logger name goes in the entry's context.
"""
def __init__(self, shipper: Shipper, level: int = logging.NOTSET) -> None:
super().__init__(level)
self._shipper = shipper
def emit(self, record: logging.LogRecord) -> None:
try:
message = self.format(record)
self._shipper.log(to_omnilogger_level(record.levelno), message, {"logger": record.name})
except Exception: # noqa: BLE001 - a log sink must never fail its host
pass
@@ -36,19 +36,24 @@ def totp_provisioning_uri(issuer: str, account: str, secret: str) -> str:
def verify_totp(secret: str, token: str, now: float | None = None) -> bool: def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
return verify_totp_step(secret, token, now) is not None
def verify_totp_step(secret: str, token: str, now: float | None = None) -> int | None:
normalized_secret = _normalize_secret(secret) normalized_secret = _normalize_secret(secret)
normalized_token = _normalize_token(token) normalized_token = _normalize_token(token)
if not normalized_secret or len(normalized_token) != TOTP_DIGITS: if not normalized_secret or len(normalized_token) != TOTP_DIGITS:
return False return None
try: try:
key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8)) key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8))
except (ValueError, binascii.Error): except (ValueError, binascii.Error):
return False return None
if not key: if not key:
return False return None
period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS) period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS)
for offset in range(-TOTP_WINDOW, TOTP_WINDOW + 1): # Prefer the current step if a six-digit collision occurs in the window.
for offset in (0, -1, 1):
counter = period + offset counter = period + offset
if counter < 0: if counter < 0:
continue continue
@@ -62,8 +67,8 @@ def verify_totp(secret: str, token: str, now: float | None = None) -> bool:
) )
candidate = f"{value % 1_000_000:06d}" candidate = f"{value % 1_000_000:06d}"
if hmac.compare_digest(candidate, normalized_token): if hmac.compare_digest(candidate, normalized_token):
return True return counter
return False return None
def _normalize_secret(value: str) -> str: def _normalize_secret(value: str) -> str:
+110 -2
View File
@@ -175,15 +175,32 @@ class AccessSettingsTests(unittest.TestCase):
self.assertEqual(response.status_code, 500) self.assertEqual(response.status_code, 500)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True}) self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
def test_internal_update_refuses_a_short_or_placeholder_secret(self) -> None:
for secret in ("short", "change-me-to-a-long-random-value"):
with self.subTest(secret=secret):
store = _FakeStore(login_required=True)
client = TestClient(
_build_app(store, _FakeClient(setup_required=False), internal_secret=secret)
)
response = client.put(
"/api/auth/access/internal",
headers={"X-Internal-Auth": secret},
json={"loginRequired": False},
)
self.assertEqual(response.status_code, 401)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None: def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
store = _FakeStore(login_required=True) store = _FakeStore(login_required=True)
client = TestClient( client = TestClient(
_build_app(store, _FakeClient(setup_required=False), internal_secret="secret") _build_app(
store, _FakeClient(setup_required=False), internal_secret="internal-test-secret"
)
) )
response = client.put( response = client.put(
"/api/auth/access/internal", "/api/auth/access/internal",
headers={"X-Internal-Auth": "secret"}, headers={"X-Internal-Auth": "internal-test-secret"},
json={"loginRequired": False}, json={"loginRequired": False},
) )
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@@ -244,6 +261,97 @@ class _RoleClient(_FakeClient):
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token]) return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
class _ProfileClient(_RoleClient):
def __init__(self, *, totp_enabled: bool = False) -> None:
super().__init__()
self.totp_enabled = totp_enabled
self.login_calls: list[tuple[str, str, str]] = []
self.update_calls: list[dict[str, object]] = []
async def me(self, token: str) -> PublicUser:
if token != "admin-token":
raise APIError(401, "unauthenticated")
return PublicUser(
id=1,
username="admin",
email="admin@example.com",
role="superadmin",
totp_enabled=self.totp_enabled,
)
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
self.login_calls.append((username_or_email, password, totp_token))
if password != "current-password":
raise APIError(401, "invalid credentials")
return SessionResult(
user=PublicUser(id=1, username="admin", email="admin@example.com", role="superadmin"),
cookies=["auth_session=reauth-token; Path=/; HttpOnly"],
)
async def update_managed_user(self, token: str, user_id: int, **kwargs) -> None:
self.update_calls.append({"token": token, "user_id": user_id, **kwargs})
class ProfileReauthenticationTests(unittest.TestCase):
def _put(self, fake: _ProfileClient, body: dict[str, str]):
client = TestClient(_build_app(_FakeStore(), fake))
return client.put(
"/api/auth/me",
headers={"Cookie": f"{DEFAULT_COOKIE_NAME}=admin-token"},
json=body,
)
def test_password_update_requires_current_password_and_totp_when_enabled(self) -> None:
no_totp = _ProfileClient()
response = self._put(
no_totp,
{"username": "admin", "email": "admin@example.com", "password": "new-password"},
)
self.assertEqual(response.status_code, 400)
self.assertEqual(no_totp.login_calls, [])
totp = _ProfileClient(totp_enabled=True)
response = self._put(
totp,
{
"username": "admin",
"email": "admin@example.com",
"password": "new-password",
"currentPassword": "current-password",
},
)
self.assertEqual(response.status_code, 400)
self.assertEqual(totp.login_calls, [])
def test_password_update_reauthenticates_and_cleans_up_temporary_session(self) -> None:
fake = _ProfileClient(totp_enabled=True)
response = self._put(
fake,
{
"username": "admin",
"email": "admin@example.com",
"password": "new-password",
"currentPassword": "current-password",
"totpToken": "123456",
},
)
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(fake.login_calls, [("admin", "current-password", "123456")])
self.assertEqual(
fake.update_calls,
[
{
"token": "admin-token",
"user_id": 1,
"username": "admin",
"email": "admin@example.com",
"password": "new-password",
}
],
)
self.assertIn("reauth-token", fake.logged_out)
class EnabledModeSetupAndLoginTests(unittest.TestCase): class EnabledModeSetupAndLoginTests(unittest.TestCase):
"""Exercises the real (client is not None) path, including the """Exercises the real (client is not None) path, including the
setup-claim flag's interaction with the store.""" setup-claim flag's interaction with the store."""
+29 -8
View File
@@ -9,7 +9,12 @@ from shared_backend.auth import (
verify_password, verify_password,
) )
from shared_backend.clientip import client_address, parse_trusted_proxies from shared_backend.clientip import client_address, parse_trusted_proxies
from shared_backend.totp import verify_totp from shared_backend.coreconfig import (
EXAMPLE_INTERNAL_SECRETS,
MIN_INTERNAL_SECRET_LENGTH,
internal_secret_matches,
)
from shared_backend.totp import verify_totp, verify_totp_step
# The Go, Node and Python auth helpers load the same fixtures; see "description" in the file. # The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
CONTRACT_PATH = Path(__file__).resolve().parents[3] / "contract" / "auth-contract.json" CONTRACT_PATH = Path(__file__).resolve().parents[3] / "contract" / "auth-contract.json"
@@ -27,22 +32,22 @@ class AuthContractTests(unittest.TestCase):
password = self.contract["password"] password = self.contract["password"]
for entry in password["hashes"]: for entry in password["hashes"]:
with self.subTest(entry["name"]): with self.subTest(entry["name"]):
plaintext = entry.get("password", password["plaintext"])
wrong_password = entry.get("wrongPassword", password["wrongPassword"])
self.assertEqual( self.assertEqual(
verify_password(password["plaintext"], entry["hash"]), verify_password(plaintext, entry["hash"]),
entry["verifies"]["python"], entry["verifies"]["python"],
) )
self.assertFalse(verify_password(password["wrongPassword"], entry["hash"])) self.assertFalse(verify_password(wrong_password, entry["hash"]))
if "python" in entry.get("needsUpgrade", {}): if "python" in entry.get("needsUpgrade", {}):
want = entry["needsUpgrade"]["python"] want = entry["needsUpgrade"]["python"]
self.assertEqual(password_hash_needs_upgrade(entry["hash"]), want) self.assertEqual(password_hash_needs_upgrade(entry["hash"]), want)
valid, upgraded = verify_and_upgrade_password( valid, upgraded = verify_and_upgrade_password(plaintext, entry["hash"])
password["plaintext"], entry["hash"]
)
self.assertTrue(valid) self.assertTrue(valid)
self.assertEqual(upgraded is not None, want) self.assertEqual(upgraded is not None, want)
if upgraded is not None: if upgraded is not None:
self.assertTrue(upgraded.startswith("bcrypt$")) self.assertTrue(upgraded.startswith(("bcrypt$", "bcrypt-sha256$")))
self.assertTrue(verify_password(password["plaintext"], upgraded)) self.assertTrue(verify_password(plaintext, upgraded))
def test_the_password_length_contract_holds_for_python(self) -> None: def test_the_password_length_contract_holds_for_python(self) -> None:
too_long = self.contract["password"]["tooLongToHash"] too_long = self.contract["password"]["tooLongToHash"]
@@ -59,6 +64,11 @@ class AuthContractTests(unittest.TestCase):
with self.subTest(entry["name"]): with self.subTest(entry["name"]):
secret = entry.get("secret", totp["secret"]) secret = entry.get("secret", totp["secret"])
self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"]) self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"])
if entry["valid"]:
self.assertEqual(
verify_totp_step(secret, entry["code"], entry["unix"]),
entry.get("matchedStep", entry["unix"] // 30),
)
def test_client_address_follows_the_contract(self) -> None: def test_client_address_follows_the_contract(self) -> None:
section = self.contract["clientAddress"] section = self.contract["clientAddress"]
@@ -72,6 +82,17 @@ class AuthContractTests(unittest.TestCase):
with self.subTest(value), self.assertRaises(ValueError): with self.subTest(value), self.assertRaises(ValueError):
parse_trusted_proxies(value) parse_trusted_proxies(value)
def test_internal_secret_gate_follows_the_contract(self) -> None:
rule = self.contract["internalSecret"]
self.assertEqual(MIN_INTERNAL_SECRET_LENGTH, rule["minLength"])
self.assertEqual(EXAMPLE_INTERNAL_SECRETS, frozenset(rule["placeholders"]))
for entry in rule["cases"]:
with self.subTest(entry["name"]):
self.assertEqual(
internal_secret_matches(entry["provided"], entry["secret"]),
entry["matches"],
)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+30 -9
View File
@@ -22,7 +22,7 @@ from shared_backend.postgres import (
retry_startup, retry_startup,
) )
from shared_backend.tokens import hash_token, new_session_token from shared_backend.tokens import hash_token, new_session_token
from shared_backend.totp import totp_provisioning_uri, verify_totp from shared_backend.totp import totp_provisioning_uri, verify_totp, verify_totp_step
class SharedBackendTests(unittest.TestCase): class SharedBackendTests(unittest.TestCase):
@@ -48,23 +48,37 @@ class SharedBackendTests(unittest.TestCase):
self.assertFalse(password_hash_needs_upgrade(password_hash)) self.assertFalse(password_hash_needs_upgrade(password_hash))
def test_unprefixed_legacy_bcrypt_hashes_still_verify_and_are_upgraded(self): def test_unprefixed_legacy_bcrypt_hashes_still_verify_and_are_upgraded(self):
legacy = bcrypt.hashpw( legacy = bcrypt.hashpw(b"correct horse battery staple", bcrypt.gensalt(rounds=12)).decode()
b"correct horse battery staple", bcrypt.gensalt(rounds=12)
).decode()
self.assertTrue(verify_password("correct horse battery staple", legacy)) self.assertTrue(verify_password("correct horse battery staple", legacy))
self.assertFalse(verify_password("wrong password", legacy)) self.assertFalse(verify_password("wrong password", legacy))
self.assertTrue(password_hash_needs_upgrade(legacy)) self.assertTrue(password_hash_needs_upgrade(legacy))
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", legacy) valid, upgraded = verify_and_upgrade_password("correct horse battery staple", legacy)
self.assertTrue(valid) self.assertTrue(valid)
assert upgraded is not None
self.assertTrue(upgraded.startswith("bcrypt$$2b$12$")) self.assertTrue(upgraded.startswith("bcrypt$$2b$12$"))
self.assertTrue(verify_password("correct horse battery staple", upgraded)) self.assertTrue(verify_password("correct horse battery staple", upgraded))
self.assertFalse(password_hash_needs_upgrade(upgraded)) self.assertFalse(password_hash_needs_upgrade(upgraded))
def test_long_legacy_pbkdf2_password_migrates_without_truncation(self):
import hashlib
password = "legacy:" + "x" * 80
salt = "0123456789abcdef0123456789abcdef"
expected = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 100_000).hex()
legacy = f"{salt}:{expected}"
valid, upgraded = verify_and_upgrade_password(password, legacy)
self.assertTrue(valid)
assert upgraded is not None
self.assertTrue(upgraded.startswith("bcrypt-sha256$$2b$12$"))
self.assertTrue(verify_password(password, upgraded))
self.assertFalse(verify_password(password + "x", upgraded))
def test_a_cost_below_the_current_policy_is_upgraded(self): def test_a_cost_below_the_current_policy_is_upgraded(self):
low_cost = "bcrypt$" + bcrypt.hashpw( low_cost = (
b"correct horse battery staple", bcrypt.gensalt(rounds=4) "bcrypt$"
).decode() + bcrypt.hashpw(b"correct horse battery staple", bcrypt.gensalt(rounds=4)).decode()
)
self.assertTrue(password_hash_needs_upgrade(low_cost)) self.assertTrue(password_hash_needs_upgrade(low_cost))
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", low_cost) valid, upgraded = verify_and_upgrade_password("correct horse battery staple", low_cost)
self.assertTrue(valid) self.assertTrue(valid)
@@ -94,6 +108,7 @@ class SharedBackendTests(unittest.TestCase):
async def run(): async def run():
valid, upgraded = await verify_and_upgrade_password_async(password, legacy) valid, upgraded = await verify_and_upgrade_password_async(password, legacy)
self.assertTrue(valid) self.assertTrue(valid)
assert upgraded is not None
self.assertTrue(await verify_password_async(password, upgraded)) self.assertTrue(await verify_password_async(password, upgraded))
asyncio.run(run()) asyncio.run(run())
@@ -114,8 +129,12 @@ class SharedBackendTests(unittest.TestCase):
return len(attempts) return len(attempts)
self.assertTrue(is_transient_connection_error(ConnectionRefusedError())) self.assertTrue(is_transient_connection_error(ConnectionRefusedError()))
self.assertTrue(is_transient_connection_error(asyncpg.exceptions.ConnectionDoesNotExistError("closed"))) self.assertTrue(
self.assertFalse(is_transient_connection_error(asyncpg.exceptions.InvalidPasswordError("bad"))) is_transient_connection_error(asyncpg.exceptions.ConnectionDoesNotExistError("closed"))
)
self.assertFalse(
is_transient_connection_error(asyncpg.exceptions.InvalidPasswordError("bad"))
)
self.assertFalse(is_transient_connection_error(ValueError("bad"))) self.assertFalse(is_transient_connection_error(ValueError("bad")))
self.assertEqual(asyncio.run(retry_with(ValueError("bad"))), 1) self.assertEqual(asyncio.run(retry_with(ValueError("bad"))), 1)
self.assertEqual(asyncio.run(retry_with(ConnectionRefusedError())), 3) self.assertEqual(asyncio.run(retry_with(ConnectionRefusedError())), 3)
@@ -151,6 +170,8 @@ class SharedBackendTests(unittest.TestCase):
] ]
for timestamp, code in vectors: for timestamp, code in vectors:
self.assertTrue(verify_totp(secret, code, timestamp)) self.assertTrue(verify_totp(secret, code, timestamp))
self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30)
self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30)
self.assertTrue( self.assertTrue(
totp_provisioning_uri("Example App", "admin@example.com", secret).startswith( totp_provisioning_uri("Example App", "admin@example.com", secret).startswith(
"otpauth://totp/" "otpauth://totp/"
@@ -1,6 +1,15 @@
import json
import unittest import unittest
from shared_backend.coreconfig import Info, Store, internal_secret_matches from shared_backend.coreconfig import (
MIN_INTERNAL_SECRET_LENGTH,
Info,
Store,
follow_omnilogger,
handle_core_services_push,
internal_secret_matches,
internal_secret_usable,
)
class StoreDefaultsTests(unittest.TestCase): class StoreDefaultsTests(unittest.TestCase):
@@ -62,6 +71,9 @@ class StoreSetTests(unittest.TestCase):
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com") self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
LONG_SECRET = "shared-secret-value"
class InternalSecretTests(unittest.TestCase): class InternalSecretTests(unittest.TestCase):
def test_unset_or_empty_secret_never_matches(self): def test_unset_or_empty_secret_never_matches(self):
self.assertFalse(internal_secret_matches(None, None)) self.assertFalse(internal_secret_matches(None, None))
@@ -70,15 +82,37 @@ class InternalSecretTests(unittest.TestCase):
self.assertFalse(internal_secret_matches("", None)) self.assertFalse(internal_secret_matches("", None))
def test_compares_the_whole_secret(self): def test_compares_the_whole_secret(self):
self.assertTrue(internal_secret_matches("shared-secret", "shared-secret")) self.assertTrue(internal_secret_matches(LONG_SECRET, LONG_SECRET))
self.assertFalse(internal_secret_matches("shared-secreT", "shared-secret")) self.assertFalse(internal_secret_matches("shared-secret-valuE", LONG_SECRET))
self.assertFalse(internal_secret_matches(None, "shared-secret")) self.assertFalse(internal_secret_matches(None, LONG_SECRET))
def test_short_secret_never_matches(self):
short = "x" * (MIN_INTERNAL_SECRET_LENGTH - 1)
self.assertFalse(internal_secret_matches(short, short))
def test_placeholder_secret_never_matches(self):
for placeholder in ("SECRET", "change-me-to-a-long-random-value"):
with self.subTest(placeholder=placeholder):
self.assertFalse(internal_secret_matches(placeholder, placeholder))
def test_usable_requires_minimum_length_and_no_placeholder(self):
self.assertFalse(internal_secret_usable(None))
self.assertFalse(internal_secret_usable(""))
self.assertFalse(internal_secret_usable("x" * (MIN_INTERNAL_SECRET_LENGTH - 1)))
self.assertTrue(internal_secret_usable("x" * MIN_INTERNAL_SECRET_LENGTH))
self.assertFalse(internal_secret_usable("change-me-to-a-long-random-value"))
self.assertTrue(internal_secret_usable(LONG_SECRET))
class UrlValidationTests(unittest.TestCase): class UrlValidationTests(unittest.TestCase):
def test_rejects_urls_that_are_not_http_or_https_with_a_host(self): def test_rejects_urls_that_are_not_http_or_https_with_a_host(self):
store = Store(Info(auth_guard_url="http://auth.example.com")) store = Store(Info(auth_guard_url="http://auth.example.com"))
for bad in ["javascript:alert(1)", "auth.example.com", "ftp://carrier.example.com", "http://"]: for bad in [
"javascript:alert(1)",
"auth.example.com",
"ftp://carrier.example.com",
"http://",
]:
with self.subTest(url=bad), self.assertRaises(ValueError): with self.subTest(url=bad), self.assertRaises(ValueError):
store.set(Info(auth_guard_url=bad)) store.set(Info(auth_guard_url=bad))
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
@@ -86,5 +120,192 @@ class UrlValidationTests(unittest.TestCase):
self.assertEqual(store.auth_guard_url, "http://auth.example.com") self.assertEqual(store.auth_guard_url, "http://auth.example.com")
class OmniLoggerStoreTests(unittest.TestCase):
def test_from_json_reads_omni_fields_and_to_json_never_carries_the_token(self):
info = Info.from_json(
{"omniLoggerUrl": "http://omni.example.com", "omniLoggerIngestToken": "tok-123"}
)
self.assertEqual(info.omni_logger_url, "http://omni.example.com")
self.assertEqual(info.omni_logger_ingest_token, "tok-123")
self.assertEqual(info.to_json()["omniLoggerUrl"], "http://omni.example.com")
self.assertNotIn("omniLoggerIngestToken", info.to_json())
self.assertNotIn("tok-123", json.dumps(info.to_json()))
self.assertNotIn("tok-123", repr(info))
def test_keeps_last_non_blank_values_and_strips_the_trailing_slash(self):
store = Store()
store.set(
Info(omni_logger_url="http://omni.example.com/", omni_logger_ingest_token="tok-1")
)
store.set(Info(omni_logger_url=" ", omni_logger_ingest_token=""))
info = store.get()
self.assertEqual(info.omni_logger_url, "http://omni.example.com")
self.assertEqual(info.omni_logger_ingest_token, "tok-1")
def test_a_bad_omni_url_is_refused_and_nothing_changes(self):
store = Store()
store.set(Info(omni_logger_url="http://omni.example.com", omni_logger_ingest_token="tok-1"))
for bad in ["omni.example.com", "ftp://omni.example.com", "http://"]:
with self.subTest(url=bad), self.assertRaises(ValueError):
store.set(Info(omni_logger_url=bad, omni_logger_ingest_token="tok-2"))
self.assertEqual(store.get().omni_logger_url, "http://omni.example.com")
self.assertEqual(store.get().omni_logger_ingest_token, "tok-1")
def test_subscribers_and_on_update_both_see_every_set(self):
store = Store()
from_on_update, from_subscriber = [], []
store.on_update(from_on_update.append)
store.subscribe(from_subscriber.append)
store.set(Info(auth_guard_url="http://auth.example.com"))
self.assertEqual(len(from_on_update), 1)
self.assertEqual(len(from_subscriber), 1)
self.assertEqual(from_subscriber[0].auth_guard_url, "http://auth.example.com")
class _RecordingShipper:
def __init__(self):
self.calls = []
def set_credentials(self, base_url, token):
self.calls.append((base_url, token))
class FollowOmniLoggerTests(unittest.TestCase):
def setUp(self):
self.store = Store()
self.shipper = _RecordingShipper()
follow_omnilogger(self.store, self.shipper)
def test_a_push_with_both_values_sets_the_shipper(self):
self.store.set(
Info(omni_logger_url="http://omni.example.com", omni_logger_ingest_token="tok-1")
)
self.assertEqual(self.shipper.calls, [("http://omni.example.com", "tok-1")])
def test_a_token_without_a_url_leaves_the_shipper_alone(self):
self.store.set(Info(omni_logger_ingest_token="tok-1"))
self.assertEqual(self.shipper.calls, [])
def test_a_url_pushed_after_a_token_applies_both(self):
self.store.set(Info(omni_logger_ingest_token="tok-1"))
self.store.set(Info(omni_logger_url="http://omni.example.com"))
self.assertEqual(self.shipper.calls, [("http://omni.example.com", "tok-1")])
def test_a_later_token_only_push_reuses_the_stored_url(self):
self.store.set(
Info(omni_logger_url="http://omni.example.com", omni_logger_ingest_token="tok-1")
)
self.store.set(Info(omni_logger_ingest_token="tok-2"))
self.assertEqual(
self.shipper.calls,
[("http://omni.example.com", "tok-1"), ("http://omni.example.com", "tok-2")],
)
def test_pushes_without_omni_fields_do_not_touch_the_shipper(self):
self.store.set(Info(auth_guard_url="http://auth.example.com"))
self.assertEqual(self.shipper.calls, [])
def test_a_store_without_omni_values_does_not_apply_at_startup(self):
follow_omnilogger(Store(), self.shipper)
self.assertEqual(self.shipper.calls, [])
INTERNAL_SECRET = "a-sufficiently-long-secret-value"
PUSH_BODY = {"omniLoggerUrl": "http://omni.example.com", "omniLoggerIngestToken": "tok-secret-1"}
AUTH_ERROR = {"error": "internal service authentication required"}
JSON_ERROR = {"error": "invalid JSON body"}
URL_ERROR = {"error": "core service URL must be an http or https URL with a host"}
class HandleCoreServicesPushTests(unittest.TestCase):
def setUp(self):
self.store = Store()
self.shipper = _RecordingShipper()
follow_omnilogger(self.store, self.shipper)
def push(self, body, auth=INTERNAL_SECRET, secret=INTERNAL_SECRET):
raw = body if isinstance(body, bytes) else json.dumps(body).encode("utf-8")
return handle_core_services_push(self.store, secret, auth, raw)
def test_a_missing_or_wrong_x_internal_auth_gets_401(self):
for auth in (None, "", "wrong-secret-value-here", INTERNAL_SECRET + "x"):
with self.subTest(auth=auth):
self.assertEqual(self.push(PUSH_BODY, auth=auth), (401, AUTH_ERROR))
self.assertEqual(self.shipper.calls, [])
self.assertEqual(self.store.get().omni_logger_url, "")
def test_an_unusable_secret_refuses_every_caller(self):
for secret in (None, "", "SECRET", "change-me-to-a-long-random-value", "short"):
with self.subTest(secret=secret):
status, _ = self.push(PUSH_BODY, auth=secret, secret=secret)
self.assertEqual(status, 401)
status, _ = self.push(PUSH_BODY, auth=INTERNAL_SECRET, secret=secret)
self.assertEqual(status, 401)
self.assertEqual(self.shipper.calls, [])
def test_a_valid_push_sets_the_shipper_and_never_echoes_the_token(self):
status, body = self.push(PUSH_BODY)
self.assertEqual((status, body), (200, {"ok": True}))
self.assertEqual(self.shipper.calls, [("http://omni.example.com", "tok-secret-1")])
self.assertNotIn("tok-secret-1", json.dumps(body))
def test_a_token_without_a_url_does_not_change_the_shipper(self):
status, body = self.push({"omniLoggerIngestToken": "tok-secret-1"})
self.assertEqual((status, body), (200, {"ok": True}))
self.assertEqual(self.shipper.calls, [])
def test_a_bad_omni_url_gets_400_and_changes_nothing(self):
for bad in ["omni.example.com", "ftp://omni.example.com", "javascript:alert(1)"]:
with self.subTest(url=bad):
body = {"omniLoggerUrl": bad, "omniLoggerIngestToken": "tok-secret-1"}
self.assertEqual(self.push(body), (400, URL_ERROR))
self.assertEqual(self.shipper.calls, [])
def test_a_bad_auth_guard_url_gets_400(self):
self.assertEqual(self.push({"authGuardUrl": "auth.example.com"}), (400, URL_ERROR))
def test_a_field_of_the_wrong_type_gets_400_not_a_server_error(self):
for body in (
{"carrierNodeUrls": 5},
{"carrierNodeUrls": True},
{"carrierNodeUrls": "http://carrier.example.com"},
{"carrierNodeUrl": ["http://carrier.example.com"]},
{"authGuardUrl": 5},
):
with self.subTest(body=body):
self.assertEqual(self.push(body), (400, JSON_ERROR))
self.assertEqual(self.shipper.calls, [])
def test_an_oversized_body_or_a_body_that_is_not_a_json_object_gets_400(self):
cases = [
json.dumps({"x": "a" * 4096}).encode("utf-8"),
b"not json",
b"[1, 2]",
b'"a string"',
b"\xff\xfe\x00",
json.dumps({"omniLoggerUrl": 5}).encode("utf-8"),
json.dumps({"omniLoggerIngestToken": ["tok"]}).encode("utf-8"),
]
for raw in cases:
with self.subTest(raw=raw[:20]):
self.assertEqual(self.push(raw), (400, JSON_ERROR))
def test_a_body_of_exactly_4096_bytes_is_read(self):
raw = json.dumps({"x": "a" * 4087}).encode("utf-8")
self.assertEqual(len(raw), 4096)
self.assertEqual(self.push(raw), (200, {"ok": True}))
def test_other_fields_and_null_values_are_ignored(self):
body = {
"contentScannerUrl": "not a url",
"comfyUiUrl": 7,
"carrierNodeSecret": "not-used-here",
"omniLoggerIngestToken": None,
"omniLoggerUrl": "http://omni.example.com",
}
self.assertEqual(self.push(body), (200, {"ok": True}))
self.assertEqual(self.shipper.calls, [])
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
@@ -0,0 +1,688 @@
import contextlib
import io
import json
import logging
import socket
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest import mock
from shared_backend.logshipper import (
DROPPED_CONTEXT,
MAX_BATCH_ENTRIES,
MAX_BODY_BYTES,
MAX_CONTEXT_BYTES,
MAX_MESSAGE_BYTES,
TRUNCATED_MARKER,
OmniLoggerHandler,
Shipper,
to_omnilogger_level,
)
class _FakeOmniLogger:
"""Local stand-in for OmniLogger's POST /api/logs. It records every request. Each request is
answered with the next status in `statuses`, and with `status` once that list is used up.
Only requests answered with a 2xx count as delivered, so `batches()` and `entries()` leave out
the refused ones."""
def __init__(self, status: int = 202) -> None:
self.status = status
self.statuses: list[int] = []
self.requests: list[dict] = []
self._lock = threading.Lock()
fake = self
class Handler(BaseHTTPRequestHandler):
def do_POST(self): # noqa: N802 - http.server's naming
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length)
with fake._lock:
status = fake.statuses.pop(0) if fake.statuses else fake.status
fake.requests.append(
{
"path": self.path,
"authorization": self.headers.get("Authorization"),
"content_type": self.headers.get("Content-Type"),
"body": raw,
"status": status,
}
)
self.send_response(status)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args): # keep the test output quiet
pass
self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.url = f"http://127.0.0.1:{self._server.server_port}"
self._thread = threading.Thread(
target=self._server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True
)
self._thread.start()
def stop(self) -> None:
self._server.shutdown()
self._server.server_close()
def batches(self) -> list[list[dict]]:
with self._lock:
return [
json.loads(request["body"])
for request in self.requests
if 200 <= request["status"] < 300
]
def entries(self) -> list[dict]:
return [entry for batch in self.batches() for entry in batch]
def _unused_url() -> str:
"""A URL nothing listens on, so connecting to it is refused at once."""
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
return f"http://127.0.0.1:{port}"
def _wait_for(predicate, timeout: float = 5.0) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return True
time.sleep(0.01)
return predicate()
class ShipperTestCase(unittest.TestCase):
def setUp(self) -> None:
self.omni = _FakeOmniLogger()
self.addCleanup(self.omni.stop)
def make_shipper(self, **overrides) -> Shipper:
"""A shipper that does not flush on its own, so each test decides when entries go out."""
options = {
"base_url": self.omni.url,
"ingest_token": "secret-token",
"service": "svc",
"flush_interval": 3600,
}
options.update(overrides)
shipper = Shipper(**options)
self.addCleanup(shipper.close)
return shipper
class BatchingTests(ShipperTestCase):
def test_flush_sends_every_buffered_entry_in_one_request(self):
shipper = self.make_shipper()
shipper.info("one")
shipper.error("two")
shipper.flush()
shipper.flush() # nothing left, so no second request
self.assertEqual(len(self.omni.requests), 1)
self.assertEqual([e["message"] for e in self.omni.entries()], ["one", "two"])
def test_reaching_the_batch_size_flushes_without_waiting_for_the_interval(self):
shipper = self.make_shipper(max_batch_size=2)
shipper.info("a")
shipper.info("b")
self.assertTrue(_wait_for(lambda: len(self.omni.entries()) == 2))
def test_the_interval_flushes_a_partial_batch(self):
shipper = self.make_shipper(flush_interval=0.05)
shipper.info("lone entry")
self.assertTrue(_wait_for(lambda: len(self.omni.entries()) == 1))
def test_a_batch_never_exceeds_1000_entries(self):
shipper = self.make_shipper(max_batch_size=10**6, buffer_capacity=5000)
for i in range(2500):
shipper.info(f"entry {i}")
shipper.flush()
batches = self.omni.batches()
self.assertTrue(all(len(batch) <= MAX_BATCH_ENTRIES for batch in batches))
self.assertEqual(sum(len(batch) for batch in batches), 2500)
self.assertEqual(self.omni.entries()[-1]["message"], "entry 2499")
def test_a_batch_body_stays_under_2_mib(self):
shipper = self.make_shipper(max_batch_size=10**6, buffer_capacity=1000)
for _ in range(600):
shipper.info("x" * MAX_MESSAGE_BYTES) # about 8 KiB each, so 600 cannot fit in one body
shipper.flush()
self.assertGreater(len(self.omni.requests), 1)
self.assertTrue(all(len(r["body"]) < MAX_BODY_BYTES for r in self.omni.requests))
self.assertEqual(len(self.omni.entries()), 600)
def test_close_sends_what_is_left_and_is_idempotent(self):
shipper = self.make_shipper()
shipper.info("last words")
shipper.close()
shipper.close()
self.assertEqual([e["message"] for e in self.omni.entries()], ["last words"])
def test_logging_after_close_is_ignored(self):
shipper = self.make_shipper()
shipper.close()
shipper.info("too late")
shipper.flush()
self.assertEqual(self.omni.requests, [])
class WireFormatTests(ShipperTestCase):
def test_request_uses_bearer_auth_json_and_the_api_logs_path(self):
shipper = self.make_shipper(base_url=self.omni.url + "/")
shipper.info("hello")
shipper.flush()
request = self.omni.requests[0]
self.assertEqual(request["path"], "/api/logs")
self.assertEqual(request["authorization"], "Bearer secret-token")
self.assertEqual(request["content_type"], "application/json")
def test_every_entry_carries_the_service_name(self):
shipper = self.make_shipper(service="heretic")
shipper.info("a")
shipper.critical("b")
shipper.flush()
self.assertEqual({e["service"] for e in self.omni.entries()}, {"heretic"})
def test_entry_fields_and_occurred_at_format(self):
shipper = self.make_shipper()
shipper.warning("careful", {"path": "/x", "status": 503})
shipper.info("plain")
shipper.flush()
warned, plain = self.omni.entries()
self.assertEqual(warned["level"], "warn")
self.assertEqual(warned["context"], {"path": "/x", "status": 503})
self.assertNotIn("context", plain)
for entry in (warned, plain):
self.assertRegex(entry["occurred_at"], r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$")
def test_context_is_sent_unscrubbed(self):
shipper = self.make_shipper()
shipper.info("request", {"userId": 7})
shipper.flush()
self.assertEqual(self.omni.entries()[0]["context"], {"userId": 7})
class ClampingTests(ShipperTestCase):
def test_a_long_message_is_cut_on_a_character_boundary_with_the_marker(self):
shipper = self.make_shipper()
shipper.info("é" * 5000) # 10000 bytes, and 8181 is an odd byte count to cut at
shipper.flush()
message = self.omni.entries()[0]["message"]
self.assertLessEqual(len(message.encode("utf-8")), MAX_MESSAGE_BYTES)
self.assertTrue(message.endswith(TRUNCATED_MARKER))
self.assertTrue(set(message[: -len(TRUNCATED_MARKER)]) <= {"é"})
def test_a_message_of_exactly_the_limit_is_untouched(self):
shipper = self.make_shipper()
exact = "y" * MAX_MESSAGE_BYTES
shipper.info(exact)
shipper.flush()
self.assertEqual(self.omni.entries()[0]["message"], exact)
def test_a_nul_byte_in_a_message_is_written_as_escape_text(self):
shipper = self.make_shipper()
shipper.info("before\x00after")
shipper.flush()
self.assertEqual(self.omni.entries()[0]["message"], "before\\u0000after")
def test_an_oversized_context_is_replaced_by_the_dropped_marker(self):
shipper = self.make_shipper()
shipper.info("big", {"blob": "x" * MAX_CONTEXT_BYTES})
shipper.flush()
entry = self.omni.entries()[0]
self.assertEqual(entry["context"], {"context_dropped": True})
self.assertEqual(entry["message"], "big")
def test_a_context_with_a_nul_is_replaced_but_an_ordinary_one_is_kept(self):
shipper = self.make_shipper()
shipper.info("nul", {"s": "a\x00b"})
shipper.info("fine", {"ok": True})
shipper.flush()
nul, fine = self.omni.entries()
self.assertEqual(json.loads(DROPPED_CONTEXT), nul["context"])
self.assertEqual(fine["context"], {"ok": True})
def test_an_unserialisable_context_is_replaced_not_lost(self):
shipper = self.make_shipper()
shipper.info("nan", {"value": float("nan")})
shipper.flush()
entry = self.omni.entries()[0]
self.assertEqual(entry["message"], "nan")
self.assertEqual(entry["context"], {"context_dropped": True})
class DisabledModeTests(unittest.TestCase):
def test_from_env_returns_none_unless_both_variables_are_set(self):
cases = [
{},
{"OMNILOGGER_URL": "http://omni:8080"},
{"OMNILOGGER_INGEST_TOKEN": "token"},
{"OMNILOGGER_URL": "", "OMNILOGGER_INGEST_TOKEN": "token"},
{"OMNILOGGER_URL": "http://omni:8080", "OMNILOGGER_INGEST_TOKEN": " "},
]
for environ in cases:
with self.subTest(environ=environ):
self.assertIsNone(Shipper.from_env("svc", environ=environ))
def test_from_env_builds_a_shipper_when_both_are_set(self):
omni = _FakeOmniLogger()
self.addCleanup(omni.stop)
shipper = Shipper.from_env(
"heretic",
environ={"OMNILOGGER_URL": omni.url, "OMNILOGGER_INGEST_TOKEN": "tok"},
level="warn",
)
self.addCleanup(shipper.close)
self.assertIsNotNone(shipper)
shipper.info("below the warn threshold")
shipper.error("shipped")
shipper.flush()
self.assertEqual([e["message"] for e in omni.entries()], ["shipped"])
self.assertEqual(omni.requests[0]["authorization"], "Bearer tok")
self.assertEqual(omni.entries()[0]["service"], "heretic")
def test_from_env_reads_os_environ_by_default(self):
omni = _FakeOmniLogger()
self.addCleanup(omni.stop)
with mock.patch.dict(
"os.environ",
{"OMNILOGGER_URL": omni.url, "OMNILOGGER_INGEST_TOKEN": "env-token"},
):
shipper = Shipper.from_env("svc")
self.assertIsNotNone(shipper)
self.addCleanup(shipper.close)
def test_disabled_logging_makes_no_network_calls_and_prints_nothing_extra(self):
omni = _FakeOmniLogger()
self.addCleanup(omni.stop)
stdout, stderr = io.StringIO(), io.StringIO()
logger = logging.getLogger("tests.logshipper.disabled")
logger.addHandler(logging.StreamHandler(stdout))
logger.setLevel(logging.INFO)
self.addCleanup(logger.handlers.clear)
with contextlib.redirect_stderr(stderr):
shipper = Shipper.from_env("svc", environ={})
logger.info("local only")
self.assertIsNone(shipper)
self.assertEqual(omni.requests, [])
self.assertEqual(stderr.getvalue(), "")
self.assertEqual(stdout.getvalue(), "local only\n")
class LevelMappingTests(ShipperTestCase):
def test_standard_levels_map_to_omnilogger_names(self):
self.assertEqual(
[
to_omnilogger_level(logging.DEBUG),
to_omnilogger_level(logging.INFO),
to_omnilogger_level(logging.WARNING),
to_omnilogger_level(logging.ERROR),
to_omnilogger_level(logging.CRITICAL),
],
["debug", "info", "warn", "error", "critical"],
)
def test_levels_between_standard_ones_take_the_lower_name(self):
self.assertEqual(to_omnilogger_level(25), "info")
self.assertEqual(to_omnilogger_level(35), "warn")
self.assertEqual(to_omnilogger_level(55), "critical")
self.assertEqual(to_omnilogger_level(5), "debug")
def test_handler_ships_each_record_at_its_mapped_level(self):
shipper = self.make_shipper(level="debug")
logger = logging.getLogger("tests.logshipper.levels")
logger.handlers.clear()
logger.addHandler(OmniLoggerHandler(shipper))
logger.setLevel(logging.DEBUG)
logger.propagate = False
self.addCleanup(setattr, logger, "propagate", True)
self.addCleanup(logger.handlers.clear)
logger.debug("d")
logger.info("i")
logger.warning("w")
logger.error("e")
logger.critical("c")
shipper.flush()
entries = self.omni.entries()
self.assertEqual(
[(e["level"], e["message"]) for e in entries],
[("debug", "d"), ("info", "i"), ("warn", "w"), ("error", "e"), ("critical", "c")],
)
self.assertEqual({e["context"]["logger"] for e in entries}, {"tests.logshipper.levels"})
def test_handler_writes_nothing_locally(self):
shipper = self.make_shipper()
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
OmniLoggerHandler(shipper).handle(
logging.LogRecord("n", logging.ERROR, __file__, 1, "quiet", None, None)
)
self.assertEqual(stderr.getvalue(), "")
def test_handler_appends_a_traceback_to_the_message(self):
shipper = self.make_shipper()
logger = logging.getLogger("tests.logshipper.traceback")
logger.handlers.clear()
logger.addHandler(OmniLoggerHandler(shipper))
logger.propagate = False
self.addCleanup(setattr, logger, "propagate", True)
self.addCleanup(logger.handlers.clear)
try:
raise ValueError("boom")
except ValueError:
logger.exception("failed")
shipper.flush()
message = self.omni.entries()[0]["message"]
self.assertTrue(message.startswith("failed\nTraceback"))
self.assertIn("ValueError: boom", message)
def test_threshold_filters_lower_levels_and_silent_ships_nothing(self):
warn_only = self.make_shipper(level="warn")
warn_only.info("skipped")
warn_only.warning("kept")
silent = self.make_shipper(level="silent")
silent.critical("never")
warn_only.flush()
silent.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["kept"])
class FailureTests(ShipperTestCase):
def test_a_rejecting_sink_never_raises_and_warns_once(self):
omni = _FakeOmniLogger(status=400)
self.addCleanup(omni.stop)
shipper = self.make_shipper(base_url=omni.url)
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
shipper.info("one")
shipper.flush()
shipper.info("two")
shipper.flush()
self.assertEqual(len(omni.requests), 2)
self.assertEqual(stderr.getvalue().count("OmniLogger rejected"), 1)
def test_an_unreachable_sink_never_raises(self):
shipper = self.make_shipper(base_url=_unused_url())
shipper.info("nobody home")
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
shipper.flush()
shipper.info("again")
shipper.flush() # inside the warning interval, so silent
self.assertIn("send 1 entries", stderr.getvalue())
self.assertEqual(stderr.getvalue().count("[logshipper]"), 1)
def test_a_full_buffer_drops_the_newest_entries_and_warns_once(self):
shipper = self.make_shipper(buffer_capacity=3, max_batch_size=10**6)
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
for i in range(10):
shipper.info(f"m{i}")
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["m0", "m1", "m2"])
self.assertEqual(stderr.getvalue().count("buffer full"), 1)
def test_a_redirect_is_not_followed_so_the_token_stays_with_the_configured_url(self):
class Redirect(BaseHTTPRequestHandler):
def do_POST(self): # noqa: N802
self.rfile.read(int(self.headers.get("Content-Length", "0")))
self.send_response(307)
self.send_header("Location", "http://127.0.0.1:1/elsewhere")
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Redirect)
threading.Thread(
target=server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True
).start()
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
shipper = self.make_shipper(base_url=f"http://127.0.0.1:{server.server_port}")
shipper.info("x")
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
shipper.flush()
self.assertIn("HTTP 307", stderr.getvalue())
def _buffered_messages(shipper: Shipper) -> list[str]:
return [json.loads(entry)["message"] for entry in shipper._buffer]
class RetryTests(ShipperTestCase):
def test_a_503_is_retried_and_each_entry_arrives_once_in_order(self):
self.omni.statuses = [503]
shipper = self.make_shipper()
with contextlib.redirect_stderr(io.StringIO()) as stderr:
shipper.info("a")
shipper.info("b")
shipper.flush() # refused with 503, so a and b wait for the next flush
shipper.info("c")
shipper.flush() # accepted: a, b and c, in order
shipper.flush() # nothing left, so no third request
self.assertEqual([r["status"] for r in self.omni.requests], [503, 202])
self.assertEqual([e["message"] for e in self.omni.entries()], ["a", "b", "c"])
self.assertIn("will retry", stderr.getvalue())
def test_a_429_or_another_5xx_is_retried_as_well(self):
for status in (429, 500):
with self.subTest(status=status):
self.omni.statuses = [status]
shipper = self.make_shipper()
with contextlib.redirect_stderr(io.StringIO()):
shipper.info(f"after {status}")
shipper.flush()
shipper.flush()
self.assertEqual(self.omni.requests[-1]["status"], 202)
messages = [e["message"] for e in self.omni.entries()]
self.assertEqual(messages.count(f"after {status}"), 1)
def test_a_400_is_dropped_and_not_retried(self):
self.omni.statuses = [400]
shipper = self.make_shipper()
with contextlib.redirect_stderr(io.StringIO()) as stderr:
shipper.info("rejected")
shipper.flush()
shipper.flush() # nothing was kept, so no second request
shipper.info("next")
shipper.flush()
self.assertEqual([r["status"] for r in self.omni.requests], [400, 202])
self.assertEqual([e["message"] for e in self.omni.entries()], ["next"])
self.assertEqual(_buffered_messages(shipper), [])
self.assertIn("OmniLogger rejected 1 entries: HTTP 400", stderr.getvalue())
def test_a_failed_batch_stops_the_rest_of_the_flush(self):
self.omni.statuses = [202, 503]
shipper = self.make_shipper(max_batch_size=10**6, buffer_capacity=1000)
# Each entry is about 8 KiB, so these 600 need three request bodies.
messages = [f"{i:04d}".ljust(MAX_MESSAGE_BYTES, "x") for i in range(600)]
with contextlib.redirect_stderr(io.StringIO()):
for message in messages:
shipper.info(message)
shipper.flush() # the first body is accepted, the second refused, the third never sent
self.assertEqual([r["status"] for r in self.omni.requests], [202, 503])
delivered = [e["message"] for e in self.omni.entries()]
self.assertEqual(delivered, messages[: len(delivered)])
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], messages)
def test_during_an_outage_the_buffer_holds_at_most_its_capacity_oldest_first(self):
self.omni.status = 503
shipper = self.make_shipper(buffer_capacity=3, max_batch_size=10**6)
with contextlib.redirect_stderr(io.StringIO()):
for message in ("a", "b", "c"):
shipper.info(message)
shipper.flush() # refused, so a, b and c wait for the next flush
for message in ("d", "e"):
shipper.info(message) # the buffer is full, so these are dropped
shipper.flush() # still refused
self.assertEqual(_buffered_messages(shipper), ["a", "b", "c"])
self.omni.status = 202
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["a", "b", "c"])
def test_entries_logged_while_a_retry_waits_are_dropped_newest_first(self):
self.omni.status = 503
shipper = self.make_shipper(buffer_capacity=3, max_batch_size=10**6)
for message in ("a", "b", "c"):
shipper.info(message)
send = shipper._post
def send_while_logging(body, count):
# d and e are logged while a, b and c are in flight, so the retried batch does not fit.
shipper.info("d")
shipper.info("e")
return send(body, count)
shipper._post = send_while_logging
with mock.patch.object(shipper, "_warn") as warn:
shipper.flush()
del shipper._post
self.assertEqual(_buffered_messages(shipper), ["a", "b", "c"])
warn.assert_any_call("buffer full while retrying, dropping 2 log entries for service 'svc'")
self.omni.status = 202
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["a", "b", "c"])
class ConstructionTests(unittest.TestCase):
def test_the_package_exports_the_shipper_and_handler(self):
import shared_backend
self.assertIs(shared_backend.Shipper, Shipper)
self.assertIs(shared_backend.OmniLoggerHandler, OmniLoggerHandler)
def test_the_trailing_slash_is_optional_and_the_level_defaults_to_info(self):
omni = _FakeOmniLogger()
self.addCleanup(omni.stop)
shipper = Shipper(base_url=omni.url + "///", ingest_token="t", service="svc")
self.addCleanup(shipper.close)
self.assertEqual(shipper._url, omni.url + "/api/logs")
self.assertEqual(shipper._threshold, 20)
self.assertEqual(shipper._thread.name, "logshipper-svc")
class SetCredentialsTests(ShipperTestCase):
def test_a_rotated_token_is_sent_from_the_next_flush(self):
shipper = self.make_shipper()
shipper.set_credentials(self.omni.url, "rotated-token")
shipper.info("after rotation")
shipper.flush()
request = self.omni.requests[0]
self.assertEqual(request["path"], "/api/logs")
self.assertEqual(request["authorization"], "Bearer rotated-token")
self.assertEqual(self.omni.entries()[0]["message"], "after rotation")
def test_a_new_url_is_used_and_its_trailing_slashes_are_stripped(self):
other = _FakeOmniLogger()
self.addCleanup(other.stop)
shipper = self.make_shipper()
shipper.set_credentials(other.url + "///", "t2")
shipper.info("to the new endpoint")
shipper.flush()
self.assertEqual(shipper._url, other.url + "/api/logs")
self.assertEqual(self.omni.requests, [])
self.assertEqual([e["message"] for e in other.entries()], ["to the new endpoint"])
def test_an_empty_url_or_token_disables_shipping_and_drops_the_buffer(self):
for base_url, token in ((self.omni.url, ""), ("", "secret-token"), (" ", "secret-token")):
with self.subTest(base_url=base_url, token=token):
shipper = self.make_shipper()
shipper.info("buffered before disabling")
shipper.set_credentials(base_url, token)
shipper.flush()
shipper.info("ignored while disabled")
shipper.flush()
self.assertEqual(self.omni.requests, [])
def test_disabled_shipper_buffers_nothing(self):
shipper = Shipper(base_url="", ingest_token="", service="svc", flush_interval=3600)
self.addCleanup(shipper.close)
shipper.info("nothing to send to")
shipper.error("still nothing")
self.assertEqual(shipper._buffer, [])
self.assertIsNone(shipper._url)
def test_re_enabling_after_disabling_ships_again(self):
shipper = self.make_shipper()
shipper.set_credentials("", "")
shipper.set_credentials(self.omni.url, "secret-token")
shipper.info("back on")
shipper.flush()
self.assertEqual([e["message"] for e in self.omni.entries()], ["back on"])
def test_an_in_flight_flush_is_dropped_once_shipping_is_disabled(self):
shipper = self.make_shipper()
shipper.set_credentials("", "")
shipper._post(b'[{"message":"late"}]', 1)
self.assertEqual(self.omni.requests, [])
def test_changing_credentials_does_not_restart_the_background_thread(self):
shipper = self.make_shipper()
thread = shipper._thread
shipper.set_credentials("", "")
shipper.set_credentials(self.omni.url, "t2")
self.assertIs(shipper._thread, thread)
self.assertTrue(thread.is_alive())
if __name__ == "__main__":
unittest.main()
+53 -2
View File
@@ -29,7 +29,7 @@ class _FakeDatabase:
async def fetchrow(self, query: str, *args): async def fetchrow(self, query: str, *args):
self.fetched.append((query, args)) self.fetched.append((query, args))
if "totp_enabled" in query: if "totp_enabled" in query:
return {"secret": "S", "enabled": self.totp_enabled} return {"secret": "S", "enabled": self.totp_enabled, "last_used_step": -1}
for condition, row in self.rows_by_condition.items(): for condition, row in self.rows_by_condition.items():
if condition in query: if condition in query:
return row return row
@@ -51,7 +51,7 @@ def _user_row(username: str, email: str = "") -> dict:
class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase): class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None: def setUp(self) -> None:
self.db = _FakeDatabase() self.db = _FakeDatabase()
self.store = AuthStore(self.db, single_user=False) # type: ignore[arg-type] self.store = AuthStore(self.db, single_user=False) # ty: ignore[invalid-argument-type]
async def test_ensure_schema_requests_the_case_insensitive_username_index(self) -> None: async def test_ensure_schema_requests_the_case_insensitive_username_index(self) -> None:
await self.store.ensure_schema() await self.store.ensure_schema()
@@ -60,6 +60,9 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("lower(username)", statements) self.assertIn("lower(username)", statements)
# The index is created only while no clashing pair exists. # The index is created only while no clashing pair exists.
self.assertIn("HAVING count(*) > 1", statements) self.assertIn("HAVING count(*) > 1", statements)
self.assertIn(
"ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1", statements
)
async def test_set_totp_secret_refuses_while_enabled(self) -> None: async def test_set_totp_secret_refuses_while_enabled(self) -> None:
self.db.execute_status = "UPDATE 0" self.db.execute_status = "UPDATE 0"
@@ -73,6 +76,52 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse
await self.store.set_totp_secret(2, "NEWSECRET") await self.store.set_totp_secret(2, "NEWSECRET")
async def test_totp_enrollment_records_its_step_and_replay_is_rejected(self) -> None:
class ReplayDatabase(_FakeDatabase):
def __init__(self) -> None:
super().__init__()
self.state = {
"secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
"enabled": False,
"last_used_step": -1,
}
async def fetchrow(self, query: str, *args):
if "FROM auth_users WHERE id = $1" in query and "totp_enabled" in query:
return dict(self.state)
return await super().fetchrow(query, *args)
async def execute(self, query: str, *args) -> str:
self.executed.append((query, args))
step, _, secret = args
if "SET totp_enabled = true" in query:
if (
not self.state["enabled"]
and secret == self.state["secret"]
and self.state["last_used_step"] < step
):
self.state["enabled"] = True
self.state["last_used_step"] = step
return "UPDATE 1"
return "UPDATE 0"
if "SET last_used_step = $1" in query:
if (
self.state["enabled"]
and secret == self.state["secret"]
and self.state["last_used_step"] < step
):
self.state["last_used_step"] = step
return "UPDATE 1"
return "UPDATE 0"
return await super().execute(query, *args)
database = ReplayDatabase()
store = AuthStore(database) # ty: ignore[invalid-argument-type]
self.assertTrue(await store.enable_totp(1, "287082", 59.0))
self.assertEqual(database.state["last_used_step"], 1)
self.assertFalse(await store.consume_totp_code(1, "287082", 59.0))
self.assertEqual(database.state["last_used_step"], 1)
async def test_credential_writes_refuse_an_empty_hash_and_an_at_username(self) -> None: async def test_credential_writes_refuse_an_empty_hash_and_an_at_username(self) -> None:
writes = [ writes = [
lambda u, h: self.store.create_user(u, "", h), lambda u, h: self.store.create_user(u, "", h),
@@ -99,11 +148,13 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
"lower(email) = lower($1)": _user_row("owner", "owner@example.com"), "lower(email) = lower($1)": _user_row("owner", "owner@example.com"),
} }
found = await self.store.find_by_identifier("owner@example.com") found = await self.store.find_by_identifier("owner@example.com")
assert found is not None
self.assertEqual(found.username, "owner@example.com") self.assertEqual(found.username, "owner@example.com")
self.assertEqual(len(self.db.fetched), 1) self.assertEqual(len(self.db.fetched), 1)
del self.db.rows_by_condition["username = $1"] del self.db.rows_by_condition["username = $1"]
found = await self.store.find_by_identifier("owner@example.com") found = await self.store.find_by_identifier("owner@example.com")
assert found is not None
self.assertEqual(found.username, "owner") self.assertEqual(found.username, "owner")
@@ -130,6 +130,9 @@
Boolean(username && (onProfile || (showSettings && onSettings) || onAbout || aboutHref || onLogout)), Boolean(username && (onProfile || (showSettings && onSettings) || onAbout || aboutHref || onLogout)),
); );
// A lone nav item is just the app's home page, so it isn't worth a header tab (or a menu toggle).
const hasNavItems = $derived(navItems.length > 1);
function closeMenus(): void { function closeMenus(): void {
navOpen = false; navOpen = false;
profileOpen = false; profileOpen = false;
@@ -164,27 +167,29 @@
<span>{brand}</span> <span>{brand}</span>
</a> </a>
<nav aria-label="Primary navigation" class="sc-nav" data-open={navOpen}> {#if hasNavItems}
{#each navItems as item} <nav aria-label="Primary navigation" class="sc-nav" data-open={navOpen}>
{@const Icon = iconFor(item)} {#each navItems as item}
<a {@const Icon = iconFor(item)}
aria-current={isActive(item) ? 'page' : undefined} <a
class="sc-nav-link" aria-current={isActive(item) ? 'page' : undefined}
data-active={isActive(item)} class="sc-nav-link"
href={item.href} data-active={isActive(item)}
onclick={(event) => { href={item.href}
if (onNavigate) { onclick={(event) => {
event.preventDefault(); if (onNavigate) {
onNavigate(item); event.preventDefault();
} onNavigate(item);
closeMenus(); }
}} closeMenus();
> }}
<Icon aria-hidden="true" class="sc-nav-icon" size={16} strokeWidth={2} /> >
{item.label} <Icon aria-hidden="true" class="sc-nav-icon" size={16} strokeWidth={2} />
</a> {item.label}
{/each} </a>
</nav> {/each}
</nav>
{/if}
<div class="sc-header-actions"> <div class="sc-header-actions">
{#if actions}{@render actions()}{/if} {#if actions}{@render actions()}{/if}
@@ -273,14 +278,16 @@
</div> </div>
{/if} {/if}
<button {#if hasNavItems}
aria-expanded={navOpen} <button
aria-label={navOpen ? 'Close navigation menu' : 'Open navigation menu'} aria-expanded={navOpen}
class="sc-icon-button sc-mobile-menu-button" aria-label={navOpen ? 'Close navigation menu' : 'Open navigation menu'}
type="button" class="sc-icon-button sc-mobile-menu-button"
onclick={() => (navOpen = !navOpen)} type="button"
> onclick={() => (navOpen = !navOpen)}
{navOpen ? '×' : '☰'} >
</button> {navOpen ? '×' : '☰'}
</button>
{/if}
</div> </div>
</header> </header>
@@ -5,25 +5,39 @@
import MediaPlayerControls, { import MediaPlayerControls, {
type MediaPlayerKind, type MediaPlayerKind,
type MediaPlayerQualityOption, type MediaPlayerQualityOption,
type MediaPlayerSettingsGroup,
} from './MediaPlayerControls.svelte' } from './MediaPlayerControls.svelte'
let { let {
kind = 'video', kind = 'video',
src = '', src,
poster = '', poster = '',
title = '', title = '',
autoplay = false, autoplay = false,
autoplayMuted = false,
class: className = '', class: className = '',
mediaClass = '', mediaClass = '',
mediaVisible = true,
showSeekButtons: _showSeekButtons = true, showSeekButtons: _showSeekButtons = true,
seekOnCommit = false,
seekWithoutDuration = false,
showVolume = true, showVolume = true,
showFullscreen = true, showFullscreen = true,
showGraph = false, showGraph = false,
graphVisible = false, graphVisible = false,
settingsGroups = [],
settings,
qualityOptions = [], qualityOptions = [],
selectedQuality = '', selectedQuality = '',
currentTime: externalCurrentTime = null, currentTime: externalCurrentTime = null,
duration: externalDuration = null, duration: externalDuration = null,
playing: externalPlaying = null,
volume: externalVolume = null,
muted: externalMuted = null,
fullscreen: externalFullscreen = null,
playbackRate: externalPlaybackRate = null,
controlsDisabled = false,
speedDisabled = false,
onError, onError,
onPlay, onPlay,
onPause, onPause,
@@ -32,8 +46,23 @@
onEnded, onEnded,
onSeek, onSeek,
onSkip, onSkip,
onTogglePlayback,
onToggleMute,
onVolumeChange,
onToggleFullscreen,
onQualityChange, onQualityChange,
onToggleGraph, onToggleGraph,
onSpeedChange,
storageKey = '',
showSpeed = true,
controls = true,
controlsPlacement = 'overlay',
autoHideControls = true,
surfaceControls = true,
globalKeyboardControls = false,
element = $bindable(null),
preload = 'auto',
crossorigin,
endControls, endControls,
}: { }: {
kind?: MediaPlayerKind kind?: MediaPlayerKind
@@ -41,19 +70,39 @@
poster?: string poster?: string
title?: string title?: string
autoplay?: boolean autoplay?: boolean
/** Start autoplaying video muted, so browser autoplay policies allow playback. */
autoplayMuted?: boolean
class?: string class?: string
mediaClass?: string mediaClass?: string
/** Hides the media element while keeping the player controls mounted. */
mediaVisible?: boolean
/** @deprecated Seeking is available with the arrow keys and mobile double-tap. */ /** @deprecated Seeking is available with the arrow keys and mobile double-tap. */
showSeekButtons?: boolean showSeekButtons?: boolean
seekOnCommit?: boolean
seekWithoutDuration?: boolean
showVolume?: boolean showVolume?: boolean
showFullscreen?: boolean showFullscreen?: boolean
showGraph?: boolean showGraph?: boolean
graphVisible?: boolean graphVisible?: boolean
settingsGroups?: MediaPlayerSettingsGroup[]
settings?: Snippet<[string]>
qualityOptions?: MediaPlayerQualityOption[] qualityOptions?: MediaPlayerQualityOption[]
selectedQuality?: string selectedQuality?: string
currentTime?: number | null currentTime?: number | null
duration?: number | null duration?: number | null
onError?: () => void playing?: boolean | null
volume?: number | null
muted?: boolean | null
fullscreen?: boolean | null
playbackRate?: number | null
controlsDisabled?: boolean
speedDisabled?: boolean
/**
* Called when the element fails. `error.code` 4 (MEDIA_ERR_SRC_NOT_SUPPORTED) means this browser
* cannot demux or decode the source, as with AVI, WMV or ASF: the app then needs a browser-playable
* copy of the file (a server transcode) rather than the original.
*/
onError?: (error: MediaError | null) => void
onPlay?: (event: Event) => void onPlay?: (event: Event) => void
onPause?: (event: Event) => void onPause?: (event: Event) => void
onTimeUpdate?: (event: Event) => void onTimeUpdate?: (event: Event) => void
@@ -61,8 +110,42 @@
onEnded?: (event: Event) => void onEnded?: (event: Event) => void
onSeek?: (value: number) => void onSeek?: (value: number) => void
onSkip?: (seconds: number) => void onSkip?: (seconds: number) => void
onTogglePlayback?: () => void
onToggleMute?: () => void
onVolumeChange?: (value: number) => void
onToggleFullscreen?: () => void | Promise<void>
onQualityChange?: (value: string) => void onQualityChange?: (value: string) => void
onToggleGraph?: () => void onToggleGraph?: () => void
onSpeedChange?: (value: number) => void
/**
* Turns on resume: the position of each source is saved in localStorage under this prefix and
* restored when the source loads. Give each app its own prefix. Empty (the default) keeps
* playback position out of browser storage.
*/
storageKey?: string
/** Offers the playback speed in the settings menu. */
showSpeed?: boolean
/**
* False renders the element with no player controls, surface clicks, keyboard handling or
* fullscreen tracking. The caller then drives playback itself, through `element`, and may set
* the element's `src` directly: this component leaves `src` alone when none is passed.
*/
controls?: boolean
/** Renders the controls over the media surface or as a toolbar below it. */
controlsPlacement?: 'overlay' | 'toolbar'
/**
* Fade the controls out after a few seconds of playback with no pointer or key activity over
* the player. False keeps them visible while playing.
*/
autoHideControls?: boolean
/** Whether clicks and key presses on the media surface control playback. */
surfaceControls?: boolean
/** Listen for player shortcuts on the window, outside media-focused use. */
globalKeyboardControls?: boolean
/** The media element, once mounted. Cleared when it goes. */
element?: HTMLMediaElement | null
preload?: 'none' | 'metadata' | 'auto'
crossorigin?: 'anonymous' | 'use-credentials'
endControls?: Snippet endControls?: Snippet
} = $props() } = $props()
@@ -70,20 +153,32 @@
let mediaElement = $state<HTMLMediaElement | null>(null) let mediaElement = $state<HTMLMediaElement | null>(null)
let internalTime = $state(0) let internalTime = $state(0)
let internalDuration = $state(0) let internalDuration = $state(0)
let playing = $state(false) let internalPlaying = $state(false)
let volume = $state(1) let internalVolume = $state(1)
let muted = $state(false) let internalMuted = $state(false)
let fullscreen = $state(false) let internalFullscreen = $state(false)
let controlsVisible = $state(true) let controlsVisible = $state(true)
let orientationLocked = $state(false) let orientationLocked = $state(false)
let controlsHideTimeout: ReturnType<typeof setTimeout> | null = null let controlsHideTimeout: ReturnType<typeof setTimeout> | null = null
let orientationLockRequest = 0 let orientationLockRequest = 0
let internalPlaybackRate = $state(1)
let lastProgressSaveAt = 0
const PROGRESS_SAVE_INTERVAL_MS = 1500
const currentTime = $derived(externalCurrentTime ?? internalTime) const currentTime = $derived(externalCurrentTime ?? internalTime)
const duration = $derived(externalDuration ?? internalDuration) const duration = $derived(externalDuration ?? internalDuration)
const playing = $derived(externalPlaying ?? internalPlaying)
const volume = $derived(externalVolume ?? internalVolume)
const muted = $derived(externalMuted ?? internalMuted)
const fullscreen = $derived(externalFullscreen ?? internalFullscreen)
const playbackRate = $derived(externalPlaybackRate ?? internalPlaybackRate)
const audio = $derived(kind === 'audio') const audio = $derived(kind === 'audio')
const controlsHideDelay = 2500 const controlsHideDelay = 2500
$effect(() => {
element = mediaElement
})
function clearControlsHideTimer() { function clearControlsHideTimer() {
if (controlsHideTimeout === null) return if (controlsHideTimeout === null) return
clearTimeout(controlsHideTimeout) clearTimeout(controlsHideTimeout)
@@ -92,7 +187,7 @@
function scheduleControlsHide() { function scheduleControlsHide() {
clearControlsHideTimer() clearControlsHideTimer()
if (audio || !playing) return if (!autoHideControls || audio || !playing) return
controlsHideTimeout = setTimeout(() => { controlsHideTimeout = setTimeout(() => {
controlsVisible = false controlsVisible = false
controlsHideTimeout = null controlsHideTimeout = null
@@ -105,7 +200,25 @@
scheduleControlsHide() scheduleControlsHide()
} }
// The picture can sit on a canvas stacked above the frame, where the pointer never reaches the
// frame's own elements. Pointer activity therefore counts anywhere inside the player's box.
function handlePointerActivity(event: PointerEvent) {
if (!controls || !playerFrame) return
const bounds = playerFrame.getBoundingClientRect()
const inside =
event.clientX >= bounds.left &&
event.clientX <= bounds.right &&
event.clientY >= bounds.top &&
event.clientY <= bounds.bottom
if (inside) handlePlayerActivity()
}
function togglePlayback() { function togglePlayback() {
if (controlsDisabled) return
if (onTogglePlayback) {
onTogglePlayback()
return
}
if (!mediaElement) return if (!mediaElement) return
if (mediaElement.paused) void mediaElement.play().catch(() => undefined) if (mediaElement.paused) void mediaElement.play().catch(() => undefined)
else mediaElement.pause() else mediaElement.pause()
@@ -116,11 +229,13 @@
} }
function handleKeydown(event: KeyboardEvent) { function handleKeydown(event: KeyboardEvent) {
if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey) return
const target = event.target as HTMLElement | null const target = event.target as HTMLElement | null
if (target?.closest('button, input, select, textarea, a')) return if (target?.closest('button, input, select, textarea, a, [contenteditable]:not([contenteditable="false"])')) return
const key = event.key.toLowerCase() const key = event.key.toLowerCase()
if (key === ' ' || key === 'k') { if (key === ' ' || key === 'k') {
if (event.repeat) return
event.preventDefault() event.preventDefault()
togglePlayback() togglePlayback()
} else if (key === 'arrowleft') { } else if (key === 'arrowleft') {
@@ -192,43 +307,112 @@
skip(event.clientX - bounds.left < bounds.width / 2 ? -10 : 10) skip(event.clientX - bounds.left < bounds.width / 2 ? -10 : 10)
} }
function progressKey() {
return `${storageKey}:${src}`
}
function restorePlaybackProgress() {
if (!storageKey || !mediaElement) return
try {
const savedProgress = Number(window.localStorage.getItem(progressKey()))
const length = mediaElement.duration
if (
Number.isFinite(savedProgress) &&
savedProgress > 0 &&
Number.isFinite(length) &&
length > 0 &&
savedProgress < length - 1
) {
mediaElement.currentTime = savedProgress
}
} catch {
// Playback remains available when browser storage is disabled or full.
}
}
function savePlaybackProgress(force = false) {
if (!storageKey || !mediaElement || mediaElement.ended) return
const position = mediaElement.currentTime
if (!Number.isFinite(position)) return
try {
if (position <= 0) {
if (force) window.localStorage.removeItem(progressKey())
return
}
if (!force && Date.now() - lastProgressSaveAt < PROGRESS_SAVE_INTERVAL_MS) return
lastProgressSaveAt = Date.now()
window.localStorage.setItem(progressKey(), String(position))
} catch {
// Keep playing when browser storage is disabled or full.
}
}
function clearPlaybackProgress() {
if (!storageKey) return
try {
window.localStorage.removeItem(progressKey())
} catch {
// Keep playback completion independent from browser storage.
}
}
function changeSpeed(value: number) {
if (!Number.isFinite(value) || value <= 0) return
if (onSpeedChange) {
onSpeedChange(value)
return
}
internalPlaybackRate = value
if (mediaElement) mediaElement.playbackRate = value
}
function handleSeeked() {
savePlaybackProgress(true)
}
function handlePlay(event: Event) { function handlePlay(event: Event) {
playing = true internalPlaying = true
onPlay?.(event) onPlay?.(event)
} }
function handlePause(event: Event) { function handlePause(event: Event) {
playing = false internalPlaying = false
controlsVisible = true controlsVisible = true
savePlaybackProgress(true)
onPause?.(event) onPause?.(event)
} }
function handleTimeUpdate(event: Event) { function handleTimeUpdate(event: Event) {
if (mediaElement) internalTime = mediaElement.currentTime || 0 if (mediaElement) internalTime = mediaElement.currentTime || 0
savePlaybackProgress()
onTimeUpdate?.(event) onTimeUpdate?.(event)
} }
function handleLoadedMetadata(event: Event) { function handleLoadedMetadata(event: Event) {
if (!mediaElement) return if (!mediaElement) return
internalDuration = Number.isFinite(mediaElement.duration) ? mediaElement.duration : 0 internalDuration = Number.isFinite(mediaElement.duration) ? mediaElement.duration : 0
volume = mediaElement.volume internalVolume = mediaElement.volume
muted = mediaElement.muted || mediaElement.volume === 0 internalMuted = mediaElement.muted || mediaElement.volume === 0
void syncScreenOrientation(fullscreen) // Loading a source resets the rate, so the chosen speed is applied again.
mediaElement.playbackRate = playbackRate
restorePlaybackProgress()
if (controls) void syncScreenOrientation(fullscreen)
onLoadedMetadata?.(event) onLoadedMetadata?.(event)
} }
function handleEnded(event: Event) { function handleEnded(event: Event) {
playing = false internalPlaying = false
controlsVisible = true controlsVisible = true
clearPlaybackProgress()
onEnded?.(event) onEnded?.(event)
} }
function handleError() { function handleError() {
onError?.() onError?.(mediaElement?.error ?? null)
} }
function seek(value: number) { function seek(value: number) {
if (!Number.isFinite(value)) return if (controlsDisabled || !Number.isFinite(value)) return
if (onSeek) { if (onSeek) {
onSeek(value) onSeek(value)
return return
@@ -240,6 +424,7 @@
} }
function skip(seconds: number) { function skip(seconds: number) {
if (controlsDisabled) return
if (onSkip) { if (onSkip) {
onSkip(seconds) onSkip(seconds)
return return
@@ -248,34 +433,48 @@
} }
function toggleMute() { function toggleMute() {
if (onToggleMute) {
onToggleMute()
return
}
if (!mediaElement) return if (!mediaElement) return
if (muted || mediaElement.muted) { if (muted || mediaElement.muted) {
mediaElement.muted = false mediaElement.muted = false
muted = false internalMuted = false
if (mediaElement.volume === 0) mediaElement.volume = volume || 1 if (mediaElement.volume === 0) mediaElement.volume = volume || 1
volume = mediaElement.volume internalVolume = mediaElement.volume
return return
} }
volume = mediaElement.volume || volume || 1 internalVolume = mediaElement.volume || volume || 1
mediaElement.muted = true mediaElement.muted = true
muted = true internalMuted = true
} }
function changeVolume(value: number) { function changeVolume(value: number) {
if (!mediaElement || !Number.isFinite(value)) return if (!Number.isFinite(value)) return
volume = Math.min(1, Math.max(0, value)) const nextVolume = Math.min(1, Math.max(0, value))
mediaElement.volume = volume if (onVolumeChange) {
mediaElement.muted = volume === 0 onVolumeChange(nextVolume)
muted = volume === 0 return
}
if (!mediaElement) return
internalVolume = nextVolume
mediaElement.volume = internalVolume
mediaElement.muted = internalVolume === 0
internalMuted = internalVolume === 0
} }
function handleVolumeChange() { function handleVolumeChange() {
if (!mediaElement) return if (!mediaElement) return
volume = mediaElement.volume internalVolume = mediaElement.volume
muted = mediaElement.muted || mediaElement.volume === 0 internalMuted = mediaElement.muted || mediaElement.volume === 0
} }
async function toggleFullscreen() { async function toggleFullscreen() {
if (onToggleFullscreen) {
await onToggleFullscreen()
return
}
if (document.fullscreenElement) { if (document.fullscreenElement) {
await document.exitFullscreen().catch(() => undefined) await document.exitFullscreen().catch(() => undefined)
return return
@@ -284,19 +483,21 @@
} }
function handleFullscreenChange() { function handleFullscreenChange() {
fullscreen = Boolean(document.fullscreenElement) if (!controls) return
internalFullscreen = Boolean(document.fullscreenElement)
void syncScreenOrientation(fullscreen) void syncScreenOrientation(fullscreen)
} }
$effect(() => { $effect(() => {
const nextSource = src const nextSource = src
if (!mediaElement || !nextSource) return if (!mediaElement || !nextSource) return
if (!audio && autoplay && autoplayMuted) mediaElement.muted = true
mediaElement.load() mediaElement.load()
if (autoplay) void mediaElement.play().catch(() => undefined) if (autoplay) void mediaElement.play().catch(() => undefined)
}) })
$effect(() => { $effect(() => {
if (audio || !playing) { if (!controls || !autoHideControls || audio || !playing) {
clearControlsHideTimer() clearControlsHideTimer()
controlsVisible = true controlsVisible = true
return return
@@ -307,7 +508,7 @@
}) })
onMount(() => { onMount(() => {
if (!playerFrame) return if (!controls || !playerFrame) return
const activityEvents = ['mousemove', 'click', 'keydown', 'focusin', 'touchstart'] as const const activityEvents = ['mousemove', 'click', 'keydown', 'focusin', 'touchstart'] as const
for (const eventName of activityEvents) playerFrame.addEventListener(eventName, handlePlayerActivity) for (const eventName of activityEvents) playerFrame.addEventListener(eventName, handlePlayerActivity)
@@ -323,17 +524,27 @@
}) })
</script> </script>
<svelte:window onfullscreenchange={handleFullscreenChange} /> <svelte:window
onfullscreenchange={handleFullscreenChange}
onkeydown={globalKeyboardControls ? handleKeydown : undefined}
onpointermove={controls ? handlePointerActivity : undefined}
onpointerdown={controls ? handlePointerActivity : undefined}
/>
<div bind:this={playerFrame} class={`media-player ${className}`}> <div
bind:this={playerFrame}
class={controls
? `media-player ${controlsPlacement === 'toolbar' ? 'media-player-toolbar ' : ''}${className}`
: className}
>
{#if audio} {#if audio}
<div <div
class="media-player-audio-surface" class="media-player-audio-surface"
role="button" role="button"
tabindex="0" tabindex="0"
aria-label={title ? `Audio player for ${title}` : 'Audio player'} aria-label={title ? `Audio player for ${title}` : 'Audio player'}
onclick={handleSurfaceClick} onclick={controls && surfaceControls ? handleSurfaceClick : undefined}
onkeydown={handleKeydown} onkeydown={controls && surfaceControls && !globalKeyboardControls ? handleKeydown : undefined}
> >
<Music2 class="media-player-audio-icon" /> <Music2 class="media-player-audio-icon" />
{#if title}<span>{title}</span>{/if} {#if title}<span>{title}</span>{/if}
@@ -342,7 +553,7 @@
bind:this={mediaElement} bind:this={mediaElement}
{src} {src}
{autoplay} {autoplay}
preload="auto" {preload}
tabindex="-1" tabindex="-1"
aria-hidden="true" aria-hidden="true"
onplay={handlePlay} onplay={handlePlay}
@@ -351,6 +562,7 @@
onloadedmetadata={handleLoadedMetadata} onloadedmetadata={handleLoadedMetadata}
onended={handleEnded} onended={handleEnded}
onvolumechange={handleVolumeChange} onvolumechange={handleVolumeChange}
onseeked={handleSeeked}
onerror={handleError} onerror={handleError}
></audio> ></audio>
{:else} {:else}
@@ -359,27 +571,35 @@
<video <video
bind:this={mediaElement} bind:this={mediaElement}
{src} {src}
{poster} poster={poster || undefined}
{autoplay} {autoplay}
preload="auto" muted={autoplay && autoplayMuted}
{preload}
{crossorigin}
playsinline playsinline
tabindex="0" tabindex={controls ? 0 : undefined}
class={`media-player-video ${mediaClass}`} class={[
controls && 'media-player-video',
controls && !mediaVisible && 'media-player-video-hidden',
mediaClass,
].filter(Boolean).join(' ')}
aria-label={title ? `Video player for ${title}` : 'Video player'} aria-label={title ? `Video player for ${title}` : 'Video player'}
onclick={handleSurfaceClick} onclick={controls && surfaceControls ? handleSurfaceClick : undefined}
ondblclick={handleVideoDoubleTap} ondblclick={controls && surfaceControls ? handleVideoDoubleTap : undefined}
onkeydown={handleKeydown} onkeydown={controls && surfaceControls && !globalKeyboardControls ? handleKeydown : undefined}
onplay={handlePlay} onplay={handlePlay}
onpause={handlePause} onpause={handlePause}
ontimeupdate={handleTimeUpdate} ontimeupdate={handleTimeUpdate}
onloadedmetadata={handleLoadedMetadata} onloadedmetadata={handleLoadedMetadata}
onended={handleEnded} onended={handleEnded}
onvolumechange={handleVolumeChange} onvolumechange={handleVolumeChange}
onseeked={handleSeeked}
onerror={handleError} onerror={handleError}
> >
<track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT%0A" /> <track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT%0A" />
</video> </video>
{/if} {/if}
{#if controls}
<MediaPlayerControls <MediaPlayerControls
{kind} {kind}
{currentTime} {currentTime}
@@ -391,6 +611,8 @@
{controlsVisible} {controlsVisible}
onTogglePlayback={togglePlayback} onTogglePlayback={togglePlayback}
onSeek={seek} onSeek={seek}
{seekOnCommit}
{seekWithoutDuration}
onToggleMute={toggleMute} onToggleMute={toggleMute}
onVolumeChange={changeVolume} onVolumeChange={changeVolume}
onToggleFullscreen={toggleFullscreen} onToggleFullscreen={toggleFullscreen}
@@ -400,11 +622,20 @@
{graphVisible} {graphVisible}
{qualityOptions} {qualityOptions}
{selectedQuality} {selectedQuality}
{settingsGroups}
{settings}
{onQualityChange} {onQualityChange}
{onToggleGraph} {onToggleGraph}
{endControls} {endControls}
overlay {showSpeed}
{playbackRate}
onSpeedChange={changeSpeed}
playbackDisabled={controlsDisabled}
{speedDisabled}
placement={controlsPlacement}
overlay={controlsPlacement === 'overlay'}
/> />
{/if}
</div> </div>
<style> <style>
@@ -426,6 +657,35 @@
border-radius: 0; border-radius: 0;
} }
.media-player-toolbar {
aspect-ratio: auto;
display: flex;
flex-direction: column;
justify-content: flex-end;
overflow: visible;
background: transparent;
color: var(--sc-fg, white);
}
.media-player-toolbar .media-player-video:not(.media-player-video-hidden) {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: auto;
}
.media-player-toolbar .media-player-video-hidden {
position: absolute;
top: 0;
left: 0;
width: 1px;
height: 1px;
overflow: hidden;
opacity: 0;
pointer-events: none;
}
.media-player-video { .media-player-video {
width: 100%; width: 100%;
height: 100%; height: 100%;
@@ -2,7 +2,7 @@
Internal to MediaPlayer. Not exported from the package barrel; do not re-export. Internal to MediaPlayer. Not exported from the package barrel; do not re-export.
--> -->
<script lang="ts"> <script lang="ts">
import { Maximize2, Minimize2, Pause, Play, Settings, Volume2, VolumeX } from '@lucide/svelte' import { Maximize2, Minimize2, Pause, Play, Settings, Volume1, Volume2, VolumeX } from '@lucide/svelte'
import { onMount } from 'svelte' import { onMount } from 'svelte'
import type { Snippet } from 'svelte' import type { Snippet } from 'svelte'
@@ -13,6 +13,14 @@
label: string label: string
} }
export interface MediaPlayerSettingsGroup {
id: string
label: string
summary: string
disabled?: boolean
hint?: string
}
let { let {
kind = 'video', kind = 'video',
currentTime = 0, currentTime = 0,
@@ -25,12 +33,20 @@
overlay = false, overlay = false,
controlsVisible = true, controlsVisible = true,
showSeekButtons: _showSeekButtons = true, showSeekButtons: _showSeekButtons = true,
seekOnCommit = false,
seekWithoutDuration = false,
showVolume = true, showVolume = true,
showFullscreen = true, showFullscreen = true,
showGraph = false, showGraph = false,
graphVisible = false, graphVisible = false,
qualityOptions = [], qualityOptions = [],
selectedQuality = '', selectedQuality = '',
settingsGroups = [],
settings,
showSpeed = true,
playbackRate = 1,
speedDisabled = false,
playbackDisabled = false,
onTogglePlayback, onTogglePlayback,
onSeek, onSeek,
onSkip: _onSkip, onSkip: _onSkip,
@@ -39,6 +55,8 @@
onToggleFullscreen, onToggleFullscreen,
onToggleGraph, onToggleGraph,
onQualityChange, onQualityChange,
onSpeedChange,
placement = 'overlay',
endControls, endControls,
}: { }: {
kind?: MediaPlayerKind kind?: MediaPlayerKind
@@ -53,12 +71,19 @@
controlsVisible?: boolean controlsVisible?: boolean
/** @deprecated Seeking is available with the arrow keys and mobile double-tap. */ /** @deprecated Seeking is available with the arrow keys and mobile double-tap. */
showSeekButtons?: boolean showSeekButtons?: boolean
seekOnCommit?: boolean
seekWithoutDuration?: boolean
showVolume?: boolean showVolume?: boolean
showFullscreen?: boolean showFullscreen?: boolean
showGraph?: boolean showGraph?: boolean
graphVisible?: boolean graphVisible?: boolean
qualityOptions?: MediaPlayerQualityOption[] qualityOptions?: MediaPlayerQualityOption[]
selectedQuality?: string selectedQuality?: string
settingsGroups?: MediaPlayerSettingsGroup[]
settings?: Snippet<[string]>
speedDisabled?: boolean
playbackDisabled?: boolean
placement?: 'overlay' | 'toolbar'
onTogglePlayback?: () => void onTogglePlayback?: () => void
onSeek?: (value: number) => void onSeek?: (value: number) => void
/** @deprecated Seeking is handled by the player surface. */ /** @deprecated Seeking is handled by the player surface. */
@@ -68,15 +93,42 @@
onToggleFullscreen?: () => void | Promise<void> onToggleFullscreen?: () => void | Promise<void>
onToggleGraph?: () => void onToggleGraph?: () => void
onQualityChange?: (value: string) => void onQualityChange?: (value: string) => void
showSpeed?: boolean
playbackRate?: number
onSpeedChange?: (value: number) => void
endControls?: Snippet endControls?: Snippet
} = $props() } = $props()
const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 2]
let settingsMenu = $state<HTMLDivElement | null>(null) let settingsMenu = $state<HTMLDivElement | null>(null)
let settingsOpen = $state(false) let settingsOpen = $state(false)
let settingsGroup = $state<string | null>(null)
let draggedTime = $state<number | null>(null)
let settingsMenuStyle = $state('')
const progress = $derived(duration > 0 ? `${Math.min(100, Math.max(0, (currentTime / duration) * 100))}%` : '0%') const displayedTime = $derived(draggedTime ?? currentTime)
const seekMax = $derived(duration > 0 ? duration : Math.max(displayedTime, 1))
const progress = $derived(duration > 0 ? `${Math.min(100, Math.max(0, (displayedTime / duration) * 100))}%` : '0%')
const displayVolume = $derived(muted ? 0 : Math.min(1, Math.max(0, volume))) const displayVolume = $derived(muted ? 0 : Math.min(1, Math.max(0, volume)))
const label = $derived(kind === 'audio' ? 'audio' : 'video') const label = $derived(kind === 'audio' ? 'audio' : 'video')
const speedChoices = $derived(SPEEDS.includes(playbackRate) ? SPEEDS : [...SPEEDS, playbackRate].sort((a, b) => a - b))
const categories = $derived<MediaPlayerSettingsGroup[]>([
...(showGraph ? [{ id: 'graph', label: 'Funscript graph', summary: graphVisible ? 'On' : 'Off' }] : []),
...(qualityOptions.length > 0
? [{
id: 'quality',
label: 'Quality',
summary: qualityOptions.find((option) => option.value === selectedQuality)?.label ?? selectedQuality,
}]
: []),
...(showSpeed ? [{ id: 'speed', label: 'Speed', summary: `${playbackRate}x` }] : []),
...settingsGroups,
])
const nestedSettings = $derived(settingsGroups.length > 0)
const openCategory = $derived(
categories.find((category) => category.id === settingsGroup && !category.disabled) ?? null,
)
function formatTime(value: number) { function formatTime(value: number) {
const seconds = Math.max(0, Math.floor(Number(value) || 0)) const seconds = Math.max(0, Math.floor(Number(value) || 0))
@@ -88,7 +140,16 @@
} }
function handleSeek(event: Event) { function handleSeek(event: Event) {
onSeek?.(Number((event.currentTarget as HTMLInputElement).value)) const value = Number((event.currentTarget as HTMLInputElement).value)
if (seekOnCommit) draggedTime = value
else onSeek?.(value)
}
function handleSeekCommit(event: Event) {
if (!seekOnCommit) return
const value = Number((event.currentTarget as HTMLInputElement).value)
draggedTime = null
onSeek?.(value)
} }
function handleVolume(event: Event) { function handleVolume(event: Event) {
@@ -98,29 +159,64 @@
function handleQuality(event: Event) { function handleQuality(event: Event) {
onQualityChange?.((event.currentTarget as HTMLSelectElement).value) onQualityChange?.((event.currentTarget as HTMLSelectElement).value)
settingsOpen = false settingsOpen = false
settingsGroup = null
}
function handleSpeed(event: Event) {
onSpeedChange?.(Number((event.currentTarget as HTMLSelectElement).value))
settingsOpen = false
settingsGroup = null
}
function closeSettings() {
settingsOpen = false
settingsGroup = null
}
function openSettings() {
if (placement === 'toolbar') {
const rect = settingsMenu?.getBoundingClientRect()
if (rect) {
const room = Math.max(120, rect.top - 16)
settingsMenuStyle = `right: ${window.innerWidth - rect.right}px; bottom: ${window.innerHeight - rect.top + 8}px; max-height: min(26rem, ${room}px);`
}
}
settingsOpen = true
}
function toggleSettings() {
if (settingsOpen) closeSettings()
else openSettings()
} }
function handleDocumentPointerDown(event: PointerEvent) { function handleDocumentPointerDown(event: PointerEvent) {
if (settingsOpen && !settingsMenu?.contains(event.target as Node)) settingsOpen = false if (settingsOpen && !settingsMenu?.contains(event.target as Node)) closeSettings()
} }
function handleDocumentKeydown(event: KeyboardEvent) { function handleDocumentKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') settingsOpen = false if (event.key !== 'Escape' || !settingsOpen) return
if (settingsGroup) settingsGroup = null
else closeSettings()
} }
onMount(() => { onMount(() => {
document.addEventListener('pointerdown', handleDocumentPointerDown) document.addEventListener('pointerdown', handleDocumentPointerDown)
document.addEventListener('keydown', handleDocumentKeydown) document.addEventListener('keydown', handleDocumentKeydown)
window.addEventListener('resize', closeSettings)
window.addEventListener('scroll', closeSettings, true)
return () => { return () => {
document.removeEventListener('pointerdown', handleDocumentPointerDown) document.removeEventListener('pointerdown', handleDocumentPointerDown)
document.removeEventListener('keydown', handleDocumentKeydown) document.removeEventListener('keydown', handleDocumentKeydown)
window.removeEventListener('resize', closeSettings)
window.removeEventListener('scroll', closeSettings, true)
} }
}) })
</script> </script>
<div <div
class:media-player-controls-overlay={overlay} class:media-player-controls-overlay={overlay}
class:media-player-controls-toolbar={placement === 'toolbar'}
class:media-player-controls-fullscreen={fullscreen} class:media-player-controls-fullscreen={fullscreen}
class:media-player-controls-hidden={!controlsVisible} class:media-player-controls-hidden={!controlsVisible}
class="media-player-controls" class="media-player-controls"
@@ -130,13 +226,14 @@
style={`--media-player-progress: ${progress}`} style={`--media-player-progress: ${progress}`}
type="range" type="range"
min="0" min="0"
max={Math.max(duration, 0.1)} max={seekMax}
step="0.1" step={seekOnCommit ? 'any' : '0.1'}
value={currentTime} value={displayedTime}
disabled={disabled || !duration} disabled={disabled || playbackDisabled || (!duration && !seekWithoutDuration)}
aria-label={`Seek ${label}`} aria-label={`Seek ${label}`}
aria-valuetext={`${formatTime(currentTime)} of ${formatTime(duration)}`} aria-valuetext={`${formatTime(displayedTime)} of ${formatTime(duration)}`}
oninput={handleSeek} oninput={handleSeek}
onchange={handleSeekCommit}
/> />
<div class="media-player-control-row"> <div class="media-player-control-row">
<button <button
@@ -144,7 +241,7 @@
class="media-player-control" class="media-player-control"
aria-label={playing ? `Pause ${label}` : `Play ${label}`} aria-label={playing ? `Pause ${label}` : `Play ${label}`}
title={playing ? 'Pause (K or Space)' : 'Play (K or Space)'} title={playing ? 'Pause (K or Space)' : 'Play (K or Space)'}
{disabled} disabled={disabled || playbackDisabled}
onclick={onTogglePlayback} onclick={onTogglePlayback}
> >
{#if playing}<Pause class="media-player-icon-large" />{:else}<Play class="media-player-icon-large" />{/if} {#if playing}<Pause class="media-player-icon-large" />{:else}<Play class="media-player-icon-large" />{/if}
@@ -158,7 +255,9 @@
{disabled} {disabled}
onclick={onToggleMute} onclick={onToggleMute}
> >
{#if muted}<VolumeX class="media-player-icon" />{:else}<Volume2 class="media-player-icon" />{/if} {#if muted || volume === 0}<VolumeX class="media-player-icon" />{:else if volume < 0.5}<Volume1
class="media-player-icon"
/>{:else}<Volume2 class="media-player-icon" />{/if}
</button> </button>
<input <input
class="media-player-volume" class="media-player-volume"
@@ -173,10 +272,13 @@
oninput={handleVolume} oninput={handleVolume}
/> />
{/if} {/if}
<span class="media-player-time">{formatTime(currentTime)} / {formatTime(duration)}</span> <span class="media-player-time">
{formatTime(displayedTime)}<span class="media-player-time-duration">
/ {placement === 'toolbar' && duration <= 0 ? '--:--' : formatTime(duration)}
</span>
</span>
<div class="media-player-control-trailing"> <div class="media-player-control-trailing">
{@render endControls?.()} {#if showGraph || qualityOptions.length > 0 || showSpeed || settingsGroups.length > 0}
{#if showGraph || qualityOptions.length > 0}
<div bind:this={settingsMenu} class="media-player-settings"> <div bind:this={settingsMenu} class="media-player-settings">
<button <button
type="button" type="button"
@@ -186,39 +288,134 @@
aria-haspopup="dialog" aria-haspopup="dialog"
title="Player settings" title="Player settings"
{disabled} {disabled}
onclick={() => (settingsOpen = !settingsOpen)} onclick={toggleSettings}
> >
<Settings class="media-player-icon" /> <Settings class="media-player-icon" />
</button> </button>
{#if settingsOpen} {#if settingsOpen}
<div class="media-player-settings-menu" role="dialog" aria-label="Player settings"> <div
{#if showGraph} class="media-player-settings-menu"
<button role="dialog"
type="button" aria-label="Player settings"
class="media-player-settings-toggle" style={placement === 'toolbar' ? settingsMenuStyle : undefined}
role="switch" >
aria-checked={graphVisible} {#if nestedSettings}
{disabled} {#if openCategory}
onclick={onToggleGraph} <div class="media-player-settings-heading">
> <button
<span>Funscript graph</span> type="button"
<span class="media-player-settings-status">{graphVisible ? 'On' : 'Off'}</span> class="media-player-settings-back"
</button> aria-label="Back"
{/if} onclick={() => (settingsGroup = null)}
{#if qualityOptions.length > 0} >
<label class="media-player-settings-quality"> <span aria-hidden="true">‹</span>
<span>Quality</span> </button>
<select value={selectedQuality} aria-label="Video quality" {disabled} onchange={handleQuality}> <span>{openCategory.label}</span>
{#each qualityOptions as option (option.value)} </div>
<option value={option.value}>{option.label}</option> {#if openCategory.id === 'graph'}
<button
type="button"
class="media-player-settings-toggle"
role="switch"
aria-checked={graphVisible}
{disabled}
onclick={onToggleGraph}
>
<span>Funscript graph</span>
<span class="media-player-settings-status">{graphVisible ? 'On' : 'Off'}</span>
</button>
{:else if openCategory.id === 'quality'}
<label class="media-player-settings-quality">
<span>Quality</span>
<select value={selectedQuality} aria-label="Video quality" {disabled} onchange={handleQuality}>
{#each qualityOptions as option (option.value)}
<option value={option.value}>{option.label}</option>
{/each}
</select>
</label>
{:else if openCategory.id === 'speed'}
<label class="media-player-settings-quality">
<span>Speed</span>
<select
value={String(playbackRate)}
aria-label="Playback speed"
disabled={disabled || playbackDisabled || speedDisabled}
onchange={handleSpeed}
>
{#each speedChoices as speed (speed)}
<option value={String(speed)}>{speed}x</option>
{/each}
</select>
</label>
{#if speedDisabled}<p class="media-player-settings-hint">Only the host device can change the speed.</p>{/if}
{:else}
{@render settings?.(openCategory.id)}
{/if}
{:else}
<ul class="media-player-settings-groups">
{#each categories as category (category.id)}
<li>
<button
type="button"
class="media-player-settings-group"
disabled={disabled || category.disabled}
title={category.disabled ? category.hint : undefined}
onclick={() => (settingsGroup = category.id)}
>
<span class="media-player-settings-group-label">{category.label}</span>
<span class="media-player-settings-group-summary">{category.summary}</span>
<span aria-hidden="true">›</span>
</button>
</li>
{/each} {/each}
</select> </ul>
</label> {/if}
{:else}
{#if showGraph}
<button
type="button"
class="media-player-settings-toggle"
role="switch"
aria-checked={graphVisible}
{disabled}
onclick={onToggleGraph}
>
<span>Funscript graph</span>
<span class="media-player-settings-status">{graphVisible ? 'On' : 'Off'}</span>
</button>
{/if}
{#if qualityOptions.length > 0}
<label class="media-player-settings-quality">
<span>Quality</span>
<select value={selectedQuality} aria-label="Video quality" {disabled} onchange={handleQuality}>
{#each qualityOptions as option (option.value)}
<option value={option.value}>{option.label}</option>
{/each}
</select>
</label>
{/if}
{#if showSpeed}
<label class="media-player-settings-quality">
<span>Speed</span>
<select
value={String(playbackRate)}
aria-label="Playback speed"
disabled={disabled || playbackDisabled || speedDisabled}
onchange={handleSpeed}
>
{#each speedChoices as speed (speed)}
<option value={String(speed)}>{speed}x</option>
{/each}
</select>
</label>
{/if}
{@render settings?.('')}
{/if} {/if}
</div> </div>
{/if} {/if}
</div> </div>
{/if} {/if}
{@render endControls?.()}
{#if showFullscreen} {#if showFullscreen}
<button <button
type="button" type="button"
@@ -255,6 +452,14 @@
transition: opacity 180ms ease; transition: opacity 180ms ease;
} }
.media-player-controls-toolbar {
position: relative;
z-index: 1;
pointer-events: auto;
padding: 0.5rem;
color: var(--sc-fg, white);
}
.media-player-controls-hidden { .media-player-controls-hidden {
opacity: 0; opacity: 0;
pointer-events: none; pointer-events: none;
@@ -424,6 +629,10 @@
color: white; color: white;
} }
.media-player-controls-toolbar .media-player-settings-menu {
position: fixed;
}
.media-player-settings-toggle, .media-player-settings-toggle,
.media-player-settings-quality { .media-player-settings-quality {
display: flex; display: flex;
@@ -469,6 +678,104 @@
color: var(--sc-fg, white); color: var(--sc-fg, white);
} }
.media-player-settings-heading,
.media-player-settings-group {
display: flex;
align-items: center;
gap: 0.5rem;
}
.media-player-settings-heading {
padding: 0.25rem 0.4rem 0.4rem;
color: white;
font-size: 0.75rem;
font-weight: 600;
}
.media-player-settings-back {
display: inline-grid;
width: 1.75rem;
height: 1.75rem;
flex: none;
place-items: center;
border: 0;
border-radius: 0.35rem;
background: transparent;
color: inherit;
cursor: pointer;
font-size: 1.25rem;
}
.media-player-settings-back:hover {
background: rgb(255 255 255 / 0.12);
}
.media-player-settings-groups {
display: grid;
gap: 0.15rem;
margin: 0;
padding: 0;
list-style: none;
}
.media-player-settings-group {
width: 100%;
min-height: 2.25rem;
justify-content: space-between;
border: 0;
border-radius: 0.4rem;
padding: 0.35rem 0.5rem;
background: transparent;
color: rgb(255 255 255 / 0.9);
cursor: pointer;
font-size: 0.75rem;
text-align: left;
}
.media-player-settings-group:hover:not(:disabled) {
background: rgb(255 255 255 / 0.12);
}
.media-player-settings-group:disabled {
cursor: not-allowed;
opacity: 0.5;
}
.media-player-settings-group-label {
min-width: 0;
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.media-player-settings-group-summary {
color: var(--sc-primary, #80b6f5);
font-size: 0.7rem;
}
.media-player-settings-hint {
margin: 0.25rem 0.5rem 0.35rem;
color: rgb(255 255 255 / 0.62);
font-size: 0.7rem;
}
.media-player-controls-toolbar .media-player-control {
border-color: transparent;
background: transparent;
color: var(--sc-fg, white);
}
.media-player-controls-toolbar .media-player-control:hover:not(:disabled) {
border-color: var(--sc-border, rgb(255 255 255 / 0.2));
background: var(--sc-surface-hover, rgb(255 255 255 / 0.1));
color: var(--sc-fg, white);
}
.media-player-controls-toolbar .media-player-time {
color: var(--sc-muted-fg, rgb(255 255 255 / 0.7));
}
.media-player-control:focus-visible, .media-player-control:focus-visible,
.media-player-progress:focus-visible, .media-player-progress:focus-visible,
.media-player-volume:focus-visible, .media-player-volume:focus-visible,
@@ -496,5 +803,13 @@
.media-player-controls-fullscreen .media-player-volume { .media-player-controls-fullscreen .media-player-volume {
display: block; display: block;
} }
.media-player-controls-fullscreen.media-player-controls-toolbar .media-player-volume {
display: none;
}
.media-player-controls-toolbar .media-player-time-duration {
display: none;
}
} }
</style> </style>
@@ -13,6 +13,7 @@
onTotpSetup, onTotpSetup,
onTotpStatus, onTotpStatus,
totpEnabled = false, totpEnabled = false,
requireCredentialsForEmailChange = false,
open = $bindable(false) open = $bindable(false)
}: { }: {
currentEmail?: string; currentEmail?: string;
@@ -23,6 +24,7 @@
onTotpSetup?: TotpSetupRequest; onTotpSetup?: TotpSetupRequest;
onTotpStatus?: TotpStatusRequest; onTotpStatus?: TotpStatusRequest;
totpEnabled?: boolean; totpEnabled?: boolean;
requireCredentialsForEmailChange?: boolean;
open?: boolean; open?: boolean;
} = $props(); } = $props();
@@ -30,8 +32,13 @@
let email = $state(''); let email = $state('');
let password = $state(''); let password = $state('');
let confirmPassword = $state(''); let confirmPassword = $state('');
let currentPassword = $state('');
let totpToken = $state('');
let error = $state(''); let error = $state('');
let saving = $state(false); let saving = $state(false);
let requiresCurrentCredentials = $derived(
!!password || (requireCredentialsForEmailChange && email.trim() !== currentEmail.trim())
);
$effect(() => { $effect(() => {
if (open) { if (open) {
@@ -39,6 +46,8 @@
email = currentEmail; email = currentEmail;
password = ''; password = '';
confirmPassword = ''; confirmPassword = '';
currentPassword = '';
totpToken = '';
error = ''; error = '';
} }
}); });
@@ -52,6 +61,16 @@
return; return;
} }
if (requiresCurrentCredentials && !currentPassword) {
error = 'Enter your current password to change your email or password.';
return;
}
if (requiresCurrentCredentials && totpEnabled && !totpToken) {
error = 'Enter a current authenticator code to change your email or password.';
return;
}
if (!onSave) { if (!onSave) {
error = 'The application has not configured its profile update handler.'; error = 'The application has not configured its profile update handler.';
return; return;
@@ -59,7 +78,13 @@
saving = true; saving = true;
try { try {
await onSave({ username, email, password: password || undefined }); const input: ProfileUpdateInput = { username, email };
if (requiresCurrentCredentials) {
input.currentPassword = currentPassword;
if (totpEnabled) input.totpToken = totpToken;
}
if (password) input.password = password;
await onSave(input);
open = false; open = false;
} catch (caught) { } catch (caught) {
error = caught instanceof Error ? caught.message : 'Profile update failed.'; error = caught instanceof Error ? caught.message : 'Profile update failed.';
@@ -100,6 +125,35 @@
/> />
</label> </label>
{#if requiresCurrentCredentials}
<label class="sc-field">
<span class="sc-label">Current password</span>
<input
autocomplete="current-password"
class="sc-input"
required
type="password"
bind:value={currentPassword}
/>
</label>
{#if totpEnabled}
<label class="sc-field">
<span class="sc-label">Current authenticator code</span>
<input
autocomplete="one-time-code"
class="sc-input"
inputmode="numeric"
maxlength="6"
pattern="[0-9]{6}"
required
type="text"
bind:value={totpToken}
/>
</label>
{/if}
{/if}
{#if password} {#if password}
<label class="sc-field"> <label class="sc-field">
<span class="sc-label">Confirm new password</span> <span class="sc-label">Confirm new password</span>
@@ -74,6 +74,21 @@ function mixHex(hex: string, towards: number, weight: number): string {
return `#${channels.map((c) => Math.round(c + (towards - c) * weight).toString(16).padStart(2, '0')).join('')}` return `#${channels.map((c) => Math.round(c + (towards - c) * weight).toString(16).padStart(2, '0')).join('')}`
} }
// WCAG relative luminance of a #rrggbb color, from 0 (black) to 1 (white).
function luminance(hex: string): number {
const [red, green, blue] = [1, 3, 5].map((start) => {
const channel = parseInt(hex.slice(start, start + 2), 16) / 255
return channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4
})
return 0.2126 * red + 0.7152 * green + 0.0722 * blue
}
// WCAG contrast ratio between two #rrggbb colors, from 1 (no contrast) to 21 (black on white).
function contrastRatio(a: string, b: string): number {
const [lighter, darker] = [luminance(a), luminance(b)].sort((x, y) => y - x)
return (lighter + 0.05) / (darker + 0.05)
}
// The color is written to a stylesheet rather than inline on <html>. Shared and app CSS re-declare these // The color is written to a stylesheet rather than inline on <html>. Shared and app CSS re-declare these
// tokens on every [data-theme] element (the AppShell root, for one), and that declaration hides the value // tokens on every [data-theme] element (the AppShell root, for one), and that declaration hides the value
// <html> would pass down, so the choice never reached the app's UI. Targeting [data-theme] elements with // <html> would pass down, so the choice never reached the app's UI. Targeting [data-theme] elements with
@@ -83,7 +98,9 @@ function primaryDeclarations(color: PaletteColor, dark: boolean): string {
// Hover is lighter on dark and darker on light, as in the shared theme. It is a hex value, not color-mix(), // Hover is lighter on dark and darker on light, as in the shared theme. It is a hex value, not color-mix(),
// because consumers such as the terminal read these tokens as plain colors. // because consumers such as the terminal read these tokens as plain colors.
const hover = dark ? mixHex(primary, 255, 0.15) : mixHex(primary, 0, 0.15) const hover = dark ? mixHex(primary, 255, 0.15) : mixHex(primary, 0, 0.15)
const foreground = dark ? color.darkFg : '#ffffff' // Text on the primary is white or the palette's dark text, whichever reads better. Mid-tone light colors
// are too light for white text, so the choice follows the color rather than the theme.
const foreground = contrastRatio(primary, '#ffffff') >= contrastRatio(primary, color.darkFg) ? '#ffffff' : color.darkFg
return [ return [
...primaryVars.map((name) => `${name}: ${primary} !important;`), ...primaryVars.map((name) => `${name}: ${primary} !important;`),
`--sc-primary-hover: ${hover} !important;`, `--sc-primary-hover: ${hover} !important;`,
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more