Compare commits
30
Commits
937f51b4fb
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
362cee26fd | ||
|
|
01b18be1e4 | ||
|
|
ed3544acfe | ||
|
|
6b84a5d27d | ||
|
|
ae98902446 | ||
|
|
5a4bf45bc7 | ||
|
|
36ab01aab1 | ||
|
|
a8b79ffd1b | ||
|
|
cf468ed833 | ||
|
|
7cea6ebb1e | ||
|
|
08ec03b6ec | ||
|
|
0c4dc3aacb | ||
|
|
5d9e3063c5 | ||
|
|
833eab04af | ||
|
|
0fd1805502 | ||
|
|
7150ebd13e | ||
|
|
817236f349 | ||
|
|
85e6db67b5 | ||
|
|
f246c4290f | ||
|
|
39953dc492 | ||
|
|
0d27c9a8d9 | ||
|
|
4e9cb20971 | ||
|
|
f5ee0298d8 | ||
|
|
71060bd020 | ||
|
|
1719b3c23b | ||
|
|
b4e9651529 | ||
|
|
62db511c7b | ||
|
|
94d52c7622 | ||
|
|
97c237be80 | ||
|
|
0ff94f9b10 |
No files matched your search
@@ -0,0 +1,224 @@
|
|||||||
|
name: Android Release (static debug key)
|
||||||
|
|
||||||
|
# Same flow as android-release.yml, but the APK is signed with a static debug key instead of the
|
||||||
|
# release keystore. The key is created on the first run, committed to CollabTableAndroid/signing/, and
|
||||||
|
# reused by every later run, so builds from this workflow can update each other in place. It is for
|
||||||
|
# test builds only: the release keystore is secret and this key is not.
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
bump_type:
|
||||||
|
description: 'Version bump type'
|
||||||
|
required: true
|
||||||
|
default: 'patch'
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- patch
|
||||||
|
- minor
|
||||||
|
- major
|
||||||
|
changelog:
|
||||||
|
description: 'Changelog for this release (leave blank to auto-generate from commits)'
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
|
||||||
|
# The first run creates the key and pushes it. Queue runs so that a later run sees the key instead of
|
||||||
|
# creating a second one.
|
||||||
|
concurrency:
|
||||||
|
group: android-release-static-debug
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
name: Bump version, build & release (static debug key)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Android debug keystore conventions (password "android", alias "androiddebugkey").
|
||||||
|
STATIC_KEYSTORE: CollabTableAndroid/signing/static-debug.jks
|
||||||
|
STATIC_STORE_PASSWORD: android
|
||||||
|
STATIC_KEY_ALIAS: androiddebugkey
|
||||||
|
STATIC_KEY_PASSWORD: android
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
# Java comes first: the key is checked with keytool before anything is pushed.
|
||||||
|
- name: Set up JDK 21
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: 'temurin'
|
||||||
|
java-version: '21'
|
||||||
|
cache: 'gradle'
|
||||||
|
|
||||||
|
# A key is generated only when the repository has never held one. If the file was committed
|
||||||
|
# before but is now missing, the run stops: a new key would change the certificate and break
|
||||||
|
# in-place updates for every installed copy.
|
||||||
|
- name: Prepare static debug key
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ -f "$STATIC_KEYSTORE" ]; then
|
||||||
|
echo "Reusing the static debug key in $STATIC_KEYSTORE"
|
||||||
|
elif [ -n "$(git log --all --format=%H -- "$STATIC_KEYSTORE")" ]; then
|
||||||
|
echo "::error::$STATIC_KEYSTORE exists in the repository history but not on this branch. Restore it (merge or cherry-pick) instead of generating a new key."
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
mkdir -p "$(dirname "$STATIC_KEYSTORE")"
|
||||||
|
keytool -genkeypair -noprompt \
|
||||||
|
-keystore "$STATIC_KEYSTORE" \
|
||||||
|
-storetype PKCS12 \
|
||||||
|
-storepass:env STATIC_STORE_PASSWORD \
|
||||||
|
-keypass:env STATIC_KEY_PASSWORD \
|
||||||
|
-alias "$STATIC_KEY_ALIAS" \
|
||||||
|
-keyalg RSA -keysize 2048 -validity 10000 \
|
||||||
|
-dname "CN=Android Debug,O=Android,C=US"
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git add "$STATIC_KEYSTORE"
|
||||||
|
git commit -m "chore(android): add static debug signing key"
|
||||||
|
git push
|
||||||
|
echo "Created the static debug key and pushed it to the repository."
|
||||||
|
fi
|
||||||
|
FINGERPRINT=$(keytool -list -v -keystore "$STATIC_KEYSTORE" -storepass:env STATIC_STORE_PASSWORD \
|
||||||
|
-alias "$STATIC_KEY_ALIAS" | sed -n 's/^[[:space:]]*SHA256: //p')
|
||||||
|
echo "::notice::Static debug certificate SHA-256: $FINGERPRINT"
|
||||||
|
|
||||||
|
- name: Bump version in build.gradle.kts
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
BUMP_TYPE: ${{ inputs.bump_type }}
|
||||||
|
run: |
|
||||||
|
GRADLE_FILE="CollabTableAndroid/app/build.gradle"
|
||||||
|
|
||||||
|
CURRENT_CODE=$(grep -oP 'versionCode\s*=\s*\K[0-9]+' "$GRADLE_FILE")
|
||||||
|
CURRENT_NAME=$(grep -oP 'versionName\s*=\s*"\K[^"]+' "$GRADLE_FILE")
|
||||||
|
|
||||||
|
IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_NAME"
|
||||||
|
|
||||||
|
case "$BUMP_TYPE" in
|
||||||
|
major) MAJOR=$((MAJOR+1)); MINOR=0; PATCH=0 ;;
|
||||||
|
minor) MINOR=$((MINOR+1)); PATCH=0 ;;
|
||||||
|
patch) PATCH=$((PATCH+1)) ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
NEW_CODE=$((CURRENT_CODE+1))
|
||||||
|
NEW_NAME="${MAJOR}.${MINOR}.${PATCH}"
|
||||||
|
|
||||||
|
sed -i "s/versionCode = ${CURRENT_CODE}/versionCode = ${NEW_CODE}/" "$GRADLE_FILE"
|
||||||
|
sed -i "s/versionName = \"${CURRENT_NAME}\"/versionName = \"${NEW_NAME}\"/" "$GRADLE_FILE"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "new_code=${NEW_CODE}"
|
||||||
|
echo "new_name=${NEW_NAME}"
|
||||||
|
echo "tag=v${NEW_NAME}-debug"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Commit version bump
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git add CollabTableAndroid/app/build.gradle
|
||||||
|
git commit -m "chore(android): bump version to ${{ steps.version.outputs.new_name }} (code ${{ steps.version.outputs.new_code }})"
|
||||||
|
git push
|
||||||
|
|
||||||
|
- name: Set up Gradle
|
||||||
|
uses: gradle/actions/setup-gradle@v3
|
||||||
|
|
||||||
|
- name: Install Android SDK
|
||||||
|
uses: android-actions/setup-android@v4
|
||||||
|
|
||||||
|
- name: Accept SDK licenses
|
||||||
|
shell: bash
|
||||||
|
run: yes | sdkmanager --licenses || true
|
||||||
|
|
||||||
|
# Install the compileSdk platform, build-tools 36.0.0 (used by AGP lint) and 37.0.0 (used by apksigner below).
|
||||||
|
- name: Install Android SDK packages
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
sdkmanager "platform-tools" "platforms;android-37.2" "build-tools;36.0.0" "build-tools;37.0.0"
|
||||||
|
|
||||||
|
- name: Run lint and ktlint
|
||||||
|
working-directory: CollabTableAndroid
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
chmod +x gradlew
|
||||||
|
./gradlew --no-daemon lintDebug ktlintCheck
|
||||||
|
|
||||||
|
# The release build type picks up the signing config from these variables, so the static key
|
||||||
|
# is used without any change to the Gradle build.
|
||||||
|
- name: Build release APK signed with the static debug key
|
||||||
|
working-directory: CollabTableAndroid
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OGS_KEYSTORE_FILE: ${{ github.workspace }}/${{ env.STATIC_KEYSTORE }}
|
||||||
|
OGS_KEYSTORE_PASSWORD: ${{ env.STATIC_STORE_PASSWORD }}
|
||||||
|
OGS_KEY_ALIAS: ${{ env.STATIC_KEY_ALIAS }}
|
||||||
|
OGS_KEY_PASSWORD: ${{ env.STATIC_KEY_PASSWORD }}
|
||||||
|
run: ./gradlew --no-daemon assembleRelease
|
||||||
|
|
||||||
|
- name: Verify APK is signed with the static debug key
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
APK="CollabTableAndroid/app/build/outputs/apk/release/app-release.apk"
|
||||||
|
APKSIGNER="$ANDROID_HOME/build-tools/37.0.0/apksigner"
|
||||||
|
CERTS=$("$APKSIGNER" verify --print-certs "$APK")
|
||||||
|
ACTUAL=$(printf '%s\n' "$CERTS" | sed -n 's/^.*certificate SHA-256 digest: //p' | sed -n '1p')
|
||||||
|
EXPECTED=$(keytool -list -v -keystore "$STATIC_KEYSTORE" -storepass:env STATIC_STORE_PASSWORD \
|
||||||
|
-alias "$STATIC_KEY_ALIAS" | sed -n 's/^[[:space:]]*SHA256: //p' | tr -d ':' | tr 'A-F' 'a-f')
|
||||||
|
if [ "$ACTUAL" != "$EXPECTED" ]; then
|
||||||
|
echo "::error::APK is signed with $ACTUAL, expected the static debug key $EXPECTED."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Rename APK with version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
SRC="CollabTableAndroid/app/build/outputs/apk/release/app-release.apk"
|
||||||
|
cp "$SRC" "CollabTable-${{ steps.version.outputs.tag }}.apk"
|
||||||
|
|
||||||
|
- name: Generate changelog
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
CHANGELOG_INPUT: ${{ inputs.changelog }}
|
||||||
|
run: |
|
||||||
|
if [ -n "$CHANGELOG_INPUT" ]; then
|
||||||
|
printf '%s' "$CHANGELOG_INPUT" > release-notes.md
|
||||||
|
else
|
||||||
|
LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
|
||||||
|
if [ -n "$LAST_TAG" ]; then
|
||||||
|
RANGE="${LAST_TAG}..HEAD"
|
||||||
|
else
|
||||||
|
RANGE="HEAD"
|
||||||
|
fi
|
||||||
|
COMMITS=$(git log "$RANGE" --pretty=format:"%s" | grep -vE "^chore\(android\): (bump version|add static debug signing key)" || true)
|
||||||
|
FEATURES=$(echo "$COMMITS" | grep -E "^feat(\\(.+\\))?:" | sed 's/^feat[^:]*: /- /' || true)
|
||||||
|
FIXES=$(echo "$COMMITS" | grep -E "^fix(\\(.+\\))?:" | sed 's/^fix[^:]*: /- /' || true)
|
||||||
|
OTHERS=$(echo "$COMMITS" | grep -vE "^(feat|fix)(\\(.+\\))?:" | grep -v '^$' | sed 's/^/- /' || true)
|
||||||
|
{
|
||||||
|
if [ -n "$FEATURES" ]; then printf '### Features\n%s\n\n' "$FEATURES"; fi
|
||||||
|
if [ -n "$FIXES" ]; then printf '### Bug Fixes\n%s\n\n' "$FIXES"; fi
|
||||||
|
if [ -n "$OTHERS" ]; then printf '### Other Changes\n%s\n\n' "$OTHERS"; fi
|
||||||
|
} > release-notes.md
|
||||||
|
if [ ! -s release-notes.md ]; then echo 'No changes recorded.' > release-notes.md; fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Marked as a pre-release so it never takes the "Latest" badge from the real release.
|
||||||
|
- name: Create GitHub pre-release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ steps.version.outputs.tag }}
|
||||||
|
name: ${{ steps.version.outputs.tag }} (static debug key)
|
||||||
|
body_path: release-notes.md
|
||||||
|
files: CollabTable-${{ steps.version.outputs.tag }}.apk
|
||||||
|
prerelease: true
|
||||||
|
fail_on_unmatched_files: true
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
name: Android Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
bump_type:
|
||||||
|
description: 'Version bump type'
|
||||||
|
required: true
|
||||||
|
default: 'patch'
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- patch
|
||||||
|
- minor
|
||||||
|
- major
|
||||||
|
changelog:
|
||||||
|
description: 'Changelog for this release (leave blank to auto-generate from commits)'
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
name: Bump version, build & release
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
# Java comes first: the signing key is checked with keytool before anything is pushed.
|
||||||
|
- name: Set up JDK 21
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: 'temurin'
|
||||||
|
java-version: '21'
|
||||||
|
cache: 'gradle'
|
||||||
|
|
||||||
|
- name: Prepare release signing key
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OGS_KEYSTORE_BASE64: ${{ secrets.OGS_KEYSTORE_BASE64 }}
|
||||||
|
OGS_KEYSTORE_PASSWORD: ${{ secrets.OGS_KEYSTORE_PASSWORD }}
|
||||||
|
OGS_KEY_ALIAS: ${{ secrets.OGS_KEY_ALIAS }}
|
||||||
|
OGS_KEY_PASSWORD: ${{ secrets.OGS_KEY_PASSWORD }}
|
||||||
|
OGS_RELEASE_CERT_SHA256: ${{ vars.OGS_RELEASE_CERT_SHA256 }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
for name in OGS_KEYSTORE_BASE64 OGS_KEYSTORE_PASSWORD OGS_KEY_ALIAS OGS_KEY_PASSWORD; do
|
||||||
|
if [ -z "${!name}" ]; then
|
||||||
|
echo "::error::Secret $name is not set. Releases must be signed with the release key."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
KEYSTORE="$RUNNER_TEMP/ogs-release.jks"
|
||||||
|
printf '%s' "$OGS_KEYSTORE_BASE64" | base64 -d > "$KEYSTORE"
|
||||||
|
|
||||||
|
# Fail before the version bump is pushed if the keystore is not the pinned release key.
|
||||||
|
ACTUAL=$(keytool -list -v -keystore "$KEYSTORE" -storepass:env OGS_KEYSTORE_PASSWORD \
|
||||||
|
-alias "$OGS_KEY_ALIAS" | sed -n 's/^[[:space:]]*SHA256: //p' | tr -d ':' | tr 'A-F' 'a-f')
|
||||||
|
EXPECTED=$(printf '%s' "$OGS_RELEASE_CERT_SHA256" | tr -d ':' | tr 'A-F' 'a-f')
|
||||||
|
if [ -z "$EXPECTED" ]; then
|
||||||
|
echo "::error::Variable OGS_RELEASE_CERT_SHA256 is not set. Set it to $ACTUAL."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ "$ACTUAL" != "$EXPECTED" ]; then
|
||||||
|
echo "::error::Release keystore certificate is $ACTUAL, expected $EXPECTED."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Bump version in build.gradle.kts
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
BUMP_TYPE: ${{ inputs.bump_type }}
|
||||||
|
run: |
|
||||||
|
GRADLE_FILE="CollabTableAndroid/app/build.gradle"
|
||||||
|
|
||||||
|
CURRENT_CODE=$(grep -oP 'versionCode\s*=\s*\K[0-9]+' "$GRADLE_FILE")
|
||||||
|
CURRENT_NAME=$(grep -oP 'versionName\s*=\s*"\K[^"]+' "$GRADLE_FILE")
|
||||||
|
|
||||||
|
IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_NAME"
|
||||||
|
|
||||||
|
case "$BUMP_TYPE" in
|
||||||
|
major) MAJOR=$((MAJOR+1)); MINOR=0; PATCH=0 ;;
|
||||||
|
minor) MINOR=$((MINOR+1)); PATCH=0 ;;
|
||||||
|
patch) PATCH=$((PATCH+1)) ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
NEW_CODE=$((CURRENT_CODE+1))
|
||||||
|
NEW_NAME="${MAJOR}.${MINOR}.${PATCH}"
|
||||||
|
|
||||||
|
sed -i "s/versionCode = ${CURRENT_CODE}/versionCode = ${NEW_CODE}/" "$GRADLE_FILE"
|
||||||
|
sed -i "s/versionName = \"${CURRENT_NAME}\"/versionName = \"${NEW_NAME}\"/" "$GRADLE_FILE"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "new_code=${NEW_CODE}"
|
||||||
|
echo "new_name=${NEW_NAME}"
|
||||||
|
echo "tag=v${NEW_NAME}"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Commit version bump
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git add CollabTableAndroid/app/build.gradle
|
||||||
|
git commit -m "chore(android): bump version to ${{ steps.version.outputs.new_name }} (code ${{ steps.version.outputs.new_code }})"
|
||||||
|
git push
|
||||||
|
|
||||||
|
- name: Set up Gradle
|
||||||
|
uses: gradle/actions/setup-gradle@v3
|
||||||
|
|
||||||
|
- name: Install Android SDK
|
||||||
|
uses: android-actions/setup-android@v4
|
||||||
|
|
||||||
|
- name: Accept SDK licenses
|
||||||
|
shell: bash
|
||||||
|
run: yes | sdkmanager --licenses || true
|
||||||
|
|
||||||
|
# Install the compileSdk platform, build-tools 36.0.0 (used by AGP lint) and 37.0.0 (used by apksigner below).
|
||||||
|
- name: Install Android SDK packages
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
sdkmanager "platform-tools" "platforms;android-37.2" "build-tools;36.0.0" "build-tools;37.0.0"
|
||||||
|
|
||||||
|
- name: Run lint and ktlint
|
||||||
|
working-directory: CollabTableAndroid
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
chmod +x gradlew
|
||||||
|
./gradlew --no-daemon lintDebug ktlintCheck
|
||||||
|
|
||||||
|
- name: Build signed release APK
|
||||||
|
working-directory: CollabTableAndroid
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OGS_KEYSTORE_FILE: ${{ runner.temp }}/ogs-release.jks
|
||||||
|
OGS_KEYSTORE_PASSWORD: ${{ secrets.OGS_KEYSTORE_PASSWORD }}
|
||||||
|
OGS_KEY_ALIAS: ${{ secrets.OGS_KEY_ALIAS }}
|
||||||
|
OGS_KEY_PASSWORD: ${{ secrets.OGS_KEY_PASSWORD }}
|
||||||
|
run: ./gradlew --no-daemon assembleRelease
|
||||||
|
|
||||||
|
- name: Verify APK is signed with the release key
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
OGS_RELEASE_CERT_SHA256: ${{ vars.OGS_RELEASE_CERT_SHA256 }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
APK="CollabTableAndroid/app/build/outputs/apk/release/app-release.apk"
|
||||||
|
APKSIGNER="$ANDROID_HOME/build-tools/37.0.0/apksigner"
|
||||||
|
CERTS=$("$APKSIGNER" verify --print-certs "$APK")
|
||||||
|
ACTUAL=$(printf '%s\n' "$CERTS" | sed -n 's/^.*certificate SHA-256 digest: //p' | sed -n '1p')
|
||||||
|
EXPECTED=$(printf '%s' "$OGS_RELEASE_CERT_SHA256" | tr -d ':' | tr 'A-F' 'a-f')
|
||||||
|
if [ "$ACTUAL" != "$EXPECTED" ]; then
|
||||||
|
echo "::error::APK is signed with $ACTUAL, expected $EXPECTED."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Rename APK with version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
SRC="CollabTableAndroid/app/build/outputs/apk/release/app-release.apk"
|
||||||
|
cp "$SRC" "CollabTable-${{ steps.version.outputs.tag }}.apk"
|
||||||
|
|
||||||
|
- name: Generate changelog
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
CHANGELOG_INPUT: ${{ inputs.changelog }}
|
||||||
|
run: |
|
||||||
|
if [ -n "$CHANGELOG_INPUT" ]; then
|
||||||
|
printf '%s' "$CHANGELOG_INPUT" > release-notes.md
|
||||||
|
else
|
||||||
|
# Skip the static debug pre-releases, so the notes cover everything since the last public release.
|
||||||
|
LAST_TAG=$(git describe --tags --abbrev=0 --exclude '*-debug' 2>/dev/null || echo "")
|
||||||
|
if [ -n "$LAST_TAG" ]; then
|
||||||
|
RANGE="${LAST_TAG}..HEAD"
|
||||||
|
else
|
||||||
|
RANGE="HEAD"
|
||||||
|
fi
|
||||||
|
COMMITS=$(git log "$RANGE" --pretty=format:"%s" | grep -vE "^chore\(android\): (bump version|add static debug signing key)" || true)
|
||||||
|
FEATURES=$(echo "$COMMITS" | grep -E "^feat(\\(.+\\))?:" | sed 's/^feat[^:]*: /- /' || true)
|
||||||
|
FIXES=$(echo "$COMMITS" | grep -E "^fix(\\(.+\\))?:" | sed 's/^fix[^:]*: /- /' || true)
|
||||||
|
OTHERS=$(echo "$COMMITS" | grep -vE "^(feat|fix)(\\(.+\\))?:" | grep -v '^$' | sed 's/^/- /' || true)
|
||||||
|
{
|
||||||
|
if [ -n "$FEATURES" ]; then printf '### Features\n%s\n\n' "$FEATURES"; fi
|
||||||
|
if [ -n "$FIXES" ]; then printf '### Bug Fixes\n%s\n\n' "$FIXES"; fi
|
||||||
|
if [ -n "$OTHERS" ]; then printf '### Other Changes\n%s\n\n' "$OTHERS"; fi
|
||||||
|
} > release-notes.md
|
||||||
|
if [ ! -s release-notes.md ]; then echo 'No changes recorded.' > release-notes.md; fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Create GitHub release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ steps.version.outputs.tag }}
|
||||||
|
name: ${{ steps.version.outputs.tag }}
|
||||||
|
body_path: release-notes.md
|
||||||
|
files: CollabTable-${{ steps.version.outputs.tag }}.apk
|
||||||
|
fail_on_unmatched_files: true
|
||||||
|
|
||||||
|
- name: Remove release keystore
|
||||||
|
if: always()
|
||||||
|
shell: bash
|
||||||
|
run: rm -f "$RUNNER_TEMP/ogs-release.jks"
|
||||||
@@ -18,7 +18,6 @@ on:
|
|||||||
- '.github/workflows/lint.yml'
|
- '.github/workflows/lint.yml'
|
||||||
workflow_dispatch: {}
|
workflow_dispatch: {}
|
||||||
|
|
||||||
env:
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint:
|
lint:
|
||||||
@@ -38,13 +37,14 @@ jobs:
|
|||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '20'
|
node-version: '22'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
cache-dependency-path: frontend/package-lock.json
|
cache-dependency-path: frontend/package-lock.json
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
npm ci --prefix ../shared --ignore-scripts --no-audit --no-fund --omit=dev
|
npm ci --prefix ../shared --ignore-scripts --no-audit --no-fund
|
||||||
|
npm run build --prefix ../shared
|
||||||
npm ci
|
npm ci
|
||||||
|
|
||||||
- name: Run ESLint
|
- name: Run ESLint
|
||||||
|
|||||||
@@ -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 .
|
||||||
@@ -18,7 +18,6 @@ on:
|
|||||||
- '.github/workflows/tests.yml'
|
- '.github/workflows/tests.yml'
|
||||||
workflow_dispatch: {}
|
workflow_dispatch: {}
|
||||||
|
|
||||||
env:
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
backend:
|
backend:
|
||||||
@@ -38,7 +37,7 @@ jobs:
|
|||||||
POSTGRES_PASSWORD: postgres
|
POSTGRES_PASSWORD: postgres
|
||||||
POSTGRES_DB: collabtable_test
|
POSTGRES_DB: collabtable_test
|
||||||
ports:
|
ports:
|
||||||
- 5432:5432
|
- "15432:5432"
|
||||||
options: >-
|
options: >-
|
||||||
--health-cmd "pg_isready -U postgres"
|
--health-cmd "pg_isready -U postgres"
|
||||||
--health-interval 5s
|
--health-interval 5s
|
||||||
@@ -57,9 +56,14 @@ jobs:
|
|||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: go test ./...
|
shell: bash
|
||||||
env:
|
env:
|
||||||
TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/collabtable_test?sslmode=disable
|
TEST_DATABASE_URL: "postgres://postgres:postgres@localhost:15432/collabtable_test?sslmode=disable"
|
||||||
|
run: |
|
||||||
|
if [ "${GITEA_ACTIONS:-}" = "true" ]; then
|
||||||
|
export TEST_DATABASE_URL="postgres://postgres:postgres@postgres:5432/collabtable_test?sslmode=disable"
|
||||||
|
fi
|
||||||
|
go test ./...
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
name: Dashboard checks
|
name: Dashboard checks
|
||||||
@@ -84,7 +88,8 @@ jobs:
|
|||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
npm install --prefix ../shared/packages/web-ui --no-package-lock --ignore-scripts --no-audit --no-fund --omit=dev
|
npm ci --prefix ../shared --ignore-scripts --no-audit --no-fund
|
||||||
|
npm run build --prefix ../shared
|
||||||
npm ci
|
npm ci
|
||||||
|
|
||||||
- name: Check dashboard
|
- name: Check dashboard
|
||||||
|
|||||||
@@ -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,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
|
||||||
@@ -1,23 +1,27 @@
|
|||||||
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id 'com.android.application'
|
id 'com.android.application'
|
||||||
id 'org.jetbrains.kotlin.android'
|
|
||||||
id 'org.jetbrains.kotlin.plugin.compose'
|
id 'org.jetbrains.kotlin.plugin.compose'
|
||||||
// KSP not available for Kotlin 2.2.21 yet; switch to kapt for Room annotation processing
|
id 'com.google.devtools.ksp'
|
||||||
id 'org.jetbrains.kotlin.kapt'
|
|
||||||
id 'org.jlleitschuh.gradle.ktlint'
|
id 'org.jlleitschuh.gradle.ktlint'
|
||||||
id 'io.gitlab.arturbosch.detekt'
|
id 'io.gitlab.arturbosch.detekt'
|
||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = 'com.collabtable.app'
|
namespace = 'com.collabtable.app'
|
||||||
compileSdk = 34
|
compileSdk {
|
||||||
|
version = release(37) {
|
||||||
|
minorApiLevel = 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "com.collabtable.app"
|
applicationId = "com.collabtable.app"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 34
|
targetSdk = 37
|
||||||
versionCode 1
|
versionCode = 1
|
||||||
versionName "1.0"
|
versionName = "1.0"
|
||||||
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
vectorDrawables {
|
vectorDrawables {
|
||||||
@@ -25,19 +29,34 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Release signing: CI supplies the keystore and its passwords from repository secrets, so every
|
||||||
|
// published APK carries the same certificate and installs can update in place. Without
|
||||||
|
// OGS_KEYSTORE_FILE, release builds stay unsigned, which keeps local builds working.
|
||||||
|
def releaseKeystoreFile = System.getenv('OGS_KEYSTORE_FILE')
|
||||||
|
signingConfigs {
|
||||||
|
release {
|
||||||
|
if (releaseKeystoreFile != null) {
|
||||||
|
storeFile file(releaseKeystoreFile)
|
||||||
|
storePassword System.getenv('OGS_KEYSTORE_PASSWORD')
|
||||||
|
keyAlias System.getenv('OGS_KEY_ALIAS')
|
||||||
|
keyPassword System.getenv('OGS_KEY_PASSWORD')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
release {
|
release {
|
||||||
minifyEnabled false
|
minifyEnabled false
|
||||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||||
|
if (releaseKeystoreFile != null) {
|
||||||
|
signingConfig signingConfigs.release
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility JavaVersion.VERSION_21
|
sourceCompatibility JavaVersion.VERSION_21
|
||||||
targetCompatibility JavaVersion.VERSION_21
|
targetCompatibility JavaVersion.VERSION_21
|
||||||
}
|
}
|
||||||
kotlinOptions {
|
|
||||||
jvmTarget = '21'
|
|
||||||
}
|
|
||||||
buildFeatures {
|
buildFeatures {
|
||||||
compose = true
|
compose = true
|
||||||
buildConfig = true
|
buildConfig = true
|
||||||
@@ -49,6 +68,12 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
compilerOptions {
|
||||||
|
jvmTarget.set(JvmTarget.JVM_21)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
// Core Android
|
// Core Android
|
||||||
implementation 'androidx.core:core-ktx:1.12.0'
|
implementation 'androidx.core:core-ktx:1.12.0'
|
||||||
@@ -69,16 +94,15 @@ dependencies {
|
|||||||
// ViewModel
|
// ViewModel
|
||||||
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2'
|
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2'
|
||||||
|
|
||||||
// Room (use kapt for annotation processing). Bump to version compatible with Kotlin 2.2 metadata
|
// Room (KSP for annotation processing)
|
||||||
implementation 'androidx.room:room-runtime:2.7.0'
|
implementation 'androidx.room:room-runtime:2.7.0'
|
||||||
implementation 'androidx.room:room-ktx:2.7.0'
|
implementation 'androidx.room:room-ktx:2.7.0'
|
||||||
kapt 'androidx.room:room-compiler:2.7.0'
|
ksp 'androidx.room:room-compiler:2.7.0'
|
||||||
|
|
||||||
// Retrofit
|
// Retrofit
|
||||||
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
|
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
|
||||||
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
|
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
|
||||||
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
|
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
|
||||||
kapt 'com.squareup.retrofit2:retrofit:2.9.0'
|
|
||||||
|
|
||||||
// Coroutines
|
// Coroutines
|
||||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import retrofit2.http.Query
|
|||||||
|
|
||||||
data class SyncRequest(
|
data class SyncRequest(
|
||||||
val lastSyncTimestamp: Long,
|
val lastSyncTimestamp: Long,
|
||||||
|
val lastSyncToken: Long,
|
||||||
val lists: List<CollabList>,
|
val lists: List<CollabList>,
|
||||||
val fields: List<Field>,
|
val fields: List<Field>,
|
||||||
val items: List<Item>,
|
val items: List<Item>,
|
||||||
@@ -24,6 +25,9 @@ data class SyncResponse(
|
|||||||
val items: List<Item>,
|
val items: List<Item>,
|
||||||
val itemValues: List<ItemValue>,
|
val itemValues: List<ItemValue>,
|
||||||
val serverTimestamp: Long,
|
val serverTimestamp: Long,
|
||||||
|
val serverChangeToken: Long,
|
||||||
|
val nextSyncToken: Long,
|
||||||
|
val hasMore: Boolean,
|
||||||
)
|
)
|
||||||
|
|
||||||
interface CollabTableApi {
|
interface CollabTableApi {
|
||||||
|
|||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package com.collabtable.app.data.repository
|
||||||
|
|
||||||
|
import com.collabtable.app.data.api.SyncResponse
|
||||||
|
|
||||||
|
internal data class SyncPageProgress(
|
||||||
|
val cursor: Long,
|
||||||
|
val firstPage: Boolean = true,
|
||||||
|
) {
|
||||||
|
fun after(response: SyncResponse): SyncPageProgress? {
|
||||||
|
if (response.hasMore && response.nextSyncToken <= cursor) {
|
||||||
|
throw IllegalStateException("Sync page cursor did not advance")
|
||||||
|
}
|
||||||
|
return if (response.hasMore) SyncPageProgress(response.nextSyncToken, firstPage = false) else null
|
||||||
|
}
|
||||||
|
}
|
||||||
+144
-126
@@ -52,6 +52,12 @@ class SyncRepository(
|
|||||||
return prefs.getLong("last_server_sync_ts", 0)
|
return prefs.getLong("last_server_sync_ts", 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun getLastServerSyncToken(): Long = prefs.getLong("last_server_sync_token", 0)
|
||||||
|
|
||||||
|
private fun setLastServerSyncToken(token: Long) {
|
||||||
|
prefs.edit().putLong("last_server_sync_token", token).apply()
|
||||||
|
}
|
||||||
|
|
||||||
private fun setLastServerSyncTs(ts: Long) {
|
private fun setLastServerSyncTs(ts: Long) {
|
||||||
prefs
|
prefs
|
||||||
.edit()
|
.edit()
|
||||||
@@ -101,30 +107,29 @@ class SyncRepository(
|
|||||||
return@withContext Result.success(Unit)
|
return@withContext Result.success(Unit)
|
||||||
}
|
}
|
||||||
val lastServerTs = getLastServerSyncTs()
|
val lastServerTs = getLastServerSyncTs()
|
||||||
|
val lastServerToken = getLastServerSyncToken()
|
||||||
val lastLocalTs = getLastLocalSyncTs()
|
val lastLocalTs = getLastLocalSyncTs()
|
||||||
// Capture a snapshot timestamp BEFORE reading local changes to avoid missing
|
// Capture a snapshot timestamp BEFORE reading local changes to avoid missing
|
||||||
// updates that happen during an in-flight sync. We'll advance the local watermark
|
// updates that happen during an in-flight sync. We'll advance the local watermark
|
||||||
// to this snapshot once the sync completes successfully.
|
// to this snapshot once the sync completes successfully.
|
||||||
val localSnapshotTs = System.currentTimeMillis()
|
val localSnapshotTs = System.currentTimeMillis()
|
||||||
val isInitialSync = lastServerTs == 0L
|
// If our local DB appears empty or this install still has the legacy timestamp cursor,
|
||||||
|
// request a full down-sync through the server change-token cursor.
|
||||||
|
val hasAnyLists = database.listDao().getAllListIds().isNotEmpty()
|
||||||
|
val hasAnyItems = database.itemDao().getAllItemIds().isNotEmpty()
|
||||||
|
val effectiveLastServerToken =
|
||||||
|
when {
|
||||||
|
// App start can request a full down-sync regardless of local contents
|
||||||
|
forceFullDown && (lastServerTs > 0L || lastServerToken > 0L) -> 0L
|
||||||
|
// Fallback: if local has no lists or items but we have a watermark, do a full down-sync
|
||||||
|
(lastServerTs > 0L || lastServerToken > 0L) && (!hasAnyLists && !hasAnyItems) -> 0L
|
||||||
|
else -> lastServerToken
|
||||||
|
}
|
||||||
|
val isInitialSync = effectiveLastServerToken == 0L
|
||||||
if (isInitialSync) {
|
if (isInitialSync) {
|
||||||
Logger.i("Sync", "[SYNC] Starting initial sync with server")
|
Logger.i("Sync", "[SYNC] Starting initial sync with server")
|
||||||
}
|
}
|
||||||
|
if (effectiveLastServerToken == 0L && (lastServerTs > 0L || lastServerToken > 0L)) {
|
||||||
// If our local DB appears empty but we have a nonzero server watermark (e.g., after reinstall
|
|
||||||
// or clearing local data), request a one-time full down-sync by resetting the effective
|
|
||||||
// lastSyncTimestamp to 0 for this request. This avoids permanently missing historical rows.
|
|
||||||
val hasAnyLists = database.listDao().getAllListIds().isNotEmpty()
|
|
||||||
val hasAnyItems = database.itemDao().getAllItemIds().isNotEmpty()
|
|
||||||
val effectiveLastServerTs =
|
|
||||||
when {
|
|
||||||
// App start can request a full down-sync regardless of local contents
|
|
||||||
forceFullDown && lastServerTs > 0L -> 0L
|
|
||||||
// Fallback: if local looks empty but we have a watermark, do a one-time full down-sync
|
|
||||||
lastServerTs > 0L && (!hasAnyLists || !hasAnyItems) -> 0L
|
|
||||||
else -> lastServerTs
|
|
||||||
}
|
|
||||||
if (effectiveLastServerTs == 0L && lastServerTs > 0L) {
|
|
||||||
val reason = if (forceFullDown) "startup forced" else "local empty"
|
val reason = if (forceFullDown) "startup forced" else "local empty"
|
||||||
Logger.w("Sync", "$reason full down-sync requested")
|
Logger.w("Sync", "$reason full down-sync requested")
|
||||||
}
|
}
|
||||||
@@ -162,125 +167,137 @@ class SyncRepository(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send to server and get updates
|
// Upload local changes once, then follow the server's bounded pages without
|
||||||
val syncRequest =
|
// replaying the same writes on every request.
|
||||||
SyncRequest(
|
var cursor = effectiveLastServerToken
|
||||||
lastSyncTimestamp = effectiveLastServerTs,
|
var pageProgress = SyncPageProgress(cursor)
|
||||||
lists = localLists,
|
var serverTimestamp = lastServerTs
|
||||||
fields = localFields,
|
while (true) {
|
||||||
items = localItems,
|
val response =
|
||||||
itemValues = localValues,
|
try {
|
||||||
)
|
api.sync(
|
||||||
|
SyncRequest(
|
||||||
// HTTP-only sync
|
lastSyncTimestamp = lastServerTs,
|
||||||
val response =
|
lastSyncToken = pageProgress.cursor,
|
||||||
try {
|
lists = if (pageProgress.firstPage) localLists else emptyList(),
|
||||||
api.sync(syncRequest)
|
fields = if (pageProgress.firstPage) localFields else emptyList(),
|
||||||
} catch (e: UnknownHostException) {
|
items = if (pageProgress.firstPage) localItems else emptyList(),
|
||||||
// Host could not be resolved; apply exponential backoff and surface a warning once.
|
itemValues = if (pageProgress.firstPage) localValues else emptyList(),
|
||||||
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
),
|
||||||
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
)
|
||||||
Logger.w("Sync", "Network host unresolved (DNS). Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
} catch (e: UnknownHostException) {
|
||||||
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
|
|
||||||
} catch (e: Exception) {
|
|
||||||
if (e.message?.contains("Unable to resolve host", ignoreCase = true) == true) {
|
|
||||||
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
||||||
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
||||||
Logger.w("Sync", "DNS failure. Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
Logger.w("Sync", "Network host unresolved (DNS). Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
||||||
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
|
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
|
||||||
}
|
} catch (e: Exception) {
|
||||||
throw e
|
if (e.message?.contains("Unable to resolve host", ignoreCase = true) == true) {
|
||||||
}
|
networkBackoffMs = if (networkBackoffMs == 0L) 5_000L else (networkBackoffMs * 2).coerceAtMost(180_000L)
|
||||||
if (!response.isSuccessful) {
|
networkBackoffUntil = System.currentTimeMillis() + networkBackoffMs
|
||||||
if (response.code() == 401) {
|
Logger.w("Sync", "DNS failure. Backing off for ${networkBackoffMs / 1000}s: ${e.message}")
|
||||||
// Unauthorized: likely bad/missing API token. Reset sync baseline and surface a clear error.
|
return@withContext Result.failure(Exception("Network unreachable: unable to resolve host"))
|
||||||
setLastServerSyncTs(0)
|
|
||||||
setLastLocalSyncTs(0)
|
|
||||||
// Apply exponential backoff on repeated auth failures
|
|
||||||
authBackoffMs = if (authBackoffMs == 0L) 2_000L else (authBackoffMs * 2).coerceAtMost(300_000L)
|
|
||||||
authBackoffUntil = System.currentTimeMillis() + authBackoffMs
|
|
||||||
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server API token."))
|
|
||||||
}
|
|
||||||
return@withContext Result.failure(Exception("Sync failed: ${response.code()}"))
|
|
||||||
}
|
|
||||||
val syncResponse = response.body()!!
|
|
||||||
// Only log receive when there are actual server changes
|
|
||||||
val inTotal =
|
|
||||||
syncResponse.lists.size +
|
|
||||||
syncResponse.fields.size +
|
|
||||||
syncResponse.items.size +
|
|
||||||
syncResponse.itemValues.size
|
|
||||||
if (inTotal > 0) {
|
|
||||||
Logger.i(
|
|
||||||
"Sync",
|
|
||||||
"[IN] Received changes " +
|
|
||||||
"(lists=${syncResponse.lists.size}, fields=${syncResponse.fields.size}, " +
|
|
||||||
"items=${syncResponse.items.size}, values=${syncResponse.itemValues.size})",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Apply server changes to local database atomically in correct order
|
|
||||||
database.withTransaction {
|
|
||||||
// 1) Upsert lists first, preserving local orderIndex when present
|
|
||||||
val localIdToOrder = database.listDao().getListIdsAndOrder().associate { it.id to it.orderIndex }
|
|
||||||
// Build a map of local updatedAt to avoid overwriting newer local changes with older server data
|
|
||||||
val localUpdatedMap = database.listDao().getListsUpdatedSince(0).associateBy({ it.id }, { it.updatedAt })
|
|
||||||
|
|
||||||
val listsPreservingOrder =
|
|
||||||
syncResponse.lists
|
|
||||||
.filter { incoming ->
|
|
||||||
val localUpdated = localUpdatedMap[incoming.id]
|
|
||||||
localUpdated == null || incoming.updatedAt >= localUpdated
|
|
||||||
}.map { incoming ->
|
|
||||||
val localOrder = localIdToOrder[incoming.id]
|
|
||||||
if (localOrder != null) incoming.copy(orderIndex = localOrder) else incoming
|
|
||||||
}
|
}
|
||||||
|
throw e
|
||||||
if (listsPreservingOrder.isNotEmpty()) {
|
|
||||||
database.listDao().insertLists(listsPreservingOrder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build set of existing list ids to guard child inserts
|
|
||||||
val existingListIds = database.listDao().getAllListIds().toSet()
|
|
||||||
|
|
||||||
// 2) Filter and upsert fields whose parent list exists
|
|
||||||
val filteredFields = syncResponse.fields.filter { f -> f.listId in existingListIds }
|
|
||||||
if (filteredFields.size != syncResponse.fields.size) {
|
|
||||||
val dropped = syncResponse.fields.size - filteredFields.size
|
|
||||||
Logger.w("Sync", "Dropping $dropped field(s) with missing parent list to avoid FK errors")
|
|
||||||
}
|
|
||||||
if (filteredFields.isNotEmpty()) {
|
|
||||||
database.fieldDao().insertFields(filteredFields)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3) Filter and upsert items whose parent list exists
|
|
||||||
val filteredItems = syncResponse.items.filter { i -> i.listId in existingListIds }
|
|
||||||
if (filteredItems.size != syncResponse.items.size) {
|
|
||||||
val dropped = syncResponse.items.size - filteredItems.size
|
|
||||||
Logger.w("Sync", "Dropping $dropped item(s) with missing parent list to avoid FK errors")
|
|
||||||
}
|
|
||||||
if (filteredItems.isNotEmpty()) {
|
|
||||||
database.itemDao().insertItems(filteredItems)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4) Filter item values to only those whose parents (item and field) exist locally
|
|
||||||
val existingItemIds = database.itemDao().getAllItemIds().toSet()
|
|
||||||
val existingFieldIds = database.fieldDao().getAllFieldIds().toSet()
|
|
||||||
val filteredValues =
|
|
||||||
syncResponse.itemValues.filter { v ->
|
|
||||||
v.itemId in existingItemIds && v.fieldId in existingFieldIds
|
|
||||||
}
|
}
|
||||||
if (filteredValues.size != syncResponse.itemValues.size) {
|
if (!response.isSuccessful) {
|
||||||
val dropped = syncResponse.itemValues.size - filteredValues.size
|
if (response.code() == 401) {
|
||||||
Logger.w("Sync", "Dropping $dropped item value(s) with missing parents to avoid FK errors")
|
setLastServerSyncTs(0)
|
||||||
|
setLastServerSyncToken(0)
|
||||||
|
setLastLocalSyncTs(0)
|
||||||
|
authBackoffMs = if (authBackoffMs == 0L) 2_000L else (authBackoffMs * 2).coerceAtMost(300_000L)
|
||||||
|
authBackoffUntil = System.currentTimeMillis() + authBackoffMs
|
||||||
|
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server API token."))
|
||||||
|
}
|
||||||
|
return@withContext Result.failure(Exception("Sync failed: ${response.code()}"))
|
||||||
}
|
}
|
||||||
if (filteredValues.isNotEmpty()) {
|
val syncResponse = response.body() ?: return@withContext Result.failure(Exception("Sync response was empty"))
|
||||||
database.itemValueDao().insertValues(filteredValues)
|
val inTotal =
|
||||||
|
syncResponse.lists.size +
|
||||||
|
syncResponse.fields.size +
|
||||||
|
syncResponse.items.size +
|
||||||
|
syncResponse.itemValues.size
|
||||||
|
if (inTotal > 0) {
|
||||||
|
Logger.i(
|
||||||
|
"Sync",
|
||||||
|
"[IN] Received changes " +
|
||||||
|
"(lists=${syncResponse.lists.size}, fields=${syncResponse.fields.size}, " +
|
||||||
|
"items=${syncResponse.items.size}, values=${syncResponse.itemValues.size})",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
database.withTransaction {
|
||||||
|
// 1) Upsert lists first, preserving local orderIndex when present
|
||||||
|
val localIdToOrder = database.listDao().getListIdsAndOrder().associate { it.id to it.orderIndex }
|
||||||
|
// Build a map of local updatedAt to avoid overwriting newer local changes with older server data
|
||||||
|
val localUpdatedMap =
|
||||||
|
database.listDao().getListsUpdatedSince(0).associateBy({ it.id }, { it.updatedAt })
|
||||||
|
|
||||||
|
val listsPreservingOrder =
|
||||||
|
syncResponse.lists
|
||||||
|
.filter { incoming ->
|
||||||
|
val localUpdated = localUpdatedMap[incoming.id]
|
||||||
|
localUpdated == null || incoming.updatedAt >= localUpdated
|
||||||
|
}.map { incoming ->
|
||||||
|
val localOrder = localIdToOrder[incoming.id]
|
||||||
|
if (localOrder != null) incoming.copy(orderIndex = localOrder) else incoming
|
||||||
|
}
|
||||||
|
|
||||||
|
if (listsPreservingOrder.isNotEmpty()) {
|
||||||
|
database.listDao().insertLists(listsPreservingOrder)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build set of existing list ids to guard child inserts
|
||||||
|
val existingListIds = database.listDao().getAllListIds().toSet()
|
||||||
|
|
||||||
|
// 2) Filter and upsert fields whose parent list exists
|
||||||
|
val filteredFields = syncResponse.fields.filter { f -> f.listId in existingListIds }
|
||||||
|
if (filteredFields.size != syncResponse.fields.size) {
|
||||||
|
val dropped = syncResponse.fields.size - filteredFields.size
|
||||||
|
Logger.w("Sync", "Dropping $dropped field(s) with missing parent list to avoid FK errors")
|
||||||
|
}
|
||||||
|
if (filteredFields.isNotEmpty()) {
|
||||||
|
database.fieldDao().insertFields(filteredFields)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) Filter and upsert items whose parent list exists
|
||||||
|
val filteredItems = syncResponse.items.filter { i -> i.listId in existingListIds }
|
||||||
|
if (filteredItems.size != syncResponse.items.size) {
|
||||||
|
val dropped = syncResponse.items.size - filteredItems.size
|
||||||
|
Logger.w("Sync", "Dropping $dropped item(s) with missing parent list to avoid FK errors")
|
||||||
|
}
|
||||||
|
if (filteredItems.isNotEmpty()) {
|
||||||
|
database.itemDao().insertItems(filteredItems)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4) Filter item values to only those whose parents (item and field) exist locally
|
||||||
|
val existingItemIds = database.itemDao().getAllItemIds().toSet()
|
||||||
|
val existingFieldIds = database.fieldDao().getAllFieldIds().toSet()
|
||||||
|
val filteredValues =
|
||||||
|
syncResponse.itemValues.filter { v ->
|
||||||
|
v.itemId in existingItemIds && v.fieldId in existingFieldIds
|
||||||
|
}
|
||||||
|
if (filteredValues.size != syncResponse.itemValues.size) {
|
||||||
|
val dropped = syncResponse.itemValues.size - filteredValues.size
|
||||||
|
Logger.w("Sync", "Dropping $dropped item value(s) with missing parents to avoid FK errors")
|
||||||
|
}
|
||||||
|
if (filteredValues.isNotEmpty()) {
|
||||||
|
database.itemValueDao().insertValues(filteredValues)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val nextPage = try {
|
||||||
|
pageProgress.after(syncResponse)
|
||||||
|
} catch (e: IllegalStateException) {
|
||||||
|
return@withContext Result.failure(e)
|
||||||
|
}
|
||||||
|
cursor = syncResponse.nextSyncToken
|
||||||
|
serverTimestamp = syncResponse.serverTimestamp
|
||||||
|
if (nextPage == null) break
|
||||||
|
pageProgress = nextPage
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update watermarks: server ts from response, local ts from device clock now
|
// Save the server-owned change cursor only after every page has been applied.
|
||||||
setLastServerSyncTs(syncResponse.serverTimestamp)
|
setLastServerSyncToken(cursor)
|
||||||
|
setLastServerSyncTs(serverTimestamp)
|
||||||
// Advance local watermark to the snapshot taken before reading local changes.
|
// Advance local watermark to the snapshot taken before reading local changes.
|
||||||
// This avoids missing updates that occurred while the sync was in-flight.
|
// This avoids missing updates that occurred while the sync was in-flight.
|
||||||
setLastLocalSyncTs(localSnapshotTs)
|
setLastLocalSyncTs(localSnapshotTs)
|
||||||
@@ -298,6 +315,7 @@ class SyncRepository(
|
|||||||
// If WS indicated unauthorized, align behavior with HTTP path
|
// If WS indicated unauthorized, align behavior with HTTP path
|
||||||
if (e.message?.contains("Unauthorized") == true) {
|
if (e.message?.contains("Unauthorized") == true) {
|
||||||
setLastServerSyncTs(0)
|
setLastServerSyncTs(0)
|
||||||
|
setLastServerSyncToken(0)
|
||||||
setLastLocalSyncTs(0)
|
setLastLocalSyncTs(0)
|
||||||
}
|
}
|
||||||
// Do not reset network backoff here; it's managed where thrown.
|
// Do not reset network backoff here; it's managed where thrown.
|
||||||
|
|||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
package com.collabtable.app.data.repository
|
||||||
|
|
||||||
|
import com.collabtable.app.data.api.SyncResponse
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SyncPageProgressTest {
|
||||||
|
@Test
|
||||||
|
fun `first page advances and marks later pages as download only`() {
|
||||||
|
val first = SyncPageProgress(cursor = 4)
|
||||||
|
|
||||||
|
assertTrue(first.firstPage)
|
||||||
|
val second = first.after(response(nextToken = 9, hasMore = true))
|
||||||
|
|
||||||
|
assertEquals(9, second?.cursor)
|
||||||
|
assertFalse(second?.firstPage ?: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `final page ends the loop`() {
|
||||||
|
val progress = SyncPageProgress(cursor = 9, firstPage = false)
|
||||||
|
|
||||||
|
assertNull(progress.after(response(nextToken = 12, hasMore = false)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `non advancing page is rejected`() {
|
||||||
|
val progress = SyncPageProgress(cursor = 9)
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException::class.java) {
|
||||||
|
progress.after(response(nextToken = 9, hasMore = true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun response(nextToken: Long, hasMore: Boolean) =
|
||||||
|
SyncResponse(
|
||||||
|
lists = emptyList(),
|
||||||
|
fields = emptyList(),
|
||||||
|
items = emptyList(),
|
||||||
|
itemValues = emptyList(),
|
||||||
|
serverTimestamp = 0,
|
||||||
|
serverChangeToken = nextToken,
|
||||||
|
nextSyncToken = nextToken,
|
||||||
|
hasMore = hasMore,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||||
plugins {
|
plugins {
|
||||||
id 'com.android.application' version '8.8.0' apply false
|
id 'com.android.application' version '9.5.0' apply false
|
||||||
id 'com.android.library' version '8.8.0' apply false
|
id 'com.android.library' version '9.5.0' apply false
|
||||||
id 'org.jetbrains.kotlin.android' version '2.2.21' apply false
|
id 'org.jetbrains.kotlin.plugin.compose' version '2.3.20' apply false
|
||||||
id 'org.jetbrains.kotlin.plugin.compose' version '2.2.21' apply false
|
id 'com.google.devtools.ksp' version '2.3.13' apply false
|
||||||
id 'org.jlleitschuh.gradle.ktlint' version '14.0.1' apply false
|
id 'org.jlleitschuh.gradle.ktlint' version '14.0.1' apply false
|
||||||
id 'io.gitlab.arturbosch.detekt' version '1.23.8' apply false
|
id 'io.gitlab.arturbosch.detekt' version '1.23.8' apply false
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
|
||||||
networkTimeout=10000
|
networkTimeout=10000
|
||||||
validateDistributionUrl=true
|
validateDistributionUrl=true
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
|||||||
+252
@@ -0,0 +1,252 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||||
|
' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
org.gradle.wrapper.GradleWrapperMain \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
+11
-11
@@ -4,10 +4,10 @@
|
|||||||
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
||||||
- **Analyzed:** 2026-10-16
|
- **Analyzed:** 2026-10-16
|
||||||
- **Commit:** 6aec03f on main
|
- **Commit:** 6aec03f on main
|
||||||
- **Working tree:** clean (no uncommitted changes, no untracked files)
|
- **Working tree:** contains uncommitted changes from the earlier and current medium passes.
|
||||||
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, TanStack Query) embedded in the Go binary; Android client (Kotlin, Room, Retrofit) with offline sync; Docker multi-stage image on `scratch`; GitHub Actions.
|
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, TanStack Query) embedded in the Go binary; Android client (Kotlin, Room, Retrofit) with offline sync; Docker multi-stage image on `scratch`; GitHub Actions.
|
||||||
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). A second Medium pass re-checked P-004, which stays open for a pagination contract decision.
|
- **Updated:** 2026-10-20 — P-004 now uses bounded keyset pages for collection endpoints and sync; Android follows all sync pages. Database-backed behavior remains unverified locally because no test database is available.
|
||||||
- **Scope:** Read all first-party backend code (`backend/*.go`, including tests), `docker/Dockerfile`, `.dockerignore`, `.github/workflows/*`, the frontend data layer, list components, routes and Vite config, the Android API client, preferences and sync repository, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, lock files (read for versions only), build output, and the rest of `shared/` (node, python and java packages, which CollabTable does not use). Tracked SQLite files were inspected read-only from a copy (schema and row counts only). No tests, builds or linters were run; the analysis is static.
|
- **Scope:** Read all first-party backend code (`backend/*.go`, including tests), `docker/Dockerfile`, `.dockerignore`, `.github/workflows/*`, the frontend data layer, list components, routes and Vite config, the Android API client, preferences and sync repository, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, lock files (read for versions only), build output, and the rest of `shared/` (node, python and java packages, which CollabTable does not use). Tracked SQLite files were inspected read-only from a copy (schema and row counts only). Verification limits are recorded in `QUALITY_REPORT.md`.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -15,11 +15,11 @@
|
|||||||
|---|---:|---:|---:|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 0 | 0 | 0 | 0 |
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
| High | 2 | 1 | 0 | 1 |
|
| High | 2 | 1 | 0 | 1 |
|
||||||
| Medium | 5 | 4 | 0 | 1 |
|
| Medium | 5 | 5 | 0 | 0 |
|
||||||
| Low | 3 | 0 | 0 | 3 |
|
| Low | 3 | 0 | 0 | 3 |
|
||||||
| Info | 1 | 0 | 0 | 1 |
|
| Info | 1 | 0 | 0 | 1 |
|
||||||
|
|
||||||
Two structural costs dominate: the dashboard re-downloads the full database every 5 seconds, and sync writes row by row with several round trips per value inside one long transaction. Missing indexes and pagination will make both worse as data grows.
|
The dashboard still sends the full dataset after a change, and sync writes rows one at a time inside one transaction. Collection endpoints and sync are now paged, while the updated-at indexes are present. Database runtime and load behavior still need verification on PostgreSQL.
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
@@ -44,12 +44,12 @@ Two structural costs dominate: the dashboard re-downloads the full database ever
|
|||||||
- **Recommendation:** Add `CREATE INDEX IF NOT EXISTS` on `updatedat` for `lists`, `items`, `fields` and `item_values` in `initSchema`. Consider `(isdeleted, updatedat)` if soft-delete filtering is common in the same queries.
|
- **Recommendation:** Add `CREATE INDEX IF NOT EXISTS` on `updatedat` for `lists`, `items`, `fields` and `item_values` in `initSchema`. Consider `(isdeleted, updatedat)` if soft-delete filtering is common in the same queries.
|
||||||
- **Status:** Fixed 2026-10-19 — `initSchema` creates indexes on `updatedat` for lists, fields, items and item values, so delta queries stop scanning whole tables. The index builds run at startup and briefly block writes on large tables. Files: backend/db.go.
|
- **Status:** Fixed 2026-10-19 — `initSchema` creates indexes on `updatedat` for lists, fields, items and item values, so delta queries stop scanning whole tables. The index builds run at startup and briefly block writes on large tables. Files: backend/db.go.
|
||||||
|
|
||||||
### P-004 · No pagination on list endpoints or the sync response; the first sync returns everything · **Medium** · Open
|
### P-004 · No pagination on list endpoints or the sync response; the first sync returns everything · **Medium** · Fixed
|
||||||
- **Location:** `backend/data.go:68-204` (`queryLists`, `queryFields`, `queryItems`, `queryValues`, none with LIMIT), `backend/data.go:228-235` (`GET /api/lists`), `backend/sync.go:216-248` (`since` is nil when `lastSync == 0`, so the full table is returned).
|
- **Location:** `backend/pagination.go` (bounded keyset pages); `backend/data.go` collection handlers; `backend/sync.go:326-405` (bounded sync response); `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt` (client page loop).
|
||||||
- **Description:** Collection endpoints return unbounded arrays. The first sync from any device (`lastSync == 0`) returns every list, field, item and value in the database in one response.
|
- **Description:** Collection endpoints now return pages of at most 500 rows (default 200), with opaque keyset cursors and `hasMore`. Sync returns at most 500 changes with a server token cursor; Android requests all pages before saving the cursor.
|
||||||
- **Impact:** Response size and server memory grow linearly with total data. Large first syncs risk the 60-second write timeout and slow mobile clients.
|
- **Impact:** Response size and server memory grow linearly with total data. Large first syncs risk the 60-second write timeout and slow mobile clients.
|
||||||
- **Recommendation:** Add keyset pagination (a `(updatedat, id)` cursor and a `limit` parameter) to the collection endpoints. For sync, return a `hasMore` flag and a cursor, and let the client loop until it is caught up.
|
- **Recommendation:** Add keyset pagination (a `(updatedat, id)` cursor and a `limit` parameter) to the collection endpoints. For sync, return a `hasMore` flag and a cursor, and let the client loop until it is caught up.
|
||||||
- **Status:** Open 2026-10-19 — Re-checked, unchanged: the collection queries have no LIMIT and `lastSync == 0` still returns every row. Decision needed: the pagination contract (`hasMore` plus a cursor, or keyset on `(updatedat, id)`), the default page size, and the rollout order. CollabTableAndroid has to loop until caught up before the server may page, or existing clients would silently get a truncated sync.
|
- **Status:** Fixed 2026-10-20 — Collection queries use keyset cursors with a default page of 200 and maximum of 500; sync responses are capped at 500 and include `hasMore` and `nextSyncToken`. Android uploads local changes on the first request, then loops through server pages and stores the final cursor only after completion. Collection GET responses now wrap `items`, `nextCursor` and `hasMore` instead of returning bare arrays. Old sync clients that omit `lastSyncToken` receive 400 and must be upgraded with the backend. PostgreSQL runtime tests are written but skipped locally; see `QUALITY_REPORT.md` Verification. Files: `backend/pagination.go`, `backend/data.go`, `backend/sync.go`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt`.
|
||||||
|
|
||||||
### P-005 · Frontend scans full arrays for every row, card and cell on each poll · **Medium** · Fixed
|
### P-005 · Frontend scans full arrays for every row, card and cell on each poll · **Medium** · Fixed
|
||||||
- **Location:** `frontend/src/routes/lists/[id]/+page.svelte:94` (`itemValuesFor(overview.values, item.id)` runs once per visible row and scans every value in the database) and `:98` (`valueFor` per cell); `frontend/src/lib/components/lists/ListCard.svelte:7-8` (each card filters all fields and all items); `frontend/src/lib/features/lists/listHelpers.js:1-15` (linear `filter` and `find` with no index).
|
- **Location:** `frontend/src/routes/lists/[id]/+page.svelte:94` (`itemValuesFor(overview.values, item.id)` runs once per visible row and scans every value in the database) and `:98` (`valueFor` per cell); `frontend/src/lib/components/lists/ListCard.svelte:7-8` (each card filters all fields and all items); `frontend/src/lib/features/lists/listHelpers.js:1-15` (linear `filter` and `find` with no index).
|
||||||
@@ -97,8 +97,8 @@ Two structural costs dominate: the dashboard re-downloads the full database ever
|
|||||||
- **Recommendation:** None.
|
- **Recommendation:** None.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- Static analysis only. No tests, builds, Docker builds, lint runs or load tests were executed. Estimates come from code reading and should be confirmed with a benchmark on realistic data (for example a few thousand items across several devices).
|
- Go and frontend verification results are in `QUALITY_REPORT.md`. No load test ran. Estimates should be confirmed with realistic data across several devices.
|
||||||
- AuthGuard's own performance is outside this repository and was not analyzed.
|
- AuthGuard's own performance is outside this repository and was not analyzed.
|
||||||
- `shared/` was reviewed selectively: the parts CollabTable imports (`backend/auth`, `authclient`, `authproxy`, `coreconfig`, `postgres`, and the `carriernodeclient` construction). The shared web-ui was searched with grep only. The node, python and java packages were not reviewed.
|
- `shared/` was reviewed selectively: the parts CollabTable imports (`backend/auth`, `authclient`, `authproxy`, `coreconfig`, `postgres`, and the `carriernodeclient` construction). The shared web-ui was searched with grep only. The node, python and java packages were not reviewed.
|
||||||
- The frontend bundle was not measured. The web-ui is imported through its barrel (`import { Pagination } from '@gabriel20xx/web-ui'`), and whether that tree-shakes needs verification with a production build.
|
- The production frontend build passed after the consumer wired the local design-tokens package and preserved shared-package symlinks; the resulting bundle size was reported by Vite but not benchmarked in a browser.
|
||||||
- No TODO, FIXME or HACK markers were found in `backend/` or `frontend/src/`.
|
- No TODO, FIXME or HACK markers were found in `backend/` or `frontend/src/`.
|
||||||
+25
-10
@@ -4,10 +4,10 @@
|
|||||||
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
||||||
- **Analyzed:** 2026-10-16
|
- **Analyzed:** 2026-10-16
|
||||||
- **Commit:** 6aec03f on main
|
- **Commit:** 6aec03f on main
|
||||||
- **Working tree:** clean (no uncommitted changes, no untracked files)
|
- **Working tree:** contains uncommitted changes from the earlier and current medium passes.
|
||||||
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed); open Medium findings name their blocker in their status lines. A second Medium pass added database-backed backend tests, frontend helper tests and a CI Postgres service (Q-004, still open for Android tests) and re-checked Q-006.
|
- **Updated:** 2026-10-20 — Q-006 now uses a server-side change token; Q-004 remains partly open because its Android JVM test and PostgreSQL integration tests could not be run here.
|
||||||
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, Tailwind 4, TanStack Query) embedded in the Go binary; Android client (Kotlin, Jetpack Compose, Room, Retrofit/OkHttp); Docker; GitHub Actions.
|
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, Tailwind 4, TanStack Query) embedded in the Go binary; Android client (Kotlin, Jetpack Compose, Room, Retrofit/OkHttp); Docker; GitHub Actions.
|
||||||
- **Scope:** Read all first-party backend code (`backend/*.go`, including the five test files), the frontend data layer, routes, list components and Vite config, the Android API client, preferences, sync repository and app Gradle file, `README.md`, `.github/workflows/*`, `docker/Dockerfile`, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper jar, generated build output, lock files (read for versions only), and the rest of `shared/`. The tracked SQLite files were inspected read-only from a copy. No tests, linters or builds were run.
|
- **Scope:** Read all first-party backend code (`backend/*.go`, including the tests), the frontend data layer, routes, list components and Vite config, the Android API client, preferences, sync repository and app Gradle file, `README.md`, `.github/workflows/*`, `docker/Dockerfile`, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper jar, generated build output, lock files (read for versions only), and the rest of `shared/`. The tracked SQLite files were inspected read-only from a copy. Verification commands and results are below.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
|---|---:|---:|---:|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 0 | 0 | 0 | 0 |
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
| High | 0 | 0 | 0 | 0 |
|
| High | 0 | 0 | 0 | 0 |
|
||||||
| Medium | 6 | 4 | 0 | 2 |
|
| Medium | 6 | 5 | 0 | 1 |
|
||||||
| Low | 8 | 0 | 0 | 8 |
|
| Low | 8 | 0 | 0 | 8 |
|
||||||
| Info | 0 | 0 | 0 | 0 |
|
| Info | 0 | 0 | 0 | 0 |
|
||||||
|
|
||||||
@@ -45,11 +45,11 @@ The backend is small and readable, but its transactional and delete logic is dup
|
|||||||
- **Status:** Fixed 2026-10-19 — `handleSync` is now a thin adapter over `applySyncRequest` and the per-table `applyLists`, `applyFields`, `applyItems` and `applyValues` helpers. The cascades (`cascadeDeleteList`, `cascadeDeleteField`, `cascadeDeleteItem`), `fieldDefaults` and `upsertValue` are shared by REST and sync, and sync picks its event type through one helper (`changeEventType`). The REST list, field and item create and update handlers keep their own SQL on purpose, because a plain `INSERT` rejects a duplicate id and switching it to the last-writer-wins upsert would change REST behaviour. Files: backend/sync.go, backend/data.go.
|
- **Status:** Fixed 2026-10-19 — `handleSync` is now a thin adapter over `applySyncRequest` and the per-table `applyLists`, `applyFields`, `applyItems` and `applyValues` helpers. The cascades (`cascadeDeleteList`, `cascadeDeleteField`, `cascadeDeleteItem`), `fieldDefaults` and `upsertValue` are shared by REST and sync, and sync picks its event type through one helper (`changeEventType`). The REST list, field and item create and update handlers keep their own SQL on purpose, because a plain `INSERT` rejects a duplicate id and switching it to the last-writer-wins upsert would change REST behaviour. Files: backend/sync.go, backend/data.go.
|
||||||
|
|
||||||
### Q-004 · Core data layer has no tests, and CI never starts a database · **Medium** · Open
|
### Q-004 · Core data layer has no tests, and CI never starts a database · **Medium** · Open
|
||||||
- **Location:** `backend/routes_test.go:8-11` (registers routes with a nil database and asserts nothing); `backend/auth_test.go`, `env_test.go`, `models_test.go` and `sync_test.go` (cover env parsing, JSON timestamp parsing, timestamp normalization and the auth stub only); `.github/workflows/tests.yml` (Go job runs `go test ./...` with no Postgres service); the frontend has no unit tests (CI runs `npm run check` only); `CollabTableAndroid/app/src` has no test sources.
|
- **Location:** `backend/db_test.go` and `.github/workflows/tests.yml` (database-backed tests and a PostgreSQL service); `frontend/src/lib/api.test.js` and the `node:test` suite; `CollabTableAndroid/app/src/test/java/com/collabtable/app/data/repository/SyncPageProgressTest.kt` (new JVM test, not yet run here).
|
||||||
- **Description:** No test exercises `handleSync`, the list, field, item and value handlers, `/web/data`, the CORS wrapper, the SPA fallback, or the frontend helpers in `listHelpers.js`. The one route test runs without assertions.
|
- **Description:** Backend and frontend coverage now exercises core paths, but local database-backed tests need PostgreSQL and the Android sync-page test has not been compiled or run. There is no Android CI job. The new coverage still needs a successful database and JVM execution.
|
||||||
- **Impact:** The most complex logic (sync merge, cascades, notification side effects, timestamp handling) is covered only by manual testing, so regressions like Q-001 and Q-002 are invisible.
|
- **Impact:** The most complex logic (sync merge, cascades, notification side effects, timestamp handling) is covered only by manual testing, so regressions like Q-001 and Q-002 are invisible.
|
||||||
- **Recommendation:** Add `httptest` integration tests against a real Postgres (as a CI service container), starting with sync round trips and delete cascades. Give `routes_test.go` real assertions on methods and status codes. Add Vitest tests for `listHelpers.js`, and JVM unit tests for the Android sync merge logic.
|
- **Recommendation:** Add `httptest` integration tests against a real Postgres (as a CI service container), starting with sync round trips and delete cascades. Give `routes_test.go` real assertions on methods and status codes. Add Vitest tests for `listHelpers.js`, and JVM unit tests for the Android sync merge logic.
|
||||||
- **Status:** Open 2026-10-19 — Partly fixed: route and middleware tests assert real behaviour (`backend/routes_test.go`, `backend/server_test.go`). New database-backed tests in `backend/db_test.go` cover sync round trips between devices, the `updatedat >= since` delta, last-writer-wins, stale and newer deletes, delete cascades on the REST and sync paths, the value-cell guard, orphan values, the notification savepoint, `/web/data` ETags and API tokens. They need `TEST_DATABASE_URL` (each test uses its own schema and drops it) and are skipped without it; `tests.yml` now starts a PostgreSQL service container and sets it. A `node --test` suite covers `listHelpers.js` (`npm test`, no new dependency, also run in CI). Run against PostgreSQL 18 here: all pass, and breaking four of the rules made a test fail. Still open: Android JVM unit tests for the sync merge logic. JUnit is declared, but there is no JDK or Gradle here to compile or run them, so none were written. The CI change itself has not run.
|
- **Status:** Open 2026-10-20 — Partly fixed: route and middleware tests assert behavior; PostgreSQL-backed tests now cover sync, pagination, change-token backfill, membership isolation, cascades, values, notifications, `/web/data` and tokens; frontend tests cover list helpers and credential proof forwarding; and `SyncPageProgressTest.kt` covers the Android page loop. The PostgreSQL tests skip locally because `TEST_DATABASE_URL` is unset and no local PostgreSQL binaries are available. The workflow defines a PostgreSQL service but was not run here. Java and Gradle are unavailable, so the JVM test remains uncompiled and unrun; no Android CI job runs it.
|
||||||
|
|
||||||
### Q-005 · Setup documentation contradicts the configuration · **Medium** · Fixed
|
### Q-005 · Setup documentation contradicts the configuration · **Medium** · Fixed
|
||||||
- **Location:** `README.md:52` (`SECRET` marked as optional, default "unset (push endpoint refuses every caller)"); `README.md:70-79` (Quick Start `docker run` sets no `SECRET`); `README.md:55` (`COOKIE_SECURE` described as marking cookies `Secure`); `shared/backend/auth/proxy.go:359-361` and `:838-841`; `backend/auth.go:113-120`; `frontend/vite.config.js:38-41` (dev proxy forwards only `/web` and `/health`).
|
- **Location:** `README.md:52` (`SECRET` marked as optional, default "unset (push endpoint refuses every caller)"); `README.md:70-79` (Quick Start `docker run` sets no `SECRET`); `README.md:55` (`COOKIE_SECURE` described as marking cookies `Secure`); `shared/backend/auth/proxy.go:359-361` and `:838-841`; `backend/auth.go:113-120`; `frontend/vite.config.js:38-41` (dev proxy forwards only `/web` and `/health`).
|
||||||
@@ -58,12 +58,12 @@ The backend is small and readable, but its transactional and delete logic is dup
|
|||||||
- **Recommendation:** Mark `SECRET` as required when auth is enabled, add it to the Quick Start, correct the `COOKIE_SECURE` description, and add `/api` to the Vite proxy.
|
- **Recommendation:** Mark `SECRET` as required when auth is enabled, add it to the Quick Start, correct the `COOKIE_SECURE` description, and add `/api` to the Vite proxy.
|
||||||
- **Status:** Fixed 2026-10-19 — README and backend README now mark `SECRET` as required unless `AUTH_DISABLED=true`, add it to the Quick Start, correct the `COOKIE_SECURE` description, and document `ALLOWED_ORIGINS`; the Vite dev proxy now forwards `/api`. Files: README.md, backend/README.md, frontend/vite.config.js.
|
- **Status:** Fixed 2026-10-19 — README and backend README now mark `SECRET` as required unless `AUTH_DISABLED=true`, add it to the Quick Start, correct the `COOKIE_SECURE` description, and document `ALLOWED_ORIGINS`; the Vite dev proxy now forwards `/api`. Files: README.md, backend/README.md, frontend/vite.config.js.
|
||||||
|
|
||||||
### Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · **Medium** · Open
|
### Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · **Medium** · Fixed
|
||||||
- **Location:** `backend/sync.go:20-43` (client timestamps accepted as sent, clamped only if in the future); upserts that overwrite regardless of the stored `updatedat`: `sync.go:64-69`, `:104-116`, `:149-156`, `:198-203`; the delta cursor filters on the stored value at `backend/data.go:75`, `:108`, `:145`, `:178`. Android: local edits stamped with device time (`CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt:148`), and the cursor is the server's `serverTimestamp` (`CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt:49-60`, `:283`).
|
- **Location:** `backend/sync.go:20-43` (client timestamps accepted as sent, clamped only if in the future); upserts that overwrite regardless of the stored `updatedat`: `sync.go:64-69`, `:104-116`, `:149-156`, `:198-203`; the delta cursor filters on the stored value at `backend/data.go:75`, `:108`, `:145`, `:178`. Android: local edits stamped with device time (`CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt:148`), and the cursor is the server's `serverTimestamp` (`CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt:49-60`, `:283`).
|
||||||
- **Description:** Two related problems. (1) A device that edits offline stamps the change with an old local time. If another device has already advanced its cursor past that time, the `updatedat >= since` filter never returns the change to it. (2) Upserts overwrite the stored row whatever its `updatedat`, so an older change that arrives later replaces a newer one. The Android client mitigates (1) by forcing a full down-sync at app start (`SyncRepository.kt:122`), so the devices affected are those that stay open for a long time.
|
- **Description:** Two related problems. (1) A device that edits offline stamps the change with an old local time. If another device has already advanced its cursor past that time, the `updatedat >= since` filter never returns the change to it. (2) Upserts overwrite the stored row whatever its `updatedat`, so an older change that arrives later replaces a newer one. The Android client mitigates (1) by forcing a full down-sync at app start (`SyncRepository.kt:122`), so the devices affected are those that stay open for a long time.
|
||||||
- **Impact:** Silent divergence between devices, and lost updates when two devices edit the same row offline. Dashboard users see stale data until a device restarts.
|
- **Impact:** Silent divergence between devices, and lost updates when two devices edit the same row offline. Dashboard users see stale data until a device restarts.
|
||||||
- **Recommendation:** Assign server-side change tokens (a monotonically increasing sequence, or the server receive time) to every write and use that as the cursor, keeping client `updatedat` for display only. Alternatively, make each upsert conditional on `EXCLUDED.updatedat` being newer than the stored value, and document the last-writer-wins rule.
|
- **Recommendation:** Assign server-side change tokens (a monotonically increasing sequence, or the server receive time) to every write and use that as the cursor, keeping client `updatedat` for display only. Alternatively, make each upsert conditional on `EXCLUDED.updatedat` being newer than the stored value, and document the last-writer-wins rule.
|
||||||
- **Status:** Open 2026-10-19 — Re-checked, unchanged. Conditional upserts are in place and now covered by `backend/db_test.go` (`TestSyncLastWriterWinsByTimestamp`, `TestStaleDeleteDoesNotCascadeButNewerDeleteDoes`; an equal timestamp still applies). Still open: a change stamped with an old device clock can miss the `updatedat >= since` cursor. The fix needs a server-side change token on every row (a new column with a backfill, so a stored-data-format change) and a rollout plan. Decision needed: the token design (server receive time or a sequence) and whether the Android cursor changes with it.
|
- **Status:** Fixed 2026-10-20 — Every list, field, item and value write now receives a monotonic server `change_token`; startup backfills existing rows. Sync reads a repeatable-read snapshot and returns a bounded page with `nextSyncToken`; Android follows all pages and saves the cursor after completion. Client timestamps remain metadata and govern stale-write handling. Existing clients must update because requests without `lastSyncToken` now receive 400. PostgreSQL runtime tests are written but skipped locally; see Verification. Files: `backend/db.go`, `backend/models.go`, `backend/sync.go`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/CollabTableApi.kt`, `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt`.
|
||||||
|
|
||||||
### Q-007 · Validation and error mapping return misleading status codes and contract drift · **Low**
|
### Q-007 · Validation and error mapping return misleading status codes and contract drift · **Low**
|
||||||
- **Location:** `backend/data.go:248-255` (duplicate list id returns `500 Failed to create list` rather than `409`); `backend/data.go:549-558` (an item value for a missing item or field fails on a foreign key and returns `500`); `backend/data.go:589-607` (`PUT /api/items/{id}` accepts a body but only bumps `updatedat`, ignoring the body); `backend/server.go:292-316` (unknown `/api/...` paths return `index.html` with `200`).
|
- **Location:** `backend/data.go:248-255` (duplicate list id returns `500 Failed to create list` rather than `409`); `backend/data.go:549-558` (an item value for a missing item or field fails on a foreign key and returns `500`); `backend/data.go:589-607` (`PUT /api/items/{id}` accepts a body but only bumps `updatedat`, ignoring the body); `backend/server.go:292-316` (unknown `/api/...` paths return `index.html` with `200`).
|
||||||
@@ -76,6 +76,7 @@ The backend is small and readable, but its transactional and delete logic is dup
|
|||||||
- **Description:** Dead helpers and an unused client remain in place. The retired tables are still managed by startup code even though nothing reads them.
|
- **Description:** Dead helpers and an unused client remain in place. The retired tables are still managed by startup code even though nothing reads them.
|
||||||
- **Impact:** Noise for maintainers, and a secret held in memory for no purpose.
|
- **Impact:** Noise for maintainers, and a secret held in memory for no purpose.
|
||||||
- **Recommendation:** Remove `isNoRows`. Construct the CarrierNode client only when a feature uses it. Drop the session-pruning goroutine, or document why it stays.
|
- **Recommendation:** Remove `isNoRows`. Construct the CarrierNode client only when a feature uses it. Drop the session-pruning goroutine, or document why it stays.
|
||||||
|
- **Status:** Partly fixed 2026-10-20 — removed `isNoRows` and the unused CarrierNode client construction/field. Retired auth tables and their pruning remain in place to avoid changing stored-data retention in this cleanup. Files: `backend/notifications.go`, `backend/server.go`.
|
||||||
|
|
||||||
### Q-009 · Several failures are discarded without a comment on the risk · **Low**
|
### Q-009 · Several failures are discarded without a comment on the risk · **Low**
|
||||||
- **Location:** `backend/data.go:424` and `:587` (`_ = decodeJSON(...)` on DELETE and PUT with an optional body); `backend/data.go:620` (`_, _ =` on the item value delete); `backend/data.go:618-619` (a failed item re-read silently skips the notification); `backend/sync.go:211` (raw database error text is logged, which can include values).
|
- **Location:** `backend/data.go:424` and `:587` (`_ = decodeJSON(...)` on DELETE and PUT with an optional body); `backend/data.go:620` (`_, _ =` on the item value delete); `backend/data.go:618-619` (a failed item re-read silently skips the notification); `backend/sync.go:211` (raw database error text is logged, which can include values).
|
||||||
@@ -113,8 +114,22 @@ The backend is small and readable, but its transactional and delete logic is dup
|
|||||||
- **Impact:** Confusing for contributors, and a risk if real data is ever saved there.
|
- **Impact:** Confusing for contributors, and a risk if real data is ever saved there.
|
||||||
- **Recommendation:** Remove the tracked files, add ignore rules for `*.db` and `build-*.txt`, and keep only the placeholder `backend/web/.gitkeep`.
|
- **Recommendation:** Remove the tracked files, add ignore rules for `*.db` and `build-*.txt`, and keep only the placeholder `backend/web/.gitkeep`.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- Go command (all database URL variables unset):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
unset DATABASE_URL SHARED_TEST_DATABASE_URL TEST_DATABASE_URL && export PATH=/tmp/medium-pass-gosdk/go/bin:$PATH GOCACHE=/tmp/medium-pass-go-cache GOMODCACHE=/tmp/medium-pass-go-mod && go test ./... && go test -v -run 'Test(ParsePageRequest|InitSchemaCanRunAgainstAnExistingDatabase|CollectionEndpointsPageWithStableCursors|SyncUsesServerChangeTokenInsteadOfClientTimestamp|SyncBoundsAndPagesLargeInitialSync|PerListMembershipScopesDataAndSync|MembershipBackfillPreservesCurrentAPITokenUsers)$' && go vet ./... && gofmt -l . && for bin in postgres psql initdb; do command -v "$bin" || true; done
|
||||||
|
```
|
||||||
|
|
||||||
|
`go test ./...` passed. All nine `TestParsePageRequest` cases passed; the six PostgreSQL-backed cases in the focused run skipped because `TEST_DATABASE_URL` is unset. `go vet ./...` passed and `gofmt -l .` printed no files. `postgres`, `psql` and `initdb` were not found.
|
||||||
|
- Frontend commands: `unset DATABASE_URL && npm test` (9 passed); `unset DATABASE_URL && npm run check` (0 errors, 0 warnings); `unset DATABASE_URL && npm run lint` (passed); `unset DATABASE_URL && npm run build` (passed after adding the local design-tokens dependency and enabling `resolve.preserveSymlinks`; the build reports one Svelte warning in shared `layout.svelte.js:44`); `unset DATABASE_URL && npx prettier --check src/lib/api.js src/lib/api.test.js src/lib/features/layout/AppShell.svelte` and `unset DATABASE_URL && npx prettier --check --end-of-line crlf vite.config.js` (both passed).
|
||||||
|
- Build dependency wiring: `unset DATABASE_URL && npm install --save '@gabriel20xx/design-tokens@file:../shared/packages/design-tokens' --offline` added the local package to `frontend/package.json` and the lockfile. The Vite build initially exposed the local shared-package symlink resolution issue; `resolve.preserveSymlinks` fixed it.
|
||||||
|
- `unset DATABASE_URL && npm run format:check` failed on four untouched files (`src/app.css`, `src/lib/components/ui/dropdown-menu/content.svelte`, `src/lib/features/layout/SettingsDialog.svelte`, `src/routes/+layout.svelte`) and `vite.config.js`, whose original CRLF line endings were preserved to keep the change limited.
|
||||||
|
- Android JVM tests were not run: Java and Gradle executables and a Unix `gradlew` wrapper are unavailable. The source test exists at the path listed in Q-004. A final redundant Svelte-check rerun was stopped after the process remained in uninterruptible I/O for several minutes; an earlier `npm run check` completed successfully before the Vite-only symlink setting.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- Static review only. No tests, linters, Go or Node builds, or Gradle runs were executed. Test coverage was assessed by reading the `_test.go` files and the CI workflows.
|
- No live AuthGuard instance or browser session was available, and no load benchmark was run. Performance estimates still need realistic data and multiple devices.
|
||||||
- Checked and clean: no `{@html}`, `innerHTML` or `eval` in the dashboard; error wrapping in `backend/db.go` and the auth helpers is consistent; `shared/backend/postgres/postgres.go:216-235` (`WithTx`) rolls back through a deferred call on every path; no TODO, FIXME or HACK markers in `backend/` or `frontend/src/`.
|
- Checked and clean: no `{@html}`, `innerHTML` or `eval` in the dashboard; error wrapping in `backend/db.go` and the auth helpers is consistent; `shared/backend/postgres/postgres.go:216-235` (`WithTx`) rolls back through a deferred call on every path; no TODO, FIXME or HACK markers in `backend/` or `frontend/src/`.
|
||||||
- `map[string]any` is used for several ad hoc response bodies (`backend/web.go:77-89`, `backend/data.go:464` and `:623`). That is acceptable for these responses, and no weakly typed data flows through the core domain types.
|
- `map[string]any` is used for several ad hoc response bodies (`backend/web.go:77-89`, `backend/data.go:464` and `:623`). That is acceptable for these responses, and no weakly typed data flows through the core domain types.
|
||||||
- `shared/` was reviewed selectively. Two items in it are outside CollabTable's runtime and are noted for the shared package owners rather than counted here: `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify` (which disables WebSocket origin checks) when the allowed origin is `*`, and the package is not imported by CollabTable.
|
- `shared/` was reviewed selectively. Two items in it are outside CollabTable's runtime and are noted for the shared package owners rather than counted here: `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify` (which disables WebSocket origin checks) when the allowed origin is `*`, and the package is not imported by CollabTable.
|
||||||
@@ -35,7 +35,7 @@ CollabTable's browser dashboard authenticates through AuthGuard, a centralized i
|
|||||||
AuthGuard integration has three states:
|
AuthGuard integration has three states:
|
||||||
- `AUTHGUARD_URL` set — used immediately.
|
- `AUTHGUARD_URL` set — used immediately.
|
||||||
- `AUTHGUARD_URL` unset, `AUTH_DISABLED` unset/false (the default) — "pending": auth stays fully enabled/gated, waiting for ProjectConfigurator to push a live URL (see below), and fails closed on auth calls until one arrives.
|
- `AUTHGUARD_URL` unset, `AUTH_DISABLED` unset/false (the default) — "pending": auth stays fully enabled/gated, waiting for ProjectConfigurator to push a live URL (see below), and fails closed on auth calls until one arrives.
|
||||||
- `AUTH_DISABLED=true` — authentication is fully off (no login screen, nothing gated, every request treated as authenticated) — only use this for local development or a deployment you are certain does not need access control.
|
- `AUTH_DISABLED=true` — browser-session gates are off. List access still requires membership; the placeholder identity used in this mode has no memberships, so dashboard data is empty and sync tokens minted for it are rejected. Use this only to develop the auth shell, not for a working data deployment.
|
||||||
|
|
||||||
Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state.
|
Because AuthGuard doesn't know "this is CollabTable's initial account" and can't answer "have any accounts been registered yet" (it's a shared identity store other projects and other CollabTable instances may already use), the one-time setup screen is instead gated by a small local flag in Postgres, independent of AuthGuard's own state.
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ The device-sync API token (generated from the dashboard's Settings page, used by
|
|||||||
|----------|----------|---------|--------------|
|
|----------|----------|---------|--------------|
|
||||||
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
|
| `DATABASE_URL` | Yes | — | PostgreSQL connection string (bring your own instance) |
|
||||||
| `AUTHGUARD_URL` | No | unset (pending) | Optional bootstrap/override base URL of the AuthGuard identity service. Leaving it unset does not disable authentication — it leaves the service "pending" until ProjectConfigurator pushes a URL, failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off. |
|
| `AUTHGUARD_URL` | No | unset (pending) | Optional bootstrap/override base URL of the AuthGuard identity service. Leaving it unset does not disable authentication — it leaves the service "pending" until ProjectConfigurator pushes a URL, failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off. |
|
||||||
| `AUTH_DISABLED` | No | `false` | Set `true` to disable authentication entirely (no login screen, nothing gated, every request treated as authenticated) — for local development or a standalone deployment with no AuthGuard integration at all. |
|
| `AUTH_DISABLED` | No | `false` | Set `true` to disable browser-session gates. List access remains membership-scoped; the placeholder identity has no memberships and its sync tokens are rejected. Use only for auth-shell development, not for a working data deployment. |
|
||||||
| `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. |
|
| `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. |
|
||||||
| `SECRET` | Yes, unless `AUTH_DISABLED=true` | unset | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal` and `PUT /api/auth/access/internal`. Without it, `GET /api/auth/status` reports `SECRET environment variable is not set.` and every auth-gated route returns 500, and the internal endpoints refuse every caller. |
|
| `SECRET` | Yes, unless `AUTH_DISABLED=true` | unset | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal` and `PUT /api/auth/access/internal`. Without it, `GET /api/auth/status` reports `SECRET environment variable is not set.` and every auth-gated route returns 500, and the internal endpoints refuse every caller. |
|
||||||
| `ALLOWED_ORIGINS` | No | unset | Comma-separated browser origins that may call the API cross-origin with credentials. Leave unset: the dashboard is same-origin and needs no CORS. |
|
| `ALLOWED_ORIGINS` | No | unset | Comma-separated browser origins that may call the API cross-origin with credentials. Leave unset: the dashboard is same-origin and needs no CORS. |
|
||||||
@@ -58,6 +58,8 @@ The device-sync API token (generated from the dashboard's Settings page, used by
|
|||||||
| `PRODUCTION` | No | `false` | Set `true` to refuse plain HTTP: requests must arrive over TLS or through a `TRUSTED_PROXIES` proxy sending `X-Forwarded-Proto: https`. Requires `TRUSTED_PROXIES`. With `false`, the server logs a warning that TLS is off. |
|
| `PRODUCTION` | No | `false` | Set `true` to refuse plain HTTP: requests must arrive over TLS or through a `TRUSTED_PROXIES` proxy sending `X-Forwarded-Proto: https`. Requires `TRUSTED_PROXIES`. With `false`, the server logs a warning that TLS is off. |
|
||||||
| `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup |
|
| `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup |
|
||||||
| `DB_INIT_RETRY_MAX_ATTEMPTS` | No | `0` (retry forever) | Max database-connection retry attempts at startup |
|
| `DB_INIT_RETRY_MAX_ATTEMPTS` | No | `0` (retry forever) | Max database-connection retry attempts at startup |
|
||||||
|
| `OMNILOGGER_URL` | No | unset | Optional initial base URL of the OmniLogger log sink. Server log lines are also sent there when it and `OMNILOGGER_INGEST_TOKEN` are both set; console output is unchanged. ProjectConfigurator's push can supply or replace it at runtime. The `remap-users` command is not shipped. |
|
||||||
|
| `OMNILOGGER_INGEST_TOKEN` | No | unset | Optional initial ingest token for this service (`collabtable`). ProjectConfigurator normally supplies the token at runtime through its core-services push, which also starts shipping. Shipping stays off until both a URL and a token are known. |
|
||||||
| `SYNC_MAX_FUTURE_SKEW_MS` | No | `0` | Client clock skew tolerated in sync timestamps, to avoid re-sending future-dated rows in hot loops |
|
| `SYNC_MAX_FUTURE_SKEW_MS` | No | `0` | Client clock skew tolerated in sync timestamps, to avoid re-sending future-dated rows in hot loops |
|
||||||
| `NOTIF_RETENTION_MS` | No | `604800000` (7 days) | How long sync notifications are retained before cleanup |
|
| `NOTIF_RETENTION_MS` | No | `604800000` (7 days) | How long sync notifications are retained before cleanup |
|
||||||
|
|
||||||
|
|||||||
+11
-11
@@ -4,10 +4,10 @@
|
|||||||
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
- **Path:** /workspace/Personal/Web/Originals/CollabTable
|
||||||
- **Analyzed:** 2026-10-16
|
- **Analyzed:** 2026-10-16
|
||||||
- **Commit:** 6aec03f on main
|
- **Commit:** 6aec03f on main
|
||||||
- **Working tree:** clean (no uncommitted changes, no untracked files)
|
- **Working tree:** contains uncommitted changes from the earlier and current medium passes.
|
||||||
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). S-006 and S-009 follow owner decisions 5 (trusted-proxy client IP) and 11 (LAN HTTP with a warning). A second Medium pass re-checked the open items: S-007 is fixed (full dashboard CSP), S-002 does not reproduce, and S-003 and S-005 stay open for owner or shared decisions.
|
- **Updated:** 2026-10-20 — S-003 now enforces the approved per-list membership model; S-005 applies the shared reauthentication rule and remains open only for other-session revocation. S-002 remains Not reproduced by owner decision.
|
||||||
- **Stack:** Go 1.26 (net/http, pgx v5) API server with PostgreSQL; identity delegated to a separate AuthGuard service via `shared/backend/auth`; SvelteKit 2 / Svelte 5 static dashboard embedded in the Go binary; Android client (Kotlin, Retrofit/OkHttp, Room, SharedPreferences); Docker multi-stage image on `scratch`; GitHub Actions.
|
- **Stack:** Go 1.26 (net/http, pgx v5) API server with PostgreSQL; identity delegated to a separate AuthGuard service via `shared/backend/auth`; SvelteKit 2 / Svelte 5 static dashboard embedded in the Go binary; Android client (Kotlin, Retrofit/OkHttp, Room, SharedPreferences); Docker multi-stage image on `scratch`; GitHub Actions.
|
||||||
- **Scope:** Read all first-party backend code (`backend/*.go`), the Docker and CI configuration, the frontend API client, routes and query layer, the Vite config, the Android API client, preferences, manifest, network security config and app Gradle file, and the shared auth, authclient, authproxy, coreconfig and postgres code that CollabTable calls. Git history was searched for credential-shaped strings and `.env` files. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, generated build output, lock files (read for versions only), and the rest of `shared/`. Tracked SQLite files were inspected read-only from a copy, schema and row counts only. No tests, audits, builds or network calls were made; the analysis is static.
|
- **Scope:** Read all first-party backend code (`backend/*.go`), the Docker and CI configuration, the frontend API client, routes and query layer, the Vite config, the Android API client, preferences, manifest, network security config and app Gradle file, and the shared auth, authclient, authproxy, coreconfig and postgres code that CollabTable calls. Git history was searched for credential-shaped strings and `.env` files. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, generated build output, lock files (read for versions only), and the rest of `shared/`. Tracked SQLite files were inspected read-only from a copy, schema and row counts only. Available tests and builds are recorded in `QUALITY_REPORT.md`; no network audit or live deployment check was made.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -15,11 +15,11 @@
|
|||||||
|---|---:|---:|---:|---:|
|
|---|---:|---:|---:|---:|
|
||||||
| Critical | 0 | 0 | 0 | 0 |
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
| High | 0 | 0 | 0 | 0 |
|
| High | 0 | 0 | 0 | 0 |
|
||||||
| Medium | 10 | 7 | 1 | 2 |
|
| Medium | 10 | 8 | 1 | 1 |
|
||||||
| Low | 7 | 0 | 0 | 7 |
|
| Low | 7 | 0 | 0 | 7 |
|
||||||
| Info | 2 | 0 | 0 | 2 |
|
| Info | 2 | 0 | 0 | 2 |
|
||||||
|
|
||||||
No critical or high-severity issues were confirmed. Authentication is delegated to AuthGuard and fails closed when it is not configured, and sync tokens are generated with 256 bits of randomness and stored hashed. The main concerns are a reflective CORS policy with credentials, a login-disabled mode that hands out sync tokens to anyone, the absence of object-level authorization on data (possibly intended, but unscoped), missing rate limiting and security headers, and several Android client exposures (the token written to logcat, cleartext traffic permitted, and the token stored in plain preferences).
|
No critical or high-severity issues were confirmed. Authentication is delegated to AuthGuard and fails closed when it is not configured, and sync tokens are generated with 256 bits of randomness and stored hashed. Data access is now scoped by list membership; legacy lists remain available to all API-token users present during migration, as approved. Other concerns include reflective CORS with credentials, missing rate limits and security headers, and Android token exposure through cleartext traffic or plain device preferences.
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
@@ -35,14 +35,14 @@ No critical or high-severity issues were confirmed. Authentication is delegated
|
|||||||
- **Description:** When login is not required (`AUTH_DISABLED=true`, or the login-required override pushed by ProjectConfigurator set to false), `RequireIfLoginRequired` lets any caller reach token regeneration without credentials. The endpoint mints a write-capable sync token for identity 0, and the bearer-token check on the sync API then passes for that caller.
|
- **Description:** When login is not required (`AUTH_DISABLED=true`, or the login-required override pushed by ProjectConfigurator set to false), `RequireIfLoginRequired` lets any caller reach token regeneration without credentials. The endpoint mints a write-capable sync token for identity 0, and the bearer-token check on the sync API then passes for that caller.
|
||||||
- **Impact:** The sync API's token requirement protects nothing in that mode, and any network client can obtain full read, write and delete access. The README describes `AUTH_DISABLED` as "nothing gated", so this matches the documented intent. The override path can be set centrally in a shared deployment, however, and nobody may notice that the token API has become open.
|
- **Impact:** The sync API's token requirement protects nothing in that mode, and any network client can obtain full read, write and delete access. The README describes `AUTH_DISABLED` as "nothing gated", so this matches the documented intent. The override path can be set centrally in a shared deployment, however, and nobody may notice that the token API has become open.
|
||||||
- **Recommendation:** Keep token minting behind a real credential even when login is off (for example, always require a session for token regeneration), or document the consequence prominently and log a warning when the override is set to false.
|
- **Recommendation:** Keep token minting behind a real credential even when login is off (for example, always require a session for token regeneration), or document the consequence prominently and log a warning when the override is set to false.
|
||||||
- **Status:** Not reproduced 2026-10-19 — The last step of the chain fails. With login off, callers resolve to the placeholder identity 0, and `requireAPIToken` (`backend/auth.go`) never accepts identity 0, so the token minted without a session gets 401 on `/api/sync` and `/api/lists`. Test `TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI` (`backend/db_test.go`, run against PostgreSQL) pins this. Write and delete access through the token API is not reachable. What login-off mode does open is the dashboard (`/web/data`, user management), as `AUTH_DISABLED` documents; `backend/README.md` now says so. Side effect: with login off, devices cannot get a working sync token; accepting identity 0 would fix that and open the sync API, so it is an owner decision. The `auth.go` comment that called such a token functional is corrected.
|
- **Status:** Not reproduced 2026-10-20 — The last step of the chain fails. With login off, callers resolve to placeholder identity 0, and `requireAPIToken` (`backend/auth.go`) never accepts identity 0, so a token minted without a session gets 401 on `/api/sync` and `/api/lists`. `TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI` pins this. Write and delete access through that token is not reachable. Login-off still bypasses the browser-session gate, but `/web/data` returns no list rows because identity 0 has no memberships. Devices cannot get a working sync token; accepting identity 0 would open sync and is not part of this decision.
|
||||||
|
|
||||||
### S-003 · No object-level ownership or roles on list, field, item or value data · **Medium** · Open
|
### S-003 · No object-level ownership or roles on list, field, item or value data · **Medium** · Fixed
|
||||||
- **Location:** `backend/auth.go:129-149` (`requireAPIToken` only checks that a token exists); `backend/server.go:195-219` (all data routes); `backend/data.go` (all handlers); `backend/sync.go:61-209`; `backend/db.go:40-189` (no owner or tenant columns); `backend/sync.go:198-203` and `backend/data.go:549-558` (item values upserted by `id` alone).
|
- **Location:** `backend/auth.go:129-149` (`requireAPIToken` only checks that a token exists); `backend/server.go:195-219` (all data routes); `backend/data.go` (all handlers); `backend/sync.go:61-209`; `backend/db.go:40-189` (no owner or tenant columns); `backend/sync.go:198-203` and `backend/data.go:549-558` (item values upserted by `id` alone).
|
||||||
- **Description:** Any valid sync token (one per account) and any logged-in account can read, overwrite, soft-delete and move every list, field, item and value. The item-value conflict clause updates only `value` and `updatedat`, so a write that names a different `itemId` or `fieldId` than the stored row is silently applied to the stored row. The schema has no owner column, and `api_tokens.user_id` is used only for token regeneration. Item values are hard-deleted when their item or list is deleted (`sync.go:88`, `:129`, `:140`, `:166`), so those deletions cannot be undone by a later sync, even though lists and items are soft-deleted.
|
- **Description:** Any valid sync token (one per account) and any logged-in account can read, overwrite, soft-delete and move every list, field, item and value. The item-value conflict clause updates only `value` and `updatedat`, so a write that names a different `itemId` or `fieldId` than the stored row is silently applied to the stored row. The schema has no owner column, and `api_tokens.user_id` is used only for token regeneration. Item values are hard-deleted when their item or list is deleted (`sync.go:88`, `:129`, `:140`, `:166`), so those deletions cannot be undone by a later sync, even though lists and items are soft-deleted.
|
||||||
- **Impact:** For a collaborative tool this may be intended, in which case every account is effectively an administrator of the data. If it is not intended, it is an authorization gap. Either way, one compromised device token can wipe or rewrite the database, and some of that loss is permanent.
|
- **Impact:** For a collaborative tool this may be intended, in which case every account is effectively an administrator of the data. If it is not intended, it is an authorization gap. Either way, one compromised device token can wipe or rewrite the database, and some of that loss is permanent.
|
||||||
- **Recommendation:** Confirm the intended model and document it. If the data is shared, make item-value upserts reject writes whose `itemid` or `fieldid` do not match the stored row. If per-list access is needed, add a membership table and check it in every handler.
|
- **Recommendation:** Confirm the intended model and document it. If the data is shared, make item-value upserts reject writes whose `itemid` or `fieldid` do not match the stored row. If per-list access is needed, add a membership table and check it in every handler.
|
||||||
- **Status:** Open 2026-10-19 — Partly addressed: item values apply only to a stored row with the same `itemId` and `fieldId` (sync and REST; tests in `backend/db_test.go`), stale writes are ignored (see Q-006), and the current access model is written down in `backend/README.md` ("Access model"). Still needed: an owner decision on the model (shared data, or per-list membership, which needs a membership table checked in every handler), and whether item values should be soft-deleted instead of removed for good (a schema change).
|
- **Status:** Fixed 2026-10-20 — `list_memberships` now scopes REST, sync, dashboard and notification reads; cross-list item/field IDs are rejected. New lists belong only to their creator. Per the owner decision, migration grants every current API-token user access to each legacy list because prior ownership cannot be reconstructed. Login-disabled identity 0 has no list access. Item values still hard-delete with their parent, as before. Files: `backend/db.go`, `backend/ownership.go`, `backend/data.go`, `backend/sync.go`, `backend/web.go`.
|
||||||
|
|
||||||
### S-004 · Managed-user routes require a login only, leaving the role check to AuthGuard · **Medium** · Fixed
|
### S-004 · Managed-user routes require a login only, leaving the role check to AuthGuard · **Medium** · Fixed
|
||||||
- **Location:** `backend/server.go:178-182` (list, create, update and delete users, behind `RequireIfLoginRequired`); `shared/backend/auth/proxy.go:897-1013` (handlers forward the caller's session to AuthGuard without a local role check); `shared/backend/auth/proxy.go:618` (`RequireUserManager` exists but CollabTable does not use it).
|
- **Location:** `backend/server.go:178-182` (list, create, update and delete users, behind `RequireIfLoginRequired`); `shared/backend/auth/proxy.go:897-1013` (handlers forward the caller's session to AuthGuard without a local role check); `shared/backend/auth/proxy.go:618` (`RequireUserManager` exists but CollabTable does not use it).
|
||||||
@@ -56,7 +56,7 @@ No critical or high-severity issues were confirmed. Authentication is delegated
|
|||||||
- **Description:** Anyone holding a session cookie can change the account password without knowing the current one. Sessions on other devices also remain valid, and there is no re-authentication step.
|
- **Description:** Anyone holding a session cookie can change the account password without knowing the current one. Sessions on other devices also remain valid, and there is no re-authentication step.
|
||||||
- **Impact:** A stolen or unattended session can lock the owner out. The usual defenses (re-authentication, and revoking other sessions on password change) are absent.
|
- **Impact:** A stolen or unattended session can lock the owner out. The usual defenses (re-authentication, and revoking other sessions on password change) are absent.
|
||||||
- **Recommendation:** Require `currentPassword` (and the TOTP code when enabled) on `POST /api/auth/credentials` whenever the password changes, and have AuthGuard revoke other sessions on a password change.
|
- **Recommendation:** Require `currentPassword` (and the TOTP code when enabled) on `POST /api/auth/credentials` whenever the password changes, and have AuthGuard revoke other sessions on a password change.
|
||||||
- **Status:** Open 2026-10-19 — Re-checked, shared-dependent. `UpdateMe` in the vendored `shared/backend/auth/proxy.go` accepts no `currentPassword`, and the shared medium pass left this open pending a decision on the request shape. Needed: that decision, then the change in Web/shared (and AuthGuard revoking other sessions), re-synced here. CollabTable cannot add the check alone without changing the `POST /api/auth/credentials` request.
|
- **Status:** Open 2026-10-20 — Partly fixed: the mirrored shared `UpdateMe` requires the current password and TOTP proof when enabled, and the dashboard forwards both values. Still open: revoking other sessions after a password change; no owner decision was made for that behavior. Files: `frontend/src/lib/api.js`, `frontend/src/lib/features/layout/AppShell.svelte`, `shared/backend/auth/proxy.go`.
|
||||||
|
|
||||||
### S-006 · No rate limiting or request budgets on login, token use, writes or body size · **Medium** · Fixed
|
### S-006 · No rate limiting or request budgets on login, token use, writes or body size · **Medium** · Fixed
|
||||||
- **Location:** `shared/backend/auth/proxy.go:1093-1142` (`Login` forwards every attempt to AuthGuard with no local throttling); `backend/auth.go:129-149` (sync-token check, no throttling); `backend/server.go:188` (token regeneration); `backend/server.go:253-259` (up to 50 MB per request, see P-007).
|
- **Location:** `shared/backend/auth/proxy.go:1093-1142` (`Login` forwards every attempt to AuthGuard with no local throttling); `backend/auth.go:129-149` (sync-token check, no throttling); `backend/server.go:188` (token regeneration); `backend/server.go:253-259` (up to 50 MB per request, see P-007).
|
||||||
@@ -147,8 +147,8 @@ No critical or high-severity issues were confirmed. Authentication is delegated
|
|||||||
- **Recommendation:** None.
|
- **Recommendation:** None.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- Static analysis only. Nothing was executed: no tests, builds, dependency audits or network calls. Fail-closed behavior was confirmed by reading the code, not by running the server.
|
- Source review and available checks are recorded in `QUALITY_REPORT.md` under Verification. No live AuthGuard instance or browser session was available, so delegated auth behavior was not exercised end to end.
|
||||||
- AuthGuard, the identity service, is outside this repository. S-001 (exploitability), S-004, S-005, S-006 and S-013 depend on how it behaves and should be verified against a running instance.
|
- AuthGuard, the identity service, is outside this repository. S-001 (exploitability), S-004, S-005, S-006 and S-013 depend on how it behaves and should be verified against a running instance.
|
||||||
- Android findings come from source, manifest and Gradle review. The app was not built or run.
|
- Android findings come from source, manifest and Gradle review. The sync-page JVM test source was added, but could not be compiled or run here because Java and Gradle are unavailable.
|
||||||
- `shared/` was reviewed selectively. `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify = true` (which disables WebSocket origin checks in the library) when the allowed origin is `*`. CollabTable does not import this package, so it is not counted here, but its owners should review it.
|
- `shared/` was reviewed selectively. `shared/backend/syncsocket/syncsocket.go:269` sets `InsecureSkipVerify = true` (which disables WebSocket origin checks in the library) when the allowed origin is `*`. CollabTable does not import this package, so it is not counted here, but its owners should review it.
|
||||||
- `shared/.githooks/post-commit` runs `shared/scripts/sync-consumers.ps1 -Commit` on commit once the hook path is configured (see `install-sync-hook.ps1`). `-Push` is opt-in (`sync-consumers.ps1:11-12` and `:370`). This is a developer-workflow concern rather than a runtime one.
|
- `shared/.githooks/post-commit` runs `shared/scripts/sync-consumers.ps1 -Commit` on commit once the hook path is configured (see `install-sync-hook.ps1`). `-Push` is opt-in (`sync-consumers.ps1:11-12` and `:370`). This is a developer-workflow concern rather than a runtime one.
|
||||||
@@ -78,3 +78,8 @@ NOTIF_RETENTION_MS=604800000
|
|||||||
SECRET=change-me-to-a-long-random-value
|
SECRET=change-me-to-a-long-random-value
|
||||||
# Set true only for local development or a standalone deployment.
|
# Set true only for local development or a standalone deployment.
|
||||||
AUTH_DISABLED=false
|
AUTH_DISABLED=false
|
||||||
|
|
||||||
|
# Optional initial values for shipping server log lines to OmniLogger. Shipping runs only when both are set.
|
||||||
|
# ProjectConfigurator normally supplies the ingest token at runtime, so these can stay empty.
|
||||||
|
OMNILOGGER_URL=
|
||||||
|
OMNILOGGER_INGEST_TOKEN=
|
||||||
+45
-15
@@ -60,6 +60,26 @@ go -C backend build -o collabtable-server .
|
|||||||
|
|
||||||
The Dockerfile performs those dashboard and Go build steps automatically.
|
The Dockerfile performs those dashboard and Go build steps automatically.
|
||||||
|
|
||||||
|
## One-time legacy user remap
|
||||||
|
|
||||||
|
Databases from before the AuthGuard migration key list memberships and API tokens by the old
|
||||||
|
local user IDs. After the migration each person's identity is their AuthGuard ID, which is
|
||||||
|
usually different, so they sign in and see none of the lists they owned. Run this once, with the
|
||||||
|
server stopped and before any AuthGuard account signs in:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# users.json: the array GET /api/auth/users returns, copied while signed in as an AuthGuard admin
|
||||||
|
collabtable-server remap-users --authguard-users users.json # dry run: prints the plan
|
||||||
|
collabtable-server remap-users --authguard-users users.json --apply # writes the remap
|
||||||
|
```
|
||||||
|
|
||||||
|
Legacy users are matched to AuthGuard accounts by email, or by username when the legacy account
|
||||||
|
has no email. For anything unmatched or ambiguous, pass `--map` with a JSON object from legacy ID to
|
||||||
|
AuthGuard ID, such as `{"3": 12}`. The tool refuses to write while a legacy user who owns rows is
|
||||||
|
unmapped, and it refuses a second run. If a legacy ID is also the ID of a different AuthGuard
|
||||||
|
account, the plan blocks until you pass `--accept-id-overlap`; use that only after confirming the
|
||||||
|
account has never signed in. `DATABASE_URL` must be set.
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
All Android synchronization routes are prefixed with `/api/` and require:
|
All Android synchronization routes are prefixed with `/api/` and require:
|
||||||
@@ -87,9 +107,11 @@ accounts can exist, with `user`/`admin`/`superadmin` roles managed via `/api/aut
|
|||||||
AuthGuard integration has three states: `AUTHGUARD_URL` set (used immediately); unset with
|
AuthGuard integration has three states: `AUTHGUARD_URL` set (used immediately); unset with
|
||||||
`AUTH_DISABLED` unset/false (the default -- "pending": auth stays fully enabled/gated, waiting
|
`AUTH_DISABLED` unset/false (the default -- "pending": auth stays fully enabled/gated, waiting
|
||||||
for ProjectConfigurator's push, failing closed on auth calls until then); or `AUTH_DISABLED=true`
|
for ProjectConfigurator's push, failing closed on auth calls until then); or `AUTH_DISABLED=true`
|
||||||
(authentication fully off -- no login screen, nothing gated). Only set `AUTH_DISABLED=true` for
|
(the browser-session gate is off). List access still requires membership. In this mode requests
|
||||||
local development or a deployment you are certain does not need access control. API tokens are
|
use placeholder identity 0, which has no list memberships, so the dashboard data is empty and
|
||||||
unrelated to AuthGuard (see below), hashed at rest, and shown only when generated.
|
sync API tokens for identity 0 are rejected. Use it only for local development of the auth shell,
|
||||||
|
not for a working data deployment. API tokens are unrelated to AuthGuard (see below), hashed at
|
||||||
|
rest, and shown only when generated.
|
||||||
|
|
||||||
### Data
|
### Data
|
||||||
|
|
||||||
@@ -106,6 +128,14 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
|||||||
- `POST /api/sync`
|
- `POST /api/sync`
|
||||||
- `GET /api/notifications/poll?since=<timestamp-ms>`
|
- `GET /api/notifications/poll?since=<timestamp-ms>`
|
||||||
|
|
||||||
|
The list, field, item and item-value collection GETs accept `limit` (default 200, maximum 500)
|
||||||
|
and an opaque `cursor`. They return `{ "items": [...], "nextCursor": "...", "hasMore": true }`;
|
||||||
|
continue with `nextCursor` while `hasMore` is true. The final page has an empty `nextCursor`.
|
||||||
|
`POST /api/sync` requires `lastSyncToken` (use `0` for the first sync) and returns at most 500
|
||||||
|
changes with `nextSyncToken` and `hasMore`. Clients must request each page until `hasMore` is
|
||||||
|
false. Older sync clients without `lastSyncToken` receive HTTP 400 and must be updated with the
|
||||||
|
server.
|
||||||
|
|
||||||
### Dashboard and health
|
### Dashboard and health
|
||||||
|
|
||||||
- `GET /health` is public.
|
- `GET /health` is public.
|
||||||
@@ -135,9 +165,9 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
|||||||
CollabTable authenticates against, default unset (pending). Leaving it unset does not disable
|
CollabTable authenticates against, default unset (pending). Leaving it unset does not disable
|
||||||
authentication -- it leaves the service "pending" until ProjectConfigurator pushes a URL,
|
authentication -- it leaves the service "pending" until ProjectConfigurator pushes a URL,
|
||||||
failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off.
|
failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off.
|
||||||
- `AUTH_DISABLED` — set `true` to disable authentication entirely (no login screen, nothing
|
- `AUTH_DISABLED` — set `true` to disable browser-session gates, default `false`. List access is
|
||||||
gated, every request treated as authenticated), default `false`. For local development or a
|
still membership-scoped; placeholder identity 0 has no memberships and its sync tokens are
|
||||||
standalone deployment with no AuthGuard integration at all.
|
rejected. Use only for local auth-shell development, not a working data deployment.
|
||||||
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
|
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
|
||||||
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
||||||
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
||||||
@@ -169,17 +199,17 @@ attribute. `Strict-Transport-Security` is not set here; set it at the TLS proxy.
|
|||||||
|
|
||||||
## Access model
|
## Access model
|
||||||
|
|
||||||
There is one shared data set. Lists, fields, items and values have no owner and no per-list
|
List, field, item and value reads and writes are scoped to `list_memberships`. On migration,
|
||||||
roles: any valid sync token can read, change and delete all of them, and any signed-in dashboard
|
every current API-token user is granted access to every existing list because the old schema did
|
||||||
user can see all of them. Tokens are per account only so that each can be regenerated on its own.
|
not store owners. Lists created afterward are owned only by their creator. There is currently no
|
||||||
Deleting an item, field or list removes its values for good, while the rows themselves are soft
|
API for owners to add or remove members, so a newly created list is private to its creator's
|
||||||
deleted. Per-list access would need a membership table checked in every handler; that has not
|
account and devices. Deleting an item, field or list still removes its values permanently, while
|
||||||
been decided.
|
the parent rows remain soft-deleted.
|
||||||
|
|
||||||
When login is off (`AUTH_DISABLED=true`, or the login-required switch turned off in
|
When login is off (`AUTH_DISABLED=true`, or the login-required switch turned off in
|
||||||
ProjectConfigurator), the dashboard data and user management need no session. Sync tokens are a
|
ProjectConfigurator), browser-session gates are bypassed. Data remains membership-scoped; the
|
||||||
separate matter: a caller without a session can only mint a token for the placeholder identity,
|
placeholder identity 0 has no memberships, so `/web/data` contains no lists. A caller without a
|
||||||
and the sync API refuses that identity.
|
session can only mint a token for that placeholder identity, and the sync API refuses it.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
+14
-1
@@ -146,11 +146,24 @@ func requireAPIToken(db *DB) func(http.Handler) http.Handler {
|
|||||||
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next.ServeHTTP(w, r)
|
ctx := context.WithValue(r.Context(), apiUserIDContextKey{}, userID)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type apiUserIDContextKey struct{}
|
||||||
|
|
||||||
|
func requestUserID(r *http.Request) int64 {
|
||||||
|
if userID, ok := r.Context().Value(apiUserIDContextKey{}).(int64); ok {
|
||||||
|
return userID
|
||||||
|
}
|
||||||
|
if user := sharedauth.UserFromContext(r.Context()); user != nil {
|
||||||
|
return user.ID
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
func extractBearer(r *http.Request) string {
|
func extractBearer(r *http.Request) string {
|
||||||
header := r.Header.Get("Authorization")
|
header := r.Header.Get("Authorization")
|
||||||
if !strings.HasPrefix(header, "Bearer ") {
|
if !strings.HasPrefix(header, "Bearer ") {
|
||||||
|
|||||||
+317
-83
@@ -65,15 +65,17 @@ func (d *DB) getList(ctx context.Context, id string) (List, error) {
|
|||||||
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64) ([]List, error) {
|
func (d *DB) queryLists(ctx context.Context, userID int64, includeDeleted bool, since *int64) ([]List, error) {
|
||||||
conditions := make([]string, 0, 2)
|
conditions := make([]string, 0, 3)
|
||||||
args := make([]any, 0, 1)
|
args := make([]any, 0, 2)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = lists.id AND m.user_id = $%d)", len(args)))
|
||||||
if !includeDeleted {
|
if !includeDeleted {
|
||||||
conditions = append(conditions, "isdeleted = 0")
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
}
|
}
|
||||||
if since != nil {
|
if since != nil {
|
||||||
conditions = append(conditions, "updatedat >= $1")
|
|
||||||
args = append(args, *since)
|
args = append(args, *since)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||||
}
|
}
|
||||||
query := `SELECT ` + listColumns + ` FROM lists`
|
query := `SELECT ` + listColumns + ` FROM lists`
|
||||||
if len(conditions) > 0 {
|
if len(conditions) > 0 {
|
||||||
@@ -98,9 +100,11 @@ func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64)
|
|||||||
return lists, rows.Err()
|
return lists, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
func (d *DB) queryFields(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||||
conditions := make([]string, 0, 3)
|
conditions := make([]string, 0, 4)
|
||||||
args := make([]any, 0, 2)
|
args := make([]any, 0, 3)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = fields.listid AND m.user_id = $%d)", len(args)))
|
||||||
if !includeDeleted {
|
if !includeDeleted {
|
||||||
conditions = append(conditions, "isdeleted = 0")
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
}
|
}
|
||||||
@@ -134,9 +138,11 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
|
|||||||
return fields, rows.Err()
|
return fields, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
func (d *DB) queryItems(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||||
conditions := make([]string, 0, 3)
|
conditions := make([]string, 0, 4)
|
||||||
args := make([]any, 0, 2)
|
args := make([]any, 0, 3)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = items.listid AND m.user_id = $%d)", len(args)))
|
||||||
if !includeDeleted {
|
if !includeDeleted {
|
||||||
conditions = append(conditions, "isdeleted = 0")
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
}
|
}
|
||||||
@@ -170,9 +176,11 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
|
|||||||
return items, rows.Err()
|
return items, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]ItemValue, error) {
|
func (d *DB) queryValues(ctx context.Context, userID int64, since *int64, itemID string) ([]ItemValue, error) {
|
||||||
conditions := make([]string, 0, 2)
|
conditions := make([]string, 0, 3)
|
||||||
args := make([]any, 0, 2)
|
args := make([]any, 0, 3)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM items i JOIN list_memberships m ON m.listid = i.listid WHERE i.id = item_values.itemid AND m.user_id = $%d)", len(args)))
|
||||||
if since != nil {
|
if since != nil {
|
||||||
args = append(args, *since)
|
args = append(args, *since)
|
||||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||||
@@ -353,7 +361,11 @@ type listMutation struct {
|
|||||||
|
|
||||||
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == http.MethodGet {
|
if r.Method == http.MethodGet {
|
||||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
page, ok := requestPage(w, r, "lists")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lists, err := s.db.queryListPage(r.Context(), requestUserID(r), false, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
||||||
return
|
return
|
||||||
@@ -371,15 +383,34 @@ func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
return err
|
||||||
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
}
|
||||||
|
if _, err := authorizeList(r.Context(), tx, requestUserID(r), request.ID, true); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := tx.Exec(r.Context(), `
|
||||||
|
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := addListOwner(r.Context(), tx, requestUserID(r), request.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
|
||||||
list, err := s.db.getList(r.Context(), request.ID)
|
list, err := s.db.getList(r.Context(), request.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||||
@@ -392,6 +423,9 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
id := r.PathValue("id")
|
id := r.PathValue("id")
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
|
if !s.requireListMembership(w, r, id) {
|
||||||
|
return
|
||||||
|
}
|
||||||
list, err := s.db.getList(r.Context(), id)
|
list, err := s.db.getList(r.Context(), id)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
@@ -416,17 +450,34 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
var list List
|
||||||
if err != nil {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
||||||
|
var scanErr error
|
||||||
|
list, scanErr = scanList(tx.QueryRow(r.Context(), `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||||
|
return scanErr
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
|
||||||
list, err := s.db.getList(r.Context(), id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||||
return
|
return
|
||||||
@@ -435,6 +486,16 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
case http.MethodDelete:
|
case http.MethodDelete:
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
result, err := tx.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
result, err := tx.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -448,7 +509,7 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -466,7 +527,15 @@ type fieldMutation struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
||||||
fields, err := s.db.queryFields(r.Context(), false, nil, r.PathValue("listId"))
|
listID := r.PathValue("listId")
|
||||||
|
if !s.requireListMembership(w, r, listID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, ok := requestPage(w, r, "fields")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fields, err := s.db.queryFieldsPage(r.Context(), requestUserID(r), false, listID, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
||||||
return
|
return
|
||||||
@@ -485,16 +554,36 @@ func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
INSERT INTO fields
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
return err
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
}
|
||||||
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), request.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(r.Context(), `
|
||||||
|
INSERT INTO fields
|
||||||
|
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||||
|
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
|
||||||
field, err := s.getField(r.Context(), request.ID)
|
field, err := s.getField(r.Context(), request.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||||
@@ -525,25 +614,49 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
result, err := s.db.pool.Exec(r.Context(), `
|
var field Field
|
||||||
UPDATE fields
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
WHERE id = $7
|
return err
|
||||||
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
}
|
||||||
if err != nil {
|
var listID string
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `
|
||||||
|
UPDATE fields
|
||||||
|
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
||||||
|
WHERE id = $7
|
||||||
|
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
var scanErr error
|
||||||
|
field, scanErr = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||||
|
if scanErr != nil {
|
||||||
|
return scanErr
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
field, err := s.getField(r.Context(), id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
|
||||||
writeJSON(w, http.StatusOK, field)
|
writeJSON(w, http.StatusOK, field)
|
||||||
case http.MethodDelete:
|
case http.MethodDelete:
|
||||||
var request struct {
|
var request struct {
|
||||||
@@ -554,11 +667,21 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
var field Field
|
var field Field
|
||||||
cascade := false
|
cascade := false
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
var err error
|
var err error
|
||||||
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), field.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -569,7 +692,7 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -594,7 +717,14 @@ func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
|||||||
listID = parts[1]
|
listID = parts[1]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
items, err := s.db.queryItems(r.Context(), false, nil, listID)
|
if !s.requireListMembership(w, r, listID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, ok := requestPage(w, r, "items")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, err := s.db.queryItemsPage(r.Context(), requestUserID(r), false, listID, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
||||||
return
|
return
|
||||||
@@ -612,15 +742,35 @@ func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, err := s.db.pool.Exec(r.Context(), `
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
return err
|
||||||
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), request.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(r.Context(), `
|
||||||
|
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
|
||||||
item, err := s.getItem(r.Context(), request.ID)
|
item, err := s.getItem(r.Context(), request.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||||
@@ -641,7 +791,23 @@ func (s *Server) handleValuesForItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
itemID = parts[0]
|
itemID = parts[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
values, err := s.db.queryValues(r.Context(), nil, itemID)
|
var listID string
|
||||||
|
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, itemID).Scan(&listID); err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||||
|
} else {
|
||||||
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !s.requireListMembership(w, r, listID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, ok := requestPage(w, r, "values")
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
values, err := s.db.queryValuesPage(r.Context(), requestUserID(r), itemID, page)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||||
return
|
return
|
||||||
@@ -662,27 +828,57 @@ func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Reques
|
|||||||
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
applied, err := upsertValue(r.Context(), s.db.pool, request.ItemValue, int64(request.UpdatedAt))
|
|
||||||
if err != nil {
|
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// An older write than the stored value changes nothing, so it notifies no one.
|
|
||||||
var listID string
|
|
||||||
if applied {
|
|
||||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
|
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var value ItemValue
|
var value ItemValue
|
||||||
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
&value.ID,
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
&value.ItemID,
|
return err
|
||||||
&value.FieldID,
|
}
|
||||||
&value.Value,
|
var fieldListID, itemListID string
|
||||||
&value.UpdatedAt,
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&fieldListID); err != nil {
|
||||||
)
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, request.ItemID).Scan(&itemListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fieldListID != itemListID {
|
||||||
|
return errCellIdentityMismatch
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), fieldListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
var storedItemID, storedFieldID string
|
||||||
|
storedErr := tx.QueryRow(r.Context(), `SELECT itemid, fieldid FROM item_values WHERE id = $1`, request.ID).Scan(&storedItemID, &storedFieldID)
|
||||||
|
if storedErr == nil && (storedItemID != request.ItemID || storedFieldID != request.FieldID) {
|
||||||
|
return errCellIdentityMismatch
|
||||||
|
}
|
||||||
|
if storedErr != nil && !errors.Is(storedErr, pgx.ErrNoRows) {
|
||||||
|
return storedErr
|
||||||
|
}
|
||||||
|
applied, err := upsertValue(r.Context(), tx, request.ItemValue, int64(request.UpdatedAt))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// An older write than the stored value changes nothing, so it notifies no one.
|
||||||
|
if applied {
|
||||||
|
var listID string
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||||
|
}
|
||||||
|
var scanErr error
|
||||||
|
value, scanErr = scanItemValue(tx.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID))
|
||||||
|
return scanErr
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, errListAccessDenied) || errors.Is(err, errCellIdentityMismatch) || errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "Item value not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -702,25 +898,63 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
updatedAt := time.Now().UnixMilli()
|
updatedAt := time.Now().UnixMilli()
|
||||||
if r.Method == http.MethodPut {
|
if r.Method == http.MethodPut {
|
||||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
var item Item
|
||||||
if err != nil {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
if result.RowsAffected() == 0 {
|
var listID string
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
result, err := tx.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.RowsAffected() == 0 {
|
||||||
|
return pgx.ErrNoRows
|
||||||
|
}
|
||||||
|
var scanErr error
|
||||||
|
item, scanErr = scanItem(tx.QueryRow(r.Context(), `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
|
||||||
|
if scanErr != nil {
|
||||||
|
return scanErr
|
||||||
|
}
|
||||||
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
item, err := s.getItem(r.Context(), id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
|
||||||
writeJSON(w, http.StatusOK, item)
|
writeJSON(w, http.StatusOK, item)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var listID string
|
||||||
|
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
result, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
result, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -738,7 +972,7 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
|||||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
+111
-3
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -35,6 +36,11 @@ func (d *DB) withTx(ctx context.Context, fn func(pgx.Tx) error) error {
|
|||||||
return sharedpostgres.WithTx(ctx, d.pool, fn)
|
return sharedpostgres.WithTx(ctx, d.pool, fn)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func lockChangeClock(ctx context.Context, tx pgx.Tx) error {
|
||||||
|
var token int64
|
||||||
|
return tx.QueryRow(ctx, `SELECT token FROM collabtable_sync_clock WHERE id = 1 FOR UPDATE`).Scan(&token)
|
||||||
|
}
|
||||||
|
|
||||||
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
||||||
// be used by the Go server without a separate migration step.
|
// be used by the Go server without a separate migration step.
|
||||||
func (d *DB) initSchema(ctx context.Context) error {
|
func (d *DB) initSchema(ctx context.Context) error {
|
||||||
@@ -44,7 +50,8 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
createdat BIGINT NOT NULL,
|
createdat BIGINT NOT NULL,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
isdeleted INTEGER NOT NULL DEFAULT 0
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS fields (
|
CREATE TABLE IF NOT EXISTS fields (
|
||||||
@@ -58,6 +65,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
createdat BIGINT NOT NULL,
|
createdat BIGINT NOT NULL,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0,
|
||||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -67,6 +75,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
createdat BIGINT NOT NULL,
|
createdat BIGINT NOT NULL,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0,
|
||||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -76,6 +85,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
fieldid TEXT NOT NULL,
|
fieldid TEXT NOT NULL,
|
||||||
value TEXT,
|
value TEXT,
|
||||||
updatedat BIGINT NOT NULL,
|
updatedat BIGINT NOT NULL,
|
||||||
|
change_token BIGINT NOT NULL DEFAULT 0,
|
||||||
FOREIGN KEY (itemid) REFERENCES items(id),
|
FOREIGN KEY (itemid) REFERENCES items(id),
|
||||||
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
||||||
);
|
);
|
||||||
@@ -88,6 +98,54 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
CREATE INDEX IF NOT EXISTS idx_fields_updatedat ON fields(updatedat);
|
CREATE INDEX IF NOT EXISTS idx_fields_updatedat ON fields(updatedat);
|
||||||
CREATE INDEX IF NOT EXISTS idx_items_updatedat ON items(updatedat);
|
CREATE INDEX IF NOT EXISTS idx_items_updatedat ON items(updatedat);
|
||||||
CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat);
|
CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_lists_page ON lists(updatedat DESC, id ASC) WHERE isdeleted = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fields_page ON fields(listid, "order" ASC, id ASC) WHERE isdeleted = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_items_page ON items(listid, updatedat DESC, id ASC) WHERE isdeleted = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_item_values_page ON item_values(itemid, updatedat ASC, id ASC);
|
||||||
|
ALTER TABLE lists ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE fields ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE items ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE item_values ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS collabtable_sync_clock (
|
||||||
|
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||||
|
token BIGINT NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
INSERT INTO collabtable_sync_clock (id, token) VALUES (1, 0) ON CONFLICT (id) DO NOTHING;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_lists_change_token ON lists(change_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fields_change_token ON fields(change_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_items_change_token ON items(change_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_item_values_change_token ON item_values(change_token);
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION collabtable_assign_change_token()
|
||||||
|
RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE next_token BIGINT;
|
||||||
|
BEGIN
|
||||||
|
UPDATE collabtable_sync_clock SET token = token + 1 WHERE id = 1 RETURNING token INTO next_token;
|
||||||
|
IF next_token IS NULL THEN
|
||||||
|
RAISE EXCEPTION 'sync clock row is missing';
|
||||||
|
END IF;
|
||||||
|
NEW.change_token := next_token;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'lists_change_token' AND tgrelid = 'lists'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER lists_change_token BEFORE INSERT OR UPDATE ON lists FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'fields_change_token' AND tgrelid = 'fields'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER fields_change_token BEFORE INSERT OR UPDATE ON fields FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'items_change_token' AND tgrelid = 'items'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER items_change_token BEFORE INSERT OR UPDATE ON items FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'item_values_change_token' AND tgrelid = 'item_values'::regclass AND NOT tgisinternal) THEN
|
||||||
|
EXECUTE 'CREATE TRIGGER item_values_change_token BEFORE INSERT OR UPDATE ON item_values FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||||
|
END IF;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS notifications (
|
CREATE TABLE IF NOT EXISTS notifications (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
@@ -190,14 +248,64 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
||||||
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
|
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS list_memberships (
|
||||||
|
listid TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
is_owner BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (listid, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_list_memberships_user ON list_memberships(user_id, listid);
|
||||||
`)
|
`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("initialize schema: %w", err)
|
return fmt.Errorf("initialize schema: %w", err)
|
||||||
}
|
}
|
||||||
|
if err := d.backfillChangeTokens(ctx); err != nil {
|
||||||
|
return fmt.Errorf("backfill change tokens: %w", err)
|
||||||
|
}
|
||||||
|
if err := d.backfillListMemberships(ctx); err != nil {
|
||||||
|
return fmt.Errorf("backfill list memberships: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *DB) backfillListMemberships(ctx context.Context) error {
|
||||||
|
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(ctx, tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO list_memberships (listid, user_id, is_owner)
|
||||||
|
SELECT lists.id, token_users.user_id, FALSE
|
||||||
|
FROM lists
|
||||||
|
CROSS JOIN (SELECT DISTINCT user_id FROM api_tokens WHERE user_id <> 0) AS token_users
|
||||||
|
-- New lists already have their creator's membership, so they are not
|
||||||
|
-- expanded to every token user on later starts.
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM list_memberships existing WHERE existing.listid = lists.id)
|
||||||
|
ON CONFLICT (listid, user_id) DO NOTHING
|
||||||
|
`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) backfillChangeTokens(ctx context.Context) error {
|
||||||
|
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(ctx, tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, table := range []string{"lists", "fields", "items", "item_values"} {
|
||||||
|
if _, err := tx.Exec(ctx, `UPDATE `+table+` SET change_token = change_token WHERE change_token = 0`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
||||||
ticker := time.NewTicker(time.Hour)
|
ticker := time.NewTicker(time.Hour)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
@@ -207,7 +315,7 @@ func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
||||||
fmt.Printf("[db] session prune failed: %v\n", err)
|
logPrintf(logshipper.LevelWarn, "[db] session prune failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,7 +335,7 @@ func (d *DB) cleanupNotifications(ctx context.Context) {
|
|||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
cutoff := time.Now().UnixMilli() - retention
|
cutoff := time.Now().UnixMilli() - retention
|
||||||
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
|
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
|
||||||
fmt.Printf("[db] notification cleanup failed: %v\n", err)
|
logPrintf(logshipper.LevelWarn, "[db] notification cleanup failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+299
-14
@@ -110,6 +110,10 @@ func newTestAPI(t *testing.T) *testAPI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRecorder {
|
func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRecorder {
|
||||||
|
return a.doAs(method, path, device, testBearer, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) doAs(method, path, device, token string, body any) *httptest.ResponseRecorder {
|
||||||
a.t.Helper()
|
a.t.Helper()
|
||||||
var reader *bytes.Reader
|
var reader *bytes.Reader
|
||||||
if body == nil {
|
if body == nil {
|
||||||
@@ -122,7 +126,7 @@ func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRe
|
|||||||
reader = bytes.NewReader(encoded)
|
reader = bytes.NewReader(encoded)
|
||||||
}
|
}
|
||||||
request := httptest.NewRequest(method, path, reader)
|
request := httptest.NewRequest(method, path, reader)
|
||||||
request.Header.Set("Authorization", "Bearer "+testBearer)
|
request.Header.Set("Authorization", "Bearer "+token)
|
||||||
if device != "" {
|
if device != "" {
|
||||||
request.Header.Set("X-Device-Id", device)
|
request.Header.Set("X-Device-Id", device)
|
||||||
}
|
}
|
||||||
@@ -140,6 +144,15 @@ func (a *testAPI) mustDo(method, path, device string, body any, wantStatus int)
|
|||||||
return recorder
|
return recorder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) mustDoAs(method, path, device, token string, body any, wantStatus int) *httptest.ResponseRecorder {
|
||||||
|
a.t.Helper()
|
||||||
|
recorder := a.doAs(method, path, device, token, body)
|
||||||
|
if recorder.Code != wantStatus {
|
||||||
|
a.t.Fatalf("%s %s status = %d, want %d; body %s", method, path, recorder.Code, wantStatus, recorder.Body.String())
|
||||||
|
}
|
||||||
|
return recorder
|
||||||
|
}
|
||||||
|
|
||||||
func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
var value T
|
var value T
|
||||||
@@ -151,10 +164,25 @@ func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
|||||||
|
|
||||||
func (a *testAPI) sync(device string, request SyncRequest) SyncResponse {
|
func (a *testAPI) sync(device string, request SyncRequest) SyncResponse {
|
||||||
a.t.Helper()
|
a.t.Helper()
|
||||||
|
if request.LastSyncToken == nil {
|
||||||
|
initialToken := int64(0)
|
||||||
|
request.LastSyncToken = &initialToken
|
||||||
|
}
|
||||||
request.DeviceID = device
|
request.DeviceID = device
|
||||||
return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK))
|
return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *testAPI) currentSyncToken() int64 {
|
||||||
|
a.t.Helper()
|
||||||
|
var token int64
|
||||||
|
if err := a.db.pool.QueryRow(context.Background(), `SELECT token FROM collabtable_sync_clock WHERE id = 1`).Scan(&token); err != nil {
|
||||||
|
a.t.Fatalf("read sync token: %v", err)
|
||||||
|
}
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
func ptrInt64(value int64) *int64 { return &value }
|
||||||
|
|
||||||
func (a *testAPI) count(query string, args ...any) int {
|
func (a *testAPI) count(query string, args ...any) int {
|
||||||
a.t.Helper()
|
a.t.Helper()
|
||||||
var n int
|
var n int
|
||||||
@@ -219,9 +247,38 @@ func (a *testAPI) seedList(device, prefix string) {
|
|||||||
|
|
||||||
func TestInitSchemaCanRunAgainstAnExistingDatabase(t *testing.T) {
|
func TestInitSchemaCanRunAgainstAnExistingDatabase(t *testing.T) {
|
||||||
db := testDB(t)
|
db := testDB(t)
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('backfill', 'Backfill', $1, $1)`, t0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists DISABLE TRIGGER lists_change_token`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `UPDATE lists SET change_token = 0 WHERE id = 'backfill'`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists ENABLE TRIGGER lists_change_token`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
if err := db.initSchema(context.Background()); err != nil {
|
if err := db.initSchema(context.Background()); err != nil {
|
||||||
t.Fatalf("second initSchema() error = %v", err)
|
t.Fatalf("second initSchema() error = %v", err)
|
||||||
}
|
}
|
||||||
|
var firstToken int64
|
||||||
|
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&firstToken); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if firstToken == 0 {
|
||||||
|
t.Fatal("initSchema left an existing list without a change token")
|
||||||
|
}
|
||||||
|
if err := db.initSchema(context.Background()); err != nil {
|
||||||
|
t.Fatalf("third initSchema() error = %v", err)
|
||||||
|
}
|
||||||
|
var secondToken int64
|
||||||
|
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&secondToken); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if secondToken != firstToken {
|
||||||
|
t.Fatalf("re-running initSchema changed backfilled token from %d to %d", firstToken, secondToken)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
||||||
@@ -240,21 +297,21 @@ func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
|||||||
t.Fatalf("orphanItemValues = %v, want none", full.OrphanItemValues)
|
t.Fatalf("orphanItemValues = %v, want none", full.OrphanItemValues)
|
||||||
}
|
}
|
||||||
|
|
||||||
// The delta filter is "updated at or after the cursor".
|
// The server returns a cursor from the same snapshot as its data page.
|
||||||
if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 11)}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 {
|
if got := api.sync("tablet", SyncRequest{LastSyncToken: &full.NextSyncToken}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 {
|
||||||
t.Fatalf("sync after the last change returned %+v, want nothing", got)
|
t.Fatalf("sync after the last change returned %+v, want nothing", got)
|
||||||
}
|
}
|
||||||
if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 10)}); len(got.Lists) != 1 || len(got.ItemValues) != 2 {
|
if got := api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(0)}); len(got.Lists) != 1 || len(got.ItemValues) != 2 {
|
||||||
t.Fatalf("sync at the change time returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues))
|
t.Fatalf("initial page returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues))
|
||||||
}
|
}
|
||||||
|
|
||||||
// The REST reads see the same data.
|
// The REST reads see the same data.
|
||||||
lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||||
if len(lists) != 1 || lists[0].Name != "Groceries" {
|
if len(lists.Items) != 1 || lists.Items[0].Name != "Groceries" || lists.HasMore {
|
||||||
t.Fatalf("GET /api/lists = %+v, want the pushed list", lists)
|
t.Fatalf("GET /api/lists = %+v, want the pushed list", lists)
|
||||||
}
|
}
|
||||||
values := decodeBody[[]ItemValue](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK))
|
values := decodeBody[PageResponse[ItemValue]](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK))
|
||||||
if len(values) != 2 {
|
if len(values.Items) != 2 || values.HasMore {
|
||||||
t.Fatalf("GET item values = %+v, want 2", values)
|
t.Fatalf("GET item values = %+v, want 2", values)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -274,6 +331,232 @@ func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCollectionEndpointsPageWithStableCursors(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
api.sync("phone", SyncRequest{
|
||||||
|
Lists: []List{testList("a-list", "A", t0+10, false)},
|
||||||
|
Items: []Item{testItem("a-item", "g-list", t0+10, false)},
|
||||||
|
})
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
endpoint string
|
||||||
|
decode func(*testing.T, *httptest.ResponseRecorder) (string, string, bool)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "lists",
|
||||||
|
endpoint: "/api/lists",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[List]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first list page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "fields",
|
||||||
|
endpoint: "/api/fields/list/g-list",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[Field]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first field page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "items",
|
||||||
|
endpoint: "/api/items/list/g-list",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[Item]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first item page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "values",
|
||||||
|
endpoint: "/api/items/g-item/values",
|
||||||
|
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||||
|
page := decodeBody[PageResponse[ItemValue]](t, recorder)
|
||||||
|
if len(page.Items) != 1 {
|
||||||
|
t.Fatalf("first value page has %d items, want 1", len(page.Items))
|
||||||
|
}
|
||||||
|
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
firstPath := test.endpoint + "?limit=1"
|
||||||
|
firstRecorder := api.mustDo(http.MethodGet, firstPath, "", nil, http.StatusOK)
|
||||||
|
firstID, cursor, hasMore := test.decode(t, firstRecorder)
|
||||||
|
if !hasMore || cursor == "" {
|
||||||
|
t.Fatalf("first page hasMore=%v cursor=%q, want another page", hasMore, cursor)
|
||||||
|
}
|
||||||
|
secondPath := firstPath + "&cursor=" + url.QueryEscape(cursor)
|
||||||
|
secondRecorder := api.mustDo(http.MethodGet, secondPath, "", nil, http.StatusOK)
|
||||||
|
secondID, nextCursor, hasMore := test.decode(t, secondRecorder)
|
||||||
|
if secondID == firstID {
|
||||||
|
t.Fatalf("cursor repeated item %q", firstID)
|
||||||
|
}
|
||||||
|
if hasMore || nextCursor != "" {
|
||||||
|
t.Fatalf("second page hasMore=%v cursor=%q, want final page", hasMore, nextCursor)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists?limit=501", "", nil, http.StatusBadRequest)
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists?cursor=not-a-cursor", "", nil, http.StatusBadRequest)
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists?cursor="+url.QueryEscape(encodePageCursor(pageCursor{Kind: "items", Key: 1, ID: "x"})), "", nil, http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncUsesServerChangeTokenInsteadOfClientTimestamp(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
cursor := api.currentSyncToken()
|
||||||
|
clientTimestamp := Timestamp(time.Now().UnixMilli())
|
||||||
|
|
||||||
|
response := api.sync("tablet", SyncRequest{
|
||||||
|
LastSyncTimestamp: clientTimestamp,
|
||||||
|
LastSyncToken: ptrInt64(cursor),
|
||||||
|
Lists: []List{testList("g-list", "Edited offline", t0+20, false)},
|
||||||
|
})
|
||||||
|
if len(response.Lists) != 1 || response.Lists[0].Name != "Edited offline" {
|
||||||
|
t.Fatalf("change with an old client timestamp = %+v, want the updated list", response.Lists)
|
||||||
|
}
|
||||||
|
if response.NextSyncToken <= cursor {
|
||||||
|
t.Fatalf("next sync token = %d, want greater than previous cursor %d", response.NextSyncToken, cursor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncBoundsAndPagesLargeInitialSync(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.mustDo(http.MethodPost, "/api/sync", "phone", map[string]any{}, http.StatusBadRequest)
|
||||||
|
lists := make([]List, 501)
|
||||||
|
for i := range lists {
|
||||||
|
id := fmt.Sprintf("list-%03d", i)
|
||||||
|
lists[i] = testList(id, id, t0+int64(i), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
first := api.sync("phone", SyncRequest{Lists: lists})
|
||||||
|
if len(first.Lists) != syncPageSize || !first.HasMore {
|
||||||
|
t.Fatalf("first page has lists=%d hasMore=%v, want %d and true", len(first.Lists), first.HasMore, syncPageSize)
|
||||||
|
}
|
||||||
|
if first.NextSyncToken <= 0 || first.NextSyncToken >= first.ServerChangeToken {
|
||||||
|
t.Fatalf("first page tokens are next=%d server=%d, want next before server high-water mark", first.NextSyncToken, first.ServerChangeToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
second := api.sync("phone", SyncRequest{LastSyncToken: ptrInt64(first.NextSyncToken)})
|
||||||
|
if len(second.Lists) != 1 || second.HasMore || second.NextSyncToken != second.ServerChangeToken {
|
||||||
|
t.Fatalf("second page has lists=%d hasMore=%v next=%d server=%d, want 1, false, and caught up", len(second.Lists), second.HasMore, second.NextSyncToken, second.ServerChangeToken)
|
||||||
|
}
|
||||||
|
if second.Lists[0].ID == first.Lists[len(first.Lists)-1].ID {
|
||||||
|
t.Fatalf("second page repeated list %q", second.Lists[0].ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPerListMembershipScopesDataAndSync(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
api.seedList("phone", "g")
|
||||||
|
const secondUserID = int64(2)
|
||||||
|
const secondToken = "second-user-device-token"
|
||||||
|
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken(secondToken)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
firstUserLists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||||
|
if len(firstUserLists.Items) != 1 || firstUserLists.Items[0].ID != "g-list" {
|
||||||
|
t.Fatalf("first user lists = %+v, want g-list", firstUserLists.Items)
|
||||||
|
}
|
||||||
|
secondUserLists := decodeBody[PageResponse[List]](t, api.mustDoAs(http.MethodGet, "/api/lists", "", secondToken, nil, http.StatusOK))
|
||||||
|
if len(secondUserLists.Items) != 0 {
|
||||||
|
t.Fatalf("second user lists = %+v, want no access to the first user's list", secondUserLists.Items)
|
||||||
|
}
|
||||||
|
api.mustDoAs(http.MethodGet, "/api/items/g-item/values", "", secondToken, nil, http.StatusNotFound)
|
||||||
|
|
||||||
|
foreignCursor := int64(0)
|
||||||
|
foreignSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken,
|
||||||
|
SyncRequest{LastSyncToken: &foreignCursor}, http.StatusOK))
|
||||||
|
if len(foreignSync.Lists)+len(foreignSync.Fields)+len(foreignSync.Items)+len(foreignSync.ItemValues) != 0 {
|
||||||
|
t.Fatalf("second user's initial sync returned another list's data: %+v", foreignSync)
|
||||||
|
}
|
||||||
|
|
||||||
|
api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
|
||||||
|
LastSyncToken: ptrInt64(0),
|
||||||
|
Lists: []List{testList("g-list", "Overwritten", t0+20, false)},
|
||||||
|
}, http.StatusNotFound)
|
||||||
|
var name string
|
||||||
|
if err := api.db.pool.QueryRow(context.Background(), `SELECT name FROM lists WHERE id = 'g-list'`).Scan(&name); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if name != "Groceries" {
|
||||||
|
t.Fatalf("unauthorized sync changed list name to %q", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
newListSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
|
||||||
|
LastSyncToken: ptrInt64(0),
|
||||||
|
Lists: []List{testList("second-list", "Private", t0+30, false)},
|
||||||
|
}, http.StatusOK))
|
||||||
|
if len(newListSync.Lists) != 1 || newListSync.Lists[0].ID != "second-list" {
|
||||||
|
t.Fatalf("creator's sync response = %+v, want only second-list", newListSync.Lists)
|
||||||
|
}
|
||||||
|
if !hasMembership(t, api.db, secondUserID, "second-list") || hasMembership(t, api.db, testUserID, "second-list") {
|
||||||
|
t.Fatal("new sync list was not private to its creator")
|
||||||
|
}
|
||||||
|
var creator bool
|
||||||
|
if err := api.db.pool.QueryRow(context.Background(), `SELECT is_owner FROM list_memberships WHERE listid = 'second-list' AND user_id = $1`, secondUserID).Scan(&creator); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !creator {
|
||||||
|
t.Fatal("new sync list did not mark its creator as owner")
|
||||||
|
}
|
||||||
|
api.mustDo(http.MethodGet, "/api/lists/second-list", "", nil, http.StatusNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMembershipBackfillPreservesCurrentAPITokenUsers(t *testing.T) {
|
||||||
|
api := newTestAPI(t)
|
||||||
|
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('legacy-list', 'Legacy', $1, $1)`, t0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
const secondUserID = int64(2)
|
||||||
|
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken("second-user-device-token")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := api.db.backfillListMemberships(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !hasMembership(t, api.db, testUserID, "legacy-list") || !hasMembership(t, api.db, secondUserID, "legacy-list") {
|
||||||
|
t.Fatal("membership migration did not grant every current API-token user access to the legacy list")
|
||||||
|
}
|
||||||
|
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('new-list', 'New', $1, $1)`, t0); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := api.db.withTx(context.Background(), func(tx pgx.Tx) error {
|
||||||
|
return addListOwner(context.Background(), tx, secondUserID, "new-list")
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := api.db.backfillListMemberships(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if hasMembership(t, api.db, testUserID, "new-list") {
|
||||||
|
t.Fatal("re-running membership backfill exposed a creator-owned list to another token user")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasMembership(t *testing.T, db *DB, userID int64, listID string) bool {
|
||||||
|
t.Helper()
|
||||||
|
member, err := hasListMembership(context.Background(), db.pool, userID, listID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return member
|
||||||
|
}
|
||||||
|
|
||||||
func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
||||||
api := newTestAPI(t)
|
api := newTestAPI(t)
|
||||||
push := func(name string, updatedAt int64) {
|
push := func(name string, updatedAt int64) {
|
||||||
@@ -307,9 +590,10 @@ func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
|||||||
func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
||||||
api := newTestAPI(t)
|
api := newTestAPI(t)
|
||||||
api.seedList("phone", "g")
|
api.seedList("phone", "g")
|
||||||
|
seedCursor := api.currentSyncToken()
|
||||||
const kept = "list=0 fields=0/2 items=0/1 values=2"
|
const kept = "list=0 fields=0/2 items=0/1 values=2"
|
||||||
|
|
||||||
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+5, true)}})
|
api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(seedCursor), Lists: []List{testList("g-list", "Groceries", t0+5, true)}})
|
||||||
if got := api.cascadeState("g-list"); got != kept {
|
if got := api.cascadeState("g-list"); got != kept {
|
||||||
t.Fatalf("state after a stale delete = %s, want %s", got, kept)
|
t.Fatalf("state after a stale delete = %s, want %s", got, kept)
|
||||||
}
|
}
|
||||||
@@ -317,7 +601,7 @@ func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
|||||||
t.Fatalf("a stale delete produced %d deleted notification(s)", got)
|
t.Fatalf("a stale delete produced %d deleted notification(s)", got)
|
||||||
}
|
}
|
||||||
|
|
||||||
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+20, true)}})
|
api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(seedCursor), Lists: []List{testList("g-list", "Groceries", t0+20, true)}})
|
||||||
if got, want := api.cascadeState("g-list"), "list=1 fields=2/2 items=1/1 values=0"; got != want {
|
if got, want := api.cascadeState("g-list"), "list=1 fields=2/2 items=1/1 values=0"; got != want {
|
||||||
t.Fatalf("state after a newer delete = %s, want %s (fields and items soft-deleted, values removed)", got, want)
|
t.Fatalf("state after a newer delete = %s, want %s (fields and items soft-deleted, values removed)", got, want)
|
||||||
}
|
}
|
||||||
@@ -326,11 +610,11 @@ func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The tombstone travels to other devices, but the REST list read hides it.
|
// The tombstone travels to other devices, but the REST list read hides it.
|
||||||
delta := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 15)})
|
delta := api.sync("phone", SyncRequest{LastSyncToken: ptrInt64(seedCursor)})
|
||||||
if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted {
|
if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted {
|
||||||
t.Fatalf("delta after the delete = %+v, want the tombstone", delta.Lists)
|
t.Fatalf("delta after the delete = %+v, want the tombstone", delta.Lists)
|
||||||
}
|
}
|
||||||
if lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists) != 0 {
|
if lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists.Items) != 0 {
|
||||||
t.Fatalf("GET /api/lists = %+v, want the deleted list hidden", lists)
|
t.Fatalf("GET /api/lists = %+v, want the deleted list hidden", lists)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -466,13 +750,14 @@ func TestRESTValueWriteIgnoresAnOlderTimestamp(t *testing.T) {
|
|||||||
func TestWebDataSupportsConditionalRequests(t *testing.T) {
|
func TestWebDataSupportsConditionalRequests(t *testing.T) {
|
||||||
api := newTestAPI(t)
|
api := newTestAPI(t)
|
||||||
api.seedList("phone", "g")
|
api.seedList("phone", "g")
|
||||||
|
server := &Server{db: api.db}
|
||||||
get := func(etag string) *httptest.ResponseRecorder {
|
get := func(etag string) *httptest.ResponseRecorder {
|
||||||
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
||||||
if etag != "" {
|
if etag != "" {
|
||||||
request.Header.Set("If-None-Match", etag)
|
request.Header.Set("If-None-Match", etag)
|
||||||
}
|
}
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
api.mux.ServeHTTP(recorder, request)
|
server.writeWebData(recorder, request, testUserID)
|
||||||
return recorder
|
return recorder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -11,7 +11,7 @@ replace repos.gfranz.ch/Gabriel20xx/shared/backend => ../shared/backend
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/go-chi/chi/v5 v5.3.1 // indirect
|
github.com/go-chi/chi/v5 v5.3.1 // indirect
|
||||||
golang.org/x/crypto v0.54.0 // indirect
|
golang.org/x/crypto v0.55.0 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -19,6 +19,6 @@ require (
|
|||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // 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
|
||||||
repos.gfranz.ch/Gabriel20xx/shared/backend v0.1.1
|
repos.gfranz.ch/Gabriel20xx/shared/backend v0.1.1
|
||||||
)
|
)
|
||||||
+4
-4
@@ -20,12 +20,12 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
|||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
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/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=
|
||||||
|
|||||||
+16
-6
@@ -86,6 +86,7 @@ type ItemValue struct {
|
|||||||
|
|
||||||
type SyncRequest struct {
|
type SyncRequest struct {
|
||||||
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
||||||
|
LastSyncToken *int64 `json:"lastSyncToken"`
|
||||||
Lists []List `json:"lists"`
|
Lists []List `json:"lists"`
|
||||||
Fields []Field `json:"fields"`
|
Fields []Field `json:"fields"`
|
||||||
Items []Item `json:"items"`
|
Items []Item `json:"items"`
|
||||||
@@ -94,12 +95,21 @@ type SyncRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SyncResponse struct {
|
type SyncResponse struct {
|
||||||
Lists []List `json:"lists"`
|
Lists []List `json:"lists"`
|
||||||
Fields []Field `json:"fields"`
|
Fields []Field `json:"fields"`
|
||||||
Items []Item `json:"items"`
|
Items []Item `json:"items"`
|
||||||
ItemValues []ItemValue `json:"itemValues"`
|
ItemValues []ItemValue `json:"itemValues"`
|
||||||
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
||||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||||
|
ServerChangeToken int64 `json:"serverChangeToken"`
|
||||||
|
NextSyncToken int64 `json:"nextSyncToken"`
|
||||||
|
HasMore bool `json:"hasMore"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PageResponse[T any] struct {
|
||||||
|
Items []T `json:"items"`
|
||||||
|
NextCursor string `json:"nextCursor"`
|
||||||
|
HasMore bool `json:"hasMore"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type OrphanValue struct {
|
type OrphanValue struct {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import (
|
|||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
)
|
)
|
||||||
|
|
||||||
type queryExecutor interface {
|
type queryExecutor interface {
|
||||||
@@ -79,10 +81,6 @@ func ignoreNotificationError(err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
// Notifications are an acceleration path for clients that poll. A failed
|
// Notifications are an acceleration path for clients that poll. A failed
|
||||||
// notification must never roll back the data mutation that produced it.
|
// notification must never roll back the data mutation that produced it.
|
||||||
fmt.Printf("[notifications] enqueue failed: %v\n", err)
|
logPrintf(logshipper.LevelWarn, "[notifications] enqueue failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func isNoRows(err error) bool {
|
|
||||||
return err == pgx.ErrNoRows
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
|
)
|
||||||
|
|
||||||
|
// omniShipper mirrors the server's console lines to OmniLogger. It is always set: with no OMNILOGGER_URL or
|
||||||
|
// OMNILOGGER_INGEST_TOKEN it is disabled and ships nothing, until main hands it ProjectConfigurator's
|
||||||
|
// pushed token (see omniShipper.Follow in server.go).
|
||||||
|
var omniShipper = newOmniLoggerShipper()
|
||||||
|
|
||||||
|
// newOmniLoggerShipper returns a shipper for OmniLogger. OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are
|
||||||
|
// optional initial values; ProjectConfigurator normally supplies the token at runtime.
|
||||||
|
func newOmniLoggerShipper() *logshipper.Shipper {
|
||||||
|
return logshipper.New(logshipper.Config{
|
||||||
|
BaseURL: strings.TrimSpace(os.Getenv("OMNILOGGER_URL")),
|
||||||
|
IngestToken: strings.TrimSpace(os.Getenv("OMNILOGGER_INGEST_TOKEN")),
|
||||||
|
Service: "collabtable",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// stdoutLog and stderrLog are the Loggers behind the helpers below. Each writes its line to its console stream
|
||||||
|
// exactly as the fmt function it replaced did, and ships the line to OmniLogger at the severity the caller names.
|
||||||
|
var (
|
||||||
|
stdoutLog = newConsoleLogger(os.Stdout, omniShipper)
|
||||||
|
stderrLog = newConsoleLogger(os.Stderr, omniShipper)
|
||||||
|
)
|
||||||
|
|
||||||
|
// newConsoleLogger returns a Logger for console. NewLogger copies the standard logger's flags, and these helper
|
||||||
|
// lines have never carried a timestamp, so the flags are cleared only while the Logger is made. The standard
|
||||||
|
// logger keeps its own flags.
|
||||||
|
func newConsoleLogger(console io.Writer, shipper *logshipper.Shipper) *logshipper.Logger {
|
||||||
|
previous := log.Flags()
|
||||||
|
log.SetFlags(0)
|
||||||
|
defer log.SetFlags(previous)
|
||||||
|
return logshipper.NewLogger(console, shipper)
|
||||||
|
}
|
||||||
|
|
||||||
|
// logPrintf, logPrintln, logErrorf and logErrorln write to stdout or stderr exactly as the fmt functions
|
||||||
|
// they wrap, and also ship the line to OmniLogger when shipping is enabled, at the severity the caller
|
||||||
|
// names. The console stream is the one the helper always used, whatever the severity.
|
||||||
|
func logPrintf(sev logshipper.Level, format string, args ...any) {
|
||||||
|
logLine(stdoutLog, sev, fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logPrintln(sev logshipper.Level, args ...any) {
|
||||||
|
logLine(stdoutLog, sev, fmt.Sprintln(args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logErrorf(sev logshipper.Level, format string, args ...any) {
|
||||||
|
logLine(stderrLog, sev, fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logErrorln(sev logshipper.Level, args ...any) {
|
||||||
|
logLine(stderrLog, sev, fmt.Sprintln(args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// logLine writes msg to l's console and ships it at sev. msg keeps the newline its fmt call added, so the console
|
||||||
|
// line is the same bytes as before. Levels outside the five OmniLogger knows are reported as errors.
|
||||||
|
func logLine(l *logshipper.Logger, sev logshipper.Level, msg string) {
|
||||||
|
switch sev {
|
||||||
|
case logshipper.LevelDebug:
|
||||||
|
l.Debugf("%s", msg)
|
||||||
|
case logshipper.LevelInfo:
|
||||||
|
l.Infof("%s", msg)
|
||||||
|
case logshipper.LevelWarn:
|
||||||
|
l.Warnf("%s", msg)
|
||||||
|
case logshipper.LevelCritical:
|
||||||
|
l.Criticalf("%s", msg)
|
||||||
|
default:
|
||||||
|
l.Errorf("%s", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// exitAfterFlush sends the buffered log lines to OmniLogger and then exits. Use it instead of os.Exit after a
|
||||||
|
// line that must reach OmniLogger, such as a critical startup failure, which os.Exit would otherwise lose.
|
||||||
|
func exitAfterFlush(code int) {
|
||||||
|
omniShipper.Flush()
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeOmniLogger is a stand-in OmniLogger that accepts only the bearer token it was started with and
|
||||||
|
// records every entry it receives.
|
||||||
|
type fakeOmniLogger struct {
|
||||||
|
*httptest.Server
|
||||||
|
mu sync.Mutex
|
||||||
|
requests int
|
||||||
|
entries []map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFakeOmniLogger(t *testing.T, token string) *fakeOmniLogger {
|
||||||
|
t.Helper()
|
||||||
|
f := &fakeOmniLogger{}
|
||||||
|
f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
f.requests++
|
||||||
|
f.mu.Unlock()
|
||||||
|
if r.Header.Get("Authorization") != "Bearer "+token {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var batch []map[string]any
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&batch); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f.mu.Lock()
|
||||||
|
f.entries = append(f.entries, batch...)
|
||||||
|
f.mu.Unlock()
|
||||||
|
w.WriteHeader(http.StatusAccepted)
|
||||||
|
}))
|
||||||
|
t.Cleanup(f.Close)
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
// received reports how many requests arrived and the entries that were accepted.
|
||||||
|
func (f *fakeOmniLogger) received() (int, []map[string]any) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
return f.requests, append([]map[string]any(nil), f.entries...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// hasMessage reports whether an entry for the collabtable service contains text.
|
||||||
|
func hasMessage(entries []map[string]any, text string) bool {
|
||||||
|
for _, entry := range entries {
|
||||||
|
message, _ := entry["message"].(string)
|
||||||
|
if entry["service"] == "collabtable" && strings.Contains(message, text) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// useOmniShipper makes shipper the package's omniShipper for the rest of the test. The helper Loggers are rebuilt
|
||||||
|
// on it with their consoles discarded, since they are made once at start-up and would otherwise keep the old shipper.
|
||||||
|
func useOmniShipper(t *testing.T, shipper *logshipper.Shipper) {
|
||||||
|
t.Helper()
|
||||||
|
previous, previousOut, previousErr := omniShipper, stdoutLog, stderrLog
|
||||||
|
omniShipper = shipper
|
||||||
|
stdoutLog = newConsoleLogger(io.Discard, shipper)
|
||||||
|
stderrLog = newConsoleLogger(io.Discard, shipper)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = shipper.Close()
|
||||||
|
omniShipper = previous
|
||||||
|
stdoutLog, stderrLog = previousOut, previousErr
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOmniLoggerShipperIsNeverNilAndDisabledWithoutConfig(t *testing.T) {
|
||||||
|
if omniShipper == nil {
|
||||||
|
t.Fatal("omniShipper must never be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Setenv("OMNILOGGER_URL", "")
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "")
|
||||||
|
shipper := newOmniLoggerShipper()
|
||||||
|
if shipper == nil {
|
||||||
|
t.Fatal("shipper must never be nil; with no configuration it is simply disabled")
|
||||||
|
}
|
||||||
|
useOmniShipper(t, shipper)
|
||||||
|
logPrintf(logshipper.LevelInfo, "no configuration, nothing should ship\n")
|
||||||
|
shipper.Flush()
|
||||||
|
|
||||||
|
// A URL without a token is still disabled, so nothing reaches a reachable OmniLogger.
|
||||||
|
sink := newFakeOmniLogger(t, "test-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", sink.URL)
|
||||||
|
shipper = newOmniLoggerShipper()
|
||||||
|
useOmniShipper(t, shipper)
|
||||||
|
logPrintf(logshipper.LevelInfo, "no token, nothing should ship\n")
|
||||||
|
shipper.Flush()
|
||||||
|
if requests, _ := sink.received(); requests != 0 {
|
||||||
|
t.Fatalf("disabled shipper sent %d requests to OmniLogger", requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogPrintfReachesOmniLogger(t *testing.T) {
|
||||||
|
sink := newFakeOmniLogger(t, "test-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", sink.URL)
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "test-token")
|
||||||
|
useOmniShipper(t, newOmniLoggerShipper())
|
||||||
|
|
||||||
|
logPrintf(logshipper.LevelInfo, "[test] hello from collabtable %d\n", 7)
|
||||||
|
_ = omniShipper.Close()
|
||||||
|
|
||||||
|
if _, entries := sink.received(); !hasMessage(entries, "hello from collabtable 7") {
|
||||||
|
t.Fatalf("OmniLogger did not receive the line; entries: %v", entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOmniLoggerFollowsCoreConfigPush(t *testing.T) {
|
||||||
|
sink := newFakeOmniLogger(t, "pushed-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", "")
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "")
|
||||||
|
shipper := newOmniLoggerShipper()
|
||||||
|
useOmniShipper(t, shipper)
|
||||||
|
store := coreconfig.NewStore(coreconfig.Info{})
|
||||||
|
shipper.Follow(store)
|
||||||
|
|
||||||
|
logPrintf(logshipper.LevelInfo, "before the push\n")
|
||||||
|
shipper.Flush()
|
||||||
|
if requests, _ := sink.received(); requests != 0 {
|
||||||
|
t.Fatalf("shipper sent %d requests before ProjectConfigurator pushed a token", requests)
|
||||||
|
}
|
||||||
|
|
||||||
|
store.Set(coreconfig.Info{OmniLoggerURL: sink.URL, OmniLoggerIngestToken: "pushed-token"})
|
||||||
|
logPrintf(logshipper.LevelInfo, "after the push\n")
|
||||||
|
_ = shipper.Close()
|
||||||
|
|
||||||
|
_, entries := sink.received()
|
||||||
|
if !hasMessage(entries, "after the push") {
|
||||||
|
t.Fatalf("OmniLogger did not receive the line after the push; entries: %v", entries)
|
||||||
|
}
|
||||||
|
if hasMessage(entries, "before the push") {
|
||||||
|
t.Fatal("a line logged before the push was shipped")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConvertedNotificationLineShipsOnceAtWarnAndKeepsConsoleLine runs a converted call site: a failed
|
||||||
|
// notification is printed on stdout as before, and reaches OmniLogger once, at warn.
|
||||||
|
func TestConvertedNotificationLineShipsOnceAtWarnAndKeepsConsoleLine(t *testing.T) {
|
||||||
|
sink := newFakeOmniLogger(t, "test-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", sink.URL)
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "test-token")
|
||||||
|
useOmniShipper(t, newOmniLoggerShipper())
|
||||||
|
|
||||||
|
reader, writer, err := os.Pipe()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
previousStdout := stdoutLog
|
||||||
|
stdoutLog = newConsoleLogger(writer, omniShipper)
|
||||||
|
ignoreNotificationError(errors.New("disk full"))
|
||||||
|
stdoutLog = previousStdout
|
||||||
|
_ = writer.Close()
|
||||||
|
console, _ := io.ReadAll(reader)
|
||||||
|
_ = reader.Close()
|
||||||
|
if got, want := string(console), "[notifications] enqueue failed: disk full\n"; got != want {
|
||||||
|
t.Fatalf("console output = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = omniShipper.Close()
|
||||||
|
_, entries := sink.received()
|
||||||
|
var levels []string
|
||||||
|
for _, entry := range entries {
|
||||||
|
message, _ := entry["message"].(string)
|
||||||
|
if entry["service"] == "collabtable" && message == "[notifications] enqueue failed: disk full" {
|
||||||
|
level, _ := entry["level"].(string)
|
||||||
|
levels = append(levels, level)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(levels) != 1 || levels[0] != "warn" {
|
||||||
|
t.Fatalf("OmniLogger levels for the notification line = %v, want exactly one warn (entries %v)", levels, entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errListAccessDenied = errors.New("list access denied")
|
||||||
|
errCellIdentityMismatch = errors.New("item and field belong to different lists")
|
||||||
|
)
|
||||||
|
|
||||||
|
type rowQueryer interface {
|
||||||
|
QueryRow(context.Context, string, ...any) pgx.Row
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasListMembership(ctx context.Context, queryer rowQueryer, userID int64, listID string) (bool, error) {
|
||||||
|
var member bool
|
||||||
|
err := queryer.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM list_memberships WHERE listid = $1 AND user_id = $2)`, listID, userID).Scan(&member)
|
||||||
|
return member, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func authorizeList(ctx context.Context, queryer rowQueryer, userID int64, listID string, allowCreate bool) (bool, error) {
|
||||||
|
if userID <= 0 || listID == "" {
|
||||||
|
return false, errListAccessDenied
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, queryer, userID, listID)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if member {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
var exists bool
|
||||||
|
if err := queryer.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM lists WHERE id = $1)`, listID).Scan(&exists); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if exists || !allowCreate {
|
||||||
|
return false, errListAccessDenied
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func addListOwner(ctx context.Context, tx pgx.Tx, userID int64, listID string) error {
|
||||||
|
_, err := tx.Exec(ctx, `INSERT INTO list_memberships (listid, user_id, is_owner) VALUES ($1, $2, TRUE) ON CONFLICT (listid, user_id) DO NOTHING`, listID, userID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) requireListMembership(w http.ResponseWriter, r *http.Request, listID string) bool {
|
||||||
|
member, err := hasListMembership(r.Context(), s.db.pool, requestUserID(r), listID)
|
||||||
|
if err != nil {
|
||||||
|
writeJSONError(w, http.StatusInternalServerError, "Failed to authorize list")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultPageSize = 200
|
||||||
|
maxPageSize = 500
|
||||||
|
)
|
||||||
|
|
||||||
|
type pageCursor struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Key int64 `json:"key"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type pageRequest struct {
|
||||||
|
Limit int
|
||||||
|
Cursor *pageCursor
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePageRequest(r *http.Request, kind string) (pageRequest, error) {
|
||||||
|
page := pageRequest{Limit: defaultPageSize}
|
||||||
|
if rawLimit := r.URL.Query().Get("limit"); rawLimit != "" {
|
||||||
|
limit, err := strconv.Atoi(rawLimit)
|
||||||
|
if err != nil || limit < 1 || limit > maxPageSize {
|
||||||
|
return pageRequest{}, fmt.Errorf("limit must be between 1 and %d", maxPageSize)
|
||||||
|
}
|
||||||
|
page.Limit = limit
|
||||||
|
}
|
||||||
|
if rawCursor := r.URL.Query().Get("cursor"); rawCursor != "" {
|
||||||
|
decoded, err := base64.RawURLEncoding.DecodeString(rawCursor)
|
||||||
|
if err != nil {
|
||||||
|
return pageRequest{}, errors.New("cursor is invalid")
|
||||||
|
}
|
||||||
|
var cursor pageCursor
|
||||||
|
if err := json.Unmarshal(decoded, &cursor); err != nil || cursor.Kind != kind || cursor.ID == "" {
|
||||||
|
return pageRequest{}, errors.New("cursor is invalid")
|
||||||
|
}
|
||||||
|
page.Cursor = &cursor
|
||||||
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestPage(w http.ResponseWriter, r *http.Request, kind string) (pageRequest, bool) {
|
||||||
|
page, err := parsePageRequest(r, kind)
|
||||||
|
if err != nil {
|
||||||
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return pageRequest{}, false
|
||||||
|
}
|
||||||
|
return page, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodePageCursor(cursor pageCursor) string {
|
||||||
|
encoded, _ := json.Marshal(cursor)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(encoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readPage[T any](rows pgx.Rows, request pageRequest, kind string, scan func(rowScanner) (T, error), key func(T) int64, id func(T) string) (PageResponse[T], error) {
|
||||||
|
defer rows.Close()
|
||||||
|
items := make([]T, 0, request.Limit+1)
|
||||||
|
for rows.Next() {
|
||||||
|
item, err := scan(rows)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[T]{}, err
|
||||||
|
}
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return PageResponse[T]{}, err
|
||||||
|
}
|
||||||
|
hasMore := len(items) > request.Limit
|
||||||
|
if hasMore {
|
||||||
|
items = items[:request.Limit]
|
||||||
|
}
|
||||||
|
response := PageResponse[T]{Items: items, HasMore: hasMore}
|
||||||
|
if hasMore {
|
||||||
|
last := items[len(items)-1]
|
||||||
|
response.NextCursor = encodePageCursor(pageCursor{Kind: kind, Key: key(last), ID: id(last)})
|
||||||
|
}
|
||||||
|
return response, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func addPageCursor(conditions *[]string, args *[]any, column string, direction string, cursor *pageCursor) {
|
||||||
|
if cursor == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
*args = append(*args, cursor.Key)
|
||||||
|
keyParam := len(*args)
|
||||||
|
*args = append(*args, cursor.ID)
|
||||||
|
idParam := len(*args)
|
||||||
|
comparison := ">"
|
||||||
|
if direction == "desc" {
|
||||||
|
comparison = "<"
|
||||||
|
}
|
||||||
|
*conditions = append(*conditions, fmt.Sprintf("(%s %s $%d OR (%s = $%d AND id > $%d))", column, comparison, keyParam, column, keyParam, idParam))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryListPage(ctx context.Context, userID int64, includeDeleted bool, request pageRequest) (PageResponse[List], error) {
|
||||||
|
conditions := make([]string, 0, 3)
|
||||||
|
args := make([]any, 0, 4)
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = lists.id AND m.user_id = $%d)", len(args)))
|
||||||
|
if !includeDeleted {
|
||||||
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
|
}
|
||||||
|
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + listColumns + ` FROM lists`
|
||||||
|
if len(conditions) > 0 {
|
||||||
|
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||||
|
}
|
||||||
|
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[List]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "lists", scanList, func(item List) int64 { return int64(item.UpdatedAt) }, func(item List) string { return item.ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryFieldsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Field], error) {
|
||||||
|
conditions := make([]string, 0, 4)
|
||||||
|
args := make([]any, 0, 5)
|
||||||
|
if !includeDeleted {
|
||||||
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
|
}
|
||||||
|
args = append(args, listID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = fields.listid AND m.user_id = $%d)", len(args)))
|
||||||
|
addPageCursor(&conditions, &args, `"order"`, "asc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + fieldColumns + ` FROM fields WHERE ` + strings.Join(conditions, " AND ")
|
||||||
|
query += fmt.Sprintf(` ORDER BY "order" ASC, id ASC LIMIT $%d`, len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[Field]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "fields", scanField, func(item Field) int64 { return int64(item.Order) }, func(item Field) string { return item.ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryItemsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Item], error) {
|
||||||
|
conditions := make([]string, 0, 4)
|
||||||
|
args := make([]any, 0, 5)
|
||||||
|
if !includeDeleted {
|
||||||
|
conditions = append(conditions, "isdeleted = 0")
|
||||||
|
}
|
||||||
|
args = append(args, listID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = items.listid AND m.user_id = $%d)", len(args)))
|
||||||
|
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + itemColumns + ` FROM items WHERE ` + strings.Join(conditions, " AND ")
|
||||||
|
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[Item]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "items", scanItem, func(item Item) int64 { return int64(item.UpdatedAt) }, func(item Item) string { return item.ID })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) queryValuesPage(ctx context.Context, userID int64, itemID string, request pageRequest) (PageResponse[ItemValue], error) {
|
||||||
|
conditions := make([]string, 0, 2)
|
||||||
|
args := make([]any, 0, 4)
|
||||||
|
args = append(args, itemID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("itemid = $%d", len(args)))
|
||||||
|
args = append(args, userID)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM items i JOIN list_memberships m ON m.listid = i.listid WHERE i.id = item_values.itemid AND m.user_id = $%d)", len(args)))
|
||||||
|
addPageCursor(&conditions, &args, "updatedat", "asc", request.Cursor)
|
||||||
|
args = append(args, request.Limit+1)
|
||||||
|
query := `SELECT ` + valueColumns + ` FROM item_values WHERE ` + strings.Join(conditions, " AND ")
|
||||||
|
query += fmt.Sprintf(" ORDER BY updatedat ASC, id ASC LIMIT $%d", len(args))
|
||||||
|
rows, err := d.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return PageResponse[ItemValue]{}, err
|
||||||
|
}
|
||||||
|
return readPage(rows, request, "values", scanItemValue, func(item ItemValue) int64 { return int64(item.UpdatedAt) }, func(item ItemValue) string { return item.ID })
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParsePageRequest(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
query string
|
||||||
|
wantLimit int
|
||||||
|
wantCursor *pageCursor
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "defaults", wantLimit: defaultPageSize},
|
||||||
|
{name: "custom limit", query: "limit=17", wantLimit: 17},
|
||||||
|
{name: "maximum limit", query: "limit=500", wantLimit: 500},
|
||||||
|
{name: "zero limit", query: "limit=0", wantErr: true},
|
||||||
|
{name: "oversized limit", query: "limit=501", wantErr: true},
|
||||||
|
{name: "invalid limit", query: "limit=large", wantErr: true},
|
||||||
|
{
|
||||||
|
name: "cursor",
|
||||||
|
query: "cursor=" + encodePageCursor(pageCursor{Kind: "lists", Key: 123, ID: "list-1"}),
|
||||||
|
wantLimit: defaultPageSize,
|
||||||
|
wantCursor: &pageCursor{Kind: "lists", Key: 123, ID: "list-1"},
|
||||||
|
},
|
||||||
|
{name: "malformed cursor", query: "cursor=not-a-cursor", wantErr: true},
|
||||||
|
{
|
||||||
|
name: "cursor for another collection",
|
||||||
|
query: "cursor=" + encodePageCursor(pageCursor{Kind: "items", Key: 123, ID: "item-1"}),
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
request := httptest.NewRequest("GET", "/api/lists?"+test.query, nil)
|
||||||
|
got, err := parsePageRequest(request, "lists")
|
||||||
|
if (err != nil) != test.wantErr {
|
||||||
|
t.Fatalf("parsePageRequest() error = %v, wantErr %v", err, test.wantErr)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got.Limit != test.wantLimit {
|
||||||
|
t.Fatalf("limit = %d, want %d", got.Limit, test.wantLimit)
|
||||||
|
}
|
||||||
|
if test.wantCursor == nil {
|
||||||
|
if got.Cursor != nil {
|
||||||
|
t.Fatalf("cursor = %+v, want none", got.Cursor)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got.Cursor == nil || *got.Cursor != *test.wantCursor {
|
||||||
|
t.Fatalf("cursor = %+v, want %+v", got.Cursor, test.wantCursor)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,528 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"maps"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"text/tabwriter"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Legacy user remap
|
||||||
|
// =================
|
||||||
|
//
|
||||||
|
// Before the AuthGuard migration, list_memberships.user_id and api_tokens.user_id
|
||||||
|
// held IDs from this database's own auth_users table. Identity now comes from
|
||||||
|
// AuthGuard, whose IDs come from a different sequence, so the same person signs in
|
||||||
|
// with a different ID and sees none of the lists they owned. This one-time tool
|
||||||
|
// rewrites each legacy ID to the AuthGuard ID of the same person.
|
||||||
|
//
|
||||||
|
// Stop the server first, and run the tool before any AuthGuard account signs in.
|
||||||
|
// Once accounts sign in, new rows are keyed by AuthGuard IDs, and they cannot be
|
||||||
|
// told apart from legacy rows that happen to share the same number:
|
||||||
|
//
|
||||||
|
// collabtable-server remap-users --authguard-users users.json # dry run
|
||||||
|
// collabtable-server remap-users --authguard-users users.json --apply
|
||||||
|
//
|
||||||
|
// users.json is the array GET /api/auth/users returns, copied while signed in to
|
||||||
|
// the dashboard as an AuthGuard admin. A legacy user is matched by email, or by
|
||||||
|
// username when the legacy account has no email. Anything unmatched or ambiguous
|
||||||
|
// needs a --map entry: a JSON object from legacy ID to AuthGuard ID, such as
|
||||||
|
// {"3": 12}.
|
||||||
|
//
|
||||||
|
// The plan refuses to write while a legacy user who still owns rows has no
|
||||||
|
// mapping, so no data is left keyed to an ID nobody can use. The write is one
|
||||||
|
// transaction that also records each mapping in collabtable_user_remap. A database
|
||||||
|
// that already has recorded mappings is refused, because a second pass would move
|
||||||
|
// rows that the first pass already moved.
|
||||||
|
|
||||||
|
// legacyUser is one row of the pre-migration auth_users table.
|
||||||
|
type legacyUser struct {
|
||||||
|
ID int64
|
||||||
|
Username string
|
||||||
|
Email string
|
||||||
|
}
|
||||||
|
|
||||||
|
// authGuardAccount is one entry of the AuthGuard user list the operator exports.
|
||||||
|
type authGuardAccount struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ownedRows counts the rows one identity holds in the two tables the remap rewrites.
|
||||||
|
type ownedRows struct {
|
||||||
|
Memberships int64
|
||||||
|
Tokens int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o ownedRows) total() int64 {
|
||||||
|
return o.Memberships + o.Tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
// remapEntry is the decision for one legacy user. Target is nil when the user is not
|
||||||
|
// mapped. Status says how the decision was made: matched, override, unmatched or
|
||||||
|
// ambiguous.
|
||||||
|
type remapEntry struct {
|
||||||
|
Legacy legacyUser
|
||||||
|
Target *authGuardAccount
|
||||||
|
Status string
|
||||||
|
Owned ownedRows
|
||||||
|
}
|
||||||
|
|
||||||
|
// remapPair is one legacy ID and the AuthGuard ID its rows move to.
|
||||||
|
type remapPair struct {
|
||||||
|
Legacy int64
|
||||||
|
AuthGuard int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// remapPlan is what a dry run prints. Problems stop --apply; warnings do not.
|
||||||
|
type remapPlan struct {
|
||||||
|
Entries []remapEntry
|
||||||
|
Problems []string
|
||||||
|
Warnings []string
|
||||||
|
}
|
||||||
|
|
||||||
|
var errUserRemapApplied = errors.New("the legacy user remap has already been applied to this database")
|
||||||
|
|
||||||
|
// planUserRemap decides where each legacy user goes. It reads only its arguments, so
|
||||||
|
// the rules can be tested without a database. legacy must be sorted by ID. owned is
|
||||||
|
// keyed by user ID across both tables.
|
||||||
|
func planUserRemap(legacy []legacyUser, accounts []authGuardAccount, overrides map[int64]int64, owned map[int64]ownedRows, acceptOverlap bool) remapPlan {
|
||||||
|
var plan remapPlan
|
||||||
|
accountByID := make(map[int64]authGuardAccount, len(accounts))
|
||||||
|
for _, account := range accounts {
|
||||||
|
accountByID[account.ID] = account
|
||||||
|
}
|
||||||
|
legacyByID := make(map[int64]legacyUser, len(legacy))
|
||||||
|
for _, user := range legacy {
|
||||||
|
legacyByID[user.ID] = user
|
||||||
|
}
|
||||||
|
for _, id := range slices.Sorted(maps.Keys(overrides)) {
|
||||||
|
if _, ok := legacyByID[id]; !ok {
|
||||||
|
plan.Problems = append(plan.Problems, fmt.Sprintf("--map names legacy user %d, which is not in auth_users", id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
claimedBy := make(map[int64]int64)
|
||||||
|
for _, user := range legacy {
|
||||||
|
entry := remapEntry{Legacy: user, Owned: owned[user.ID]}
|
||||||
|
if target, ok := overrides[user.ID]; ok {
|
||||||
|
entry.Status = "override"
|
||||||
|
if account, found := accountByID[target]; found {
|
||||||
|
entry.Target = &account
|
||||||
|
} else {
|
||||||
|
plan.Problems = append(plan.Problems, fmt.Sprintf("--map sends legacy user %d to AuthGuard %d, which is not in the account list", user.ID, target))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
matches := matchAuthGuardAccounts(user, accounts)
|
||||||
|
switch len(matches) {
|
||||||
|
case 0:
|
||||||
|
entry.Status = "unmatched"
|
||||||
|
case 1:
|
||||||
|
entry.Status = "matched"
|
||||||
|
entry.Target = &matches[0]
|
||||||
|
default:
|
||||||
|
entry.Status = "ambiguous"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if entry.Target == nil && entry.Owned.total() > 0 {
|
||||||
|
plan.Problems = append(plan.Problems, fmt.Sprintf("legacy user %d (%s) owns %d rows but is %s; map it with --map", user.ID, user.Username, entry.Owned.total(), entry.Status))
|
||||||
|
}
|
||||||
|
if target := entry.Target; target != nil {
|
||||||
|
if other, taken := claimedBy[target.ID]; taken {
|
||||||
|
plan.Problems = append(plan.Problems, fmt.Sprintf("legacy users %d and %d both map to AuthGuard %d", other, user.ID, target.ID))
|
||||||
|
}
|
||||||
|
claimedBy[target.ID] = user.ID
|
||||||
|
if _, clash := accountByID[user.ID]; clash && target.ID != user.ID && entry.Owned.total() > 0 {
|
||||||
|
message := fmt.Sprintf("rows keyed %d may belong to AuthGuard account %d, which has that ID", user.ID, user.ID)
|
||||||
|
if acceptOverlap {
|
||||||
|
plan.Warnings = append(plan.Warnings, message)
|
||||||
|
} else {
|
||||||
|
plan.Problems = append(plan.Problems, message+"; if that account has never signed in, pass --accept-id-overlap")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
plan.Entries = append(plan.Entries, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
var unknown []int64
|
||||||
|
for _, id := range slices.Sorted(maps.Keys(owned)) {
|
||||||
|
if _, isLegacy := legacyByID[id]; !isLegacy && id != 0 {
|
||||||
|
unknown = append(unknown, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(unknown) > 0 {
|
||||||
|
plan.Warnings = append(plan.Warnings, fmt.Sprintf("rows keyed by IDs that are not legacy users are left unchanged: %v", unknown))
|
||||||
|
}
|
||||||
|
return plan
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchAuthGuardAccounts returns the AuthGuard accounts that identify the same person
|
||||||
|
// as a legacy user: the same email when the legacy account has one, otherwise the
|
||||||
|
// same username.
|
||||||
|
func matchAuthGuardAccounts(user legacyUser, accounts []authGuardAccount) []authGuardAccount {
|
||||||
|
var matches []authGuardAccount
|
||||||
|
for _, account := range accounts {
|
||||||
|
same := sameText(account.Username, user.Username)
|
||||||
|
if strings.TrimSpace(user.Email) != "" {
|
||||||
|
same = sameText(account.Email, user.Email)
|
||||||
|
}
|
||||||
|
if same {
|
||||||
|
matches = append(matches, account)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matches
|
||||||
|
}
|
||||||
|
|
||||||
|
// sameText compares ignoring case and surrounding spaces. An empty value never matches.
|
||||||
|
func sameText(a, b string) bool {
|
||||||
|
a, b = strings.TrimSpace(a), strings.TrimSpace(b)
|
||||||
|
return a != "" && strings.EqualFold(a, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadAuthGuardAccounts reads the AuthGuard account list. IDs must be positive and
|
||||||
|
// unique, since either problem would make the matching meaningless.
|
||||||
|
func loadAuthGuardAccounts(path string) ([]authGuardAccount, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read --authguard-users: %w", err)
|
||||||
|
}
|
||||||
|
var accounts []authGuardAccount
|
||||||
|
if err := json.Unmarshal(data, &accounts); err != nil {
|
||||||
|
return nil, fmt.Errorf("parse --authguard-users: expected a JSON array of accounts: %w", err)
|
||||||
|
}
|
||||||
|
seen := make(map[int64]bool, len(accounts))
|
||||||
|
for _, account := range accounts {
|
||||||
|
if account.ID <= 0 {
|
||||||
|
return nil, fmt.Errorf("--authguard-users contains an account with ID %d", account.ID)
|
||||||
|
}
|
||||||
|
if seen[account.ID] {
|
||||||
|
return nil, fmt.Errorf("--authguard-users lists AuthGuard ID %d twice", account.ID)
|
||||||
|
}
|
||||||
|
seen[account.ID] = true
|
||||||
|
}
|
||||||
|
return accounts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadRemapOverrides reads the optional --map file, a JSON object from legacy ID to
|
||||||
|
// AuthGuard ID. An empty path means no overrides.
|
||||||
|
func loadRemapOverrides(path string) (map[int64]int64, error) {
|
||||||
|
overrides := make(map[int64]int64)
|
||||||
|
if path == "" {
|
||||||
|
return overrides, nil
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read --map: %w", err)
|
||||||
|
}
|
||||||
|
var raw map[string]int64
|
||||||
|
if err := json.Unmarshal(data, &raw); err != nil {
|
||||||
|
return nil, fmt.Errorf("parse --map: expected a JSON object of legacy ID to AuthGuard ID: %w", err)
|
||||||
|
}
|
||||||
|
for key, target := range raw {
|
||||||
|
id, err := strconv.ParseInt(key, 10, 64)
|
||||||
|
if err != nil || id <= 0 {
|
||||||
|
return nil, fmt.Errorf("--map key %q is not a legacy user ID", key)
|
||||||
|
}
|
||||||
|
if target <= 0 {
|
||||||
|
return nil, fmt.Errorf("--map value for legacy user %d must be a positive AuthGuard ID", id)
|
||||||
|
}
|
||||||
|
overrides[id] = target
|
||||||
|
}
|
||||||
|
return overrides, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// legacyUsers reads the pre-migration accounts, oldest first.
|
||||||
|
func (d *DB) legacyUsers(ctx context.Context) ([]legacyUser, error) {
|
||||||
|
rows, err := d.pool.Query(ctx, `SELECT id, username, email FROM auth_users ORDER BY id`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read auth_users: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
users := make([]legacyUser, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var user legacyUser
|
||||||
|
if err := rows.Scan(&user.ID, &user.Username, &user.Email); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
users = append(users, user)
|
||||||
|
}
|
||||||
|
return users, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ownedRowCounts counts rows per user ID in list_memberships and api_tokens.
|
||||||
|
func (d *DB) ownedRowCounts(ctx context.Context) (map[int64]ownedRows, error) {
|
||||||
|
memberships, err := d.countRowsByUser(ctx, `SELECT user_id, count(*) FROM list_memberships GROUP BY user_id`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tokens, err := d.countRowsByUser(ctx, `SELECT user_id, count(*) FROM api_tokens GROUP BY user_id`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
owned := make(map[int64]ownedRows)
|
||||||
|
for id, count := range memberships {
|
||||||
|
row := owned[id]
|
||||||
|
row.Memberships = count
|
||||||
|
owned[id] = row
|
||||||
|
}
|
||||||
|
for id, count := range tokens {
|
||||||
|
row := owned[id]
|
||||||
|
row.Tokens = count
|
||||||
|
owned[id] = row
|
||||||
|
}
|
||||||
|
return owned, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DB) countRowsByUser(ctx context.Context, query string) (map[int64]int64, error) {
|
||||||
|
rows, err := d.pool.Query(ctx, query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("count rows by user: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
counts := make(map[int64]int64)
|
||||||
|
for rows.Next() {
|
||||||
|
var id, count int64
|
||||||
|
if err := rows.Scan(&id, &count); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
counts[id] = count
|
||||||
|
}
|
||||||
|
return counts, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// userRemapAppliedCount reports how many mappings an earlier run recorded. The table
|
||||||
|
// is created on the first apply, so a database that was never remapped has none.
|
||||||
|
func (d *DB) userRemapAppliedCount(ctx context.Context) (int64, error) {
|
||||||
|
var exists bool
|
||||||
|
if err := d.pool.QueryRow(ctx, `SELECT to_regclass('collabtable_user_remap') IS NOT NULL`).Scan(&exists); err != nil {
|
||||||
|
return 0, fmt.Errorf("check collabtable_user_remap: %w", err)
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
var count int64
|
||||||
|
if err := d.pool.QueryRow(ctx, `SELECT count(*) FROM collabtable_user_remap`).Scan(&count); err != nil {
|
||||||
|
return 0, fmt.Errorf("count collabtable_user_remap: %w", err)
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyUserRemap moves every row keyed by a legacy ID to its AuthGuard ID in one
|
||||||
|
// transaction, then records the mappings. The plan was read before this runs, and
|
||||||
|
// the server may have written since, so the stranded-row rule is checked again under
|
||||||
|
// the lock.
|
||||||
|
func (d *DB) applyUserRemap(ctx context.Context, pairs []remapPair) error {
|
||||||
|
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||||
|
// SHARE ROW EXCLUSIVE blocks concurrent writers while rows move and still lets
|
||||||
|
// readers run.
|
||||||
|
if _, err := tx.Exec(ctx, `LOCK TABLE list_memberships, api_tokens IN SHARE ROW EXCLUSIVE MODE`); err != nil {
|
||||||
|
return fmt.Errorf("lock identity tables: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS collabtable_user_remap (
|
||||||
|
legacy_id BIGINT PRIMARY KEY,
|
||||||
|
authguard_id BIGINT NOT NULL,
|
||||||
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
)`); err != nil {
|
||||||
|
return fmt.Errorf("create collabtable_user_remap: %w", err)
|
||||||
|
}
|
||||||
|
var applied int64
|
||||||
|
if err := tx.QueryRow(ctx, `SELECT count(*) FROM collabtable_user_remap`).Scan(&applied); err != nil {
|
||||||
|
return fmt.Errorf("read collabtable_user_remap: %w", err)
|
||||||
|
}
|
||||||
|
if applied > 0 {
|
||||||
|
return errUserRemapApplied
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := tx.Exec(ctx, `CREATE TEMP TABLE remap_pairs (old_id BIGINT PRIMARY KEY, new_id BIGINT NOT NULL) ON COMMIT DROP`); err != nil {
|
||||||
|
return fmt.Errorf("create remap_pairs: %w", err)
|
||||||
|
}
|
||||||
|
for _, pair := range pairs {
|
||||||
|
if _, err := tx.Exec(ctx, `INSERT INTO remap_pairs (old_id, new_id) VALUES ($1, $2)`, pair.Legacy, pair.AuthGuard); err != nil {
|
||||||
|
return fmt.Errorf("stage remap %d to %d: %w", pair.Legacy, pair.AuthGuard, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var stranded int64
|
||||||
|
if err := tx.QueryRow(ctx, `
|
||||||
|
SELECT count(*) FROM (
|
||||||
|
SELECT user_id FROM list_memberships
|
||||||
|
UNION ALL
|
||||||
|
SELECT user_id FROM api_tokens
|
||||||
|
) AS owned
|
||||||
|
WHERE owned.user_id IN (SELECT id FROM auth_users)
|
||||||
|
AND owned.user_id NOT IN (SELECT old_id FROM remap_pairs)`).Scan(&stranded); err != nil {
|
||||||
|
return fmt.Errorf("check for unmapped legacy rows: %w", err)
|
||||||
|
}
|
||||||
|
if stranded > 0 {
|
||||||
|
return fmt.Errorf("%d rows are keyed by legacy IDs with no mapping", stranded)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rows leave list_memberships in one statement and return in the next. If the
|
||||||
|
// two were one statement, an insert could conflict with a row that the same
|
||||||
|
// statement is deleting, when a legacy ID maps onto another legacy ID.
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
CREATE TEMP TABLE moved_memberships (
|
||||||
|
listid TEXT NOT NULL,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
is_owner BOOLEAN NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
) ON COMMIT DROP`); err != nil {
|
||||||
|
return fmt.Errorf("create moved_memberships: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
WITH moved AS (
|
||||||
|
DELETE FROM list_memberships AS m
|
||||||
|
USING remap_pairs AS p
|
||||||
|
WHERE m.user_id = p.old_id
|
||||||
|
RETURNING m.listid, p.new_id AS user_id, m.is_owner, m.created_at
|
||||||
|
)
|
||||||
|
INSERT INTO moved_memberships (listid, user_id, is_owner, created_at)
|
||||||
|
SELECT listid, user_id, is_owner, created_at FROM moved`); err != nil {
|
||||||
|
return fmt.Errorf("move memberships: %w", err)
|
||||||
|
}
|
||||||
|
// An AuthGuard account that already holds a row on the same list keeps that row.
|
||||||
|
// Ownership from either side is kept.
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO list_memberships (listid, user_id, is_owner, created_at)
|
||||||
|
SELECT listid, user_id, is_owner, created_at FROM moved_memberships
|
||||||
|
ON CONFLICT (listid, user_id) DO UPDATE SET is_owner = list_memberships.is_owner OR EXCLUDED.is_owner`); err != nil {
|
||||||
|
return fmt.Errorf("restore memberships: %w", err)
|
||||||
|
}
|
||||||
|
// Tokens move with their owner. Sync resolves a device token to the same
|
||||||
|
// identity its memberships use, so the two must change together.
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
UPDATE api_tokens AS t
|
||||||
|
SET user_id = p.new_id
|
||||||
|
FROM remap_pairs AS p
|
||||||
|
WHERE t.user_id = p.old_id`); err != nil {
|
||||||
|
return fmt.Errorf("move API tokens: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
INSERT INTO collabtable_user_remap (legacy_id, authguard_id)
|
||||||
|
SELECT old_id, new_id FROM remap_pairs`); err != nil {
|
||||||
|
return fmt.Errorf("record remap: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// runRemapUsers implements `collabtable-server remap-users` and returns the exit code.
|
||||||
|
func runRemapUsers(args []string, out io.Writer) int {
|
||||||
|
flags := flag.NewFlagSet("remap-users", flag.ContinueOnError)
|
||||||
|
accountsPath := flags.String("authguard-users", "", "JSON array of AuthGuard accounts, as returned by GET /api/auth/users (required)")
|
||||||
|
overridesPath := flags.String("map", "", `optional JSON object from legacy ID to AuthGuard ID, for example {"3": 12}`)
|
||||||
|
apply := flags.Bool("apply", false, "write the remap; without it only the plan is printed")
|
||||||
|
acceptOverlap := flags.Bool("accept-id-overlap", false, "acknowledge the ID-overlap problems after checking that those AuthGuard accounts have never signed in")
|
||||||
|
if err := flags.Parse(args); err != nil {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if *accountsPath == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "remap-users: --authguard-users is required")
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
accounts, err := loadAuthGuardAccounts(*accountsPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
overrides, err := loadRemapOverrides(*overridesPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
|
if connectionString == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "remap-users: DATABASE_URL environment variable is required")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
database, err := connectDB(ctx, connectionString)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: connect: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
defer database.close()
|
||||||
|
|
||||||
|
applied, err := database.userRemapAppliedCount(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if applied > 0 {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v (%d mappings recorded); nothing to do\n", errUserRemapApplied, applied)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
legacy, err := database.legacyUsers(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
owned, err := database.ownedRowCounts(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
plan := planUserRemap(legacy, accounts, overrides, owned, *acceptOverlap)
|
||||||
|
printRemapPlan(out, plan)
|
||||||
|
if len(plan.Problems) > 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "remap-users: not writing; resolve the problems above first")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if !*apply {
|
||||||
|
fmt.Fprintln(out, "dry run: nothing written. Re-run with --apply to write the remap.")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
var pairs []remapPair
|
||||||
|
for _, entry := range plan.Entries {
|
||||||
|
if entry.Target != nil {
|
||||||
|
pairs = append(pairs, remapPair{Legacy: entry.Legacy.ID, AuthGuard: entry.Target.ID})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(pairs) == 0 {
|
||||||
|
fmt.Fprintln(out, "no legacy users are mapped; nothing to write")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if err := database.applyUserRemap(ctx, pairs); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "remap-users: %v; nothing was written\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(out, "remapped %d legacy users\n", len(pairs))
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// printRemapPlan writes the plan as a table, then its warnings and problems.
|
||||||
|
func printRemapPlan(out io.Writer, plan remapPlan) {
|
||||||
|
table := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0)
|
||||||
|
fmt.Fprintln(table, "LEGACY\tUSERNAME\tEMAIL\tAUTHGUARD\tAUTHGUARD USERNAME\tSTATUS\tMEMBERSHIPS\tTOKENS")
|
||||||
|
for _, entry := range plan.Entries {
|
||||||
|
target, targetName := "-", "-"
|
||||||
|
if entry.Target != nil {
|
||||||
|
target = strconv.FormatInt(entry.Target.ID, 10)
|
||||||
|
targetName = entry.Target.Username
|
||||||
|
}
|
||||||
|
fmt.Fprintf(table, "%d\t%s\t%s\t%s\t%s\t%s\t%d\t%d\n",
|
||||||
|
entry.Legacy.ID, entry.Legacy.Username, entry.Legacy.Email, target, targetName,
|
||||||
|
entry.Status, entry.Owned.Memberships, entry.Owned.Tokens)
|
||||||
|
}
|
||||||
|
_ = table.Flush()
|
||||||
|
for _, warning := range plan.Warnings {
|
||||||
|
fmt.Fprintf(out, "warning: %s\n", warning)
|
||||||
|
}
|
||||||
|
for _, problem := range plan.Problems {
|
||||||
|
fmt.Fprintf(out, "problem: %s\n", problem)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"maps"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPlanUserRemapMatchesByEmailThenUsername(t *testing.T) {
|
||||||
|
legacy := []legacyUser{
|
||||||
|
{ID: 1, Username: "alice", Email: "Alice@Example.com"},
|
||||||
|
{ID: 2, Username: "bob"},
|
||||||
|
{ID: 3, Username: "carol", Email: "carol@old.example"},
|
||||||
|
}
|
||||||
|
accounts := []authGuardAccount{
|
||||||
|
{ID: 10, Username: "alice2", Email: "alice@example.com"},
|
||||||
|
{ID: 11, Username: "Bob", Email: "bob@example.com"},
|
||||||
|
{ID: 12, Username: "carol", Email: "carol@new.example"},
|
||||||
|
}
|
||||||
|
|
||||||
|
plan := planUserRemap(legacy, accounts, nil, nil, false)
|
||||||
|
|
||||||
|
if len(plan.Problems) != 0 {
|
||||||
|
t.Fatalf("unexpected problems: %v", plan.Problems)
|
||||||
|
}
|
||||||
|
want := []struct {
|
||||||
|
status string
|
||||||
|
target int64
|
||||||
|
}{{"matched", 10}, {"matched", 11}, {"unmatched", 0}}
|
||||||
|
for i, entry := range plan.Entries {
|
||||||
|
if entry.Status != want[i].status || entryTargetID(entry) != want[i].target {
|
||||||
|
t.Fatalf("legacy %d: got status %q target %d, want %q target %d",
|
||||||
|
entry.Legacy.ID, entry.Status, entryTargetID(entry), want[i].status, want[i].target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapBlocksAmbiguousOwners(t *testing.T) {
|
||||||
|
legacy := []legacyUser{
|
||||||
|
{ID: 4, Username: "dave", Email: "dave@example.com"},
|
||||||
|
{ID: 5, Username: "erin"},
|
||||||
|
}
|
||||||
|
accounts := []authGuardAccount{
|
||||||
|
{ID: 20, Username: "dave-a", Email: "dave@example.com"},
|
||||||
|
{ID: 21, Username: "dave-b", Email: "dave@example.com"},
|
||||||
|
}
|
||||||
|
owned := map[int64]ownedRows{4: {Memberships: 2}}
|
||||||
|
|
||||||
|
plan := planUserRemap(legacy, accounts, nil, owned, false)
|
||||||
|
|
||||||
|
if len(plan.Problems) != 1 || !strings.Contains(plan.Problems[0], "ambiguous") {
|
||||||
|
t.Fatalf("want one ambiguous-owner problem, got %v", plan.Problems)
|
||||||
|
}
|
||||||
|
if plan.Entries[1].Status != "unmatched" {
|
||||||
|
t.Fatalf("erin owns nothing, so an unmatched user must not block; got %+v", plan.Entries[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapGuardsIDOverlap(t *testing.T) {
|
||||||
|
// Each legacy user's new ID is the other's legacy ID, so rows keyed 1 and 2
|
||||||
|
// could belong to either person.
|
||||||
|
legacy := []legacyUser{
|
||||||
|
{ID: 1, Username: "alice", Email: "alice@example.com"},
|
||||||
|
{ID: 2, Username: "bob", Email: "bob@example.com"},
|
||||||
|
}
|
||||||
|
accounts := []authGuardAccount{
|
||||||
|
{ID: 1, Username: "bob", Email: "bob@example.com"},
|
||||||
|
{ID: 2, Username: "alice", Email: "alice@example.com"},
|
||||||
|
}
|
||||||
|
owned := map[int64]ownedRows{1: {Memberships: 1}, 2: {Tokens: 1}}
|
||||||
|
|
||||||
|
blocked := planUserRemap(legacy, accounts, nil, owned, false)
|
||||||
|
if len(blocked.Problems) != 2 || !strings.Contains(blocked.Problems[0], "--accept-id-overlap") {
|
||||||
|
t.Fatalf("want two overlap problems without acceptance, got %v", blocked.Problems)
|
||||||
|
}
|
||||||
|
|
||||||
|
accepted := planUserRemap(legacy, accounts, nil, owned, true)
|
||||||
|
if len(accepted.Problems) != 0 || len(accepted.Warnings) != 2 {
|
||||||
|
t.Fatalf("want two warnings and no problems with acceptance, got problems %v warnings %v",
|
||||||
|
accepted.Problems, accepted.Warnings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapRejectsDuplicateTargets(t *testing.T) {
|
||||||
|
legacy := []legacyUser{
|
||||||
|
{ID: 1, Username: "alice"},
|
||||||
|
{ID: 2, Username: "bob"},
|
||||||
|
}
|
||||||
|
accounts := []authGuardAccount{{ID: 9, Username: "shared"}}
|
||||||
|
|
||||||
|
plan := planUserRemap(legacy, accounts, map[int64]int64{1: 9, 2: 9}, nil, false)
|
||||||
|
|
||||||
|
if len(plan.Problems) != 1 || !strings.Contains(plan.Problems[0], "both map to AuthGuard 9") {
|
||||||
|
t.Fatalf("want one duplicate-target problem, got %v", plan.Problems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapOverrides(t *testing.T) {
|
||||||
|
legacy := []legacyUser{{ID: 3, Username: "carol", Email: "carol@old.example"}}
|
||||||
|
accounts := []authGuardAccount{{ID: 12, Username: "carol", Email: "carol@new.example"}}
|
||||||
|
owned := map[int64]ownedRows{3: {Memberships: 1}}
|
||||||
|
|
||||||
|
mapped := planUserRemap(legacy, accounts, map[int64]int64{3: 12}, owned, false)
|
||||||
|
if len(mapped.Problems) != 0 || mapped.Entries[0].Status != "override" || entryTargetID(mapped.Entries[0]) != 12 {
|
||||||
|
t.Fatalf("override should map 3 to 12 without problems, got %+v problems %v", mapped.Entries, mapped.Problems)
|
||||||
|
}
|
||||||
|
|
||||||
|
missingAccount := planUserRemap(legacy, accounts, map[int64]int64{3: 99}, owned, false)
|
||||||
|
if len(missingAccount.Problems) == 0 || !strings.Contains(missingAccount.Problems[0], "not in the account list") {
|
||||||
|
t.Fatalf("override to an unknown AuthGuard ID must be a problem, got %v", missingAccount.Problems)
|
||||||
|
}
|
||||||
|
|
||||||
|
unknownLegacy := planUserRemap(legacy, accounts, map[int64]int64{8: 12}, nil, false)
|
||||||
|
if len(unknownLegacy.Problems) != 1 || !strings.Contains(unknownLegacy.Problems[0], "not in auth_users") {
|
||||||
|
t.Fatalf("override naming an unknown legacy user must be a problem, got %v", unknownLegacy.Problems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUserRemapReportsUnknownOwnersWithoutBlocking(t *testing.T) {
|
||||||
|
owned := map[int64]ownedRows{0: {Memberships: 1}, 77: {Tokens: 1}}
|
||||||
|
|
||||||
|
plan := planUserRemap(nil, nil, nil, owned, false)
|
||||||
|
|
||||||
|
if len(plan.Problems) != 0 {
|
||||||
|
t.Fatalf("unknown owners must not block the remap, got %v", plan.Problems)
|
||||||
|
}
|
||||||
|
want := "rows keyed by IDs that are not legacy users are left unchanged: [77]"
|
||||||
|
if len(plan.Warnings) != 1 || plan.Warnings[0] != want {
|
||||||
|
t.Fatalf("got warnings %v, want [%q]", plan.Warnings, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestApplyUserRemapMovesIdentitiesAndRefusesSecondRun seeds a swap (1 to 2 and 2 to 1,
|
||||||
|
// which only works if every row moves in one pass), a merge onto an AuthGuard account
|
||||||
|
// that already has a row, and a device token that must follow its owner.
|
||||||
|
func TestApplyUserRemapMovesIdentitiesAndRefusesSecondRun(t *testing.T) {
|
||||||
|
db := testDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
seedRemapFixture(t, db)
|
||||||
|
|
||||||
|
legacy, err := db.legacyUsers(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
owned, err := db.ownedRowCounts(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
plan := planUserRemap(legacy, remapFixtureAccounts(), nil, owned, true)
|
||||||
|
if len(plan.Problems) != 0 {
|
||||||
|
t.Fatalf("fixture plan blocked: %v", plan.Problems)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.applyUserRemap(ctx, remapPairsFromPlan(plan)); err != nil {
|
||||||
|
t.Fatalf("apply: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assertMembershipOwners(t, db, "l-alice", map[int64]bool{2: true})
|
||||||
|
assertMembershipOwners(t, db, "l-bob", map[int64]bool{1: true})
|
||||||
|
assertMembershipOwners(t, db, "l-shared", map[int64]bool{1: true, 2: false})
|
||||||
|
assertMembershipOwners(t, db, "l-merge", map[int64]bool{7: true})
|
||||||
|
assertTokenOwner(t, db, "alice-device", 2)
|
||||||
|
assertTokenOwner(t, db, "bob-device", 1)
|
||||||
|
|
||||||
|
var leftover int64
|
||||||
|
if err := db.pool.QueryRow(ctx, `SELECT count(*) FROM list_memberships WHERE user_id = 3`).Scan(&leftover); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if leftover != 0 {
|
||||||
|
t.Fatalf("%d membership rows still keyed by legacy ID 3", leftover)
|
||||||
|
}
|
||||||
|
|
||||||
|
recorded, err := db.userRemapAppliedCount(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if recorded != 3 {
|
||||||
|
t.Fatalf("recorded %d mappings, want 3", recorded)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = db.applyUserRemap(ctx, remapPairsFromPlan(plan))
|
||||||
|
if !errors.Is(err, errUserRemapApplied) {
|
||||||
|
t.Fatalf("second apply: got %v, want errUserRemapApplied", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestApplyUserRemapRollsBackWhenAnOwnerIsUnmapped checks that a write which would
|
||||||
|
// strand rows writes nothing at all.
|
||||||
|
func TestApplyUserRemapRollsBackWhenAnOwnerIsUnmapped(t *testing.T) {
|
||||||
|
db := testDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
seedRemapFixture(t, db)
|
||||||
|
|
||||||
|
err := db.applyUserRemap(ctx, []remapPair{{Legacy: 1, AuthGuard: 2}})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "no mapping") {
|
||||||
|
t.Fatalf("apply with unmapped owners: got %v, want a no-mapping error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assertMembershipOwners(t, db, "l-bob", map[int64]bool{2: true})
|
||||||
|
assertTokenOwner(t, db, "bob-device", 2)
|
||||||
|
recorded, err := db.userRemapAppliedCount(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if recorded != 0 {
|
||||||
|
t.Fatalf("failed apply recorded %d mappings", recorded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func entryTargetID(entry remapEntry) int64 {
|
||||||
|
if entry.Target == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return entry.Target.ID
|
||||||
|
}
|
||||||
|
|
||||||
|
func remapPairsFromPlan(plan remapPlan) []remapPair {
|
||||||
|
var pairs []remapPair
|
||||||
|
for _, entry := range plan.Entries {
|
||||||
|
if entry.Target != nil {
|
||||||
|
pairs = append(pairs, remapPair{Legacy: entry.Legacy.ID, AuthGuard: entry.Target.ID})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pairs
|
||||||
|
}
|
||||||
|
|
||||||
|
// remapFixtureAccounts are the AuthGuard accounts for the fixture below. Legacy 1 and 2
|
||||||
|
// swap IDs, and legacy 3 keeps its email.
|
||||||
|
func remapFixtureAccounts() []authGuardAccount {
|
||||||
|
return []authGuardAccount{
|
||||||
|
{ID: 1, Username: "bob", Email: "bob@example.com"},
|
||||||
|
{ID: 2, Username: "alice", Email: "alice@example.com"},
|
||||||
|
{ID: 7, Username: "carol", Email: "carol@example.com"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedRemapFixture(t *testing.T, db *DB) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
exec := func(query string, args ...any) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := db.pool.Exec(ctx, query, args...); err != nil {
|
||||||
|
t.Fatalf("seed %q: %v", query, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exec(`INSERT INTO auth_users (id, username, email, password_hash) VALUES
|
||||||
|
(1, 'alice', 'alice@example.com', 'x'),
|
||||||
|
(2, 'bob', 'bob@example.com', 'x'),
|
||||||
|
(3, 'carol', 'carol@example.com', 'x')`)
|
||||||
|
for _, id := range []string{"l-alice", "l-bob", "l-shared", "l-merge"} {
|
||||||
|
exec(`INSERT INTO lists (id, name, createdat, updatedat) VALUES ($1, $1, $2, $2)`, id, t0)
|
||||||
|
}
|
||||||
|
exec(`INSERT INTO list_memberships (listid, user_id, is_owner) VALUES
|
||||||
|
('l-alice', 1, TRUE),
|
||||||
|
('l-bob', 2, TRUE),
|
||||||
|
('l-shared', 1, FALSE),
|
||||||
|
('l-shared', 2, TRUE),
|
||||||
|
('l-merge', 3, FALSE),
|
||||||
|
('l-merge', 7, TRUE)`)
|
||||||
|
exec(`INSERT INTO api_tokens (user_id, token_hash) VALUES (1, $1), (2, $2)`,
|
||||||
|
hashToken("alice-device"), hashToken("bob-device"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertMembershipOwners(t *testing.T, db *DB, listID string, want map[int64]bool) {
|
||||||
|
t.Helper()
|
||||||
|
rows, err := db.pool.Query(context.Background(), `SELECT user_id, is_owner FROM list_memberships WHERE listid = $1`, listID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
got := make(map[int64]bool)
|
||||||
|
for rows.Next() {
|
||||||
|
var userID int64
|
||||||
|
var owner bool
|
||||||
|
if err := rows.Scan(&userID, &owner); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got[userID] = owner
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !maps.Equal(got, want) {
|
||||||
|
t.Fatalf("%s memberships: got %v, want %v", listID, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertTokenOwner(t *testing.T, db *DB, device string, want int64) {
|
||||||
|
t.Helper()
|
||||||
|
got, err := db.getAPITokenUserID(context.Background(), hashToken(device))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("%s token owner: got %d, want %d", device, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
BIN
Binary file not shown.
+33
-30
@@ -6,8 +6,9 @@ import (
|
|||||||
"embed"
|
"embed"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"io"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -19,8 +20,8 @@ import (
|
|||||||
_ "github.com/joho/godotenv/autoload"
|
_ "github.com/joho/godotenv/autoload"
|
||||||
|
|
||||||
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/coreconfig"
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -37,7 +38,6 @@ type Server struct {
|
|||||||
startTime time.Time
|
startTime time.Time
|
||||||
internalServiceSecret string
|
internalServiceSecret string
|
||||||
coreConfig *coreconfig.Store
|
coreConfig *coreconfig.Store
|
||||||
carrierNode *carriernodeclient.Client
|
|
||||||
syncSlots chan struct{}
|
syncSlots chan struct{}
|
||||||
// trustedProxies are the TRUSTED_PROXIES networks whose X-Forwarded-For and
|
// trustedProxies are the TRUSTED_PROXIES networks whose X-Forwarded-For and
|
||||||
// X-Forwarded-Proto headers are believed. Nil trusts no proxy.
|
// X-Forwarded-Proto headers are believed. Nil trusts no proxy.
|
||||||
@@ -52,25 +52,29 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
if len(os.Args) > 1 && os.Args[1] == "remap-users" {
|
||||||
|
os.Exit(runRemapUsers(os.Args[2:], os.Stdout))
|
||||||
|
}
|
||||||
|
log.SetOutput(io.MultiWriter(os.Stderr, omniShipper.Writer()))
|
||||||
port := envOrDefault("PORT", "8080")
|
port := envOrDefault("PORT", "8080")
|
||||||
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
if connectionString == "" {
|
if connectionString == "" {
|
||||||
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
|
logErrorln(logshipper.LevelCritical, "DATABASE_URL environment variable is required")
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
|
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
|
||||||
|
|
||||||
trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES"))
|
trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintln(os.Stderr, err)
|
logErrorln(logshipper.LevelCritical, err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
// PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so
|
// PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so
|
||||||
// the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES.
|
// the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES.
|
||||||
production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true")
|
production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true")
|
||||||
if production && len(trustedProxies) == 0 {
|
if production && len(trustedProxies) == 0 {
|
||||||
fmt.Fprintln(os.Stderr, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there")
|
logErrorln(logshipper.LevelCritical, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there")
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
@@ -78,8 +82,8 @@ func main() {
|
|||||||
|
|
||||||
database, err := connectWithRetry(ctx, connectionString)
|
database, err := connectWithRetry(ctx, connectionString)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err)
|
logErrorf(logshipper.LevelCritical, "database initialization failed: %v\n", err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
defer database.close()
|
defer database.close()
|
||||||
go database.pruneExpiredSessions(ctx)
|
go database.pruneExpiredSessions(ctx)
|
||||||
@@ -97,11 +101,11 @@ func main() {
|
|||||||
authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true")
|
authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true")
|
||||||
switch {
|
switch {
|
||||||
case authDisabled:
|
case authDisabled:
|
||||||
fmt.Println("auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated")
|
logPrintln(logshipper.LevelWarn, "auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated")
|
||||||
case authGuardURL != "":
|
case authGuardURL != "":
|
||||||
fmt.Printf("auth: AuthGuard at %s\n", authGuardURL)
|
logPrintf(logshipper.LevelInfo, "auth: AuthGuard at %s\n", authGuardURL)
|
||||||
default:
|
default:
|
||||||
fmt.Println("auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then")
|
logPrintln(logshipper.LevelWarn, "auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then")
|
||||||
}
|
}
|
||||||
auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"), authDisabled)
|
auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"), authDisabled)
|
||||||
|
|
||||||
@@ -114,30 +118,26 @@ func main() {
|
|||||||
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
|
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
|
||||||
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
|
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
|
||||||
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
|
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
|
||||||
|
omniShipper.Follow(coreConfig)
|
||||||
coreConfig.OnUpdate(func(info coreconfig.Info) {
|
coreConfig.OnUpdate(func(info coreconfig.Info) {
|
||||||
if info.AuthGuardURL != "" {
|
if info.AuthGuardURL != "" {
|
||||||
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
|
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
carrierNode := carriernodeclient.New(internalServiceSecret, func(context.Context) string {
|
|
||||||
return coreConfig.CarrierNodeURL()
|
|
||||||
})
|
|
||||||
|
|
||||||
server := &Server{
|
server := &Server{
|
||||||
db: database,
|
db: database,
|
||||||
auth: auth,
|
auth: auth,
|
||||||
startTime: time.Now(),
|
startTime: time.Now(),
|
||||||
internalServiceSecret: internalServiceSecret,
|
internalServiceSecret: internalServiceSecret,
|
||||||
coreConfig: coreConfig,
|
coreConfig: coreConfig,
|
||||||
carrierNode: carrierNode,
|
|
||||||
syncSlots: make(chan struct{}, maxConcurrentSyncs),
|
syncSlots: make(chan struct{}, maxConcurrentSyncs),
|
||||||
trustedProxies: trustedProxies,
|
trustedProxies: trustedProxies,
|
||||||
}
|
}
|
||||||
|
|
||||||
webRoot, err := fs.Sub(webFS, "web")
|
webRoot, err := fs.Sub(webFS, "web")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err)
|
logErrorf(logshipper.LevelCritical, "embedded web assets missing: %v\n", err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
@@ -146,9 +146,9 @@ func main() {
|
|||||||
handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux)))
|
handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux)))
|
||||||
if production {
|
if production {
|
||||||
handler = withHTTPSRequired(trustedProxies, handler)
|
handler = withHTTPSRequired(trustedProxies, handler)
|
||||||
fmt.Println("PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https")
|
logPrintln(logshipper.LevelInfo, "PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https")
|
||||||
} else {
|
} else {
|
||||||
fmt.Fprintln(os.Stderr, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.")
|
logErrorln(logshipper.LevelWarn, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.")
|
||||||
}
|
}
|
||||||
|
|
||||||
httpServer := &http.Server{
|
httpServer := &http.Server{
|
||||||
@@ -160,11 +160,11 @@ func main() {
|
|||||||
IdleTimeout: 120 * time.Second,
|
IdleTimeout: 120 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("CollabTable Go server listening on :%s\n", port)
|
logPrintf(logshipper.LevelInfo, "CollabTable Go server listening on :%s\n", port)
|
||||||
fmt.Printf("Database: PostgreSQL (pgx)\n")
|
logPrintf(logshipper.LevelInfo, "Database: PostgreSQL (pgx)\n")
|
||||||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
|
logErrorf(logshipper.LevelCritical, "server error: %v\n", err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,7 +176,7 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
||||||
if attempt > 1 {
|
if attempt > 1 {
|
||||||
fmt.Printf("[DB] Connected after %d attempt(s)\n", attempt)
|
logPrintf(logshipper.LevelInfo, "[DB] Connected after %d attempt(s)\n", attempt)
|
||||||
}
|
}
|
||||||
return database, nil
|
return database, nil
|
||||||
} else {
|
} else {
|
||||||
@@ -185,11 +185,11 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
logErrorf(logshipper.LevelWarn, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
||||||
if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts {
|
if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
fmt.Printf("[DB] Retrying in %s...\n", retryOptions.Interval)
|
logPrintf(logshipper.LevelWarn, "[DB] Retrying in %s...\n", retryOptions.Interval)
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return nil, ctx.Err()
|
return nil, ctx.Err()
|
||||||
@@ -458,6 +458,9 @@ func spaFileServer(root fs.FS) http.Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// The path is cleaned as a rooted URL path, and it is only read from webRoot,
|
||||||
|
// an embed.FS, so it cannot name a file outside the embedded build.
|
||||||
|
// nosemgrep: go.lang.security.filepath-clean-misuse.filepath-clean-misuse
|
||||||
cleanPath := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
|
cleanPath := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
|
||||||
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
|
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
|
||||||
serveIndex(w, r)
|
serveIndex(w, r)
|
||||||
|
|||||||
+185
-35
@@ -2,16 +2,20 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sort"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
)
|
)
|
||||||
|
|
||||||
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
|
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
|
||||||
// (DATABASE_MAX_CONNS defaults to 20), so syncs cannot hold every connection.
|
// (DATABASE_MAX_CONNS defaults to 20), so syncs cannot hold every connection.
|
||||||
const maxConcurrentSyncs = 4
|
const maxConcurrentSyncs = 4
|
||||||
|
const syncPageSize = 500
|
||||||
|
|
||||||
func syncMaxFutureSkew() int64 {
|
func syncMaxFutureSkew() int64 {
|
||||||
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
||||||
@@ -48,11 +52,11 @@ func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
|
|||||||
|
|
||||||
// valueReferences returns the list ID of each field and the existence of each
|
// valueReferences returns the list ID of each field and the existence of each
|
||||||
// item that the values refer to, using one statement per table.
|
// item that the values refer to, using one statement per table.
|
||||||
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]bool, error) {
|
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]string, error) {
|
||||||
fieldLists := make(map[string]string)
|
fieldLists := make(map[string]string)
|
||||||
existingItems := make(map[string]bool)
|
itemLists := make(map[string]string)
|
||||||
if len(values) == 0 {
|
if len(values) == 0 {
|
||||||
return fieldLists, existingItems, nil
|
return fieldLists, itemLists, nil
|
||||||
}
|
}
|
||||||
fieldIDs := make([]string, 0, len(values))
|
fieldIDs := make([]string, 0, len(values))
|
||||||
itemIDs := make([]string, 0, len(values))
|
itemIDs := make([]string, 0, len(values))
|
||||||
@@ -77,22 +81,22 @@ func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[st
|
|||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
itemRows, err := tx.Query(ctx, `SELECT id FROM items WHERE id = ANY($1)`, itemIDs)
|
itemRows, err := tx.Query(ctx, `SELECT id, listid FROM items WHERE id = ANY($1)`, itemIDs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
defer itemRows.Close()
|
defer itemRows.Close()
|
||||||
for itemRows.Next() {
|
for itemRows.Next() {
|
||||||
var itemID string
|
var itemID, listID string
|
||||||
if err := itemRows.Scan(&itemID); err != nil {
|
if err := itemRows.Scan(&itemID, &listID); err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
existingItems[itemID] = true
|
itemLists[itemID] = listID
|
||||||
}
|
}
|
||||||
if err := itemRows.Err(); err != nil {
|
if err := itemRows.Err(); err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
return fieldLists, existingItems, nil
|
return fieldLists, itemLists, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// changeEventType names a synced change for the notification feed: a tombstone
|
// changeEventType names a synced change for the notification feed: a tombstone
|
||||||
@@ -110,6 +114,7 @@ func changeEventType(initialSync, deleted bool) string {
|
|||||||
// syncBatch holds what every row of one sync request shares.
|
// syncBatch holds what every row of one sync request shares.
|
||||||
type syncBatch struct {
|
type syncBatch struct {
|
||||||
now int64
|
now int64
|
||||||
|
userID int64
|
||||||
initialSync bool
|
initialSync bool
|
||||||
deviceID string
|
deviceID string
|
||||||
}
|
}
|
||||||
@@ -122,11 +127,20 @@ func (b syncBatch) notify(ctx context.Context, tx pgx.Tx, eventType, entityType,
|
|||||||
// changes nothing, so it triggers no cascade or notification.
|
// changes nothing, so it triggers no cascade or notification.
|
||||||
func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) error {
|
func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) error {
|
||||||
for _, list := range lists {
|
for _, list := range lists {
|
||||||
|
member, err := authorizeList(ctx, tx, batch.userID, list.ID, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), batch.now)
|
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), batch.now)
|
||||||
applied, err := upsertList(ctx, tx, list, createdAt, updatedAt)
|
applied, err := upsertList(ctx, tx, list, createdAt, updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if !member {
|
||||||
|
if err := addListOwner(ctx, tx, batch.userID, list.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
if !applied {
|
if !applied {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -141,8 +155,33 @@ func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) e
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ensureEntityList(ctx context.Context, tx pgx.Tx, table, id, listID string) error {
|
||||||
|
var storedListID string
|
||||||
|
err := tx.QueryRow(ctx, `SELECT listid FROM `+table+` WHERE id = $1`, id).Scan(&storedListID)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if storedListID != listID {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
|
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
|
||||||
for _, field := range fields {
|
for _, field := range fields {
|
||||||
|
if err := ensureEntityList(ctx, tx, "fields", field.ID, field.ListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, tx, batch.userID, field.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
|
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
|
||||||
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
|
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -164,6 +203,16 @@ func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch
|
|||||||
|
|
||||||
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
|
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
|
||||||
for _, item := range items {
|
for _, item := range items {
|
||||||
|
if err := ensureEntityList(ctx, tx, "items", item.ID, item.ListID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
member, err := hasListMembership(ctx, tx, batch.userID, item.ListID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return errListAccessDenied
|
||||||
|
}
|
||||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
|
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
|
||||||
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
|
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -189,7 +238,7 @@ func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncB
|
|||||||
orphans := make([]OrphanValue, 0)
|
orphans := make([]OrphanValue, 0)
|
||||||
// Resolve the fields and items the values refer to once per request, not once
|
// Resolve the fields and items the values refer to once per request, not once
|
||||||
// per value.
|
// per value.
|
||||||
fieldLists, existingItems, err := valueReferences(ctx, tx, values)
|
fieldLists, itemLists, err := valueReferences(ctx, tx, values)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -201,8 +250,16 @@ func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncB
|
|||||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
member, err := hasListMembership(ctx, tx, batch.userID, listID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !member {
|
||||||
|
return nil, errListAccessDenied
|
||||||
|
}
|
||||||
|
|
||||||
if !existingItems[value.ItemID] {
|
itemListID, itemExists := itemLists[value.ItemID]
|
||||||
|
if !itemExists {
|
||||||
if _, err := tx.Exec(ctx, `
|
if _, err := tx.Exec(ctx, `
|
||||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||||
VALUES ($1, $2, $3, $3, 0)
|
VALUES ($1, $2, $3, $3, 0)
|
||||||
@@ -211,7 +268,17 @@ func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncB
|
|||||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
existingItems[value.ItemID] = true
|
itemLists[value.ItemID] = listID
|
||||||
|
} else if itemListID != listID {
|
||||||
|
itemMember, err := hasListMembership(ctx, tx, batch.userID, itemListID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !itemMember {
|
||||||
|
return nil, errListAccessDenied
|
||||||
|
}
|
||||||
|
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "itemFieldListMismatch"})
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
applied, err := upsertValue(ctx, tx, value, updatedAt)
|
applied, err := upsertValue(ctx, tx, value, updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -239,27 +306,104 @@ func applySyncRequest(ctx context.Context, tx pgx.Tx, request SyncRequest, batch
|
|||||||
return applyValues(ctx, tx, request.ItemValues, batch)
|
return applyValues(ctx, tx, request.ItemValues, batch)
|
||||||
}
|
}
|
||||||
|
|
||||||
// changesSince reads what a device has to pull: everything when since is nil,
|
type syncChange struct {
|
||||||
// otherwise the rows updated at or after it. The caller adds the orphan list and
|
token int64
|
||||||
// the server timestamp.
|
kind string
|
||||||
func (d *DB) changesSince(ctx context.Context, since *int64) (SyncResponse, error) {
|
value any
|
||||||
lists, err := d.queryLists(ctx, true, since)
|
}
|
||||||
|
|
||||||
|
type trailingTokenScanner struct {
|
||||||
|
row rowScanner
|
||||||
|
token int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *trailingTokenScanner) Scan(dest ...any) error {
|
||||||
|
return s.row.Scan(append(dest, &s.token)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// changesSince returns a bounded page from one repeatable-read snapshot. Each
|
||||||
|
// data write takes the clock row lock before touching a row, so a later commit
|
||||||
|
// cannot publish a lower token than a cursor already returned to a device.
|
||||||
|
func (d *DB) changesSince(ctx context.Context, userID int64, cursor int64) (SyncResponse, error) {
|
||||||
|
tx, err := d.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return SyncResponse{}, err
|
return SyncResponse{}, err
|
||||||
}
|
}
|
||||||
fields, err := d.queryFields(ctx, true, since, "")
|
defer tx.Rollback(ctx)
|
||||||
if err != nil {
|
|
||||||
|
var serverToken int64
|
||||||
|
if err := tx.QueryRow(ctx, `SELECT token FROM collabtable_sync_clock WHERE id = 1`).Scan(&serverToken); err != nil {
|
||||||
return SyncResponse{}, err
|
return SyncResponse{}, err
|
||||||
}
|
}
|
||||||
items, err := d.queryItems(ctx, true, since, "")
|
if cursor > serverToken {
|
||||||
if err != nil {
|
cursor = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
queries := []struct {
|
||||||
|
kind string
|
||||||
|
stmt string
|
||||||
|
scan func(rowScanner) (any, error)
|
||||||
|
}{
|
||||||
|
{kind: "list", stmt: `SELECT lists.id, lists.name, lists.createdat, lists.updatedat, COALESCE(lists.isdeleted, 0), lists.change_token FROM lists JOIN list_memberships m ON m.listid = lists.id WHERE m.user_id = $1 AND lists.change_token > $2 ORDER BY lists.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanList(row) }},
|
||||||
|
{kind: "field", stmt: `SELECT fields.id, fields.name, fields.fieldtype, COALESCE(fields.fieldoptions, ''), COALESCE(fields.alignment, 'start'), fields.listid, fields."order", fields.createdat, fields.updatedat, COALESCE(fields.isdeleted, 0), fields.change_token FROM fields JOIN list_memberships m ON m.listid = fields.listid WHERE m.user_id = $1 AND fields.change_token > $2 ORDER BY fields.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanField(row) }},
|
||||||
|
{kind: "item", stmt: `SELECT items.id, items.listid, items.createdat, items.updatedat, COALESCE(items.isdeleted, 0), items.change_token FROM items JOIN list_memberships m ON m.listid = items.listid WHERE m.user_id = $1 AND items.change_token > $2 ORDER BY items.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanItem(row) }},
|
||||||
|
{kind: "value", stmt: `SELECT item_values.id, item_values.itemid, item_values.fieldid, COALESCE(item_values.value, ''), item_values.updatedat, item_values.change_token FROM item_values JOIN items i ON i.id = item_values.itemid JOIN list_memberships m ON m.listid = i.listid WHERE m.user_id = $1 AND item_values.change_token > $2 ORDER BY item_values.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanItemValue(row) }},
|
||||||
|
}
|
||||||
|
changes := make([]syncChange, 0, syncPageSize*2)
|
||||||
|
for _, query := range queries {
|
||||||
|
rows, err := tx.Query(ctx, query.stmt, userID, cursor, syncPageSize+1)
|
||||||
|
if err != nil {
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
scanner := trailingTokenScanner{row: rows}
|
||||||
|
value, err := query.scan(&scanner)
|
||||||
|
if err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
changes = append(changes, syncChange{token: scanner.token, kind: query.kind, value: value})
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return SyncResponse{}, err
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
}
|
||||||
|
sort.Slice(changes, func(i, j int) bool { return changes[i].token < changes[j].token })
|
||||||
|
hasMore := len(changes) > syncPageSize
|
||||||
|
if hasMore {
|
||||||
|
changes = changes[:syncPageSize]
|
||||||
|
}
|
||||||
|
nextToken := serverToken
|
||||||
|
if hasMore {
|
||||||
|
nextToken = changes[len(changes)-1].token
|
||||||
|
}
|
||||||
|
response := SyncResponse{
|
||||||
|
Lists: make([]List, 0),
|
||||||
|
Fields: make([]Field, 0),
|
||||||
|
Items: make([]Item, 0),
|
||||||
|
ItemValues: make([]ItemValue, 0),
|
||||||
|
ServerChangeToken: serverToken,
|
||||||
|
NextSyncToken: nextToken,
|
||||||
|
HasMore: hasMore,
|
||||||
|
}
|
||||||
|
for _, change := range changes {
|
||||||
|
switch change.kind {
|
||||||
|
case "list":
|
||||||
|
response.Lists = append(response.Lists, change.value.(List))
|
||||||
|
case "field":
|
||||||
|
response.Fields = append(response.Fields, change.value.(Field))
|
||||||
|
case "item":
|
||||||
|
response.Items = append(response.Items, change.value.(Item))
|
||||||
|
case "value":
|
||||||
|
response.ItemValues = append(response.ItemValues, change.value.(ItemValue))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
return SyncResponse{}, err
|
return SyncResponse{}, err
|
||||||
}
|
}
|
||||||
values, err := d.queryValues(ctx, since, "")
|
return response, nil
|
||||||
if err != nil {
|
|
||||||
return SyncResponse{}, err
|
|
||||||
}
|
|
||||||
return SyncResponse{Lists: lists, Fields: fields, Items: items, ItemValues: values}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -278,32 +422,38 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeDecodeError(w, err, "Invalid sync request")
|
writeDecodeError(w, err, "Invalid sync request")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if request.LastSyncToken == nil || *request.LastSyncToken < 0 {
|
||||||
|
writeJSONError(w, http.StatusBadRequest, "lastSyncToken is required; update the CollabTable client")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
|
batch := syncBatch{now: now, userID: requestUserID(r), initialSync: *request.LastSyncToken == 0, deviceID: requestDeviceID(r, request.DeviceID)}
|
||||||
batch := syncBatch{now: now, initialSync: lastSync == 0, deviceID: requestDeviceID(r, request.DeviceID)}
|
|
||||||
orphans := make([]OrphanValue, 0)
|
orphans := make([]OrphanValue, 0)
|
||||||
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
||||||
if incoming > 0 {
|
if incoming > 0 {
|
||||||
fmt.Printf("[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
|
logPrintf(logshipper.LevelInfo, "[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
|
||||||
}
|
}
|
||||||
|
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
|
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
var err error
|
var err error
|
||||||
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
|
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("[SYNC] Failed: %v\n", err)
|
if errors.Is(err, errListAccessDenied) {
|
||||||
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
logPrintf(logshipper.LevelError, "[SYNC] Failed: %v\n", err)
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var since *int64
|
response, err := s.db.changesSince(r.Context(), requestUserID(r), *request.LastSyncToken)
|
||||||
if lastSync != 0 {
|
|
||||||
since = &lastSync
|
|
||||||
}
|
|
||||||
response, err := s.db.changesSince(r.Context(), since)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||||
return
|
return
|
||||||
|
|||||||
+14
-6
@@ -11,22 +11,26 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
||||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
s.writeWebData(w, r, requestUserID(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) writeWebData(w http.ResponseWriter, r *http.Request, userID int64) {
|
||||||
|
lists, err := s.db.queryLists(r.Context(), userID, false, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fields, err := s.db.queryFields(r.Context(), false, nil, "")
|
fields, err := s.db.queryFields(r.Context(), userID, false, nil, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
items, err := s.db.queryItems(r.Context(), false, nil, "")
|
items, err := s.db.queryItems(r.Context(), userID, false, nil, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
values, err := s.db.queryValues(r.Context(), nil, "")
|
values, err := s.db.queryValues(r.Context(), userID, nil, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||||
return
|
return
|
||||||
@@ -134,10 +138,14 @@ func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request)
|
|||||||
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
||||||
FROM notifications
|
FROM notifications
|
||||||
WHERE createdat > $1
|
WHERE createdat > $1
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM list_memberships m
|
||||||
|
WHERE m.listid = notifications.listid AND m.user_id = $2
|
||||||
|
)
|
||||||
`
|
`
|
||||||
args := []any{since}
|
args := []any{since, requestUserID(r)}
|
||||||
if deviceID != "" {
|
if deviceID != "" {
|
||||||
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $2)`
|
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $3)`
|
||||||
args = append(args, deviceID)
|
args = append(args, deviceID)
|
||||||
}
|
}
|
||||||
query += ` ORDER BY createdat ASC LIMIT 500`
|
query += ` ORDER BY createdat ASC LIMIT 500`
|
||||||
|
|||||||
+2
-1
@@ -8,7 +8,7 @@ COPY shared/package.json shared/package-lock.json /shared/
|
|||||||
COPY shared/packages/design-tokens/package.json /shared/packages/design-tokens/
|
COPY shared/packages/design-tokens/package.json /shared/packages/design-tokens/
|
||||||
COPY shared/packages/node-backend/package.json /shared/packages/node-backend/
|
COPY shared/packages/node-backend/package.json /shared/packages/node-backend/
|
||||||
COPY shared/packages/web-ui/package.json /shared/packages/web-ui/
|
COPY shared/packages/web-ui/package.json /shared/packages/web-ui/
|
||||||
RUN npm ci --prefix /shared --ignore-scripts --no-audit --no-fund --omit=dev
|
RUN npm ci --prefix /shared --ignore-scripts --no-audit --no-fund
|
||||||
RUN --mount=type=cache,target=/root/.npm \
|
RUN --mount=type=cache,target=/root/.npm \
|
||||||
for attempt in 1 2 3 4 5; do \
|
for attempt in 1 2 3 4 5; do \
|
||||||
npm ci && break; \
|
npm ci && break; \
|
||||||
@@ -20,6 +20,7 @@ RUN --mount=type=cache,target=/root/.npm \
|
|||||||
COPY shared/packages/design-tokens /shared/packages/design-tokens
|
COPY shared/packages/design-tokens /shared/packages/design-tokens
|
||||||
COPY shared/packages/node-backend /shared/packages/node-backend
|
COPY shared/packages/node-backend /shared/packages/node-backend
|
||||||
COPY shared/packages/web-ui /shared/packages/web-ui
|
COPY shared/packages/web-ui /shared/packages/web-ui
|
||||||
|
RUN npm run build --prefix /shared
|
||||||
COPY frontend/ ./
|
COPY frontend/ ./
|
||||||
RUN rm -rf /frontend/node_modules/@gabriel20xx/web-ui && \
|
RUN rm -rf /frontend/node_modules/@gabriel20xx/web-ui && \
|
||||||
ln -s /shared/packages/web-ui /frontend/node_modules/@gabriel20xx/web-ui
|
ln -s /shared/packages/web-ui /frontend/node_modules/@gabriel20xx/web-ui
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
{
|
{
|
||||||
"extends": "./.svelte-kit/tsconfig.json",
|
"extends": "$app/tsconfig",
|
||||||
|
"include": ["src", "test", "*"],
|
||||||
|
"exclude": ["src/service-worker"],
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"checkJs": false,
|
"checkJs": false,
|
||||||
|
|||||||
Generated
+181
-251
@@ -8,6 +8,7 @@
|
|||||||
"name": "collabtable-server-frontend",
|
"name": "collabtable-server-frontend",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@gabriel20xx/design-tokens": "file:../shared/packages/design-tokens",
|
||||||
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
||||||
"@lucide/svelte": "latest",
|
"@lucide/svelte": "latest",
|
||||||
"@tanstack/svelte-query": "latest",
|
"@tanstack/svelte-query": "latest",
|
||||||
@@ -18,8 +19,8 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "latest",
|
"@eslint/js": "latest",
|
||||||
"@sveltejs/adapter-static": "latest",
|
"@sveltejs/adapter-static": "^4.0.1",
|
||||||
"@sveltejs/kit": "latest",
|
"@sveltejs/kit": "^3.1.1",
|
||||||
"@sveltejs/vite-plugin-svelte": "latest",
|
"@sveltejs/vite-plugin-svelte": "latest",
|
||||||
"@tailwindcss/vite": "latest",
|
"@tailwindcss/vite": "latest",
|
||||||
"eslint": "latest",
|
"eslint": "latest",
|
||||||
@@ -27,13 +28,18 @@
|
|||||||
"eslint-plugin-svelte": "latest",
|
"eslint-plugin-svelte": "latest",
|
||||||
"prettier": "latest",
|
"prettier": "latest",
|
||||||
"prettier-plugin-svelte": "latest",
|
"prettier-plugin-svelte": "latest",
|
||||||
"svelte": "latest",
|
"svelte": "^5.57.3",
|
||||||
"svelte-check": "latest",
|
"svelte-check": "latest",
|
||||||
"tailwindcss": "latest",
|
"tailwindcss": "latest",
|
||||||
"tw-animate-css": "latest",
|
"tw-animate-css": "latest",
|
||||||
"vite": "latest"
|
"vite": "^8.3.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"../shared/packages/design-tokens": {
|
||||||
|
"name": "@gabriel20xx/design-tokens",
|
||||||
|
"version": "0.1.1",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"../shared/packages/web-ui": {
|
"../shared/packages/web-ui": {
|
||||||
"name": "@gabriel20xx/web-ui",
|
"name": "@gabriel20xx/web-ui",
|
||||||
"version": "0.1.1",
|
"version": "0.1.1",
|
||||||
@@ -52,37 +58,6 @@
|
|||||||
"svelte": "^5.0.0"
|
"svelte": "^5.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@emnapi/core": {
|
|
||||||
"version": "2.0.0-alpha.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-alpha.3.tgz",
|
|
||||||
"integrity": "sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@emnapi/wasi-threads": "2.0.1",
|
|
||||||
"tslib": "^2.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@emnapi/runtime": {
|
|
||||||
"version": "2.0.0-alpha.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-alpha.3.tgz",
|
|
||||||
"integrity": "sha512-hFPAhMUjJD9BSyCANEISPOogeXC9Zo9ZQl7L6vKnaVsMkCtzznaW/naYypeyl0Gv5rYfWYsZbpixTMpjDJzQeA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "^2.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@emnapi/wasi-threads": {
|
|
||||||
"version": "2.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.0.1.tgz",
|
|
||||||
"integrity": "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "^2.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@eslint-community/eslint-utils": {
|
"node_modules/@eslint-community/eslint-utils": {
|
||||||
"version": "4.10.1",
|
"version": "4.10.1",
|
||||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
|
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
|
||||||
@@ -236,6 +211,10 @@
|
|||||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@gabriel20xx/design-tokens": {
|
||||||
|
"resolved": "../shared/packages/design-tokens",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
"node_modules/@gabriel20xx/web-ui": {
|
"node_modules/@gabriel20xx/web-ui": {
|
||||||
"resolved": "../shared/packages/web-ui",
|
"resolved": "../shared/packages/web-ui",
|
||||||
"link": true
|
"link": true
|
||||||
@@ -346,9 +325,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@jridgewell/sourcemap-codec": {
|
"node_modules/@jridgewell/sourcemap-codec": {
|
||||||
"version": "1.5.5",
|
"version": "1.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
|
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
|
||||||
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
|
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@jridgewell/trace-mapping": {
|
"node_modules/@jridgewell/trace-mapping": {
|
||||||
@@ -370,35 +349,14 @@
|
|||||||
"svelte": "^5"
|
"svelte": "^5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@napi-rs/wasm-runtime": {
|
|
||||||
"version": "1.2.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.2.tgz",
|
|
||||||
"integrity": "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@tybys/wasm-util": "^0.10.3"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
|
|
||||||
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@oxc-project/types": {
|
"node_modules/@oxc-project/types": {
|
||||||
"version": "0.142.0",
|
"version": "0.155.0",
|
||||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.142.0.tgz",
|
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz",
|
||||||
"integrity": "sha512-7W+2q5AKQVU36fkaryontrHn3YDt1RyUYXatw9i5H8ocYe2sPKSFB6eS8WNPeRKiN1qAWWZUPm7gwFzJGrccqQ==",
|
"integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/Boshen"
|
"url": "https://github.com/sponsors/oxc-project"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@polka/url": {
|
"node_modules/@polka/url": {
|
||||||
@@ -408,10 +366,26 @@
|
|||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@rolldown/binding-android-arm-eabi": {
|
||||||
|
"version": "1.2.15",
|
||||||
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz",
|
||||||
|
"integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@rolldown/binding-android-arm64": {
|
"node_modules/@rolldown/binding-android-arm64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz",
|
||||||
"integrity": "sha512-02hOeOSryYxVrOIphmLAsqnCJWxwlzFk+pEt/N/i6OgT3lShHO7xGCU5cpgchRDHboAEbSjzgGh+O/u1GswQmA==",
|
"integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -425,9 +399,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-darwin-arm64": {
|
"node_modules/@rolldown/binding-darwin-arm64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz",
|
||||||
"integrity": "sha512-fMsTOnN0OjFm3CyppWPitKnc8UlliVARUULW6cfU6AIqjdtgmSFWSk9vecHzZduv/yMWIHDlRhM1e8Iff9uAfA==",
|
"integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -441,9 +415,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-darwin-x64": {
|
"node_modules/@rolldown/binding-darwin-x64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz",
|
||||||
"integrity": "sha512-1wjKdz/XLGKHaTNHjQveQ/B23TKx4ItAqm1JbyVuvNPc4Ze0Fb48s49TAd/2zcplPl8okE/UbTgmlVfwT7eFeQ==",
|
"integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -457,9 +431,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-freebsd-x64": {
|
"node_modules/@rolldown/binding-freebsd-x64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz",
|
||||||
"integrity": "sha512-Fa0jHR07E7YBN4vOEsbVf2briYNsuOowfLJaXULZM0ldMlaCaj2LJgLMbMe4iacRyZmvR8efFhgR9wKuGclQUg==",
|
"integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -473,9 +447,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz",
|
||||||
"integrity": "sha512-pzkgu1SSHGgRRyRZ4fbmSgmajbVt+epaLP99NDjFft69v/ypfTi6swBMiVdh2EkQ0OSnHE1lZDM7DRGkyAzUpA==",
|
"integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
@@ -489,9 +463,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz",
|
||||||
"integrity": "sha512-QI5SEDY8cbiYWHx0VO4vIc3UlS6a32vXHjU8Qy/17adEmZIPuByJg13UEvo9c/UCiUkdcVWY83C+b+JrwnNyUg==",
|
"integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -508,9 +482,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz",
|
||||||
"integrity": "sha512-Sm41FyCeXqmYcERoYOCbGIL5hNfd8w9LQ7Y61Bev48HkcjaJqV/iiVOaiDxjVTRMS+QKrZmD8cfPt4uMVnvM+A==",
|
"integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -527,9 +501,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz",
|
||||||
"integrity": "sha512-2x+WhXTGl9yJYPbltW/BSEPTVz9OIWQyER4N+gJEDWkkn904eRcBzELqh/Hf7K0w/ubGbKNMv0ZC+94QK/IFEg==",
|
"integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
@@ -546,9 +520,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz",
|
||||||
"integrity": "sha512-eEjmQpuRQayHPWWnywaWHkFT3ToPbP3RYy42VVd/B9aBGDA+Ol25EIWHxKQST3IiWJjikCWUF7KtbfqwZrzVwQ==",
|
"integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
@@ -565,9 +539,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz",
|
||||||
"integrity": "sha512-/Orga1fZYkLc/56jBICcHrKchl8Z2UKdDSr3LG9ToWO1lQ6a4Livk9Xz+9WN91zsz5QR3XQz2NNoSDEvP6qadw==",
|
"integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -584,9 +558,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-x64-musl": {
|
"node_modules/@rolldown/binding-linux-x64-musl": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz",
|
||||||
"integrity": "sha512-xxBJRL+0q0Kce7orznGWLuylHDY65vuARXZRpX+hPdv+DqK2c3NlCsVA98tlWzWNEE7yPqA/1NQ5nnCrj49Y5A==",
|
"integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -603,9 +577,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-openharmony-arm64": {
|
"node_modules/@rolldown/binding-openharmony-arm64": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz",
|
||||||
"integrity": "sha512-M6AdXIXw3s+/8XpKMzdGDEXGS1S7kwUsy+rcTIUIOx5Ge4nXKCtAFHFV9YKkXvGcC5WMoTjAteLzlsQROVI0Yw==",
|
"integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -618,25 +592,10 @@
|
|||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-wasm32-wasi": {
|
|
||||||
"version": "1.2.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.1.tgz",
|
|
||||||
"integrity": "sha512-/TX0SoRGojHzSAHpfVBbavRVSazg5U3h3Y3VXfcc0cdugq6kxdqw8LPGFiPr+/7gE/60zRcsOY2Vi9b9eT0jww==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@emnapi/core": "2.0.0-alpha.3",
|
|
||||||
"@emnapi/runtime": "2.0.0-alpha.3",
|
|
||||||
"@napi-rs/wasm-runtime": "^1.2.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@rolldown/binding-win32-arm64-msvc": {
|
"node_modules/@rolldown/binding-win32-arm64-msvc": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz",
|
||||||
"integrity": "sha512-EvRrivJieyHG+AO9lleZWgq+g0+S7oV2C51yuqlcyU/R9net+sI4Pj0F+lUoP2bEr6TWX3SqFaaS0SzfLxSzkw==",
|
"integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -650,9 +609,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz",
|
||||||
"integrity": "sha512-Z4eCmn5QJ/5+azF9knpLWKfVd9aidn0mAe9TpJgvBLId9Ax3t0+JVxBmT25Bv7NBbVW1TZyKjQjQReouMeH5UQ==",
|
"integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -680,56 +639,53 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@sveltejs/acorn-typescript": {
|
"node_modules/@sveltejs/acorn-typescript": {
|
||||||
"version": "1.0.11",
|
"version": "1.0.13",
|
||||||
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz",
|
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz",
|
||||||
"integrity": "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==",
|
"integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"acorn": "^8.9.0"
|
"acorn": "^8.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@sveltejs/adapter-static": {
|
"node_modules/@sveltejs/adapter-static": {
|
||||||
"version": "3.0.10",
|
"version": "4.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@sveltejs/adapter-static/-/adapter-static-3.0.10.tgz",
|
"resolved": "https://registry.npmjs.org/@sveltejs/adapter-static/-/adapter-static-4.0.1.tgz",
|
||||||
"integrity": "sha512-7D9lYFWJmB7zxZyTE/qxjksvMqzMuYrrsyh1f4AlZqeZeACPRySjbC3aFiY55wb1tWUaKOQG9PVbm74JcN2Iew==",
|
"integrity": "sha512-svOU1OcBiJ9Kn1cdxHDmJIsBy1/iQe9STPvUFkO2/iinxPFS7r8fc9TiCaWWUgbrE+7ox6Bt4MURv3RPi7sunQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@sveltejs/kit": "^2.0.0"
|
"@sveltejs/kit": "^3.0.0-next.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@sveltejs/kit": {
|
"node_modules/@sveltejs/kit": {
|
||||||
"version": "2.70.2",
|
"version": "3.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.70.2.tgz",
|
"resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-3.2.0.tgz",
|
||||||
"integrity": "sha512-RzRoRpuR2KXqc5yMO0akQHDZeT4AslOlznGITURsqHaVbtyYP4Wn3eE3gxj9JcDyNYO0crkxhdwFHc+2vkVm6w==",
|
"integrity": "sha512-zhb8GTeFd/6BwfqaY4wKIF7eFACYOgn/KNppV6UHFBHk174B4d7xTtN7x0PxaPPlwnCTgbnpaYF6r9lirz0Biw==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@standard-schema/spec": "^1.0.0",
|
"@jridgewell/trace-mapping": "^0.3.31",
|
||||||
"@sveltejs/acorn-typescript": "^1.0.9",
|
"@rolldown/pluginutils": "^1.0.1",
|
||||||
"@types/cookie": "^0.6.0",
|
"@standard-schema/spec": "^1.1.0",
|
||||||
"acorn": "^8.16.0",
|
"cookie": "^2.0.1",
|
||||||
"cookie": "^0.6.0",
|
"devalue": "^5.9.4",
|
||||||
"devalue": "^5.8.1",
|
|
||||||
"esm-env": "^1.2.2",
|
"esm-env": "^1.2.2",
|
||||||
"kleur": "^4.1.5",
|
"magic-string": "^1.2.3",
|
||||||
"magic-string": "^0.30.5",
|
"mrmime": "^2.0.1",
|
||||||
"mrmime": "^2.0.0",
|
"sirv": "^3.0.2"
|
||||||
"set-cookie-parser": "^3.0.0",
|
|
||||||
"sirv": "^3.0.0"
|
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"svelte-kit": "svelte-kit.js"
|
"svelte-kit": "svelte-kit.js"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.13"
|
"node": ">=22.17"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@opentelemetry/api": "^1.0.0",
|
"@opentelemetry/api": "^1.0.0",
|
||||||
"@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0",
|
"@sveltejs/vite-plugin-svelte": "^7.0.0",
|
||||||
"svelte": "^4.0.0 || ^5.0.0-next.0",
|
"svelte": "^5.57.1",
|
||||||
"typescript": "^5.3.3 || ^6.0.0",
|
"typescript": "^6.0.0",
|
||||||
"vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0"
|
"vite": "^8.0.12"
|
||||||
},
|
},
|
||||||
"peerDependenciesMeta": {
|
"peerDependenciesMeta": {
|
||||||
"@opentelemetry/api": {
|
"@opentelemetry/api": {
|
||||||
@@ -740,6 +696,16 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@sveltejs/kit/node_modules/magic-string": {
|
||||||
|
"version": "1.4.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz",
|
||||||
|
"integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/sourcemap-codec": "^1.6.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@sveltejs/load-config": {
|
"node_modules/@sveltejs/load-config": {
|
||||||
"version": "0.2.1",
|
"version": "0.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.1.tgz",
|
||||||
@@ -1156,23 +1122,6 @@
|
|||||||
"svelte": "^5.25.0"
|
"svelte": "^5.25.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@tybys/wasm-util": {
|
|
||||||
"version": "0.10.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
|
|
||||||
"integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "^2.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@types/cookie": {
|
|
||||||
"version": "0.6.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
|
|
||||||
"integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",
|
|
||||||
"devOptional": true,
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@types/esrecurse": {
|
"node_modules/@types/esrecurse": {
|
||||||
"version": "4.3.1",
|
"version": "4.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
|
||||||
@@ -1193,12 +1142,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@types/trusted-types": {
|
|
||||||
"version": "2.0.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
|
||||||
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/acorn": {
|
"node_modules/acorn": {
|
||||||
"version": "8.18.0",
|
"version": "8.18.0",
|
||||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
|
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
|
||||||
@@ -1291,9 +1234,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/brace-expansion": {
|
"node_modules/brace-expansion": {
|
||||||
"version": "5.0.9",
|
"version": "5.0.12",
|
||||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
|
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
|
||||||
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
|
"integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -1341,13 +1284,17 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/cookie": {
|
"node_modules/cookie": {
|
||||||
"version": "0.6.0",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.2.tgz",
|
||||||
"integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==",
|
"integrity": "sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 0.6"
|
"node": ">=22"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/express"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/cross-spawn": {
|
"node_modules/cross-spawn": {
|
||||||
@@ -1433,9 +1380,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/devalue": {
|
"node_modules/devalue": {
|
||||||
"version": "5.9.0",
|
"version": "5.9.4",
|
||||||
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.0.tgz",
|
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz",
|
||||||
"integrity": "sha512-RWrqdArjvPbsATEhOPUo6Wndc/iWnkWKlhIrdlF3zMMYo/c3CVtoaVAyLtWxz5h8nSlkHzxnzV2uLydPXmtF+A==",
|
"integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/enhanced-resolve": {
|
"node_modules/enhanced-resolve": {
|
||||||
@@ -1644,9 +1591,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/esrap": {
|
"node_modules/esrap": {
|
||||||
"version": "2.3.0",
|
"version": "2.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz",
|
||||||
"integrity": "sha512-GQ/7RN8uOtEfNpzZzBMTzW9JBcX42oaSVtPzdF+6cEL8pqIL094iUpr9jzYGn4O4P/1S60dJ6izyT8F4LYARng==",
|
"integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@jridgewell/sourcemap-codec": "^1.4.15"
|
"@jridgewell/sourcemap-codec": "^1.4.15"
|
||||||
@@ -1936,16 +1883,6 @@
|
|||||||
"json-buffer": "3.0.1"
|
"json-buffer": "3.0.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/kleur": {
|
|
||||||
"version": "4.1.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
|
|
||||||
"integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",
|
|
||||||
"devOptional": true,
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/known-css-properties": {
|
"node_modules/known-css-properties": {
|
||||||
"version": "0.37.0",
|
"version": "0.37.0",
|
||||||
"resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz",
|
"resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz",
|
||||||
@@ -2334,9 +2271,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/nanoid": {
|
"node_modules/nanoid": {
|
||||||
"version": "3.3.16",
|
"version": "3.3.20",
|
||||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
|
||||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
"integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -2451,9 +2388,9 @@
|
|||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/picomatch": {
|
"node_modules/picomatch": {
|
||||||
"version": "4.0.5",
|
"version": "4.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
|
||||||
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
|
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -2464,9 +2401,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/postcss": {
|
"node_modules/postcss": {
|
||||||
"version": "8.5.25",
|
"version": "8.5.32",
|
||||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
|
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz",
|
||||||
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
|
"integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -2484,9 +2421,9 @@
|
|||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"nanoid": "^3.3.16",
|
"nanoid": "^3.3.20",
|
||||||
"picocolors": "^1.1.1",
|
"picocolors": "^1.1.1",
|
||||||
"source-map-js": "^1.2.1"
|
"source-map-js": "^1.2.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^10 || ^12 || >=14"
|
"node": "^10 || ^12 || >=14"
|
||||||
@@ -2665,13 +2602,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/rolldown": {
|
"node_modules/rolldown": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz",
|
||||||
"integrity": "sha512-4FKJhg8d3OiyQOA6Q1Q0hoFFpW9/OoX+VsHzpECsdsIZoOArrAK90gl59YK/Z+gnDel45bgJZK03ozH/9bCqEw==",
|
"integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@oxc-project/types": "=0.142.0",
|
"@oxc-project/types": "=0.155.0",
|
||||||
"@rolldown/pluginutils": "^1.0.0"
|
"@rolldown/pluginutils": "^1.0.0"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
@@ -2681,21 +2618,21 @@
|
|||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@rolldown/binding-android-arm64": "1.2.1",
|
"@rolldown/binding-android-arm-eabi": "1.2.15",
|
||||||
"@rolldown/binding-darwin-arm64": "1.2.1",
|
"@rolldown/binding-android-arm64": "1.2.15",
|
||||||
"@rolldown/binding-darwin-x64": "1.2.1",
|
"@rolldown/binding-darwin-arm64": "1.2.15",
|
||||||
"@rolldown/binding-freebsd-x64": "1.2.1",
|
"@rolldown/binding-darwin-x64": "1.2.15",
|
||||||
"@rolldown/binding-linux-arm-gnueabihf": "1.2.1",
|
"@rolldown/binding-freebsd-x64": "1.2.15",
|
||||||
"@rolldown/binding-linux-arm64-gnu": "1.2.1",
|
"@rolldown/binding-linux-arm-gnueabihf": "1.2.15",
|
||||||
"@rolldown/binding-linux-arm64-musl": "1.2.1",
|
"@rolldown/binding-linux-arm64-gnu": "1.2.15",
|
||||||
"@rolldown/binding-linux-ppc64-gnu": "1.2.1",
|
"@rolldown/binding-linux-arm64-musl": "1.2.15",
|
||||||
"@rolldown/binding-linux-s390x-gnu": "1.2.1",
|
"@rolldown/binding-linux-ppc64-gnu": "1.2.15",
|
||||||
"@rolldown/binding-linux-x64-gnu": "1.2.1",
|
"@rolldown/binding-linux-s390x-gnu": "1.2.15",
|
||||||
"@rolldown/binding-linux-x64-musl": "1.2.1",
|
"@rolldown/binding-linux-x64-gnu": "1.2.15",
|
||||||
"@rolldown/binding-openharmony-arm64": "1.2.1",
|
"@rolldown/binding-linux-x64-musl": "1.2.15",
|
||||||
"@rolldown/binding-wasm32-wasi": "1.2.1",
|
"@rolldown/binding-openharmony-arm64": "1.2.15",
|
||||||
"@rolldown/binding-win32-arm64-msvc": "1.2.1",
|
"@rolldown/binding-win32-arm64-msvc": "1.2.15",
|
||||||
"@rolldown/binding-win32-x64-msvc": "1.2.1"
|
"@rolldown/binding-win32-x64-msvc": "1.2.15"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/runed": {
|
"node_modules/runed": {
|
||||||
@@ -2748,13 +2685,6 @@
|
|||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/set-cookie-parser": {
|
|
||||||
"version": "3.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.2.tgz",
|
|
||||||
"integrity": "sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==",
|
|
||||||
"devOptional": true,
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/shebang-command": {
|
"node_modules/shebang-command": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||||
@@ -2794,9 +2724,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/source-map-js": {
|
"node_modules/source-map-js": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
|
||||||
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
|
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "BSD-3-Clause",
|
"license": "BSD-3-Clause",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -2813,23 +2743,22 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/svelte": {
|
"node_modules/svelte": {
|
||||||
"version": "5.56.8",
|
"version": "5.57.3",
|
||||||
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz",
|
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.3.tgz",
|
||||||
"integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==",
|
"integrity": "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@jridgewell/remapping": "^2.3.4",
|
"@jridgewell/remapping": "^2.3.5",
|
||||||
"@jridgewell/sourcemap-codec": "^1.5.0",
|
"@jridgewell/sourcemap-codec": "^1.6.0",
|
||||||
"@sveltejs/acorn-typescript": "^1.0.10",
|
"@sveltejs/acorn-typescript": "^1.0.13",
|
||||||
"@types/estree": "^1.0.5",
|
"@types/estree": "^1.0.9",
|
||||||
"@types/trusted-types": "^2.0.7",
|
"acorn": "^8.18.0",
|
||||||
"acorn": "^8.12.1",
|
|
||||||
"aria-query": "5.3.1",
|
"aria-query": "5.3.1",
|
||||||
"axobject-query": "^4.1.0",
|
"axobject-query": "^4.1.0",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"devalue": "^5.8.1",
|
"devalue": "^5.9.2",
|
||||||
"esm-env": "^1.2.1",
|
"esm-env": "^1.2.1",
|
||||||
"esrap": "^2.2.12",
|
"esrap": "^2.3.6",
|
||||||
"is-reference": "^3.0.3",
|
"is-reference": "^3.0.3",
|
||||||
"locate-character": "^3.0.0",
|
"locate-character": "^3.0.0",
|
||||||
"magic-string": "^0.30.11",
|
"magic-string": "^0.30.11",
|
||||||
@@ -3031,7 +2960,8 @@
|
|||||||
"version": "2.8.1",
|
"version": "2.8.1",
|
||||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||||
"license": "0BSD"
|
"license": "0BSD",
|
||||||
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/tw-animate-css": {
|
"node_modules/tw-animate-css": {
|
||||||
"version": "1.4.0",
|
"version": "1.4.0",
|
||||||
@@ -3089,16 +3019,16 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "8.2.0",
|
"version": "8.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.3.tgz",
|
||||||
"integrity": "sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==",
|
"integrity": "sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"lightningcss": "^1.33.0",
|
"lightningcss": "^1.33.0",
|
||||||
"picomatch": "^4.0.5",
|
"picomatch": "^4.0.7",
|
||||||
"postcss": "^8.5.23",
|
"postcss": "^8.5.28",
|
||||||
"rolldown": "~1.2.0",
|
"rolldown": "~1.2.11",
|
||||||
"tinyglobby": "^0.2.17"
|
"tinyglobby": "^0.2.17"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
@@ -3115,7 +3045,7 @@
|
|||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@types/node": "^20.19.0 || >=22.12.0",
|
"@types/node": "^20.19.0 || >=22.12.0",
|
||||||
"@vitejs/devtools": "^0.4.0",
|
"@vitejs/devtools": "^0.7.1",
|
||||||
"esbuild": "^0.27.0 || ^0.28.0",
|
"esbuild": "^0.27.0 || ^0.28.0",
|
||||||
"jiti": ">=1.21.0",
|
"jiti": ">=1.21.0",
|
||||||
"less": "^4.0.0",
|
"less": "^4.0.0",
|
||||||
|
|||||||
@@ -15,8 +15,8 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "latest",
|
"@eslint/js": "latest",
|
||||||
"@sveltejs/adapter-static": "latest",
|
"@sveltejs/adapter-static": "^4.0.1",
|
||||||
"@sveltejs/kit": "latest",
|
"@sveltejs/kit": "^3.1.1",
|
||||||
"@sveltejs/vite-plugin-svelte": "latest",
|
"@sveltejs/vite-plugin-svelte": "latest",
|
||||||
"@tailwindcss/vite": "latest",
|
"@tailwindcss/vite": "latest",
|
||||||
"eslint": "latest",
|
"eslint": "latest",
|
||||||
@@ -24,14 +24,15 @@
|
|||||||
"eslint-plugin-svelte": "latest",
|
"eslint-plugin-svelte": "latest",
|
||||||
"prettier": "latest",
|
"prettier": "latest",
|
||||||
"prettier-plugin-svelte": "latest",
|
"prettier-plugin-svelte": "latest",
|
||||||
"svelte": "latest",
|
"svelte": "^5.57.3",
|
||||||
"svelte-check": "latest",
|
"svelte-check": "latest",
|
||||||
"tailwindcss": "latest",
|
"tailwindcss": "latest",
|
||||||
"tw-animate-css": "latest",
|
"tw-animate-css": "latest",
|
||||||
"vite": "latest"
|
"vite": "^8.3.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
"@gabriel20xx/design-tokens": "file:../shared/packages/design-tokens",
|
||||||
|
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
||||||
"@lucide/svelte": "latest",
|
"@lucide/svelte": "latest",
|
||||||
"@tanstack/svelte-query": "latest",
|
"@tanstack/svelte-query": "latest",
|
||||||
"bits-ui": "latest",
|
"bits-ui": "latest",
|
||||||
|
|||||||
@@ -120,12 +120,13 @@ export async function logout() {
|
|||||||
// always be the account's current values when the caller isn't actually
|
// always be the account's current values when the caller isn't actually
|
||||||
// changing them. ProfileDialog's form (@gabriel20xx/web-ui) always pre-fills
|
// changing them. ProfileDialog's form (@gabriel20xx/web-ui) always pre-fills
|
||||||
// and requires both fields, so AppShell.svelte's saveProfile always has them
|
// and requires both fields, so AppShell.svelte's saveProfile always has them
|
||||||
// on hand. newPassword remains genuinely optional (omitted/blank leaves the
|
// on hand. When changing the password, the shared ProfileDialog also supplies
|
||||||
// password unchanged).
|
// currentPassword and (when enabled) totpToken for sharedauth's reauthentication
|
||||||
export async function updateCredentials({ newUsername, newEmail, newPassword }) {
|
// check. newPassword remains optional when it is not being changed.
|
||||||
|
export async function updateCredentials({ newUsername, newEmail, newPassword, currentPassword, totpToken }) {
|
||||||
return request('/api/auth/credentials', {
|
return request('/api/auth/credentials', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ username: newUsername, email: newEmail, password: newPassword }),
|
body: JSON.stringify({ username: newUsername, email: newEmail, password: newPassword, currentPassword, totpToken }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { test } from 'node:test';
|
||||||
|
|
||||||
|
import { updateCredentials } from './api.js';
|
||||||
|
|
||||||
|
test('updateCredentials forwards current password and TOTP proof', async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
let captured;
|
||||||
|
globalThis.fetch = async (url, options) => {
|
||||||
|
captured = { url, options };
|
||||||
|
return { ok: true, status: 200, json: async () => ({}) };
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await updateCredentials({
|
||||||
|
newUsername: 'owner',
|
||||||
|
newEmail: 'owner@example.com',
|
||||||
|
newPassword: 'new-password',
|
||||||
|
currentPassword: 'current-password',
|
||||||
|
totpToken: '123456',
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(captured.url, '/api/auth/credentials');
|
||||||
|
assert.deepEqual(JSON.parse(captured.options.body), {
|
||||||
|
username: 'owner',
|
||||||
|
email: 'owner@example.com',
|
||||||
|
password: 'new-password',
|
||||||
|
currentPassword: 'current-password',
|
||||||
|
totpToken: '123456',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('updateCredentials omits reauthentication proof when password is unchanged', async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
let captured;
|
||||||
|
globalThis.fetch = async (_url, options) => {
|
||||||
|
captured = options;
|
||||||
|
return { ok: true, status: 200, json: async () => ({}) };
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await updateCredentials({ newUsername: 'owner', newEmail: 'owner@example.com' });
|
||||||
|
assert.deepEqual(JSON.parse(captured.body), {
|
||||||
|
username: 'owner',
|
||||||
|
email: 'owner@example.com',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -2,14 +2,7 @@
|
|||||||
import { DropdownMenu } from 'bits-ui';
|
import { DropdownMenu } from 'bits-ui';
|
||||||
import { cn } from '$lib/utils/cn.js';
|
import { cn } from '$lib/utils/cn.js';
|
||||||
|
|
||||||
let {
|
let { ref = $bindable(null), class: className, sideOffset = 6, align = 'end', children, ...restProps } = $props();
|
||||||
ref = $bindable(null),
|
|
||||||
class: className,
|
|
||||||
sideOffset = 6,
|
|
||||||
align = 'end',
|
|
||||||
children,
|
|
||||||
...restProps
|
|
||||||
} = $props();
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<DropdownMenu.Portal>
|
<DropdownMenu.Portal>
|
||||||
|
|||||||
@@ -30,6 +30,8 @@
|
|||||||
newUsername: input.username.trim(),
|
newUsername: input.username.trim(),
|
||||||
newEmail: input.email.trim(),
|
newEmail: input.email.trim(),
|
||||||
newPassword: input.password || undefined,
|
newPassword: input.password || undefined,
|
||||||
|
currentPassword: input.currentPassword,
|
||||||
|
totpToken: input.totpToken,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -68,7 +68,6 @@
|
|||||||
type="checkbox"
|
type="checkbox"
|
||||||
checked={layoutState.wide}
|
checked={layoutState.wide}
|
||||||
onchange={(event) => layoutState.setWide(event.currentTarget.checked)}
|
onchange={(event) => layoutState.setWide(event.currentTarget.checked)}
|
||||||
|
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<div class="sc-form-actions">
|
<div class="sc-form-actions">
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/env';
|
||||||
|
|
||||||
export const languages = [
|
export const languages = [
|
||||||
{ id: 'ar', label: 'العربية' },
|
{ id: 'ar', label: 'العربية' },
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/env';
|
||||||
|
|
||||||
const STORAGE_KEY = 'collabtable-wide-layout';
|
const STORAGE_KEY = 'collabtable-wide-layout';
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/env';
|
||||||
|
|
||||||
const STORAGE_KEY = 'collabtable-theme';
|
const STORAGE_KEY = 'collabtable-theme';
|
||||||
|
|
||||||
|
|||||||
@@ -104,16 +104,18 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<Pagination
|
<div class="mt-4">
|
||||||
{page}
|
<Pagination
|
||||||
{pageSize}
|
{page}
|
||||||
pageLength={pageItems.length}
|
{pageSize}
|
||||||
totalLength={listItems.length}
|
pageLength={pageItems.length}
|
||||||
onPaging={(e) => {
|
totalLength={listItems.length}
|
||||||
page = e.page;
|
onPaging={(e) => {
|
||||||
pageSize = e.pageSize;
|
page = e.page;
|
||||||
}}
|
pageSize = e.pageSize;
|
||||||
/>
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
import adapter from '@sveltejs/adapter-static';
|
|
||||||
|
|
||||||
/** @type {import('@sveltejs/kit').Config} */
|
|
||||||
const config = {
|
|
||||||
kit: {
|
|
||||||
// Static SPA build: the Go server serves this output and falls back to
|
|
||||||
// index.html for any path so SvelteKit's client-side router can take over.
|
|
||||||
adapter: adapter({
|
|
||||||
fallback: 'index.html',
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export default config;
|
|
||||||
+16
-1
@@ -3,6 +3,7 @@ import path from 'node:path';
|
|||||||
import tailwindcss from '@tailwindcss/vite';
|
import tailwindcss from '@tailwindcss/vite';
|
||||||
import { sveltekit } from '@sveltejs/kit/vite';
|
import { sveltekit } from '@sveltejs/kit/vite';
|
||||||
import { defineConfig } from 'vite';
|
import { defineConfig } from 'vite';
|
||||||
|
import adapter from '@sveltejs/adapter-static';
|
||||||
|
|
||||||
// Real installed frontend dependency versions for the About page, resolved from
|
// Real installed frontend dependency versions for the About page, resolved from
|
||||||
// node_modules (not the package.json semver range) so it can't drift from what's bundled.
|
// node_modules (not the package.json semver range) so it can't drift from what's bundled.
|
||||||
@@ -29,7 +30,21 @@ const frontendTechStack = FRONTEND_TECH_STACK_PACKAGES.flatMap(({ name, pkg }) =
|
|||||||
});
|
});
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [tailwindcss(), sveltekit()],
|
plugins: [
|
||||||
|
tailwindcss(),
|
||||||
|
sveltekit({
|
||||||
|
// SvelteKit 3 removed the $lib alias; keep it pointing at src/lib so imports stay unchanged.
|
||||||
|
alias: { $lib: 'src/lib' },
|
||||||
|
// Static SPA build: the Go server serves this output and falls back to
|
||||||
|
// index.html for any path so SvelteKit's client-side router can take over.
|
||||||
|
adapter: adapter({
|
||||||
|
fallback: 'index.html',
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
resolve: {
|
||||||
|
preserveSymlinks: true,
|
||||||
|
},
|
||||||
define: {
|
define: {
|
||||||
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Fix the primary color chosen in `PrimaryColorPicker` not reaching the app's UI. The choice is now applied through a stylesheet that also targets `[data-theme]` elements, such as the `AppShell` root, so it takes effect immediately everywhere instead of being hidden by those elements' own theme tokens. The picker also sets the `--sc-*` primary, accent, and hover tokens the shared components read.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": minor
|
||||||
|
---
|
||||||
|
|
||||||
|
`UserManagement` is removed from the package, along with its `UserListRequest`, `UserCreateRequest`, `UserUpdateRequest`, and `UserDeleteRequest` types and its `.sc-user-*` styles. The component was only used by AuthGuard, which now owns a copy in `features/users`. Applications that still render it should keep their own copy or build their own user table. `KnownRole`, `ManagedUser`, `UserCreateInput`, and `UserUpdateInput` remain exported.
|
||||||
@@ -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"
|
||||||
|
|
||||||
|
|||||||
Vendored
+6
@@ -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)
|
||||||
|
|||||||
+155
@@ -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 .
|
||||||
Vendored
+51
-2
@@ -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
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# Performance Report — shared
|
||||||
|
|
||||||
|
- **Project:** shared
|
||||||
|
- **Path:** /workspace/Personal/Web/shared
|
||||||
|
- **Analyzed:** 2026-10-16
|
||||||
|
- **Commit:** 22887fe on main
|
||||||
|
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
|
||||||
|
- **Stack:** Go 1.25 (`backend/`, module `repos.gfranz.ch/Gabriel20xx/shared/backend`, pgx, chi, coder/websocket, goose); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; PowerShell and Node scripts; Gitea and GitHub Actions. No Dockerfile, compose file or `.dockerignore` exists in the repo.
|
||||||
|
- **Scope:** This is a shared library consumed by other projects (vendored snapshot), not an application. Read: all first-party Go packages except `backend/auth/*` and `backend/config` (reviewed in a separate pass), the Node, Python and Java AuthGuard clients and stores, the web-ui components that perform I/O or timers, root manifests, `.github` and `.gitea` workflows, and `scripts/`. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies (used only for coverage notes). Paths below are relative to the repo root. Backend findings come from read-only static review passes; the highest-severity citations were re-checked in the code. Nothing was built, run or profiled.
|
||||||
|
- **Updated:** 2026-10-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
|
||||||
|
|
||||||
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|
|---|---:|---:|---:|---:|
|
||||||
|
| Critical | 0 | 0 | 0 | 0 |
|
||||||
|
| High | 1 | 1 | 0 | 0 |
|
||||||
|
| Medium | 4 | 4 | 0 | 0 |
|
||||||
|
| Low | 4 | 0 | 0 | 4 |
|
||||||
|
| 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.
|
||||||
|
|
||||||
|
## Issues
|
||||||
|
|
||||||
|
### 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)
|
||||||
|
- **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).
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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).
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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**
|
||||||
|
- **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)
|
||||||
|
- **Description:** The Python client performs blocking `urllib` calls through `asyncio.to_thread`, which uses the event loop's default executor shared with other `to_thread` users, and opens a new connection per call. In Node the abort timer is set at line 177; the review pass reports it is cleared once headers arrive, which would leave the body read without a deadline (needs verification at `authclient.js:186-188`).
|
||||||
|
- **Impact:** A slow AuthGuard can exhaust executor threads needed elsewhere in the process, and a stalled response body can hang a request.
|
||||||
|
- **Recommendation:** Use a pooled async HTTP client (httpx or aiohttp in Python; undici or a reused agent in Node), and keep the timeout active until the body is fully read, or apply an overall deadline.
|
||||||
|
|
||||||
|
### P-007 · Admin user operations over-fetch and make sequential calls; the Go store lists all users · **Low**
|
||||||
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:644-652` (updating one user lists all users to find it), `packages/python-backend/src/shared_backend/authproxy.py:406-416` (`/status` makes two sequential AuthGuard calls), `backend/auth/store.go:294` (`ListUsers` returns every row with no limit)
|
||||||
|
- **Description:** After a user update the Python handler fetches the entire user list to locate one row. The status endpoint makes two independent AuthGuard calls one after the other. The Go store's `ListUsers` has no `LIMIT`, and the client list calls have no pagination.
|
||||||
|
- **Impact:** Latency and memory grow with the number of accounts.
|
||||||
|
- **Recommendation:** Add a get-by-id method (or return the updated record from the update call), run independent calls concurrently, and add pagination to the list endpoints.
|
||||||
|
|
||||||
|
### P-008 · CarrierNode client has no transport timeout; the media proxy depends on caller deadlines · **Low**
|
||||||
|
- **Location:** `backend/carriernodeclient/carriernodeclient.go:28-30` (package-level `http.Client` with no `Timeout`; the comment says callers set context deadlines), `backend/carriernodeclient/carriernodeclient.go:171-213` (`Proxy` uses the incoming request context), `backend/carriernodeclient/carriernodeclient.go:510-522` (thumbnail HEAD probe on the same client)
|
||||||
|
- **Description:** The shared client is deliberately timeout-free so that large media streams are not cut off. Control calls and the proxy paths rely on each caller to attach a deadline. Where a caller does not, a hung CarrierNode holds the request open indefinitely.
|
||||||
|
- **Impact:** Goroutines and client connections can be tied up by a slow upstream. The severity depends on consumers' server-level timeouts (needs verification).
|
||||||
|
- **Recommendation:** Set a `ResponseHeaderTimeout` on the transport so that stalled upstreams fail quickly while streams still work. Attach deadlines to control calls, and document the requirement for callers that use the proxy paths.
|
||||||
|
|
||||||
|
### P-009 · Status widget polls two endpoints every 15 seconds regardless of tab visibility · **Low**
|
||||||
|
- **Location:** `packages/web-ui/src/lib/components/StatusWidget.svelte:76-79` (`onMount` starts a 15 s interval that issues `/healthz` and `/ready` requests)
|
||||||
|
- **Description:** Each mounted `StatusWidget` polls both probes on a fixed interval, with no check for `document.hidden`. Consumers may mount the widget on several pages or in several open tabs. The cleanup on unmount is correct.
|
||||||
|
- **Impact:** Background tabs and multiple widgets add steady load to every backend that exposes these probes.
|
||||||
|
- **Recommendation:** Pause polling while `document.hidden` is true and refresh on `visibilitychange`. Consider a longer interval for `/ready`, which may query the database.
|
||||||
|
|
||||||
|
### P-010 · Info: the root `prepare` script builds on install, and CI runs the build twice · **Info**
|
||||||
|
- **Location:** `package.json` (`prepare` runs `npm run build` and `build-root-styles`; `test` runs `npm run build` before `test:node-backend`), `.github/workflows/tests.yml` (`npm ci` followed by `npm test`)
|
||||||
|
- **Description:** `npm ci` runs the root `prepare` script, which builds the web-ui package, and then `npm test` builds it again.
|
||||||
|
- **Impact:** Extra CI time on every run. No runtime impact.
|
||||||
|
- **Recommendation:** Either skip the duplicate build in `test`, or move the build out of `prepare` into an explicit CI step.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- **Docker:** No Dockerfile, compose file or `.dockerignore` exists in this repository, so image size, multi-stage builds and base-image checks do not apply here. Consumer projects that build images from the vendored snapshot should be reviewed separately.
|
||||||
|
- **Frontend checks:** No whole-library imports were found; `@lucide/svelte` is imported by name in every component. No `{@html}`, unbounded caches or leaked intervals were found in the web-ui, and the timers and listeners in `MediaPlayer`, `MediaPlayerControls`, `StatusWidget`, `AppShell` and `notifications.svelte.ts` are cleaned up. `shared-styles.css` (1134 lines, about 21 KB) is loaded in full by consumers. As a component library it has no route-level code-splitting, which is expected rather than a defect. Four of seven `{#each}` blocks in the components are keyed; the remaining ones are listed under quality findings.
|
||||||
|
- **HTTP caching and compression:** Not applicable to the library code; the backends are API services and the static styles are shipped to consumers' own build pipelines.
|
||||||
|
- **Not verified:** No query plans (no database access), 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).
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
# Code Quality Report — shared
|
||||||
|
|
||||||
|
- **Project:** shared
|
||||||
|
- **Path:** /workspace/Personal/Web/shared
|
||||||
|
- **Analyzed:** 2026-10-16
|
||||||
|
- **Commit:** 22887fe on main
|
||||||
|
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
|
||||||
|
- **Stack:** Go 1.25 (`backend/`); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`, ruff configured); Java 8 target with Jackson and JUnit 5 (`packages/java-backend`); Svelte 5 and TypeScript with svelte-check (`packages/web-ui`); PowerShell and Node build and sync scripts; Gitea and GitHub Actions.
|
||||||
|
- **Scope:** A shared library consumed by other projects as a vendored snapshot. Read: root manifests and changesets, `.github` and `.gitea` workflows, `.githooks`, `scripts/` (sync, build, and the `scripts/media` tooling), all four language packages (AuthGuard clients, stores, TOTP, config, coreconfig, proxies), Go packages under `backend/` (auth read in a separate pass), and the web-ui library source (barrel, styles, primary-color, notifications, components that do I/O or timers). Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), and test bodies except for coverage notes. Backend findings 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
|
||||||
|
|
||||||
|
| Severity | Count |
|
||||||
|
|---|---:|
|
||||||
|
| Critical | 0 |
|
||||||
|
| High | 0 |
|
||||||
|
| Medium | 9 |
|
||||||
|
| Low | 7 |
|
||||||
|
| Info | 0 |
|
||||||
|
|
||||||
|
The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-test code, no `any` or `@ts-ignore` in the web-ui, and parameterised SQL throughout. The weak spots are operational: several scripts and workflows no longer match the repository layout, Java and most Go packages are not tested in CI, the publish pipeline skips the checks that exist for pull requests, and the four AuthGuard clients have drifted apart in behaviour.
|
||||||
|
|
||||||
|
## Issues
|
||||||
|
|
||||||
|
### 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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
|
||||||
|
- **Description:** Node and Python write incompatible hash formats into the same column, so a database shared between them cannot be verified by both. Python's list and create paths return the hash in their payloads; Node's do not. Java's middleware lets an unchecked exception escape where Node returns 401. The startup retry policy differs, so Python retries forever on errors that Node would surface immediately.
|
||||||
|
- **Impact:** A service behaves differently depending on which runtime serves it, and a password hash can reach an API response in Python.
|
||||||
|
- **Recommendation:** Standardise the hash format (or rehash on login), strip `password_hash` from every DTO, align the retry policy and the middleware failure modes, and add cross-language contract tests that run the same fixtures against each client.
|
||||||
|
- **Status:** Fixed 2026-10-20 — Node now writes the same prefixed bcrypt cost-12 scheme as Go and Python, and each runtime verifies current/legacy bcrypt plus both legacy Node PBKDF2 formats. Successful legacy verification returns an upgraded hash; AuthGuard conditionally persists that upgrade after a successful login. Long legacy PBKDF2 passwords use the explicit `bcrypt-sha256$` scheme to avoid bcrypt truncation, while new passwords over 72 bytes are rejected. The Java AuthClient does not create or verify stored password hashes. Node also depends on `bcryptjs` to share the scheme. The shared contract covers current, low-cost, malformed, legacy and over-limit cases. Files: `backend/auth/password.go`, `backend/auth/contract_test.go`, `Central/AuthGuard/internal/httpapi/{auth.go,server.go,server_test.go}`, `packages/node-backend/{package.json,src/auth.js,test/auth.test.js,test/contract.test.js}`, `packages/python-backend/src/shared_backend/auth.py`, `packages/python-backend/tests/{test_core.py,test_contract.py}`, `contract/auth-contract.json`.
|
||||||
|
|
||||||
|
### Q-009 · The Node and web-ui code has no linter, formatter or component tests · **Medium** · Fixed
|
||||||
|
- **Location:** `.github/workflows/lint.yml` (Node job runs `npm run lint`, which is svelte-check and `node --check` only), `scripts/media/lint-all.mjs:57-64` (expects ESLint and Prettier configs in a package that does not have them), `packages/web-ui/` (no test files and no test script), `packages/node-backend/package.json` (no lint script)
|
||||||
|
- **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.
|
||||||
|
- **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**
|
||||||
|
- **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)
|
||||||
|
- **Description:** An AuthGuard outage looks like a wrong authenticator code, so operators and users cannot tell the two apart. Logout clears the browser cookie even when the upstream call fails, which can leave a valid server-side session behind.
|
||||||
|
- **Impact:** Harder debugging, misleading user feedback, and possible sessions that survive a logout.
|
||||||
|
- **Recommendation:** Catch the specific error classes. Return 502 or 503 for upstream failures, log transport errors at warning level, and clear local cookies only after the upstream logout succeeds or fails in a known way.
|
||||||
|
|
||||||
|
### Q-011 · Node version drift between publish and CI · **Low**
|
||||||
|
- **Location:** `.gitea/workflows/publish-npm.yml:24` (`node-version: 22`), `.github/workflows/lint.yml` and `.github/workflows/tests.yml` (`node-version: '24'`), `packages/node-backend/package.json` (`engines` `>=20`)
|
||||||
|
- **Description:** The packages are published from a build on Node 22, while lint and tests run on Node 24, and the package claims support from Node 20.
|
||||||
|
- **Impact:** The published artifacts are built with a different toolchain from the one that is tested, and the supported range is not exercised.
|
||||||
|
- **Recommendation:** Use one Node version for build and publish that matches what CI tests, and add a matrix entry for the minimum supported version.
|
||||||
|
|
||||||
|
### Q-012 · Package export maps are incomplete, and the root `.` export points at the README · **Low**
|
||||||
|
- **Location:** `package.json:19` (`"." : "./README.md"`), `package.json:28-33` (no `./node-backend/coreconfig` export, though the file ships in `files`), `packages/node-backend/package.json` `exports` (no `./totp` or `./authclient`, although both files exist and are re-exported from `src/index.js`), `packages/python-backend/src/shared_backend/__init__.py` (does not re-export `APIError`)
|
||||||
|
- **Description:** The root package's main entry resolves to a documentation file. Subpath imports for `totp` and `authclient` fail with `ERR_PACKAGE_PATH_NOT_EXPORTED` even though the modules exist, and the root export map omits `coreconfig`.
|
||||||
|
- **Impact:** Consumers cannot import documented modules, and tooling that resolves the package main gets the README.
|
||||||
|
- **Recommendation:** Point `.` at a real index module or remove it, add the missing subpath exports, and add a smoke test that imports every exported path.
|
||||||
|
|
||||||
|
### Q-013 · Versioning and changeset hygiene · **Low**
|
||||||
|
- **Location:** `.changeset/config.json:11` (ignores `@gabriel20xx/shared-workspace`, which does not exist; the root package is `@gabriel20xx/shared-code`), `packages/java-backend/pom.xml:6` (`0.1.0`, while the npm and Python packages are `0.1.1`), `packages/python-backend/pyproject.toml` (`0.1.1`, versioned by hand)
|
||||||
|
- **Description:** Changesets cover only the npm packages. Python and Java versions are maintained by hand, and recent changes to those packages (for example commits `f5a20b7`, `de9b599` and `97a5ecd`) have no changeset. The ignore entry names a package that does not exist.
|
||||||
|
- **Impact:** Release notes and version numbers can drift between runtimes.
|
||||||
|
- **Recommendation:** Correct the ignore entry. Either add changesets for the Python and Java packages, or document that they are versioned by tag and record the tag in the changelog.
|
||||||
|
|
||||||
|
### Q-014 · Stale README and comments after the component removal and the monorepo extraction · **Low**
|
||||||
|
- **Location:** `README.md:31` ("22 components"; the working-tree removal leaves 20 exports in `packages/web-ui/src/lib/index.ts`), `README.md:24` (names a `mediaauth` package that is not in `backend/`), `backend/authproxy/authproxy.go:9` and `backend/mediacore/migrate.go:15` (refer to `mediaauth`), `.gitignore:4` (`webui/.svelte-kit/` targets a directory that was removed)
|
||||||
|
- **Description:** Documentation names a package and a count that no longer match the tree, and a `.gitignore` entry targets a directory that no longer exists.
|
||||||
|
- **Impact:** Misleading documentation for consumers and maintainers.
|
||||||
|
- **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**
|
||||||
|
- **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 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.
|
||||||
|
- **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**
|
||||||
|
- **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)
|
||||||
|
- **Description:** The navigation list comes from a prop and is rendered without a key, so Svelte reconciles it by index. The sign-in field applies the setup minimum, so an account whose existing password is shorter cannot sign in through this form. Whether such accounts exist needs verification; the server enforces eight characters at setup (`backend/auth/proxy.go:1460`, `packages/node-backend/src/auth.js:57`, `packages/python-backend/src/shared_backend/auth.py:124`).
|
||||||
|
- **Impact:** Minor re-render inefficiency, and a possible lockout of legacy accounts.
|
||||||
|
- **Recommendation:** Key the each block by `item.href`, and apply `minlength` only when setup is required.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- **Checked, clean:** No `TODO`, `FIXME`, `HACK` or `XXX` markers in first-party non-test code. No `any`, `@ts-ignore`, `@ts-expect-error` or `svelte-ignore` in `packages/web-ui/src`. No `{@html}`, `innerHTML`, `eval` or `new Function` in the web-ui or scripts. External links use `rel="noreferrer"`. Timers and document listeners are cleaned up in `StatusWidget`, `MediaPlayer`, `MediaPlayerControls`, `PrimaryColorPicker` and `notifications.svelte.ts`.
|
||||||
|
- **Checked, consistent:** Go code is gofmt-checked and `go vet`-checked in CI. Python code is ruff-checked (`E`, `F`, `I`). Node syntax is checked for `packages/node-backend`. Parameterised SQL is used across the Go, Node and Python stores.
|
||||||
|
- **Duplication by design:** The AuthGuard client exists in four languages on purpose. Q-008 covers where the behaviour has drifted.
|
||||||
|
- **Verification:** Node backend: 73 tests passed. Python backend: 122 tests and Ruff passed. Web-ui: 29 tests, package build, `svelte-check`, `npm run lint`, and `format:check` passed. Go: `gofmt -l`, `go test ./...` and `go vet ./...` passed. Java tests were not run because no JDK or Maven is available. No database-backed integration test ran.
|
||||||
|
- **Not verified:** Whether consumers depend on the removed `UserManagement` export or the `MediaPlayerControls` barrel removal (the changeset says only AuthGuard used it). Whether the `packages/media-shared-assets` and `media-backend` paths in history were ever shipped.
|
||||||
|
- **Excluded from analysis:** `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies beyond coverage notes.
|
||||||
+17
-6
@@ -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.
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
# Security Report — shared
|
||||||
|
|
||||||
|
- **Project:** shared
|
||||||
|
- **Path:** /workspace/Personal/Web/shared
|
||||||
|
- **Analyzed:** 2026-10-16
|
||||||
|
- **Commit:** 22887fe on main
|
||||||
|
- **Working tree:** Contains uncommitted changes from the earlier finding pass and this continuation; no changes have been committed.
|
||||||
|
- **Stack:** Go 1.25 (`backend/`: session proxy, AuthGuard client, websocket sync hub, media core, CarrierNode client, log shipper, Postgres helpers, goose migrations); Node.js ESM with `pg` (`packages/node-backend`); Python 3.10+ with asyncpg, bcrypt and optional FastAPI (`packages/python-backend`); Java 8 target with Jackson (`packages/java-backend`); Svelte 5 and TypeScript (`packages/web-ui`); PostgreSQL; Gitea and GitHub Actions. No Dockerfile is present.
|
||||||
|
- **Scope:** A shared library that other projects vendor as a snapshot. The AuthGuard identity service itself is not in this repository, so every finding that depends on AuthGuard's cookie attributes, rate limits or role enforcement is marked "needs verification". Read: all first-party code in the four languages (the Go auth package was read in a separate pass), the web-ui library source, workflows, scripts and manifests; git history was searched for credential-shaped content. Excluded: `node_modules`, `packages/web-ui/dist` and `.svelte-kit` (gitignored, not tracked), `package-lock.json` and `go.sum` (versions only), test bodies except to look for fixtures. Backend findings 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
|
||||||
|
|
||||||
|
| Severity | Count | Fixed | Not reproduced | Open |
|
||||||
|
|---|---:|---:|---:|---:|
|
||||||
|
| Critical | 1 | 1 | 0 | 0 |
|
||||||
|
| High | 3 | 2 | 0 | 1 |
|
||||||
|
| Medium | 13 | 12 | 0 | 1 |
|
||||||
|
| Low | 5 | 0 | 0 | 5 |
|
||||||
|
| 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.
|
||||||
|
|
||||||
|
## Issues
|
||||||
|
|
||||||
|
### 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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`)
|
||||||
|
- **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 `+`.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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).
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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).
|
||||||
|
- **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.
|
||||||
|
- **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** · 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`)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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`)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · Open
|
||||||
|
- **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.
|
||||||
|
- **Impact:** A stolen or fixated session cookie becomes permanent account takeover, because the attacker can set a new password. Needs verification of whether AuthGuard revokes other sessions on password change.
|
||||||
|
- **Recommendation:** Require the current password (and a TOTP code when enabled) for password or email changes, and revoke other sessions when the password changes.
|
||||||
|
- **Status:** Partly fixed 2026-10-20 — the decided rule is implemented: Go and Python self-service profile updates require `currentPassword` for a password change and a TOTP code when enabled; both reauthenticate through AuthGuard, omit proof fields from the managed-user update, and attempt to clear the temporary session. The shared web-ui prompts for and sends those values. No self-service `UpdateMe` route exists in the shared Node or Java clients. Still open: revoking other sessions after a password change is controlled by AuthGuard and has no owner decision. Files: `backend/auth/proxy.go`, `backend/auth/proxy_handlers_test.go`, `packages/python-backend/src/shared_backend/authproxy.py`, `packages/python-backend/tests/test_authproxy.py`, `packages/web-ui/src/lib/components/ProfileDialog.svelte`, `packages/web-ui/tests/ProfileDialog.test.ts`.
|
||||||
|
|
||||||
|
### S-011 · TOTP codes can be replayed within their validity window in every runtime · **Medium** · Open
|
||||||
|
- **Location:** `backend/auth/totp.go` and `packages/{node-backend/src/totp.js,python-backend/src/shared_backend/totp.py,java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}` return the matched time step; Go, Node and Python auth stores persist it.
|
||||||
|
- **Description:** Verification accepts the current and adjacent 30-second steps and records nothing about use. A code that an attacker observes stays valid for about 90 seconds and can be submitted repeatedly within that window.
|
||||||
|
- **Impact:** A phished or shoulder-surfed code can be reused.
|
||||||
|
- **Recommendation:** Return the matched time step, persist `last_used_step` per user, and reject any step less than or equal to it, updating it atomically.
|
||||||
|
- **Status:** Fixed 2026-10-20 — verifiers return the matched time step; Go, Node and Python stores add `last_used_step` through additive schema changes and atomically advance it only when the step is newer. AuthGuard consumes steps for login, enrollment and disable, so a code already used in its validity window is refused. Files: `backend/auth/{totp.go,store.go}`, `Central/AuthGuard/internal/httpapi/{auth.go,totp.go,server.go}`, `packages/{node-backend/src/{auth.js,totp.js},python-backend/src/shared_backend/{auth.py,totp.py},java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java}`. Go, Node, Python and web-ui checks passed; Java tests could not run because no JDK or Maven is available.
|
||||||
|
|
||||||
|
### S-012 · The Java client parses the authentication decision with unanchored regular expressions · **Medium** · Fixed
|
||||||
|
- **Location:** `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java:109-112` (patterns for `valid`, `user_id`, `username`, `role`), with the parsing in `validate` (around lines 829-851, per review)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · Fixed
|
||||||
|
- **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.
|
||||||
|
- **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`.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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.
|
||||||
|
- **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** · 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)
|
||||||
|
- **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).
|
||||||
|
- **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**
|
||||||
|
- **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)
|
||||||
|
- **Description:** `IsAdmin` admits moderators while `NormalizeRole` and `CanManageUsers` do not. The assignment check exists but is not used, and roles from requests are forwarded without a local check.
|
||||||
|
- **Impact:** Moderators may receive access that the other definitions do not grant, and an escalation becomes possible if AuthGuard or the calling service does not enforce role rules (needs verification).
|
||||||
|
- **Recommendation:** Use one typed role set. Call `CanAssignRole` in the managed-user handlers as defence in depth, and restrict or document what moderators can do.
|
||||||
|
|
||||||
|
### S-019 · Reset codes are weak and unlimited, and TOTP secrets are stored in plaintext · **Low**
|
||||||
|
- **Location:** `backend/auth/reset.go:37` (four random bytes, so 32 bits), `backend/auth/reset.go:48` (code printed to stdout), `packages/node-backend/src/auth.js:106` (`randomBytes(4)`), `packages/python-backend/src/shared_backend/auth.py:83` and `:101` (`token_hex(4)` with `compare_digest`), `packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/ResetManager.java` (per review), `backend/auth/store.go:84` (`totp_secret TEXT`), `packages/node-backend/src/auth.js:30` (`totp_secret TEXT`)
|
||||||
|
- **Description:** Administrator reset codes are 32-bit values. They can be guessed with unlimited attempts during their five-minute life, and calling `request` again rotates them. The code is printed to stdout, where log shipping may capture it. TOTP seeds are stored in plaintext in `auth_users`.
|
||||||
|
- **Impact:** A reset code can be brute-forced within its lifetime, and second-factor seeds are exposed if the database leaks.
|
||||||
|
- **Recommendation:** Add an attempt counter with lockout, and require an authenticated caller to request a code. Do not print codes to stdout in production. Encrypt TOTP secrets at rest with an application key kept outside the database.
|
||||||
|
|
||||||
|
### S-020 · Insecure-by-configuration options: secure cookies off by default, and database certificate verification can be disabled · **Low**
|
||||||
|
- **Location:** `packages/python-backend/src/shared_backend/authproxy.py:244` (`secure_cookie` defaults to `False`), `packages/python-backend/src/shared_backend/authproxy.py:276` (`Secure` applied to cleared cookies), `packages/python-backend/src/shared_backend/authproxy.py:279-281` (AuthGuard `Set-Cookie` values forwarded unchanged), `packages/node-backend/src/config.js:48-51` (`DATABASE_SSL_ALLOW_INVALID` sets `rejectUnauthorized: false`)
|
||||||
|
- **Description:** The Python proxy does not set or validate `Secure`, `HttpOnly` or `SameSite` on forwarded session cookies, and `Secure` defaults to off. The Node configuration lets an environment flag turn off database certificate verification. Both are opt-in, but the defaults are the unsafe choice.
|
||||||
|
- **Impact:** Session cookies can travel over cleartext behind an HTTPS misconfiguration, and database connections can be made without certificate checks.
|
||||||
|
- **Recommendation:** Default `secure_cookie` to true, or derive it from the request scheme. Rewrite forwarded cookie attributes, and log a warning when database TLS verification is disabled.
|
||||||
|
|
||||||
|
### S-021 · CI workflows and repository hygiene need hardening, and history contains an example file with embedded database credentials · **Low**
|
||||||
|
- **Location:** `.github/workflows/lint.yml:37`, `:39`, `:59`, `:61` and `.github/workflows/tests.yml` (actions referenced by mutable tags such as `actions/checkout@v4`), `.gitea/workflows/publish-npm.yml:71`, `.gitea/workflows/publish-go.yml:61`, `.gitea/workflows/publish-python.yml:43` (registry token passed as a `curl --user` argument, so it is visible in process listings on the runner), `.gitignore` (no rules for `.env*`, `*.pem`, `*.key` or `.npmrc`), git history: commit `acde180` added `media-backend/.env.example`, which the working tree no longer contains; its `DATABASE_URL` line contains embedded credentials (value redacted, needs verification of whether it was ever valid)
|
||||||
|
- **Description:** Action references are mutable tags rather than commit SHAs. Workflow permissions are correctly `contents: read`. Registry credentials appear on command lines during upload, although the npm workflow correctly writes its token to a file. The ignore rules do not block common secret files, so an accidental commit would not be stopped. The removed example file shows that a connection string with credentials was committed once.
|
||||||
|
- **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.
|
||||||
|
|
||||||
|
### 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)
|
||||||
|
- **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.
|
||||||
|
- **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
|
||||||
|
- **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.
|
||||||
|
- **Checked, no issue found:** SQL is parameterised in the Go, Node and Python stores and in the mediacore queries; dynamic `SET` fragments use fixed column names. Tokens and secrets come from `crypto/rand`, `crypto.randomBytes`, Python `secrets` and `SecureRandom`; no `math/rand`, `Math.random`, `random.` or `java.util.Random` was found. Session tokens are 256-bit and stored as SHA-256 hashes, and no JWT is used. No `eval`, `pickle`, `yaml.load`, `shell=True`, `os.system` or `exec.Command` appears in scope. No `InsecureSkipVerify` on any TLS configuration; the only use is the websocket origin option (S-014). The Go request bodies are capped (512 KB for mediacore, 4 KB for coreconfig, 128 KB for the proxy). Outbound clients have timeouts. Logout clears cookies with `HttpOnly` and `SameSite` in the Python proxy. No CORS configuration or debug mode was found.
|
||||||
|
- **Dependencies (not audited):** No known-vulnerable version is asserted in this report, since no audit tool or network access was used. Versions to confirm: Go `coder/websocket` v1.8.15, `go-chi/chi` v5.3.1, `pgx` v5.10.0, `goose` v3.27.3, `golang.org/x/crypto` v0.54.0 (`backend/go.mod`); Node `pg` 8.22.0 (locked in `package-lock.json`, declared `^8.17.2`); Python `bcrypt>=4.2` and `asyncpg>=0.30` with no upper bounds (`packages/python-backend/pyproject.toml`); Java Jackson 2.18.6, JUnit 5.10.2 (`packages/java-backend/pom.xml`). Run `govulncheck`, `npm audit`, `pip-audit` and an OWASP dependency check.
|
||||||
|
- **Not verified / coverage gaps:** AuthGuard's own server code (cookie attributes, rate limiting, role enforcement, session revocation on password change) is not in this repository, so every finding marked "needs verification" depends on it. Consumer wiring of `/ws`, `/media/*`, `/access` and the core-config route was not reviewed. `backend/auth` and `backend/config` were covered by a separate pass. CarrierNode-side path validation and the file types it stores are outside the repository. Java `AuthClient` cookie and redirect behaviour was assessed from code only. 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`.
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
+228
-79
@@ -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.
|
||||||
@@ -291,8 +306,10 @@ type Service struct {
|
|||||||
type ServiceOption func(*serviceOptions)
|
type ServiceOption func(*serviceOptions)
|
||||||
|
|
||||||
type serviceOptions struct {
|
type serviceOptions struct {
|
||||||
disabled bool
|
disabled bool
|
||||||
requireSecret bool
|
requireSecret bool
|
||||||
|
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
|
||||||
}
|
}
|
||||||
@@ -677,9 +704,11 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var input struct {
|
var input struct {
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
|
CurrentPassword string `json:"currentPassword"`
|
||||||
|
TOTPToken string `json:"totpToken"`
|
||||||
}
|
}
|
||||||
if err := decodeProxyJSON(r, &input); err != nil {
|
if err := decodeProxyJSON(r, &input); err != nil {
|
||||||
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
|
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
@@ -702,7 +731,29 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeProxyError(w, http.StatusBadRequest, err.Error())
|
writeProxyError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
managedInput.Password = input.Password
|
}
|
||||||
|
if input.Password != "" || (s.reauthenticateEmailChanges && email != current.Email) {
|
||||||
|
if input.CurrentPassword == "" {
|
||||||
|
writeProxyError(w, http.StatusBadRequest, "currentPassword is required to change email or password")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if current.MFAEnabled && strings.TrimSpace(input.TOTPToken) == "" {
|
||||||
|
writeProxyError(w, http.StatusBadRequest, "totpToken is required to change email or password")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reauthenticated, err := s.authGuard.Login(r.Context(), current.Username, input.CurrentPassword, input.TOTPToken)
|
||||||
|
if err != nil {
|
||||||
|
writeAuthGuardError(w, err, "current credentials could not be verified")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if token := temporarySessionToken(reauthenticated); token != "" {
|
||||||
|
defer func() {
|
||||||
|
_, _ = s.authGuard.Logout(context.WithoutCancel(r.Context()), token)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
if input.Password != "" {
|
||||||
|
managedInput.Password = input.Password
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
token := s.sessionToken(r)
|
token := s.sessionToken(r)
|
||||||
@@ -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 {
|
||||||
if err := s.store.SetLoginRequired(ctx, required); err != nil {
|
return errNoLoginRequiredStore
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
s.loginRequiredMu.Lock()
|
if err := s.store.SetLoginRequired(ctx, required); err != nil {
|
||||||
s.loginRequiredOverride = &required
|
return err
|
||||||
s.loginRequiredMu.Unlock()
|
}
|
||||||
|
// Drop the cached value rather than setting it, so the next read comes from the store and a
|
||||||
|
// store that discards writes cannot leave this process with its own login setting.
|
||||||
|
s.loginCacheMu.Lock()
|
||||||
|
s.loginCacheSet = false
|
||||||
|
s.loginCacheMu.Unlock()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -816,7 +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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
+181
-143
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
-12
@@ -16,11 +16,10 @@ import (
|
|||||||
|
|
||||||
// TOTP follows RFC 6238's default interoperable profile.
|
// TOTP follows RFC 6238's default interoperable profile.
|
||||||
const (
|
const (
|
||||||
TOTPPeriod = 30 * time.Second
|
TOTPPeriod = 30 * time.Second
|
||||||
TOTPDigits = 6
|
TOTPDigits = 6
|
||||||
TOTPSecretBytes = 20
|
TOTPSecretBytes = 20
|
||||||
TOTPWindow = 1
|
TOTPWindow = 1
|
||||||
TOTPSecretLength = 32
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// GenerateTOTPSecret returns a base32 secret suitable for authenticator apps.
|
// GenerateTOTPSecret returns a base32 secret suitable for authenticator apps.
|
||||||
@@ -52,19 +51,22 @@ func TOTPProvisioningURI(issuer, account, secret string) string {
|
|||||||
return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode()
|
return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode()
|
||||||
}
|
}
|
||||||
|
|
||||||
// VerifyTOTP checks a six-digit token with a one-period clock-skew window.
|
// VerifyTOTP checks a six-digit token with a one-period clock-skew window and
|
||||||
func VerifyTOTP(secret, token string, now time.Time) bool {
|
// returns the matching time step. A caller must atomically record that step
|
||||||
|
// before accepting the code so it cannot be used twice.
|
||||||
|
func VerifyTOTP(secret, token string, now time.Time) (int64, bool) {
|
||||||
secret = normalizeTOTPSecret(secret)
|
secret = normalizeTOTPSecret(secret)
|
||||||
token = normalizeTOTPToken(token)
|
token = normalizeTOTPToken(token)
|
||||||
if secret == "" || len(token) != TOTPDigits {
|
if secret == "" || len(token) != TOTPDigits {
|
||||||
return false
|
return -1, false
|
||||||
}
|
}
|
||||||
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
|
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
|
||||||
if err != nil || len(key) == 0 {
|
if err != nil || len(key) == 0 {
|
||||||
return false
|
return -1, false
|
||||||
}
|
}
|
||||||
period := now.Unix() / int64(TOTPPeriod/time.Second)
|
period := now.Unix() / int64(TOTPPeriod/time.Second)
|
||||||
for offset := int64(-TOTPWindow); offset <= TOTPWindow; offset++ {
|
// Prefer the current step if a six-digit collision occurs in the window.
|
||||||
|
for _, offset := range [...]int64{0, -1, 1} {
|
||||||
if period+offset < 0 {
|
if period+offset < 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -80,10 +82,10 @@ func VerifyTOTP(secret, token string, now time.Time) bool {
|
|||||||
uint32(digest[index+3])
|
uint32(digest[index+3])
|
||||||
candidate := fmt.Sprintf("%06d", value%1000000)
|
candidate := fmt.Sprintf("%06d", value%1000000)
|
||||||
if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 {
|
if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 {
|
||||||
return true
|
return period + offset, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return -1, false
|
||||||
}
|
}
|
||||||
|
|
||||||
func normalizeTOTPSecret(value string) string {
|
func normalizeTOTPSecret(value string) string {
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,7 +68,10 @@ type Client struct {
|
|||||||
// restrictions can be enforced. Empty means "don't identify" - the
|
// restrictions can be enforced. Empty means "don't identify" - the
|
||||||
// caller is treated as unrestricted; see AuthServer's project-scoping
|
// caller is treated as unrestricted; see AuthServer's project-scoping
|
||||||
// feature and WithProjectKey.
|
// feature and WithProjectKey.
|
||||||
projectKey string
|
projectKey string
|
||||||
|
validationMu sync.Mutex
|
||||||
|
validationCache map[[32]byte]validationCacheEntry
|
||||||
|
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
|
||||||
@@ -112,9 +115,11 @@ func WithProjectKey(key string) Option {
|
|||||||
// is always left as-is, overriding the inference.
|
// is always left as-is, overriding the inference.
|
||||||
func New(baseURL string, opts ...Option) *Client {
|
func New(baseURL string, opts ...Option) *Client {
|
||||||
c := &Client{
|
c := &Client{
|
||||||
baseURL: normalizeBaseURL(baseURL),
|
baseURL: normalizeBaseURL(baseURL),
|
||||||
httpClient: &http.Client{Timeout: 5 * time.Second},
|
httpClient: &http.Client{Timeout: 5 * time.Second},
|
||||||
cookieName: DefaultCookieName,
|
cookieName: DefaultCookieName,
|
||||||
|
validationCache: make(map[[32]byte]validationCacheEntry),
|
||||||
|
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
|
||||||
|
|||||||
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user