feat: add Android release signing and user remapping
Lint / Lint (push) Successful in 1m2s
Security / Secrets (gitleaks) (push) Successful in 1m11s
Tests / Dashboard checks (push) Successful in 1m17s
Security / Dependencies (Trivy) (push) Successful in 1m20s
Security / Code (Semgrep) (push) Successful in 3m15s
Tests / Go backend (push) Successful in 3m29s
Docker / Docker Build & Push (push) Successful in 8m42s

- Add release signing configuration and static debug-key workflow
- Add a CLI to remap legacy users to AuthGuard accounts
This commit is contained in:
Gabriel20xx committed 2026-11-01 19:09:06 +01:00
1 parent 817236f349
commit 7150ebd13e
8 files changed
+1553 -2

No files matched your search

@@ -0,0 +1,223 @@
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
- name: Install Android SDK packages
shell: bash
run: |
sdkmanager "platform-tools" "platforms;android-36" "build-tools;36.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/36.0.0/apksigner"
CERTS=$("$APKSIGNER" verify --print-certs "$APK")
ACTUAL=$(printf '%s\n' "$CERTS" | sed -n 's/^Signer #1 certificate SHA-256 digest: //p')
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
+208
View File
@@ -0,0 +1,208 @@
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
- name: Install Android SDK packages
shell: bash
run: |
sdkmanager "platform-tools" "platforms;android-36" "build-tools;36.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/36.0.0/apksigner"
CERTS=$("$APKSIGNER" verify --print-certs "$APK")
ACTUAL=$(printf '%s\n' "$CERTS" | sed -n 's/^Signer #1 certificate SHA-256 digest: //p')
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"
+20 -2
View File
@@ -16,8 +16,8 @@ android {
applicationId = "com.collabtable.app"
minSdk = 26
targetSdk = 34
versionCode 1
versionName "1.0"
versionCode = 1
versionName = "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
@@ -25,10 +25,28 @@ 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 {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
if (releaseKeystoreFile != null) {
signingConfig signingConfigs.release
}
}
}
compileOptions {
Vendored Executable
+252
View File
@@ -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" "$@"
+20
View File
@@ -60,6 +60,26 @@ go -C backend build -o collabtable-server .
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
All Android synchronization routes are prefixed with `/api/` and require:
+528
View File
@@ -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)
}
}
+299
View File
@@ -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)
}
}
+3
View File
@@ -50,6 +50,9 @@ const (
)
func main() {
if len(os.Args) > 1 && os.Args[1] == "remap-users" {
os.Exit(runRemapUsers(os.Args[2:], os.Stdout))
}
port := envOrDefault("PORT", "8080")
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if connectionString == "" {