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