Files
CollabTable/backend/remap_users_test.go
T
Gabriel20xx 7150ebd13e
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
feat: add Android release signing and user remapping
- Add release signing configuration and static debug-key workflow
- Add a CLI to remap legacy users to AuthGuard accounts
2026-11-01 19:09:06 +01:00

300 lines
9.9 KiB
Go

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)
}
}