Compare commits
29
Commits
7fd2f14f91
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf19a057c5 | ||
|
|
5745995a34 | ||
|
|
170c7570e4 | ||
|
|
8701874efb | ||
|
|
76bf5916fe | ||
|
|
a8dce33dc5 | ||
|
|
ba171a74a9 | ||
|
|
9e58b6db01 | ||
|
|
7f21bb9073 | ||
|
|
fc01c93aeb | ||
|
|
d20eb96969 | ||
|
|
750e9b7a85 | ||
|
|
60befcd883 | ||
|
|
61d8da5fb3 | ||
|
|
fb4274bd5c | ||
|
|
74942e55f9 | ||
|
|
75c08beec6 | ||
|
|
e8cb7c6c68 | ||
|
|
b776bacd70 | ||
|
|
37a4a8e2ca | ||
|
|
8ec0d89437 | ||
|
|
657d478d48 | ||
|
|
b9c2365bca | ||
|
|
cb7a899c77 | ||
|
|
a15827fe76 | ||
|
|
add64ff180 | ||
|
|
f7819904b9 | ||
|
|
22887fef03 | ||
|
|
199a5efaef |
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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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`.
|
||||||
@@ -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.
|
||||||
@@ -26,6 +26,17 @@ jobs:
|
|||||||
go-version-file: backend/go.mod
|
go-version-file: backend/go.mod
|
||||||
cache: false
|
cache: false
|
||||||
|
|
||||||
|
- name: Check formatting and vet the Go module
|
||||||
|
working-directory: backend
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
mapfile -d '' go_files < <(find . -type f -name '*.go' -print0)
|
||||||
|
if ((${#go_files[@]})); then
|
||||||
|
test -z "$(gofmt -l "${go_files[@]}")"
|
||||||
|
fi
|
||||||
|
go vet ./...
|
||||||
|
|
||||||
- name: Test Go module
|
- name: Test Go module
|
||||||
working-directory: backend
|
working-directory: backend
|
||||||
run: go test ./...
|
run: go test ./...
|
||||||
|
|||||||
@@ -29,6 +29,11 @@ jobs:
|
|||||||
npm ci
|
npm ci
|
||||||
npm run build
|
npm run build
|
||||||
|
|
||||||
|
- name: Run the lint and test checks that gate pull requests
|
||||||
|
run: |
|
||||||
|
npm run lint
|
||||||
|
npm test
|
||||||
|
|
||||||
- name: Configure Gitea npm registry
|
- name: Configure Gitea npm registry
|
||||||
env:
|
env:
|
||||||
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
||||||
|
|||||||
@@ -23,6 +23,13 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: '3.12'
|
python-version: '3.12'
|
||||||
|
|
||||||
|
- name: Run the lint and test checks that gate pull requests
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
python -m pip install --disable-pip-version-check --upgrade pip ruff -e "packages/python-backend[fastapi]"
|
||||||
|
ruff check packages/python-backend/src packages/python-backend/tests
|
||||||
|
python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
|
||||||
|
|
||||||
- name: Build and publish package
|
- name: Build and publish package
|
||||||
env:
|
env:
|
||||||
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Consumer synchronization is opt-in. It commits into every registered consumer repository, so it
|
||||||
|
# runs only for a commit made with SHARED_SYNC_COMMIT=1 in the environment.
|
||||||
|
if [ "${SHARED_SYNC_COMMIT:-0}" != "1" ]; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
repo_root="$(git rev-parse --show-toplevel)"
|
repo_root="$(git rev-parse --show-toplevel)"
|
||||||
sync_script="$repo_root/scripts/sync-consumers.ps1"
|
sync_script="$repo_root/scripts/sync-consumers.ps1"
|
||||||
|
|
||||||
|
|||||||
@@ -43,8 +43,14 @@ jobs:
|
|||||||
cache-dependency-path: package-lock.json
|
cache-dependency-path: package-lock.json
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
- name: Check the generated root stylesheet is current
|
||||||
|
run: git diff --exit-code -- shared-styles.css
|
||||||
|
- name: Check for skipped tests
|
||||||
|
run: npm run media:enforce:no-skipped-tests
|
||||||
- name: Run Node/Svelte lint checks
|
- name: Run Node/Svelte lint checks
|
||||||
run: npm run lint
|
run: npm run lint
|
||||||
|
- name: Check Prettier formatting
|
||||||
|
run: npm run format:check
|
||||||
|
|
||||||
go:
|
go:
|
||||||
name: Lint (Go)
|
name: Lint (Go)
|
||||||
|
|||||||
@@ -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 .
|
||||||
@@ -54,6 +54,26 @@ jobs:
|
|||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
working-directory: backend
|
working-directory: backend
|
||||||
|
# A throwaway PostgreSQL for the tests that need a real database (the auth store, the
|
||||||
|
# platform-user SQL, the media routes and the migrate package). Without these two
|
||||||
|
# variables those tests skip themselves.
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: scratch
|
||||||
|
ports:
|
||||||
|
- 5432/tcp
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U postgres"
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 10
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgres://postgres:postgres@localhost:${{ job.services.postgres.ports['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
|
||||||
@@ -62,8 +82,16 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
go-version-file: backend/go.mod
|
go-version-file: backend/go.mod
|
||||||
cache: true
|
cache: true
|
||||||
|
# -p 1 runs one package at a time, because the database tests share one scratch database.
|
||||||
- name: Run Go tests
|
- name: Run Go tests
|
||||||
run: go test ./...
|
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)
|
||||||
@@ -78,6 +106,27 @@ 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'
|
||||||
|
|
||||||
|
java:
|
||||||
|
name: Test (Java)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: packages/java-backend
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up JDK
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: '17'
|
||||||
|
cache: maven
|
||||||
|
cache-dependency-path: packages/java-backend/pom.xml
|
||||||
|
- name: Run Java tests
|
||||||
|
run: mvn -B test
|
||||||
@@ -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$''',
|
||||||
|
]
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
**/dist/
|
||||||
|
**/.svelte-kit/
|
||||||
|
**/node_modules/
|
||||||
|
backend/
|
||||||
|
packages/java-backend/
|
||||||
|
packages/python-backend/
|
||||||
|
shared-styles.css
|
||||||
|
package-lock.json
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"printWidth": 120,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"plugins": ["prettier-plugin-svelte"],
|
||||||
|
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
|
||||||
|
}
|
||||||
@@ -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
|
||||||
+21
-15
@@ -3,54 +3,60 @@
|
|||||||
- **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-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
|
||||||
|
|
||||||
| Severity | Count |
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|---|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 0 |
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
| High | 1 |
|
| High | 1 | 1 | 0 | 0 |
|
||||||
| Medium | 4 |
|
| Medium | 4 | 4 | 0 | 0 |
|
||||||
| Low | 4 |
|
| Low | 4 | 0 | 0 | 4 |
|
||||||
| Info | 1 |
|
| Info | 1 | 0 | 0 | 1 |
|
||||||
|
|
||||||
The auth code has no obvious SQL N+1 outside the playlist reorder path, and most outbound calls have timeouts. The main performance risks are unbounded in-memory state in the sync websocket hub, a per-request AuthGuard round trip with no caching, blocking CPU work (password hashing) on event loops, and a media lookup that defeats its index.
|
The auth code has no obvious SQL N+1 outside the playlist reorder path, and most outbound calls have timeouts. The main performance risks are unbounded in-memory state in the sync websocket hub, a per-request AuthGuard round trip with no caching, blocking CPU work (password hashing) on event loops, and a media lookup that defeats its index.
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
### P-001 · Unbounded per-session timing maps and no connection cap in the sync hub · **High**
|
### P-001 · Unbounded per-session timing maps and no connection cap in the sync hub · **High** · Fixed
|
||||||
- **Location:** `backend/syncsocket/syncsocket.go:443` (sync:update handler), `backend/syncsocket/syncsocket.go:446-455` (writes to `playAt`, `playAtLocalMs`, `capturedAtMs` keyed by session ID), `backend/syncsocket/syncsocket.go:457-463` (eviction covers only `states`), `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts unlimited connections)
|
- **Location:** `backend/syncsocket/syncsocket.go:443` (sync:update handler), `backend/syncsocket/syncsocket.go:446-455` (writes to `playAt`, `playAtLocalMs`, `capturedAtMs` keyed by session ID), `backend/syncsocket/syncsocket.go:457-463` (eviction covers only `states`), `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts unlimited connections)
|
||||||
- **Description:** The three timing maps are written per session ID and are cleared only in narrow branches. The 1000-session cap on `states` does not touch them, so the maps grow for every new session ID ever seen. `ServeWebSocket` has no peer or connection limit, and each connection holds a goroutine and buffers.
|
- **Description:** The three timing maps are written per session ID and are cleared only in narrow branches. The 1000-session cap on `states` does not touch them, so the maps grow for every new session ID ever seen. `ServeWebSocket` has no peer or connection limit, and each connection holds a goroutine and buffers.
|
||||||
- **Impact:** Memory grows without bound in a long-running process, and one client sending `sync:update` with fresh session IDs can drive that growth. Exposure depends on whether consumers gate `/ws` with authentication (see Security S-003; needs verification in consumers).
|
- **Impact:** Memory grows without bound in a long-running process, and one client sending `sync:update` with fresh session IDs can drive that growth. Exposure depends on whether consumers gate `/ws` with authentication (see Security S-003; needs verification in consumers).
|
||||||
- **Recommendation:** Remove timing entries when a session is evicted or loses its last peer. Apply the same cap to all per-session maps. Add a maximum connection count and per-IP and per-peer message-rate limits.
|
- **Recommendation:** Remove timing entries when a session is evicted or loses its last peer. Apply the same cap to all per-session maps. Add a maximum connection count and per-IP and per-peer message-rate limits.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the `playAt`, `playAtLocalMs` and `capturedAtMs` maps are trimmed to `maxSyncSessions` (1000) after each `sync:update` write, and `ServeWebSocket` refuses connections past `maxSyncConnections` (1000) by closing with 1013 Try Again Later. Over the cap, entries are dropped arbitrarily, as `states` already is, instead of being removed on last-peer exit; per-IP and per-peer message-rate limits are not added. Behaviour change: an 1001st concurrent websocket is closed at once. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`.
|
||||||
|
|
||||||
### P-002 · Sync fan-out runs on the HTTP request path and writes to peers one at a time · **Medium**
|
### P-002 · Sync fan-out runs on the HTTP request path and writes to peers one at a time · **Medium** · Fixed
|
||||||
- **Location:** `backend/syncsocket/syncsocket.go:234` (`Broadcast`), `backend/syncsocket/syncsocket.go:247-261` (serial per-peer writes, 2 s timeout each; JSON marshalled once per peer), `backend/mediacore/mediacore.go:150` (`PUT /sync` calls `Broadcast` inline), `backend/syncsocket/syncsocket.go:486` (each `sync:update` fans out to the whole session)
|
- **Location:** `backend/syncsocket/syncsocket.go:234` (`Broadcast`), `backend/syncsocket/syncsocket.go:247-261` (serial per-peer writes, 2 s timeout each; JSON marshalled once per peer), `backend/mediacore/mediacore.go:150` (`PUT /sync` calls `Broadcast` inline), `backend/syncsocket/syncsocket.go:486` (each `sync:update` fans out to the whole session)
|
||||||
- **Description:** `Broadcast` marshals the payload once per peer and writes to peers sequentially, each with up to a 2 s deadline. The HTTP handler for `PUT /sync` calls it on the request goroutine, so one slow peer can hold the HTTP response for up to 2 s per peer. Peers may send `sync:update` at any rate, and each message is fanned out to the entire session.
|
- **Description:** `Broadcast` marshals the payload once per peer and writes to peers sequentially, each with up to a 2 s deadline. The HTTP handler for `PUT /sync` calls it on the request goroutine, so one slow peer can hold the HTTP response for up to 2 s per peer. Peers may send `sync:update` at any rate, and each message is fanned out to the entire session.
|
||||||
- **Impact:** Slow or hostile peers add latency to unrelated HTTP responses, and one client can multiply its traffic across every peer in its session.
|
- **Impact:** Slow or hostile peers add latency to unrelated HTTP responses, and one client can multiply its traffic across every peer in its session.
|
||||||
- **Recommendation:** Marshal once per broadcast, send through per-peer buffered queues written concurrently, and drop peers whose queue is full. Move HTTP-triggered broadcasts off the request goroutine. Add per-peer message-rate limits.
|
- **Recommendation:** Marshal once per broadcast, send through per-peer buffered queues written concurrently, and drop peers whose queue is full. Move HTTP-triggered broadcasts off the request goroutine. Add per-peer message-rate limits.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `Broadcast` marshals once and queues the message on a buffered per-peer channel without waiting on the network, a peer whose queue is full is dropped, and each peer now has a message-rate limit (120 messages per second; a faster client is closed with status 1008). Verifying it with a real stuck peer found that dropping the peer still blocked the caller: `conn.Close` waits up to five seconds for a close frame that a stuck peer never sends, and `Broadcast` (so `PUT /sync` and every other peer's read loop) ran that inline. `peer.drop` now closes the peer's `done` channel and runs the close handshake in its own goroutine, used by `Broadcast` and by the targeted send in `handleSyncUpdate`; a test fails without it (five seconds instead of microseconds). Behaviour change: none for well-behaved clients; a client sending over 120 messages in one second is disconnected. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`, `backend/mediacore/mediacore.go`, `backend/mediacore/routes_test.go`.
|
||||||
|
|
||||||
### P-003 · Media lookup defeats the `media_key` index, and playlist reorder issues one UPDATE per id · **Medium**
|
### P-003 · Media lookup defeats the `media_key` index, and playlist reorder issues one UPDATE per id · **Medium** · Fixed
|
||||||
- **Location:** `backend/mediacore/mediacore.go:735` (`findMedia`: `WHERE media_key=$1 OR CAST(id AS TEXT)=$1`), `backend/mediacore/mediacore.go:210` (thumbnail join with the same OR pattern), `backend/mediacore/mediacore.go:711-713` (reorder loop, one UPDATE per id, errors discarded, no transaction)
|
- **Location:** `backend/mediacore/mediacore.go:735` (`findMedia`: `WHERE media_key=$1 OR CAST(id AS TEXT)=$1`), `backend/mediacore/mediacore.go:210` (thumbnail join with the same OR pattern), `backend/mediacore/mediacore.go:711-713` (reorder loop, one UPDATE per id, errors discarded, no transaction)
|
||||||
- **Description:** An OR with a cast on `id` makes the planner unlikely to use the `media_key` index alone. Stream and thumbnail requests call this path on every request (`mediacore.go:181`, `194-224`). The reorder handler issues one statement per submitted id without a transaction and ignores errors; the 512 KB body cap allows tens of thousands of ids.
|
- **Description:** An OR with a cast on `id` makes the planner unlikely to use the `media_key` index alone. Stream and thumbnail requests call this path on every request (`mediacore.go:181`, `194-224`). The reorder handler issues one statement per submitted id without a transaction and ignores errors; the 512 KB body cap allows tens of thousands of ids.
|
||||||
- **Impact:** Each media request can cost a sequential scan on a large `media` table, and a single reorder call can issue tens of thousands of statements and report success after a partial failure. Plan impact was not measured (no database access).
|
- **Impact:** Each media request can cost a sequential scan on a large `media` table, and a single reorder call can issue tens of thousands of statements and report success after a partial failure. Plan impact was not measured (no database access).
|
||||||
- **Recommendation:** Look up by `media_key` only, and try the numeric id only when the input is all digits. Replace the loop with one `UPDATE ... FROM unnest(...)` inside a transaction, check errors, and cap the id count. Confirm with `EXPLAIN` on a populated table.
|
- **Recommendation:** Look up by `media_key` only, and try the numeric id only when the input is all digits. Replace the loop with one `UPDATE ... FROM unnest(...)` inside a transaction, check errors, and cap the id count. Confirm with `EXPLAIN` on a populated table.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `findMedia` and the thumbnail join match `media_key` and only a canonical decimal `id` (`canonicalMediaID`), so the id comparison no longer casts the column. Playlist reorder is one `UPDATE ... FROM unnest(...)` in a transaction, its error is checked, and requests above 10,000 ids are refused. Not measured: no database was available, so the `EXPLAIN` check on a populated table is still needed. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/paths_test.go`.
|
||||||
|
|
||||||
### P-004 · Password hashing blocks the event loop · **Medium**
|
### P-004 · Password hashing blocks the event loop · **Medium** · Fixed
|
||||||
- **Location:** `packages/node-backend/src/auth.js:61` and `:69` (`crypto.pbkdf2Sync` in `hashPassword` and `verifyPassword`), `packages/python-backend/src/shared_backend/auth.py:126` and `:131` (`bcrypt.hashpw` and `bcrypt.checkpw` called synchronously inside an otherwise async module)
|
- **Location:** `packages/node-backend/src/auth.js:61` and `:69` (`crypto.pbkdf2Sync` in `hashPassword` and `verifyPassword`), `packages/python-backend/src/shared_backend/auth.py:126` and `:131` (`bcrypt.hashpw` and `bcrypt.checkpw` called synchronously inside an otherwise async module)
|
||||||
- **Description:** Both runtimes perform deliberately expensive hashing synchronously on the thread that serves requests. Node uses 100,000 PBKDF2 iterations; Python uses bcrypt defaults. Each call takes tens to hundreds of milliseconds of CPU.
|
- **Description:** Both runtimes perform deliberately expensive hashing synchronously on the thread that serves requests. Node uses 100,000 PBKDF2 iterations; Python uses bcrypt defaults. Each call takes tens to hundreds of milliseconds of CPU.
|
||||||
- **Impact:** A burst of login or signup attempts stalls every other request in the process, which makes this a cheap denial-of-service lever as well as a latency problem.
|
- **Impact:** A burst of login or signup attempts stalls every other request in the process, which makes this a cheap denial-of-service lever as well as a latency problem.
|
||||||
- **Recommendation:** In Node, use the async `crypto.pbkdf2` or `scrypt`. In Python, wrap the bcrypt calls in `asyncio.to_thread` or expose async variants and use them from async handlers.
|
- **Recommendation:** In Node, use the async `crypto.pbkdf2` or `scrypt`. In Python, wrap the bcrypt calls in `asyncio.to_thread` or expose async variants and use them from async handlers.
|
||||||
|
- **Status:** Fixed 2026-10-19 — Node exports `hashPasswordAsync` and `verifyPasswordAsync` (async PBKDF2), and Python exports `hash_password_async` and `verify_password_async` (bcrypt in `asyncio.to_thread`). The sync helpers are unchanged, so consumers that hash inside request handlers must call the async variants. Files: `packages/node-backend/src/auth.js`, `packages/node-backend/src/index.js`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/src/shared_backend/__init__.py`.
|
||||||
|
|
||||||
### P-005 · Every authenticated request costs a fresh AuthGuard round trip, and the login-required flag is re-read per request · **Medium**
|
### P-005 · Every authenticated request costs a fresh AuthGuard round trip, and the login-required flag is re-read per request · **Medium** · Fixed
|
||||||
- **Location:** `backend/auth/proxy.go:504` (`CurrentUser` calls AuthGuard `/api/me` on each request), `backend/auth/proxy.go:512`, `:566`, `:598`, `:651`, `:733`, `:773`, `:848` (each re-reads the login-required setting from the store), `packages/node-backend/src/authclient.js:167` (`validate` per request), `packages/python-backend/src/shared_backend/authclient.py:254` (same), `backend/authclient/client.go:265-285` (middleware validates per request)
|
- **Location:** `backend/auth/proxy.go:504` (`CurrentUser` calls AuthGuard `/api/me` on each request), `backend/auth/proxy.go:512`, `:566`, `:598`, `:651`, `:733`, `:773`, `:848` (each re-reads the login-required setting from the store), `packages/node-backend/src/authclient.js:167` (`validate` per request), `packages/python-backend/src/shared_backend/authclient.py:254` (same), `backend/authclient/client.go:265-285` (middleware validates per request)
|
||||||
- **Description:** No client caches validated sessions, and the Go proxy re-reads the login-required flag from Postgres in each middleware and handler. A request carrying an invalid token still triggers an outbound call. The clients are otherwise correct about timeouts and context propagation.
|
- **Description:** No client caches validated sessions, and the Go proxy re-reads the login-required flag from Postgres in each middleware and handler. A request carrying an invalid token still triggers an outbound call. The clients are otherwise correct about timeouts and context propagation.
|
||||||
- **Impact:** Every request pays an AuthGuard round trip and at least one database read, so latency and load on AuthGuard and Postgres scale directly with traffic. Invalid tokens can be used to drive outbound calls.
|
- **Impact:** Every request pays an AuthGuard round trip and at least one database read, so latency and load on AuthGuard and Postgres scale directly with traffic. Invalid tokens can be used to drive outbound calls.
|
||||||
- **Recommendation:** Cache the login-required flag in memory with a short TTL, passing the resolved value down the request. Add a short-TTL session cache keyed by a SHA-256 of the token, storing both positive and negative results and bounded in size. Keep connections pooled in every client.
|
- **Recommendation:** Cache the login-required flag in memory with a short TTL, passing the resolved value down the request. Add a short-TTL session cache keyed by a SHA-256 of the token, storing both positive and negative results and bounded in size. Keep connections pooled in every client.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the Go proxy caches the login-required flag, and the Go AuthGuard client caches validation results, for two seconds, positive and negative, bounded at 10,000 entries and keyed by the SHA-256 of the token. The Node and Python AuthGuard clients now cache `validate` the same way, drop the entry on `logout`, and clear the cache when the base URL changes. Behaviour change: a session revoked elsewhere can still validate for up to two seconds. Files: `backend/auth/proxy.go`, `backend/authclient/client.go`, `backend/authclient/validation_cache.go`, `packages/node-backend/src/authclient.js`, `packages/node-backend/test/authclient.test.js`, `packages/python-backend/src/shared_backend/authclient.py`, `packages/python-backend/tests/test_authclient.py`.
|
||||||
|
|
||||||
### P-006 · Outbound AuthGuard calls use blocking `urllib` on the default thread pool · **Low**
|
### P-006 · Outbound AuthGuard calls use blocking `urllib` on the default thread pool · **Low**
|
||||||
- **Location:** `packages/python-backend/src/shared_backend/authclient.py:265` (`asyncio.to_thread`), `:276` (`urllib.request.urlopen`), `packages/node-backend/src/authclient.js:177` (abort timer)
|
- **Location:** `packages/python-backend/src/shared_backend/authclient.py:265` (`asyncio.to_thread`), `:276` (`urllib.request.urlopen`), `packages/node-backend/src/authclient.js:177` (abort timer)
|
||||||
@@ -86,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).
|
||||||
+26
-15
@@ -3,10 +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-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
|
||||||
|
|
||||||
@@ -22,59 +23,68 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
|
|||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
### Q-001 · Node database wrapper: no pool `error` listener, and writes are retried blindly · **Medium**
|
### Q-001 · Node database wrapper: no pool `error` listener, and writes are retried blindly · **Medium** · Fixed
|
||||||
- **Location:** `packages/node-backend/src/db.js:43` (`new Pool(...)` with no `'error'` handler; grep of the package finds none), `packages/node-backend/src/db.js:80-88` (`query()` retries once on any transient error)
|
- **Location:** `packages/node-backend/src/db.js:43` (`new Pool(...)` with no `'error'` handler; grep of the package finds none), `packages/node-backend/src/db.js:80-88` (`query()` retries once on any transient error)
|
||||||
- **Description:** `pg` emits `'error'` on the pool when an idle client fails, for example after a database restart. With no listener, that event is thrown and can terminate the process. Separately, `query()` retries once on any transient error for every statement, including `INSERT` and `UPDATE`, so a write that committed before the connection dropped can be applied twice.
|
- **Description:** `pg` emits `'error'` on the pool when an idle client fails, for example after a database restart. With no listener, that event is thrown and can terminate the process. Separately, `query()` retries once on any transient error for every statement, including `INSERT` and `UPDATE`, so a write that committed before the connection dropped can be applied twice.
|
||||||
- **Impact:** A database restart can crash a service that uses this wrapper, and non-idempotent writes can be duplicated.
|
- **Impact:** A database restart can crash a service that uses this wrapper, and non-idempotent writes can be duplicated.
|
||||||
- **Recommendation:** Attach a logging `pool.on('error', ...)` handler. Retry only reads, or require the caller to opt in to retrying a specific statement.
|
- **Recommendation:** Attach a logging `pool.on('error', ...)` handler. Retry only reads, or require the caller to opt in to retrying a specific statement.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `Database` attaches a logging `error` listener to the pool, so a failed idle client is logged instead of thrown. `query()` retries after a transient error only for plain read-only SELECTs, and a caller can opt a statement in with `{ retry: true }`. Behaviour change: a write that hits a transient error is no longer retried by default. Files: `packages/node-backend/src/db.js`, `packages/node-backend/test/db.test.js`.
|
||||||
|
|
||||||
### Q-002 · Repo-level media lint and test tooling points at directories that no longer exist · **Medium**
|
### Q-002 · Repo-level media lint and test tooling points at directories that no longer exist · **Medium** · Fixed
|
||||||
- **Location:** `scripts/media/lint-all.mjs:26` (package list `webui`) and `:51` (fails with "directory not found"), `scripts/media/enforce-no-skipped-tests.mjs:18-20` (roots `tests`, `webui/src`, `shared/packages`) and `:99-102` (prints OK when nothing is scanned), `scripts/media/upgrade-deps.mjs:102-104` (comment asserts there is no root `package.json`, which is false), `package.json:49-65` (`media:*` scripts)
|
- **Location:** `scripts/media/lint-all.mjs:26` (package list `webui`) and `:51` (fails with "directory not found"), `scripts/media/enforce-no-skipped-tests.mjs:18-20` (roots `tests`, `webui/src`, `shared/packages`) and `:99-102` (prints OK when nothing is scanned), `scripts/media/upgrade-deps.mjs:102-104` (comment asserts there is no root `package.json`, which is false), `package.json:49-65` (`media:*` scripts)
|
||||||
- **Description:** This tooling was carried over from a monorepo. `webui/`, `media-backend/` and `shared/packages` do not exist here; the real package is `packages/web-ui`. `media:lint:all` fails immediately, and `media:enforce:no-skipped-tests` scans zero files and still reports success, which gives false confidence. None of these scripts runs in CI.
|
- **Description:** This tooling was carried over from a monorepo. `webui/`, `media-backend/` and `shared/packages` do not exist here; the real package is `packages/web-ui`. `media:lint:all` fails immediately, and `media:enforce:no-skipped-tests` scans zero files and still reports success, which gives false confidence. None of these scripts runs in CI.
|
||||||
- **Impact:** Dead tooling that either fails or passes vacuously, and misleading comments about the repository layout.
|
- **Impact:** Dead tooling that either fails or passes vacuously, and misleading comments about the repository layout.
|
||||||
- **Recommendation:** Delete the unused scripts, or repoint them at `packages/web-ui` and `packages/*/test(s)`. Make the no-skipped-tests check fail when it scans zero files, and wire any script that is kept into CI.
|
- **Recommendation:** Delete the unused scripts, or repoint them at `packages/web-ui` and `packages/*/test(s)`. Make the no-skipped-tests check fail when it scans zero files, and wire any script that is kept into CI.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `lint-all.mjs` and `lint-all-json.mjs` point at `packages/web-ui`, `upgrade-deps.mjs` names the real local packages, and `enforce-no-skipped-tests.mjs` scans `packages/web-ui/src` and `packages/node-backend/test` and fails when it finds no files. The no-skipped-tests check now runs in `lint.yml`; `lint-all` is still not wired into CI because web-ui has no ESLint config (Q-009). Files: `scripts/media/lint-all.mjs`, `scripts/media/lint-all-json.mjs`, `scripts/media/upgrade-deps.mjs`, `scripts/media/enforce-no-skipped-tests.mjs`, `.github/workflows/lint.yml`.
|
||||||
|
|
||||||
### Q-003 · Java package has tests, but no CI job runs them · **Medium**
|
### Q-003 · Java package has tests, but no CI job runs them · **Medium** · Fixed
|
||||||
- **Location:** `packages/java-backend/pom.xml`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`, `.github/workflows/tests.yml`, `.github/workflows/lint.yml` (neither mentions Java or Maven)
|
- **Location:** `packages/java-backend/pom.xml`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`, `.github/workflows/tests.yml`, `.github/workflows/lint.yml` (neither mentions Java or Maven)
|
||||||
- **Description:** The only Java test class is `AuthClientTest`. `Totp`, `ResetManager`, `Roles` and cookie extraction have no direct tests. The package is compiled into a consuming project as source, so a regression here reaches that project without any signal in this repository.
|
- **Description:** The only Java test class is `AuthClientTest`. `Totp`, `ResetManager`, `Roles` and cookie extraction have no direct tests. The package is compiled into a consuming project as source, so a regression here reaches that project without any signal in this repository.
|
||||||
- **Impact:** Java changes can break without detection.
|
- **Impact:** Java changes can break without detection.
|
||||||
- **Recommendation:** Add a Java job (`mvn -B test` on a JDK matching the target) to `tests.yml`, and add unit tests for `Totp`, `ResetManager`, `Roles` and cookie extraction.
|
- **Recommendation:** Add a Java job (`mvn -B test` on a JDK matching the target) to `tests.yml`, and add unit tests for `Totp`, `ResetManager`, `Roles` and cookie extraction.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `tests.yml` has a `java` job that runs `mvn -B test` on JDK 17 in `packages/java-backend`. Not compiled or run: no JDK or Maven is available here, so the workflow and the Java test classes were checked by reading only. Files: `.github/workflows/tests.yml`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`.
|
||||||
|
|
||||||
### Q-004 · Go test coverage is absent for several packages, including the media core and the sync hub · **Medium**
|
### Q-004 · Go test coverage is absent for several packages, including the media core and the sync hub · **Medium** · Fixed
|
||||||
- **Location:** `backend/mediacore/mediacore.go` (1107 lines, no tests), `backend/syncsocket/syncsocket.go` (581 lines, no tests), `backend/logshipper/shipper.go` (438 lines, no tests), `backend/config/config.go` and `backend/migrate/migrate.go` (no tests), `backend/auth/proxy.go` (1525 lines; `proxy_test.go` covers constructors, middleware gating and normalizers only)
|
- **Location:** `backend/mediacore/mediacore.go` (1107 lines, no tests), `backend/syncsocket/syncsocket.go` (581 lines, no tests), `backend/logshipper/shipper.go` (438 lines, no tests), `backend/config/config.go` and `backend/migrate/migrate.go` (no tests), `backend/auth/proxy.go` (1525 lines; `proxy_test.go` covers constructors, middleware gating and normalizers only)
|
||||||
- **Description:** `git ls-files` shows no `_test.go` file in `mediacore`, `syncsocket`, `logshipper`, `config` or `migrate`. In `backend/auth`, the handler-level behaviour of Signup, Login, Logout, UpdateMe, the managed-user endpoints, the TOTP endpoints and the platform-user SQL is untested (per review pass).
|
- **Description:** `git ls-files` shows no `_test.go` file in `mediacore`, `syncsocket`, `logshipper`, `config` or `migrate`. In `backend/auth`, the handler-level behaviour of Signup, Login, Logout, UpdateMe, the managed-user endpoints, the TOTP endpoints and the platform-user SQL is untested (per review pass).
|
||||||
- **Impact:** The largest and most security-relevant code paths (media routes, websocket hub message handling, log redaction) change without tests.
|
- **Impact:** The largest and most security-relevant code paths (media routes, websocket hub message handling, log redaction) change without tests.
|
||||||
- **Recommendation:** Add `httptest` handler tests for the auth-gated routes and for websocket message handling, and table tests for the path helpers (`SafeRelative`, `ResolveUnderRoots`, `thumbnailFile`).
|
- **Recommendation:** Add `httptest` handler tests for the auth-gated routes and for websocket message handling, and table tests for the path helpers (`SafeRelative`, `ResolveUnderRoots`, `thumbnailFile`).
|
||||||
|
- **Status:** Fixed 2026-10-19 — every gap the finding names now has tests. `syncsocket`: connection cap, origin handling, identity, the per-peer message rate (`allowMessage`, and a flooding client is closed with 1008), and a stuck peer being dropped without holding up `Broadcast`. `logshipper`: levels, the local line, ID scrubbing, batching, the bounded buffer, flush and close, and a failing sink never failing the caller. `config` and `migrate`: the environment helpers, the argument and connection errors, and real goose runs. `mediacore`: the auth gate on every `Require` route, the sync routes (validation, clamping, broadcast to the session only), and, against PostgreSQL, stream and thumbnail (hidden media, escaped and refused paths), likes, saves, views, tags, and playlists including reorder and ownership. `auth`: handler tests for Login, Signup, Logout, UpdateMe, the managed-user routes, the TOTP routes, the gating middlewares and `Me` against a fake AuthGuard, the platform-user SQL against PostgreSQL, and the new contract file. Writing them found and fixed two defects: `Broadcast` could block for five seconds in the close handshake of a stuck peer (see P-002), and `GET /media/{id}/tags` always answered an empty list because the query's `tag` column was ambiguous (`backend/mediacore/mediacore.go`). The PostgreSQL tests skip unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` names a scratch database; `.github/workflows/tests.yml` now provides one to the Go job (`go test -p 1 ./...`). Files: `backend/syncsocket/syncsocket_test.go`, `backend/logshipper/shipper_test.go`, `backend/config/config_test.go`, `backend/migrate/migrate_test.go`, `backend/mediacore/routes_test.go`, `backend/mediacore/routes_db_test.go`, `backend/auth/proxy_handlers_test.go`, `backend/auth/platform_users_integration_test.go`, `backend/auth/store_integration_test.go`, `backend/auth/contract_test.go`, `backend/auth/proxy_test.go`, `.github/workflows/tests.yml`.
|
||||||
|
|
||||||
### Q-005 · The generated root stylesheet keeps a package import that the build was meant to strip · **Medium**
|
### Q-005 · The generated root stylesheet keeps a package import that the build was meant to strip · **Medium** · Fixed
|
||||||
- **Location:** `scripts/build-root-styles.mjs:4` (token import as a single-quoted string) and `:7` (filter compares exact text), `shared-styles.css:3` (`@import "@gabriel20xx/design-tokens/theme.css";` kept)
|
- **Location:** `scripts/build-root-styles.mjs:4` (token import as a single-quoted string) and `:7` (filter compares exact text), `shared-styles.css:3` (`@import "@gabriel20xx/design-tokens/theme.css";` kept)
|
||||||
- **Description:** The build removes the token import only when it matches the single-quoted string. `packages/web-ui/src/lib/styles.css:1` uses double quotes, so the filter misses it. The generated `shared-styles.css` keeps a bare package import on line 3 beside the relative import on line 1. This was already present at HEAD. No CI step checks that the committed generated file matches the build output.
|
- **Description:** The build removes the token import only when it matches the single-quoted string. `packages/web-ui/src/lib/styles.css:1` uses double quotes, so the filter misses it. The generated `shared-styles.css` keeps a bare package import on line 3 beside the relative import on line 1. This was already present at HEAD. No CI step checks that the committed generated file matches the build output.
|
||||||
- **Impact:** Consumers that vendor this file must resolve a package they may not install, or their bundler fails. The duplicated import also shows that the generation step is not verified.
|
- **Impact:** Consumers that vendor this file must resolve a package they may not install, or their bundler fails. The duplicated import also shows that the generation step is not verified.
|
||||||
- **Recommendation:** Normalise quotes in the filter (or match both forms), then add a CI step that rebuilds and runs `git diff --exit-code shared-styles.css`.
|
- **Recommendation:** Normalise quotes in the filter (or match both forms), then add a CI step that rebuilds and runs `git diff --exit-code shared-styles.css`.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the build's token-import filter matches both quote styles and an optional semicolon, so the package import is stripped. Running the build reproduces `shared-styles.css` byte for byte, and `lint.yml` now runs `git diff --exit-code -- shared-styles.css` after `npm ci`. Files: `scripts/build-root-styles.mjs`, `shared-styles.css`, `.github/workflows/lint.yml`.
|
||||||
|
|
||||||
### Q-006 · The sync script can overwrite consumer changes, and the post-commit hook commits into consumer repositories · **Medium**
|
### Q-006 · The sync script can overwrite consumer changes, and the post-commit hook commits into consumer repositories · **Medium** · Fixed
|
||||||
- **Location:** `scripts/sync-consumers.ps1:273` (dirty-destination check bypassed by `-Force`), `scripts/sync-consumers.ps1:291` (stale files removed) and `:301` (files overwritten), `.githooks/post-commit:8-10` (runs the sync with `-Commit` after every commit), `scripts/install-sync-hook.ps1` (enables the hook)
|
- **Location:** `scripts/sync-consumers.ps1:273` (dirty-destination check bypassed by `-Force`), `scripts/sync-consumers.ps1:291` (stale files removed) and `:301` (files overwritten), `.githooks/post-commit:8-10` (runs the sync with `-Commit` after every commit), `scripts/install-sync-hook.ps1` (enables the hook)
|
||||||
- **Description:** With `-Force`, uncommitted changes inside a consumer's `shared/` folder are deleted or overwritten with no backup. The hook, once installed, runs the sync with `-Commit` after every commit in this repository, which creates commits in each registered consumer repository (22 entries in `$consumerProjects`).
|
- **Description:** With `-Force`, uncommitted changes inside a consumer's `shared/` folder are deleted or overwritten with no backup. The hook, once installed, runs the sync with `-Commit` after every commit in this repository, which creates commits in each registered consumer repository (22 entries in `$consumerProjects`).
|
||||||
- **Impact:** Possible loss of uncommitted consumer work, and unexpected commits in other projects after an unrelated commit here.
|
- **Impact:** Possible loss of uncommitted consumer work, and unexpected commits in other projects after an unrelated commit here.
|
||||||
- **Recommendation:** Make destructive overwrite require an explicit flag that first stashes or backs up the destination. Make the hook opt-in, or have it report what would change instead of committing. Document the behaviour in the README.
|
- **Recommendation:** Make destructive overwrite require an explicit flag that first stashes or backs up the destination. Make the hook opt-in, or have it report what would change instead of committing. Document the behaviour in the README.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the post-commit hook runs the consumer sync only when `SHARED_SYNC_COMMIT=1` is set for that commit, and `sync-consumers.ps1` copies a dirty destination to a temp backup before `-Force` overwrites it. Behaviour change: an ordinary commit no longer syncs or commits into consumer repositories. Not run: PowerShell is not installed here, so the script change is unparsed. Files: `.githooks/post-commit`, `scripts/sync-consumers.ps1`, `scripts/install-sync-hook.ps1`.
|
||||||
|
|
||||||
### Q-007 · Publish workflows release without running the checks that exist for pull requests · **Medium**
|
### Q-007 · Publish workflows release without running the checks that exist for pull requests · **Medium** · Fixed
|
||||||
- **Location:** `.gitea/workflows/publish-npm.yml:27-49` (builds, then publishes; no lint or test step), `.gitea/workflows/publish-python.yml:26-39` (builds and uploads; no ruff or unittest), `.gitea/workflows/publish-go.yml:29-31` (runs `go test` only; no `go vet` or gofmt)
|
- **Location:** `.gitea/workflows/publish-npm.yml:27-49` (builds, then publishes; no lint or test step), `.gitea/workflows/publish-python.yml:26-39` (builds and uploads; no ruff or unittest), `.gitea/workflows/publish-go.yml:29-31` (runs `go test` only; no `go vet` or gofmt)
|
||||||
- **Description:** A `v*` tag or a published release publishes whatever is tagged, without the lint and test jobs in `.github/workflows` that gate changes. The publish workflows run in a separate system, so the same checks are not enforced at release time.
|
- **Description:** A `v*` tag or a published release publishes whatever is tagged, without the lint and test jobs in `.github/workflows` that gate changes. The publish workflows run in a separate system, so the same checks are not enforced at release time.
|
||||||
- **Impact:** Broken or unlinted code can reach the shared registries that projects consume.
|
- **Impact:** Broken or unlinted code can reach the shared registries that projects consume.
|
||||||
- **Recommendation:** Make each publish job run the same checks as CI (`npm run lint` and `npm test`, `ruff check`, `python -m unittest`, `go vet` and gofmt) before upload, or depend on a prior successful workflow run.
|
- **Recommendation:** Make each publish job run the same checks as CI (`npm run lint` and `npm test`, `ruff check`, `python -m unittest`, `go vet` and gofmt) before upload, or depend on a prior successful workflow run.
|
||||||
|
- **Status:** Fixed 2026-10-19 — each publish workflow runs the checks that gate pull requests before it uploads: npm runs `npm run lint` and `npm test`, Python runs ruff and the unittest suite, and Go runs gofmt and `go vet` before `go test`. Not run: no Gitea runner is available here. The Go gofmt step will fail until `backend/authclient/client.go` and `backend/syncsocket/syncsocket.go` are gofmt-clean; their in-progress hunks were not reformatted in this pass. Files: `.gitea/workflows/publish-npm.yml`, `.gitea/workflows/publish-python.yml`, `.gitea/workflows/publish-go.yml`.
|
||||||
|
|
||||||
### Q-008 · The four AuthGuard clients diverge in behaviour and in the stored password-hash format · **Medium**
|
### Q-008 · The four AuthGuard clients diverge in behaviour and in the stored password-hash format · **Medium** · Open
|
||||||
- **Location:** `packages/node-backend/src/auth.js:56-81` (PBKDF2 `salt:hex` hashes) vs `packages/python-backend/src/shared_backend/auth.py:123-133` (bcrypt hashes) in the same `auth_users.password_hash` column; `packages/python-backend/src/shared_backend/auth.py:225-240` (`list_users` and `create_managed_user` return `password_hash`) vs `packages/node-backend/src/auth.js:221-233` (excludes it); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:195` (`IllegalStateException` escapes `middleware` while Node returns 401); `packages/node-backend/src/db.js:69-74` (retries only transient errors) vs `packages/python-backend/src/shared_backend/postgres.py:63` (retries every exception); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:80` (`String.equals`) vs constant-time comparison in Node and Python
|
- **Location:** `packages/node-backend/src/auth.js:56-81` (PBKDF2 `salt:hex` hashes) vs `packages/python-backend/src/shared_backend/auth.py:123-133` (bcrypt hashes) in the same `auth_users.password_hash` column; `packages/python-backend/src/shared_backend/auth.py:225-240` (`list_users` and `create_managed_user` return `password_hash`) vs `packages/node-backend/src/auth.js:221-233` (excludes it); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:195` (`IllegalStateException` escapes `middleware` while Node returns 401); `packages/node-backend/src/db.js:69-74` (retries only transient errors) vs `packages/python-backend/src/shared_backend/postgres.py:63` (retries every exception); `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java:80` (`String.equals`) vs constant-time comparison in Node and Python
|
||||||
- **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately.
|
- **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately.
|
||||||
- **Impact:** A service behaves differently depending on which runtime serves it, and a password hash can reach an API response in Python.
|
- **Impact:** A service behaves differently depending on which runtime serves it, and a password hash can reach an API response in Python.
|
||||||
- **Recommendation:** Standardise the hash format (or rehash on login), strip `password_hash` from every DTO, align the retry policy and the middleware failure modes, and add cross-language contract tests that run the same fixtures against each client.
|
- **Recommendation:** Standardise the hash format (or rehash on login), strip `password_hash` from every DTO, align the retry policy and the middleware failure modes, and add cross-language contract tests that run the same fixtures against each client.
|
||||||
|
- **Status:** 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**
|
### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium** · Fixed
|
||||||
- **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script)
|
- **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script)
|
||||||
- **Description:** No ESLint, Prettier or Stylelint configuration is tracked for `packages/web-ui` or `packages/node-backend`. Lint covers type checks and syntax only. `packages/web-ui` has no tests, so components such as `AuthPage`, `MediaPlayer` and the notification and primary-color stores are unverified.
|
- **Description:** No ESLint, Prettier or Stylelint configuration is tracked for `packages/web-ui` or `packages/node-backend`. Lint covers type checks and syntax only. `packages/web-ui` has no tests, so components such as `AuthPage`, `MediaPlayer` and the notification and primary-color stores are unverified.
|
||||||
- **Impact:** Style drift and behavioural regressions in a UI library that several applications consume.
|
- **Impact:** Style drift and behavioural regressions in a UI library that several applications consume.
|
||||||
- **Recommendation:** Add ESLint (with `eslint-plugin-svelte`) and Prettier configuration at package level, and a small Vitest and `@testing-library/svelte` suite covering `AuthPage`, the notification store and the primary-color helpers.
|
- **Recommendation:** Add ESLint (with `eslint-plugin-svelte`) and Prettier configuration at package level, and a small Vitest and `@testing-library/svelte` suite covering `AuthPage`, the notification store and the primary-color helpers.
|
||||||
|
- **Status:** Fixed 2026-10-19 — ESLint (flat config `eslint.config.js`: `@eslint/js`, `typescript-eslint`, `eslint-plugin-svelte`) now lints `packages/web-ui`, `packages/node-backend` and `scripts` with `--max-warnings=0`; it is part of `npm run lint` (so of `lint.yml` and the publish gate) and each package has a `lint` script. Prettier 3 with `prettier-plugin-svelte` is configured in `.prettierrc.json`, with `npm run format` and `format:check` (also a `lint.yml` step). `packages/web-ui` has a Vitest and `@testing-library/svelte` suite in `packages/web-ui/tests` (27 tests: `AuthPage` login, two-factor challenge, setup and reset flows; the notification store and `NotificationStack`; the primary-color helpers), run by `npm run test:web-ui`, which `npm test` and `release` now include. All of it is root `devDependencies` (`eslint`, `@eslint/js`, `typescript-eslint`, `eslint-plugin-svelte`, `globals`, `prettier`, `prettier-plugin-svelte`, `vitest`, `jsdom`, `@testing-library/svelte`; no way to fix the finding without them), so `packages/web-ui/package.json`'s dependencies and the consumers' lockfile entries for it are unchanged; only a `lint` and a `test` script were added there. The existing code passes ESLint without code changes beyond three unused bindings in `scripts/media`; three Svelte rules that would change how shipped components render or hold state (`require-each-key`, `prefer-writable-derived`, `prefer-svelte-reactivity`) are turned off with a comment. Not done: Prettier is enforced only on the files written to its style (44 older files differ from it and were not reformatted, to keep the mirrored diff small), and Stylelint was not added. Files: `eslint.config.js`, `.prettierrc.json`, `.prettierignore`, `package.json`, `package-lock.json`, `packages/web-ui/{package.json,vitest.config.ts,tests/}`, `packages/node-backend/package.json`, `scripts/media/{lint-all,lint-all-json,list-skipped-tests,enforce-no-skipped-tests}.mjs`, `.github/workflows/lint.yml`.
|
||||||
|
|
||||||
### Q-010 · Errors on security paths are masked as invalid codes or swallowed · **Low**
|
### Q-010 · Errors on security paths are masked as invalid codes or swallowed · **Low**
|
||||||
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:723` and `:740` (`except Exception` returns "Invalid authenticator code"), `packages/python-backend/src/shared_backend/authproxy.py:506-507` (logout ignores `APIError` but clears the cookie), `backend/auth/proxy.go:1232-1235` (`TOTPVerify` maps every error to 401 invalid code), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:282-284` (`IOException` discarded without logging)
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:723` and `:740` (`except Exception` returns "Invalid authenticator code"), `packages/python-backend/src/shared_backend/authproxy.py:506-507` (logout ignores `APIError` but clears the cookie), `backend/auth/proxy.go:1232-1235` (`TOTPVerify` maps every error to 401 invalid code), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:282-284` (`IOException` discarded without logging)
|
||||||
@@ -107,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)
|
||||||
@@ -122,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.
|
||||||
@@ -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
|
||||||
@@ -106,7 +110,7 @@ To pull the latest snapshot into every registered consumer:
|
|||||||
.\scripts\sync-consumers.ps1 -Commit -Push
|
.\scripts\sync-consumers.ps1 -Commit -Push
|
||||||
```
|
```
|
||||||
|
|
||||||
The script copies every tracked file in this repo into each consumer's `shared/` folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared snapshot from `<short-sha>`"). Consumers are registered in the script's `$consumerProjects` list. A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) runs this automatically — with `-Commit` only, never `-Push` — after every commit to this repo, so pushing the sync commits it creates to each consumer is still a manual follow-up step.
|
The script copies every tracked file in this repo into each consumer's `shared/` folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared snapshot from `<short-sha>`"). Consumers are registered in the script's `$consumerProjects` list. A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) can run this automatically, with `-Commit` only and never `-Push`. It is opt-in: it does nothing unless the commit is made with `SHARED_SYNC_COMMIT=1` in the environment, so an ordinary commit here never writes to a consumer repository. Pushing the sync commits to each consumer remains a manual follow-up step. Running with `-Force` over a consumer that has local changes first copies the replaced `shared/` folder to a temporary backup directory, and the script prints its path.
|
||||||
|
|
||||||
### Published registry packages (for standalone/external use)
|
### Published registry packages (for standalone/external use)
|
||||||
|
|
||||||
@@ -119,8 +123,11 @@ The npm, Go, and Python packages are also published to this Gitea instance's pac
|
|||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
npm run check
|
npm run check
|
||||||
|
npm run lint # svelte-check, Node syntax check and ESLint
|
||||||
|
npm run format:check # Prettier, for the files written to its style (.prettierrc.json)
|
||||||
npm run build # builds packages/web-ui/dist (gitignored, not committed)
|
npm run build # builds packages/web-ui/dist (gitignored, not committed)
|
||||||
npm run test:node-backend
|
npm run test:node-backend
|
||||||
|
npm run test:web-ui # Vitest component and store tests (jsdom)
|
||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -129,6 +136,10 @@ go test ./...
|
|||||||
go vet ./...
|
go vet ./...
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Go tests that need PostgreSQL skip themselves unless a scratch database is named: `DATABASE_URL` for the auth store tests, `SHARED_TEST_DATABASE_URL` for the platform-user, 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, 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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Typical `web-ui` wiring
|
## Typical `web-ui` wiring
|
||||||
@@ -196,4 +207,4 @@ The Go module lives under `backend`, so its release tag uses the submodule prefi
|
|||||||
|
|
||||||
## CI/CD
|
## CI/CD
|
||||||
|
|
||||||
`lint.yml` and `tests.yml` each run three jobs — Node/Svelte, Go, and Python. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above.
|
`lint.yml` runs three jobs — Node/Svelte (svelte-check, ESLint, Prettier), Go, and Python; `tests.yml` runs four — Node/Svelte (including the web-ui Vitest suite), Go (against a PostgreSQL service), Python, and Java. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above.
|
||||||
+49
-30
@@ -3,126 +3,144 @@
|
|||||||
- **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-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
|
||||||
|
|
||||||
| Severity | Count |
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|---|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 1 |
|
| Critical | 1 | 1 | 0 | 0 |
|
||||||
| High | 3 |
|
| High | 3 | 2 | 0 | 1 |
|
||||||
| Medium | 13 |
|
| Medium | 13 | 12 | 0 | 1 |
|
||||||
| Low | 5 |
|
| Low | 5 | 0 | 0 | 5 |
|
||||||
| Info | 0 |
|
| Info | 0 | 0 | 0 | 0 |
|
||||||
|
|
||||||
The most serious issue is a Python router route that lets an anonymous caller switch off login for everything guarded by `require_session`. Beyond it, the common themes are fail-open defaults, a websocket hub with no identity, credential endpoints with no throttling, and weaker-than-intended hashing and second-factor controls. No live secrets were found in the current tree or in git history. Most findings that depend on AuthGuard need confirmation against that service.
|
The most serious issue is a Python router route that lets an anonymous caller switch off login for everything guarded by `require_session`. Beyond it, the common themes are fail-open defaults, a websocket hub with no identity, credential endpoints with no throttling, and weaker-than-intended hashing and second-factor controls. No live secrets were found in the current tree or in git history. Most findings that depend on AuthGuard need confirmation against that service.
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
### S-001 · Anonymous `PUT /access` switches off login for every guarded route · **Critical**
|
### S-001 · Anonymous `PUT /access` switches off login for every guarded route · **Critical** · Fixed
|
||||||
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:561-569` (`PUT /access` has no session or role dependency; `GET /access` at `:557-559` is also open), `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns the local superadmin profile once login is not required), `packages/python-backend/src/shared_backend/authproxy.py:103-105` (`_LOCAL_PROFILE`), `packages/python-backend/tests/test_authproxy.py:116-122` (asserts the unauthenticated PUT succeeds)
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:561-569` (`PUT /access` has no session or role dependency; `GET /access` at `:557-559` is also open), `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns the local superadmin profile once login is not required), `packages/python-backend/src/shared_backend/authproxy.py:103-105` (`_LOCAL_PROFILE`), `packages/python-backend/tests/test_authproxy.py:116-122` (asserts the unauthenticated PUT succeeds)
|
||||||
- **Description:** The public `PUT /access` only depends on the store, so any anonymous request with `{"loginRequired": false}` disables authentication. Once the flag is off, `require_session` returns the superadmin profile for every request. The internal variant at `authproxy.py:570-584` correctly requires `X-Internal-Auth`; the public one does not. The Go equivalent, `backend/auth/proxy.go:781`, is documented as manager-only (`proxy.go:796`).
|
- **Description:** The public `PUT /access` only depends on the store, so any anonymous request with `{"loginRequired": false}` disables authentication. Once the flag is off, `require_session` returns the superadmin profile for every request. The internal variant at `authproxy.py:570-584` correctly requires `X-Internal-Auth`; the public one does not. The Go equivalent, `backend/auth/proxy.go:781`, is documented as manager-only (`proxy.go:796`).
|
||||||
- **Impact:** Anyone who can reach a service that mounts `build_auth_router` can remove authentication from every route guarded by `require_session`. This is the documented usage (`packages/python-backend/README.md:123-133`), so exposure is likely in consumers. Consumer wiring was not reviewed.
|
- **Impact:** Anyone who can reach a service that mounts `build_auth_router` can remove authentication from every route guarded by `require_session`. This is the documented usage (`packages/python-backend/README.md:123-133`), so exposure is likely in consumers. Consumer wiring was not reviewed.
|
||||||
- **Recommendation:** Require a user-manager session for `PUT /access`, and for `GET` unless the value is intentionally public. Add a `require_admin` dependency, mirroring the Go `RequireAdmin`. Change the test at `test_authproxy.py:116-122` to expect 401 without a session, and confirm no consumer exposes the router without this change.
|
- **Recommendation:** Require a user-manager session for `PUT /access`, and for `GET` unless the value is intentionally public. Add a `require_admin` dependency, mirroring the Go `RequireAdmin`. Change the test at `test_authproxy.py:116-122` to expect 401 without a session, and confirm no consumer exposes the router without this change.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `PUT /access` now depends on a new `require_admin` dependency that needs a session whose role can manage users (401 without a session or AuthGuard, 403 for other roles), so an anonymous caller can no longer clear the login flag. `GET /access` stays public for the login screen, and the internal route keeps its shared-secret check; the tests now assert 401 and 403 and that an admin session can still toggle. Files: `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`.
|
||||||
|
|
||||||
### S-002 · Malformed cookies crash the Node middleware and fail requests in Java · **High**
|
### S-002 · Malformed cookies crash the Node middleware and fail requests in Java · **High** · Fixed
|
||||||
- **Location:** `packages/node-backend/src/authclient.js:214` (`tokenFromRequest` runs before the `try` block), `packages/node-backend/src/authclient.js:239` (`decodeURIComponent` on the cookie value), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:718-721` (`URLDecoder.decode` with only an `UnsupportedEncodingException` catch), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:278` (`extractToken` called from `middleware`)
|
- **Location:** `packages/node-backend/src/authclient.js:214` (`tokenFromRequest` runs before the `try` block), `packages/node-backend/src/authclient.js:239` (`decodeURIComponent` on the cookie value), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:718-721` (`URLDecoder.decode` with only an `UnsupportedEncodingException` catch), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:278` (`extractToken` called from `middleware`)
|
||||||
- **Description:** In Node, the async middleware calls `tokenFromRequest` before its `try`. `decodeURIComponent` throws `URIError` on a malformed escape such as a bare `%`, so the middleware rejects. Express 4 does not catch async rejections, and Node's default unhandled-rejection mode terminates the process. In Java, `URLDecoder.decode` throws `IllegalArgumentException` on a malformed escape; the only catch is for a different exception type, so the request fails with an error rather than a 401. `URLDecoder` also turns `+` into a space, which alters valid tokens.
|
- **Description:** In Node, the async middleware calls `tokenFromRequest` before its `try`. `decodeURIComponent` throws `URIError` on a malformed escape such as a bare `%`, so the middleware rejects. Express 4 does not catch async rejections, and Node's default unhandled-rejection mode terminates the process. In Java, `URLDecoder.decode` throws `IllegalArgumentException` on a malformed escape; the only catch is for a different exception type, so the request fails with an error rather than a 401. `URLDecoder` also turns `+` into a space, which alters valid tokens.
|
||||||
- **Impact:** A single unauthenticated request with a crafted cookie can crash a Node service (the package requires Node 20 or newer, `packages/node-backend/package.json` `engines`). Java returns server errors instead of 401 and can mangle tokens containing `+`.
|
- **Impact:** A single unauthenticated request with a crafted cookie can crash a Node service (the package requires Node 20 or newer, `packages/node-backend/package.json` `engines`). Java returns server errors instead of 401 and can mangle tokens containing `+`.
|
||||||
- **Recommendation:** Move token extraction inside the `try` in Node, and make `tokenFromRequest` return `''` on decode errors. In Java, catch `IllegalArgumentException` and percent-decode without treating `+` as a space. Add tests for malformed cookies in both packages.
|
- **Recommendation:** Move token extraction inside the `try` in Node, and make `tokenFromRequest` return `''` on decode errors. In Java, catch `IllegalArgumentException` and percent-decode without treating `+` as a space. Add tests for malformed cookies in both packages.
|
||||||
|
- **Status:** Fixed 2026-10-19 — in Node, `middleware()` now calls `tokenFromRequest` inside its `try`, and a malformed cookie escape yields `''`, so the request gets a 401 instead of an unhandled rejection. In Java, `extractCookieToken` escapes a literal `+` before `URLDecoder` so it is kept, and a malformed escape returns `""` instead of throwing. Tests were added in both packages; the Java tests were not compiled or run because no JDK is installed here, so they were checked by reading only. Files: `packages/node-backend/src/authclient.js`, `packages/node-backend/test/authclient.test.js`, `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`.
|
||||||
|
|
||||||
### S-003 · The websocket sync hub has no identity, and self-asserted client IDs gate remote control · **High**
|
### S-003 · The websocket sync hub has no identity, and self-asserted client IDs gate remote control · **High** · Open
|
||||||
- **Location:** `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts any connection), `backend/syncsocket/syncsocket.go:109` (client ID assigned from the message), `backend/syncsocket/syncsocket.go:366-369` (`control:claim` and `control:release` compare the requester against the same self-asserted ID), `backend/syncsocket/syncsocket.go:146-150` (every peer's ID and `remoteControlEnabled` is broadcast to all members)
|
- **Location:** `backend/syncsocket/syncsocket.go:293` (`ServeWebSocket` accepts any connection), `backend/syncsocket/syncsocket.go:109` (client ID assigned from the message), `backend/syncsocket/syncsocket.go:366-369` (`control:claim` and `control:release` compare the requester against the same self-asserted ID), `backend/syncsocket/syncsocket.go:146-150` (every peer's ID and `remoteControlEnabled` is broadcast to all members)
|
||||||
- **Description:** The hub does not authenticate the connection. A client chooses its `clientId` in `sync:hello` or `client:status`, with no uniqueness or ownership check. Peers can see each other's IDs and control state, so a new client can adopt the ID of a peer that has remote control enabled and then claim or release that control.
|
- **Description:** The hub does not authenticate the connection. A client chooses its `clientId` in `sync:hello` or `client:status`, with no uniqueness or ownership check. Peers can see each other's IDs and control state, so a new client can adopt the ID of a peer that has remote control enabled and then claim or release that control.
|
||||||
- **Impact:** Any client that can reach `/ws` and join a session can take over playback control or impersonate another device. Exposure depends on whether each consumer gates `/ws` with authentication (not verifiable here; the package's own example wires it with no middleware).
|
- **Impact:** Any client that can reach `/ws` and join a session can take over playback control or impersonate another device. Exposure depends on whether each consumer gates `/ws` with authentication (not verifiable here; the package's own example wires it with no middleware).
|
||||||
- **Recommendation:** Bind each connection to a server-issued identity (an authenticated user or a signed session token) at upgrade time. Reject duplicate client IDs within a session. Require authentication on the `/ws` route in every consumer, and show that in the package documentation.
|
- **Recommendation:** Bind each connection to a server-issued identity (an authenticated user or a signed session token) at upgrade time. Reject duplicate client IDs within a session. Require authentication on the `/ws` route in every consumer, and show that in the package documentation.
|
||||||
|
- **Status:** Open 2026-10-19 — partly fixed (decision 12): each websocket connection is issued a random `clientId` at upgrade time and receives it in its `hello` frame. A message naming any other identity gets a `client-id-mismatch` error frame and is dropped, so self-chosen and duplicate IDs are no longer possible. Behaviour change: a client must take its ID from `hello`, and a reconnect gets a new identity, so control claims and remote-control flags do not carry over. Still open: `/ws` still accepts unauthenticated connections, so an anonymous connection can still obtain an identity and claim control of any peer that enabled remote control. Requiring authentication on each consumer's `/ws` route is a consumer change and was not made here. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`.
|
||||||
|
|
||||||
### S-004 · Anonymous `PUT /sync` writes unvalidated JSON into shared session state · **High**
|
### S-004 · Anonymous `PUT /sync` writes unvalidated JSON into shared session state · **High** · Fixed
|
||||||
- **Location:** `backend/mediacore/mediacore.go:88` (`r.With(c.auth.Optional).Put("/sync", ...)`), `backend/mediacore/mediacore.go:124-152` (`putSyncState`, which does not check the caller), `backend/mediacore/mediacore.go:135` (session ID defaults to `"default"`), `backend/mediacore/mediacore.go:138` and `:146-148` (raw `mediaId` and `playAt` stored), `backend/mediacore/mediacore.go:1049` (512 KB body cap), `backend/syncsocket/syncsocket.go:204-213` (1000-session cap, no per-entry size limit)
|
- **Location:** `backend/mediacore/mediacore.go:88` (`r.With(c.auth.Optional).Put("/sync", ...)`), `backend/mediacore/mediacore.go:124-152` (`putSyncState`, which does not check the caller), `backend/mediacore/mediacore.go:135` (session ID defaults to `"default"`), `backend/mediacore/mediacore.go:138` and `:146-148` (raw `mediaId` and `playAt` stored), `backend/mediacore/mediacore.go:1049` (512 KB body cap), `backend/syncsocket/syncsocket.go:204-213` (1000-session cap, no per-entry size limit)
|
||||||
- **Description:** The route uses `Optional`, so anonymous callers reach `putSyncState`, which never checks who they are. Any caller can overwrite any session's playback state, including the shared `"default"` session. Values are stored without the type checks that the websocket path applies (`syncsocket.go:489-498`). This assumes `Optional` admits anonymous requests; `backend/auth` was not read in this pass (needs verification).
|
- **Description:** The route uses `Optional`, so anonymous callers reach `putSyncState`, which never checks who they are. Any caller can overwrite any session's playback state, including the shared `"default"` session. Values are stored without the type checks that the websocket path applies (`syncsocket.go:489-498`). This assumes `Optional` admits anonymous requests; `backend/auth` was not read in this pass (needs verification).
|
||||||
- **Impact:** Anonymous clients can overwrite shared playback state, and can pin substantial memory by filling many sessions with large bodies.
|
- **Impact:** Anonymous clients can overwrite shared playback state, and can pin substantial memory by filling many sessions with large bodies.
|
||||||
- **Recommendation:** Require authentication, or a session-scoped token, for `PUT /sync`. Validate `mediaId` and `playAt` types the way the websocket path does, and cap the stored size per session.
|
- **Recommendation:** Require authentication, or a session-scoped token, for `PUT /sync`. Validate `mediaId` and `playAt` types the way the websocket path does, and cap the stored size per session.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `PUT /sync` now sits behind `Require`, so anonymous callers get 401 when login is required. `mediaId` and `playAt` must be null, a number or a string, and strings are trimmed and capped at 128 bytes, so other shapes are refused with 400 and the stored state holds only scalars. Behaviour change: clients that send anonymous `PUT /sync` with login enabled are now refused, and non-scalar `mediaId` or `playAt` values get 400. Any authenticated user can still write any session, including `"default"`, which is the session model rather than part of this finding. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/mediacore_test.go`.
|
||||||
|
|
||||||
### S-005 · The Python proxy fails open to superadmin when AuthGuard is not configured, and the login override is per process · **Medium**
|
### S-005 · The Python proxy fails open to superadmin when AuthGuard is not configured, and the login override is per process · **Medium** · Fixed
|
||||||
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns `_LOCAL_PROFILE` when `get_client` returns `None` or login is off), `packages/python-backend/src/shared_backend/authproxy.py:349` and `:389` (the configuration check runs only in `get_me` and `get_status`), `packages/python-backend/src/shared_backend/authproxy.py:255` and `:308-311` (process-local override that is never refreshed from the store), `packages/python-backend/src/shared_backend/authproxy.py:565-567` and `:582-583` (set the override). The Go handler has the same override pattern (`backend/auth/proxy.go:759-811`, per review).
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:313-320` (`require_session` returns `_LOCAL_PROFILE` when `get_client` returns `None` or login is off), `packages/python-backend/src/shared_backend/authproxy.py:349` and `:389` (the configuration check runs only in `get_me` and `get_status`), `packages/python-backend/src/shared_backend/authproxy.py:255` and `:308-311` (process-local override that is never refreshed from the store), `packages/python-backend/src/shared_backend/authproxy.py:565-567` and `:582-583` (set the override). The Go handler has the same override pattern (`backend/auth/proxy.go:759-811`, per review).
|
||||||
- **Description:** A missing or unset AuthGuard URL silently makes every guarded route public with a superadmin identity, because the configuration error is enforced on only two routes. Separately, once a process has seen a login-required change, it keeps its own value and never re-reads the store, so other workers or replicas can disagree.
|
- **Description:** A missing or unset AuthGuard URL silently makes every guarded route public with a superadmin identity, because the configuration error is enforced on only two routes. Separately, once a process has seen a login-required change, it keeps its own value and never re-reads the store, so other workers or replicas can disagree.
|
||||||
- **Impact:** A missing environment variable in production silently removes authentication. A worker can stay unauthenticated after login has been re-enabled elsewhere, until it restarts.
|
- **Impact:** A missing environment variable in production silently removes authentication. A worker can stay unauthenticated after login has been re-enabled elsewhere, until it restarts.
|
||||||
- **Recommendation:** Make auth-disabled mode an explicit opt-in flag that must be set, and apply the configuration check inside `require_session`. Remove the process-local override and read the store on each call, with a short-TTL cache if needed.
|
- **Recommendation:** Make auth-disabled mode an explicit opt-in flag that must be set, and apply the configuration check inside `require_session`. Remove the process-local override and read the store on each call, with a short-TTL cache if needed.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the Python guarded routes now resolve through `_configured_client`, which fails closed with a 500 when AUTHGUARD_URL is unset unless the consumer passes `local_profile_without_authguard=True`, and the process-local login override is gone because the store is read on each call. In Go, `SetLoginRequired` now clears the two-second login cache instead of writing its own value, so a store that discards writes cannot leave a process with a local setting. Behaviour change: Python consumers that run without AuthGuard must pass `local_profile_without_authguard=True`, or their guarded routes return 500. Files: `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`, `backend/auth/proxy.go`, `backend/auth/proxy_test.go`.
|
||||||
|
|
||||||
### S-006 · The documented core-config push guard fails open when the secret is unset, and the pushed AuthGuard URL is not validated · **Medium**
|
### S-006 · The documented core-config push guard fails open when the secret is unset, and the pushed AuthGuard URL is not validated · **Medium** · Fixed
|
||||||
- **Location:** `packages/node-backend/README.md:50` (documented handler), `packages/node-backend/src/coreconfig.js:121` (same check, inside a JSDoc example), `packages/node-backend/src/coreconfig.js:67` (URL normalised, with no scheme or host check), `packages/python-backend/README.md:104` and `packages/python-backend/src/shared_backend/coreconfig.py:111` (same comparison in the Python example), `backend/coreconfig/coreconfig.go:182` (fails closed on an empty secret but compares with `!=`; per review), `backend/auth/proxy.go:819` (`r.Header.Get("X-Internal-Auth") != secret`)
|
- **Location:** `packages/node-backend/README.md:50` (documented handler), `packages/node-backend/src/coreconfig.js:121` (same check, inside a JSDoc example), `packages/node-backend/src/coreconfig.js:67` (URL normalised, with no scheme or host check), `packages/python-backend/README.md:104` and `packages/python-backend/src/shared_backend/coreconfig.py:111` (same comparison in the Python example), `backend/coreconfig/coreconfig.go:182` (fails closed on an empty secret but compares with `!=`; per review), `backend/auth/proxy.go:819` (`r.Header.Get("X-Internal-Auth") != secret`)
|
||||||
- **Description:** The documented guard is `req.get('X-Internal-Auth') !== process.env.SECRET` (and the Python equivalent). If `SECRET` is unset and the header is absent, both sides are `undefined`, so the check passes. The examples do not reject an empty secret, and every comparison is non-constant-time. The store accepts any `authGuardUrl` and forwards it to `AuthClient.setBaseUrl`, so an accepted push can point session validation at a server the attacker controls. The Python internal route at `authproxy.py:576-581` does reject an empty secret, which is the correct pattern.
|
- **Description:** The documented guard is `req.get('X-Internal-Auth') !== process.env.SECRET` (and the Python equivalent). If `SECRET` is unset and the header is absent, both sides are `undefined`, so the check passes. The examples do not reject an empty secret, and every comparison is non-constant-time. The store accepts any `authGuardUrl` and forwards it to `AuthClient.setBaseUrl`, so an accepted push can point session validation at a server the attacker controls. The Python internal route at `authproxy.py:576-581` does reject an empty secret, which is the correct pattern.
|
||||||
- **Impact:** A consumer that copies the example gets an authentication bypass through a push that controls the AuthGuard target. The timing difference is small in practice but is avoidable.
|
- **Impact:** A consumer that copies the example gets an authentication bypass through a push that controls the AuthGuard target. The timing difference is small in practice but is avoidable.
|
||||||
- **Recommendation:** Reject an empty configured secret in every handler. Compare with `crypto.timingSafeEqual` or `hmac.compare_digest`. Validate the scheme and host in the store before accepting a URL. Correct the examples.
|
- **Recommendation:** Reject an empty configured secret in every handler. Compare with `crypto.timingSafeEqual` or `hmac.compare_digest`. Validate the scheme and host in the store before accepting a URL. Correct the examples.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the Go handler, the Node and Python guards and the stores now reject an empty secret and compare in constant time (`subtle.ConstantTimeCompare`, `crypto.timingSafeEqual`, `hmac.compare_digest`). The Node and Python stores accept only http or https URLs with a host, the Go handler checks the same before storing, and the README examples call `internalSecretMatches` and `internal_secret_matches`. Files: `backend/coreconfig/coreconfig.go`, `backend/coreconfig/coreconfig_test.go`, `backend/auth/proxy.go`, `packages/node-backend/src/coreconfig.js`, `packages/node-backend/test/coreconfig.test.js`, `packages/python-backend/src/shared_backend/coreconfig.py`, `packages/python-backend/tests/test_coreconfig.py`, `packages/node-backend/README.md`, `packages/python-backend/README.md`.
|
||||||
|
|
||||||
### S-007 · Go proxy routes that change state accept any Content-Type and Origin · **Medium**
|
### S-007 · Go proxy routes that change state accept any Content-Type and Origin · **Medium** · Fixed
|
||||||
- **Location:** `backend/auth/proxy.go:1509` (`decodeProxyJSON` does not check `Content-Type`, `Origin` or `Sec-Fetch-Site`), state-changing handlers including `UpdateAccessSettings` (`proxy.go:781`), `UpdateMe` (`proxy.go:664`), managed-user create, update and delete (around `proxy.go:920`, `:951`, `:994`), `TOTPDisable` (`proxy.go:1239`) and `Logout` (`proxy.go:1144`)
|
- **Location:** `backend/auth/proxy.go:1509` (`decodeProxyJSON` does not check `Content-Type`, `Origin` or `Sec-Fetch-Site`), state-changing handlers including `UpdateAccessSettings` (`proxy.go:781`), `UpdateMe` (`proxy.go:664`), managed-user create, update and delete (around `proxy.go:920`, `:951`, `:994`), `TOTPDisable` (`proxy.go:1239`) and `Logout` (`proxy.go:1144`)
|
||||||
- **Description:** There is no CSRF protection in the proxy. A cross-site form submission with a `text/plain` body is decoded just like a JSON request, so protection rests entirely on the `SameSite` attribute of the session cookie. That attribute is set by AuthGuard and forwarded here. `backend/authclient/client.go:324` notes that the cookie can be domain-scoped (`AUTH_COOKIE_DOMAIN`) for cross-project SSO, which makes sibling subdomains same-site.
|
- **Description:** There is no CSRF protection in the proxy. A cross-site form submission with a `text/plain` body is decoded just like a JSON request, so protection rests entirely on the `SameSite` attribute of the session cookie. That attribute is set by AuthGuard and forwarded here. `backend/authclient/client.go:324` notes that the cookie can be domain-scoped (`AUTH_COOKIE_DOMAIN`) for cross-project SSO, which makes sibling subdomains same-site.
|
||||||
- **Impact:** If a session cookie is domain-scoped and a sibling application is compromised or hostile, it can forge admin actions against this proxy. Needs verification of AuthGuard's cookie attributes.
|
- **Impact:** If a session cookie is domain-scoped and a sibling application is compromised or hostile, it can forge admin actions against this proxy. Needs verification of AuthGuard's cookie attributes.
|
||||||
- **Recommendation:** On non-GET routes, require `Content-Type: application/json` and check `Origin` or `Sec-Fetch-Site` against an allowlist, or require a custom header that cross-site forms cannot set. Confirm AuthGuard's `SameSite` setting.
|
- **Recommendation:** On non-GET routes, require `Content-Type: application/json` and check `Origin` or `Sec-Fetch-Site` against an allowlist, or require a custom header that cross-site forms cannot set. Confirm AuthGuard's `SameSite` setting.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `decodeProxyJSON` refuses any body that is not `application/json` and any request marked `Sec-Fetch-Site: cross-site`, and the body-less state-changing handlers (logout, TOTP initiate, managed user delete) refuse cross-site requests with a 403. Origin is still not checked, and requests from browsers that omit `Sec-Fetch-Site` are accepted, so SameSite remains a second layer. Behaviour change: clients that send a non-JSON body, or a cross-site request, to these routes are now refused. Files: `backend/auth/proxy.go`, `backend/auth/proxy_test.go`.
|
||||||
|
|
||||||
### S-008 · Signup and first-run setup are not gated on the login setting, and the oldest user is re-promoted to superadmin on restart · **Medium**
|
### S-008 · Signup and first-run setup are not gated on the login setting, and the oldest user is re-promoted to superadmin on restart · **Medium** · Fixed
|
||||||
- **Location:** `backend/auth/proxy.go:1014` (`Signup` checks only whether the service is enabled; no login-required check before forwarding), `backend/auth/proxy.go:724` (`AdminNeeded`), `backend/auth/store.go:92-94` (`EnsureSchema` promotes the oldest user when no superadmin exists), `backend/auth/store.go:237` (first account becomes superadmin)
|
- **Location:** `backend/auth/proxy.go:1014` (`Signup` checks only whether the service is enabled; no login-required check before forwarding), `backend/auth/proxy.go:724` (`AdminNeeded`), `backend/auth/store.go:92-94` (`EnsureSchema` promotes the oldest user when no superadmin exists), `backend/auth/store.go:237` (first account becomes superadmin)
|
||||||
- **Description:** When login is not required, `AdminNeeded` reports no setup is needed, but `Signup` does not check the setting. On a fresh AuthGuard the first caller to sign up becomes superadmin, and there is no bootstrap secret. Separately, at each schema initialisation, if no superadmin exists, the oldest user is promoted. Deleting or demoting the superadmin and then restarting elevates whoever is oldest, possibly an ordinary user.
|
- **Description:** When login is not required, `AdminNeeded` reports no setup is needed, but `Signup` does not check the setting. On a fresh AuthGuard the first caller to sign up becomes superadmin, and there is no bootstrap secret. Separately, at each schema initialisation, if no superadmin exists, the oldest user is promoted. Deleting or demoting the superadmin and then restarting elevates whoever is oldest, possibly an ordinary user.
|
||||||
- **Impact:** On a service with login disabled and no accounts, an anonymous visitor could register as superadmin of the shared AuthGuard (needs verification of AuthGuard's behaviour). Restarts can silently escalate privileges.
|
- **Impact:** On a service with login disabled and no accounts, an anonymous visitor could register as superadmin of the shared AuthGuard (needs verification of AuthGuard's behaviour). Restarts can silently escalate privileges.
|
||||||
- **Recommendation:** Reject `Signup` when login is not required, or require a one-time setup token. Run the promotion only when the table is created, and otherwise require an explicit administrator action.
|
- **Recommendation:** Reject `Signup` when login is not required, or require a one-time setup token. Run the promotion only when the table is created, and otherwise require an explicit administrator action.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `Signup` answers 409 while login is not required, so an anonymous caller cannot become superadmin on a service with login off. The oldest-user promotion in `EnsureSchema` now runs only in the migration that adds the `role` column, so a restart no longer promotes someone when no superadmin exists. Residual: with login required and an empty AuthGuard the first signup still becomes superadmin, as designed; a one-time setup token would be a product decision. Files: `backend/auth/proxy.go`, `backend/auth/store.go`, `backend/auth/proxy_test.go`.
|
||||||
|
|
||||||
### S-009 · Login and TOTP endpoints have no attempt limiting, and the client's IP address is not forwarded · **Medium**
|
### S-009 · Login and TOTP endpoints have no attempt limiting, and the client's IP address is not forwarded · **Medium** · Fixed
|
||||||
- **Location:** `backend/auth/proxy.go:1093` (`Login`), `backend/auth/proxy.go:1210` (`TOTPVerify`), `backend/auth/proxy.go:1239` (`TOTPDisable`), `backend/authclient/client.go:426-459` (outbound headers are bearer token, content type and project key only), `packages/python-backend/src/shared_backend/authclient.py` and `packages/node-backend/src/authclient.js` (same pattern; per review)
|
- **Location:** `backend/auth/proxy.go:1093` (`Login`), `backend/auth/proxy.go:1210` (`TOTPVerify`), `backend/auth/proxy.go:1239` (`TOTPDisable`), `backend/authclient/client.go:426-459` (outbound headers are bearer token, content type and project key only), `packages/python-backend/src/shared_backend/authclient.py` and `packages/node-backend/src/authclient.js` (same pattern; per review)
|
||||||
- **Description:** The proxy adds no throttling or lockout to password or six-digit TOTP attempts. The AuthGuard clients do not send the end user's IP address, so any per-IP limit that AuthGuard applies sees the proxy's address for every user.
|
- **Description:** The proxy adds no throttling or lockout to password or six-digit TOTP attempts. The AuthGuard clients do not send the end user's IP address, so any per-IP limit that AuthGuard applies sees the proxy's address for every user.
|
||||||
- **Impact:** Password and TOTP guessing is limited only by AuthGuard, whose behaviour is not in this repository. A per-IP limit at AuthGuard either does nothing or locks out all users together. Needs verification of AuthGuard's limiter.
|
- **Impact:** Password and TOTP guessing is limited only by AuthGuard, whose behaviour is not in this repository. A per-IP limit at AuthGuard either does nothing or locks out all users together. Needs verification of AuthGuard's limiter.
|
||||||
- **Recommendation:** Add a per-identifier and per-client-IP limiter in the proxy. Forward the client IP over a trusted channel using trusted-proxy-aware extraction, and confirm how AuthGuard limits attempts.
|
- **Recommendation:** Add a per-identifier and per-client-IP limiter in the proxy. Forward the client IP over a trusted channel using trusted-proxy-aware extraction, and confirm how AuthGuard limits attempts.
|
||||||
|
- **Status:** Fixed 2026-10-19 — login has a per-account limit (10 per 15 minutes) and a per-client-address limit (200), and TOTP verify and disable share a per-user limit (5), all held in process memory: `backend/auth/ratelimit.go` for the Go proxy and, new in this pass, `shared_backend/ratelimit.py` and `authproxy.build_auth_router` for the Python router (same numbers, `429` beyond them). The client address honours `X-Forwarded-For` only from peers listed in `TRUSTED_PROXIES` (decision 5): `backend/auth/clientip.go`, and the new `shared_backend/clientip.py` (the router reads the variable, or a `trusted_proxies` argument; an invalid list raises `ValueError` at startup). The verified address is now forwarded to AuthGuard as `X-Forwarded-For` on login, signup/register and TOTP verify/disable: Go `authclient.WithClientIP` (set by `auth.Service`), Python `authclient.forwarded_client_ip` (set by the router), Node an optional `{ clientIp }` on `register`, `login`, `totpVerify`, `totpDisable` and the reset calls. Only IP-address values are sent, never a raw request header. AuthGuard's own limiters (`Central/AuthGuard/internal/httpapi`, read for this pass) key on its `clientIP`, which reads the header only from peers inside AuthGuard's own `TRUSTED_PROXIES`, so the forwarding takes effect once an operator lists the consuming service's address there and is ignored until then. Residual: counters are per replica, so N replicas of one service allow N times the attempts (AuthGuard's central limiter still applies). Behaviour change: Python services now answer 429 on login and TOTP routes after the limits, and `build_auth_router` gains the `trusted_proxies` argument and reads `TRUSTED_PROXIES`. Files: `backend/auth/ratelimit.go`, `backend/auth/proxy.go`, `backend/auth/clientip.go`, `backend/authclient/client.go`, `backend/auth/proxy_handlers_test.go`, `backend/authclient/client_test.go`, `packages/python-backend/src/shared_backend/{authproxy,authclient,clientip,ratelimit}.py`, `packages/python-backend/tests/{test_authproxy,test_authclient,test_attempt_limits}.py`, `packages/node-backend/src/authclient.js`, `packages/node-backend/test/authclient.test.js`.
|
||||||
|
|
||||||
### S-010 · Self-service profile update changes the password without re-authentication · **Medium**
|
### S-010 · Self-service profile update changes the password without re-authentication · **Medium** · Open
|
||||||
- **Location:** `backend/auth/proxy.go:664-712` (`UpdateMe` accepts `password` at `:700-709` and forwards it with only the session cookie)
|
- **Location:** `backend/auth/proxy.go:664-712` (`UpdateMe` accepts `password` at `:700-709` and forwards it with only the session cookie)
|
||||||
- **Description:** A new password is validated and forwarded to AuthGuard without asking for the current password or a TOTP code.
|
- **Description:** A new password is validated and forwarded to AuthGuard without asking for the current password or a TOTP code.
|
||||||
- **Impact:** A stolen or fixated session cookie becomes permanent account takeover, because the attacker can set a new password. Needs verification of whether AuthGuard revokes other sessions on password change.
|
- **Impact:** A stolen or fixated session cookie becomes permanent account takeover, because the attacker can set a new password. Needs verification of whether AuthGuard revokes other sessions on password change.
|
||||||
- **Recommendation:** Require the current password (and a TOTP code when enabled) for password or email changes, and revoke other sessions when the password changes.
|
- **Recommendation:** Require the current password (and a TOTP code when enabled) for password or email changes, and revoke other sessions when the password changes.
|
||||||
|
- **Status:** 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**
|
### 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:** 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**
|
### S-012 · The Java client parses the authentication decision with unanchored regular expressions · **Medium** · Fixed
|
||||||
- **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review)
|
- **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review)
|
||||||
- **Description:** The values are extracted from the raw response body with `Matcher.find()`, which returns the first match anywhere in the text, including inside nested objects. The class already depends on Jackson (`packages/java-backend/pom.xml`), so a real parser is available.
|
- **Description:** The values are extracted from the raw response body with `Matcher.find()`, which returns the first match anywhere in the text, including inside nested objects. The class already depends on Jackson (`packages/java-backend/pom.xml`), so a real parser is available.
|
||||||
- **Impact:** A change to AuthGuard's response shape, or a nested field with the same name, could make the client accept a session for the wrong user or role.
|
- **Impact:** A change to AuthGuard's response shape, or a nested field with the same name, could make the client accept a session for the wrong user or role.
|
||||||
- **Recommendation:** Parse the response with Jackson and read top-level fields only. Add tests with nested and reordered fields.
|
- **Recommendation:** Parse the response with Jackson and read top-level fields only. Add tests with nested and reordered fields.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `AuthClient.validate` parses the AuthGuard response with Jackson and reads only the top-level `valid`, `user_id`, `username` and `role` fields, so nested fields with the same names are ignored, and tests cover nested and reordered fields. Not compiled or run: no JDK or Maven is available here, so this was checked by reading only. Files: `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java`, `packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java`.
|
||||||
|
|
||||||
### S-013 · Password hashing is below the intended settings in two runtimes · **Medium**
|
### S-013 · Password hashing is below the intended settings in two runtimes · **Medium** · Fixed
|
||||||
- **Location:** `packages/node-backend/src/auth.js:3` and `:56` (100,000 PBKDF2-SHA256 iterations, with an `iterations` option), `packages/node-backend/src/auth.js:61` and `:69-72` (verification always uses the constant, and the stored `salt:hash` format records no parameters), `backend/auth/proxy.go:1344` and `:1417` (`bcrypt.DefaultCost`, which is 10, for platform users) vs `backend/auth/password.go:7` (`BcryptCost = 12`, described as the one policy), `backend/auth/proxy.go:1460` (accepts up to 1024 runes, but bcrypt uses only the first 72 bytes)
|
- **Location:** `packages/node-backend/src/auth.js:3` and `:56` (100,000 PBKDF2-SHA256 iterations, with an `iterations` option), `packages/node-backend/src/auth.js:61` and `:69-72` (verification always uses the constant, and the stored `salt:hash` format records no parameters), `backend/auth/proxy.go:1344` and `:1417` (`bcrypt.DefaultCost`, which is 10, for platform users) vs `backend/auth/password.go:7` (`BcryptCost = 12`, described as the one policy), `backend/auth/proxy.go:1460` (accepts up to 1024 runes, but bcrypt uses only the first 72 bytes)
|
||||||
- **Description:** The Node PBKDF2 count is fixed at 100,000 iterations. OWASP's current guidance for PBKDF2-HMAC-SHA256 is 600,000 (confirm against the current cheat sheet). A caller passing a different `iterations` value produces hashes that can never verify, and because the format stores no parameters the cost cannot be raised without a migration. Go's platform-user path hashes at cost 10 rather than the package's stated cost of 12. Bcrypt ignores bytes beyond 72, so long passwords are silently truncated, which the current validation does not prevent.
|
- **Description:** The Node PBKDF2 count is fixed at 100,000 iterations. OWASP's current guidance for PBKDF2-HMAC-SHA256 is 600,000 (confirm against the current cheat sheet). A caller passing a different `iterations` value produces hashes that can never verify, and because the format stores no parameters the cost cannot be raised without a migration. Go's platform-user path hashes at cost 10 rather than the package's stated cost of 12. Bcrypt ignores bytes beyond 72, so long passwords are silently truncated, which the current validation does not prevent.
|
||||||
- **Impact:** Stored hashes are cheaper to crack than the package intends, and the cost cannot be upgraded.
|
- **Impact:** Stored hashes are cheaper to crack than the package intends, and the cost cannot be upgraded.
|
||||||
- **Recommendation:** Store the algorithm and parameters with each hash and rehash on login. Raise the PBKDF2 count, or move to scrypt or argon2id. Call `HashPassword` everywhere in Go, and reject or pre-hash passwords longer than 72 bytes with a clear message.
|
- **Recommendation:** Store the algorithm and parameters with each hash and rehash on login. Raise the PBKDF2 count, or move to scrypt or argon2id. Call `HashPassword` everywhere in Go, and reject or pre-hash passwords longer than 72 bytes with a clear message.
|
||||||
|
- **Status:** Fixed 2026-10-19 — every hash now carries a scheme prefix, and verification dispatches on it. Node writes `pbkdf2-sha256$<iterations>$<salt>$<hash>` at 600,000 iterations. Go and Python write `bcrypt$` followed by an unchanged bcrypt string at cost 12 (`BcryptCost`). Legacy Node `salt:hex` hashes (100,000 iterations) and unprefixed bcrypt hashes still verify, and any other format fails closed. Rehash on login: `verifyAndUpgradePasswordAsync` (Node), `verify_and_upgrade_password_async` (Python) and `VerifyAndUpgradePassword` (Go) return a current-scheme hash after a matching password, for the caller to store. Go platform-user writes now use `HashPassword`. Caveats: no login route in this repository checks local hashes (AuthGuard checks logins), so the rewrite happens only in a consumer that calls the helper; Node still cannot verify bcrypt. Behaviour change: Python and Go code from before this change cannot verify the new `bcrypt$` hashes, so services that share a database must move together. The 72-byte limit is enforced in Go (`validateProxyPassword` refuses more than 72 bytes, and bcrypt itself refuses them) and, since this pass, in Python (`MAX_PASSWORD_BYTES`: `hash_password` raises `ValueError` and the router's `_validate_password` answers 400, whatever bcrypt version is installed); Node's PBKDF2 has no such limit. Files: `backend/auth/password.go`, `backend/auth/password_test.go`, `backend/auth/store_test.go`, `backend/auth/proxy.go`, `packages/node-backend/src/auth.js`, `packages/node-backend/src/index.js`, `packages/node-backend/test/auth.test.js`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/src/shared_backend/__init__.py`, `packages/python-backend/tests/test_core.py`, `packages/python-backend/tests/test_store.py`.
|
||||||
|
|
||||||
### S-014 · Websocket origin verification is disabled when the allowed origin is `*` · **Medium**
|
### S-014 · Websocket origin verification is disabled when the allowed origin is `*` · **Medium** · Fixed
|
||||||
- **Location:** `backend/syncsocket/syncsocket.go:267-270` (`websocketAcceptOptions` sets `InsecureSkipVerify = true` when `allowedOrigin == "*"`)
|
- **Location:** `backend/syncsocket/syncsocket.go:267-270` (`websocketAcceptOptions` sets `InsecureSkipVerify = true` when `allowedOrigin == "*"`)
|
||||||
- **Description:** In `coder/websocket`, that option disables the Origin check. It is not TLS verification, despite the name. With the wildcard setting, any web page can open a sync socket from a visitor's browser, which combines with S-003 to let cross-site pages act as peers.
|
- **Description:** In `coder/websocket`, that option disables the Origin check. It is not TLS verification, despite the name. With the wildcard setting, any web page can open a sync socket from a visitor's browser, which combines with S-003 to let cross-site pages act as peers.
|
||||||
- **Impact:** A page on any origin can connect to a LAN-hosted sync hub, read session state and send control messages if identity is not enforced.
|
- **Impact:** A page on any origin can connect to a LAN-hosted sync hub, read session state and send control messages if identity is not enforced.
|
||||||
- **Recommendation:** Remove the wildcard escape hatch, or require an explicit origin list. Never map `"*"` to `InsecureSkipVerify`.
|
- **Recommendation:** Remove the wildcard escape hatch, or require an explicit origin list. Never map `"*"` to `InsecureSkipVerify`.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `websocketAcceptOptions` no longer maps `*` to `InsecureSkipVerify`; origin verification is always on, and `*` adds no extra origin. Behaviour change: a deployment that relied on `CORS_ORIGIN=*` to accept sockets from any page must now list each origin explicitly. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`.
|
||||||
|
|
||||||
### S-015 · Peer IP addresses and user agents are broadcast to all session members, and X-Forwarded-For is trusted unconditionally · **Medium**
|
### S-015 · Peer IP addresses and user agents are broadcast to all session members, and X-Forwarded-For is trusted unconditionally · **Medium** · Fixed
|
||||||
- **Location:** `backend/syncsocket/syncsocket.go:301` (first `X-Forwarded-For` value used with no trusted-proxy check), `backend/syncsocket/syncsocket.go:146-150` (IP address and user agent sent to every peer in the session)
|
- **Location:** `backend/syncsocket/syncsocket.go:301` (first `X-Forwarded-For` value used with no trusted-proxy check), `backend/syncsocket/syncsocket.go:146-150` (IP address and user agent sent to every peer in the session)
|
||||||
- **Description:** The client's address is taken from the first `X-Forwarded-For` value whenever that header is present, and it is shared with every session member along with the user agent.
|
- **Description:** The client's address is taken from the first `X-Forwarded-For` value whenever that header is present, and it is shared with every session member along with the user agent.
|
||||||
- **Impact:** Any session member can see the addresses and user agents of other members, and a client can spoof the address that others see.
|
- **Impact:** Any session member can see the addresses and user agents of other members, and a client can spoof the address that others see.
|
||||||
- **Recommendation:** Honour `X-Forwarded-For` only from configured trusted proxies, and remove IP address and user agent from broadcast payloads.
|
- **Recommendation:** Honour `X-Forwarded-For` only from configured trusted proxies, and remove IP address and user agent from broadcast payloads.
|
||||||
|
- **Status:** Fixed 2026-10-19 — the sync hub no longer reads `X-Forwarded-For`, and it no longer sends a peer's IP address or user agent in the client list. The Go proxy's client address honours `X-Forwarded-For` only when the TCP peer is inside `TRUSTED_PROXIES` (decision 5), and otherwise uses the TCP peer. Behaviour change: clients that displayed the `ipAddress` or `userAgent` of other peers will no longer receive those fields. A service behind a reverse proxy gets per-client login limits only once it sets `TRUSTED_PROXIES`; until then its behaviour is unchanged. Files: `backend/syncsocket/syncsocket.go`, `backend/syncsocket/syncsocket_test.go`, `backend/auth/clientip.go`, `backend/auth/clientip_test.go`, `backend/auth/proxy.go`.
|
||||||
|
|
||||||
### S-016 · Store primitives allow identity confusion and silently disable TOTP · **Medium**
|
### S-016 · Store primitives allow identity confusion and silently disable TOTP · **Medium** · Fixed
|
||||||
- **Location:** `backend/auth/store.go:261` (`WHERE username = $1 OR lower(email) = lower($1)`, with no ordering), `backend/auth/store.go:72` (username is unique only case-sensitively), `backend/auth/store.go:184` (`SetTOTPSecret` sets `totp_enabled = false`), `backend/auth/store.go:277-285` (`UpdateCredentials` writes whatever `passwordHash` it receives, per review)
|
- **Location:** `backend/auth/store.go:261` (`WHERE username = $1 OR lower(email) = lower($1)`, with no ordering), `backend/auth/store.go:72` (username is unique only case-sensitively), `backend/auth/store.go:184` (`SetTOTPSecret` sets `totp_enabled = false`), `backend/auth/store.go:277-285` (`UpdateCredentials` writes whatever `passwordHash` it receives, per review)
|
||||||
- **Description:** The identifier lookup matches a username against any account's email, so a username can equal another account's email and make the match ambiguous. Usernames are unique only case-sensitively, so `Admin` and `admin` can both exist. `SetTOTPSecret` silently disables an enabled second factor if it is called. Credential updates accept an empty hash.
|
- **Description:** The identifier lookup matches a username against any account's email, so a username can equal another account's email and make the match ambiguous. Usernames are unique only case-sensitively, so `Admin` and `admin` can both exist. `SetTOTPSecret` silently disables an enabled second factor if it is called. Credential updates accept an empty hash.
|
||||||
- **Impact:** Ambiguous logins that can route a sign-in to the wrong account, and silent second-factor removal if a caller makes a mistake.
|
- **Impact:** Ambiguous logins that can route a sign-in to the wrong account, and silent second-factor removal if a caller makes a mistake.
|
||||||
- **Recommendation:** Add a unique index on `lower(username)`. Reject usernames containing `@`. Look up usernames and emails separately with a deterministic order. Refuse `SetTOTPSecret` while TOTP is enabled, and reject empty password hashes.
|
- **Recommendation:** Add a unique index on `lower(username)`. Reject usernames containing `@`. Look up usernames and emails separately with a deterministic order. Refuse `SetTOTPSecret` while TOTP is enabled, and reject empty password hashes.
|
||||||
|
- **Status:** Fixed 2026-10-19 — `SetTOTPSecret` refuses while TOTP is enabled (`ErrTOTPAlreadyEnabled`), credential writes refuse an empty password hash and a username containing `@`, and identifier lookup tries usernames before emails in a fixed order. New in this pass: usernames are unique ignoring case through an index on `lower(username)` (`auth_users_username_lower_idx`), created by `EnsureSchema` (Go), `AuthStore.ensureSchema` (Node) and `AuthStore.ensure_schema` (Python) only while no pair such as `Admin` and `admin` exists. Choice made without an owner decision: a database that already holds such a pair still starts, gets no index, and logs the clashing names on each start (a warning in Node and Python) until an operator renames or removes one account of each pair; no account is merged or renamed automatically. The Node and Python stores now carry the same guards as Go (empty hash, `@` in a username, no TOTP secret replacement while enabled, username-then-email lookup). Behaviour change: registering a username that differs from an existing one only by case now fails as an existing user; `setTotpSecret`/`set_totp_secret` throw (`AUTH_TOTP_ALREADY_ENABLED`, `TotpAlreadyEnabledError`) while TOTP is enabled; a credential write with an empty hash or an `@` username throws (`AUTH_EMPTY_PASSWORD_HASH`/`AUTH_INVALID_USERNAME`, `EmptyPasswordHashError`/`InvalidUsernameError`). Files: `backend/auth/store.go`, `backend/auth/store_test.go`, `backend/auth/store_integration_test.go`, `packages/node-backend/src/auth.js`, `packages/node-backend/test/authstore.test.js`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/tests/test_store.py`.
|
||||||
|
|
||||||
### S-017 · Stored paths and caller-supplied names are concatenated into CarrierNode URLs without escaping or validation · **Medium**
|
### S-017 · Stored paths and caller-supplied names are concatenated into CarrierNode URLs without escaping or validation · **Medium** · Fixed
|
||||||
- **Location:** `backend/mediacore/mediacore.go:187` and `:224` (`"/media/" + urlPath(record.FilePath)` from the database), `backend/mediacore/mediacore.go:992-997` (`urlPath` strips only leading slashes and a `media/` prefix), `backend/carriernodeclient/carriernodeclient.go:144` (path concatenated without escaping), `backend/carriernodeclient/carriernodeclient.go:673-719` (`PushThumbnail`, `DeleteThumbnail`, `PushOutput`, `PushInput`, `PushCopy` use `url.PathEscape` only, which leaves `.` and `..` unchanged), `backend/carriernodeclient/carriernodeclient.go:453-458` (a strict `thumbnailFile` check exists for thumbnails only), `backend/carriernodeclient/carriernodeclient.go:228-246` (`MountPath` escapes segments and rejects `..` correctly)
|
- **Location:** `backend/mediacore/mediacore.go:187` and `:224` (`"/media/" + urlPath(record.FilePath)` from the database), `backend/mediacore/mediacore.go:992-997` (`urlPath` strips only leading slashes and a `media/` prefix), `backend/carriernodeclient/carriernodeclient.go:144` (path concatenated without escaping), `backend/carriernodeclient/carriernodeclient.go:673-719` (`PushThumbnail`, `DeleteThumbnail`, `PushOutput`, `PushInput`, `PushCopy` use `url.PathEscape` only, which leaves `.` and `..` unchanged), `backend/carriernodeclient/carriernodeclient.go:453-458` (a strict `thumbnailFile` check exists for thumbnails only), `backend/carriernodeclient/carriernodeclient.go:228-246` (`MountPath` escapes segments and rejects `..` correctly)
|
||||||
- **Description:** A stored `file_path` containing `?`, `#` or `..` is parsed by CarrierNode as a query, a fragment, or a traversal. `SafeRelative` is applied to IDs but not to stored paths. The push and delete helpers escape `/` but not `.` or `..`, and no name validation runs for them.
|
- **Description:** A stored `file_path` containing `?`, `#` or `..` is parsed by CarrierNode as a query, a fragment, or a traversal. `SafeRelative` is applied to IDs but not to stored paths. The push and delete helpers escape `/` but not `.` or `..`, and no name validation runs for them.
|
||||||
- **Impact:** A malformed stored path or caller-supplied name can address a different upstream resource, or write or delete outside the intended root, depending on CarrierNode's own checks (not in this repository; needs verification).
|
- **Impact:** A malformed stored path or caller-supplied name can address a different upstream resource, or write or delete outside the intended root, depending on CarrierNode's own checks (not in this repository; needs verification).
|
||||||
- **Recommendation:** Apply `SafeRelative` to stored paths, escape each segment as `MountPath` does, and reject query and fragment characters. Validate names in every push and delete helper the way `thumbnailFile` does (reject `.`, `..` and path separators).
|
- **Recommendation:** Apply `SafeRelative` to stored paths, escape each segment as `MountPath` does, and reject query and fragment characters. Validate names in every push and delete helper the way `thumbnailFile` does (reject `.`, `..` and path separators).
|
||||||
|
- **Status:** Fixed 2026-10-19 — stored media paths go through `upstreamMediaPath`, which applies `SafeRelative`, refuses `?` and `#`, and escapes each segment before the CarrierNode call. The push and delete helpers for thumbnails, outputs, inputs and copies reject `.`, `..` and path separators through `validName`. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/paths_test.go`, `backend/carriernodeclient/carriernodeclient.go`, `backend/carriernodeclient/thumbnails_test.go`.
|
||||||
|
|
||||||
### S-018 · The role vocabulary is defined three ways, and role assignments are not checked locally · **Low**
|
### S-018 · The role vocabulary is defined three ways, and role assignments are not checked locally · **Low**
|
||||||
- **Location:** `backend/auth/proxy.go:629-634` (`IsAdmin` treats `moderator` as admin), `backend/auth/roles.go:13-32` (`NormalizeRole`, `CanManageUsers`, `CanAssignRole`; `CanAssignRole` is not called from the handlers), `backend/auth/proxy.go:935-938` and `:965-971` (client-supplied role forwarded to AuthGuard)
|
- **Location:** `backend/auth/proxy.go:629-634` (`IsAdmin` treats `moderator` as admin), `backend/auth/roles.go:13-32` (`NormalizeRole`, `CanManageUsers`, `CanAssignRole`; `CanAssignRole` is not called from the handlers), `backend/auth/proxy.go:935-938` and `:965-971` (client-supplied role forwarded to AuthGuard)
|
||||||
@@ -148,16 +166,17 @@ The most serious issue is a Python router route that lets an anonymous caller sw
|
|||||||
- **Impact:** Supply-chain exposure from tag changes, credential exposure to other processes on a shared runner, and a higher chance of future secret commits.
|
- **Impact:** Supply-chain exposure from tag changes, credential exposure to other processes on a shared runner, and a higher chance of future secret commits.
|
||||||
- **Recommendation:** Pin actions to commit SHAs. Pass registry credentials through a netrc or header file rather than argv. Add `.env*`, `*.pem`, `*.key` and `.npmrc` to `.gitignore`. Confirm that the historical credential is not live, and rotate it if it is.
|
- **Recommendation:** Pin actions to commit SHAs. Pass registry credentials through a netrc or header file rather than argv. Add `.env*`, `*.pem`, `*.key` and `.npmrc` to `.gitignore`. Confirm that the historical credential is not live, and rotate it if it is.
|
||||||
|
|
||||||
### S-022 · Media stream and thumbnail routes are unauthenticated, and upstream content types reach the app origin unchecked · **Low**
|
### S-022 · Media stream and thumbnail routes are unauthenticated, and upstream content types reach the app origin unchecked · **Low** · Open
|
||||||
- **Location:** `backend/mediacore/mediacore.go:95-97` (`/media/stream` and `/media/thumb` registered without an auth wrapper, unlike the other media routes), `backend/carriernodeclient/carriernodeclient.go:202-206` (upstream `Content-Type` and `Content-Disposition` copied, with no `X-Content-Type-Options` or CSP), `backend/mediacore/mediacore.go:957-960` (`ServeFile` maps extensions such as `.html` and `.svg` to active types)
|
- **Location:** `backend/mediacore/mediacore.go:95-97` (`/media/stream` and `/media/thumb` registered without an auth wrapper, unlike the other media routes), `backend/carriernodeclient/carriernodeclient.go:202-206` (upstream `Content-Type` and `Content-Disposition` copied, with no `X-Content-Type-Options` or CSP), `backend/mediacore/mediacore.go:957-960` (`ServeFile` maps extensions such as `.html` and `.svg` to active types)
|
||||||
- **Description:** Anyone who knows a media key can download the file, and the list endpoints return those keys. Proxied responses keep the upstream content type without `nosniff` or a restrictive CSP, so a file stored with an HTML or SVG type would render on the application origin. This module has no upload handler, so whether such files can exist depends on CarrierNode and its writers (needs verification).
|
- **Description:** Anyone who knows a media key can download the file, and the list endpoints return those keys. Proxied responses keep the upstream content type without `nosniff` or a restrictive CSP, so a file stored with an HTML or SVG type would render on the application origin. This module has no upload handler, so whether such files can exist depends on CarrierNode and its writers (needs verification).
|
||||||
- **Impact:** Public access to media if the library is meant to be private, and stored XSS if active content can be placed under a media path.
|
- **Impact:** Public access to media if the library is meant to be private, and stored XSS if active content can be placed under a media path.
|
||||||
- **Recommendation:** Add `Optional` or `Require` to these routes unless public access is intended, and document the choice. Set `X-Content-Type-Options: nosniff` and a restrictive CSP on proxied and served media, and force attachment or an allowlisted type for non-media extensions. Also check `backend/mediacore/mediacore.go:723`, which returns the full `*sharedauth.User` struct from the request context; whether that exposes secrets depends on its JSON tags in `backend/auth` (not reviewed).
|
- **Recommendation:** Add `Optional` or `Require` to these routes unless public access is intended, and document the choice. Set `X-Content-Type-Options: nosniff` and a restrictive CSP on proxied and served media, and force attachment or an allowlisted type for non-media extensions. Also check `backend/mediacore/mediacore.go:723`, which returns the full `*sharedauth.User` struct from the request context; whether that exposes secrets depends on its JSON tags in `backend/auth` (not reviewed).
|
||||||
|
- **Status:** Open 2026-10-19 — the access part is fixed: `/media/stream` (GET and HEAD) and `/media/thumb` now sit behind `RequireIfLoginRequired`, so anonymous requests get 401 while login is required and are served while it is off (applied from the vendored ContentScanner change). Hidden media (`active = FALSE`) returns 404 to non-moderators on the stream, thumb and original-image lookups, and a database error in that check counts as hidden (ported from the ModerationHub change); the caller rule has a unit test, the SQL filter does not, because the test suite has no database. Other media routes (state, tags, playlists) are not covered by this rule. Files: `backend/mediacore/mediacore.go`, `backend/mediacore/mediacore_test.go`. Still open: the `X-Content-Type-Options: nosniff` and restrictive CSP on proxied and served media (`backend/carriernodeclient/carriernodeclient.go`), the active-type mapping in `ServeFile` (`backend/mediacore/mediacore.go`, `.html` and `.svg`), and the `*sharedauth.User` JSON-tag question. Those need a header and content-type change in CarrierNode and the media server, and a decision on whether active types are allowed under media paths.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- **Positive checks:** No live credentials were found in the current tracked files. The only credential-shaped matches are identifiers (fields named `password`, `secret` or `token`), environment-variable references in `.gitea/workflows/publish-python.yml`, and test fixtures: `packages/node-backend/test/auth.test.js:37` uses the public RFC 6238 test secret, and `packages/python-backend/tests/test_core.py:38` and `backend/coreconfig/coreconfig_test.go:38,132-133` use short placeholder values. In git history, about twenty commits matched credential-shaped patterns; all were code identifiers or test fixtures, except the example file described in S-021. Values were masked during the review and are not reproduced here.
|
- **Positive checks:** No live credentials were found in the current tracked files. The only credential-shaped matches are identifiers (fields named `password`, `secret` or `token`), environment-variable references in `.gitea/workflows/publish-python.yml`, and test fixtures: `packages/node-backend/test/auth.test.js:37` uses the public RFC 6238 test secret, and `packages/python-backend/tests/test_core.py:38` and `backend/coreconfig/coreconfig_test.go:38,132-133` use short placeholder values. In git history, about twenty commits matched credential-shaped patterns; all were code identifiers or test fixtures, except the example file described in S-021. Values were masked during the review and are not reproduced here.
|
||||||
- **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`.
|
||||||
+3
-3
@@ -5,12 +5,12 @@ services, not application-specific SQL or HTTP handlers.
|
|||||||
|
|
||||||
- `config` — environment string, required value, boolean, integer, and duration helpers.
|
- `config` — environment string, required value, boolean, integer, and duration helpers.
|
||||||
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
|
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
|
||||||
- `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence.
|
- `auth` — versioned bcrypt password hashes (`HashPassword` writes a `bcrypt$` prefix; `VerifyAndUpgradePassword` rewrites older hashes on login), trusted-proxy client addresses (`ParseTrustedProxies` reads `TRUSTED_PROXIES`, a comma-separated CIDR list; `X-Forwarded-For` is honoured only from those peers), secure token generation/hashing, account/session schema (usernames are unique ignoring case once no clashing pair exists), account/session persistence, and attempt limits on the login and TOTP routes (per account and per client address, held in process memory).
|
||||||
- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database.
|
- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database. `WithClientIP(ctx, ip)` makes the credential calls send the end user's address as `X-Forwarded-For`; AuthServer reads it only from peers in its own `TRUSTED_PROXIES`.
|
||||||
- `migrate` — embedded filesystem adapter for Goose migrations.
|
- `migrate` — embedded filesystem adapter for Goose migrations.
|
||||||
- `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package.
|
- `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package.
|
||||||
|
|
||||||
Run `go test ./...` and `go vet ./...` from this directory. The module path is
|
Run `go test ./...` and `go vet ./...` from this directory. Tests that need PostgreSQL skip themselves unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` (platform users, 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.
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ParseTrustedProxies parses the TRUSTED_PROXIES setting: a comma-separated
|
||||||
|
// list of CIDR ranges or bare IP addresses. Only a request whose TCP peer is
|
||||||
|
// inside one of these ranges may have its X-Forwarded-For header honoured. An
|
||||||
|
// empty value trusts no proxy.
|
||||||
|
func ParseTrustedProxies(value string) ([]*net.IPNet, error) {
|
||||||
|
var networks []*net.IPNet
|
||||||
|
for _, entry := range strings.Split(value, ",") {
|
||||||
|
entry = strings.TrimSpace(entry)
|
||||||
|
if entry == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !strings.Contains(entry, "/") {
|
||||||
|
ip := net.ParseIP(entry)
|
||||||
|
if ip == nil {
|
||||||
|
return nil, fmt.Errorf("trusted proxy %q is neither an IP address nor a CIDR range", entry)
|
||||||
|
}
|
||||||
|
bits := 8 * net.IPv6len
|
||||||
|
if ip.To4() != nil {
|
||||||
|
bits = 8 * net.IPv4len
|
||||||
|
}
|
||||||
|
entry = fmt.Sprintf("%s/%d", ip.String(), bits)
|
||||||
|
}
|
||||||
|
_, network, err := net.ParseCIDR(entry)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("trusted proxy %q is not a valid CIDR range: %w", entry, err)
|
||||||
|
}
|
||||||
|
networks = append(networks, network)
|
||||||
|
}
|
||||||
|
return networks, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// clientAddress returns the address a login attempt is counted against. The
|
||||||
|
// TCP peer is used unless it is a trusted proxy. For a trusted peer,
|
||||||
|
// X-Forwarded-For is read from the right and trusted hops are skipped, so the
|
||||||
|
// first untrusted address is the one the proxy chain actually saw. A malformed
|
||||||
|
// entry makes the peer address the answer, so a bad header can never choose the
|
||||||
|
// key.
|
||||||
|
func (s *Service) clientAddress(r *http.Request) string {
|
||||||
|
peer := peerHost(r)
|
||||||
|
if !s.isTrustedProxy(peer) {
|
||||||
|
return peer
|
||||||
|
}
|
||||||
|
hops := forwardedHops(r.Header.Values("X-Forwarded-For"))
|
||||||
|
if len(hops) == 0 {
|
||||||
|
return peer
|
||||||
|
}
|
||||||
|
for i := len(hops) - 1; i >= 0; i-- {
|
||||||
|
ip := net.ParseIP(hops[i])
|
||||||
|
if ip == nil {
|
||||||
|
return peer
|
||||||
|
}
|
||||||
|
if !s.isTrustedProxyIP(ip) {
|
||||||
|
return ip.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Every hop is a trusted proxy, so the left-most one is closest to the client.
|
||||||
|
return net.ParseIP(hops[0]).String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// withClientIP returns the request context carrying clientAddress, so the
|
||||||
|
// credential calls to AuthGuard report the end user's address (as
|
||||||
|
// X-Forwarded-For) instead of this service's. AuthGuard honours that header
|
||||||
|
// only for peers in its own TRUSTED_PROXIES list.
|
||||||
|
func (s *Service) withClientIP(r *http.Request) context.Context {
|
||||||
|
return authclient.WithClientIP(r.Context(), s.clientAddress(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) isTrustedProxy(host string) bool {
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
return ip != nil && s.isTrustedProxyIP(ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) isTrustedProxyIP(ip net.IP) bool {
|
||||||
|
for _, network := range s.trustedProxies {
|
||||||
|
if network.Contains(ip) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// peerHost is the host part of the address the TCP connection came from.
|
||||||
|
func peerHost(r *http.Request) string {
|
||||||
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||||
|
if err != nil {
|
||||||
|
return r.RemoteAddr
|
||||||
|
}
|
||||||
|
return host
|
||||||
|
}
|
||||||
|
|
||||||
|
// forwardedHops flattens every X-Forwarded-For header line into its entries,
|
||||||
|
// left to right.
|
||||||
|
func forwardedHops(values []string) []string {
|
||||||
|
var hops []string
|
||||||
|
for _, value := range values {
|
||||||
|
for _, part := range strings.Split(value, ",") {
|
||||||
|
if part = strings.TrimSpace(part); part != "" {
|
||||||
|
hops = append(hops, part)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hops
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mustTrustedProxies(t *testing.T, value string) []*net.IPNet {
|
||||||
|
t.Helper()
|
||||||
|
networks, err := ParseTrustedProxies(value)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ParseTrustedProxies(%q) error = %v", value, err)
|
||||||
|
}
|
||||||
|
return networks
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseTrustedProxiesAcceptsCIDRsAndBareAddresses(t *testing.T) {
|
||||||
|
networks := mustTrustedProxies(t, " 10.0.0.0/8, 192.168.1.5 , ::1 ,")
|
||||||
|
if len(networks) != 3 {
|
||||||
|
t.Fatalf("networks = %d, want 3", len(networks))
|
||||||
|
}
|
||||||
|
for _, ip := range []string{"10.20.30.40", "192.168.1.5", "::1"} {
|
||||||
|
if !(&Service{trustedProxies: networks}).isTrustedProxy(ip) {
|
||||||
|
t.Errorf("%s not trusted", ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (&Service{trustedProxies: networks}).isTrustedProxy("192.168.1.6") {
|
||||||
|
t.Error("192.168.1.6 trusted, but only 192.168.1.5 was listed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseTrustedProxiesRejectsInvalidEntries(t *testing.T) {
|
||||||
|
for _, value := range []string{"10.0.0.0/33", "proxy.internal", "10.0.0.1/8/8"} {
|
||||||
|
if _, err := ParseTrustedProxies(value); err == nil {
|
||||||
|
t.Errorf("ParseTrustedProxies(%q) accepted an invalid entry", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
networks, err := ParseTrustedProxies(" ")
|
||||||
|
if err != nil || len(networks) != 0 {
|
||||||
|
t.Fatalf("empty setting = %v, %v; want no proxies and no error", networks, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func clientAddressFor(s *Service, remote string, forwarded ...string) string {
|
||||||
|
r := httptest.NewRequest(http.MethodPost, "/auth/login", nil)
|
||||||
|
r.RemoteAddr = remote
|
||||||
|
for _, value := range forwarded {
|
||||||
|
r.Header.Add("X-Forwarded-For", value)
|
||||||
|
}
|
||||||
|
return s.clientAddress(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClientAddressIgnoresForwardedForWithoutTrustedProxies(t *testing.T) {
|
||||||
|
s := &Service{}
|
||||||
|
if got := clientAddressFor(s, "203.0.113.7:4444", "198.51.100.1"); got != "203.0.113.7" {
|
||||||
|
t.Fatalf("clientAddress = %q, want the TCP peer 203.0.113.7", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClientAddressIgnoresForwardedForFromAnUnknownPeer(t *testing.T) {
|
||||||
|
s := &Service{trustedProxies: mustTrustedProxies(t, "10.0.0.0/8")}
|
||||||
|
if got := clientAddressFor(s, "203.0.113.7:4444", "198.51.100.1"); got != "203.0.113.7" {
|
||||||
|
t.Fatalf("clientAddress = %q, want the TCP peer 203.0.113.7", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClientAddressHonoursForwardedForFromATrustedPeer(t *testing.T) {
|
||||||
|
s := &Service{trustedProxies: mustTrustedProxies(t, "10.0.0.0/8, 172.16.0.0/12")}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
forwarded []string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"single client", []string{"198.51.100.9"}, "198.51.100.9"},
|
||||||
|
{"client behind a second trusted hop", []string{"198.51.100.9, 172.16.4.4"}, "198.51.100.9"},
|
||||||
|
{"spoofed left-most entry is skipped", []string{"6.6.6.6, 198.51.100.9, 172.16.4.4"}, "198.51.100.9"},
|
||||||
|
{"entries across header lines", []string{"6.6.6.6", "198.51.100.9"}, "198.51.100.9"},
|
||||||
|
{"malformed entry falls back to the peer", []string{"198.51.100.9, not-an-ip"}, "10.0.0.2"},
|
||||||
|
{"no header falls back to the peer", nil, "10.0.0.2"},
|
||||||
|
{"every hop trusted uses the left-most", []string{"10.1.1.1, 172.16.4.4"}, "10.1.1.1"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := clientAddressFor(s, "10.0.0.2:1000", tt.forwarded...); got != tt.want {
|
||||||
|
t.Fatalf("clientAddress = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// contractFile holds the fixtures the Go, Node and Python auth helpers must agree on. The Node and
|
||||||
|
// Python suites load the same file; see the "description" field in it.
|
||||||
|
const contractFile = "../../contract/auth-contract.json"
|
||||||
|
|
||||||
|
type authContract struct {
|
||||||
|
Password struct {
|
||||||
|
Plaintext string `json:"plaintext"`
|
||||||
|
WrongPassword string `json:"wrongPassword"`
|
||||||
|
Hashes []struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Hash string `json:"hash"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
WrongPassword string `json:"wrongPassword"`
|
||||||
|
Verifies map[string]bool `json:"verifies"`
|
||||||
|
NeedsUpgrade map[string]bool `json:"needsUpgrade"`
|
||||||
|
} `json:"hashes"`
|
||||||
|
TooLongToHash struct {
|
||||||
|
Bytes int `json:"bytes"`
|
||||||
|
Accepted map[string]bool `json:"accepted"`
|
||||||
|
} `json:"tooLongToHash"`
|
||||||
|
} `json:"password"`
|
||||||
|
TOTP struct {
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
Cases []struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Unix int64 `json:"unix"`
|
||||||
|
Code string `json:"code"`
|
||||||
|
Secret *string `json:"secret"`
|
||||||
|
MatchedStep *int64 `json:"matchedStep"`
|
||||||
|
Valid bool `json:"valid"`
|
||||||
|
} `json:"cases"`
|
||||||
|
} `json:"totp"`
|
||||||
|
ClientAddress struct {
|
||||||
|
InvalidTrustedProxyLists []string `json:"invalidTrustedProxyLists"`
|
||||||
|
Cases []struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Trusted string `json:"trusted"`
|
||||||
|
Peer string `json:"peer"`
|
||||||
|
Forwarded []string `json:"forwarded"`
|
||||||
|
Want string `json:"want"`
|
||||||
|
} `json:"cases"`
|
||||||
|
} `json:"clientAddress"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadContract(t *testing.T) authContract {
|
||||||
|
t.Helper()
|
||||||
|
data, err := os.ReadFile(contractFile)
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
t.Skipf("%s is not part of this checkout", contractFile)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var contract authContract
|
||||||
|
if err := json.Unmarshal(data, &contract); err != nil {
|
||||||
|
t.Fatalf("decode %s: %v", contractFile, err)
|
||||||
|
}
|
||||||
|
return contract
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContractPasswordHashes(t *testing.T) {
|
||||||
|
contract := loadContract(t)
|
||||||
|
for _, entry := range contract.Password.Hashes {
|
||||||
|
t.Run(entry.Name, func(t *testing.T) {
|
||||||
|
password := entry.Password
|
||||||
|
if password == "" {
|
||||||
|
password = contract.Password.Plaintext
|
||||||
|
}
|
||||||
|
wrongPassword := entry.WrongPassword
|
||||||
|
if wrongPassword == "" {
|
||||||
|
wrongPassword = contract.Password.WrongPassword
|
||||||
|
}
|
||||||
|
if got := VerifyPassword(entry.Hash, password); got != entry.Verifies["go"] {
|
||||||
|
t.Errorf("VerifyPassword = %v, want %v", got, entry.Verifies["go"])
|
||||||
|
}
|
||||||
|
if VerifyPassword(entry.Hash, wrongPassword) {
|
||||||
|
t.Error("VerifyPassword accepted the wrong password")
|
||||||
|
}
|
||||||
|
if want, ok := entry.NeedsUpgrade["go"]; ok {
|
||||||
|
if got := PasswordHashNeedsUpgrade(entry.Hash); got != want {
|
||||||
|
t.Errorf("PasswordHashNeedsUpgrade = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
valid, upgraded, err := VerifyAndUpgradePassword(entry.Hash, password)
|
||||||
|
if err != nil || !valid || (upgraded != "") != want {
|
||||||
|
t.Errorf("VerifyAndUpgradePassword = %v, upgraded %v, %v; want valid with an upgrade = %v", valid, upgraded != "", err, want)
|
||||||
|
}
|
||||||
|
if upgraded != "" && (!strings.HasPrefix(upgraded, bcryptScheme) && !strings.HasPrefix(upgraded, bcryptSHA256Scheme) || !VerifyPassword(upgraded, password)) {
|
||||||
|
t.Errorf("the upgraded hash %q is not a verifiable current-scheme hash", upgraded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContractPasswordLength(t *testing.T) {
|
||||||
|
contract := loadContract(t)
|
||||||
|
_, err := HashPassword(strings.Repeat("a", contract.Password.TooLongToHash.Bytes))
|
||||||
|
if accepted := err == nil; accepted != contract.Password.TooLongToHash.Accepted["go"] {
|
||||||
|
t.Fatalf("HashPassword of %d bytes accepted = %v, want %v (error %v)", contract.Password.TooLongToHash.Bytes, accepted, contract.Password.TooLongToHash.Accepted["go"], err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContractTOTP(t *testing.T) {
|
||||||
|
contract := loadContract(t)
|
||||||
|
for _, entry := range contract.TOTP.Cases {
|
||||||
|
t.Run(entry.Name, func(t *testing.T) {
|
||||||
|
secret := contract.TOTP.Secret
|
||||||
|
if entry.Secret != nil {
|
||||||
|
secret = *entry.Secret
|
||||||
|
}
|
||||||
|
step, got := VerifyTOTP(secret, entry.Code, time.Unix(entry.Unix, 0))
|
||||||
|
if got != entry.Valid {
|
||||||
|
t.Errorf("VerifyTOTP = %v, want %v", got, entry.Valid)
|
||||||
|
}
|
||||||
|
if got {
|
||||||
|
want := entry.Unix / 30
|
||||||
|
if entry.MatchedStep != nil {
|
||||||
|
want = *entry.MatchedStep
|
||||||
|
}
|
||||||
|
if step != want {
|
||||||
|
t.Errorf("VerifyTOTP matched step %d, want %d", step, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContractClientAddress(t *testing.T) {
|
||||||
|
contract := loadContract(t)
|
||||||
|
for _, entry := range contract.ClientAddress.Cases {
|
||||||
|
t.Run(entry.Name, func(t *testing.T) {
|
||||||
|
networks, err := ParseTrustedProxies(entry.Trusted)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/auth/login", nil)
|
||||||
|
request.RemoteAddr = entry.Peer + ":4000"
|
||||||
|
if strings.Contains(entry.Peer, ":") {
|
||||||
|
request.RemoteAddr = "[" + entry.Peer + "]:4000"
|
||||||
|
}
|
||||||
|
for _, line := range entry.Forwarded {
|
||||||
|
request.Header.Add("X-Forwarded-For", line)
|
||||||
|
}
|
||||||
|
if got := (&Service{trustedProxies: networks}).clientAddress(request); got != entry.Want {
|
||||||
|
t.Errorf("clientAddress = %q, want %q", got, entry.Want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for _, list := range contract.ClientAddress.InvalidTrustedProxyLists {
|
||||||
|
if _, err := ParseTrustedProxies(list); err == nil {
|
||||||
|
t.Errorf("ParseTrustedProxies(%q) accepted an invalid list", list)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+137
-6
@@ -1,21 +1,152 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import "golang.org/x/crypto/bcrypt"
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"golang.org/x/crypto/pbkdf2"
|
||||||
|
)
|
||||||
|
|
||||||
// BcryptCost is kept in one place so all services use the same password
|
// BcryptCost is kept in one place so all services use the same password
|
||||||
// storage policy. Existing hashes remain valid when this value is raised.
|
// storage policy. Hashes stored at a lower cost are rewritten on the next
|
||||||
|
// successful login (see VerifyAndUpgradePassword).
|
||||||
const BcryptCost = 12
|
const BcryptCost = 12
|
||||||
|
|
||||||
// HashPassword returns a bcrypt password hash suitable for storage.
|
// bcryptScheme prefixes every hash HashPassword writes, so verification picks
|
||||||
|
// the algorithm from the stored value. The bcrypt string follows unchanged, so
|
||||||
|
// a stored value reads "bcrypt$$2a$12$..." (the bcrypt string itself starts
|
||||||
|
// with "$"). Unprefixed bcrypt hashes from before the prefix still verify and
|
||||||
|
// are upgraded on login.
|
||||||
|
const bcryptScheme = "bcrypt$"
|
||||||
|
const bcryptSHA256Scheme = "bcrypt-sha256$"
|
||||||
|
|
||||||
|
const (
|
||||||
|
maxPasswordBytes = 72
|
||||||
|
legacyPBKDF2Iterations = 100000
|
||||||
|
maxPBKDF2Iterations = 10000000
|
||||||
|
)
|
||||||
|
|
||||||
|
// HashPassword returns a versioned password hash suitable for storage.
|
||||||
func HashPassword(password string) (string, error) {
|
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
|
||||||
}
|
}
|
||||||
return string(hash), nil
|
return bcryptScheme + string(hash), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// VerifyPassword checks a plaintext password against a stored bcrypt hash.
|
// VerifyPassword checks a plaintext password against bcrypt and legacy Node
|
||||||
|
// PBKDF2 hashes. A valid legacy hash is rewritten by VerifyAndUpgradePassword.
|
||||||
func VerifyPassword(hash, password string) bool {
|
func VerifyPassword(hash, password string) bool {
|
||||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
if bcryptHash, ok := strings.CutPrefix(hash, bcryptSHA256Scheme); ok {
|
||||||
|
digest := sha256.Sum256([]byte(password))
|
||||||
|
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(hex.EncodeToString(digest[:]))) == nil
|
||||||
|
}
|
||||||
|
if iterations, salt, expected, ok := parsePBKDF2Hash(hash); ok {
|
||||||
|
actual := pbkdf2.Key([]byte(password), []byte(salt), iterations, 32, sha256.New)
|
||||||
|
expectedBytes, err := hex.DecodeString(expected)
|
||||||
|
return err == nil && subtle.ConstantTimeCompare(expectedBytes, actual) == 1
|
||||||
|
}
|
||||||
|
bcryptHash, ok := bcryptHashOf(hash)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if len([]byte(password)) > maxPasswordBytes {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return bcrypt.CompareHashAndPassword([]byte(bcryptHash), []byte(password)) == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PasswordHashNeedsUpgrade reports whether a stored hash is not in the current
|
||||||
|
// scheme: an unprefixed legacy hash, or a bcrypt cost below BcryptCost.
|
||||||
|
func PasswordHashNeedsUpgrade(hash string) bool {
|
||||||
|
if bcryptHash, prefixed := strings.CutPrefix(hash, bcryptSHA256Scheme); prefixed {
|
||||||
|
cost, err := bcrypt.Cost([]byte(bcryptHash))
|
||||||
|
return err != nil || cost < BcryptCost
|
||||||
|
}
|
||||||
|
if _, _, _, ok := parsePBKDF2Hash(hash); ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
bcryptHash, prefixed := strings.CutPrefix(hash, bcryptScheme)
|
||||||
|
if !prefixed {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
cost, err := bcrypt.Cost([]byte(bcryptHash))
|
||||||
|
return err != nil || cost < BcryptCost
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyAndUpgradePassword checks password against a stored hash. When it
|
||||||
|
// matches a hash that is not in the current scheme, it returns a replacement
|
||||||
|
// from HashPassword for the caller to store; upgraded is empty when no rewrite
|
||||||
|
// is needed or the password does not match. A non-nil error with valid set
|
||||||
|
// means the login succeeded but the replacement could not be made.
|
||||||
|
func VerifyAndUpgradePassword(hash, password string) (valid bool, upgraded string, err error) {
|
||||||
|
if !VerifyPassword(hash, password) {
|
||||||
|
return false, "", nil
|
||||||
|
}
|
||||||
|
if !PasswordHashNeedsUpgrade(hash) {
|
||||||
|
return true, "", nil
|
||||||
|
}
|
||||||
|
if len([]byte(password)) > maxPasswordBytes {
|
||||||
|
digest := sha256.Sum256([]byte(password))
|
||||||
|
var hashBytes []byte
|
||||||
|
hashBytes, err = bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(digest[:])), BcryptCost)
|
||||||
|
if err == nil {
|
||||||
|
upgraded = bcryptSHA256Scheme + string(hashBytes)
|
||||||
|
}
|
||||||
|
return true, upgraded, err
|
||||||
|
}
|
||||||
|
upgraded, err = HashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
return true, "", err
|
||||||
|
}
|
||||||
|
return true, upgraded, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// bcryptHashOf returns the bcrypt string inside a stored hash.
|
||||||
|
func bcryptHashOf(stored string) (string, bool) {
|
||||||
|
if rest, prefixed := strings.CutPrefix(stored, bcryptScheme); prefixed {
|
||||||
|
return rest, true
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(stored, "$2a$") || strings.HasPrefix(stored, "$2b$") || strings.HasPrefix(stored, "$2y$") {
|
||||||
|
return stored, true
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testPassword = "correct horse battery staple"
|
||||||
|
|
||||||
|
func TestHashPasswordWritesTheSchemePrefix(t *testing.T) {
|
||||||
|
hash, err := HashPassword(testPassword)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(hash, "bcrypt$$2") {
|
||||||
|
t.Fatalf("hash = %q, want the bcrypt$ scheme prefix before a bcrypt string", hash)
|
||||||
|
}
|
||||||
|
if PasswordHashNeedsUpgrade(hash) {
|
||||||
|
t.Fatal("a fresh hash in the current scheme needs no upgrade")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyPasswordAcceptsUnprefixedLegacyBcrypt(t *testing.T) {
|
||||||
|
legacy, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !VerifyPassword(string(legacy), testPassword) {
|
||||||
|
t.Fatal("legacy unprefixed bcrypt hash no longer verifies")
|
||||||
|
}
|
||||||
|
if VerifyPassword(string(legacy), "wrong password") {
|
||||||
|
t.Fatal("legacy unprefixed bcrypt hash accepted the wrong password")
|
||||||
|
}
|
||||||
|
if !PasswordHashNeedsUpgrade(string(legacy)) {
|
||||||
|
t.Fatal("unprefixed hash should be marked for upgrade")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyPasswordFailsClosedOnUnknownFormats(t *testing.T) {
|
||||||
|
for _, stored := range []string{
|
||||||
|
"",
|
||||||
|
"salt:0123abcd",
|
||||||
|
"pbkdf2-sha256$600000$00$00",
|
||||||
|
"argon2id$v=19$whatever",
|
||||||
|
"bcrypt$",
|
||||||
|
"bcrypt$not-a-bcrypt-string",
|
||||||
|
} {
|
||||||
|
if VerifyPassword(stored, testPassword) {
|
||||||
|
t.Errorf("VerifyPassword accepted unknown format %q", stored)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyAndUpgradeRewritesLegacyHashesOnSuccess(t *testing.T) {
|
||||||
|
legacy, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
valid, upgraded, err := VerifyAndUpgradePassword(string(legacy), testPassword)
|
||||||
|
if err != nil || !valid {
|
||||||
|
t.Fatalf("VerifyAndUpgradePassword() = %v, %v; want valid", valid, err)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(upgraded, bcryptScheme) {
|
||||||
|
t.Fatalf("upgraded hash = %q, want the current scheme", upgraded)
|
||||||
|
}
|
||||||
|
if !VerifyPassword(upgraded, testPassword) {
|
||||||
|
t.Fatal("upgraded hash does not verify the password")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyAndUpgradeRewritesLowCostHashes(t *testing.T) {
|
||||||
|
lowCost, err := bcrypt.GenerateFromPassword([]byte(testPassword), bcrypt.MinCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
stored := bcryptScheme + string(lowCost)
|
||||||
|
if !PasswordHashNeedsUpgrade(stored) {
|
||||||
|
t.Fatal("a prefixed hash below BcryptCost should be marked for upgrade")
|
||||||
|
}
|
||||||
|
valid, upgraded, err := VerifyAndUpgradePassword(stored, testPassword)
|
||||||
|
if err != nil || !valid || upgraded == "" {
|
||||||
|
t.Fatalf("VerifyAndUpgradePassword() = %v, %q, %v; want a rewrite", valid, upgraded, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyAndUpgradeLeavesCurrentAndFailedChecksAlone(t *testing.T) {
|
||||||
|
current, err := HashPassword(testPassword)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
valid, upgraded, err := VerifyAndUpgradePassword(current, testPassword)
|
||||||
|
if err != nil || !valid || upgraded != "" {
|
||||||
|
t.Fatalf("current hash: VerifyAndUpgradePassword() = %v, %q, %v; want valid with no rewrite", valid, upgraded, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
legacy, err := bcrypt.GenerateFromPassword([]byte(testPassword), BcryptCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
valid, upgraded, err = VerifyAndUpgradePassword(string(legacy), "wrong password")
|
||||||
|
if err != nil || valid || upgraded != "" {
|
||||||
|
t.Fatalf("wrong password: VerifyAndUpgradePassword() = %v, %q, %v; want a plain refusal", valid, upgraded, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
|
)
|
||||||
|
|
||||||
|
// platformUsersSchema holds the test's own `users` table, so it never meets the fuller table that
|
||||||
|
// the media package's migration creates in the same database.
|
||||||
|
const platformUsersSchema = "platform_users_test"
|
||||||
|
|
||||||
|
// withSearchPath returns databaseURL with its search_path set to schema.
|
||||||
|
func withSearchPath(t *testing.T, databaseURL, schema string) string {
|
||||||
|
t.Helper()
|
||||||
|
parsed, err := url.Parse(databaseURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse database URL: %v", err)
|
||||||
|
}
|
||||||
|
query := parsed.Query()
|
||||||
|
query.Set("search_path", schema)
|
||||||
|
parsed.RawQuery = query.Encode()
|
||||||
|
return parsed.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPlatformUserSQL runs the moderatable platform-user methods (CreateUser, ListUsers,
|
||||||
|
// UpdateUser, SetPassword, DeleteUser) against a real database. The `users` table normally comes
|
||||||
|
// from 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
|
||||||
|
// database, for example:
|
||||||
|
//
|
||||||
|
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./auth/ -run TestPlatformUserSQL
|
||||||
|
func TestPlatformUserSQL(t *testing.T) {
|
||||||
|
databaseURL := os.Getenv("SHARED_TEST_DATABASE_URL")
|
||||||
|
if databaseURL == "" {
|
||||||
|
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres platform-user test")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
admin, err := postgres.Open(ctx, postgres.DefaultConfig(databaseURL))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open pool: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(admin.Close)
|
||||||
|
if _, err := admin.Exec(ctx, `DROP SCHEMA IF EXISTS `+platformUsersSchema+` CASCADE; CREATE SCHEMA `+platformUsersSchema); err != nil {
|
||||||
|
t.Fatalf("create schema: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_, _ = admin.Exec(context.Background(), `DROP SCHEMA IF EXISTS `+platformUsersSchema+` CASCADE`)
|
||||||
|
})
|
||||||
|
|
||||||
|
pool, err := postgres.Open(ctx, postgres.DefaultConfig(withSearchPath(t, databaseURL, platformUsersSchema)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open pool: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(pool.Close)
|
||||||
|
if _, err := pool.Exec(ctx, `
|
||||||
|
CREATE TABLE users (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
email TEXT NOT NULL UNIQUE,
|
||||||
|
username TEXT,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
|
disabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
last_login_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)`); err != nil {
|
||||||
|
t.Fatalf("create users table: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
service := New(pool, "session", false, "", "testproject")
|
||||||
|
|
||||||
|
if _, err := service.CreateUser(ctx, "not-an-email", "x", "password123", "user"); err == nil {
|
||||||
|
t.Fatal("CreateUser accepted an invalid email")
|
||||||
|
}
|
||||||
|
if _, err := service.CreateUser(ctx, "platform-test-bad@example.com", "x@y", "password123", "user"); err == nil {
|
||||||
|
t.Fatal("CreateUser accepted a username containing @")
|
||||||
|
}
|
||||||
|
if _, err := service.CreateUser(ctx, "platform-test-bad@example.com", "x", strings.Repeat("p", 73), "user"); err == nil {
|
||||||
|
t.Fatal("CreateUser accepted a password longer than 72 bytes")
|
||||||
|
}
|
||||||
|
|
||||||
|
alice, err := service.CreateUser(ctx, " Platform-Test-Alice@Example.com ", "alice-platform", "password123", "MODERATOR")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateUser(alice) error = %v", err)
|
||||||
|
}
|
||||||
|
if alice.Email != "platform-test-alice@example.com" || alice.Username != "alice-platform" || alice.Role != "moderator" {
|
||||||
|
t.Fatalf("created user = %+v, want a lower-cased email and the normalized moderator role", alice)
|
||||||
|
}
|
||||||
|
bob, err := service.CreateUser(ctx, "platform-test-bob@example.com", "bob-platform", "password123", "superuser")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateUser(bob) error = %v", err)
|
||||||
|
}
|
||||||
|
if bob.Role != "user" {
|
||||||
|
t.Fatalf("an unknown role was stored as %q, want it reduced to user", bob.Role)
|
||||||
|
}
|
||||||
|
if _, err := service.CreateUser(ctx, "platform-test-alice@example.com", "other", "password123", "user"); err == nil {
|
||||||
|
t.Fatal("CreateUser accepted a duplicate email")
|
||||||
|
}
|
||||||
|
|
||||||
|
var storedHash string
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT password_hash FROM users WHERE id=$1`, alice.ID).Scan(&storedHash); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(storedHash, bcryptScheme) || !VerifyPassword(storedHash, "password123") {
|
||||||
|
t.Fatalf("stored hash %q is not a verifiable versioned hash", storedHash)
|
||||||
|
}
|
||||||
|
|
||||||
|
listed, total, err := service.ListUsers(ctx, "platform-test-", 1, 0)
|
||||||
|
if err != nil || total != 2 || len(listed) != 1 {
|
||||||
|
t.Fatalf("ListUsers page 1 = %d rows, total %d, %v; want 1 row of 2", len(listed), total, err)
|
||||||
|
}
|
||||||
|
if listed[0]["id"] != bob.ID {
|
||||||
|
t.Fatalf("first row = %v, want the newest user (ordered by id descending)", listed[0]["id"])
|
||||||
|
}
|
||||||
|
if page, _, _ := service.ListUsers(ctx, "platform-test-", 1, 1); len(page) != 1 || page[0]["id"] != alice.ID {
|
||||||
|
t.Fatalf("second page = %v, want alice", page)
|
||||||
|
}
|
||||||
|
if found, total, _ := service.ListUsers(ctx, "ALICE-platform", 50, 0); total != 1 || len(found) != 1 || found[0]["email"] != "platform-test-alice@example.com" {
|
||||||
|
t.Fatalf("search by username = %v (total %d), want alice, matched ignoring case", found, total)
|
||||||
|
}
|
||||||
|
if found, total, _ := service.ListUsers(ctx, "no-such-person-anywhere", 50, 0); total != 0 || len(found) != 0 {
|
||||||
|
t.Fatalf("search with no match = %v (total %d)", found, total)
|
||||||
|
}
|
||||||
|
|
||||||
|
disabled := true
|
||||||
|
if err := service.UpdateUser(ctx, alice.ID, "", "alice-renamed", "", &disabled); err != nil {
|
||||||
|
t.Fatalf("UpdateUser error = %v", err)
|
||||||
|
}
|
||||||
|
account, err := service.managedAccount(ctx, alice.ID)
|
||||||
|
if err != nil || account == nil {
|
||||||
|
t.Fatalf("managedAccount = %v, %v", account, err)
|
||||||
|
}
|
||||||
|
if account.Username != "alice-renamed" || account.Email != "platform-test-alice@example.com" || account.Role != "moderator" || !account.Disabled {
|
||||||
|
t.Fatalf("after a partial update = %+v, want only the username and disabled flag changed", account)
|
||||||
|
}
|
||||||
|
if err := service.UpdateUser(ctx, alice.ID, "", "", " ADMIN ", nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if account, _ := service.managedAccount(ctx, alice.ID); account.Role != "admin" || !account.Disabled {
|
||||||
|
t.Fatalf("after a role-only update = %+v, want the admin role and the disabled flag kept", account)
|
||||||
|
}
|
||||||
|
if err := service.UpdateUser(ctx, alice.ID, "", "", "wizard", nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if account, _ := service.managedAccount(ctx, alice.ID); account.Role != "user" {
|
||||||
|
t.Fatalf("an unknown role was stored as %q, want it reduced to user", account.Role)
|
||||||
|
}
|
||||||
|
if missing, err := service.managedAccount(ctx, -1); err != nil || missing != nil {
|
||||||
|
t.Fatalf("managedAccount of a missing id = %v, %v; want nil, nil", missing, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := service.SetPassword(ctx, bob.ID, "short"); err == nil {
|
||||||
|
t.Fatal("SetPassword accepted a short password")
|
||||||
|
}
|
||||||
|
if err := service.SetPassword(ctx, bob.ID, "a-new-password-1"); err != nil {
|
||||||
|
t.Fatalf("SetPassword error = %v", err)
|
||||||
|
}
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT password_hash FROM users WHERE id=$1`, bob.ID).Scan(&storedHash); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !VerifyPassword(storedHash, "a-new-password-1") || VerifyPassword(storedHash, "password123") {
|
||||||
|
t.Fatal("SetPassword did not replace the stored hash")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := service.DeleteUser(ctx, alice.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if gone, _ := service.managedAccount(ctx, alice.ID); gone != nil {
|
||||||
|
t.Fatal("DeleteUser left the account in place")
|
||||||
|
}
|
||||||
|
}
|
||||||
+220
-71
@@ -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
|
||||||
@@ -167,7 +163,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -178,9 +177,9 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
|
||||||
|
"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
|
||||||
@@ -221,7 +220,12 @@ 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.")
|
||||||
|
errSetupRequiresLogin = errors.New("Account setup is only available while login is required.")
|
||||||
|
errNoLoginRequiredStore = errors.New("the login-required setting has no store to save to")
|
||||||
|
errCrossSiteRequest = errors.New("cross-site request refused")
|
||||||
|
errJSONContentType = errors.New("request body must be application/json")
|
||||||
errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.")
|
errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.")
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -230,6 +234,8 @@ const (
|
|||||||
setupClaimedSettingKey = "setup_claimed"
|
setupClaimedSettingKey = "setup_claimed"
|
||||||
|
|
||||||
proxyMinPasswordLength = 8
|
proxyMinPasswordLength = 8
|
||||||
|
// maxBcryptPasswordBytes is the longest password bcrypt hashes in full.
|
||||||
|
maxBcryptPasswordBytes = 72
|
||||||
proxyMaxUsernameLength = 64
|
proxyMaxUsernameLength = 64
|
||||||
proxyMaxEmailLength = 254
|
proxyMaxEmailLength = 254
|
||||||
)
|
)
|
||||||
@@ -247,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.
|
||||||
@@ -262,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.
|
||||||
@@ -277,12 +283,21 @@ type Service struct {
|
|||||||
// real base URL.
|
// real base URL.
|
||||||
authGuard *authclient.Client
|
authGuard *authclient.Client
|
||||||
configurationError error
|
configurationError error
|
||||||
// loginRequiredOverride is populated by the internal ProjectConfigurator
|
// reauthenticateEmailChanges is opt-in because older consumers historically
|
||||||
// endpoint. Some legacy consumers intentionally use a no-op ProxyStore for
|
// allowed email-only edits without the current password. Password changes
|
||||||
// this setting because they historically had no local toggle; the live
|
// always require current credentials in UpdateMe.
|
||||||
// override lets those services still honor the central setting immediately.
|
reauthenticateEmailChanges bool
|
||||||
loginRequiredMu sync.RWMutex
|
loginCacheMu sync.Mutex
|
||||||
loginRequiredOverride *bool
|
loginCacheValue bool
|
||||||
|
loginCacheSet bool
|
||||||
|
loginCacheExpires time.Time
|
||||||
|
// Attempt counters for the credential endpoints; see ratelimit.go.
|
||||||
|
loginAccountAttempts *attemptLimiter
|
||||||
|
loginClientAttempts *attemptLimiter
|
||||||
|
totpAttempts *attemptLimiter
|
||||||
|
// trustedProxies are the peers whose X-Forwarded-For header is honoured;
|
||||||
|
// see clientAddress in clientip.go.
|
||||||
|
trustedProxies []*net.IPNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServiceOption configures optional New/NewWithStore construction behavior.
|
// ServiceOption configures optional New/NewWithStore construction behavior.
|
||||||
@@ -293,6 +308,8 @@ type ServiceOption func(*serviceOptions)
|
|||||||
type serviceOptions struct {
|
type serviceOptions struct {
|
||||||
disabled bool
|
disabled bool
|
||||||
requireSecret bool
|
requireSecret bool
|
||||||
|
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
|
||||||
@@ -314,7 +331,23 @@ func RequireSecret() ServiceOption {
|
|||||||
return func(o *serviceOptions) { o.requireSecret = true }
|
return func(o *serviceOptions) { o.requireSecret = true }
|
||||||
}
|
}
|
||||||
|
|
||||||
// New constructs a Service backed by the media family's shared `settings`
|
// ReauthenticateEmailChanges requires current-password proof, and TOTP when
|
||||||
|
// enabled, for email changes through UpdateMe. Password changes already
|
||||||
|
// require the same proof. This is opt-in to preserve existing consumers that
|
||||||
|
// have not adopted the matching profile-dialog flow.
|
||||||
|
func ReauthenticateEmailChanges() ServiceOption {
|
||||||
|
return func(o *serviceOptions) { o.reauthenticateEmailChanges = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is
|
||||||
|
// honoured when a login's client address is taken. Build the list from the
|
||||||
|
// TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer
|
||||||
|
// is always the client address.
|
||||||
|
func WithTrustedProxies(networks []*net.IPNet) ServiceOption {
|
||||||
|
return func(o *serviceOptions) { o.trustedProxies = networks }
|
||||||
|
}
|
||||||
|
|
||||||
|
// New constructs a Service backed by the 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
|
||||||
@@ -336,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).
|
||||||
@@ -356,15 +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{
|
||||||
|
store: store,
|
||||||
|
cookieName: cookieName,
|
||||||
|
secureCookies: secureCookies,
|
||||||
|
authGuard: client,
|
||||||
|
configurationError: configurationError,
|
||||||
|
reauthenticateEmailChanges: options.reauthenticateEmailChanges,
|
||||||
|
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
|
||||||
|
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
|
||||||
|
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
|
||||||
|
trustedProxies: options.trustedProxies,
|
||||||
}
|
}
|
||||||
return &Service{store: store, cookieName: cookieName, secureCookies: secureCookies, authGuard: client, configurationError: configurationError}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -562,16 +605,8 @@ func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler {
|
|||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// CurrentUser returns no user only when login is required (it returns the
|
||||||
loginRequired, err := s.LoginRequired(r.Context())
|
// synthetic admin for every other case), so no second settings read is needed.
|
||||||
if err != nil {
|
|
||||||
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !loginRequired {
|
|
||||||
next.ServeHTTP(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@@ -595,15 +630,7 @@ func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler {
|
|||||||
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := UserFromContext(r.Context())
|
user := UserFromContext(r.Context())
|
||||||
if user == nil {
|
if user == nil {
|
||||||
loginRequired, err := s.LoginRequired(r.Context())
|
// As in RequireIfLoginRequired, a nil user means login is required.
|
||||||
if err != nil {
|
|
||||||
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !loginRequired {
|
|
||||||
next.ServeHTTP(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -680,6 +707,8 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
|||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
|
CurrentPassword string `json:"currentPassword"`
|
||||||
|
TOTPToken string `json:"totpToken"`
|
||||||
}
|
}
|
||||||
if err := decodeProxyJSON(r, &input); err != nil {
|
if err := decodeProxyJSON(r, &input); err != nil {
|
||||||
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
|
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
@@ -702,8 +731,30 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeProxyError(w, http.StatusBadRequest, err.Error())
|
writeProxyError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
if input.Password != "" || (s.reauthenticateEmailChanges && email != current.Email) {
|
||||||
|
if input.CurrentPassword == "" {
|
||||||
|
writeProxyError(w, http.StatusBadRequest, "currentPassword is required to change email or password")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if current.MFAEnabled && strings.TrimSpace(input.TOTPToken) == "" {
|
||||||
|
writeProxyError(w, http.StatusBadRequest, "totpToken is required to change email or password")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reauthenticated, err := s.authGuard.Login(r.Context(), current.Username, input.CurrentPassword, input.TOTPToken)
|
||||||
|
if err != nil {
|
||||||
|
writeAuthGuardError(w, err, "current credentials could not be verified")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if token := temporarySessionToken(reauthenticated); token != "" {
|
||||||
|
defer func() {
|
||||||
|
_, _ = s.authGuard.Logout(context.WithoutCancel(r.Context()), token)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
if input.Password != "" {
|
||||||
managedInput.Password = input.Password
|
managedInput.Password = input.Password
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
token := s.sessionToken(r)
|
token := s.sessionToken(r)
|
||||||
if err := s.authGuard.UpdateManagedUser(r.Context(), token, current.ID, managedInput); err != nil {
|
if err := s.authGuard.UpdateManagedUser(r.Context(), token, current.ID, managedInput); err != nil {
|
||||||
@@ -719,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) {
|
||||||
@@ -756,17 +819,37 @@ func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired})
|
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LoginRequired caches the store's value briefly to avoid a database read for
|
||||||
|
// every authenticated route. Updates through this Service clear the cache
|
||||||
|
// immediately; changes made by another replica become visible within two seconds.
|
||||||
func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
|
func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
|
||||||
s.loginRequiredMu.RLock()
|
|
||||||
override := s.loginRequiredOverride
|
|
||||||
s.loginRequiredMu.RUnlock()
|
|
||||||
if override != nil {
|
|
||||||
return *override, nil
|
|
||||||
}
|
|
||||||
if s.store == nil {
|
if s.store == nil {
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
return s.store.LoginRequired(ctx)
|
now := time.Now()
|
||||||
|
s.loginCacheMu.Lock()
|
||||||
|
if s.loginCacheSet && now.Before(s.loginCacheExpires) {
|
||||||
|
value := s.loginCacheValue
|
||||||
|
s.loginCacheMu.Unlock()
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
s.loginCacheMu.Unlock()
|
||||||
|
|
||||||
|
value, err := s.store.LoginRequired(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
s.loginCacheMu.Lock()
|
||||||
|
if s.loginCacheSet && time.Now().Before(s.loginCacheExpires) {
|
||||||
|
cached := s.loginCacheValue
|
||||||
|
s.loginCacheMu.Unlock()
|
||||||
|
return cached, nil
|
||||||
|
}
|
||||||
|
s.loginCacheValue = value
|
||||||
|
s.loginCacheSet = true
|
||||||
|
s.loginCacheExpires = time.Now().Add(2 * time.Second)
|
||||||
|
s.loginCacheMu.Unlock()
|
||||||
|
return value, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) {
|
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -799,14 +882,17 @@ func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) {
|
|||||||
// central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an
|
// central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an
|
||||||
// admin session of its own.
|
// admin session of its own.
|
||||||
func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
|
func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
|
||||||
if s.store != nil {
|
if s.store == nil {
|
||||||
|
return errNoLoginRequiredStore
|
||||||
|
}
|
||||||
if err := s.store.SetLoginRequired(ctx, required); err != nil {
|
if err := s.store.SetLoginRequired(ctx, required); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
// Drop the cached value rather than setting it, so the next read comes from the store and a
|
||||||
s.loginRequiredMu.Lock()
|
// store that discards writes cannot leave this process with its own login setting.
|
||||||
s.loginRequiredOverride = &required
|
s.loginCacheMu.Lock()
|
||||||
s.loginRequiredMu.Unlock()
|
s.loginCacheSet = false
|
||||||
|
s.loginCacheMu.Unlock()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -816,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) == "" || r.Header.Get("X-Internal-Auth") != secret {
|
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
|
||||||
}
|
}
|
||||||
@@ -992,6 +1078,9 @@ func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) {
|
|||||||
// enforces authorization (including "this user cannot be deleted" rules)
|
// enforces authorization (including "this user cannot be deleted" rules)
|
||||||
// itself.
|
// itself.
|
||||||
func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) {
|
func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if refuseCrossSite(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
id, err := strconv.ParseInt(idURLParam(r), 10, 64)
|
id, err := strconv.ParseInt(idURLParam(r), 10, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeProxyError(w, http.StatusBadRequest, "invalid user id")
|
writeProxyError(w, http.StatusBadRequest, "invalid user id")
|
||||||
@@ -1017,6 +1106,18 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeProxyJSON(w, http.StatusCreated, map[string]any{"user": &user})
|
writeProxyJSON(w, http.StatusCreated, map[string]any{"user": &user})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// First-run setup only applies while login is required. With login off, every
|
||||||
|
// caller already gets the local admin identity, and a fresh AuthGuard would make
|
||||||
|
// an anonymous signup its superadmin.
|
||||||
|
loginRequired, err := s.LoginRequired(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !loginRequired {
|
||||||
|
writeProxyError(w, http.StatusConflict, errSetupRequiresLogin.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var input struct {
|
var input struct {
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
@@ -1074,7 +1175,7 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := s.authGuard.Register(r.Context(), username, email, input.Password)
|
result, err := s.authGuard.Register(s.withClientIP(r), username, email, input.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// The claim slot is only valid once actually backed by a real
|
// The claim slot is only valid once actually backed by a real
|
||||||
// AuthGuard account; reopen it so a corrected retry can proceed.
|
// AuthGuard account; reopen it so a corrected retry can proceed.
|
||||||
@@ -1115,8 +1216,13 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeProxyError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
|
writeProxyError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
now := time.Now()
|
||||||
|
if !s.loginAccountAttempts.allow(strings.ToLower(identifier), now) || !s.loginClientAttempts.allow(s.clientAddress(r), now) {
|
||||||
|
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
result, err := s.authGuard.Login(r.Context(), identifier, input.Password, input.TOTPToken)
|
result, err := s.authGuard.Login(s.withClientIP(r), identifier, input.Password, input.TOTPToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var apiErr *authclient.APIError
|
var apiErr *authclient.APIError
|
||||||
if errors.As(err, &apiErr) {
|
if errors.As(err, &apiErr) {
|
||||||
@@ -1142,6 +1248,9 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
|
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if refuseCrossSite(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
if !s.enabled() {
|
if !s.enabled() {
|
||||||
writeProxyJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
writeProxyJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||||
return
|
return
|
||||||
@@ -1181,6 +1290,9 @@ func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) {
|
|||||||
// /api/totp/enable (AuthGuard's "enable" is this service's "initiate" step -
|
// /api/totp/enable (AuthGuard's "enable" is this service's "initiate" step -
|
||||||
// naming differs, the two-step provision-then-confirm flow is identical).
|
// naming differs, the two-step provision-then-confirm flow is identical).
|
||||||
func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) {
|
func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if refuseCrossSite(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
if !s.enabled() {
|
if !s.enabled() {
|
||||||
writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
|
writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
|
||||||
return
|
return
|
||||||
@@ -1217,6 +1329,10 @@ func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if !s.totpAttempts.allow(strconv.FormatInt(user.ID, 10), time.Now()) {
|
||||||
|
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
var input struct {
|
var input struct {
|
||||||
Token string `json:"token"`
|
Token string `json:"token"`
|
||||||
TOTPToken string `json:"totpToken"`
|
TOTPToken string `json:"totpToken"`
|
||||||
@@ -1229,7 +1345,7 @@ func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
|
|||||||
if token == "" {
|
if token == "" {
|
||||||
token = strings.TrimSpace(input.Token)
|
token = strings.TrimSpace(input.Token)
|
||||||
}
|
}
|
||||||
if err := s.authGuard.TOTPVerify(r.Context(), s.sessionToken(r), token); err != nil {
|
if err := s.authGuard.TOTPVerify(s.withClientIP(r), s.sessionToken(r), token); err != nil {
|
||||||
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
|
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -1246,6 +1362,10 @@ func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if !s.totpAttempts.allow(strconv.FormatInt(user.ID, 10), time.Now()) {
|
||||||
|
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
var input struct {
|
var input struct {
|
||||||
Token string `json:"token"`
|
Token string `json:"token"`
|
||||||
TOTPToken string `json:"totpToken"`
|
TOTPToken string `json:"totpToken"`
|
||||||
@@ -1258,7 +1378,7 @@ func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
|
|||||||
if token == "" {
|
if token == "" {
|
||||||
token = strings.TrimSpace(input.Token)
|
token = strings.TrimSpace(input.Token)
|
||||||
}
|
}
|
||||||
if err := s.authGuard.TOTPDisable(r.Context(), s.sessionToken(r), token); err != nil {
|
if err := s.authGuard.TOTPDisable(s.withClientIP(r), s.sessionToken(r), token); err != nil {
|
||||||
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
|
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -1341,7 +1461,7 @@ func (s *Service) CreateUser(ctx context.Context, email, username, password, rol
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
role = normalizePlatformRole(role)
|
role = normalizePlatformRole(role)
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
hash, err := HashPassword(password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -1350,7 +1470,7 @@ func (s *Service) CreateUser(ctx context.Context, email, username, password, rol
|
|||||||
INSERT INTO users (email, username, password_hash, role)
|
INSERT INTO users (email, username, password_hash, role)
|
||||||
VALUES ($1, $2, $3, $4)
|
VALUES ($1, $2, $3, $4)
|
||||||
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user')
|
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user')
|
||||||
`, email, username, string(hash), role).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
|
`, email, username, hash, role).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -1414,11 +1534,11 @@ func (s *Service) SetPassword(ctx context.Context, id int64, password string) er
|
|||||||
if err := validateProxyPassword(password); err != nil {
|
if err := validateProxyPassword(password); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
hash, err := HashPassword(password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, string(hash))
|
_, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, hash)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1445,6 +1565,10 @@ func normalizeProxyUsername(value string) (string, error) {
|
|||||||
if len([]rune(value)) > proxyMaxUsernameLength {
|
if len([]rune(value)) > proxyMaxUsernameLength {
|
||||||
return "", errors.New("username is too long")
|
return "", errors.New("username is too long")
|
||||||
}
|
}
|
||||||
|
// An identifier containing "@" could be read as another account's email at login.
|
||||||
|
if strings.Contains(value, "@") {
|
||||||
|
return "", errors.New("username cannot contain @")
|
||||||
|
}
|
||||||
return value, nil
|
return value, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1460,6 +1584,10 @@ func validateProxyPassword(password string) error {
|
|||||||
if len([]rune(password)) < proxyMinPasswordLength || len([]rune(password)) > 1024 {
|
if len([]rune(password)) < proxyMinPasswordLength || len([]rune(password)) > 1024 {
|
||||||
return errors.New("Password must be at least 8 characters.")
|
return errors.New("Password must be at least 8 characters.")
|
||||||
}
|
}
|
||||||
|
// bcrypt uses only the first 72 bytes, so a longer password would be refused at hashing time.
|
||||||
|
if len(password) > maxBcryptPasswordBytes {
|
||||||
|
return errors.New("Password must be at most 72 bytes.")
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1496,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 {
|
||||||
@@ -1506,8 +1634,29 @@ func idURLParam(r *http.Request) string {
|
|||||||
return r.PathValue("id")
|
return r.PathValue("id")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// decodeProxyJSON reads a JSON request body. It refuses a body that is not sent as
|
||||||
|
// application/json, which a cross-site HTML form cannot produce, and any request the browser
|
||||||
|
// marks as cross-site.
|
||||||
|
// refuseCrossSite answers a state-changing request that carries no JSON body (logout, TOTP
|
||||||
|
// initiate, user delete) when the browser says it came from another site. Simple cross-site
|
||||||
|
// forms cannot send a JSON body, so decodeProxyJSON already refuses them; this covers the rest.
|
||||||
|
func refuseCrossSite(w http.ResponseWriter, r *http.Request) bool {
|
||||||
|
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||||
|
writeProxyError(w, http.StatusForbidden, errCrossSiteRequest.Error())
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func decodeProxyJSON(r *http.Request, target any) error {
|
func decodeProxyJSON(r *http.Request, target any) error {
|
||||||
defer r.Body.Close()
|
defer r.Body.Close()
|
||||||
|
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||||
|
return errCrossSiteRequest
|
||||||
|
}
|
||||||
|
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
|
if err != nil || mediaType != "application/json" {
|
||||||
|
return errJSONContentType
|
||||||
|
}
|
||||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
|
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
|
||||||
return decoder.Decode(target)
|
return decoder.Decode(target)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,694 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||||
|
)
|
||||||
|
|
||||||
|
// recordedCall is one request a fakeAuthGuard received.
|
||||||
|
type recordedCall struct {
|
||||||
|
Method string
|
||||||
|
Path string
|
||||||
|
Forwarded string
|
||||||
|
Authorization string
|
||||||
|
Body map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeAuthGuard is an httptest AuthGuard that records every call and answers from a route table.
|
||||||
|
type fakeAuthGuard struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
calls []recordedCall
|
||||||
|
routes map[string]func(w http.ResponseWriter, body map[string]any)
|
||||||
|
server *httptest.Server
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFakeAuthGuard(t *testing.T) *fakeAuthGuard {
|
||||||
|
t.Helper()
|
||||||
|
f := &fakeAuthGuard{routes: map[string]func(http.ResponseWriter, map[string]any){}}
|
||||||
|
f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
raw, _ := io.ReadAll(r.Body)
|
||||||
|
var body map[string]any
|
||||||
|
_ = json.Unmarshal(raw, &body)
|
||||||
|
f.mu.Lock()
|
||||||
|
f.calls = append(f.calls, recordedCall{
|
||||||
|
Method: r.Method, Path: r.URL.Path, Forwarded: r.Header.Get("X-Forwarded-For"),
|
||||||
|
Authorization: r.Header.Get("Authorization"), Body: body,
|
||||||
|
})
|
||||||
|
route := f.routes[r.Method+" "+r.URL.Path]
|
||||||
|
f.mu.Unlock()
|
||||||
|
if route == nil {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
route(w, body)
|
||||||
|
}))
|
||||||
|
t.Cleanup(f.server.Close)
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAuthGuard) handle(route string, handler func(w http.ResponseWriter, body map[string]any)) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.routes[route] = handler
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAuthGuard) reply(route string, status int, payload any) {
|
||||||
|
f.handle(route, func(w http.ResponseWriter, _ map[string]any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_ = json.NewEncoder(w).Encode(payload)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAuthGuard) callsTo(route string) []recordedCall {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
var matched []recordedCall
|
||||||
|
for _, call := range f.calls {
|
||||||
|
if call.Method+" "+call.Path == route {
|
||||||
|
matched = append(matched, call)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matched
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAuthGuard) service(t *testing.T, options ...ServiceOption) (*Service, *fakeProxyStore) {
|
||||||
|
t.Helper()
|
||||||
|
store := &fakeProxyStore{loginRequired: true}
|
||||||
|
return NewWithStore(store, "session", false, f.server.URL, "testproject", options...), store
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonRequest(method, target, body string) *http.Request {
|
||||||
|
req := httptest.NewRequest(method, target, strings.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
return req
|
||||||
|
}
|
||||||
|
|
||||||
|
func withSession(req *http.Request, token string) *http.Request {
|
||||||
|
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: token})
|
||||||
|
return req
|
||||||
|
}
|
||||||
|
|
||||||
|
func withUser(req *http.Request, user *ProxyUser) *http.Request {
|
||||||
|
return req.WithContext(context.WithValue(req.Context(), proxyUserContextKey, user))
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
var out map[string]any
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||||
|
t.Fatalf("response body %q is not JSON: %v", rec.Body.String(), err)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginForwardsTheVerifiedClientAddressToAuthGuard(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
trusted string
|
||||||
|
remote string
|
||||||
|
forwarded string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"peer without trusted proxies", "", "203.0.113.7:4444", "", "203.0.113.7"},
|
||||||
|
{"spoofed header from an untrusted peer", "10.0.0.0/8", "203.0.113.7:4444", "6.6.6.6", "203.0.113.7"},
|
||||||
|
{"client behind a trusted proxy", "10.0.0.0/8", "10.0.0.2:4444", "6.6.6.6, 198.51.100.9", "198.51.100.9"},
|
||||||
|
{"unparseable peer sends nothing", "", "not-an-address", "", ""},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("POST /api/login", http.StatusOK, map[string]any{"user": map[string]any{"id": 1, "username": "a", "role": "user"}})
|
||||||
|
networks, err := ParseTrustedProxies(tt.trusted)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
service, _ := guard.service(t, WithTrustedProxies(networks))
|
||||||
|
req := jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"a","password":"password123"}`)
|
||||||
|
req.RemoteAddr = tt.remote
|
||||||
|
if tt.forwarded != "" {
|
||||||
|
req.Header.Set("X-Forwarded-For", tt.forwarded)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Login(rec, req)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("login status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
calls := guard.callsTo("POST /api/login")
|
||||||
|
if len(calls) != 1 || calls[0].Forwarded != tt.want {
|
||||||
|
t.Fatalf("AuthGuard saw X-Forwarded-For %+v, want %q", calls, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginMapsAuthGuardAnswers(t *testing.T) {
|
||||||
|
login := func(guard *fakeAuthGuard) *httptest.ResponseRecorder {
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"email":"a@b.com","password":"password123"}`))
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("success forwards the session cookie", func(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) {
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "tok", Path: "/", HttpOnly: true})
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"user":{"id":3,"username":"a","email":"a@b.com","role":"admin","totp_enabled":true}}`))
|
||||||
|
})
|
||||||
|
rec := login(guard)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d", rec.Code)
|
||||||
|
}
|
||||||
|
user := decodeBody(t, rec)["user"].(map[string]any)
|
||||||
|
if user["role"] != "admin" || user["canManageUsers"] != true || user["mfaEnabled"] != true {
|
||||||
|
t.Fatalf("user = %v", user)
|
||||||
|
}
|
||||||
|
if cookies := rec.Result().Cookies(); len(cookies) != 1 || cookies[0].Value != "tok" {
|
||||||
|
t.Fatalf("cookies = %v, want the AuthGuard session cookie", cookies)
|
||||||
|
}
|
||||||
|
if body := guard.callsTo("POST /api/login")[0].Body; body["username_or_email"] != "a@b.com" {
|
||||||
|
t.Fatalf("AuthGuard body = %v, want the email used as the identifier", body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("wrong credentials answer 401 with the generic message", func(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "no such account"})
|
||||||
|
rec := login(guard)
|
||||||
|
if rec.Code != http.StatusUnauthorized || decodeBody(t, rec)["error"] != ErrInvalidLogin.Error() {
|
||||||
|
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("a required second factor is reported as mfaRequired", func(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "code required", "totp_required": true})
|
||||||
|
rec := login(guard)
|
||||||
|
if rec.Code != http.StatusUnauthorized || decodeBody(t, rec)["mfaRequired"] != true {
|
||||||
|
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("an unreachable AuthGuard answers 500 with the unavailable message", func(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
guard.server.Close()
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"a","password":"password123"}`))
|
||||||
|
if rec.Code != http.StatusInternalServerError || decodeBody(t, rec)["error"] != errAuthGuardUnavailable.Error() {
|
||||||
|
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("a missing identifier and a non-JSON body are refused before AuthGuard", func(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Login(rec, jsonRequest(http.MethodPost, "/auth/login", `{"password":"password123"}`))
|
||||||
|
if rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("missing identifier status = %d, want 401", rec.Code)
|
||||||
|
}
|
||||||
|
plain := httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader(`{"identifier":"a"}`))
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
service.Login(rec, plain)
|
||||||
|
if rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("form-typed body status = %d, want 400", rec.Code)
|
||||||
|
}
|
||||||
|
if len(guard.callsTo("POST /api/login")) != 0 {
|
||||||
|
t.Fatal("a refused login still reached AuthGuard")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginIsLimitedPerClientAddress(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("POST /api/login", http.StatusUnauthorized, map[string]any{"error": "bad"})
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
attempt := func(i int, remote string) int {
|
||||||
|
req := jsonRequest(http.MethodPost, "/auth/login", `{"identifier":"user`+strings.Repeat("x", i)+`","password":"guess"}`)
|
||||||
|
req.RemoteAddr = remote
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Login(rec, req)
|
||||||
|
return rec.Code
|
||||||
|
}
|
||||||
|
for i := 0; i < loginClientLimit; i++ {
|
||||||
|
if code := attempt(i, "203.0.113.7:1"); code == http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("attempt %d refused before the limit", i+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code := attempt(loginClientLimit, "203.0.113.7:1"); code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("attempt past the per-address limit status = %d, want 429", code)
|
||||||
|
}
|
||||||
|
if code := attempt(loginClientLimit+1, "203.0.113.8:1"); code == http.StatusTooManyRequests {
|
||||||
|
t.Fatal("a different client address was refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSignupForwardsTheClientAddressAndClaimsSetup(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("GET /api/setup-status", http.StatusOK, map[string]any{"setup_required": true})
|
||||||
|
guard.reply("POST /api/register", http.StatusCreated, map[string]any{"user": map[string]any{"id": 1, "username": "root", "email": "root@example.com", "role": "superadmin"}})
|
||||||
|
service, store := guard.service(t)
|
||||||
|
req := jsonRequest(http.MethodPost, "/auth/signup", `{"email":"Root@Example.com","username":"root","password":"password123"}`)
|
||||||
|
req.RemoteAddr = "198.51.100.20:5555"
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Signup(rec, req)
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("signup status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if !store.setupClaimed {
|
||||||
|
t.Fatal("signup did not claim the setup flag")
|
||||||
|
}
|
||||||
|
calls := guard.callsTo("POST /api/register")
|
||||||
|
if len(calls) != 1 || calls[0].Forwarded != "198.51.100.20" || calls[0].Body["email"] != "root@example.com" {
|
||||||
|
t.Fatalf("register call = %+v", calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSignupValidatesInputBeforeClaimingSetup(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
service, store := guard.service(t)
|
||||||
|
for name, body := range map[string]string{
|
||||||
|
"missing username": `{"email":"a@b.com","password":"password123"}`,
|
||||||
|
"bad email": `{"email":"nope","username":"a","password":"password123"}`,
|
||||||
|
"at in username": `{"email":"a@b.com","username":"a@b.com","password":"password123"}`,
|
||||||
|
"short password": `{"email":"a@b.com","username":"a","password":"short"}`,
|
||||||
|
} {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Signup(rec, jsonRequest(http.MethodPost, "/auth/signup", body))
|
||||||
|
if rec.Code != http.StatusBadRequest {
|
||||||
|
t.Errorf("%s: status = %d, want 400", name, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if store.setupClaimed || len(guard.calls) != 0 {
|
||||||
|
t.Fatal("a refused signup claimed setup or reached AuthGuard")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSignupReleasesTheClaimWhenAuthGuardAlreadyHasAnAccount(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("GET /api/setup-status", http.StatusOK, map[string]any{"setup_required": false})
|
||||||
|
service, store := guard.service(t)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Signup(rec, jsonRequest(http.MethodPost, "/auth/signup", `{"email":"a@b.com","username":"a","password":"password123"}`))
|
||||||
|
if rec.Code != http.StatusConflict || store.setupClaimed {
|
||||||
|
t.Fatalf("status = %d, claimed = %v; want 409 and a released claim", rec.Code, store.setupClaimed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTOTPVerifyAndDisableForwardTheAddressAndShareAUserLimit(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("POST /api/totp/verify", http.StatusUnauthorized, map[string]any{"error": "bad code"})
|
||||||
|
guard.reply("POST /api/totp/disable", http.StatusUnauthorized, map[string]any{"error": "bad code"})
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
user := &ProxyUser{ID: 7, Role: "user"}
|
||||||
|
post := func(handler http.HandlerFunc, body string) int {
|
||||||
|
req := withUser(withSession(jsonRequest(http.MethodPost, "/totp", body), "tok-7"), user)
|
||||||
|
req.RemoteAddr = "198.51.100.30:9"
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
handler(rec, req)
|
||||||
|
return rec.Code
|
||||||
|
}
|
||||||
|
for i := 0; i < totpAttemptLimit-1; i++ {
|
||||||
|
if code := post(service.TOTPVerify, `{"totpToken":"000000"}`); code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("verify attempt %d status = %d, want 401", i+1, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code := post(service.TOTPDisable, `{"token":"000000"}`); code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("disable attempt status = %d, want 401", code)
|
||||||
|
}
|
||||||
|
if code := post(service.TOTPVerify, `{"totpToken":"123456"}`); code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("verify past the shared limit status = %d, want 429", code)
|
||||||
|
}
|
||||||
|
if code := post(service.TOTPDisable, `{"token":"123456"}`); code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("disable past the shared limit status = %d, want 429", code)
|
||||||
|
}
|
||||||
|
verifies, disables := guard.callsTo("POST /api/totp/verify"), guard.callsTo("POST /api/totp/disable")
|
||||||
|
if len(verifies) != totpAttemptLimit-1 || len(disables) != 1 {
|
||||||
|
t.Fatalf("AuthGuard saw %d verify and %d disable calls, want %d and 1", len(verifies), len(disables), totpAttemptLimit-1)
|
||||||
|
}
|
||||||
|
for _, call := range append(verifies, disables...) {
|
||||||
|
if call.Forwarded != "198.51.100.30" || call.Authorization != "Bearer tok-7" {
|
||||||
|
t.Fatalf("call = %+v, want the client address and the session token", call)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if verifies[0].Body["token"] != "000000" {
|
||||||
|
t.Fatalf("verify body = %v, want the totpToken sent as token", verifies[0].Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
other := withUser(withSession(jsonRequest(http.MethodPost, "/totp", `{"token":"1"}`), "tok-8"), &ProxyUser{ID: 8})
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.TOTPVerify(rec, other)
|
||||||
|
if rec.Code == http.StatusTooManyRequests {
|
||||||
|
t.Fatal("another user shares the first user's TOTP limit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTOTPHandlersNeedASessionUser(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
for name, handler := range map[string]http.HandlerFunc{
|
||||||
|
"status": service.TOTPStatus, "initiate": service.TOTPInitiate, "verify": service.TOTPVerify, "disable": service.TOTPDisable,
|
||||||
|
} {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
handler(rec, jsonRequest(http.MethodPost, "/totp", `{}`))
|
||||||
|
if rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("%s without a session user: status = %d, want 401", name, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(guard.calls) != 0 {
|
||||||
|
t.Fatal("an unauthenticated TOTP request reached AuthGuard")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTOTPInitiateAndStatus(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("POST /api/totp/enable", http.StatusOK, map[string]any{"secret": "JBSWY3DP", "otpauth_url": "otpauth://totp/x", "enabled": false})
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.TOTPStatus(rec, withUser(httptest.NewRequest(http.MethodGet, "/totp/status", nil), &ProxyUser{ID: 1, MFAEnabled: true}))
|
||||||
|
if body := decodeBody(t, rec); body["enabled"] != true || body["mfaEnabled"] != true {
|
||||||
|
t.Fatalf("status = %v", body)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
service.TOTPInitiate(rec, withUser(withSession(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), "tok"), &ProxyUser{ID: 1}))
|
||||||
|
data := decodeBody(t, rec)["data"].(map[string]any)
|
||||||
|
if rec.Code != http.StatusOK || data["secret"] != "JBSWY3DP" || data["otpauthUrl"] != "otpauth://totp/x" {
|
||||||
|
t.Fatalf("initiate status = %d, data %v", rec.Code, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
service.TOTPInitiate(rec, withUser(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), &ProxyUser{ID: 1, MFAEnabled: true}))
|
||||||
|
if rec.Code != http.StatusConflict {
|
||||||
|
t.Fatalf("initiate while enabled status = %d, want 409", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
cross := withUser(httptest.NewRequest(http.MethodPost, "/totp/initiate", nil), &ProxyUser{ID: 1})
|
||||||
|
cross.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
service.TOTPInitiate(rec, cross)
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("cross-site initiate status = %d, want 403", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpdateMeValidatesAndForwardsToAuthGuard(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.handle("POST /api/login", func(w http.ResponseWriter, _ map[string]any) {
|
||||||
|
w.Header().Add("Set-Cookie", authclient.DefaultCookieName+"=reauth-token; Path=/; HttpOnly")
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
|
||||||
|
})
|
||||||
|
guard.reply("POST /api/logout", http.StatusOK, map[string]any{"ok": true})
|
||||||
|
guard.reply("PUT /api/admin/users/7", http.StatusOK, map[string]any{})
|
||||||
|
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 7, "username": "boss", "email": "boss@example.com", "role": "admin"}})
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
update := func(user *ProxyUser, body string) *httptest.ResponseRecorder {
|
||||||
|
req := withSession(jsonRequest(http.MethodPut, "/auth/me", body), "tok-7")
|
||||||
|
if user != nil {
|
||||||
|
req = withUser(req, user)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.UpdateMe(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
manager := &ProxyUser{ID: 7, Username: "boss", Role: "admin", MFAEnabled: true}
|
||||||
|
|
||||||
|
if rec := update(nil, `{}`); rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("no session user: status = %d, want 401", rec.Code)
|
||||||
|
}
|
||||||
|
if rec := update(&ProxyUser{ID: 7, Role: "user"}, `{"email":"a@b.com"}`); rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("ordinary user: status = %d, want 403", rec.Code)
|
||||||
|
}
|
||||||
|
for name, body := range map[string]string{
|
||||||
|
"bad email": `{"email":"nope","username":"boss"}`,
|
||||||
|
"at in username": `{"email":"a@b.com","username":"a@b.com"}`,
|
||||||
|
"short password": `{"email":"a@b.com","username":"boss","password":"short"}`,
|
||||||
|
"long password": `{"email":"a@b.com","username":"boss","password":"` + strings.Repeat("a", 73) + `"}`,
|
||||||
|
"missing current password": `{"email":"a@b.com","username":"boss","password":"new-password"}`,
|
||||||
|
"missing current totp": `{"email":"a@b.com","username":"boss","password":"new-password","currentPassword":"current-password"}`,
|
||||||
|
"not JSON": `nope`,
|
||||||
|
} {
|
||||||
|
if rec := update(manager, body); rec.Code != http.StatusBadRequest {
|
||||||
|
t.Errorf("%s: status = %d, want 400", name, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(guard.callsTo("PUT /api/admin/users/7")) != 0 {
|
||||||
|
t.Fatal("a refused update reached AuthGuard")
|
||||||
|
}
|
||||||
|
|
||||||
|
rec := update(manager, `{"email":"Boss@Example.com","username":" boss "}`)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("update status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
calls := guard.callsTo("PUT /api/admin/users/7")
|
||||||
|
if len(calls) != 1 || calls[0].Authorization != "Bearer tok-7" || calls[0].Body["email"] != "boss@example.com" || calls[0].Body["username"] != "boss" {
|
||||||
|
t.Fatalf("AuthGuard update = %+v", calls)
|
||||||
|
}
|
||||||
|
if _, sent := calls[0].Body["password"]; sent {
|
||||||
|
t.Fatal("an update without a password sent one to AuthGuard")
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = update(manager, `{"email":"boss@example.com","username":"boss","password":"new-password","currentPassword":"current-password","totpToken":"123456"}`)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("password update status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
loginCalls := guard.callsTo("POST /api/login")
|
||||||
|
if len(loginCalls) != 1 || loginCalls[0].Body["username_or_email"] != "boss" || loginCalls[0].Body["password"] != "current-password" || loginCalls[0].Body["totp_token"] != "123456" {
|
||||||
|
t.Fatalf("reauthentication request = %+v", loginCalls)
|
||||||
|
}
|
||||||
|
calls = guard.callsTo("PUT /api/admin/users/7")
|
||||||
|
if len(calls) != 2 || calls[1].Body["password"] != "new-password" {
|
||||||
|
t.Fatalf("password update request = %+v", calls)
|
||||||
|
}
|
||||||
|
if _, sent := calls[1].Body["currentPassword"]; sent {
|
||||||
|
t.Fatal("current password was forwarded to the managed-user API")
|
||||||
|
}
|
||||||
|
if _, sent := calls[1].Body["totpToken"]; sent {
|
||||||
|
t.Fatal("TOTP code was forwarded to the managed-user API")
|
||||||
|
}
|
||||||
|
logoutCalls := guard.callsTo("POST /api/logout")
|
||||||
|
if len(logoutCalls) != 1 || logoutCalls[0].Authorization != "Bearer reauth-token" {
|
||||||
|
t.Fatalf("temporary login session was not removed: %+v", logoutCalls)
|
||||||
|
}
|
||||||
|
if user := decodeBody(t, rec)["user"].(map[string]any); user["username"] != "boss" {
|
||||||
|
t.Fatalf("response user = %v", user)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagedUserHandlers(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("GET /api/admin/users", http.StatusOK, map[string]any{"users": []map[string]any{
|
||||||
|
{"id": 1, "username": "root", "email": "root@example.com", "role": "superadmin"},
|
||||||
|
{"id": 2, "username": "pat", "email": "pat@example.com", "role": "weird-role"},
|
||||||
|
}})
|
||||||
|
guard.reply("POST /api/admin/users", http.StatusCreated, map[string]any{"user": map[string]any{"id": 3, "username": "new", "email": "new@example.com", "role": "admin"}})
|
||||||
|
guard.reply("PUT /api/admin/users/2", http.StatusOK, map[string]any{})
|
||||||
|
guard.reply("DELETE /api/admin/users/2", http.StatusOK, map[string]any{})
|
||||||
|
guard.reply("DELETE /api/admin/users/1", http.StatusForbidden, map[string]any{"error": "the superadmin cannot be deleted"})
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
|
||||||
|
t.Run("list normalizes roles", func(t *testing.T) {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.ManagedUsers(rec, withSession(httptest.NewRequest(http.MethodGet, "/users", nil), "tok"))
|
||||||
|
var users []map[string]any
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &users); err != nil || len(users) != 2 {
|
||||||
|
t.Fatalf("users = %s, %v", rec.Body.String(), err)
|
||||||
|
}
|
||||||
|
if users[0]["role"] != "superadmin" || users[1]["role"] != "user" {
|
||||||
|
t.Fatalf("roles = %v, %v; want superadmin and the unknown role reduced to user", users[0]["role"], users[1]["role"])
|
||||||
|
}
|
||||||
|
if call := guard.callsTo("GET /api/admin/users")[0]; call.Authorization != "Bearer tok" {
|
||||||
|
t.Fatalf("list call = %+v, want the session token", call)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("create forwards the role", func(t *testing.T) {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := withSession(jsonRequest(http.MethodPost, "/users", `{"email":"new@example.com","username":"new","password":"password123","role":" admin "}`), "tok")
|
||||||
|
service.ManagedCreateUser(rec, req)
|
||||||
|
if rec.Code != http.StatusCreated || decodeBody(t, rec)["role"] != "admin" {
|
||||||
|
t.Fatalf("create status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if body := guard.callsTo("POST /api/admin/users")[0].Body; body["role"] != "admin" || body["username"] != "new" {
|
||||||
|
t.Fatalf("create body = %v", body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("update answers with the refreshed user, or 404", func(t *testing.T) {
|
||||||
|
req := withSession(jsonRequest(http.MethodPut, "/users/2", `{"username":"pat2"}`), "tok")
|
||||||
|
req.SetPathValue("id", "2")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.ManagedUpdateUser(rec, req)
|
||||||
|
if rec.Code != http.StatusOK || decodeBody(t, rec)["username"] != "pat" {
|
||||||
|
t.Fatalf("update status = %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
missing := withSession(jsonRequest(http.MethodPut, "/users/9", `{}`), "tok")
|
||||||
|
missing.SetPathValue("id", "9")
|
||||||
|
guard.reply("PUT /api/admin/users/9", http.StatusOK, map[string]any{})
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
service.ManagedUpdateUser(rec, missing)
|
||||||
|
if rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("update of an id that is not listed: status = %d, want 404", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("delete", func(t *testing.T) {
|
||||||
|
del := func(id string, header http.Header) *httptest.ResponseRecorder {
|
||||||
|
req := withSession(httptest.NewRequest(http.MethodDelete, "/users/"+id, nil), "tok")
|
||||||
|
req.SetPathValue("id", id)
|
||||||
|
for key, values := range header {
|
||||||
|
req.Header[key] = values
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.ManagedDeleteUser(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
if rec := del("2", nil); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("delete status = %d", rec.Code)
|
||||||
|
}
|
||||||
|
if rec := del("1", nil); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "superadmin") {
|
||||||
|
t.Fatalf("AuthGuard refusal status = %d, body %s; want it forwarded", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if rec := del("abc", nil); rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("bad id status = %d, want 400", rec.Code)
|
||||||
|
}
|
||||||
|
before := len(guard.callsTo("DELETE /api/admin/users/2"))
|
||||||
|
if rec := del("2", http.Header{"Sec-Fetch-Site": {"cross-site"}}); rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("cross-site delete status = %d, want 403", rec.Code)
|
||||||
|
}
|
||||||
|
if len(guard.callsTo("DELETE /api/admin/users/2")) != before {
|
||||||
|
t.Fatal("a cross-site delete reached AuthGuard")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogoutForwardsTheTokenAndClearsCookies(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.handle("POST /api/logout", func(w http.ResponseWriter, _ map[string]any) {
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "", Path: "/", MaxAge: -1})
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{}`))
|
||||||
|
})
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Logout(rec, withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "tok"))
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("logout status = %d", rec.Code)
|
||||||
|
}
|
||||||
|
if calls := guard.callsTo("POST /api/logout"); len(calls) != 1 || calls[0].Authorization != "Bearer tok" {
|
||||||
|
t.Fatalf("logout calls = %+v", calls)
|
||||||
|
}
|
||||||
|
cleared := false
|
||||||
|
for _, cookie := range rec.Result().Cookies() {
|
||||||
|
if cookie.Name == "auth_session" && cookie.MaxAge < 0 {
|
||||||
|
cleared = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !cleared {
|
||||||
|
t.Fatalf("cookies = %v, want the session cookie cleared", rec.Result().Cookies())
|
||||||
|
}
|
||||||
|
|
||||||
|
guard.reply("POST /api/logout", http.StatusUnauthorized, map[string]any{"error": "expired"})
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
service.Logout(rec, withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "stale"))
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("logout of an expired session status = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
cross := withSession(httptest.NewRequest(http.MethodPost, "/auth/logout", nil), "tok")
|
||||||
|
cross.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
service.Logout(rec, cross)
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("cross-site logout status = %d, want 403", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGatingMiddlewaresResolveSessionsThroughAuthGuard(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
roles := map[string]string{"user-tok": "user", "admin-tok": "admin", "mod-tok": "moderator"}
|
||||||
|
service, _ := guard.service(t)
|
||||||
|
served := func(role string) {
|
||||||
|
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 5, "username": "u", "role": role}})
|
||||||
|
}
|
||||||
|
ok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) })
|
||||||
|
run := func(mw func(http.Handler) http.Handler, token string) int {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/x", nil)
|
||||||
|
if token != "" {
|
||||||
|
withSession(req, token)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
mw(ok).ServeHTTP(rec, req)
|
||||||
|
return rec.Code
|
||||||
|
}
|
||||||
|
|
||||||
|
guard.reply("GET /api/me", http.StatusUnauthorized, map[string]any{"error": "no session"})
|
||||||
|
if code := run(service.Require, ""); code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("Require without a cookie = %d, want 401", code)
|
||||||
|
}
|
||||||
|
if code := run(service.Require, "stale"); code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("Require with an expired session = %d, want 401", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
for token, role := range roles {
|
||||||
|
served(role)
|
||||||
|
wantAdmin := http.StatusForbidden
|
||||||
|
if role == "admin" || role == "moderator" {
|
||||||
|
wantAdmin = http.StatusNoContent
|
||||||
|
}
|
||||||
|
wantManager := http.StatusForbidden
|
||||||
|
if role == "admin" {
|
||||||
|
wantManager = http.StatusNoContent
|
||||||
|
}
|
||||||
|
if code := run(service.Require, token); code != http.StatusNoContent {
|
||||||
|
t.Errorf("Require as %s = %d, want 204", role, code)
|
||||||
|
}
|
||||||
|
if code := run(service.RequireAdmin, token); code != wantAdmin {
|
||||||
|
t.Errorf("RequireAdmin as %s = %d, want %d", role, code, wantAdmin)
|
||||||
|
}
|
||||||
|
if code := run(service.RequireUserManager, token); code != wantManager {
|
||||||
|
t.Errorf("RequireUserManager as %s = %d, want %d", role, code, wantManager)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
guard.server.Close()
|
||||||
|
if code := run(service.Require, "any-token"); code != http.StatusInternalServerError {
|
||||||
|
t.Fatalf("Require with AuthGuard down = %d, want 500", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMeReportsTheSessionUserAndLoginRequirement(t *testing.T) {
|
||||||
|
guard := newFakeAuthGuard(t)
|
||||||
|
guard.reply("GET /api/me", http.StatusOK, map[string]any{"user": map[string]any{"id": 5, "username": "u", "email": "u@example.com", "role": "user"}})
|
||||||
|
service, store := guard.service(t)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Me(rec, withSession(httptest.NewRequest(http.MethodGet, "/auth/me", nil), "tok"))
|
||||||
|
body := decodeBody(t, rec)
|
||||||
|
if rec.Code != http.StatusOK || body["authRequired"] != true || body["user"].(map[string]any)["username"] != "u" {
|
||||||
|
t.Fatalf("me status = %d, body %v", rec.Code, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The login setting is cached for a moment, so the second answer comes from a fresh Service.
|
||||||
|
service, store = guard.service(t)
|
||||||
|
store.loginRequired = false
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
service.Me(rec, httptest.NewRequest(http.MethodGet, "/auth/me", nil))
|
||||||
|
body = decodeBody(t, rec)
|
||||||
|
if body["authRequired"] != false || body["user"].(map[string]any)["username"] != "Admin" {
|
||||||
|
t.Fatalf("me with login off = %v, want the local admin and authRequired false", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
+143
-3
@@ -4,7 +4,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fakeProxyStore is a minimal in-memory ProxyStore for constructing a
|
// fakeProxyStore is a minimal in-memory ProxyStore for constructing a
|
||||||
@@ -95,7 +98,10 @@ func TestLoginDisabledUsesAdminIdentityWithoutCredentials(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestInternalLoginOverrideWorksWithNoOpStore(t *testing.T) {
|
// TestNoOpStoreDoesNotKeepAProcessLocalLoginOverride checks that the login-required setting is read
|
||||||
|
// from the store on each call. A store that discards writes keeps login required everywhere, rather
|
||||||
|
// than letting one process diverge from the rest.
|
||||||
|
func TestNoOpStoreDoesNotKeepAProcessLocalLoginOverride(t *testing.T) {
|
||||||
store := &noOpLoginProxyStore{fakeProxyStore: fakeProxyStore{loginRequired: true}}
|
store := &noOpLoginProxyStore{fakeProxyStore: fakeProxyStore{loginRequired: true}}
|
||||||
service := NewWithStore(store, "session", false, "", "testproject")
|
service := NewWithStore(store, "session", false, "", "testproject")
|
||||||
if err := service.SetLoginRequired(context.Background(), false); err != nil {
|
if err := service.SetLoginRequired(context.Background(), false); err != nil {
|
||||||
@@ -103,8 +109,142 @@ func TestInternalLoginOverrideWorksWithNoOpStore(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
user, err := service.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
|
user, err := service.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
|
||||||
if err != nil || user == nil || user.Username != "Admin" {
|
if err != nil || user != nil {
|
||||||
t.Fatalf("no-op store override resolved user=%+v err=%v, want Admin", user, err)
|
t.Fatalf("no-op store resolved user=%+v err=%v, want no user while login is still required", user, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBodylessStateChangesRefuseCrossSite checks the routes that take no JSON body, which
|
||||||
|
// decodeProxyJSON cannot guard, refuse a request the browser marks as cross-site.
|
||||||
|
func TestBodylessStateChangesRefuseCrossSite(t *testing.T) {
|
||||||
|
service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject")
|
||||||
|
handlers := map[string]http.HandlerFunc{
|
||||||
|
"logout": service.Logout,
|
||||||
|
"totp initiate": service.TOTPInitiate,
|
||||||
|
"delete user": service.ManagedDeleteUser,
|
||||||
|
}
|
||||||
|
for name, handler := range handlers {
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/", nil)
|
||||||
|
req.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
handler(rec, req)
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Errorf("%s with Sec-Fetch-Site: cross-site returned %d, want 403", name, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetLoginRequiredNeedsAStore(t *testing.T) {
|
||||||
|
service := NewWithStore(nil, "session", false, "", "testproject")
|
||||||
|
if err := service.SetLoginRequired(context.Background(), false); err == nil {
|
||||||
|
t.Fatal("SetLoginRequired with no store succeeded, want an error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeProxyJSONRequiresAJSONBodyAndRefusesCrossSite(t *testing.T) {
|
||||||
|
decode := func(contentType, fetchSite string) error {
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"loginRequired":true}`))
|
||||||
|
if contentType != "" {
|
||||||
|
req.Header.Set("Content-Type", contentType)
|
||||||
|
}
|
||||||
|
if fetchSite != "" {
|
||||||
|
req.Header.Set("Sec-Fetch-Site", fetchSite)
|
||||||
|
}
|
||||||
|
var input struct {
|
||||||
|
LoginRequired bool `json:"loginRequired"`
|
||||||
|
}
|
||||||
|
return decodeProxyJSON(req, &input)
|
||||||
|
}
|
||||||
|
if err := decode("application/json", ""); err != nil {
|
||||||
|
t.Fatalf("application/json body refused: %v", err)
|
||||||
|
}
|
||||||
|
if err := decode("application/json; charset=utf-8", "same-site"); err != nil {
|
||||||
|
t.Fatalf("same-site application/json body refused: %v", err)
|
||||||
|
}
|
||||||
|
for _, contentType := range []string{"", "text/plain", "application/x-www-form-urlencoded", "multipart/form-data; boundary=x"} {
|
||||||
|
if err := decode(contentType, ""); err == nil {
|
||||||
|
t.Errorf("Content-Type %q accepted, want refused", contentType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := decode("application/json", "cross-site"); err == nil {
|
||||||
|
t.Error("cross-site application/json body accepted, want refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSignupIsRefusedWhileLoginIsNotRequired(t *testing.T) {
|
||||||
|
store := &fakeProxyStore{loginRequired: false}
|
||||||
|
service := NewWithStore(store, "session", false, "", "testproject")
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"email":"a@b.com","username":"a","password":"password123"}`))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Signup(rec, req)
|
||||||
|
if rec.Code != http.StatusConflict {
|
||||||
|
t.Fatalf("signup with login off status = %d, want 409", rec.Code)
|
||||||
|
}
|
||||||
|
if store.setupClaimed {
|
||||||
|
t.Fatal("refused signup still claimed the setup flag")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginIsRateLimitedPerAccount(t *testing.T) {
|
||||||
|
service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject")
|
||||||
|
post := func() int {
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"identifier":"Victim","password":"guess"}`))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
service.Login(rec, req)
|
||||||
|
return rec.Code
|
||||||
|
}
|
||||||
|
for i := 0; i < loginAccountLimit; i++ {
|
||||||
|
if code := post(); code == http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("attempt %d refused before the limit", i+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code := post(); code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("attempt past the limit status = %d, want 429", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAttemptLimiterWindowAndTableBound(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
limiter := newAttemptLimiter(time.Minute, 2)
|
||||||
|
if !limiter.allow("k", now) || !limiter.allow("k", now) {
|
||||||
|
t.Fatal("attempts within the limit were refused")
|
||||||
|
}
|
||||||
|
if limiter.allow("k", now) {
|
||||||
|
t.Fatal("attempt past the limit was allowed")
|
||||||
|
}
|
||||||
|
if !limiter.allow("k", now.Add(time.Minute)) {
|
||||||
|
t.Fatal("limit did not reset after the window")
|
||||||
|
}
|
||||||
|
|
||||||
|
full := newAttemptLimiter(time.Hour, 1)
|
||||||
|
for i := 0; i < maxTrackedAttemptKeys; i++ {
|
||||||
|
full.allow(strconv.Itoa(i), now)
|
||||||
|
}
|
||||||
|
if full.allow("new-key", now) {
|
||||||
|
t.Fatal("a new key was tracked past the table bound")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateProxyPasswordRefusesMoreThan72Bytes(t *testing.T) {
|
||||||
|
if err := validateProxyPassword(strings.Repeat("a", 72)); err != nil {
|
||||||
|
t.Fatalf("72-byte password refused: %v", err)
|
||||||
|
}
|
||||||
|
if err := validateProxyPassword(strings.Repeat("a", 73)); err == nil {
|
||||||
|
t.Fatal("73-byte password accepted, want refused")
|
||||||
|
}
|
||||||
|
if err := validateProxyPassword(strings.Repeat("é", 40)); err == nil {
|
||||||
|
t.Fatal("80-byte multi-byte password accepted, want refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeProxyUsernameRefusesAt(t *testing.T) {
|
||||||
|
if _, err := normalizeProxyUsername("name@example.com"); err == nil {
|
||||||
|
t.Fatal("username containing @ accepted")
|
||||||
|
}
|
||||||
|
if got, err := normalizeProxyUsername(" plain "); err != nil || got != "plain" {
|
||||||
|
t.Fatalf("plain username = %q, %v", got, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Attempt limits for the credential endpoints (login and the TOTP verify/disable routes). Each key
|
||||||
|
// may make limit attempts per window; further attempts are refused until the window ends. The
|
||||||
|
// counters live in this process, and AuthGuard's own limits still apply on top.
|
||||||
|
const (
|
||||||
|
attemptWindow = 15 * time.Minute
|
||||||
|
loginAccountLimit = 10
|
||||||
|
loginClientLimit = 200
|
||||||
|
totpAttemptLimit = 5
|
||||||
|
maxTrackedAttemptKeys = 10000
|
||||||
|
)
|
||||||
|
|
||||||
|
type attemptCounter struct {
|
||||||
|
windowStart time.Time
|
||||||
|
count int
|
||||||
|
}
|
||||||
|
|
||||||
|
// attemptLimiter is a fixed-window counter keyed by an account, a client address or a user.
|
||||||
|
type attemptLimiter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
window time.Duration
|
||||||
|
limit int
|
||||||
|
counts map[string]attemptCounter
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAttemptLimiter(window time.Duration, limit int) *attemptLimiter {
|
||||||
|
return &attemptLimiter{window: window, limit: limit, counts: make(map[string]attemptCounter)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// allow records one attempt for key at time now and reports whether it is within the limit. When
|
||||||
|
// the table is full of live keys, a new key is refused rather than tracked, so flooding distinct
|
||||||
|
// keys cannot grow memory without bound.
|
||||||
|
func (l *attemptLimiter) allow(key string, now time.Time) bool {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
counter, tracked := l.counts[key]
|
||||||
|
if !tracked && len(l.counts) >= maxTrackedAttemptKeys {
|
||||||
|
for existing, state := range l.counts {
|
||||||
|
if now.Sub(state.windowStart) >= l.window {
|
||||||
|
delete(l.counts, existing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(l.counts) >= maxTrackedAttemptKeys {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if counter.windowStart.IsZero() || now.Sub(counter.windowStart) >= l.window {
|
||||||
|
counter = attemptCounter{windowStart: now}
|
||||||
|
}
|
||||||
|
counter.count++
|
||||||
|
l.counts[key] = counter
|
||||||
|
return counter.count <= l.limit
|
||||||
|
}
|
||||||
+179
-141
@@ -7,6 +7,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -47,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,6 +64,17 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
|||||||
return errors.New("auth postgres pool is nil")
|
return errors.New("auth postgres pool is nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Only a table that predates the role column needs its oldest account promoted, so the
|
||||||
|
// promotion below runs once, in the migration that adds the column.
|
||||||
|
var roleColumnMissing bool
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
SELECT NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_schema = current_schema() AND table_name = 'auth_users' AND column_name = 'role'
|
||||||
|
)`).Scan(&roleColumnMissing); err != nil {
|
||||||
|
return fmt.Errorf("check auth schema: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
_, err := pool.Exec(ctx, `
|
_, err := pool.Exec(ctx, `
|
||||||
CREATE TABLE IF NOT EXISTS auth_users (
|
CREATE TABLE IF NOT EXISTS auth_users (
|
||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
@@ -75,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
|
||||||
@@ -83,15 +93,13 @@ 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
|
||||||
-- alone does not count, only a successful POST /api/login) and has no
|
-- alone does not count, only a successful POST /api/login) and has no
|
||||||
-- DEFAULT, unlike every other column here.
|
-- DEFAULT, unlike every other column here.
|
||||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
|
||||||
UPDATE auth_users SET role = 'superadmin'
|
|
||||||
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
|
|
||||||
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
|
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
|
||||||
ON auth_users (lower(email)) WHERE email <> '';
|
ON auth_users (lower(email)) WHERE email <> '';
|
||||||
|
|
||||||
@@ -109,6 +117,20 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
|||||||
return fmt.Errorf("ensure auth schema: %w", err)
|
return fmt.Errorf("ensure auth schema: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := ensureUsernameCaseIndex(ctx, pool); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if roleColumnMissing {
|
||||||
|
if _, err := pool.Exec(ctx, `
|
||||||
|
UPDATE auth_users SET role = 'superadmin'
|
||||||
|
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
|
||||||
|
`); err != nil {
|
||||||
|
return fmt.Errorf("promote oldest auth user: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if options.SingleUser {
|
if options.SingleUser {
|
||||||
if _, err := pool.Exec(ctx, `
|
if _, err := pool.Exec(ctx, `
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
||||||
@@ -126,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)
|
||||||
}
|
}
|
||||||
@@ -153,11 +169,53 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ensureUsernameCaseIndex makes usernames unique ignoring case, so "Admin" and "admin" cannot both
|
||||||
|
// be registered. The index is created only while no such pair exists: a database that already
|
||||||
|
// holds one still starts, logs the clashing names, and gets the index on the first start after an
|
||||||
|
// operator has renamed or removed one of each pair.
|
||||||
|
func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error {
|
||||||
|
rows, err := pool.Query(ctx, `
|
||||||
|
SELECT min(username) FROM auth_users GROUP BY lower(username) HAVING count(*) > 1
|
||||||
|
ORDER BY 1 LIMIT 10
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("check duplicate usernames: %w", err)
|
||||||
|
}
|
||||||
|
var clashing []string
|
||||||
|
for rows.Next() {
|
||||||
|
var name string
|
||||||
|
if err := rows.Scan(&name); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return fmt.Errorf("check duplicate usernames: %w", err)
|
||||||
|
}
|
||||||
|
clashing = append(clashing, name)
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return fmt.Errorf("check duplicate usernames: %w", err)
|
||||||
|
}
|
||||||
|
if len(clashing) > 0 {
|
||||||
|
log.Printf("[auth] usernames that differ only by case exist (%q); the case-insensitive username index was not created. Rename or remove one account of each pair and restart.", clashing)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if _, err := pool.Exec(ctx, `CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx ON auth_users (lower(username))`); err != nil {
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||||
|
// An account was registered between the check and the index build; the next start retries.
|
||||||
|
log.Printf("[auth] the case-insensitive username index was not created because a clashing username was just added: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("ensure username index: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// TOTPState is the private provisioning state for one account. Secret must
|
// TOTPState is the private provisioning state for one account. Secret must
|
||||||
// never be included in an API response.
|
// never be included in an API response.
|
||||||
type TOTPState struct {
|
type TOTPState struct {
|
||||||
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.
|
||||||
@@ -166,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
|
||||||
}
|
}
|
||||||
@@ -176,28 +234,61 @@ func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, erro
|
|||||||
return state, nil
|
return state, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetTOTPSecret stores a pending secret without enabling two-factor auth.
|
// SetTOTPSecret stores a pending secret without enabling two-factor auth. It refuses while TOTP is
|
||||||
|
// already enabled, so a replaced secret cannot silently switch the second factor off.
|
||||||
func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) error {
|
func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) error {
|
||||||
if err := s.validate(); err != nil {
|
if err := s.validate(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2`, secret, userID)
|
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, 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)
|
||||||
}
|
}
|
||||||
|
if tag.RowsAffected() == 0 {
|
||||||
|
state, err := s.GetTOTPState(ctx, userID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if state.Enabled {
|
||||||
|
return ErrTOTPAlreadyEnabled
|
||||||
|
}
|
||||||
|
}
|
||||||
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.
|
||||||
@@ -205,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)
|
||||||
}
|
}
|
||||||
@@ -230,6 +321,9 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st
|
|||||||
if err := s.validate(); err != nil {
|
if err := s.validate(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := validateCredentials(username, passwordHash); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
var user User
|
var user User
|
||||||
err := s.pool.QueryRow(ctx, `
|
err := s.pool.QueryRow(ctx, `
|
||||||
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||||
@@ -255,10 +349,19 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User,
|
|||||||
if err := s.validate(); err != nil {
|
if err := s.validate(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
// Usernames are tried before emails, so an identifier resolves to one account in a fixed order.
|
||||||
|
user, err := s.find(ctx, `
|
||||||
|
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
|
||||||
|
FROM auth_users
|
||||||
|
WHERE username = $1
|
||||||
|
`, identifier)
|
||||||
|
if err != nil || user != nil {
|
||||||
|
return user, err
|
||||||
|
}
|
||||||
return s.find(ctx, `
|
return s.find(ctx, `
|
||||||
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
|
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
|
||||||
FROM auth_users
|
FROM auth_users
|
||||||
WHERE username = $1 OR lower(email) = lower($1)
|
WHERE lower(email) = lower($1)
|
||||||
`, identifier)
|
`, identifier)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,17 +381,40 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
|
|||||||
if err := s.validate(); err != nil {
|
if err := s.validate(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err := validateCredentials(username, passwordHash); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
_, err := s.pool.Exec(ctx, `
|
_, err := s.pool.Exec(ctx, `
|
||||||
UPDATE auth_users
|
UPDATE auth_users
|
||||||
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
||||||
WHERE id = $4
|
WHERE id = $4
|
||||||
`, username, email, passwordHash, id)
|
`, username, email, passwordHash, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||||
|
return ErrUserExists
|
||||||
|
}
|
||||||
return fmt.Errorf("update auth credentials: %w", err)
|
return fmt.Errorf("update auth credentials: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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) {
|
||||||
@@ -319,6 +445,9 @@ func (s *Store) CreateManagedUser(ctx context.Context, username, email, password
|
|||||||
if err := s.validate(); err != nil {
|
if err := s.validate(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := validateCredentials(username, passwordHash); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
role = NormalizeRole(string(role))
|
role = NormalizeRole(string(role))
|
||||||
var user User
|
var user User
|
||||||
err := s.pool.QueryRow(ctx, `
|
err := s.pool.QueryRow(ctx, `
|
||||||
@@ -343,6 +472,9 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
|
|||||||
if err := s.validate(); err != nil {
|
if err := s.validate(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err := validateCredentials(username, passwordHash); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if role == nil {
|
if role == nil {
|
||||||
return s.UpdateCredentials(ctx, id, username, email, passwordHash)
|
return s.UpdateCredentials(ctx, id, username, email, passwordHash)
|
||||||
}
|
}
|
||||||
@@ -353,6 +485,10 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
|
|||||||
WHERE id = $5
|
WHERE id = $5
|
||||||
`, username, email, passwordHash, *role, id)
|
`, username, email, passwordHash, *role, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||||
|
return ErrUserExists
|
||||||
|
}
|
||||||
return fmt.Errorf("update managed auth user: %w", err)
|
return fmt.Errorf("update managed auth user: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -445,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 {
|
||||||
@@ -466,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
|
||||||
@@ -520,113 +642,29 @@ 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
|
var ErrUserExists = errors.New("auth user already exists")
|
||||||
// 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
|
// ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on.
|
||||||
// deployment's accounts on upgrade.
|
var ErrTOTPAlreadyEnabled = errors.New("auth: TOTP is already enabled; disable it before setting a new secret")
|
||||||
func (s *Store) SetUserProjects(ctx context.Context, userID int64, projects []string) error {
|
|
||||||
if err := s.validate(); err != nil {
|
// ErrEmptyPasswordHash is returned when a credential write has no password hash.
|
||||||
return err
|
var ErrEmptyPasswordHash = errors.New("auth: password hash is required")
|
||||||
|
|
||||||
|
// ErrInvalidUsername is returned for a username containing "@", which would be read as an email.
|
||||||
|
var ErrInvalidUsername = errors.New("auth: username cannot contain @")
|
||||||
|
|
||||||
|
// validateCredentials refuses a credential write that would leave an account without a password
|
||||||
|
// hash, or that stores a username which could be mistaken for another account's email.
|
||||||
|
func validateCredentials(username, passwordHash string) error {
|
||||||
|
if passwordHash == "" {
|
||||||
|
return ErrEmptyPasswordHash
|
||||||
}
|
}
|
||||||
tx, err := s.pool.Begin(ctx)
|
if strings.Contains(username, "@") {
|
||||||
if err != nil {
|
return ErrInvalidUsername
|
||||||
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
|
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")
|
|
||||||
|
|
||||||
func (s *Store) validate() error {
|
func (s *Store) validate() error {
|
||||||
if s == nil || s.pool == nil {
|
if s == nil || s.pool == nil {
|
||||||
return errors.New("auth store has no postgres pool")
|
return errors.New("auth store has no postgres pool")
|
||||||
|
|||||||
@@ -2,10 +2,13 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -119,3 +122,135 @@ func TestStoreIntegration(t *testing.T) {
|
|||||||
t.Fatalf("FindByID() after UpdateLastLogin = %+v, want LastLoginAt set", afterLogin)
|
t.Fatalf("FindByID() after UpdateLastLogin = %+v, want LastLoginAt set", afterLogin)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// openScratchStore opens DATABASE_URL (a scratch database, see TestStoreIntegration), applies the
|
||||||
|
// schema and removes every account before and after the test.
|
||||||
|
func openScratchStore(t *testing.T) (context.Context, *pgxpool.Pool, *Store) {
|
||||||
|
t.Helper()
|
||||||
|
url := os.Getenv("DATABASE_URL")
|
||||||
|
if url == "" {
|
||||||
|
t.Skip("DATABASE_URL not set; skipping Postgres integration test")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open pool: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(pool.Close)
|
||||||
|
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
|
||||||
|
t.Fatalf("EnsureSchema() error = %v", err)
|
||||||
|
}
|
||||||
|
store := NewStore(pool)
|
||||||
|
if err := store.DeleteAllUsers(ctx); err != nil {
|
||||||
|
t.Fatalf("DeleteAllUsers() (pre-test cleanup) error = %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if err := store.DeleteAllUsers(context.Background()); err != nil {
|
||||||
|
t.Logf("cleanup: DeleteAllUsers() error = %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return ctx, pool, store
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestStoreRefusesUsernamesThatDifferOnlyByCase covers the unique index on lower(username).
|
||||||
|
func TestStoreRefusesUsernamesThatDifferOnlyByCase(t *testing.T) {
|
||||||
|
ctx, _, store := openScratchStore(t)
|
||||||
|
hash, err := HashPassword("correct horse battery staple")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := store.CreateUser(ctx, "Admin", "", hash); err != nil {
|
||||||
|
t.Fatalf("CreateUser(Admin) error = %v", err)
|
||||||
|
}
|
||||||
|
if _, err := store.CreateUser(ctx, "admin", "", hash); !errors.Is(err, ErrUserExists) {
|
||||||
|
t.Fatalf("CreateUser(admin) error = %v, want ErrUserExists", err)
|
||||||
|
}
|
||||||
|
if _, err := store.CreateManagedUser(ctx, "ADMIN", "", hash, RoleUser); !errors.Is(err, ErrUserExists) {
|
||||||
|
t.Fatalf("CreateManagedUser(ADMIN) error = %v, want ErrUserExists", err)
|
||||||
|
}
|
||||||
|
bob, err := store.CreateUser(ctx, "bob", "", hash)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateUser(bob) error = %v", err)
|
||||||
|
}
|
||||||
|
if err := store.UpdateCredentials(ctx, bob.ID, "admin", "", hash); !errors.Is(err, ErrUserExists) {
|
||||||
|
t.Fatalf("UpdateCredentials(admin) error = %v, want ErrUserExists", err)
|
||||||
|
}
|
||||||
|
role := RoleUser
|
||||||
|
if err := store.UpdateUser(ctx, bob.ID, "Admin", "", hash, &role); !errors.Is(err, ErrUserExists) {
|
||||||
|
t.Fatalf("UpdateUser(Admin) error = %v, want ErrUserExists", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEnsureSchemaStartsWithExistingCaseVariantUsernames checks that a database already holding
|
||||||
|
// "Admin" and "admin" still starts, gets no index, and gets one after the pair is resolved.
|
||||||
|
func TestEnsureSchemaStartsWithExistingCaseVariantUsernames(t *testing.T) {
|
||||||
|
ctx, pool, store := openScratchStore(t)
|
||||||
|
if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS auth_users_username_lower_idx`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := pool.Exec(ctx, `INSERT INTO auth_users (username, password_hash) VALUES ('Admin', 'x'), ('admin', 'x')`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
indexExists := func() bool {
|
||||||
|
var exists bool
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'auth_users_username_lower_idx')`).Scan(&exists); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return exists
|
||||||
|
}
|
||||||
|
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
|
||||||
|
t.Fatalf("EnsureSchema() with clashing usernames error = %v, want it to start", err)
|
||||||
|
}
|
||||||
|
if indexExists() {
|
||||||
|
t.Fatal("the case-insensitive index was created over clashing usernames")
|
||||||
|
}
|
||||||
|
if err := store.DeleteAllUsers(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
|
||||||
|
t.Fatalf("EnsureSchema() after cleanup error = %v", err)
|
||||||
|
}
|
||||||
|
if !indexExists() {
|
||||||
|
t.Fatal("the case-insensitive index was not created once the clash was gone")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestStoreTOTPAndIdentifierPrimitives covers SetTOTPSecret refusing to replace an enabled second
|
||||||
|
// factor and FindByIdentifier trying usernames before emails.
|
||||||
|
func TestStoreTOTPAndIdentifierPrimitives(t *testing.T) {
|
||||||
|
ctx, pool, store := openScratchStore(t)
|
||||||
|
hash, err := HashPassword("correct horse battery staple")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
owner, err := store.CreateUser(ctx, "owner", "owner@example.com", hash)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := store.SetTOTPSecret(ctx, owner.ID, "JBSWY3DPEHPK3PXP"); err != nil {
|
||||||
|
t.Fatalf("SetTOTPSecret() while disabled error = %v", err)
|
||||||
|
}
|
||||||
|
if enabled, err := store.EnableTOTP(ctx, owner.ID, "JBSWY3DPEHPK3PXP", 123); err != nil || !enabled {
|
||||||
|
t.Fatalf("EnableTOTP() = %v, %v; want enabled", enabled, err)
|
||||||
|
}
|
||||||
|
if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) {
|
||||||
|
t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err)
|
||||||
|
}
|
||||||
|
if state, err := store.GetTOTPState(ctx, owner.ID); err != nil || !state.Enabled || state.Secret != "JBSWY3DPEHPK3PXP" {
|
||||||
|
t.Fatalf("TOTP state after a refused replace = %+v, %v; want the original secret still enabled", state, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A username equal to another account's email (a row written outside the store's validation)
|
||||||
|
// resolves to the username's own account, not to the email's owner.
|
||||||
|
if _, err := pool.Exec(ctx, `INSERT INTO auth_users (username, email, password_hash) VALUES ('owner@example.com', 'second@example.com', 'x')`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
found, err := store.FindByIdentifier(ctx, "owner@example.com")
|
||||||
|
if err != nil || found == nil || found.Username != "owner@example.com" {
|
||||||
|
t.Fatalf("FindByIdentifier() = %+v, %v; want the account whose username matches", found, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := store.UpdateCredentials(ctx, owner.ID, "owner", "owner@example.com", ""); !errors.Is(err, ErrEmptyPasswordHash) {
|
||||||
|
t.Fatalf("UpdateCredentials() with an empty hash error = %v, want ErrEmptyPasswordHash", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -19,7 +20,7 @@ func TestPasswordRoundTrip(t *testing.T) {
|
|||||||
if VerifyPassword(hash, "wrong password") {
|
if VerifyPassword(hash, "wrong password") {
|
||||||
t.Fatal("VerifyPassword() accepted the wrong password")
|
t.Fatal("VerifyPassword() accepted the wrong password")
|
||||||
}
|
}
|
||||||
if cost, err := bcrypt.Cost([]byte(hash)); err != nil || cost != BcryptCost {
|
if cost, err := bcrypt.Cost([]byte(strings.TrimPrefix(hash, bcryptScheme))); err != nil || cost != BcryptCost {
|
||||||
t.Fatalf("bcrypt cost = %d, error = %v; want %d", cost, err, BcryptCost)
|
t.Fatalf("bcrypt cost = %d, error = %v; want %d", cost, err, BcryptCost)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -67,3 +68,29 @@ func TestResetManagerExpiresCode(t *testing.T) {
|
|||||||
t.Fatal("Confirm() accepted an expired reset code")
|
t.Fatal("Confirm() accepted an expired reset code")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestValidateCredentialsRefusesEmptyHashAndAtUsername(t *testing.T) {
|
||||||
|
if err := validateCredentials("alice", ""); !errors.Is(err, ErrEmptyPasswordHash) {
|
||||||
|
t.Fatalf("empty hash error = %v, want ErrEmptyPasswordHash", err)
|
||||||
|
}
|
||||||
|
if err := validateCredentials("alice@example.com", "hash"); !errors.Is(err, ErrInvalidUsername) {
|
||||||
|
t.Fatalf("@ username error = %v, want ErrInvalidUsername", err)
|
||||||
|
}
|
||||||
|
if err := validateCredentials("alice", "hash"); err != nil {
|
||||||
|
t.Fatalf("valid credentials refused: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHashPasswordUsesTheSharedBcryptCost(t *testing.T) {
|
||||||
|
hash, err := HashPassword("correct horse battery staple")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cost, err := bcrypt.Cost([]byte(strings.TrimPrefix(hash, bcryptScheme)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if cost != BcryptCost {
|
||||||
|
t.Fatalf("bcrypt cost = %d, want %d", cost, BcryptCost)
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-8
@@ -20,7 +20,6 @@ const (
|
|||||||
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 {
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,6 +69,9 @@ type Client struct {
|
|||||||
// caller is treated as unrestricted; see AuthServer's project-scoping
|
// caller is treated as unrestricted; see AuthServer's project-scoping
|
||||||
// feature and WithProjectKey.
|
// feature and WithProjectKey.
|
||||||
projectKey string
|
projectKey string
|
||||||
|
validationMu sync.Mutex
|
||||||
|
validationCache map[[32]byte]validationCacheEntry
|
||||||
|
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
|
||||||
@@ -115,6 +118,8 @@ func New(baseURL string, opts ...Option) *Client {
|
|||||||
baseURL: normalizeBaseURL(baseURL),
|
baseURL: normalizeBaseURL(baseURL),
|
||||||
httpClient: &http.Client{Timeout: 5 * time.Second},
|
httpClient: &http.Client{Timeout: 5 * time.Second},
|
||||||
cookieName: DefaultCookieName,
|
cookieName: DefaultCookieName,
|
||||||
|
validationCache: make(map[[32]byte]validationCacheEntry),
|
||||||
|
profileCache: make(map[[32]byte]profileCacheEntry),
|
||||||
}
|
}
|
||||||
for _, opt := range opts {
|
for _, opt := range opts {
|
||||||
opt(c)
|
opt(c)
|
||||||
@@ -138,6 +143,7 @@ func (c *Client) SetBaseURL(baseURL string) {
|
|||||||
c.baseURLMu.Lock()
|
c.baseURLMu.Lock()
|
||||||
c.baseURL = normalized
|
c.baseURL = normalized
|
||||||
c.baseURLMu.Unlock()
|
c.baseURLMu.Unlock()
|
||||||
|
c.clearValidationCache()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) getBaseURL() string {
|
func (c *Client) getBaseURL() string {
|
||||||
@@ -155,6 +161,33 @@ func (c *Client) setProjectKeyHeader(req *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ForwardedForHeader carries the end user's address to AuthServer on the
|
||||||
|
// credential calls (see WithClientIP). AuthServer reads it only when the
|
||||||
|
// calling service's own address is listed in its TRUSTED_PROXIES, so sending
|
||||||
|
// it changes nothing for a deployment that has not opted in.
|
||||||
|
const ForwardedForHeader = "X-Forwarded-For"
|
||||||
|
|
||||||
|
type clientIPKey struct{}
|
||||||
|
|
||||||
|
// WithClientIP returns a context that makes Login, Register, TOTPVerify,
|
||||||
|
// TOTPDisable and the password-reset calls send ip as X-Forwarded-For, so
|
||||||
|
// AuthServer's per-address limits see the end user instead of this service.
|
||||||
|
// Pass an address the caller has already verified (for example
|
||||||
|
// auth.Service's trusted-proxy-aware client address), never a raw request
|
||||||
|
// header. Anything that is not an IP address is ignored.
|
||||||
|
func WithClientIP(ctx context.Context, ip string) context.Context {
|
||||||
|
return context.WithValue(ctx, clientIPKey{}, strings.TrimSpace(ip))
|
||||||
|
}
|
||||||
|
|
||||||
|
// setClientIPHeader attaches ForwardedForHeader when ctx carries a valid
|
||||||
|
// address from WithClientIP; a no-op otherwise.
|
||||||
|
func setClientIPHeader(ctx context.Context, req *http.Request) {
|
||||||
|
ip, _ := ctx.Value(clientIPKey{}).(string)
|
||||||
|
if parsed := net.ParseIP(ip); parsed != nil {
|
||||||
|
req.Header.Set(ForwardedForHeader, parsed.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func normalizeBaseURL(baseURL string) string {
|
func normalizeBaseURL(baseURL string) string {
|
||||||
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||||
if trimmed == "" {
|
if trimmed == "" {
|
||||||
@@ -211,6 +244,9 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
|
|||||||
if token == "" {
|
if token == "" {
|
||||||
return nil, ErrInvalidSession
|
return nil, ErrInvalidSession
|
||||||
}
|
}
|
||||||
|
if user, cachedErr, ok := c.cachedValidation(token); ok {
|
||||||
|
return user, cachedErr
|
||||||
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api/session/validate", nil)
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api/session/validate", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -233,15 +269,22 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
|
|||||||
}
|
}
|
||||||
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
|
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
|
||||||
if resp.StatusCode == http.StatusUnauthorized {
|
if resp.StatusCode == http.StatusUnauthorized {
|
||||||
|
c.cacheValidation(token, nil, false)
|
||||||
return nil, ErrInvalidSession
|
return nil, ErrInvalidSession
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err)
|
return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK || !payload.Valid {
|
if resp.StatusCode == http.StatusUnauthorized || (resp.StatusCode == http.StatusOK && !payload.Valid) {
|
||||||
|
c.cacheValidation(token, nil, false)
|
||||||
return nil, ErrInvalidSession
|
return nil, ErrInvalidSession
|
||||||
}
|
}
|
||||||
return &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}, nil
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("authclient: AuthServer returned HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
user := &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}
|
||||||
|
c.cacheValidation(token, user, true)
|
||||||
|
return user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// contextKey is unexported so only this package can set/read the resolved
|
// contextKey is unexported so only this package can set/read the resolved
|
||||||
@@ -451,6 +494,7 @@ func (c *Client) call(ctx context.Context, method, path, token string, body, out
|
|||||||
req.Header.Set("Authorization", "Bearer "+token)
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
}
|
}
|
||||||
c.setProjectKeyHeader(req)
|
c.setProjectKeyHeader(req)
|
||||||
|
setClientIPHeader(ctx, req)
|
||||||
|
|
||||||
resp, err := c.httpClient.Do(req)
|
resp, err := c.httpClient.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -535,17 +579,30 @@ func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, erro
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
c.invalidateValidation(token)
|
||||||
return resp.Cookies(), nil
|
return resp.Cookies(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -564,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -572,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -623,6 +686,9 @@ func (c *Client) CreateManagedUser(ctx context.Context, token string, input Mana
|
|||||||
// UpdateManagedUser calls PUT /api/admin/users/{id}.
|
// UpdateManagedUser calls PUT /api/admin/users/{id}.
|
||||||
func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error {
|
func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error {
|
||||||
_, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil)
|
_, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil)
|
||||||
|
if err == nil {
|
||||||
|
c.invalidateValidation(token)
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -110,3 +110,43 @@ func TestSetBaseURLIgnoresBlank(t *testing.T) {
|
|||||||
t.Fatalf("SetBaseURL(blank) changed baseURL to %q, want unchanged", got)
|
t.Fatalf("SetBaseURL(blank) changed baseURL to %q, want unchanged", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWithClientIPSendsXForwardedForOnCredentialCalls(t *testing.T) {
|
||||||
|
var seen []string
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
seen = append(seen, r.Header.Get(ForwardedForHeader))
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"user":{"id":1,"username":"a"}}`))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
client := New(server.URL)
|
||||||
|
|
||||||
|
ctx := WithClientIP(context.Background(), " 203.0.113.9 ")
|
||||||
|
if _, err := client.Login(ctx, "a", "password123", ""); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := client.Register(WithClientIP(context.Background(), "2001:db8::1"), "a", "a@b.com", "password123"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := client.TOTPVerify(ctx, "tok", "123456"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// No address, and values that are not IP addresses, send no header.
|
||||||
|
if _, err := client.Login(context.Background(), "a", "password123", ""); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"", "not-an-ip", "203.0.113.9\r\nX-Evil: 1"} {
|
||||||
|
if _, err := client.Login(WithClientIP(context.Background(), bad), "a", "password123", ""); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
want := []string{"203.0.113.9", "2001:db8::1", "203.0.113.9", "", "", "", ""}
|
||||||
|
if len(seen) != len(want) {
|
||||||
|
t.Fatalf("server saw %d requests, want %d", len(seen), len(want))
|
||||||
|
}
|
||||||
|
for i := range want {
|
||||||
|
if seen[i] != want[i] {
|
||||||
|
t.Errorf("request %d X-Forwarded-For = %q, want %q", i, seen[i], want[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package authclient
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
validationCacheTTL = 2 * time.Second
|
||||||
|
maxValidationCacheSize = 10000
|
||||||
|
)
|
||||||
|
|
||||||
|
// A session revoked directly in AuthGuard may remain accepted by this client
|
||||||
|
// for up to two seconds. Logout through this Client clears the cached result.
|
||||||
|
|
||||||
|
type validationCacheEntry struct {
|
||||||
|
user User
|
||||||
|
valid bool
|
||||||
|
expires time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type profileCacheEntry struct {
|
||||||
|
profile PublicUser
|
||||||
|
expires time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) cachedValidation(token string) (*User, error, bool) {
|
||||||
|
key := sha256.Sum256([]byte(token))
|
||||||
|
now := time.Now()
|
||||||
|
c.validationMu.Lock()
|
||||||
|
defer c.validationMu.Unlock()
|
||||||
|
entry, ok := c.validationCache[key]
|
||||||
|
if !ok {
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
if !now.Before(entry.expires) {
|
||||||
|
delete(c.validationCache, key)
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
if !entry.valid {
|
||||||
|
return nil, ErrInvalidSession, true
|
||||||
|
}
|
||||||
|
user := entry.user
|
||||||
|
return &user, nil, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) cacheValidation(token string, user *User, valid bool) {
|
||||||
|
key := sha256.Sum256([]byte(token))
|
||||||
|
now := time.Now()
|
||||||
|
c.validationMu.Lock()
|
||||||
|
defer c.validationMu.Unlock()
|
||||||
|
if c.validationCache == nil {
|
||||||
|
c.validationCache = make(map[[32]byte]validationCacheEntry)
|
||||||
|
}
|
||||||
|
if len(c.validationCache) >= maxValidationCacheSize {
|
||||||
|
for existing, entry := range c.validationCache {
|
||||||
|
if !now.Before(entry.expires) {
|
||||||
|
delete(c.validationCache, existing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(c.validationCache) >= maxValidationCacheSize {
|
||||||
|
for existing := range c.validationCache {
|
||||||
|
delete(c.validationCache, existing)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entry := validationCacheEntry{valid: valid, expires: now.Add(validationCacheTTL)}
|
||||||
|
if user != nil {
|
||||||
|
entry.user = *user
|
||||||
|
}
|
||||||
|
c.validationCache[key] = entry
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) cachedProfile(token string) (*PublicUser, bool) {
|
||||||
|
key := sha256.Sum256([]byte(token))
|
||||||
|
now := time.Now()
|
||||||
|
c.validationMu.Lock()
|
||||||
|
defer c.validationMu.Unlock()
|
||||||
|
entry, ok := c.profileCache[key]
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if !now.Before(entry.expires) {
|
||||||
|
delete(c.profileCache, key)
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
profile := entry.profile
|
||||||
|
return &profile, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) cacheProfile(token string, profile *PublicUser) {
|
||||||
|
if profile == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key := sha256.Sum256([]byte(token))
|
||||||
|
now := time.Now()
|
||||||
|
c.validationMu.Lock()
|
||||||
|
defer c.validationMu.Unlock()
|
||||||
|
if c.profileCache == nil {
|
||||||
|
c.profileCache = make(map[[32]byte]profileCacheEntry)
|
||||||
|
}
|
||||||
|
if len(c.profileCache) >= maxValidationCacheSize {
|
||||||
|
for existing, entry := range c.profileCache {
|
||||||
|
if !now.Before(entry.expires) {
|
||||||
|
delete(c.profileCache, existing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(c.profileCache) >= maxValidationCacheSize {
|
||||||
|
for existing := range c.profileCache {
|
||||||
|
delete(c.profileCache, existing)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.profileCache[key] = profileCacheEntry{profile: *profile, expires: now.Add(validationCacheTTL)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) invalidateValidation(token string) {
|
||||||
|
key := sha256.Sum256([]byte(token))
|
||||||
|
c.validationMu.Lock()
|
||||||
|
delete(c.validationCache, key)
|
||||||
|
delete(c.profileCache, key)
|
||||||
|
c.validationMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) clearValidationCache() {
|
||||||
|
c.validationMu.Lock()
|
||||||
|
c.validationCache = make(map[[32]byte]validationCacheEntry)
|
||||||
|
c.profileCache = make(map[[32]byte]profileCacheEntry)
|
||||||
|
c.validationMu.Unlock()
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -457,6 +522,30 @@ func thumbnailFile(id string) (string, error) {
|
|||||||
return id + ".jpg", nil
|
return id + ".jpg", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// validName reports an error unless name can be used as one path segment: it must not be empty,
|
||||||
|
// ".", ".." or contain a path separator. Every push and delete helper checks its name with this.
|
||||||
|
func validName(name string) error {
|
||||||
|
if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) {
|
||||||
|
return fmt.Errorf("invalid name %q", name)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validRelativeName is validName for outputs, inputs and copies, which may sit in nested
|
||||||
|
// directories (for example CraftStudio's "<user>/<workflow>/<file>"). It refuses an empty or
|
||||||
|
// absolute name, a backslash, and any empty, "." or ".." segment.
|
||||||
|
func validRelativeName(name string) error {
|
||||||
|
if name == "" || strings.HasPrefix(name, "/") || strings.ContainsRune(name, '\\') {
|
||||||
|
return fmt.Errorf("invalid name %q", name)
|
||||||
|
}
|
||||||
|
for _, segment := range strings.Split(name, "/") {
|
||||||
|
if segment == "" || segment == "." || segment == ".." {
|
||||||
|
return fmt.Errorf("invalid name %q", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// thumbnailPaths lists every CarrierNode path a thumbnail may live at, in lookup order: the
|
// thumbnailPaths lists every CarrierNode path a thumbnail may live at, in lookup order: the
|
||||||
// project's thumbnails mount first, then CarrierNode's legacy thumbnail root. Thumbnails
|
// project's thumbnails mount first, then CarrierNode's legacy thumbnail root. Thumbnails
|
||||||
// stored before the mount existed sit in the legacy root, and reads keep finding them there
|
// stored before the mount existed sit in the legacy root, and reads keep finding them there
|
||||||
@@ -512,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 {
|
for _, path := range paths {
|
||||||
if exists, _, _, probeErr := c.Probe(r.Context(), path); probeErr == nil && exists {
|
if path != cachedPath {
|
||||||
c.Proxy(w, r, path)
|
ordered = append(ordered, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
paths = ordered
|
||||||
|
}
|
||||||
|
for _, path := range paths {
|
||||||
|
for _, baseURL := range c.candidateBaseURLs(r.Context()) {
|
||||||
|
request, err := c.newRequest(r.Context(), baseURL, r.Method, path, nil)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, header := range forwardRequestHeaders {
|
||||||
|
if value := r.Header.Get(header); value != "" {
|
||||||
|
request.Header.Set(header, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
response, err := httpClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if response.StatusCode >= http.StatusBadRequest {
|
||||||
|
response.Body.Close()
|
||||||
|
if path == cachedPath {
|
||||||
|
c.forgetThumbnailPath(cacheKey)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, header := range forwardResponseHeaders {
|
||||||
|
if value := response.Header.Get(header); value != "" {
|
||||||
|
w.Header().Set(header, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.WriteHeader(response.StatusCode)
|
||||||
|
if r.Method != http.MethodHead {
|
||||||
|
_, _ = io.Copy(w, response.Body)
|
||||||
|
}
|
||||||
|
response.Body.Close()
|
||||||
|
c.rememberThumbnailPath(cacheKey, path)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Client) cachedThumbnailPath(key string) string {
|
||||||
|
c.thumbnailMu.Lock()
|
||||||
|
defer c.thumbnailMu.Unlock()
|
||||||
|
entry, ok := c.thumbnailPaths[key]
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if !time.Now().Before(entry.expires) {
|
||||||
|
delete(c.thumbnailPaths, key)
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return entry.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) rememberThumbnailPath(key, path string) {
|
||||||
|
c.thumbnailMu.Lock()
|
||||||
|
defer c.thumbnailMu.Unlock()
|
||||||
|
if c.thumbnailPaths == nil {
|
||||||
|
c.thumbnailPaths = make(map[string]thumbnailPathEntry)
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
for cacheKey, entry := range c.thumbnailPaths {
|
||||||
|
if !now.Before(entry.expires) {
|
||||||
|
delete(c.thumbnailPaths, cacheKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(c.thumbnailPaths) >= thumbnailPathCacheLimit {
|
||||||
|
var oldestKey string
|
||||||
|
var oldest time.Time
|
||||||
|
first := true
|
||||||
|
for cacheKey, entry := range c.thumbnailPaths {
|
||||||
|
if first || entry.expires.Before(oldest) {
|
||||||
|
oldestKey, oldest, first = cacheKey, entry.expires, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delete(c.thumbnailPaths, oldestKey)
|
||||||
|
}
|
||||||
|
c.thumbnailPaths[key] = thumbnailPathEntry{path: path, expires: now.Add(thumbnailPathCacheTTL)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) forgetThumbnailPath(key string) {
|
||||||
|
c.thumbnailMu.Lock()
|
||||||
|
delete(c.thumbnailPaths, key)
|
||||||
|
c.thumbnailMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
// FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking
|
// FetchThumbnailToScratch downloads a stored thumbnail into an ephemeral local file, looking
|
||||||
// in the project's thumbnails mount and then the legacy root. Callers must invoke the returned
|
// in the project's thumbnails mount and then the legacy root. Callers must invoke the returned
|
||||||
// cleanup once done.
|
// cleanup once done.
|
||||||
@@ -670,6 +847,9 @@ func pushedSize(response *http.Response) int64 {
|
|||||||
|
|
||||||
// PushThumbnail uploads a locally-generated thumbnail to CarrierNode.
|
// PushThumbnail uploads a locally-generated thumbnail to CarrierNode.
|
||||||
func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
|
func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
|
||||||
|
if err := validName(id); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
response, err := c.push(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
|
response, err := c.push(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -680,6 +860,9 @@ func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64
|
|||||||
// DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as
|
// DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as
|
||||||
// already-deleted, not an error. Always targets the primary instance.
|
// already-deleted, not an error. Always targets the primary instance.
|
||||||
func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
|
func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
|
||||||
|
if err := validName(id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
|
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -698,6 +881,9 @@ func (c *Client) DeleteThumbnail(ctx context.Context, id string) error {
|
|||||||
// PushOutput uploads a locally-produced output file (e.g. a converted or
|
// PushOutput uploads a locally-produced output file (e.g. a converted or
|
||||||
// generated media file) to CarrierNode's OutputRoot.
|
// generated media file) to CarrierNode's OutputRoot.
|
||||||
func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64, error) {
|
func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64, error) {
|
||||||
|
if err := validRelativeName(name); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
response, err := c.push(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
|
response, err := c.push(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -707,6 +893,9 @@ func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64,
|
|||||||
|
|
||||||
// PushInput uploads a local file to CarrierNode's InputRoot.
|
// PushInput uploads a local file to CarrierNode's InputRoot.
|
||||||
func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64, error) {
|
func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64, error) {
|
||||||
|
if err := validRelativeName(name); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
response, err := c.push(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
|
response, err := c.push(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -716,6 +905,9 @@ func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64,
|
|||||||
|
|
||||||
// PushCopy uploads a local file to CarrierNode's CopyRoot.
|
// PushCopy uploads a local file to CarrierNode's CopyRoot.
|
||||||
func (c *Client) PushCopy(ctx context.Context, name, localPath string) (int64, error) {
|
func (c *Client) PushCopy(ctx context.Context, name, localPath string) (int64, error) {
|
||||||
|
if err := validRelativeName(name); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
response, err := c.push(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
|
response, err := c.push(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
|
|||||||
@@ -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", "")), ®istered)
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -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) {
|
||||||
@@ -181,3 +204,58 @@ func TestThumbnailIDsCannotEscapeTheThumbnailsDirectory(t *testing.T) {
|
|||||||
t.Fatalf("invalid thumbnail ids reached CarrierNode: %v", got)
|
t.Fatalf("invalid thumbnail ids reached CarrierNode: %v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestPushAndDeleteNamesCannotEscapeTheirDirectory checks that the push and delete helpers refuse
|
||||||
|
// names that are "." or ".." or contain a separator before any request reaches CarrierNode.
|
||||||
|
func TestPushAndDeleteNamesCannotEscapeTheirDirectory(t *testing.T) {
|
||||||
|
client, node := newThumbnailTestClient(t, nil)
|
||||||
|
ctx := context.Background()
|
||||||
|
local := filepath.Join(t.TempDir(), "payload.bin")
|
||||||
|
if err := os.WriteFile(local, []byte("x"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, name := range []string{"", ".", "..", "../escape", `..\escape`, "nested/name"} {
|
||||||
|
if _, err := client.PushThumbnail(ctx, name, local); err == nil {
|
||||||
|
t.Errorf("PushThumbnail accepted name %q", name)
|
||||||
|
}
|
||||||
|
if err := client.DeleteThumbnail(ctx, name); err == nil {
|
||||||
|
t.Errorf("DeleteThumbnail accepted name %q", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Outputs, inputs and copies may nest, but no segment may climb out of its directory.
|
||||||
|
for _, name := range []string{"", ".", "..", "../escape", `..\escape`, "/abs", "a//b", "a/../b", "a/./b", "a/"} {
|
||||||
|
if _, err := client.PushOutput(ctx, name, local); err == nil {
|
||||||
|
t.Errorf("PushOutput accepted name %q", name)
|
||||||
|
}
|
||||||
|
if _, err := client.PushInput(ctx, name, local); err == nil {
|
||||||
|
t.Errorf("PushInput accepted name %q", name)
|
||||||
|
}
|
||||||
|
if _, err := client.PushCopy(ctx, name, local); err == nil {
|
||||||
|
t.Errorf("PushCopy accepted name %q", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := node.seen(); len(got) != 0 {
|
||||||
|
t.Fatalf("invalid names reached CarrierNode: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNestedOutputNamesAreAccepted checks that CraftStudio-style nested output names pass the
|
||||||
|
// relative-name check, so generator outputs keep their CarrierNode path.
|
||||||
|
func TestNestedOutputNamesAreAccepted(t *testing.T) {
|
||||||
|
for _, name := range []string{"CraftStudio/alice/flux/out.png", "a/b.txt"} {
|
||||||
|
if err := validRelativeName(name); err != nil {
|
||||||
|
t.Errorf("validRelativeName(%q) = %v, want nil", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestValidNamesAreNotRefused checks that ordinary names, including ones with spaces or query
|
||||||
|
// characters, pass the name check; the path escaping in MountPath and the push helpers handles them.
|
||||||
|
func TestValidNamesAreNotRefused(t *testing.T) {
|
||||||
|
for _, name := range []string{"clip.mp4", "my clip?.mp4", "a#b", "v1.2.final"} {
|
||||||
|
if err := validName(name); err != nil {
|
||||||
|
t.Errorf("validName(%q) = %v, want nil", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStringTrimsAndFallsBack(t *testing.T) {
|
||||||
|
t.Setenv("CFG_TEST_STRING", " value ")
|
||||||
|
if got := String("CFG_TEST_STRING", "fallback"); got != "value" {
|
||||||
|
t.Fatalf("String = %q, want the trimmed value", got)
|
||||||
|
}
|
||||||
|
t.Setenv("CFG_TEST_STRING", " ")
|
||||||
|
if got := String("CFG_TEST_STRING", "fallback"); got != "fallback" {
|
||||||
|
t.Fatalf("String of a blank value = %q, want the fallback", got)
|
||||||
|
}
|
||||||
|
if got := String("CFG_TEST_UNSET", "fallback"); got != "fallback" {
|
||||||
|
t.Fatalf("String of an unset variable = %q, want the fallback", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequiredNamesTheMissingVariable(t *testing.T) {
|
||||||
|
t.Setenv("CFG_TEST_REQUIRED", " secret ")
|
||||||
|
if got, err := Required("CFG_TEST_REQUIRED"); err != nil || got != "secret" {
|
||||||
|
t.Fatalf("Required = %q, %v; want the trimmed value", got, err)
|
||||||
|
}
|
||||||
|
t.Setenv("CFG_TEST_REQUIRED", " ")
|
||||||
|
if _, err := Required("CFG_TEST_REQUIRED"); err == nil || err.Error() != "CFG_TEST_REQUIRED is required" {
|
||||||
|
t.Fatalf("Required of a blank value error = %v, want it to name the variable", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBoolIntAndDurationFallBackOnInvalidValues(t *testing.T) {
|
||||||
|
t.Setenv("CFG_TEST_BOOL", "true")
|
||||||
|
t.Setenv("CFG_TEST_INT", " 42 ")
|
||||||
|
t.Setenv("CFG_TEST_DURATION", "1m30s")
|
||||||
|
if !Bool("CFG_TEST_BOOL", false) || Int("CFG_TEST_INT", 0) != 42 || Duration("CFG_TEST_DURATION", 0) != 90*time.Second {
|
||||||
|
t.Fatal("valid values were not parsed")
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Setenv("CFG_TEST_BOOL", "maybe")
|
||||||
|
t.Setenv("CFG_TEST_INT", "4x")
|
||||||
|
t.Setenv("CFG_TEST_DURATION", "soon")
|
||||||
|
if !Bool("CFG_TEST_BOOL", true) || Bool("CFG_TEST_BOOL", false) {
|
||||||
|
t.Fatal("an invalid boolean did not fall back")
|
||||||
|
}
|
||||||
|
if Int("CFG_TEST_INT", 7) != 7 || Duration("CFG_TEST_DURATION", time.Second) != time.Second {
|
||||||
|
t.Fatal("an invalid integer or duration did not fall back")
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Setenv("CFG_TEST_BOOL", "")
|
||||||
|
t.Setenv("CFG_TEST_INT", "")
|
||||||
|
t.Setenv("CFG_TEST_DURATION", "")
|
||||||
|
if !Bool("CFG_TEST_BOOL", true) || Int("CFG_TEST_INT", 7) != 7 || Duration("CFG_TEST_DURATION", time.Second) != time.Second {
|
||||||
|
t.Fatal("an empty value did not fall back")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,12 +11,42 @@
|
|||||||
package coreconfig
|
package coreconfig
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/subtle"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"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 {
|
||||||
@@ -48,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,6 +98,7 @@ 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.
|
||||||
@@ -102,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
|
||||||
@@ -112,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) {
|
||||||
@@ -135,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
|
||||||
@@ -175,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 == "" || r.Header.Get("X-Internal-Auth") != secret {
|
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
|
||||||
}
|
}
|
||||||
@@ -188,16 +255,38 @@ func Handler(secret string, store *Store) http.HandlerFunc {
|
|||||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if err := validateServiceURLs(input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
store.Set(input)
|
store.Set(input)
|
||||||
// Do not echo service credentials to the caller. The push is authenticated, but
|
// Do not echo service credentials to the caller. The push is authenticated, but
|
||||||
// these credentials are needed only by the recipient.
|
// these credentials are needed only by the recipient.
|
||||||
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})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// validateServiceURLs refuses a pushed URL that is not an http or https URL with a host, so a push
|
||||||
|
// cannot point this service's clients at another scheme or at an empty host.
|
||||||
|
func validateServiceURLs(info Info) error {
|
||||||
|
urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL, info.OmniLoggerURL}, info.CarrierNodeURLs...)
|
||||||
|
for _, raw := range urls {
|
||||||
|
value := strings.TrimSpace(raw)
|
||||||
|
if value == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parsed, err := url.Parse(value)
|
||||||
|
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
|
||||||
|
return errors.New("core service URL must be an http or https URL with a host")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
w.WriteHeader(status)
|
w.WriteHeader(status)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|
||||||
@@ -149,3 +149,44 @@ func TestHandlerAppliesPushedInfo(t *testing.T) {
|
|||||||
t.Fatal("response echoed the ContentScanner secret")
|
t.Fatal("response echoed the ContentScanner secret")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHandlerRejectsNonHTTPURLsWithoutChangingStore(t *testing.T) {
|
||||||
|
store := NewStore(Info{AuthGuardURL: "http://auth.example.com"})
|
||||||
|
handler := Handler("test-internal-secret", store)
|
||||||
|
for _, bad := range []Info{
|
||||||
|
{AuthGuardURL: "javascript:alert(1)"},
|
||||||
|
{AuthGuardURL: "auth.example.com"},
|
||||||
|
{CarrierNodeURLs: []string{"http://carrier.example.com", "file:///etc/passwd"}},
|
||||||
|
{ContentScannerURL: "http://"},
|
||||||
|
} {
|
||||||
|
body, _ := json.Marshal(bad)
|
||||||
|
req := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", bytes.NewReader(body))
|
||||||
|
req.Header.Set("X-Internal-Auth", "test-internal-secret")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
handler(rec, req)
|
||||||
|
if rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("status = %d for %+v, want 400", rec.Code, bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := store.Get(); got.AuthGuardURL != "http://auth.example.com" || len(got.CarrierNodeURLs) != 0 {
|
||||||
|
t.Fatalf("store changed by a rejected push: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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})
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package files
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSafeRelativeRejectsTraversalAndAbsolutePaths(t *testing.T) {
|
||||||
|
for _, value := range []string{"", ".", "..", "../x", "a/../../x", "sub/../a.mp4x", "/etc/passwd", `\etc\passwd`, `C:\x`, "a\x00b"} {
|
||||||
|
if SafeRelative(value) {
|
||||||
|
t.Errorf("SafeRelative(%q) = true, want false", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range []string{"a.mp4", "sub/b.mp4", "v1..2/clip.mp4"} {
|
||||||
|
if !SafeRelative(value) {
|
||||||
|
t.Errorf("SafeRelative(%q) = false, want true", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveUnderRootsStaysInsideTheRoots(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
if err := os.MkdirAll(filepath.Join(root, "sub"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(root, "a.mp4"), []byte("a"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(root, "sub", "b.mp4"), []byte("b"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
outside := filepath.Join(t.TempDir(), "secret.txt")
|
||||||
|
if err := os.WriteFile(outside, []byte("s"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = os.Symlink(outside, filepath.Join(root, "link.txt"))
|
||||||
|
|
||||||
|
for value, want := range map[string]string{
|
||||||
|
"a.mp4": filepath.Join(root, "a.mp4"),
|
||||||
|
"/media/a.mp4": filepath.Join(root, "a.mp4"),
|
||||||
|
"sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
|
||||||
|
"/media/sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
|
||||||
|
} {
|
||||||
|
got, err := ResolveUnderRoots(value, []string{root})
|
||||||
|
if err != nil || got != want {
|
||||||
|
t.Errorf("ResolveUnderRoots(%q) = %q, %v; want %q", value, got, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, value := range []string{"../secret.txt", "sub", "missing.mp4", "link.txt", "", "a\x00b"} {
|
||||||
|
if _, err := ResolveUnderRoots(value, []string{root}); err == nil {
|
||||||
|
t.Errorf("ResolveUnderRoots(%q) resolved, want an error", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := ResolveUnderRoots("missing.mp4", []string{root}); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("missing file error = %v, want os.ErrNotExist", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -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 (
|
||||||
@@ -18,5 +18,5 @@ require (
|
|||||||
github.com/sethvargo/go-retry v0.4.0 // indirect
|
github.com/sethvargo/go-retry v0.4.0 // indirect
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
golang.org/x/sync v0.22.0 // indirect
|
golang.org/x/sync v0.22.0 // indirect
|
||||||
golang.org/x/text v0.40.0 // indirect
|
golang.org/x/text v0.41.0 // indirect
|
||||||
)
|
)
|
||||||
+4
-4
@@ -38,14 +38,14 @@ 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.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
|||||||
@@ -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...) }
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+270
-22
@@ -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,9 +159,13 @@ type Shipper struct {
|
|||||||
logAll bool
|
logAll bool
|
||||||
|
|
||||||
service string
|
service string
|
||||||
|
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
|
url string
|
||||||
token string
|
token string
|
||||||
client *http.Client
|
|
||||||
|
|
||||||
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 {
|
||||||
|
|||||||
@@ -0,0 +1,686 @@
|
|||||||
|
package logshipper
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"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.
|
||||||
|
func captureStd(t *testing.T, fn func()) (stdout, stderr string) {
|
||||||
|
t.Helper()
|
||||||
|
oldOut, oldErr := os.Stdout, os.Stderr
|
||||||
|
outR, outW, err := os.Pipe()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
errR, errW, err := os.Pipe()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
os.Stdout, os.Stderr = outW, errW
|
||||||
|
defer func() { os.Stdout, os.Stderr = oldOut, oldErr }()
|
||||||
|
|
||||||
|
fn()
|
||||||
|
|
||||||
|
outW.Close()
|
||||||
|
errW.Close()
|
||||||
|
os.Stdout, os.Stderr = oldOut, oldErr
|
||||||
|
outBytes, _ := io.ReadAll(outR)
|
||||||
|
errBytes, _ := io.ReadAll(errR)
|
||||||
|
return string(outBytes), string(errBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ingest is a stand-in OmniLogger that records every batch it is sent.
|
||||||
|
type ingest struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
batches [][]wireEntry
|
||||||
|
auth []string
|
||||||
|
status int
|
||||||
|
server *httptest.Server
|
||||||
|
}
|
||||||
|
|
||||||
|
func newIngest(t *testing.T, status int) *ingest {
|
||||||
|
t.Helper()
|
||||||
|
in := &ingest{status: status}
|
||||||
|
in.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var batch []wireEntry
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&batch)
|
||||||
|
in.mu.Lock()
|
||||||
|
in.batches = append(in.batches, batch)
|
||||||
|
in.auth = append(in.auth, r.Method+" "+r.URL.Path+" "+r.Header.Get("Authorization"))
|
||||||
|
in.mu.Unlock()
|
||||||
|
w.WriteHeader(in.status)
|
||||||
|
}))
|
||||||
|
t.Cleanup(in.server.Close)
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
|
||||||
|
func (in *ingest) entries() []wireEntry {
|
||||||
|
in.mu.Lock()
|
||||||
|
defer in.mu.Unlock()
|
||||||
|
var all []wireEntry
|
||||||
|
for _, batch := range in.batches {
|
||||||
|
all = append(all, batch...)
|
||||||
|
}
|
||||||
|
return all
|
||||||
|
}
|
||||||
|
|
||||||
|
// newTestShipper keeps the background loop quiet so a test decides when entries are sent, and
|
||||||
|
// points a shipper that names no sink at a throwaway one so closing it prints nothing.
|
||||||
|
func newTestShipper(t *testing.T, cfg Config) *Shipper {
|
||||||
|
t.Helper()
|
||||||
|
if cfg.FlushInterval == 0 {
|
||||||
|
cfg.FlushInterval = time.Hour
|
||||||
|
}
|
||||||
|
if cfg.BaseURL == "" {
|
||||||
|
cfg.BaseURL = newIngest(t, http.StatusAccepted).server.URL
|
||||||
|
}
|
||||||
|
if cfg.IngestToken == "" {
|
||||||
|
cfg.IngestToken = "test-token"
|
||||||
|
}
|
||||||
|
return New(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLevelOfAcceptsTheSharedLogVocabulary(t *testing.T) {
|
||||||
|
cases := map[string]Level{
|
||||||
|
"debug": LevelDebug, " DEBUG ": LevelDebug, "info": LevelInfo, "": LevelInfo, "bogus": LevelInfo,
|
||||||
|
"warn": LevelWarn, "warning": LevelWarn, "error": LevelError, "critical": LevelCritical,
|
||||||
|
"silent": LevelSilent, "none": LevelSilent, "off": LevelSilent,
|
||||||
|
}
|
||||||
|
for input, want := range cases {
|
||||||
|
if got := levelOf(input); got != want {
|
||||||
|
t.Errorf("levelOf(%q) = %d, want %d", input, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSevNameGivesTheLowercaseNameOmniLoggerExpects(t *testing.T) {
|
||||||
|
for sev, want := range map[Level][2]string{
|
||||||
|
LevelDebug: {"DEBUG", "debug"}, LevelInfo: {"INFO", "info"}, LevelWarn: {"WARN", "warn"},
|
||||||
|
LevelError: {"ERROR", "error"}, LevelCritical: {"CRITICAL", "critical"},
|
||||||
|
} {
|
||||||
|
if upper, lower := sevName(sev); upper != want[0] || lower != want[1] {
|
||||||
|
t.Errorf("sevName(%d) = %q, %q; want %q, %q", sev, upper, lower, want[0], want[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFormatArgsJoinsErrorsStringsAndValues(t *testing.T) {
|
||||||
|
got := formatArgs([]any{"failed:", errors.New("boom"), 42, map[string]int{"a": 1}, make(chan int)})
|
||||||
|
if !strings.HasPrefix(got, `failed: boom 42 {"a":1} `) {
|
||||||
|
t.Fatalf("formatArgs = %q", got)
|
||||||
|
}
|
||||||
|
if formatArgs(nil) != "" {
|
||||||
|
t.Fatal("formatArgs(nil) is not empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScrubIDsDropsIdentifierFieldsFromTheLocalDump(t *testing.T) {
|
||||||
|
ctx := map[string]any{
|
||||||
|
"id": 1, "userId": 2, "user_id": 3, "requestID": "r", "path": "/x", "status": 200, "ok": true,
|
||||||
|
}
|
||||||
|
got := scrubIDs(ctx)
|
||||||
|
if len(got) != 3 || got["path"] != "/x" || got["status"] != 200 || got["ok"] != true {
|
||||||
|
t.Fatalf("scrubIDs = %v, want only path, status and ok", got)
|
||||||
|
}
|
||||||
|
if len(ctx) != 7 {
|
||||||
|
t.Fatal("scrubIDs modified its input")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEmitGatesOnTheThresholdAndWritesTheLocalLine(t *testing.T) {
|
||||||
|
shipper := newTestShipper(t, Config{Service: "svc", Module: "mod", Level: "warn"})
|
||||||
|
defer shipper.Close()
|
||||||
|
stdout, stderr := captureStd(t, func() {
|
||||||
|
shipper.Info("below threshold")
|
||||||
|
shipper.Warn("warned")
|
||||||
|
shipper.Error("failed", errors.New("boom"))
|
||||||
|
})
|
||||||
|
if stdout != "" {
|
||||||
|
t.Fatalf("stdout = %q, want nothing", stdout)
|
||||||
|
}
|
||||||
|
if strings.Contains(stderr, "below threshold") || !strings.Contains(stderr, "[WARN] [mod] warned") || !strings.Contains(stderr, "[ERROR] [mod] failed boom") {
|
||||||
|
t.Fatalf("stderr = %q", stderr)
|
||||||
|
}
|
||||||
|
if got := len(shipper.buffer); got != 2 {
|
||||||
|
t.Fatalf("buffered %d entries, want the 2 at or above the threshold", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSilentLevelWritesAndBuffersNothing(t *testing.T) {
|
||||||
|
shipper := newTestShipper(t, Config{Service: "svc", Level: "silent"})
|
||||||
|
defer shipper.Close()
|
||||||
|
stdout, stderr := captureStd(t, func() {
|
||||||
|
shipper.Critical("never shown")
|
||||||
|
})
|
||||||
|
if stdout != "" || stderr != "" || len(shipper.buffer) != 0 {
|
||||||
|
t.Fatalf("silent shipper wrote %q / %q and buffered %d entries", stdout, stderr, len(shipper.buffer))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogAllScrubsIDsLocallyButShipsTheFullContext(t *testing.T) {
|
||||||
|
in := newIngest(t, http.StatusAccepted)
|
||||||
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", LogAll: true})
|
||||||
|
defer shipper.Close()
|
||||||
|
stdout, _ := captureStd(t, func() {
|
||||||
|
shipper.InfoCtx(map[string]any{"userId": 7, "path": "/x"}, "request")
|
||||||
|
})
|
||||||
|
if !strings.Contains(stdout, `[DETAILS] {"path":"/x"}`) || strings.Contains(stdout, "userId") {
|
||||||
|
t.Fatalf("local dump = %q, want the ID scrubbed", stdout)
|
||||||
|
}
|
||||||
|
shipper.Flush()
|
||||||
|
entries := in.entries()
|
||||||
|
if len(entries) != 1 || !strings.Contains(string(entries[0].Context), `"userId":7`) {
|
||||||
|
t.Fatalf("shipped entries = %+v, want the unscrubbed context", entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuditShipsAnInfoEntryWithTheDetails(t *testing.T) {
|
||||||
|
in := newIngest(t, http.StatusAccepted)
|
||||||
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
|
||||||
|
defer shipper.Close()
|
||||||
|
captureStd(t, func() { shipper.Audit("login", map[string]any{"user": "a"}) })
|
||||||
|
shipper.Flush()
|
||||||
|
entries := in.entries()
|
||||||
|
if len(entries) != 1 || entries[0].Level != "info" || !strings.HasPrefix(entries[0].Message, "audit:login") {
|
||||||
|
t.Fatalf("entries = %+v", entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFlushSendsOneAuthenticatedBatchAndEmptiesTheBuffer(t *testing.T) {
|
||||||
|
in := newIngest(t, http.StatusAccepted)
|
||||||
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL + "/", IngestToken: "secret", Service: "svc"})
|
||||||
|
defer shipper.Close()
|
||||||
|
captureStd(t, func() {
|
||||||
|
shipper.Info("one")
|
||||||
|
shipper.Error("two")
|
||||||
|
})
|
||||||
|
shipper.Flush()
|
||||||
|
shipper.Flush() // nothing left: no second request
|
||||||
|
in.mu.Lock()
|
||||||
|
defer in.mu.Unlock()
|
||||||
|
if len(in.batches) != 1 || len(in.batches[0]) != 2 {
|
||||||
|
t.Fatalf("batches = %+v, want one batch of two entries", in.batches)
|
||||||
|
}
|
||||||
|
if in.auth[0] != "POST /api/logs Bearer secret" {
|
||||||
|
t.Fatalf("request = %q", in.auth[0])
|
||||||
|
}
|
||||||
|
first := in.batches[0][0]
|
||||||
|
if first.Service != "svc" || first.Level != "info" || first.Message != "one" || first.OccurredAt.IsZero() {
|
||||||
|
t.Fatalf("first entry = %+v", first)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBufferDropsNewEntriesOnceFullInsteadOfBlocking(t *testing.T) {
|
||||||
|
shipper := newTestShipper(t, Config{Service: "svc", BufferCapacity: 3, MaxBatchSize: 1000})
|
||||||
|
defer shipper.Close()
|
||||||
|
_, stderr := captureStd(t, func() {
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
shipper.enqueue(wireEntry{Message: "m"})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if len(shipper.buffer) != 3 {
|
||||||
|
t.Fatalf("buffer holds %d entries, want the capacity of 3", len(shipper.buffer))
|
||||||
|
}
|
||||||
|
if strings.Count(stderr, "buffer full") != 1 {
|
||||||
|
t.Fatalf("stderr = %q, want the full-buffer warning exactly once", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReachingTheBatchSizeFlushesWithoutWaitingForTheInterval(t *testing.T) {
|
||||||
|
in := newIngest(t, http.StatusAccepted)
|
||||||
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", MaxBatchSize: 2})
|
||||||
|
defer shipper.Close()
|
||||||
|
captureStd(t, func() {
|
||||||
|
shipper.Info("a")
|
||||||
|
shipper.Info("b")
|
||||||
|
})
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
for len(in.entries()) < 2 {
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("a full batch was not flushed ahead of the interval")
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCloseFlushesWhatIsLeft(t *testing.T) {
|
||||||
|
in := newIngest(t, http.StatusAccepted)
|
||||||
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
|
||||||
|
captureStd(t, func() { shipper.Info("last words") })
|
||||||
|
if err := shipper.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := shipper.Close(); err != nil {
|
||||||
|
t.Fatalf("second Close error = %v", err)
|
||||||
|
}
|
||||||
|
if entries := in.entries(); len(entries) != 1 || entries[0].Message != "last words" {
|
||||||
|
t.Fatalf("entries after Close = %+v", entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAFailingSinkNeverFailsTheCallerAndWarnsOnlyOnce(t *testing.T) {
|
||||||
|
in := newIngest(t, http.StatusInternalServerError)
|
||||||
|
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
|
||||||
|
defer shipper.Close()
|
||||||
|
_, stderr := captureStd(t, func() {
|
||||||
|
shipper.Info("one")
|
||||||
|
shipper.Flush()
|
||||||
|
shipper.Info("two")
|
||||||
|
shipper.Flush()
|
||||||
|
})
|
||||||
|
if strings.Count(stderr, "answered HTTP 500") != 1 {
|
||||||
|
t.Fatalf("stderr = %q, want one rate-limited warning", stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
in.server.Close()
|
||||||
|
_, stderr = captureStd(t, func() {
|
||||||
|
shipper.Info("three")
|
||||||
|
shipper.Flush() // the sink is gone: swallowed, and still inside the warning interval
|
||||||
|
})
|
||||||
|
if strings.Contains(stderr, "send 1 entries") {
|
||||||
|
t.Fatalf("stderr = %q, want the second warning suppressed", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewAppliesDefaults(t *testing.T) {
|
||||||
|
shipper := New(Config{BaseURL: "http://omni:8090///", IngestToken: "t", Service: "svc"})
|
||||||
|
defer shipper.Close()
|
||||||
|
if shipper.url != "http://omni:8090/api/logs" || shipper.module != "svc" || shipper.threshold != LevelInfo {
|
||||||
|
t.Fatalf("url = %q, module = %q, threshold = %d", shipper.url, shipper.module, shipper.threshold)
|
||||||
|
}
|
||||||
|
if shipper.maxBatch != defaultMaxBatchSize || shipper.bufCap != defaultBufferCapacity || shipper.client == nil {
|
||||||
|
t.Fatalf("defaults not applied: %+v", shipper)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,53 +35,48 @@ 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"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Config wires a Core to the rest of one service's dependencies.
|
// maxPlaylistReorderItems caps one reorder request. The reorder runs as a single statement, so the
|
||||||
|
// cap bounds its size; a playlist longer than this is reordered in more than one request.
|
||||||
|
const maxPlaylistReorderItems = 10000
|
||||||
|
|
||||||
|
// Config wires a 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.Optional).Put("/sync", c.putSyncState)
|
|
||||||
r.With(c.auth.Optional).Get("/media/state", c.mediaState)
|
r.With(c.auth.Optional).Get("/media/state", c.mediaState)
|
||||||
r.With(c.auth.Require).Post("/media/like", c.mediaLike)
|
r.With(c.auth.Require).Post("/media/like", c.mediaLike)
|
||||||
r.With(c.auth.Require).Post("/media/save", c.mediaSave)
|
r.With(c.auth.Require).Post("/media/save", c.mediaSave)
|
||||||
r.With(c.auth.Optional).Post("/media/view", c.mediaView)
|
r.With(c.auth.Optional).Post("/media/view", c.mediaView)
|
||||||
r.With(c.auth.Optional).Post("/media/view-session", c.mediaViewSession)
|
r.With(c.auth.Optional).Post("/media/view-session", c.mediaViewSession)
|
||||||
r.With(c.auth.Require).Get("/media/liked", c.mediaLiked)
|
r.With(c.auth.Require).Get("/media/liked", c.mediaLiked)
|
||||||
r.Get("/media/stream", c.streamMediaByQuery)
|
r.With(c.auth.RequireIfLoginRequired).Get("/media/stream", c.streamMediaByQuery)
|
||||||
r.Head("/media/stream", c.streamMediaByQuery)
|
r.With(c.auth.RequireIfLoginRequired).Head("/media/stream", c.streamMediaByQuery)
|
||||||
r.Get("/media/thumb", c.thumbnailMediaByQuery)
|
r.With(c.auth.RequireIfLoginRequired).Get("/media/thumb", c.thumbnailMediaByQuery)
|
||||||
|
|
||||||
r.With(c.auth.Optional).Get("/media/{id}/tags", c.mediaTags)
|
r.With(c.auth.Optional).Get("/media/{id}/tags", c.mediaTags)
|
||||||
r.With(c.auth.Require).Post("/media/{id}/tags", c.addMediaTag)
|
r.With(c.auth.Require).Post("/media/{id}/tags", c.addMediaTag)
|
||||||
@@ -112,43 +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
|
|
||||||
}
|
|
||||||
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
|
|
||||||
state := map[string]any{
|
|
||||||
"sessionId": sessionID,
|
|
||||||
"mediaId": input["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 {
|
|
||||||
state["playAt"] = value
|
|
||||||
}
|
|
||||||
c.sync.SetHTTPState(sessionID, state)
|
|
||||||
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.
|
||||||
@@ -172,31 +117,59 @@ 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)
|
record, err := c.findMedia(r.Context(), identifier, canSeeHidden(r))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusNotFound, "media not found")
|
writeError(w, http.StatusNotFound, "media not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath))
|
upstream, ok := upstreamMediaPath(record.FilePath)
|
||||||
|
if !ok {
|
||||||
|
writeError(w, http.StatusNotFound, "media not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.carrierNode.Proxy(w, r, 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
|
||||||
}
|
}
|
||||||
|
includeHidden := canSeeHidden(r)
|
||||||
|
if !includeHidden && c.isHiddenMedia(r.Context(), id) {
|
||||||
|
writeError(w, http.StatusNotFound, "thumbnail not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
|
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
|
||||||
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, id) {
|
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, id) {
|
||||||
return
|
return
|
||||||
@@ -207,24 +180,29 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
|
|||||||
SELECT t.id::text
|
SELECT t.id::text
|
||||||
FROM thumbnails t
|
FROM thumbnails t
|
||||||
JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
|
JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
|
||||||
WHERE m.media_key=$1 OR CAST(m.id AS TEXT)=$1
|
WHERE m.media_key=$1 OR m.id=$2
|
||||||
ORDER BY t.created_at DESC
|
ORDER BY t.created_at DESC
|
||||||
LIMIT 1`, id).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) {
|
LIMIT 1`, id, mediaIDArg(id)).Scan(&thumbnailID); err == nil && 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) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
record, err := c.findMedia(r.Context(), id)
|
record, err := c.findMedia(r.Context(), id, includeHidden)
|
||||||
if err != nil || !isImagePath(record.FilePath) {
|
if err != nil || !isImagePath(record.FilePath) {
|
||||||
writeError(w, http.StatusNotFound, "thumbnail not found")
|
writeError(w, http.StatusNotFound, "thumbnail not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath))
|
upstream, ok := upstreamMediaPath(record.FilePath)
|
||||||
|
if !ok {
|
||||||
|
writeError(w, http.StatusNotFound, "thumbnail not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.carrierNode.Proxy(w, r, "/media/"+upstream)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) {
|
func (c *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")
|
||||||
@@ -247,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")
|
||||||
@@ -298,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
|
||||||
@@ -322,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"`
|
||||||
@@ -337,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
|
||||||
@@ -353,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 {
|
||||||
@@ -372,12 +381,12 @@ 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 tag, COALESCE(SUM(vote), 0) AS score
|
SELECT mt.tag, COALESCE(SUM(mv.vote), 0) AS score
|
||||||
FROM media_tags mt LEFT JOIN media_tag_votes mv ON mv.media_key = mt.media_key AND LOWER(mv.tag) = LOWER(mt.tag)
|
FROM media_tags mt LEFT JOIN media_tag_votes mv ON mv.media_key = mt.media_key AND LOWER(mv.tag) = LOWER(mt.tag)
|
||||||
WHERE mt.media_key = $1 GROUP BY tag ORDER BY score DESC, LOWER(tag)`, key)
|
WHERE mt.media_key = $1 GROUP BY mt.tag ORDER BY score DESC, LOWER(mt.tag)`, key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}})
|
writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}})
|
||||||
return
|
return
|
||||||
@@ -394,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"`
|
||||||
@@ -417,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"`
|
||||||
@@ -443,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
|
||||||
@@ -462,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
|
||||||
@@ -480,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 {
|
||||||
@@ -503,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"))
|
||||||
@@ -527,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 {
|
||||||
@@ -543,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"`
|
||||||
@@ -567,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 {
|
||||||
@@ -582,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 {
|
||||||
@@ -613,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 {
|
||||||
@@ -646,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 {
|
||||||
@@ -670,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")
|
||||||
@@ -689,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 {
|
||||||
@@ -708,22 +742,63 @@ func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) {
|
|||||||
if len(ids) == 0 {
|
if len(ids) == 0 {
|
||||||
ids = input.ItemIDs
|
ids = input.ItemIDs
|
||||||
}
|
}
|
||||||
for position, itemID := range ids {
|
if len(ids) > maxPlaylistReorderItems {
|
||||||
_, _ = c.db.Exec(r.Context(), `UPDATE playlist_items SET position=$1 WHERE id=$2 AND playlist_id=$3 AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, position, itemID, id, user.ID)
|
writeError(w, http.StatusBadRequest, "too many items to reorder")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
positions := make([]int32, len(ids))
|
||||||
|
for position := range ids {
|
||||||
|
positions[position] = int32(position)
|
||||||
|
}
|
||||||
|
tx, err := c.db.Begin(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func() { _ = tx.Rollback(r.Context()) }()
|
||||||
|
if _, err := tx.Exec(r.Context(), `
|
||||||
|
UPDATE playlist_items AS i SET position=v.position
|
||||||
|
FROM unnest($1::bigint[], $2::int[]) AS v(item_id, position)
|
||||||
|
WHERE i.id=v.item_id AND i.playlist_id=$3
|
||||||
|
AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, ids, positions, id, user.ID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := tx.Commit(r.Context()); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not reorder playlist")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered"))
|
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Core) profile(w http.ResponseWriter, r *http.Request) {
|
// canSeeHidden reports whether the caller is a moderator, who may stream and view media that has
|
||||||
user := sharedauth.UserFromContext(r.Context())
|
// been hidden (active = FALSE). Everyone else gets hidden media as not found.
|
||||||
if user == nil {
|
func canSeeHidden(r *http.Request) bool {
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"user": nil})
|
return sharedauth.IsAdmin(sharedauth.UserFromContext(r.Context()))
|
||||||
return
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"user": user})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, error) {
|
// isHiddenMedia reports whether identifier names a media item that has been hidden. A lookup
|
||||||
|
// error counts as hidden, so a database fault never exposes hidden media.
|
||||||
|
func (c *Service) isHiddenMedia(ctx context.Context, identifier string) bool {
|
||||||
|
var hidden bool
|
||||||
|
err := c.db.QueryRow(ctx, `
|
||||||
|
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR id=$2))`,
|
||||||
|
strings.TrimSpace(identifier), mediaIDArg(strings.TrimSpace(identifier))).Scan(&hidden)
|
||||||
|
return err != nil || hidden
|
||||||
|
}
|
||||||
|
|
||||||
|
// MediaLookupOptions controls which otherwise-hidden records a media lookup may return.
|
||||||
|
type MediaLookupOptions struct {
|
||||||
|
// IncludeHidden lets moderators look up media with active = FALSE.
|
||||||
|
IncludeHidden bool
|
||||||
|
// RequireContentScannerProcessed limits the result to items imported by ContentScanner.
|
||||||
|
RequireContentScannerProcessed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindMedia looks up one media item by media key or numeric id. Shared media routes
|
||||||
|
// preserve moderator access to hidden items; ContentScanner-backed consumers can also
|
||||||
|
// request the same processed-only filtering used by MediaViewer's library routes.
|
||||||
|
func (c *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, `
|
||||||
@@ -731,15 +806,17 @@ func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, e
|
|||||||
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 CAST(id AS TEXT)=$1 LIMIT 1`, identifier)
|
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 {
|
||||||
@@ -778,8 +855,14 @@ func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, e
|
|||||||
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 {
|
||||||
@@ -791,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,
|
||||||
@@ -801,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
|
||||||
}
|
}
|
||||||
|
return result
|
||||||
// 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
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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", "")), ®istered)
|
|
||||||
var urls []string
|
|
||||||
for _, project := range registered {
|
|
||||||
key := strings.ToLower(strings.TrimSpace(project))
|
|
||||||
if !carrierNodeInstancePattern.MatchString(key) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if url := strings.TrimSpace(SettingValue(ctx, db, key+"_url", "")); url != "" {
|
|
||||||
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)) {
|
||||||
@@ -996,6 +928,44 @@ func urlPath(value string) string {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// upstreamMediaPath returns the CarrierNode path for a stored file path. It reports false only when
|
||||||
|
// the stored path is not a safe relative 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) {
|
||||||
|
relative := urlPath(filePath)
|
||||||
|
if !files.SafeRelative(relative) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return (&url.URL{Path: relative}).EscapedPath(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// canonicalMediaID returns the numeric media id that identifier spells exactly. Leading zeros, signs
|
||||||
|
// and whitespace are not canonical, so they never match an id.
|
||||||
|
func canonicalMediaID(identifier string) (int64, bool) {
|
||||||
|
if identifier == "" || strings.Trim(identifier, "0123456789") != "" {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
id, err := strconv.ParseInt(identifier, 10, 64)
|
||||||
|
if err != nil || strconv.FormatInt(id, 10) != identifier {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return id, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// mediaIDArg is the id query argument for identifier: the id when identifier is a canonical number,
|
||||||
|
// otherwise NULL, which matches no row. Comparing the id column directly, instead of casting it to
|
||||||
|
// text, lets the planner use the primary-key index for the id arm.
|
||||||
|
func mediaIDArg(identifier string) any {
|
||||||
|
if id, ok := canonicalMediaID(identifier); ok {
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func firstNonEmpty(values ...string) string {
|
func firstNonEmpty(values ...string) string {
|
||||||
for _, value := range values {
|
for _, value := range values {
|
||||||
if strings.TrimSpace(value) != "" {
|
if strings.TrimSpace(value) != "" {
|
||||||
@@ -1060,48 +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
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package media
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||||
|
)
|
||||||
|
|
||||||
|
// loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be
|
||||||
|
// exercised without a database.
|
||||||
|
type loginRequiredStore struct{}
|
||||||
|
|
||||||
|
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
|
||||||
|
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
|
||||||
|
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
|
||||||
|
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
|
||||||
|
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
|
||||||
|
|
||||||
|
// loginOffStore is loginRequiredStore with login switched off for the whole application.
|
||||||
|
type loginOffStore struct{ loginRequiredStore }
|
||||||
|
|
||||||
|
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
|
||||||
|
|
||||||
|
// TestMediaStreamAndThumbnailRequireLogin checks that anonymous requests to the media stream and
|
||||||
|
// thumbnail routes are refused when login is required, before any database lookup or CarrierNode
|
||||||
|
// call. The Core in this test has no database and no CarrierNode client, so reaching either would
|
||||||
|
// panic.
|
||||||
|
func TestMediaStreamAndThumbnailRequireLogin(t *testing.T) {
|
||||||
|
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
|
||||||
|
router := chi.NewRouter()
|
||||||
|
New(Config{Auth: auth}).Mount(router)
|
||||||
|
|
||||||
|
for _, request := range []struct{ method, target string }{
|
||||||
|
{http.MethodGet, "/media/stream?mediaKey=1"},
|
||||||
|
{http.MethodHead, "/media/stream?mediaKey=1"},
|
||||||
|
{http.MethodGet, "/media/thumb?mediaKey=1"},
|
||||||
|
} {
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(response, httptest.NewRequest(request.method, request.target, nil))
|
||||||
|
if response.Code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("%s %s status = %d, want %d", request.method, request.target, response.Code, http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMediaGateAllowsAnonymousWhenLoginIsOff checks the gate the media stream and thumbnail routes
|
||||||
|
// use: with login disabled an anonymous request reaches the handler, as it does for the rest of
|
||||||
|
// the application. The handler here is a stub, so no database or CarrierNode call is made.
|
||||||
|
func TestMediaGateAllowsAnonymousWhenLoginIsOff(t *testing.T) {
|
||||||
|
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject")
|
||||||
|
reached := false
|
||||||
|
gate := auth.RequireIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
reached = true
|
||||||
|
}))
|
||||||
|
for _, target := range []string{"/media/stream?mediaKey=1", "/media/thumb?mediaKey=1"} {
|
||||||
|
reached = false
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
gate.ServeHTTP(response, httptest.NewRequest(http.MethodGet, target, nil))
|
||||||
|
if !reached || response.Code != http.StatusOK {
|
||||||
|
t.Errorf("GET %s with login off: reached = %v, status = %d; want reached and 200", target, reached, response.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newRoleAuthGuard stands in for AuthGuard's GET /api/me. Each bearer token maps to one role, so a
|
||||||
|
// test can act as a viewer, a moderator or an admin without a database.
|
||||||
|
func newRoleAuthGuard(t *testing.T) *httptest.Server {
|
||||||
|
t.Helper()
|
||||||
|
roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
role, ok := roles[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
|
||||||
|
if !ok || r.URL.Path != "/api/me" {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
fmt.Fprintf(w, `{"user":{"id":1,"username":"tester","role":%q}}`, role)
|
||||||
|
}))
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
return server
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOnlyModeratorsCanSeeHiddenMedia checks which callers get hidden media looked up at all.
|
||||||
|
// Anonymous callers and viewers may not; moderators and admins may. With login off every caller
|
||||||
|
// is the placeholder superadmin, as for the rest of the application. The active = FALSE filter
|
||||||
|
// itself needs a database and is not exercised here.
|
||||||
|
func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) {
|
||||||
|
guard := newRoleAuthGuard(t)
|
||||||
|
login := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
|
||||||
|
loginOff := sharedauth.NewWithStore(loginOffStore{}, "session", false, guard.URL, "testproject")
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
auth *sharedauth.Service
|
||||||
|
token string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"anonymous with login required", login, "", "false"},
|
||||||
|
{"viewer", login, "viewer-token", "false"},
|
||||||
|
{"moderator", login, "moderator-token", "true"},
|
||||||
|
{"admin", login, "admin-token", "true"},
|
||||||
|
{"anonymous with login off", loginOff, "", "true"},
|
||||||
|
} {
|
||||||
|
router := chi.NewRouter()
|
||||||
|
router.With(tc.auth.Optional).Get("/probe", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, canSeeHidden(r))
|
||||||
|
})
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||||
|
if tc.token != "" {
|
||||||
|
request.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: tc.token})
|
||||||
|
}
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(response, request)
|
||||||
|
if got := response.Body.String(); got != tc.want {
|
||||||
|
t.Errorf("%s: canSeeHidden = %q, want %q", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStreamUpstreamPathForwardsOnlyLiveTranscodeOptions(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
query url.Values
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"plain stream", url.Values{"mediaKey": {"abc"}}, "/media/Videos/clip.mp4"},
|
||||||
|
{"blank options are dropped", url.Values{"quality": {" "}, "start": {""}}, "/media/Videos/clip.mp4"},
|
||||||
|
{"quality and start are forwarded", url.Values{"mediaKey": {"abc"}, "quality": {"1080"}, "start": {" 12.5 "}}, "/media/Videos/clip.mp4?quality=1080&start=12.5"},
|
||||||
|
{"quality alone", url.Values{"quality": {"720"}}, "/media/Videos/clip.mp4?quality=720"},
|
||||||
|
{"format is forwarded for audio copies", url.Values{"mediaKey": {"abc"}, "format": {"mp3"}}, "/media/Videos/clip.mp4?format=mp3"},
|
||||||
|
} {
|
||||||
|
if got := streamUpstreamPath("Videos/clip.mp4", tc.query); got != tc.want {
|
||||||
|
t.Errorf("%s: streamUpstreamPath() = %q, want %q", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,534 @@
|
|||||||
|
package media
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The tests in this file run the media routes against a real PostgreSQL database and a stand-in
|
||||||
|
// CarrierNode. They create the media tables and a few rows, so they are skipped unless
|
||||||
|
// SHARED_TEST_DATABASE_URL points at a scratch database, for example:
|
||||||
|
//
|
||||||
|
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./media/
|
||||||
|
|
||||||
|
const (
|
||||||
|
aliceID = 9101
|
||||||
|
bobID = 9102
|
||||||
|
modID = 9103
|
||||||
|
)
|
||||||
|
|
||||||
|
// newIdentityAuthGuard answers GET /api/me for three fixed sessions: two ordinary users and a moderator.
|
||||||
|
func newIdentityAuthGuard(t *testing.T) *httptest.Server {
|
||||||
|
t.Helper()
|
||||||
|
people := map[string]struct {
|
||||||
|
id int64
|
||||||
|
role string
|
||||||
|
}{"alice-token": {aliceID, "user"}, "bob-token": {bobID, "user"}, "mod-token": {modID, "moderator"}}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
person, ok := people[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
|
||||||
|
if !ok || r.URL.Path != "/api/me" {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
fmt.Fprintf(w, `{"user":{"id":%d,"username":"u%d","role":%q}}`, person.id, person.id, person.role)
|
||||||
|
}))
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
return server
|
||||||
|
}
|
||||||
|
|
||||||
|
// stubCarrierNode serves a body for every /media/ path and 404s the rest, recording what it was asked.
|
||||||
|
type stubCarrierNode struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
requests []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *stubCarrierNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
n.mu.Lock()
|
||||||
|
n.requests = append(n.requests, r.Method+" "+r.URL.EscapedPath())
|
||||||
|
n.mu.Unlock()
|
||||||
|
if !strings.HasPrefix(r.URL.Path, "/media/") {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
if r.Method != http.MethodHead {
|
||||||
|
_, _ = io.WriteString(w, "BYTES")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *stubCarrierNode) seen() []string {
|
||||||
|
n.mu.Lock()
|
||||||
|
defer n.mu.Unlock()
|
||||||
|
return append([]string(nil), n.requests...)
|
||||||
|
}
|
||||||
|
|
||||||
|
type dbHarness struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
router chi.Router
|
||||||
|
carrier *stubCarrierNode
|
||||||
|
hub *syncsocket.Hub
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDBHarness(t *testing.T) *dbHarness {
|
||||||
|
t.Helper()
|
||||||
|
url := os.Getenv("SHARED_TEST_DATABASE_URL")
|
||||||
|
if url == "" {
|
||||||
|
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres route tests")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open pool: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(pool.Close)
|
||||||
|
|
||||||
|
carrier := &stubCarrierNode{}
|
||||||
|
carrierServer := httptest.NewServer(carrier)
|
||||||
|
t.Cleanup(carrierServer.Close)
|
||||||
|
guard := newIdentityAuthGuard(t)
|
||||||
|
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
|
||||||
|
hub := syncsocket.NewHub()
|
||||||
|
core := New(Config{
|
||||||
|
DB: pool,
|
||||||
|
Auth: auth,
|
||||||
|
CarrierNode: carriernodeclient.New("", func(context.Context) string { return carrierServer.URL }),
|
||||||
|
ServiceName: "routes-test",
|
||||||
|
})
|
||||||
|
if err := core.Migrate(ctx); err != nil {
|
||||||
|
t.Fatalf("Migrate() error = %v", err)
|
||||||
|
}
|
||||||
|
cleanup := func() {
|
||||||
|
for _, statement := range []string{
|
||||||
|
`DELETE FROM playlists WHERE user_id IN (9101, 9102, 9103)`,
|
||||||
|
`DELETE FROM media_stats WHERE media_key LIKE 'rt-%' OR user_id IN (9101, 9102, 9103)`,
|
||||||
|
`DELETE FROM media_view_sessions WHERE media_key LIKE 'rt-%'`,
|
||||||
|
`DELETE FROM media_tag_votes WHERE media_key LIKE 'rt-%'`,
|
||||||
|
`DELETE FROM media_tags WHERE media_key LIKE 'rt-%'`,
|
||||||
|
`DELETE FROM media WHERE media_key LIKE 'rt-%'`,
|
||||||
|
`DELETE FROM users WHERE id IN (9101, 9102, 9103)`,
|
||||||
|
} {
|
||||||
|
if _, err := pool.Exec(ctx, statement); err != nil {
|
||||||
|
t.Fatalf("cleanup %q: %v", statement, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cleanup()
|
||||||
|
t.Cleanup(cleanup)
|
||||||
|
for _, id := range []int64{aliceID, bobID, modID} {
|
||||||
|
if _, err := pool.Exec(ctx, `INSERT INTO users (id, email, username, password_hash) VALUES ($1, $2, $3, 'x')`, id, fmt.Sprintf("rt%d@example.com", id), fmt.Sprintf("rt%d", id)); err != nil {
|
||||||
|
t.Fatalf("insert user: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
router := chi.NewRouter()
|
||||||
|
core.Mount(router)
|
||||||
|
return &dbHarness{pool: pool, router: router, carrier: carrier, hub: hub}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *dbHarness) insertMedia(t *testing.T, key, mediaType, filePath string, active bool) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := h.pool.Exec(context.Background(), `INSERT INTO media (media_key, media_type, file_path, active) VALUES ($1, $2, $3, $4)`, key, mediaType, filePath, active); err != nil {
|
||||||
|
t.Fatalf("insert media %s: %v", key, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *dbHarness) do(method, target, token, body string) *httptest.ResponseRecorder {
|
||||||
|
var reader io.Reader
|
||||||
|
if body != "" {
|
||||||
|
reader = strings.NewReader(body)
|
||||||
|
}
|
||||||
|
request := httptest.NewRequest(method, target, reader)
|
||||||
|
if token != "" {
|
||||||
|
request.AddCookie(&http.Cookie{Name: "auth_session", Value: token})
|
||||||
|
}
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
h.router.ServeHTTP(response, request)
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
func decode(t *testing.T, response *httptest.ResponseRecorder) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
var out map[string]any
|
||||||
|
if err := json.Unmarshal(response.Body.Bytes(), &out); err != nil {
|
||||||
|
t.Fatalf("body %q is not JSON: %v", response.Body.String(), err)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func dataOf(t *testing.T, response *httptest.ResponseRecorder) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
data, _ := decode(t, response)["data"].(map[string]any)
|
||||||
|
if data == nil {
|
||||||
|
t.Fatalf("response %s has no data object", response.Body.String())
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMediaStreamAndThumbnailAgainstPostgres(t *testing.T) {
|
||||||
|
h := newDBHarness(t)
|
||||||
|
h.insertMedia(t, "rt-visible", "video", "folder/clip one.mp4", true)
|
||||||
|
h.insertMedia(t, "rt-hidden", "video", "secret.mp4", false)
|
||||||
|
h.insertMedia(t, "rt-image", "image", "pics/photo.jpg", true)
|
||||||
|
h.insertMedia(t, "rt-escape", "video", "../etc/passwd", true)
|
||||||
|
h.insertMedia(t, "rt-query", "video", "a?b.mp4", true)
|
||||||
|
var visibleID int64
|
||||||
|
if err := h.pool.QueryRow(context.Background(), `SELECT id FROM media WHERE media_key='rt-visible'`).Scan(&visibleID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("an anonymous caller is refused while login is required", func(t *testing.T) {
|
||||||
|
if code := h.do(http.MethodGet, "/media/stream?mediaKey=rt-visible", "", "").Code; code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("status = %d, want 401", code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("a stored path reaches CarrierNode escaped, by key or by id, for GET and HEAD", func(t *testing.T) {
|
||||||
|
for _, target := range []string{"/media/stream?mediaKey=rt-visible", fmt.Sprintf("/media/stream?id=%d", visibleID)} {
|
||||||
|
response := h.do(http.MethodGet, target, "alice-token", "")
|
||||||
|
if response.Code != http.StatusOK || response.Body.String() != "BYTES" {
|
||||||
|
t.Fatalf("GET %s = %d %q, want the proxied bytes", target, response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if response := h.do(http.MethodHead, "/media/stream?mediaKey=rt-visible", "alice-token", ""); response.Code != http.StatusOK || response.Body.Len() != 0 {
|
||||||
|
t.Fatalf("HEAD = %d with %d body bytes, want 200 and none", response.Code, response.Body.Len())
|
||||||
|
}
|
||||||
|
for _, request := range h.carrier.seen() {
|
||||||
|
if request != "GET /media/folder/clip%20one.mp4" && request != "HEAD /media/folder/clip%20one.mp4" {
|
||||||
|
t.Fatalf("CarrierNode saw %q, want the escaped stored path", request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("unsafe stored paths and unknown keys are not found, and never reach CarrierNode", func(t *testing.T) {
|
||||||
|
before := len(h.carrier.seen())
|
||||||
|
for _, key := range []string{"rt-escape", "rt-missing", ""} {
|
||||||
|
if code := h.do(http.MethodGet, "/media/stream?mediaKey="+key, "alice-token", "").Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("stream of %q status = %d, want 404", key, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := len(h.carrier.seen()); got != before {
|
||||||
|
t.Fatalf("CarrierNode got %d extra requests, want none", got-before)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("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) {
|
||||||
|
for _, target := range []string{"/media/stream?mediaKey=rt-hidden", "/media/thumb?mediaKey=rt-hidden"} {
|
||||||
|
if code := h.do(http.MethodGet, target, "alice-token", "").Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("viewer GET %s = %d, want 404", target, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if response := h.do(http.MethodGet, "/media/stream?mediaKey=rt-hidden", "mod-token", ""); response.Code != http.StatusOK {
|
||||||
|
t.Errorf("moderator stream of hidden media = %d, want 200", response.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("a thumbnail falls back to the original image, and only for images", func(t *testing.T) {
|
||||||
|
response := h.do(http.MethodGet, "/media/thumb?mediaKey=rt-image", "alice-token", "")
|
||||||
|
if response.Code != http.StatusOK || response.Body.String() != "BYTES" {
|
||||||
|
t.Fatalf("image thumbnail = %d %q, want the original image", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodGet, "/media/thumb?mediaKey=rt-visible", "alice-token", "").Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("video without a thumbnail = %d, want 404", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodGet, "/media/thumb?mediaKey=../x", "alice-token", "").Code; code != http.StatusBadRequest {
|
||||||
|
t.Errorf("unsafe thumbnail id = %d, want 400", code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMediaStatsAndViewsAgainstPostgres(t *testing.T) {
|
||||||
|
h := newDBHarness(t)
|
||||||
|
h.insertMedia(t, "rt-stats", "video", "rt-stats.mp4", true)
|
||||||
|
state := func(token string) map[string]any {
|
||||||
|
return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
if code := h.do(http.MethodGet, "/media/state", "", "").Code; code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("state without a key = %d, want 400", code)
|
||||||
|
}
|
||||||
|
for _, body := range []string{`{}`, `{"mediaKey":"rt-stats","bogus":1}`, `nope`} {
|
||||||
|
if code := h.do(http.MethodPost, "/media/like", "alice-token", body).Code; code != http.StatusBadRequest {
|
||||||
|
t.Errorf("like with %q = %d, want 400", body, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats"}`)
|
||||||
|
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats"}`) // a repeat is not a second like
|
||||||
|
h.do(http.MethodPost, "/media/like", "bob-token", `{"mediaKey":"rt-stats","like":true}`)
|
||||||
|
h.do(http.MethodPost, "/media/save", "alice-token", `{"mediaKey":"rt-stats"}`)
|
||||||
|
if got := state("alice-token"); got["likeCount"] != float64(2) || got["saveCount"] != float64(1) || got["likedByUser"] != true || got["savedByUser"] != true {
|
||||||
|
t.Fatalf("state for alice = %v", got)
|
||||||
|
}
|
||||||
|
if got := state("bob-token"); got["likedByUser"] != true || got["savedByUser"] != false {
|
||||||
|
t.Fatalf("state for bob = %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if response := h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-stats","like":false}`); dataOf(t, response)["enabled"] != false {
|
||||||
|
t.Fatalf("unlike = %s", response.Body.String())
|
||||||
|
}
|
||||||
|
if got := state("alice-token"); got["likeCount"] != float64(1) || got["likedByUser"] != false {
|
||||||
|
t.Fatalf("state after unliking = %v", got)
|
||||||
|
}
|
||||||
|
h.do(http.MethodPost, "/media/like", "bob-token", `{"mediaKey":"rt-stats","value":false}`)
|
||||||
|
if got := state(""); got["likeCount"] != float64(0) {
|
||||||
|
t.Fatalf("anonymous state after both unlikes = %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.do(http.MethodPost, "/media/like", "alice-token", `{"mediaKey":"rt-liked"}`)
|
||||||
|
liked := decode(t, h.do(http.MethodGet, "/media/liked", "alice-token", ""))["items"].([]any)
|
||||||
|
if len(liked) != 1 || liked[0].(map[string]any)["mediaKey"] != "rt-liked" {
|
||||||
|
t.Fatalf("liked = %v, want only rt-liked", liked)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Views and watch sessions can be recorded without logging in.
|
||||||
|
if code := h.do(http.MethodPost, "/media/view?mediaKey=rt-stats", "", "").Code; code != http.StatusOK {
|
||||||
|
t.Fatalf("anonymous view = %d, want 200", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodPost, "/media/view", "", "").Code; code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("view without a key = %d, want 400", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodPost, "/media/view-session", "", `{"mediaKey":"rt-stats","durationMs":1500}`).Code; code != http.StatusOK {
|
||||||
|
t.Fatalf("view session = %d, want 200", code)
|
||||||
|
}
|
||||||
|
for _, body := range []string{`{"mediaKey":"rt-stats"}`, `{"mediaKey":"rt-stats","durationMs":-3}`, `{"durationMs":10}`} {
|
||||||
|
if code := h.do(http.MethodPost, "/media/view-session", "", body).Code; code != http.StatusBadRequest {
|
||||||
|
t.Errorf("view session %q = %d, want 400", body, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := state(""); got["viewCount"] != float64(1) {
|
||||||
|
t.Fatalf("view count = %v, want 1", got["viewCount"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTagsAgainstPostgres(t *testing.T) {
|
||||||
|
h := newDBHarness(t)
|
||||||
|
for _, body := range []string{`{}`, `{"tag":" "}`, `{"tag":"` + strings.Repeat("x", 81) + `"}`, `nope`} {
|
||||||
|
if code := h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", body).Code; code != http.StatusBadRequest {
|
||||||
|
t.Errorf("add tag %q = %d, want 400", body, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", `{"tag":"Funny"}`).Code; code != http.StatusCreated {
|
||||||
|
t.Fatalf("add tag = %d, want 201", code)
|
||||||
|
}
|
||||||
|
h.do(http.MethodPost, "/media/rt-tags/tags", "alice-token", `{"tag":"Funny"}`) // the same user's repeat is ignored
|
||||||
|
h.do(http.MethodPost, "/media/rt-tags/tags", "bob-token", `{"tag":"Quiet"}`)
|
||||||
|
|
||||||
|
for _, vote := range []string{"2", "-2", "\"up\""} {
|
||||||
|
if code := h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "alice-token", `{"vote":`+vote+`}`).Code; code != http.StatusBadRequest {
|
||||||
|
t.Errorf("vote %s = %d, want 400", vote, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "alice-token", `{"vote":1}`)
|
||||||
|
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "bob-token", `{"vote":1}`)
|
||||||
|
h.do(http.MethodPost, "/media/rt-tags/tags/Quiet/vote", "alice-token", `{"vote":-1}`)
|
||||||
|
h.do(http.MethodPost, "/media/rt-tags/tags/Funny/vote", "bob-token", `{"vote":0}`) // clears bob's vote
|
||||||
|
|
||||||
|
tags := decode(t, h.do(http.MethodGet, "/media/rt-tags/tags", "", ""))["tags"].([]any)
|
||||||
|
if len(tags) != 2 {
|
||||||
|
t.Fatalf("tags = %v, want Funny and Quiet", tags)
|
||||||
|
}
|
||||||
|
first, second := tags[0].(map[string]any), tags[1].(map[string]any)
|
||||||
|
if first["tag"] != "Funny" || first["score"] != float64(1) || second["tag"] != "Quiet" || second["score"] != float64(-1) {
|
||||||
|
t.Fatalf("tags = %v, want Funny at 1 ahead of Quiet at -1", tags)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A tag keeps its rows after its media is hidden or leaves the library. Only the library's
|
||||||
|
// media is listed for the tag, so a tag's examples never point at a thumbnail that is not found.
|
||||||
|
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)
|
||||||
|
if len(listed) != 1 || listed[0].(map[string]any)["mediaKey"] != "rt-tags" {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlaylistsAgainstPostgres(t *testing.T) {
|
||||||
|
h := newDBHarness(t)
|
||||||
|
create := func(token, name string) *httptest.ResponseRecorder {
|
||||||
|
return h.do(http.MethodPost, "/playlists", token, `{"name":`+fmt.Sprintf("%q", name)+`}`)
|
||||||
|
}
|
||||||
|
for _, name := range []string{"", " ", strings.Repeat("n", 121)} {
|
||||||
|
if code := create("alice-token", name).Code; code != http.StatusBadRequest {
|
||||||
|
t.Errorf("create %q = %d, want 400", name, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
response := create("alice-token", "Road trip")
|
||||||
|
if response.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("create = %d, body %s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
id := int64(dataOf(t, response)["playlist"].(map[string]any)["id"].(float64))
|
||||||
|
if again := create("alice-token", "Road trip"); int64(dataOf(t, again)["playlist"].(map[string]any)["id"].(float64)) != id {
|
||||||
|
t.Fatal("creating the same name again made a second playlist")
|
||||||
|
}
|
||||||
|
base := fmt.Sprintf("/playlists/%d", id)
|
||||||
|
|
||||||
|
// Another user cannot see, change or delete it.
|
||||||
|
if code := h.do(http.MethodGet, base, "bob-token", "").Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("bob reading alice's playlist = %d, want 404", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodPost, base+"/items", "bob-token", `{"mediaKey":"rt-a"}`).Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("bob adding to alice's playlist = %d, want 404", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodDelete, base, "bob-token", "").Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("bob deleting alice's playlist = %d, want 404", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodGet, base+"/items", "", "").Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("anonymous items = %d, want 404", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodPost, "/playlists/abc/items", "alice-token", `{"mediaKey":"rt-a"}`).Code; code != http.StatusBadRequest {
|
||||||
|
t.Errorf("bad playlist id = %d, want 400", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, key := range []string{"rt-a", "rt-b", "rt-c"} {
|
||||||
|
if code := h.do(http.MethodPost, base+"/items", "alice-token", `{"mediaKey":"`+key+`"}`).Code; code != http.StatusCreated {
|
||||||
|
t.Fatalf("add %s = %d, want 201", key, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.do(http.MethodPost, base+"/items", "alice-token", `{"media_key":"rt-a"}`) // a repeat is ignored
|
||||||
|
if code := h.do(http.MethodPost, base+"/items", "alice-token", `{}`).Code; code != http.StatusBadRequest {
|
||||||
|
t.Errorf("add without a key = %d, want 400", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
keys := func() []string {
|
||||||
|
var out []string
|
||||||
|
for _, item := range dataOf(t, h.do(http.MethodGet, base+"/items", "alice-token", ""))["items"].([]any) {
|
||||||
|
out = append(out, item.(map[string]any)["mediaKey"].(string))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
itemIDs := map[string]int64{}
|
||||||
|
for _, item := range dataOf(t, h.do(http.MethodGet, base+"/items", "alice-token", ""))["items"].([]any) {
|
||||||
|
entry := item.(map[string]any)
|
||||||
|
itemIDs[entry["mediaKey"].(string)] = int64(entry["id"].(float64))
|
||||||
|
}
|
||||||
|
if len(itemIDs) != 3 {
|
||||||
|
t.Fatalf("items = %v, want three distinct entries", itemIDs)
|
||||||
|
}
|
||||||
|
|
||||||
|
reorder := fmt.Sprintf(`{"ids":[%d,%d,%d]}`, itemIDs["rt-c"], itemIDs["rt-a"], itemIDs["rt-b"])
|
||||||
|
if code := h.do(http.MethodPatch, base+"/items/reorder", "alice-token", reorder).Code; code != http.StatusOK {
|
||||||
|
t.Fatalf("reorder = %d, want 200", code)
|
||||||
|
}
|
||||||
|
if got := strings.Join(keys(), ","); got != "rt-c,rt-a,rt-b" {
|
||||||
|
t.Fatalf("order after reorder = %s, want rt-c,rt-a,rt-b", got)
|
||||||
|
}
|
||||||
|
// The older field name still works, and another user's reorder changes nothing.
|
||||||
|
h.do(http.MethodPatch, base+"/items/reorder", "alice-token", fmt.Sprintf(`{"itemIds":[%d,%d,%d]}`, itemIDs["rt-b"], itemIDs["rt-c"], itemIDs["rt-a"]))
|
||||||
|
if got := strings.Join(keys(), ","); got != "rt-b,rt-c,rt-a" {
|
||||||
|
t.Fatalf("order after itemIds reorder = %s, want rt-b,rt-c,rt-a", got)
|
||||||
|
}
|
||||||
|
h.do(http.MethodPatch, base+"/items/reorder", "bob-token", reorder)
|
||||||
|
if got := strings.Join(keys(), ","); got != "rt-b,rt-c,rt-a" {
|
||||||
|
t.Fatalf("bob's reorder changed alice's playlist to %s", got)
|
||||||
|
}
|
||||||
|
tooMany := make([]string, maxPlaylistReorderItems+1)
|
||||||
|
for i := range tooMany {
|
||||||
|
tooMany[i] = "1"
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodPatch, base+"/items/reorder", "alice-token", `{"ids":[`+strings.Join(tooMany, ",")+`]}`).Code; code != http.StatusBadRequest {
|
||||||
|
t.Errorf("an oversized reorder = %d, want 400", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
random := dataOf(t, h.do(http.MethodGet, base+"/random", "alice-token", ""))
|
||||||
|
if key, _ := random["mediaKey"].(string); key != "rt-a" && key != "rt-b" && key != "rt-c" {
|
||||||
|
t.Fatalf("random item = %v", random)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodGet, base+"/random", "bob-token", "").Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("bob's random pick from alice's playlist = %d, want 404", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
summary := dataOf(t, h.do(http.MethodGet, "/playlists/summary", "alice-token", ""))["playlists"].([]any)
|
||||||
|
if len(summary) != 1 || summary[0].(map[string]any)["item_count"] != float64(3) {
|
||||||
|
t.Fatalf("summary = %v, want one playlist with three items", summary)
|
||||||
|
}
|
||||||
|
if anonymous := dataOf(t, h.do(http.MethodGet, "/playlists/summary", "", ""))["playlists"].([]any); len(anonymous) != 0 {
|
||||||
|
t.Fatalf("anonymous summary = %v, want none", anonymous)
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteBody := `{"mediaKey":"rt-a"}`
|
||||||
|
if code := h.do(http.MethodDelete, base+"/items", "bob-token", deleteBody).Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("bob removing alice's item = %d, want 404", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodDelete, base+"/items", "alice-token", deleteBody).Code; code != http.StatusOK {
|
||||||
|
t.Errorf("alice removing her item = %d, want 200", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodDelete, base+"/items", "alice-token", deleteBody).Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("removing it twice = %d, want 404", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodDelete, base, "alice-token", "").Code; code != http.StatusOK {
|
||||||
|
t.Errorf("deleting the playlist = %d, want 200", code)
|
||||||
|
}
|
||||||
|
if code := h.do(http.MethodGet, base, "alice-token", "").Code; code != http.StatusNotFound {
|
||||||
|
t.Errorf("the deleted playlist = %d, want 404", code)
|
||||||
|
}
|
||||||
|
if listed := dataOf(t, h.do(http.MethodGet, "/playlists", "alice-token", ""))["playlists"].([]any); len(listed) != 0 {
|
||||||
|
t.Fatalf("playlists after deleting = %v, want none", listed)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package migrate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"testing/fstest"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
_ "github.com/jackc/pgx/v5/stdlib"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUpRefusesMissingInputsBeforeConnecting(t *testing.T) {
|
||||||
|
files := fstest.MapFS{"migrations/001_init.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n")}}
|
||||||
|
if err := Up(context.Background(), "", files, "migrations"); err == nil || !strings.Contains(err.Error(), "database URL is required") {
|
||||||
|
t.Fatalf("empty URL error = %v", err)
|
||||||
|
}
|
||||||
|
if err := Up(context.Background(), "postgres://localhost/none", nil, "migrations"); err == nil || !strings.Contains(err.Error(), "migration filesystem is required") {
|
||||||
|
t.Fatalf("nil filesystem error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpReportsAnUnreachableDatabase(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
files := fstest.MapFS{"migrations/001_init.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n")}}
|
||||||
|
err := Up(ctx, "postgres://nobody@127.0.0.1:1/none?sslmode=disable&connect_timeout=2", files, "migrations")
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "ping migration database") {
|
||||||
|
t.Fatalf("unreachable database error = %v, want a ping failure", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestUpAppliesMigrationsOnce runs real migrations. It creates goose_db_version and a table, so it
|
||||||
|
// is skipped unless SHARED_TEST_DATABASE_URL points at a scratch database, for example:
|
||||||
|
//
|
||||||
|
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./migrate/
|
||||||
|
func TestUpAppliesMigrationsOnce(t *testing.T) {
|
||||||
|
url := os.Getenv("SHARED_TEST_DATABASE_URL")
|
||||||
|
if url == "" {
|
||||||
|
t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres migration test")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
db, err := sql.Open("pgx", url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_, _ = db.Exec(`DROP TABLE IF EXISTS migrate_test_widgets; DROP TABLE IF EXISTS goose_db_version`)
|
||||||
|
})
|
||||||
|
_, _ = db.Exec(`DROP TABLE IF EXISTS migrate_test_widgets; DROP TABLE IF EXISTS goose_db_version`)
|
||||||
|
|
||||||
|
files := fstest.MapFS{
|
||||||
|
"migrations/001_widgets.sql": {Data: []byte("-- +goose Up\nCREATE TABLE migrate_test_widgets (id INT PRIMARY KEY);\n-- +goose Down\nDROP TABLE migrate_test_widgets;\n")},
|
||||||
|
"migrations/002_seed.sql": {Data: []byte("-- +goose Up\nINSERT INTO migrate_test_widgets (id) VALUES (1);\n-- +goose Down\nDELETE FROM migrate_test_widgets;\n")},
|
||||||
|
}
|
||||||
|
for run := 1; run <= 2; run++ {
|
||||||
|
if err := Up(ctx, url, files, "migrations"); err != nil {
|
||||||
|
t.Fatalf("run %d: Up() error = %v", run, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var rows int
|
||||||
|
if err := db.QueryRowContext(ctx, `SELECT count(*) FROM migrate_test_widgets`).Scan(&rows); err != nil || rows != 1 {
|
||||||
|
t.Fatalf("widgets = %d, %v; want the seed applied exactly once", rows, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
broken := fstest.MapFS{"migrations/003_broken.sql": {Data: []byte("-- +goose Up\nSELECT * FROM no_such_table;\n")}}
|
||||||
|
if err := Up(ctx, url, broken, "migrations"); err == nil || !strings.Contains(err.Error(), "run migrations") {
|
||||||
|
t.Fatalf("broken migration error = %v, want a run-migrations failure", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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`,
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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})
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
package syncsocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/coder/websocket"
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
// syncRouter mounts the sync routes on hub. Auth is disabled, so every caller is the placeholder
|
||||||
|
// administrator.
|
||||||
|
func syncRouter(hub *Hub) chi.Router {
|
||||||
|
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject", sharedauth.Disabled())
|
||||||
|
router := chi.NewRouter()
|
||||||
|
MountRoutes(router, hub, auth.Optional, auth.Require)
|
||||||
|
return router
|
||||||
|
}
|
||||||
|
|
||||||
|
func putSync(router http.Handler, target, body string) *httptest.ResponseRecorder {
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodPut, target, strings.NewReader(body)))
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPutSyncRejectsBadInput(t *testing.T) {
|
||||||
|
router := syncRouter(NewHub())
|
||||||
|
for name, body := range map[string]string{
|
||||||
|
"not JSON": `nope`,
|
||||||
|
"missing clientId": `{"mediaId":"m1"}`,
|
||||||
|
"blank clientId": `{"clientId":" ","mediaId":"m1"}`,
|
||||||
|
"object mediaId": `{"clientId":"c1","mediaId":{"a":1}}`,
|
||||||
|
"boolean mediaId": `{"clientId":"c1","mediaId":true}`,
|
||||||
|
"array playAt": `{"clientId":"c1","mediaId":"m1","playAt":[1]}`,
|
||||||
|
"object playAt": `{"clientId":"c1","mediaId":"m1","playAt":{"a":1}}`,
|
||||||
|
"clientId not text": `{"clientId":5,"mediaId":"m1"}`,
|
||||||
|
} {
|
||||||
|
if response := putSync(router, "/sync", body); response.Code != http.StatusBadRequest {
|
||||||
|
t.Errorf("%s: status = %d, want 400 (body %s)", name, response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
router := syncRouter(hub)
|
||||||
|
|
||||||
|
response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"c1","mediaId":42,"timeMs":-5,"paused":true,"fps":100000,"frame":9,"playAt":"2026-10-19T10:00:00Z"}`)
|
||||||
|
if response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("PUT status = %d, body %s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
var written struct {
|
||||||
|
Success bool `json:"success"`
|
||||||
|
State map[string]any `json:"state"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil || !written.Success {
|
||||||
|
t.Fatalf("PUT body = %s, %v", response.Body.String(), err)
|
||||||
|
}
|
||||||
|
state := written.State
|
||||||
|
if state["sessionId"] != "room-1" || state["fromClientId"] != "c1" || state["mediaId"] != float64(42) || state["paused"] != true {
|
||||||
|
t.Fatalf("state = %v", state)
|
||||||
|
}
|
||||||
|
if state["timeMs"] != float64(0) || state["fps"] != float64(240) || state["frame"] != float64(9) || state["playAt"] != "2026-10-19T10:00:00Z" {
|
||||||
|
t.Fatalf("a negative time was not clamped to 0, or fps to 240: %v", state)
|
||||||
|
}
|
||||||
|
|
||||||
|
get := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(get, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-1", nil))
|
||||||
|
var read map[string]any
|
||||||
|
if err := json.Unmarshal(get.Body.Bytes(), &read); err != nil || read["fromClientId"] != "c1" || read["mediaId"] != float64(42) {
|
||||||
|
t.Fatalf("GET /sync = %s, %v; want the stored state", get.Body.String(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
other := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(other, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-2", nil))
|
||||||
|
var empty map[string]any
|
||||||
|
if err := json.Unmarshal(other.Body.Bytes(), &empty); err != nil || empty["fromClientId"] == "c1" {
|
||||||
|
t.Fatalf("another session got %s, %v; want it untouched", other.Body.String(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) {
|
||||||
|
router := syncRouter(NewHub())
|
||||||
|
long := strings.Repeat("s", 300)
|
||||||
|
response := putSync(router, "/sync", `{"clientId":"`+strings.Repeat("c", 300)+`","mediaId":null,"sessionId":"`+long+`"}`)
|
||||||
|
if response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, body %s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
var written struct{ State map[string]any }
|
||||||
|
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := written.State["sessionId"].(string); len(got) != 128 {
|
||||||
|
t.Errorf("sessionId length = %d, want 128", len(got))
|
||||||
|
}
|
||||||
|
if got := written.State["fromClientId"].(string); len(got) != 128 {
|
||||||
|
t.Errorf("fromClientId length = %d, want 128", len(got))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPutSyncBroadcastsToThePeersOfThatSession checks the HTTP write reaches websocket peers in
|
||||||
|
// the session, and only those.
|
||||||
|
func TestPutSyncBroadcastsToThePeersOfThatSession(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
router := syncRouter(hub)
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hub.ServeWebSocket(w, r, "")
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
url := "ws" + strings.TrimPrefix(server.URL, "http")
|
||||||
|
|
||||||
|
join := func(session string) (*websocket.Conn, string) {
|
||||||
|
conn, _, err := websocket.Dial(ctx, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { conn.CloseNow() })
|
||||||
|
hello := readFrame(t, ctx, conn, "hello")
|
||||||
|
id := hello["clientId"].(string)
|
||||||
|
data, _ := json.Marshal(map[string]any{"type": "sync:hello", "clientId": id, "sessionId": session})
|
||||||
|
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
readFrame(t, ctx, conn, "sync:state")
|
||||||
|
return conn, id
|
||||||
|
}
|
||||||
|
inRoom, _ := join("room-1")
|
||||||
|
elsewhere, _ := join("room-2")
|
||||||
|
|
||||||
|
if response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"http-client","mediaId":"clip-9","timeMs":1500}`); response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("PUT status = %d", response.Code)
|
||||||
|
}
|
||||||
|
frame := readFrame(t, ctx, inRoom, "sync:state")
|
||||||
|
state, _ := frame["state"].(map[string]any)
|
||||||
|
if state["mediaId"] != "clip-9" || state["timeMs"] != float64(1500) {
|
||||||
|
t.Fatalf("the session peer got %v", frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
short, shortCancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||||
|
defer shortCancel()
|
||||||
|
if _, _, err := elsewhere.Read(short); err == nil {
|
||||||
|
t.Fatal("a peer in another session received the broadcast")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
for {
|
||||||
|
_, data, err := conn.Read(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read while waiting for %q: %v", want, err)
|
||||||
|
}
|
||||||
|
var message map[string]any
|
||||||
|
if err := json.Unmarshal(data, &message); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if message["type"] == want {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,14 +10,17 @@
|
|||||||
// 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
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"math"
|
"math"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
@@ -33,15 +34,20 @@ import (
|
|||||||
const (
|
const (
|
||||||
maxSyncIdentifier = 128
|
maxSyncIdentifier = 128
|
||||||
maxSyncSessions = 1000
|
maxSyncSessions = 1000
|
||||||
|
maxSyncConnections = 1000
|
||||||
|
maxPeerWriteQueue = 64
|
||||||
|
maxPeerMessagesPerSecond = 120
|
||||||
)
|
)
|
||||||
|
|
||||||
type peer struct {
|
type peer struct {
|
||||||
conn *websocket.Conn
|
conn *websocket.Conn
|
||||||
writeMu sync.Mutex
|
out chan []byte
|
||||||
|
done chan struct{}
|
||||||
|
closeOnce sync.Once
|
||||||
|
messageWindow time.Time
|
||||||
|
messageCount int
|
||||||
clientID string
|
clientID string
|
||||||
sessionID string
|
sessionID string
|
||||||
userAgent string
|
|
||||||
ipAddress string
|
|
||||||
remoteControlEnabled bool
|
remoteControlEnabled bool
|
||||||
uiView string
|
uiView string
|
||||||
uiMediaID any
|
uiMediaID any
|
||||||
@@ -73,16 +79,26 @@ func NewHub() *Hub {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hub) add(p *peer) {
|
// add registers a peer, or reports false when the hub already holds maxSyncConnections peers.
|
||||||
|
func (h *Hub) add(p *peer) bool {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
|
if len(h.peers) >= maxSyncConnections {
|
||||||
|
h.mu.Unlock()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
p.out = make(chan []byte, maxPeerWriteQueue)
|
||||||
|
p.done = make(chan struct{})
|
||||||
h.peers[p] = struct{}{}
|
h.peers[p] = struct{}{}
|
||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
|
go p.writeLoop()
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hub) remove(p *peer) string {
|
func (h *Hub) remove(p *peer) string {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
defer h.mu.Unlock()
|
defer h.mu.Unlock()
|
||||||
delete(h.peers, p)
|
delete(h.peers, p)
|
||||||
|
p.closeOnce.Do(func() { close(p.done) })
|
||||||
if p.clientID != "" && !h.hasClientLocked(p.clientID) {
|
if p.clientID != "" && !h.hasClientLocked(p.clientID) {
|
||||||
delete(h.controlOwners, p.clientID)
|
delete(h.controlOwners, p.clientID)
|
||||||
for targetID, ownerID := range h.controlOwners {
|
for targetID, ownerID := range h.controlOwners {
|
||||||
@@ -103,11 +119,8 @@ func (h *Hub) hasClientLocked(clientID string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hub) updatePeer(p *peer, clientID, sessionID string) {
|
func (h *Hub) updatePeer(p *peer, sessionID string) {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
if clientID != "" {
|
|
||||||
p.clientID = clientID
|
|
||||||
}
|
|
||||||
if sessionID != "" {
|
if sessionID != "" {
|
||||||
p.sessionID = sessionID
|
p.sessionID = sessionID
|
||||||
}
|
}
|
||||||
@@ -145,8 +158,6 @@ func (h *Hub) clientsLocked(sessionID string) []map[string]any {
|
|||||||
if !exists {
|
if !exists {
|
||||||
entry = map[string]any{
|
entry = map[string]any{
|
||||||
"clientId": p.clientID,
|
"clientId": p.clientID,
|
||||||
"userAgent": p.userAgent,
|
|
||||||
"ipAddress": p.ipAddress,
|
|
||||||
"remoteControlEnabled": p.remoteControlEnabled,
|
"remoteControlEnabled": p.remoteControlEnabled,
|
||||||
"controlOwnerClientId": nil,
|
"controlOwnerClientId": nil,
|
||||||
}
|
}
|
||||||
@@ -191,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()
|
||||||
@@ -199,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()
|
||||||
@@ -244,9 +255,13 @@ func (h *Hub) Broadcast(sessionID string) {
|
|||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
|
|
||||||
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
|
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
|
||||||
|
data, err := json.Marshal(message)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
for _, p := range peers {
|
for _, p := range peers {
|
||||||
if err := p.send(message); err != nil {
|
if err := p.sendData(data); err != nil {
|
||||||
_ = p.conn.Close(websocket.StatusGoingAway, "write failed")
|
p.drop(websocket.StatusGoingAway, "slow or closed peer")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -256,20 +271,76 @@ func (p *peer) send(message any) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
p.writeMu.Lock()
|
return p.sendData(data)
|
||||||
defer p.writeMu.Unlock()
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
return p.conn.Write(ctx, websocket.MessageText, data)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *peer) sendData(data []byte) error {
|
||||||
|
select {
|
||||||
|
case <-p.done:
|
||||||
|
return context.Canceled
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case p.out <- data:
|
||||||
|
return nil
|
||||||
|
case <-p.done:
|
||||||
|
return context.Canceled
|
||||||
|
default:
|
||||||
|
return errPeerWriteQueueFull
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var errPeerWriteQueueFull = errors.New("sync websocket peer write queue is full")
|
||||||
|
|
||||||
|
func (p *peer) writeLoop() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-p.done:
|
||||||
|
return
|
||||||
|
case data := <-p.out:
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
err := p.conn.Write(ctx, websocket.MessageText, data)
|
||||||
|
cancel()
|
||||||
|
if err != nil {
|
||||||
|
p.stop(websocket.StatusGoingAway, "write failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *peer) allowMessage(now time.Time) bool {
|
||||||
|
if now.Sub(p.messageWindow) >= time.Second {
|
||||||
|
p.messageWindow = now
|
||||||
|
p.messageCount = 0
|
||||||
|
}
|
||||||
|
p.messageCount++
|
||||||
|
return p.messageCount <= maxPeerMessagesPerSecond
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *peer) close() {
|
||||||
|
p.stop(websocket.StatusPolicyViolation, "message rate exceeded")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *peer) stop(status websocket.StatusCode, reason string) {
|
||||||
|
p.closeOnce.Do(func() { close(p.done) })
|
||||||
|
_ = p.conn.Close(status, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
// drop stops a peer on behalf of code that is serving other peers or an HTTP request. Close waits
|
||||||
|
// for the peer's close frame (up to five seconds), which a stuck peer never sends, so it runs in
|
||||||
|
// its own goroutine instead of holding up the caller.
|
||||||
|
func (p *peer) drop(status websocket.StatusCode, reason string) {
|
||||||
|
p.closeOnce.Do(func() { close(p.done) })
|
||||||
|
go func() { _ = p.conn.Close(status, reason) }()
|
||||||
|
}
|
||||||
|
|
||||||
|
// websocketAcceptOptions enables origin verification for every connection. A
|
||||||
|
// configured origin and the request's own host are accepted. "*" adds no
|
||||||
|
// extra origin, so it does not turn the check off: a page on another site
|
||||||
|
// cannot open the socket unless its origin is listed explicitly.
|
||||||
func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions {
|
func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions {
|
||||||
options := &websocket.AcceptOptions{}
|
options := &websocket.AcceptOptions{}
|
||||||
if allowedOrigin == "*" {
|
|
||||||
options.InsecureSkipVerify = true
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
|
|
||||||
patterns := make([]string, 0, 2)
|
patterns := make([]string, 0, 2)
|
||||||
addOrigin := func(value string) {
|
addOrigin := func(value string) {
|
||||||
parsed, err := url.Parse(strings.TrimSpace(value))
|
parsed, err := url.Parse(strings.TrimSpace(value))
|
||||||
@@ -287,20 +358,55 @@ func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.Ac
|
|||||||
return options
|
return options
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// newClientID returns a random identifier for one connection. The hub issues it
|
||||||
|
// at upgrade time and clients cannot choose it, so two connections never share
|
||||||
|
// an identity.
|
||||||
|
func newClientID() (string, error) {
|
||||||
|
var buf [16]byte
|
||||||
|
if _, err := rand.Read(buf[:]); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(buf[:]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// acceptsClientID reports whether a message's clientId, if it carries one,
|
||||||
|
// names the identity issued to this connection. A message without clientId
|
||||||
|
// is taken as this connection's own.
|
||||||
|
func (p *peer) acceptsClientID(message map[string]any) bool {
|
||||||
|
requested := boundedSyncString(syncString(message, "clientId"))
|
||||||
|
return requested == "" || requested == p.clientID
|
||||||
|
}
|
||||||
|
|
||||||
|
// refuseClientID drops a message that named another identity. The connection
|
||||||
|
// stays open, and the error frame repeats the identity the client holds.
|
||||||
|
func (p *peer) refuseClientID() {
|
||||||
|
_ = p.send(map[string]any{"type": "error", "code": "client-id-mismatch", "clientId": p.clientID})
|
||||||
|
}
|
||||||
|
|
||||||
// ServeWebSocket upgrades the request to a websocket connection and services
|
// ServeWebSocket upgrades the request to a websocket connection and services
|
||||||
// it until the client disconnects. allowedOrigin should be the service's own
|
// it until the client disconnects. allowedOrigin should be the service's own
|
||||||
// CORS_ORIGIN config value (or "*" to accept any origin).
|
// explicit CORS_ORIGIN value; "*" does not bypass origin verification.
|
||||||
|
//
|
||||||
|
// Each connection is issued a clientId at upgrade time. It is sent in the
|
||||||
|
// first "hello" frame, and every later message must either omit clientId or
|
||||||
|
// repeat it. A message naming any other identity gets a "client-id-mismatch"
|
||||||
|
// error frame and is otherwise ignored. A reconnect is a new connection with a
|
||||||
|
// new identity.
|
||||||
func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) {
|
func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) {
|
||||||
conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin))
|
conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
p := &peer{
|
clientID, err := newClientID()
|
||||||
conn: conn,
|
if err != nil {
|
||||||
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
|
_ = conn.Close(websocket.StatusInternalError, "could not issue client identity")
|
||||||
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
|
return
|
||||||
|
}
|
||||||
|
p := &peer{conn: conn, clientID: clientID}
|
||||||
|
if !h.add(p) {
|
||||||
|
_ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
h.add(p)
|
|
||||||
defer func() {
|
defer func() {
|
||||||
sessionID := h.remove(p)
|
sessionID := h.remove(p)
|
||||||
_ = conn.Close(websocket.StatusNormalClosure, "")
|
_ = conn.Close(websocket.StatusNormalClosure, "")
|
||||||
@@ -309,12 +415,16 @@ func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrig
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
_ = p.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()})
|
_ = p.send(map[string]any{"type": "hello", "clientId": clientID, "ts": time.Now().UnixMilli()})
|
||||||
for {
|
for {
|
||||||
messageType, payload, readErr := conn.Read(r.Context())
|
messageType, payload, readErr := conn.Read(r.Context())
|
||||||
if readErr != nil {
|
if readErr != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if !p.allowMessage(time.Now()) {
|
||||||
|
p.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
if messageType != websocket.MessageText {
|
if messageType != websocket.MessageText {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -337,20 +447,23 @@ func (h *Hub) handleMessage(p *peer, message map[string]any) {
|
|||||||
"serverReceivedAt": time.Now().UnixMilli(),
|
"serverReceivedAt": time.Now().UnixMilli(),
|
||||||
})
|
})
|
||||||
case "sync:hello":
|
case "sync:hello":
|
||||||
clientID := boundedSyncString(syncString(message, "clientId"))
|
if !p.acceptsClientID(message) {
|
||||||
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
|
p.refuseClientID()
|
||||||
if clientID == "" || sessionID == "" {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.updatePeer(p, clientID, sessionID)
|
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
|
||||||
|
if sessionID == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.updatePeer(p, sessionID)
|
||||||
h.Broadcast(sessionID)
|
h.Broadcast(sessionID)
|
||||||
case "client:status":
|
case "client:status":
|
||||||
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
|
if !p.acceptsClientID(message) {
|
||||||
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
|
p.refuseClientID()
|
||||||
if clientID == "" {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.updatePeer(p, clientID, sessionID)
|
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
|
||||||
|
h.updatePeer(p, sessionID)
|
||||||
mediaID, mediaIDSet := syncMediaID(message)
|
mediaID, mediaIDSet := syncMediaID(message)
|
||||||
remote, remoteSet := message["remoteControlEnabled"].(bool)
|
remote, remoteSet := message["remoteControlEnabled"].(bool)
|
||||||
h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
|
h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
|
||||||
@@ -363,10 +476,14 @@ func (h *Hub) handleMessage(p *peer, message map[string]any) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) {
|
func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) {
|
||||||
requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
|
if !p.acceptsClientID(message) {
|
||||||
|
p.refuseClientID()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
requesterID := p.clientID
|
||||||
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
|
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
|
||||||
targetID := boundedSyncString(syncString(message, "targetClientId"))
|
targetID := boundedSyncString(syncString(message, "targetClientId"))
|
||||||
if requesterID == "" || targetID == "" || requesterID != p.clientID {
|
if targetID == "" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -413,11 +530,12 @@ func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
|
func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
|
||||||
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
|
if !p.acceptsClientID(message) {
|
||||||
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
|
p.refuseClientID()
|
||||||
if clientID == "" || clientID != p.clientID {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
clientID := p.clientID
|
||||||
|
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
|
||||||
mediaID, _ := syncMediaID(message)
|
mediaID, _ := syncMediaID(message)
|
||||||
paused := syncBool(message, "paused")
|
paused := syncBool(message, "paused")
|
||||||
state := map[string]any{
|
state := map[string]any{
|
||||||
@@ -453,6 +571,9 @@ func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
|
|||||||
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
|
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
|
||||||
h.capturedAtMs[sessionID] = captured
|
h.capturedAtMs[sessionID] = captured
|
||||||
}
|
}
|
||||||
|
trimSessionMap(h.playAt)
|
||||||
|
trimSessionMap(h.playAtLocalMs)
|
||||||
|
trimSessionMap(h.capturedAtMs)
|
||||||
if toClientID == "" {
|
if toClientID == "" {
|
||||||
h.states[sessionID] = cloneMap(state)
|
h.states[sessionID] = cloneMap(state)
|
||||||
if len(h.states) > maxSyncSessions {
|
if len(h.states) > maxSyncSessions {
|
||||||
@@ -478,7 +599,7 @@ func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
|
|||||||
if toClientID != "" {
|
if toClientID != "" {
|
||||||
for _, target := range peers {
|
for _, target := range peers {
|
||||||
if err := target.send(messageOut); err != nil {
|
if err := target.send(messageOut); err != nil {
|
||||||
_ = target.conn.Close(websocket.StatusGoingAway, "write failed")
|
target.drop(websocket.StatusGoingAway, "write failed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
@@ -571,6 +692,18 @@ func cloneMap(value map[string]any) map[string]any {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// trimSessionMap keeps a per-session map within maxSyncSessions by dropping entries, the same
|
||||||
|
// bound the states map uses. Session IDs come from clients, so without it each map would grow
|
||||||
|
// for every ID ever seen.
|
||||||
|
func trimSessionMap[V any](values map[string]V) {
|
||||||
|
for len(values) > maxSyncSessions {
|
||||||
|
for key := range values {
|
||||||
|
delete(values, key)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func firstNonEmpty(values ...string) string {
|
func firstNonEmpty(values ...string) string {
|
||||||
for _, value := range values {
|
for _, value := range values {
|
||||||
if strings.TrimSpace(value) != "" {
|
if strings.TrimSpace(value) != "" {
|
||||||
|
|||||||
@@ -0,0 +1,318 @@
|
|||||||
|
package syncsocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/coder/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the
|
||||||
|
// per-session timing maps past maxSyncSessions.
|
||||||
|
func TestSessionTimingMapsStayBounded(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
p := &peer{clientID: "client-1"}
|
||||||
|
for i := 0; i < maxSyncSessions+100; i++ {
|
||||||
|
hub.handleSyncUpdate(p, map[string]any{
|
||||||
|
"clientId": "client-1",
|
||||||
|
"sessionId": fmt.Sprintf("session-%d", i),
|
||||||
|
"paused": false,
|
||||||
|
"playAt": "2026-10-19T10:00:00Z",
|
||||||
|
"playAtLocalMs": float64(1),
|
||||||
|
"capturedAtLocalMs": float64(1),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if n := len(hub.playAt); n > maxSyncSessions {
|
||||||
|
t.Errorf("playAt holds %d sessions, want at most %d", n, maxSyncSessions)
|
||||||
|
}
|
||||||
|
if n := len(hub.playAtLocalMs); n > maxSyncSessions {
|
||||||
|
t.Errorf("playAtLocalMs holds %d sessions, want at most %d", n, maxSyncSessions)
|
||||||
|
}
|
||||||
|
if n := len(hub.capturedAtMs); n > maxSyncSessions {
|
||||||
|
t.Errorf("capturedAtMs holds %d sessions, want at most %d", n, maxSyncSessions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestHubRefusesPeersBeyondTheConnectionCap checks that the hub stops registering connections
|
||||||
|
// once it holds maxSyncConnections peers.
|
||||||
|
func TestHubRefusesPeersBeyondTheConnectionCap(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
for i := 0; i < maxSyncConnections; i++ {
|
||||||
|
if !hub.add(&peer{}) {
|
||||||
|
t.Fatalf("add refused peer %d, below the cap", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if hub.add(&peer{}) {
|
||||||
|
t.Fatal("add accepted a peer beyond maxSyncConnections")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWildcardOriginKeepsOriginVerification checks that CORS_ORIGIN "*" does not disable the
|
||||||
|
// websocket origin check: only the request's own host is accepted.
|
||||||
|
func TestWildcardOriginKeepsOriginVerification(t *testing.T) {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "http://hub.example.com/ws", nil)
|
||||||
|
options := websocketAcceptOptions(req, "*")
|
||||||
|
if options.InsecureSkipVerify {
|
||||||
|
t.Fatal("wildcard origin disabled origin verification")
|
||||||
|
}
|
||||||
|
if want := []string{"http://hub.example.com"}; !slices.Equal(options.OriginPatterns, want) {
|
||||||
|
t.Fatalf("origin patterns = %v, want %v", options.OriginPatterns, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestExplicitOriginIsAcceptedAlongsideTheRequestHost checks that a listed origin is accepted
|
||||||
|
// without turning the check off.
|
||||||
|
func TestExplicitOriginIsAcceptedAlongsideTheRequestHost(t *testing.T) {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "https://hub.example.com/ws", nil)
|
||||||
|
options := websocketAcceptOptions(req, "https://app.example.com/")
|
||||||
|
if options.InsecureSkipVerify {
|
||||||
|
t.Fatal("explicit origin disabled origin verification")
|
||||||
|
}
|
||||||
|
for _, want := range []string{"https://app.example.com", "https://hub.example.com"} {
|
||||||
|
if !slices.Contains(options.OriginPatterns, want) {
|
||||||
|
t.Errorf("origin patterns %v missing %q", options.OriginPatterns, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestClientListOmitsPeerAddressAndUserAgent checks that broadcast client entries carry no peer
|
||||||
|
// IP address or user agent.
|
||||||
|
func TestClientListOmitsPeerAddressAndUserAgent(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
hub.add(&peer{clientID: "client-1", sessionID: "session-1", remoteControlEnabled: true})
|
||||||
|
clients := hub.clientsLocked("session-1")
|
||||||
|
if len(clients) != 1 {
|
||||||
|
t.Fatalf("clients = %d, want 1", len(clients))
|
||||||
|
}
|
||||||
|
for _, key := range []string{"ipAddress", "userAgent"} {
|
||||||
|
if _, ok := clients[0][key]; ok {
|
||||||
|
t.Errorf("client entry carries %q", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if clients[0]["clientId"] != "client-1" {
|
||||||
|
t.Errorf("clientId = %v, want client-1", clients[0]["clientId"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestClientIdentityIsIssuedAtUpgradeAndEnforced checks the protocol change: each connection gets a
|
||||||
|
// server-issued clientId in its hello frame, a message naming another identity is refused with an
|
||||||
|
// error frame, and a message carrying the issued identity is applied.
|
||||||
|
func TestClientIdentityIsIssuedAtUpgradeAndEnforced(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hub.ServeWebSocket(w, r, "")
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
url := "ws" + strings.TrimPrefix(server.URL, "http")
|
||||||
|
|
||||||
|
first := dialSyncSocket(t, ctx, url)
|
||||||
|
defer first.CloseNow()
|
||||||
|
second := dialSyncSocket(t, ctx, url)
|
||||||
|
defer second.CloseNow()
|
||||||
|
firstID := readSyncFrame(t, ctx, first, "hello")["clientId"].(string)
|
||||||
|
secondID := readSyncFrame(t, ctx, second, "hello")["clientId"].(string)
|
||||||
|
if len(firstID) != 32 || firstID == secondID {
|
||||||
|
t.Fatalf("issued identities = %q and %q, want two distinct 32-character IDs", firstID, secondID)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": secondID, "sessionId": "s1"})
|
||||||
|
refusal := readSyncFrame(t, ctx, first, "error")
|
||||||
|
if refusal["code"] != "client-id-mismatch" || refusal["clientId"] != firstID {
|
||||||
|
t.Fatalf("refusal = %v, want client-id-mismatch carrying the issued identity", refusal)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": firstID, "sessionId": "s1"})
|
||||||
|
state := readSyncFrame(t, ctx, first, "sync:state")
|
||||||
|
clients, _ := state["clients"].([]any)
|
||||||
|
found := false
|
||||||
|
for _, entry := range clients {
|
||||||
|
if client, ok := entry.(map[string]any); ok && client["clientId"] == firstID {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatalf("clients = %v, want the issued identity %q listed", clients, firstID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAcceptsClientIDOnlyForTheIssuedIdentity(t *testing.T) {
|
||||||
|
p := &peer{clientID: "issued"}
|
||||||
|
for _, tt := range []struct {
|
||||||
|
name string
|
||||||
|
message map[string]any
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"no clientId", map[string]any{}, true},
|
||||||
|
{"the issued identity", map[string]any{"clientId": "issued"}, true},
|
||||||
|
{"another identity", map[string]any{"clientId": "other"}, false},
|
||||||
|
{"an oversized identity", map[string]any{"clientId": strings.Repeat("x", maxSyncIdentifier+1)}, false},
|
||||||
|
} {
|
||||||
|
if got := p.acceptsClientID(tt.message); got != tt.want {
|
||||||
|
t.Errorf("%s: acceptsClientID = %v, want %v", tt.name, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPeerMessageRateWindow checks the per-peer limit: maxPeerMessagesPerSecond messages are
|
||||||
|
// allowed in a one-second window, the next is refused, and the count restarts with the next window.
|
||||||
|
func TestPeerMessageRateWindow(t *testing.T) {
|
||||||
|
p := &peer{}
|
||||||
|
start := time.Unix(1000, 0)
|
||||||
|
for i := 0; i < maxPeerMessagesPerSecond; i++ {
|
||||||
|
if !p.allowMessage(start.Add(time.Duration(i) * time.Millisecond)) {
|
||||||
|
t.Fatalf("message %d refused inside the limit", i+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.allowMessage(start.Add(500 * time.Millisecond)) {
|
||||||
|
t.Fatal("a message past the limit was allowed")
|
||||||
|
}
|
||||||
|
if !p.allowMessage(start.Add(time.Second)) {
|
||||||
|
t.Fatal("the count did not restart with the next window")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPeerExceedingTheMessageRateIsDisconnected checks that a client flooding messages is closed
|
||||||
|
// with a policy-violation status instead of being fanned out.
|
||||||
|
func TestPeerExceedingTheMessageRateIsDisconnected(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hub.ServeWebSocket(w, r, "")
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
conn := dialSyncSocket(t, ctx, "ws"+strings.TrimPrefix(server.URL, "http"))
|
||||||
|
defer conn.CloseNow()
|
||||||
|
readSyncFrame(t, ctx, conn, "hello")
|
||||||
|
go func() {
|
||||||
|
for i := 0; i < maxPeerMessagesPerSecond*4; i++ {
|
||||||
|
if conn.Write(ctx, websocket.MessageText, []byte(`{"type":"ws:ping"}`)) != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
if _, _, err := conn.Read(ctx); err != nil {
|
||||||
|
if got := websocket.CloseStatus(err); got != websocket.StatusPolicyViolation {
|
||||||
|
t.Fatalf("close status = %v (error %v), want policy violation", got, err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking checks that a peer that never drains its
|
||||||
|
// write queue is stopped by Broadcast, which returns at once, and that a healthy peer in the same
|
||||||
|
// session still receives the state.
|
||||||
|
func TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking(t *testing.T) {
|
||||||
|
hub := NewHub()
|
||||||
|
slowReady := make(chan *peer, 1)
|
||||||
|
release := make(chan struct{})
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/slow" {
|
||||||
|
hub.ServeWebSocket(w, r, "")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn, err := websocket.Accept(w, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.CloseNow()
|
||||||
|
p := &peer{
|
||||||
|
conn: conn, clientID: "slow", sessionID: "s1",
|
||||||
|
out: make(chan []byte, maxPeerWriteQueue), done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
for i := 0; i < maxPeerWriteQueue; i++ {
|
||||||
|
p.out <- []byte("{}")
|
||||||
|
}
|
||||||
|
hub.mu.Lock()
|
||||||
|
hub.peers[p] = struct{}{}
|
||||||
|
hub.mu.Unlock()
|
||||||
|
slowReady <- p
|
||||||
|
<-release
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
defer close(release)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
url := "ws" + strings.TrimPrefix(server.URL, "http")
|
||||||
|
|
||||||
|
fast := dialSyncSocket(t, ctx, url)
|
||||||
|
defer fast.CloseNow()
|
||||||
|
fastID := readSyncFrame(t, ctx, fast, "hello")["clientId"].(string)
|
||||||
|
writeSyncFrame(t, ctx, fast, map[string]any{"type": "sync:hello", "clientId": fastID, "sessionId": "s1"})
|
||||||
|
readSyncFrame(t, ctx, fast, "sync:state")
|
||||||
|
|
||||||
|
slowClient := dialSyncSocket(t, ctx, url+"/slow")
|
||||||
|
defer slowClient.CloseNow()
|
||||||
|
slow := <-slowReady
|
||||||
|
|
||||||
|
// Stopping a peer waits for a close frame that a stuck peer never sends, so Broadcast must not
|
||||||
|
// do it inline: it would hold up the caller (an HTTP request, or another peer's read loop).
|
||||||
|
started := time.Now()
|
||||||
|
hub.Broadcast("s1")
|
||||||
|
if elapsed := time.Since(started); elapsed > time.Second {
|
||||||
|
t.Fatalf("Broadcast took %v behind a stuck peer, want it to return at once", elapsed)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-slow.done:
|
||||||
|
default:
|
||||||
|
t.Fatal("the peer with a full queue was not stopped")
|
||||||
|
}
|
||||||
|
state := readSyncFrame(t, ctx, fast, "sync:state")
|
||||||
|
if _, ok := state["clients"].([]any); !ok {
|
||||||
|
t.Fatalf("the healthy peer got %v, want a state with the client list", state)
|
||||||
|
}
|
||||||
|
if elapsed := time.Since(started); elapsed > time.Second {
|
||||||
|
t.Fatalf("the healthy peer's state took %v, want it at once", elapsed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func dialSyncSocket(t *testing.T, ctx context.Context, url string) *websocket.Conn {
|
||||||
|
t.Helper()
|
||||||
|
conn, _, err := websocket.Dial(ctx, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dial %s: %v", url, err)
|
||||||
|
}
|
||||||
|
return conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, message map[string]any) {
|
||||||
|
t.Helper()
|
||||||
|
data, err := json.Marshal(message)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
|
||||||
|
t.Fatalf("write %v: %v", message["type"], err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// readSyncFrame reads frames until one of the wanted type arrives, failing if the connection ends first.
|
||||||
|
func readSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
for {
|
||||||
|
_, data, err := conn.Read(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read while waiting for %q: %v", want, err)
|
||||||
|
}
|
||||||
|
var message map[string]any
|
||||||
|
if err := json.Unmarshal(data, &message); err != nil {
|
||||||
|
t.Fatalf("decode frame: %v", err)
|
||||||
|
}
|
||||||
|
if message["type"] == want {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
{
|
||||||
|
"description": "Fixtures that the Go, Node and Python auth helpers must agree on. Each runtime's test suite loads this file and checks its own column. Change a value only together with the code that changes the behavior.",
|
||||||
|
"password": {
|
||||||
|
"plaintext": "correct horse battery staple",
|
||||||
|
"wrongPassword": "not the right password",
|
||||||
|
"hashes": [
|
||||||
|
{
|
||||||
|
"name": "Legacy PBKDF2 scheme with recorded iteration count",
|
||||||
|
"hash": "pbkdf2-sha256$600000$76add00c36dafceac62928d01f706c20$f50eec2591755f169bd151369e41a4e6918c6a2816d19516cc38763bfa63c0ca",
|
||||||
|
"verifies": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
},
|
||||||
|
"needsUpgrade": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Legacy salt:hex PBKDF2 at 100000 iterations",
|
||||||
|
"hash": "0123456789abcdef0123456789abcdef:69a26fc4b1624cd29ecc2b2444aa876251575c65deb4af9effbd9eadbd4195c6",
|
||||||
|
"verifies": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
},
|
||||||
|
"needsUpgrade": {
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Go and Python, bcrypt scheme prefix, cost 4",
|
||||||
|
"hash": "bcrypt$$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
|
||||||
|
"verifies": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
},
|
||||||
|
"needsUpgrade": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Go and Python, unprefixed legacy bcrypt, cost 4",
|
||||||
|
"hash": "$2b$04$swZK.9qxywaA8ezhm5aomuRTjsKm844M.p2KuaXqqp1jaK9.bnaa2",
|
||||||
|
"verifies": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
},
|
||||||
|
"needsUpgrade": {
|
||||||
|
"go": true,
|
||||||
|
"node": true,
|
||||||
|
"python": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "unknown scheme",
|
||||||
|
"hash": "argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHQ$YWJj",
|
||||||
|
"verifies": {
|
||||||
|
"go": false,
|
||||||
|
"node": false,
|
||||||
|
"python": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "plain text stored as a hash",
|
||||||
|
"hash": "correct horse battery staple",
|
||||||
|
"verifies": {
|
||||||
|
"go": false,
|
||||||
|
"node": false,
|
||||||
|
"python": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "empty hash",
|
||||||
|
"hash": "",
|
||||||
|
"verifies": {
|
||||||
|
"go": false,
|
||||||
|
"node": false,
|
||||||
|
"python": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"tooLongToHash": {
|
||||||
|
"bytes": 73,
|
||||||
|
"accepted": {
|
||||||
|
"go": false,
|
||||||
|
"node": false,
|
||||||
|
"python": false
|
||||||
|
},
|
||||||
|
"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": {
|
||||||
|
"secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
|
||||||
|
"cases": [
|
||||||
|
{
|
||||||
|
"name": "RFC 6238 T=59",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "287082",
|
||||||
|
"valid": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "RFC 6238 T=1111111109",
|
||||||
|
"unix": 1111111109,
|
||||||
|
"code": "081804",
|
||||||
|
"valid": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "RFC 6238 T=1111111111",
|
||||||
|
"unix": 1111111111,
|
||||||
|
"code": "050471",
|
||||||
|
"valid": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "RFC 6238 T=1234567890",
|
||||||
|
"unix": 1234567890,
|
||||||
|
"code": "005924",
|
||||||
|
"valid": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "RFC 6238 T=2000000000",
|
||||||
|
"unix": 2000000000,
|
||||||
|
"code": "279037",
|
||||||
|
"valid": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "the next step still accepts the previous code",
|
||||||
|
"unix": 1111111139,
|
||||||
|
"code": "081804",
|
||||||
|
"matchedStep": 37037036,
|
||||||
|
"valid": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "the previous step accepts the next code",
|
||||||
|
"unix": 1111111079,
|
||||||
|
"code": "081804",
|
||||||
|
"matchedStep": 37037036,
|
||||||
|
"valid": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "two steps late is refused",
|
||||||
|
"unix": 1111111169,
|
||||||
|
"code": "081804",
|
||||||
|
"valid": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "two steps early is refused",
|
||||||
|
"unix": 1111111049,
|
||||||
|
"code": "081804",
|
||||||
|
"valid": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "a code is not a different code",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "287083",
|
||||||
|
"valid": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "a code with a letter",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "28708a",
|
||||||
|
"valid": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "five digits",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "28708",
|
||||||
|
"valid": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "seven digits",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "2870820",
|
||||||
|
"valid": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "empty code",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "",
|
||||||
|
"valid": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "non-ASCII digits",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "٢٨٧٠٨٢",
|
||||||
|
"valid": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "surrounding spaces are trimmed",
|
||||||
|
"unix": 59,
|
||||||
|
"code": " 287082 ",
|
||||||
|
"valid": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "secret in lower case with spaces and padding",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "287082",
|
||||||
|
"secret": "gezd gnbv gy3t qojq gezd gnbv gy3t qojq====",
|
||||||
|
"valid": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "empty secret",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "287082",
|
||||||
|
"secret": "",
|
||||||
|
"valid": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "secret that is not base32",
|
||||||
|
"unix": 59,
|
||||||
|
"code": "287082",
|
||||||
|
"secret": "not base32 !!",
|
||||||
|
"valid": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"clientAddress": {
|
||||||
|
"note": "Go and Python only. The address is the TCP peer unless the peer is in the trusted list; then X-Forwarded-For is read from the right and trusted hops are skipped (owner decision 5).",
|
||||||
|
"invalidTrustedProxyLists": [
|
||||||
|
"not-an-ip",
|
||||||
|
"10.0.0.0/33",
|
||||||
|
"10.0.0.1, bogus"
|
||||||
|
],
|
||||||
|
"cases": [
|
||||||
|
{
|
||||||
|
"name": "no trusted proxies ignores the header",
|
||||||
|
"trusted": "",
|
||||||
|
"peer": "203.0.113.7",
|
||||||
|
"forwarded": [
|
||||||
|
"198.51.100.1"
|
||||||
|
],
|
||||||
|
"want": "203.0.113.7"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "an unknown peer's header is ignored",
|
||||||
|
"trusted": "10.0.0.0/8",
|
||||||
|
"peer": "203.0.113.7",
|
||||||
|
"forwarded": [
|
||||||
|
"198.51.100.1"
|
||||||
|
],
|
||||||
|
"want": "203.0.113.7"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "single client behind a trusted peer",
|
||||||
|
"trusted": "10.0.0.0/8, 172.16.0.0/12",
|
||||||
|
"peer": "10.0.0.2",
|
||||||
|
"forwarded": [
|
||||||
|
"198.51.100.9"
|
||||||
|
],
|
||||||
|
"want": "198.51.100.9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "second trusted hop is skipped",
|
||||||
|
"trusted": "10.0.0.0/8, 172.16.0.0/12",
|
||||||
|
"peer": "10.0.0.2",
|
||||||
|
"forwarded": [
|
||||||
|
"198.51.100.9, 172.16.4.4"
|
||||||
|
],
|
||||||
|
"want": "198.51.100.9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "a spoofed left-most entry is skipped",
|
||||||
|
"trusted": "10.0.0.0/8, 172.16.0.0/12",
|
||||||
|
"peer": "10.0.0.2",
|
||||||
|
"forwarded": [
|
||||||
|
"6.6.6.6, 198.51.100.9, 172.16.4.4"
|
||||||
|
],
|
||||||
|
"want": "198.51.100.9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "entries across header lines",
|
||||||
|
"trusted": "10.0.0.0/8, 172.16.0.0/12",
|
||||||
|
"peer": "10.0.0.2",
|
||||||
|
"forwarded": [
|
||||||
|
"6.6.6.6",
|
||||||
|
"198.51.100.9"
|
||||||
|
],
|
||||||
|
"want": "198.51.100.9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "a malformed entry falls back to the peer",
|
||||||
|
"trusted": "10.0.0.0/8, 172.16.0.0/12",
|
||||||
|
"peer": "10.0.0.2",
|
||||||
|
"forwarded": [
|
||||||
|
"198.51.100.9, not-an-ip"
|
||||||
|
],
|
||||||
|
"want": "10.0.0.2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "no header falls back to the peer",
|
||||||
|
"trusted": "10.0.0.0/8, 172.16.0.0/12",
|
||||||
|
"peer": "10.0.0.2",
|
||||||
|
"forwarded": [],
|
||||||
|
"want": "10.0.0.2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "every hop trusted uses the left-most",
|
||||||
|
"trusted": "10.0.0.0/8, 172.16.0.0/12",
|
||||||
|
"peer": "10.0.0.2",
|
||||||
|
"forwarded": [
|
||||||
|
"10.1.1.1, 172.16.4.4"
|
||||||
|
],
|
||||||
|
"want": "10.1.1.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "a bare address is a one-host range",
|
||||||
|
"trusted": "192.168.1.5",
|
||||||
|
"peer": "192.168.1.5",
|
||||||
|
"forwarded": [
|
||||||
|
"198.51.100.9"
|
||||||
|
],
|
||||||
|
"want": "198.51.100.9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "an IPv6 proxy range",
|
||||||
|
"trusted": "fd00::/8",
|
||||||
|
"peer": "fd00::2",
|
||||||
|
"forwarded": [
|
||||||
|
"2001:db8::9"
|
||||||
|
],
|
||||||
|
"want": "2001:db8::9"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import js from '@eslint/js';
|
||||||
|
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||||
|
import svelte from 'eslint-plugin-svelte';
|
||||||
|
import globals from 'globals';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
|
// An unused binding is fine when its name starts with an underscore (a prop or argument kept for
|
||||||
|
// its position or its documentation).
|
||||||
|
const unusedUnderscore = [
|
||||||
|
'error',
|
||||||
|
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' },
|
||||||
|
];
|
||||||
|
|
||||||
|
// Lints the JavaScript, TypeScript and Svelte first-party code. The Go, Python and Java packages
|
||||||
|
// have their own linters (gofmt and go vet, ruff), and generated output is never linted.
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores([
|
||||||
|
'**/dist/**',
|
||||||
|
'**/.svelte-kit/**',
|
||||||
|
'**/node_modules/**',
|
||||||
|
'backend/**',
|
||||||
|
'contract/**',
|
||||||
|
'packages/java-backend/**',
|
||||||
|
'packages/python-backend/**',
|
||||||
|
'shared-styles.css',
|
||||||
|
]),
|
||||||
|
js.configs.recommended,
|
||||||
|
{ rules: { 'no-unused-vars': unusedUnderscore } },
|
||||||
|
{
|
||||||
|
files: ['**/*.ts', '**/*.svelte'],
|
||||||
|
extends: [tseslint.configs.recommended],
|
||||||
|
rules: { 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': unusedUnderscore },
|
||||||
|
},
|
||||||
|
svelte.configs.recommended,
|
||||||
|
{
|
||||||
|
files: ['packages/node-backend/**/*.js', 'scripts/**/*.{js,mjs}', 'eslint.config.js'],
|
||||||
|
languageOptions: { globals: globals.node },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['packages/web-ui/**/*.{ts,svelte}'],
|
||||||
|
languageOptions: { globals: globals.browser },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.svelte', '**/*.svelte.ts'],
|
||||||
|
languageOptions: { parserOptions: { parser: tseslint.parser } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// These three Svelte rules ask for changes to how shipped components render or hold state
|
||||||
|
// (keyed each blocks, derived state, reactive Map and Set). That changes consumer-visible
|
||||||
|
// behaviour, so it is a decision for a component change, not for the lint set-up.
|
||||||
|
files: ['packages/web-ui/**/*.{ts,svelte}'],
|
||||||
|
rules: {
|
||||||
|
'svelte/require-each-key': 'off',
|
||||||
|
'svelte/prefer-writable-derived': 'off',
|
||||||
|
'svelte/prefer-svelte-reactivity': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
Generated
+2417
-35
File diff suppressed because it is too large.
Load diff
+18
-4
@@ -38,14 +38,18 @@
|
|||||||
"check": "npm run check --workspace=@gabriel20xx/web-ui",
|
"check": "npm run check --workspace=@gabriel20xx/web-ui",
|
||||||
"build": "npm run package --workspace=@gabriel20xx/web-ui",
|
"build": "npm run package --workspace=@gabriel20xx/web-ui",
|
||||||
"package": "npm run package --workspace=@gabriel20xx/web-ui",
|
"package": "npm run package --workspace=@gabriel20xx/web-ui",
|
||||||
"lint": "npm run check && npm run lint:node",
|
"lint": "npm run check && npm run lint:node && npm run lint:eslint",
|
||||||
"lint:node": "node scripts/check-node-syntax.mjs",
|
"lint:node": "node scripts/check-node-syntax.mjs",
|
||||||
"test": "npm run build && npm run test:node-backend",
|
"lint:eslint": "eslint . --max-warnings=0",
|
||||||
|
"format:check": "prettier --check eslint.config.js packages/web-ui/vitest.config.ts packages/web-ui/tests packages/node-backend/test/authstore.test.js packages/node-backend/test/contract.test.js",
|
||||||
|
"format": "prettier --write eslint.config.js packages/web-ui/vitest.config.ts packages/web-ui/tests packages/node-backend/test/authstore.test.js packages/node-backend/test/contract.test.js",
|
||||||
|
"test": "npm run build && npm run test:node-backend && npm run test:web-ui",
|
||||||
"test:node-backend": "npm test --workspace=@gabriel20xx/node-backend",
|
"test:node-backend": "npm test --workspace=@gabriel20xx/node-backend",
|
||||||
|
"test:web-ui": "npm test --workspace=@gabriel20xx/web-ui",
|
||||||
"prepare": "npm run build && node scripts/build-root-styles.mjs",
|
"prepare": "npm run build && node scripts/build-root-styles.mjs",
|
||||||
"changeset": "changeset",
|
"changeset": "changeset",
|
||||||
"version-packages": "changeset version",
|
"version-packages": "changeset version",
|
||||||
"release": "npm run build && npm run test:node-backend && changeset publish",
|
"release": "npm run build && npm run test:node-backend && npm run test:web-ui && changeset publish",
|
||||||
"media:audit:html-js": "node scripts/media/audit-html-js.mjs",
|
"media:audit:html-js": "node scripts/media/audit-html-js.mjs",
|
||||||
"media:audit:layout": "node scripts/media/audit-inline-layout.mjs",
|
"media:audit:layout": "node scripts/media/audit-inline-layout.mjs",
|
||||||
"media:audit:layout:strict": "node scripts/media/audit-inline-layout.mjs --strict",
|
"media:audit:layout:strict": "node scripts/media/audit-inline-layout.mjs --strict",
|
||||||
@@ -63,6 +67,16 @@
|
|||||||
"pg": "^8.17.2"
|
"pg": "^8.17.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@changesets/cli": "^2.29.8"
|
"@changesets/cli": "^2.29.8",
|
||||||
|
"@eslint/js": "^10.0.1",
|
||||||
|
"@testing-library/svelte": "^5.4.2",
|
||||||
|
"eslint": "^10.13.0",
|
||||||
|
"eslint-plugin-svelte": "^3.23.1",
|
||||||
|
"globals": "^17.13.0",
|
||||||
|
"jsdom": "^30.1.3",
|
||||||
|
"prettier": "^3.9.10",
|
||||||
|
"prettier-plugin-svelte": "^4.1.1",
|
||||||
|
"typescript-eslint": "^8.72.0",
|
||||||
|
"vitest": "^5.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -73,24 +73,21 @@ import java.util.regex.Pattern;
|
|||||||
* this class can be built and tested in isolation (see this package's
|
* this class can be built and tested in isolation (see this package's
|
||||||
* README); it targets Java 8 for the same reason.
|
* README); it targets Java 8 for the same reason.
|
||||||
*
|
*
|
||||||
* <p>{@link #validate(String)} still hand-parses AuthGuard's small, fixed
|
* <p>{@link #validate(String)} parses AuthGuard's {@code GET /api/session/validate}
|
||||||
* {@code GET /api/session/validate} response shape with a few targeted
|
* response with Jackson and reads top-level fields only, so a nested object
|
||||||
* regular expressions rather than Jackson, keeping the minimal
|
* with the same field names cannot change the decision. {@code ResetManager},
|
||||||
* validate-only surface dependency-free beyond the JDK - {@code ResetManager},
|
* {@code Roles}, and {@code Totp}, the other classes in this package, use only
|
||||||
* {@code Roles}, and {@code Totp}, the other classes in this package, stay
|
* the JDK. The full-proxy methods added below (register/login/setup/
|
||||||
* that way too. The full-proxy methods added below (register/login/setup/
|
* reset/admin-user-management) also build and parse a handful of small JSON
|
||||||
* reset/admin-user-management) are a different tradeoff: they must both
|
* request/response bodies, which would be considerably worse hand-rolled, so
|
||||||
* build and parse a handful of small JSON request/response bodies, which
|
* they use Jackson ({@code jackson-databind}) too. This makes {@code jackson-databind} a compile-time dependency of
|
||||||
* would be considerably worse hand-rolled than {@code validate}'s
|
|
||||||
* fixed-shape parsing, so they use Jackson ({@code jackson-databind})
|
|
||||||
* instead. This makes {@code jackson-databind} a compile-time dependency of
|
|
||||||
* this whole class (Java has no way to make an import conditional on which
|
* this whole class (Java has no way to make an import conditional on which
|
||||||
* methods a given consumer actually calls) - acceptable here because
|
* methods a given consumer actually calls) - acceptable here because
|
||||||
* MegaBasterd, this package's only verified consumer, already depends on
|
* MegaBasterd, this package's only verified consumer, already depends on
|
||||||
* Jackson for its own code. A hypothetical future consumer that only ever
|
* Jackson for its own code. A hypothetical future consumer that only ever
|
||||||
* calls {@code validate}/{@code middleware} and doesn't already carry
|
* calls {@code validate}/{@code middleware} and doesn't already carry
|
||||||
* Jackson would need to add it just to compile this file; that tradeoff was
|
* Jackson would need to add it just to compile this file; that tradeoff was
|
||||||
* chosen deliberately over hand-rolling JSON request bodies with regex.
|
* chosen deliberately over hand-rolling JSON with regular expressions.
|
||||||
*/
|
*/
|
||||||
public final class AuthClient {
|
public final class AuthClient {
|
||||||
|
|
||||||
@@ -106,10 +103,6 @@ public final class AuthClient {
|
|||||||
*/
|
*/
|
||||||
public static final String PROJECT_KEY_HEADER = "X-Project-Key";
|
public static final String PROJECT_KEY_HEADER = "X-Project-Key";
|
||||||
|
|
||||||
private static final Pattern VALID_PATTERN = Pattern.compile("\"valid\"\\s*:\\s*(true|false)");
|
|
||||||
private static final Pattern USER_ID_PATTERN = Pattern.compile("\"user_id\"\\s*:\\s*(-?\\d+)");
|
|
||||||
private static final Pattern USERNAME_PATTERN = Pattern.compile("\"username\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
|
|
||||||
private static final Pattern ROLE_PATTERN = Pattern.compile("\"role\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
|
|
||||||
private static final String BEARER_PREFIX = "Bearer ";
|
private static final String BEARER_PREFIX = "Bearer ";
|
||||||
|
|
||||||
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
|
/** Used only by the full-proxy methods below; see the class javadoc's Jackson tradeoff note. */
|
||||||
@@ -279,7 +272,8 @@ public final class AuthClient {
|
|||||||
User user;
|
User user;
|
||||||
try {
|
try {
|
||||||
user = validate(token);
|
user = validate(token);
|
||||||
} catch (InvalidSessionException | IOException ex) {
|
} catch (InvalidSessionException | IOException | IllegalStateException ex) {
|
||||||
|
// IllegalStateException is a client with no base URL yet; it fails closed like Node's middleware.
|
||||||
return onUnauthorized.get();
|
return onUnauthorized.get();
|
||||||
}
|
}
|
||||||
return onAuthenticated.handle(user);
|
return onAuthenticated.handle(user);
|
||||||
@@ -715,9 +709,13 @@ public final class AuthClient {
|
|||||||
if (candidate.startsWith(prefix)) {
|
if (candidate.startsWith(prefix)) {
|
||||||
String value = candidate.substring(prefix.length());
|
String value = candidate.substring(prefix.length());
|
||||||
try {
|
try {
|
||||||
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
|
// URLDecoder would turn a literal "+" into a space; escape it first so it survives, as in Node.
|
||||||
|
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8.name());
|
||||||
} catch (UnsupportedEncodingException ex) {
|
} catch (UnsupportedEncodingException ex) {
|
||||||
return value;
|
return value;
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
|
||||||
|
return "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -825,59 +823,43 @@ public final class AuthClient {
|
|||||||
return buffer.toString(StandardCharsets.UTF_8.name());
|
return buffer.toString(StandardCharsets.UTF_8.name());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Defensively hand-parses AuthGuard's small, fixed response shape - see the class javadoc for why. */
|
/**
|
||||||
|
* Parses AuthGuard's response with Jackson and reads top-level fields only, so a nested object
|
||||||
|
* with the same field names cannot stand in for the real answer.
|
||||||
|
*/
|
||||||
private static RawPayload parsePayload(String body) {
|
private static RawPayload parsePayload(String body) {
|
||||||
if (body == null || body.isEmpty()) {
|
if (body == null || body.isEmpty()) {
|
||||||
throw new IllegalArgumentException("empty AuthGuard response body");
|
throw new IllegalArgumentException("empty AuthGuard response body");
|
||||||
}
|
}
|
||||||
Matcher validMatcher = VALID_PATTERN.matcher(body);
|
JsonNode root;
|
||||||
if (!validMatcher.find()) {
|
try {
|
||||||
|
root = JSON.readTree(body);
|
||||||
|
} catch (IOException ex) {
|
||||||
|
throw new IllegalArgumentException("AuthGuard response is not JSON: " + ex.getMessage(), ex);
|
||||||
|
}
|
||||||
|
if (root == null || !root.isObject()) {
|
||||||
|
throw new IllegalArgumentException("AuthGuard response is not a JSON object");
|
||||||
|
}
|
||||||
|
JsonNode validNode = root.get("valid");
|
||||||
|
if (validNode == null || !validNode.isBoolean()) {
|
||||||
throw new IllegalArgumentException("missing \"valid\" field in AuthGuard response");
|
throw new IllegalArgumentException("missing \"valid\" field in AuthGuard response");
|
||||||
}
|
}
|
||||||
boolean valid = Boolean.parseBoolean(validMatcher.group(1));
|
|
||||||
|
|
||||||
long userId = 0L;
|
long userId = 0L;
|
||||||
Matcher userIdMatcher = USER_ID_PATTERN.matcher(body);
|
JsonNode userIdNode = root.get("user_id");
|
||||||
if (userIdMatcher.find()) {
|
if (userIdNode != null && userIdNode.isIntegralNumber()) {
|
||||||
userId = Long.parseLong(userIdMatcher.group(1));
|
if (!userIdNode.canConvertToLong()) {
|
||||||
|
throw new IllegalArgumentException("user_id is out of range in AuthGuard response");
|
||||||
|
}
|
||||||
|
userId = userIdNode.longValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
return new RawPayload(valid, userId, extractString(USERNAME_PATTERN, body), extractString(ROLE_PATTERN, body));
|
return new RawPayload(validNode.booleanValue(), userId, textualField(root, "username"), textualField(root, "role"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String extractString(Pattern pattern, String body) {
|
private static String textualField(JsonNode root, String name) {
|
||||||
Matcher matcher = pattern.matcher(body);
|
JsonNode node = root.get(name);
|
||||||
return matcher.find() ? unescapeJson(matcher.group(1)) : "";
|
return node != null && node.isTextual() ? node.textValue() : "";
|
||||||
}
|
|
||||||
|
|
||||||
private static String unescapeJson(String raw) {
|
|
||||||
StringBuilder result = new StringBuilder(raw.length());
|
|
||||||
for (int index = 0; index < raw.length(); index++) {
|
|
||||||
char current = raw.charAt(index);
|
|
||||||
if (current != '\\' || index + 1 >= raw.length()) {
|
|
||||||
result.append(current);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
char next = raw.charAt(++index);
|
|
||||||
switch (next) {
|
|
||||||
case '"': result.append('"'); break;
|
|
||||||
case '\\': result.append('\\'); break;
|
|
||||||
case '/': result.append('/'); break;
|
|
||||||
case 'n': result.append('\n'); break;
|
|
||||||
case 't': result.append('\t'); break;
|
|
||||||
case 'r': result.append('\r'); break;
|
|
||||||
case 'b': result.append('\b'); break;
|
|
||||||
case 'f': result.append('\f'); break;
|
|
||||||
case 'u':
|
|
||||||
if (index + 4 < raw.length()) {
|
|
||||||
result.append((char) Integer.parseInt(raw.substring(index + 1, index + 5), 16));
|
|
||||||
index += 4;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default: result.append(next);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result.toString();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class RawPayload {
|
private static final class RawPayload {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.gabriel20xx.shared.auth;
|
|||||||
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
import java.security.SecureRandom;
|
import java.security.SecureRandom;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import javax.crypto.Mac;
|
import javax.crypto.Mac;
|
||||||
@@ -12,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();
|
||||||
|
|
||||||
@@ -42,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;
|
||||||
}
|
}
|
||||||
@@ -77,14 +83,15 @@ public final class Totp {
|
|||||||
| ((hash[index + 2] & 0xff) << 8)
|
| ((hash[index + 2] & 0xff) << 8)
|
||||||
| (hash[index + 3] & 0xff);
|
| (hash[index + 3] & 0xff);
|
||||||
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
|
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
|
||||||
if (candidate.equals(normalizedToken)) {
|
if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII),
|
||||||
return true;
|
normalizedToken.getBytes(StandardCharsets.US_ASCII))) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -218,6 +218,34 @@ class AuthClientTest {
|
|||||||
assertEquals("right", token);
|
assertEquals("right", token);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void extractTokenKeepsALiteralPlusSignInTheCookieValue() {
|
||||||
|
AuthClient client = new AuthClient("https://auth.example.com");
|
||||||
|
|
||||||
|
String token = client.extractToken(name -> null, "auth_session=ab+cd%2Bef");
|
||||||
|
|
||||||
|
assertEquals("ab+cd+ef", token);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void extractTokenTreatsAMalformedCookieEscapeAsNoToken() {
|
||||||
|
AuthClient client = new AuthClient("https://auth.example.com");
|
||||||
|
|
||||||
|
String token = client.extractToken(name -> null, "auth_session=bad%zz; other=1");
|
||||||
|
|
||||||
|
assertEquals("", token);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void middlewareFailsClosedOnAMalformedCookieInsteadOfThrowing() throws Exception {
|
||||||
|
AuthClient client = new AuthClient("https://auth.example.com");
|
||||||
|
|
||||||
|
String result = client.middleware(name -> null, "auth_session=100%",
|
||||||
|
user -> "authenticated", () -> "unauthorized");
|
||||||
|
|
||||||
|
assertEquals("unauthorized", result);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void middlewareFailsClosedAndDoesNotInvokeTheHandlerOnAnInvalidSession() throws Exception {
|
void middlewareFailsClosedAndDoesNotInvokeTheHandlerOnAnInvalidSession() throws Exception {
|
||||||
server = fakeAuthGuard(401, "{\"valid\":false}");
|
server = fakeAuthGuard(401, "{\"valid\":false}");
|
||||||
@@ -250,6 +278,54 @@ class AuthClientTest {
|
|||||||
assertEquals("user", result.role);
|
assertEquals("user", result.role);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateReadsTopLevelFieldsOnlyWhenNestedFieldsRepeatThem() throws Exception {
|
||||||
|
// The nested object says valid:true, but the top-level answer is valid:false, so the session is invalid.
|
||||||
|
server = fakeAuthGuard(200, "{\"session\":{\"valid\":true,\"user_id\":99,\"username\":\"evil\",\"role\":\"admin\"},\"valid\":false}");
|
||||||
|
AuthClient client = new AuthClient(baseUrl(server));
|
||||||
|
|
||||||
|
assertThrows(InvalidSessionException.class, () -> client.validate("token"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateIgnoresANestedValidFieldWhenTheTopLevelOneIsMissing() throws Exception {
|
||||||
|
server = fakeAuthGuard(200, "{\"data\":{\"valid\":true,\"user_id\":5,\"username\":\"x\",\"role\":\"admin\"}}");
|
||||||
|
AuthClient client = new AuthClient(baseUrl(server));
|
||||||
|
|
||||||
|
assertThrows(IOException.class, () -> client.validate("token"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateAcceptsReorderedTopLevelFields() throws Exception {
|
||||||
|
server = fakeAuthGuard(200, "{\"username\":\"gabriel\",\"role\":\"admin\",\"user_id\":7,\"valid\":true}");
|
||||||
|
AuthClient client = new AuthClient(baseUrl(server));
|
||||||
|
|
||||||
|
AuthClient.User user = client.validate("token");
|
||||||
|
|
||||||
|
assertEquals(7L, user.id);
|
||||||
|
assertEquals("gabriel", user.username);
|
||||||
|
assertEquals("admin", user.role);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateDecodesEscapedUsernames() throws Exception {
|
||||||
|
server = fakeAuthGuard(200, "{\"valid\":true,\"user_id\":3,\"username\":\"a\\\"b\\u00e9\",\"role\":\"user\"}");
|
||||||
|
AuthClient client = new AuthClient(baseUrl(server));
|
||||||
|
|
||||||
|
assertEquals("a\"b\u00e9", client.validate("token").username);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void middlewareFailsClosedOnAClientWithNoBaseUrlYet() throws Exception {
|
||||||
|
AuthClient client = new AuthClient("");
|
||||||
|
Function<String, String> headerLookup = name -> "Authorization".equals(name) ? "Bearer some-token" : null;
|
||||||
|
|
||||||
|
String result = client.middleware(headerLookup, null,
|
||||||
|
user -> "authenticated", () -> "unauthorized");
|
||||||
|
|
||||||
|
assertEquals("unauthorized", result);
|
||||||
|
}
|
||||||
|
|
||||||
/** Like fakeAuthGuard, but for one arbitrary path instead of the fixed /api/session/validate one. */
|
/** Like fakeAuthGuard, but for one arbitrary path instead of the fixed /api/session/validate one. */
|
||||||
private static HttpServer fakeEndpoint(String path, int status, String body) throws IOException {
|
private static HttpServer fakeEndpoint(String path, int status, String body) throws IOException {
|
||||||
return fakeEndpointCapturingRequest(path, status, body, new String[0]);
|
return fakeEndpointCapturingRequest(path, status, body, new String[0]);
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package com.gabriel20xx.shared.auth;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class ResetManagerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void requestReturnsAnEightDigitHexCodeAndPrintsIt() {
|
||||||
|
ResetManager manager = new ResetManager();
|
||||||
|
PrintStream original = System.out;
|
||||||
|
ByteArrayOutputStream captured = new ByteArrayOutputStream();
|
||||||
|
System.setOut(new PrintStream(captured));
|
||||||
|
String code;
|
||||||
|
try {
|
||||||
|
code = manager.request();
|
||||||
|
} finally {
|
||||||
|
System.setOut(original);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(code.matches("[0-9A-F]{8}"));
|
||||||
|
assertTrue(captured.toString().contains("ADMIN RESET CODE: " + code));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void confirmAcceptsTheCodeOnceAndTrimsAndCase() {
|
||||||
|
ResetManager manager = new ResetManager();
|
||||||
|
String code = quietRequest(manager);
|
||||||
|
|
||||||
|
assertFalse(manager.confirm(null));
|
||||||
|
assertTrue(manager.confirm(" " + code.toLowerCase() + " "));
|
||||||
|
assertFalse(manager.confirm(code));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void confirmRejectsAWrongCodeButKeepsTheCodeRetryable() {
|
||||||
|
ResetManager manager = new ResetManager();
|
||||||
|
String code = quietRequest(manager);
|
||||||
|
String wrong = code.charAt(0) == '0' ? "1" + code.substring(1) : "0" + code.substring(1);
|
||||||
|
|
||||||
|
assertFalse(manager.confirm(wrong));
|
||||||
|
assertTrue(manager.confirm(code));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void confirmFailsWithoutARequestedCode() {
|
||||||
|
assertFalse(new ResetManager().confirm("00000000"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void aNewRequestInvalidatesThePreviousCode() {
|
||||||
|
ResetManager manager = new ResetManager();
|
||||||
|
String first = quietRequest(manager);
|
||||||
|
String second = quietRequest(manager);
|
||||||
|
|
||||||
|
if (!first.equals(second)) {
|
||||||
|
assertFalse(manager.confirm(first));
|
||||||
|
}
|
||||||
|
assertTrue(manager.confirm(second));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String quietRequest(ResetManager manager) {
|
||||||
|
PrintStream original = System.out;
|
||||||
|
System.setOut(new PrintStream(new ByteArrayOutputStream()));
|
||||||
|
try {
|
||||||
|
return manager.request();
|
||||||
|
} finally {
|
||||||
|
System.setOut(original);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.gabriel20xx.shared.auth;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class RolesTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void normalizeIsCaseInsensitiveAndDefaultsToUser() {
|
||||||
|
assertEquals(Roles.SUPERADMIN, Roles.normalize(" SuperAdmin "));
|
||||||
|
assertEquals(Roles.ADMIN, Roles.normalize("ADMIN"));
|
||||||
|
assertEquals(Roles.USER, Roles.normalize("moderator"));
|
||||||
|
assertEquals(Roles.USER, Roles.normalize(""));
|
||||||
|
assertEquals(Roles.USER, Roles.normalize(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void onlyAdminRolesCanManageUsers() {
|
||||||
|
assertTrue(Roles.canManageUsers(Roles.SUPERADMIN));
|
||||||
|
assertTrue(Roles.canManageUsers(Roles.ADMIN));
|
||||||
|
assertFalse(Roles.canManageUsers(Roles.USER));
|
||||||
|
assertFalse(Roles.canManageUsers("moderator"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void onlySuperadminCanAssignNonSuperadminRoles() {
|
||||||
|
assertTrue(Roles.canAssignRole(Roles.SUPERADMIN, Roles.ADMIN));
|
||||||
|
assertTrue(Roles.canAssignRole(Roles.SUPERADMIN, Roles.USER));
|
||||||
|
assertFalse(Roles.canAssignRole(Roles.SUPERADMIN, Roles.SUPERADMIN));
|
||||||
|
assertFalse(Roles.canAssignRole(Roles.ADMIN, Roles.USER));
|
||||||
|
assertFalse(Roles.canAssignRole(Roles.USER, Roles.USER));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.gabriel20xx.shared.auth;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class TotpTest {
|
||||||
|
|
||||||
|
// RFC 6238 SHA-1 test secret "12345678901234567890", base32-encoded.
|
||||||
|
private static final String RFC_SECRET = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyAcceptsTheRfc6238Vectors() {
|
||||||
|
// The RFC lists 8-digit codes; these are their last six digits.
|
||||||
|
assertTrue(Totp.verify(RFC_SECRET, "287082", 59_000L));
|
||||||
|
assertEquals(1L, Totp.verifyStep(RFC_SECRET, "287082", 59_000L));
|
||||||
|
assertTrue(Totp.verify(RFC_SECRET, "081804", 1_111_111_109_000L));
|
||||||
|
assertTrue(Totp.verify(RFC_SECRET, "050471", 1_111_111_111_000L));
|
||||||
|
assertTrue(Totp.verify(RFC_SECRET, "005924", 1_234_567_890_000L));
|
||||||
|
assertTrue(Totp.verify(RFC_SECRET, "279037", 2_000_000_000_000L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyAcceptsOneStepEitherSideOfTheCurrentTime() {
|
||||||
|
// At t=59 the counter is 1. Counter 0 (t=0) and counter 2 (t=60) are inside the window.
|
||||||
|
assertTrue(Totp.verify(RFC_SECRET, "755224", 59_000L));
|
||||||
|
assertTrue(Totp.verify(RFC_SECRET, "359152", 59_000L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyRejectsCodesOutsideTheWindow() {
|
||||||
|
// Counter 3 (t=90) is two steps ahead of counter 1; 2 steps behind would need a negative counter.
|
||||||
|
assertFalse(Totp.verify(RFC_SECRET, "969429", 59_000L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyRejectsMalformedInput() {
|
||||||
|
assertFalse(Totp.verify(RFC_SECRET, null, 59_000L));
|
||||||
|
assertFalse(Totp.verify(RFC_SECRET, "", 59_000L));
|
||||||
|
assertFalse(Totp.verify(RFC_SECRET, "28708", 59_000L));
|
||||||
|
assertFalse(Totp.verify(RFC_SECRET, "28708a", 59_000L));
|
||||||
|
assertFalse(Totp.verify(RFC_SECRET, "2870821", 59_000L));
|
||||||
|
assertFalse(Totp.verify("", "287082", 59_000L));
|
||||||
|
assertFalse(Totp.verify(null, "287082", 59_000L));
|
||||||
|
assertFalse(Totp.verify("not base32!", "287082", 59_000L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyTrimsWhitespaceAroundTheCode() {
|
||||||
|
assertTrue(Totp.verify(RFC_SECRET, " 287082 ", 59_000L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyAcceptsASecretWithSpacesAndPadding() {
|
||||||
|
String spaced = "GEZD GNBV GY3T QOJQ GEZD GNBV GY3T QOJQ====";
|
||||||
|
assertTrue(Totp.verify(spaced, "287082", 59_000L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void generatedSecretsAreBase32OfTheExpectedLength() {
|
||||||
|
String first = Totp.generateSecret();
|
||||||
|
String second = Totp.generateSecret();
|
||||||
|
assertEquals(32, first.length());
|
||||||
|
assertTrue(first.matches("[A-Z2-7]+"));
|
||||||
|
assertFalse(first.equals(second));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void provisioningUriCarriesTheSecretAndParameters() {
|
||||||
|
String uri = Totp.provisioningUri("Shared App", "gabriel", RFC_SECRET);
|
||||||
|
assertTrue(uri.startsWith("otpauth://totp/Shared%20App%3Agabriel?secret=" + RFC_SECRET));
|
||||||
|
assertTrue(uri.contains("&issuer=Shared%20App"));
|
||||||
|
assertTrue(uri.endsWith("&algorithm=SHA1&digits=6&period=30"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,15 +3,16 @@
|
|||||||
Shared Node.js backend infrastructure for services that use PostgreSQL:
|
Shared Node.js backend infrastructure for services that use PostgreSQL:
|
||||||
|
|
||||||
- validated `DATABASE_URL` and pool settings;
|
- validated `DATABASE_URL` and pool settings;
|
||||||
- one pool owner with startup retry, transient query retry, transactions, and shutdown;
|
- one pool owner with startup retry, transient retry for read-only queries, transactions, and shutdown;
|
||||||
- PBKDF2 password hashing and secure session-token helpers;
|
- PBKDF2 password hashing (`verifyAndUpgradePasswordAsync` returns a current-scheme hash for a login to store) and secure session-token helpers;
|
||||||
- short-lived, one-time admin reset codes printed to the server console;
|
- short-lived, one-time admin reset codes printed to the server console;
|
||||||
- common account/session persistence;
|
- common account/session persistence;
|
||||||
- transaction-locked ordered migrations.
|
- transaction-locked ordered migrations;
|
||||||
|
- 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
|
||||||
@@ -20,7 +21,9 @@ share one PostgreSQL database, so their migration histories cannot collide.
|
|||||||
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
|
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
|
||||||
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
|
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely).
|
||||||
|
|
||||||
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`.
|
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `shared`; `npm run lint` runs ESLint with the repository's config.
|
||||||
|
|
||||||
|
`AuthClient`'s `register`, `login`, `totpVerify`, `totpDisable`, `requestPasswordReset` and `confirmPasswordReset` take an optional trailing `{ clientIp }`, sent to AuthGuard as `X-Forwarded-For` so its per-address limits see the end user. Pass an address you have verified (for example the socket peer, or `X-Forwarded-For` only from a proxy you trust), never a raw request header. `AuthStore` refuses an empty password hash and a username containing `@`, refuses `setTotpSecret` while TOTP is enabled (error code `AUTH_TOTP_ALREADY_ENABLED`), and makes usernames unique ignoring case when no clashing pair already exists.
|
||||||
|
|
||||||
## `authclient`/`coreconfig`: adopting AuthGuard instead of local auth
|
## `authclient`/`coreconfig`: adopting AuthGuard instead of local auth
|
||||||
|
|
||||||
@@ -39,7 +42,7 @@ live whenever ProjectConfigurator pushes a fresh
|
|||||||
`authClient.setBaseUrl` so a project never needs to hardcode `AUTHGUARD_URL`:
|
`authClient.setBaseUrl` so a project never needs to hardcode `AUTHGUARD_URL`:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { AuthClient, CoreConfigStore } from '@gabriel20xx/node-backend';
|
import { AuthClient, CoreConfigStore, internalSecretMatches } from '@gabriel20xx/node-backend';
|
||||||
|
|
||||||
const authClient = new AuthClient('');
|
const authClient = new AuthClient('');
|
||||||
const coreConfig = new CoreConfigStore({ authGuardUrl: '' });
|
const coreConfig = new CoreConfigStore({ authGuardUrl: '' });
|
||||||
@@ -47,10 +50,15 @@ coreConfig.onUpdate((info) => authClient.setBaseUrl(info.authGuardUrl));
|
|||||||
|
|
||||||
// in your own route for PUT /api/core-services/internal:
|
// in your own route for PUT /api/core-services/internal:
|
||||||
app.put('/api/core-services/internal', (req, res) => {
|
app.put('/api/core-services/internal', (req, res) => {
|
||||||
if (req.get('X-Internal-Auth') !== process.env.SECRET) {
|
if (!internalSecretMatches(req.get('X-Internal-Auth'), process.env.SECRET)) {
|
||||||
return res.status(401).json({ error: 'internal service authentication required' });
|
return res.status(401).json({ error: 'internal service authentication required' });
|
||||||
}
|
}
|
||||||
const info = coreConfig.set(req.body);
|
let info;
|
||||||
|
try {
|
||||||
|
info = coreConfig.set(req.body);
|
||||||
|
} catch (error) {
|
||||||
|
return res.status(400).json({ error: error.message });
|
||||||
|
}
|
||||||
res.json({ ok: true, info: info.toJSON() });
|
res.json({ ok: true, info: info.toJSON() });
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
@@ -19,10 +19,12 @@
|
|||||||
"./package.json": "./package.json"
|
"./package.json": "./package.json"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
"pg": "^8.17.2"
|
"pg": "^8.17.2"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node --test"
|
"test": "node --test",
|
||||||
|
"lint": "eslint ."
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20"
|
"node": ">=20"
|
||||||
|
|||||||
@@ -1,8 +1,21 @@
|
|||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
import { verifyTotpStep } from './totp.js';
|
||||||
|
|
||||||
const PASSWORD_ITERATIONS = 100000;
|
const pbkdf2 = promisify(crypto.pbkdf2);
|
||||||
|
|
||||||
|
// Node's old formats remain readable so successful logins can migrate them.
|
||||||
|
const LEGACY_PASSWORD_ITERATIONS = 100000;
|
||||||
|
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 BCRYPT_SCHEME = 'bcrypt$';
|
||||||
|
const BCRYPT_SHA256_SCHEME = 'bcrypt-sha256$';
|
||||||
|
const BCRYPT_ROUNDS = 12;
|
||||||
|
const BCRYPT_MAX_PASSWORD_BYTES = 72;
|
||||||
|
const LEGACY_PASSWORD_PATTERN = /^[0-9a-f]+:[0-9a-f]+$/;
|
||||||
export const RESET_CODE_TTL_MS = 5 * 60 * 1000;
|
export const 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' });
|
||||||
|
|
||||||
@@ -29,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()
|
||||||
);
|
);
|
||||||
@@ -36,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'
|
||||||
@@ -53,33 +68,196 @@ CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at
|
|||||||
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
|
// Usernames are unique ignoring case ("Admin" and "admin" are one identity to a reader). The index
|
||||||
|
// is created only while no such pair exists, so a database that already holds one still starts and
|
||||||
|
// raises a warning; it is built on the first start after one account of each pair is renamed.
|
||||||
|
const USERNAME_CASE_INDEX = `
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM auth_users GROUP BY lower(username) HAVING count(*) > 1) THEN
|
||||||
|
RAISE WARNING 'auth_users holds usernames that differ only by case; the case-insensitive username index was not created';
|
||||||
|
ELSE
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx ON auth_users (lower(username));
|
||||||
|
END IF;
|
||||||
|
EXCEPTION WHEN unique_violation THEN
|
||||||
|
RAISE WARNING 'the case-insensitive username index was not created: a clashing username was just added';
|
||||||
|
END
|
||||||
|
$$
|
||||||
|
`;
|
||||||
|
|
||||||
|
function authError(message, code) {
|
||||||
|
const error = new Error(message);
|
||||||
|
error.code = code;
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refuses a write that would leave an account without a password hash, or store a username that
|
||||||
|
// could be mistaken for another account's email. undefined means "leave unchanged".
|
||||||
|
function assertCredentials(username, passwordHash) {
|
||||||
|
if (passwordHash !== undefined && !passwordHash) {
|
||||||
|
throw authError('password hash is required', 'AUTH_EMPTY_PASSWORD_HASH');
|
||||||
|
}
|
||||||
|
if (typeof username === 'string' && username.includes('@')) {
|
||||||
|
throw authError('username cannot contain @', 'AUTH_INVALID_USERNAME');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertPasswordLength(password) {
|
||||||
if (typeof password !== 'string' || password.length < 8) {
|
if (typeof password !== 'string' || password.length < 8) {
|
||||||
throw new Error('Password must be at least 8 characters');
|
throw new Error('Password must be at least 8 characters');
|
||||||
}
|
}
|
||||||
const salt = crypto.randomBytes(16).toString('hex');
|
if (Buffer.byteLength(password, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) {
|
||||||
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
throw new Error(`Password must be at most ${BCRYPT_MAX_PASSWORD_BYTES} bytes`);
|
||||||
return `${salt}:${hash.toString('hex')}`;
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function verifyPassword(password, stored) {
|
function parsePbkdf2Hash(stored) {
|
||||||
|
const text = String(stored);
|
||||||
|
let iterations = LEGACY_PASSWORD_ITERATIONS;
|
||||||
|
let salt;
|
||||||
|
let expected;
|
||||||
|
if (text.startsWith(`${PASSWORD_FORMAT}$`)) {
|
||||||
|
const parts = text.split('$');
|
||||||
|
if (parts.length !== 4) return null;
|
||||||
|
[, iterations, salt, expected] = parts;
|
||||||
|
iterations = Number(iterations);
|
||||||
|
} else if (LEGACY_PASSWORD_PATTERN.test(text)) {
|
||||||
|
[salt, expected] = text.split(':');
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!/^[0-9a-f]{32}$/.test(salt) || !/^[0-9a-f]{64}$/.test(expected)) return null;
|
||||||
|
if (!Number.isSafeInteger(iterations) || iterations < 1 || iterations > MAX_PBKDF2_ITERATIONS) return null;
|
||||||
|
return { iterations, salt, expected };
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBcryptHash(stored) {
|
||||||
|
const text = String(stored);
|
||||||
|
if (text.startsWith(BCRYPT_SHA256_SCHEME)) return { hash: text.slice(BCRYPT_SHA256_SCHEME.length), prehashed: true };
|
||||||
|
if (text.startsWith(BCRYPT_SCHEME)) return { hash: text.slice(BCRYPT_SCHEME.length), prehashed: false };
|
||||||
|
if (/^\$2[aby]\$/.test(text)) return { hash: text, prehashed: false, legacy: true };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validBcryptHash(parsed) {
|
||||||
|
if (!parsed?.hash) return false;
|
||||||
try {
|
try {
|
||||||
const [salt, expected] = String(stored).split(':');
|
bcrypt.getRounds(parsed.hash);
|
||||||
if (!salt || !expected) return false;
|
return true;
|
||||||
const actual = crypto.pbkdf2Sync(
|
|
||||||
String(password),
|
|
||||||
salt,
|
|
||||||
PASSWORD_ITERATIONS,
|
|
||||||
PASSWORD_KEY_LENGTH,
|
|
||||||
PASSWORD_DIGEST
|
|
||||||
);
|
|
||||||
const expectedBytes = Buffer.from(expected, 'hex');
|
|
||||||
return expectedBytes.length === actual.length && crypto.timingSafeEqual(expectedBytes, actual);
|
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function passwordHashMatches(expected, actual) {
|
||||||
|
const expectedBytes = Buffer.from(expected, 'hex');
|
||||||
|
return expectedBytes.length === actual.length && crypto.timingSafeEqual(expectedBytes, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Blocking bcrypt hash. Prefer hashPasswordAsync in request handlers, because
|
||||||
|
* this call holds the event loop for the whole derivation.
|
||||||
|
*/
|
||||||
|
export function hashPassword(password) {
|
||||||
|
assertPasswordLength(password);
|
||||||
|
return BCRYPT_SCHEME + bcrypt.hashSync(password, BCRYPT_ROUNDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Non-blocking variant of hashPassword with the same bcrypt format. */
|
||||||
|
export async function hashPasswordAsync(password) {
|
||||||
|
assertPasswordLength(password);
|
||||||
|
return BCRYPT_SCHEME + await bcrypt.hash(password, BCRYPT_ROUNDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A legacy PBKDF2 password can exceed bcrypt's 72-byte input limit. Preserve
|
||||||
|
// the full password by hashing its UTF-8 bytes before bcrypt and marking that
|
||||||
|
// representation explicitly in the stored scheme.
|
||||||
|
function bcryptInputForLegacyPassword(password) {
|
||||||
|
const text = String(password);
|
||||||
|
if (Buffer.byteLength(text, 'utf8') <= BCRYPT_MAX_PASSWORD_BYTES) {
|
||||||
|
return { scheme: BCRYPT_SCHEME, input: text };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
scheme: BCRYPT_SHA256_SCHEME,
|
||||||
|
input: crypto.createHash('sha256').update(text, 'utf8').digest('hex'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function derivePasswordHashAsync(password) {
|
||||||
|
const { scheme, input } = bcryptInputForLegacyPassword(password);
|
||||||
|
return scheme + await bcrypt.hash(input, BCRYPT_ROUNDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Blocking verify. Prefer verifyPasswordAsync in request handlers. */
|
||||||
|
export function verifyPassword(password, stored) {
|
||||||
|
try {
|
||||||
|
const bcryptHash = parseBcryptHash(stored);
|
||||||
|
if (bcryptHash) {
|
||||||
|
if (!validBcryptHash(bcryptHash)) return false;
|
||||||
|
const input = bcryptHash.prehashed
|
||||||
|
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
|
||||||
|
: String(password);
|
||||||
|
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
|
||||||
|
return bcrypt.compareSync(input, bcryptHash.hash);
|
||||||
|
}
|
||||||
|
const parsed = parsePbkdf2Hash(stored);
|
||||||
|
if (!parsed) return false;
|
||||||
|
const actual = crypto.pbkdf2Sync(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||||
|
return passwordHashMatches(parsed.expected, actual);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Non-blocking variant of verifyPassword. */
|
||||||
|
export async function verifyPasswordAsync(password, stored) {
|
||||||
|
try {
|
||||||
|
const bcryptHash = parseBcryptHash(stored);
|
||||||
|
if (bcryptHash) {
|
||||||
|
if (!validBcryptHash(bcryptHash)) return false;
|
||||||
|
const input = bcryptHash.prehashed
|
||||||
|
? crypto.createHash('sha256').update(String(password), 'utf8').digest('hex')
|
||||||
|
: String(password);
|
||||||
|
if (!bcryptHash.prehashed && Buffer.byteLength(input, 'utf8') > BCRYPT_MAX_PASSWORD_BYTES) return false;
|
||||||
|
return await bcrypt.compare(input, bcryptHash.hash);
|
||||||
|
}
|
||||||
|
const parsed = parsePbkdf2Hash(stored);
|
||||||
|
if (!parsed) return false;
|
||||||
|
const actual = await pbkdf2(String(password), parsed.salt, parsed.iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||||
|
return passwordHashMatches(parsed.expected, actual);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when a stored hash should be rewritten after a successful login.
|
||||||
|
*/
|
||||||
|
export function passwordHashNeedsUpgrade(stored) {
|
||||||
|
const bcryptHash = parseBcryptHash(stored);
|
||||||
|
if (bcryptHash) {
|
||||||
|
if (!validBcryptHash(bcryptHash)) return true;
|
||||||
|
return Boolean(bcryptHash.legacy) || bcrypt.getRounds(bcryptHash.hash) < BCRYPT_ROUNDS;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies a password and, when it matches a hash in an older scheme, returns a
|
||||||
|
* replacement in the current scheme. The caller stores upgradedHash, for example
|
||||||
|
* with AuthStore.updateUser(id, { passwordHash }). upgradedHash is null when the
|
||||||
|
* password does not match or no rewrite is needed.
|
||||||
|
*/
|
||||||
|
export async function verifyAndUpgradePasswordAsync(password, stored) {
|
||||||
|
if (!(await verifyPasswordAsync(password, stored))) {
|
||||||
|
return { valid: false, upgradedHash: null };
|
||||||
|
}
|
||||||
|
if (!passwordHashNeedsUpgrade(stored)) {
|
||||||
|
return { valid: true, upgradedHash: null };
|
||||||
|
}
|
||||||
|
return { valid: true, upgradedHash: await derivePasswordHashAsync(password) };
|
||||||
|
}
|
||||||
|
|
||||||
export function createSessionToken() {
|
export function createSessionToken() {
|
||||||
const token = crypto.randomBytes(32).toString('base64url');
|
const token = crypto.randomBytes(32).toString('base64url');
|
||||||
return { token, tokenHash: hashToken(token) };
|
return { token, tokenHash: hashToken(token) };
|
||||||
@@ -143,6 +321,7 @@ export class AuthStore {
|
|||||||
|
|
||||||
async ensureSchema() {
|
async ensureSchema() {
|
||||||
await this.database.query(AUTH_SCHEMA);
|
await this.database.query(AUTH_SCHEMA);
|
||||||
|
await this.database.query(USERNAME_CASE_INDEX);
|
||||||
if (this.singleUser) {
|
if (this.singleUser) {
|
||||||
await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))');
|
await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))');
|
||||||
} else {
|
} else {
|
||||||
@@ -156,6 +335,7 @@ export class AuthStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createUser(username, email, passwordHash) {
|
async createUser(username, email, passwordHash) {
|
||||||
|
assertCredentials(username, passwordHash ?? '');
|
||||||
try {
|
try {
|
||||||
const result = await this.database.query(
|
const result = await this.database.query(
|
||||||
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||||
@@ -177,15 +357,20 @@ export class AuthStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async findByIdentifier(identifier) {
|
async findByIdentifier(identifier) {
|
||||||
|
// Usernames are tried before emails, so an identifier resolves to one account in a fixed order.
|
||||||
|
for (const condition of ['username = $1', 'lower(email) = lower($1)']) {
|
||||||
const result = await this.database.query(
|
const result = await this.database.query(
|
||||||
`SELECT id, username, email, password_hash, role, created_at, updated_at
|
`SELECT id, username, email, password_hash, role, created_at, updated_at
|
||||||
FROM auth_users WHERE username = $1 OR lower(email) = lower($1)`,
|
FROM auth_users WHERE ${condition}`,
|
||||||
[identifier]
|
[identifier]
|
||||||
);
|
);
|
||||||
return result.rows[0] || null;
|
if (result.rows[0]) return result.rows[0];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateCredentials(id, username, email, passwordHash) {
|
async updateCredentials(id, username, email, passwordHash) {
|
||||||
|
assertCredentials(username, passwordHash ?? '');
|
||||||
await this.database.query(
|
await this.database.query(
|
||||||
`UPDATE auth_users SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
`UPDATE auth_users SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
||||||
WHERE id = $4`,
|
WHERE id = $4`,
|
||||||
@@ -226,6 +411,7 @@ export class AuthStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createManagedUser(username, email, passwordHash, role = USER_ROLES.USER) {
|
async createManagedUser(username, email, passwordHash, role = USER_ROLES.USER) {
|
||||||
|
assertCredentials(username, passwordHash ?? '');
|
||||||
try {
|
try {
|
||||||
const result = await this.database.query(
|
const result = await this.database.query(
|
||||||
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
`INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||||
@@ -245,6 +431,7 @@ export class AuthStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async updateUser(id, { username, email, passwordHash, role } = {}) {
|
async updateUser(id, { username, email, passwordHash, role } = {}) {
|
||||||
|
assertCredentials(username, passwordHash);
|
||||||
const fields = [];
|
const fields = [];
|
||||||
const values = [];
|
const values = [];
|
||||||
const add = (sql, value) => { fields.push(sql); values.push(value); };
|
const add = (sql, value) => { fields.push(sql); values.push(value); };
|
||||||
@@ -270,29 +457,54 @@ 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 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stores a pending secret without enabling two-factor auth. Throws an error with code
|
||||||
|
* AUTH_TOTP_ALREADY_ENABLED while it is enabled, so a replaced secret cannot silently switch the
|
||||||
|
* second factor off.
|
||||||
|
*/
|
||||||
async setTotpSecret(userId, secret) {
|
async setTotpSecret(userId, secret) {
|
||||||
await this.database.query(
|
const result = await this.database.query(
|
||||||
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2',
|
'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, 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) {
|
||||||
|
throw authError('TOTP is already enabled; disable it before setting a new secret', 'AUTH_TOTP_ALREADY_ENABLED');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,8 +22,16 @@
|
|||||||
// requestPasswordReset/confirmPasswordReset, list/create/update/delete
|
// requestPasswordReset/confirmPasswordReset, list/create/update/delete
|
||||||
// ManagedUser(s), setupStatus.
|
// ManagedUser(s), setupStatus.
|
||||||
|
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { isIP } from 'node:net';
|
||||||
|
|
||||||
const DEFAULT_COOKIE_NAME = 'auth_session';
|
const DEFAULT_COOKIE_NAME = 'auth_session';
|
||||||
const DEFAULT_TIMEOUT_MS = 5000;
|
const DEFAULT_TIMEOUT_MS = 5000;
|
||||||
|
// validate() results, positive and negative, are reused for this long so a burst of requests
|
||||||
|
// with one token costs one AuthGuard call. Revocation through this client (logout) clears the
|
||||||
|
// entry at once; revocation elsewhere is seen within the TTL. Mirrors the Go client.
|
||||||
|
const VALIDATION_CACHE_TTL_MS = 2000;
|
||||||
|
const MAX_VALIDATION_CACHE_ENTRIES = 10000;
|
||||||
|
|
||||||
// PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
|
// PROJECT_KEY_HEADER is the header AuthClient attaches to every request when
|
||||||
// constructed with a projectKey, identifying the calling project to
|
// constructed with a projectKey, identifying the calling project to
|
||||||
@@ -31,6 +39,14 @@ const DEFAULT_TIMEOUT_MS = 5000;
|
|||||||
// AuthGuard's project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
|
// AuthGuard's project-scope admin UI). Mirrors Go's authclient.ProjectKeyHeader.
|
||||||
export const PROJECT_KEY_HEADER = 'X-Project-Key';
|
export const PROJECT_KEY_HEADER = 'X-Project-Key';
|
||||||
|
|
||||||
|
// FORWARDED_FOR_HEADER carries the end user's address on the credential calls (the `clientIp`
|
||||||
|
// option of register, login, totpVerify, totpDisable and the password-reset calls), so AuthGuard's
|
||||||
|
// per-address limits see the end user instead of this service. AuthGuard reads it only when the
|
||||||
|
// calling service's own address is in its TRUSTED_PROXIES, so sending it changes nothing for a
|
||||||
|
// deployment that has not opted in. Pass an address the caller has already verified, never a raw
|
||||||
|
// request header; anything that is not an IP address is ignored.
|
||||||
|
export const FORWARDED_FOR_HEADER = 'X-Forwarded-For';
|
||||||
|
|
||||||
export class InvalidSessionError extends Error {
|
export class InvalidSessionError extends Error {
|
||||||
constructor(message = 'authclient: invalid or missing session') {
|
constructor(message = 'authclient: invalid or missing session') {
|
||||||
super(message);
|
super(message);
|
||||||
@@ -81,6 +97,40 @@ export class AuthClient {
|
|||||||
// Normally a project's own lowercase identifier, matching the key
|
// Normally a project's own lowercase identifier, matching the key
|
||||||
// ProjectConfigurator registers it under.
|
// ProjectConfigurator registers it under.
|
||||||
this.projectKey = String(options.projectKey ?? '').trim().toLowerCase();
|
this.projectKey = String(options.projectKey ?? '').trim().toLowerCase();
|
||||||
|
this._validationCache = new Map();
|
||||||
|
}
|
||||||
|
|
||||||
|
_validationKey(token) {
|
||||||
|
return createHash('sha256').update(token).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns the cached validate() outcome for token: a user, null for a known-invalid session, or undefined on a miss. */
|
||||||
|
_cachedValidation(token) {
|
||||||
|
const key = this._validationKey(token);
|
||||||
|
const entry = this._validationCache.get(key);
|
||||||
|
if (!entry) return undefined;
|
||||||
|
if (Date.now() >= entry.expires) {
|
||||||
|
this._validationCache.delete(key);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return entry.user;
|
||||||
|
}
|
||||||
|
|
||||||
|
_cacheValidation(token, user) {
|
||||||
|
if (this._validationCache.size >= MAX_VALIDATION_CACHE_ENTRIES) {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [key, entry] of this._validationCache) {
|
||||||
|
if (now >= entry.expires) this._validationCache.delete(key);
|
||||||
|
}
|
||||||
|
if (this._validationCache.size >= MAX_VALIDATION_CACHE_ENTRIES) {
|
||||||
|
// Map keeps insertion order, so this drops the oldest entry.
|
||||||
|
this._validationCache.delete(this._validationCache.keys().next().value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this._validationCache.set(this._validationKey(token), {
|
||||||
|
user,
|
||||||
|
expires: Date.now() + VALIDATION_CACHE_TTL_MS,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
_projectKeyHeaders() {
|
_projectKeyHeaders() {
|
||||||
@@ -105,6 +155,7 @@ export class AuthClient {
|
|||||||
const normalized = AuthClient._normalizeBaseUrl(baseUrl);
|
const normalized = AuthClient._normalizeBaseUrl(baseUrl);
|
||||||
if (normalized) {
|
if (normalized) {
|
||||||
this.baseUrl = normalized;
|
this.baseUrl = normalized;
|
||||||
|
this._validationCache.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,6 +223,13 @@ export class AuthClient {
|
|||||||
if (!trimmed) {
|
if (!trimmed) {
|
||||||
throw new InvalidSessionError();
|
throw new InvalidSessionError();
|
||||||
}
|
}
|
||||||
|
const cached = this._cachedValidation(trimmed);
|
||||||
|
if (cached === null) {
|
||||||
|
throw new InvalidSessionError();
|
||||||
|
}
|
||||||
|
if (cached !== undefined) {
|
||||||
|
return { ...cached };
|
||||||
|
}
|
||||||
|
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||||
@@ -192,15 +250,22 @@ export class AuthClient {
|
|||||||
payload = await response.json();
|
payload = await response.json();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (response.status === 401) {
|
if (response.status === 401) {
|
||||||
|
this._cacheValidation(trimmed, null);
|
||||||
throw new InvalidSessionError();
|
throw new InvalidSessionError();
|
||||||
}
|
}
|
||||||
throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err });
|
throw new Error(`authclient: decode AuthGuard response: ${err.message}`, { cause: err });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response.status !== 200 || !payload?.valid) {
|
if (response.status === 401 || (response.status === 200 && !payload?.valid)) {
|
||||||
|
this._cacheValidation(trimmed, null);
|
||||||
throw new InvalidSessionError();
|
throw new InvalidSessionError();
|
||||||
}
|
}
|
||||||
return { id: payload.user_id, username: payload.username, role: payload.role };
|
if (response.status !== 200) {
|
||||||
|
throw new InvalidSessionError();
|
||||||
|
}
|
||||||
|
const user = { id: payload.user_id, username: payload.username, role: payload.role };
|
||||||
|
this._cacheValidation(trimmed, user);
|
||||||
|
return { ...user };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -211,9 +276,8 @@ export class AuthClient {
|
|||||||
*/
|
*/
|
||||||
middleware() {
|
middleware() {
|
||||||
return async (req, res, next) => {
|
return async (req, res, next) => {
|
||||||
const token = this.tokenFromRequest(req);
|
|
||||||
try {
|
try {
|
||||||
req.authUser = await this.validate(token);
|
req.authUser = await this.validate(this.tokenFromRequest(req));
|
||||||
next();
|
next();
|
||||||
} catch {
|
} catch {
|
||||||
// Fail closed on both an invalid session and a transport/decoding
|
// Fail closed on both an invalid session and a transport/decoding
|
||||||
@@ -236,7 +300,14 @@ export class AuthClient {
|
|||||||
.split(';')
|
.split(';')
|
||||||
.map(part => part.trim())
|
.map(part => part.trim())
|
||||||
.find(part => part.startsWith(`${this.cookieName}=`));
|
.find(part => part.startsWith(`${this.cookieName}=`));
|
||||||
if (match) return decodeURIComponent(match.slice(this.cookieName.length + 1));
|
if (match) {
|
||||||
|
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(match.slice(this.cookieName.length + 1));
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
@@ -252,13 +323,14 @@ export class AuthClient {
|
|||||||
* AuthClient._call exactly.
|
* AuthClient._call exactly.
|
||||||
* @returns {Promise<{payload: any, cookies: string[]}>}
|
* @returns {Promise<{payload: any, cookies: string[]}>}
|
||||||
*/
|
*/
|
||||||
async _call(method, path, { token = '', body } = {}) {
|
async _call(method, path, { token = '', body, clientIp } = {}) {
|
||||||
if (!this.baseUrl) {
|
if (!this.baseUrl) {
|
||||||
throw new Error('authclient: client has no base URL');
|
throw new Error('authclient: client has no base URL');
|
||||||
}
|
}
|
||||||
const headers = { ...this._projectKeyHeaders() };
|
const headers = { ...this._projectKeyHeaders() };
|
||||||
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
||||||
if (token) headers.Authorization = `Bearer ${token}`;
|
if (token) headers.Authorization = `Bearer ${token}`;
|
||||||
|
if (typeof clientIp === 'string' && isIP(clientIp.trim())) headers[FORWARDED_FOR_HEADER] = clientIp.trim();
|
||||||
|
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||||
@@ -347,9 +419,10 @@ export class AuthClient {
|
|||||||
* starting a session for it.
|
* starting a session for it.
|
||||||
* @returns {Promise<{user: object, cookies: string[]}>}
|
* @returns {Promise<{user: object, cookies: string[]}>}
|
||||||
*/
|
*/
|
||||||
async register(username, email, password) {
|
async register(username, email, password, { clientIp } = {}) {
|
||||||
const { payload, cookies } = await this._call('POST', '/api/register', {
|
const { payload, cookies } = await this._call('POST', '/api/register', {
|
||||||
body: { username, email, password },
|
body: { username, email, password },
|
||||||
|
clientIp,
|
||||||
});
|
});
|
||||||
return { user: AuthClient._publicUser(payload), cookies };
|
return { user: AuthClient._publicUser(payload), cookies };
|
||||||
}
|
}
|
||||||
@@ -360,10 +433,10 @@ export class AuthClient {
|
|||||||
* enabled and no valid code was supplied.
|
* enabled and no valid code was supplied.
|
||||||
* @returns {Promise<{user: object, cookies: string[]}>}
|
* @returns {Promise<{user: object, cookies: string[]}>}
|
||||||
*/
|
*/
|
||||||
async login(usernameOrEmail, password, totpToken = '') {
|
async login(usernameOrEmail, password, totpToken = '', { clientIp } = {}) {
|
||||||
const body = { username_or_email: usernameOrEmail, password };
|
const body = { username_or_email: usernameOrEmail, password };
|
||||||
if (totpToken) body.totp_token = totpToken;
|
if (totpToken) body.totp_token = totpToken;
|
||||||
const { payload, cookies } = await this._call('POST', '/api/login', { body });
|
const { payload, cookies } = await this._call('POST', '/api/login', { body, clientIp });
|
||||||
return { user: AuthClient._publicUser(payload), cookies };
|
return { user: AuthClient._publicUser(payload), cookies };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -375,6 +448,7 @@ export class AuthClient {
|
|||||||
*/
|
*/
|
||||||
async logout(token) {
|
async logout(token) {
|
||||||
const { cookies } = await this._call('POST', '/api/logout', { token });
|
const { cookies } = await this._call('POST', '/api/logout', { token });
|
||||||
|
this._validationCache.delete(this._validationKey(String(token ?? '').trim()));
|
||||||
return cookies;
|
return cookies;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -405,8 +479,8 @@ export class AuthClient {
|
|||||||
* Calls POST /api/totp/verify, confirming code against the pending
|
* Calls POST /api/totp/verify, confirming code against the pending
|
||||||
* secret totpEnable provisioned and activating two-factor auth.
|
* secret totpEnable provisioned and activating two-factor auth.
|
||||||
*/
|
*/
|
||||||
async totpVerify(token, code) {
|
async totpVerify(token, code, { clientIp } = {}) {
|
||||||
await this._call('POST', '/api/totp/verify', { token, body: { token: code } });
|
await this._call('POST', '/api/totp/verify', { token, body: { token: code }, clientIp });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -414,8 +488,8 @@ export class AuthClient {
|
|||||||
* account. AuthGuard requires code to be one last valid TOTP code as
|
* account. AuthGuard requires code to be one last valid TOTP code as
|
||||||
* proof of possession.
|
* proof of possession.
|
||||||
*/
|
*/
|
||||||
async totpDisable(token, code) {
|
async totpDisable(token, code, { clientIp } = {}) {
|
||||||
await this._call('POST', '/api/totp/disable', { token, body: { token: code } });
|
await this._call('POST', '/api/totp/disable', { token, body: { token: code }, clientIp });
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- password reset ("break glass", console-only - see AuthGuard's README) --
|
// --- password reset ("break glass", console-only - see AuthGuard's README) --
|
||||||
@@ -428,9 +502,9 @@ export class AuthClient {
|
|||||||
* the intended place to drive this, not an individual project (see
|
* the intended place to drive this, not an individual project (see
|
||||||
* AuthGuard's README's "Web UI" section).
|
* AuthGuard's README's "Web UI" section).
|
||||||
*/
|
*/
|
||||||
async requestPasswordReset(usernameOrEmail = '') {
|
async requestPasswordReset(usernameOrEmail = '', { clientIp } = {}) {
|
||||||
const body = usernameOrEmail ? { username_or_email: usernameOrEmail } : {};
|
const body = usernameOrEmail ? { username_or_email: usernameOrEmail } : {};
|
||||||
await this._call('POST', '/api/password-reset/request', { body });
|
await this._call('POST', '/api/password-reset/request', { body, clientIp });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -438,9 +512,10 @@ export class AuthClient {
|
|||||||
* relayed out-of-band and a new password, and invalidates every
|
* relayed out-of-band and a new password, and invalidates every
|
||||||
* existing session for that account.
|
* existing session for that account.
|
||||||
*/
|
*/
|
||||||
async confirmPasswordReset(code, newPassword) {
|
async confirmPasswordReset(code, newPassword, { clientIp } = {}) {
|
||||||
await this._call('POST', '/api/password-reset/confirm', {
|
await this._call('POST', '/api/password-reset/confirm', {
|
||||||
body: { code, password: newPassword },
|
body: { code, password: newPassword },
|
||||||
|
clientIp,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,8 @@
|
|||||||
* example.
|
* example.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {{authGuardUrl?: string, carrierNodeUrl?: string, carrierNodeUrls?: string[]}} InfoLike
|
* @typedef {{authGuardUrl?: string, carrierNodeUrl?: string, carrierNodeUrls?: string[]}} InfoLike
|
||||||
*/
|
*/
|
||||||
@@ -58,6 +60,51 @@ export class Info {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Shortest SECRET a service accepts for its internal routes. */
|
||||||
|
export const MIN_INTERNAL_SECRET_LENGTH = 16;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placeholders from .env.example files and the bare variable name. They are
|
||||||
|
* public, so they never gate a route.
|
||||||
|
*/
|
||||||
|
export const EXAMPLE_INTERNAL_SECRETS = new Set(['SECRET', 'change-me-to-a-long-random-value']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the configured secret is strong enough to gate an internal route:
|
||||||
|
* at least MIN_INTERNAL_SECRET_LENGTH characters and not an example
|
||||||
|
* placeholder. Length counts characters, as the Python and Go helpers do.
|
||||||
|
* @param {unknown} secret
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function internalSecretUsable(secret) {
|
||||||
|
const value = String(secret ?? '');
|
||||||
|
return [...value].length >= MIN_INTERNAL_SECRET_LENGTH && !EXAMPLE_INTERNAL_SECRETS.has(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the X-Internal-Auth value equals the configured secret. A secret
|
||||||
|
* that is not usable (see internalSecretUsable) never matches, and the
|
||||||
|
* comparison is constant-time.
|
||||||
|
* @param {unknown} provided
|
||||||
|
* @param {unknown} secret
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function internalSecretMatches(provided, secret) {
|
||||||
|
if (!internalSecretUsable(secret)) return false;
|
||||||
|
const expected = Buffer.from(String(secret));
|
||||||
|
const actual = Buffer.from(String(provided ?? ''));
|
||||||
|
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isServiceUrl(value) {
|
||||||
|
try {
|
||||||
|
const url = new URL(value);
|
||||||
|
return (url.protocol === 'http:' || url.protocol === 'https:') && url.host !== '';
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function normalize(info) {
|
function normalize(info) {
|
||||||
let cleaned = (info.carrierNodeUrls ?? []).map((u) => String(u ?? '').trim()).filter(Boolean);
|
let cleaned = (info.carrierNodeUrls ?? []).map((u) => String(u ?? '').trim()).filter(Boolean);
|
||||||
if (cleaned.length === 0 && String(info.carrierNodeUrl ?? '').trim()) {
|
if (cleaned.length === 0 && String(info.carrierNodeUrl ?? '').trim()) {
|
||||||
@@ -115,13 +162,20 @@ export class Store {
|
|||||||
/**
|
/**
|
||||||
* Replaces the current Info, field by field, ignoring a blank/empty field
|
* Replaces the current Info, field by field, ignoring a blank/empty field
|
||||||
* so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers
|
* so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers
|
||||||
* the other value. Returns the resulting Info. Minimal Express usage:
|
* the other value. Every URL must be an http or https URL with a host;
|
||||||
|
* otherwise nothing is changed and an error is thrown. Returns the resulting
|
||||||
|
* Info. Minimal Express usage:
|
||||||
*
|
*
|
||||||
* app.put('/api/core-services/internal', (req, res) => {
|
* app.put('/api/core-services/internal', (req, res) => {
|
||||||
* if (req.get('X-Internal-Auth') !== process.env.SECRET) {
|
* if (!internalSecretMatches(req.get('X-Internal-Auth'), process.env.SECRET)) {
|
||||||
* return res.status(401).json({ error: 'internal service authentication required' });
|
* return res.status(401).json({ error: 'internal service authentication required' });
|
||||||
* }
|
* }
|
||||||
* const info = coreConfigStore.set(Info.fromJSON(req.body));
|
* let info;
|
||||||
|
* try {
|
||||||
|
* info = coreConfigStore.set(Info.fromJSON(req.body));
|
||||||
|
* } catch (error) {
|
||||||
|
* return res.status(400).json({ error: error.message });
|
||||||
|
* }
|
||||||
* res.json({ ok: true, info: info.toJSON() });
|
* res.json({ ok: true, info: info.toJSON() });
|
||||||
* });
|
* });
|
||||||
*
|
*
|
||||||
@@ -130,6 +184,12 @@ export class Store {
|
|||||||
*/
|
*/
|
||||||
set(nextInfo) {
|
set(nextInfo) {
|
||||||
const next = normalize(nextInfo instanceof Info ? nextInfo : new Info(nextInfo));
|
const next = normalize(nextInfo instanceof Info ? nextInfo : new Info(nextInfo));
|
||||||
|
const badUrl = [next.authGuardUrl, ...next.carrierNodeUrls].find(
|
||||||
|
(url) => url && !isServiceUrl(url)
|
||||||
|
);
|
||||||
|
if (badUrl !== undefined) {
|
||||||
|
throw new TypeError(`core service URL must be an http or https URL with a host: ${badUrl}`);
|
||||||
|
}
|
||||||
if (next.authGuardUrl) {
|
if (next.authGuardUrl) {
|
||||||
this._info.authGuardUrl = next.authGuardUrl;
|
this._info.authGuardUrl = next.authGuardUrl;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,6 +32,18 @@ export function isTransientConnectionError(error) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const READ_ONLY_STATEMENT = /^\s*select\b/i;
|
||||||
|
const LOCKING_OR_WRITING_READ = /\bfor\s+(update|share|no\s+key\s+update|key\s+share)\b|\binto\b|\b(nextval|setval)\s*\(/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True for a plain SELECT that cannot change data or sequences. Only these
|
||||||
|
* statements are retried after a transient error by default.
|
||||||
|
*/
|
||||||
|
export function isReadOnlyStatement(text) {
|
||||||
|
const sql = String(text);
|
||||||
|
return READ_ONLY_STATEMENT.test(sql) && !LOCKING_OR_WRITING_READ.test(sql);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owns one pg pool and exposes bounded startup, retry, transaction, and
|
* Owns one pg pool and exposes bounded startup, retry, transaction, and
|
||||||
* shutdown behavior. Domain repositories should depend on this abstraction
|
* shutdown behavior. Domain repositories should depend on this abstraction
|
||||||
@@ -39,10 +51,18 @@ export function isTransientConnectionError(error) {
|
|||||||
*/
|
*/
|
||||||
export class Database {
|
export class Database {
|
||||||
constructor(options = {}) {
|
constructor(options = {}) {
|
||||||
const { pool, ...poolOptions } = options;
|
const { pool, log = console.error, ...poolOptions } = options;
|
||||||
this.pool = pool || new Pool(poolOptions);
|
this.pool = pool || new Pool(poolOptions);
|
||||||
this.ownsPool = !pool;
|
this.ownsPool = !pool;
|
||||||
this.ready = false;
|
this.ready = false;
|
||||||
|
this.log = log;
|
||||||
|
if (typeof this.pool.on === 'function') {
|
||||||
|
// pg emits 'error' for an idle client that fails, for example after a
|
||||||
|
// database restart. With no listener the event is thrown and can end the process.
|
||||||
|
this.pool.on('error', error => {
|
||||||
|
this.log(`[database] idle pool client error: ${error?.message || error}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static fromEnv(env = process.env) {
|
static fromEnv(env = process.env) {
|
||||||
@@ -77,12 +97,19 @@ export class Database {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async query(text, values = []) {
|
/**
|
||||||
|
* Runs one statement. After a transient connection error the statement is
|
||||||
|
* retried only when it is read-only, so a write that committed before the
|
||||||
|
* connection dropped is not applied twice. Pass `{ retry: true }` to opt a
|
||||||
|
* known-idempotent statement in, or `{ retry: false }` to opt a read out.
|
||||||
|
*/
|
||||||
|
async query(text, values = [], options = {}) {
|
||||||
await this.connect();
|
await this.connect();
|
||||||
try {
|
try {
|
||||||
return await this.pool.query(text, values);
|
return await this.pool.query(text, values);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isTransientConnectionError(error)) throw error;
|
const retry = options.retry ?? isReadOnlyStatement(text);
|
||||||
|
if (!retry || !isTransientConnectionError(error)) throw error;
|
||||||
return this.pool.query(text, values);
|
return this.pool.query(text, values);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,12 +15,16 @@ export {
|
|||||||
ResetManager,
|
ResetManager,
|
||||||
createSessionToken,
|
createSessionToken,
|
||||||
hashPassword,
|
hashPassword,
|
||||||
|
hashPasswordAsync,
|
||||||
hashToken,
|
hashToken,
|
||||||
USER_ROLES,
|
USER_ROLES,
|
||||||
canAssignRole,
|
canAssignRole,
|
||||||
canManageUsers,
|
canManageUsers,
|
||||||
normalizeRole,
|
normalizeRole,
|
||||||
|
passwordHashNeedsUpgrade,
|
||||||
|
verifyAndUpgradePasswordAsync,
|
||||||
verifyPassword,
|
verifyPassword,
|
||||||
|
verifyPasswordAsync,
|
||||||
} from './auth.js';
|
} from './auth.js';
|
||||||
export {
|
export {
|
||||||
TOTP_DIGITS,
|
TOTP_DIGITS,
|
||||||
@@ -29,7 +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 { Info as CoreConfigInfo, Store as CoreConfigStore } from './coreconfig.js';
|
export {
|
||||||
|
EXAMPLE_INTERNAL_SECRETS,
|
||||||
|
Info as CoreConfigInfo,
|
||||||
|
MIN_INTERNAL_SECRET_LENGTH,
|
||||||
|
Store as CoreConfigStore,
|
||||||
|
internalSecretMatches,
|
||||||
|
internalSecretUsable,
|
||||||
|
} from './coreconfig.js';
|
||||||
@@ -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;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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) {
|
||||||
|
|||||||
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user