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
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:
1 parent
817236f349
commit
7150ebd13e
8 files changed
+1553
-2
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 == "" {
|
||||
|
||||
Reference in new issue
Block a user