package auth import ( "context" "net/url" "os" "strings" "testing" "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres" ) // platformUsersSchema holds the test's own `users` table, so it never meets the fuller table that // mediacore's migration creates in the same database. const platformUsersSchema = "platform_users_test" // withSearchPath returns databaseURL with its search_path set to schema. func withSearchPath(t *testing.T, databaseURL, schema string) string { t.Helper() parsed, err := url.Parse(databaseURL) if err != nil { t.Fatalf("parse database URL: %v", err) } query := parsed.Query() query.Set("search_path", schema) parsed.RawQuery = query.Encode() return parsed.String() } // TestPlatformUserSQL runs the moderatable platform-user methods (CreateUser, ListUsers, // UpdateUser, SetPassword, DeleteUser) against a real database. The `users` table normally comes // from mediacore's migration, which this package cannot import, so the test creates the columns it // needs in a schema of its own. It is skipped unless SHARED_TEST_DATABASE_URL points at a scratch // database, for example: // // SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./auth/ -run TestPlatformUserSQL func TestPlatformUserSQL(t *testing.T) { databaseURL := os.Getenv("SHARED_TEST_DATABASE_URL") if databaseURL == "" { t.Skip("SHARED_TEST_DATABASE_URL not set; skipping Postgres platform-user test") } ctx := context.Background() admin, err := postgres.Open(ctx, postgres.DefaultConfig(databaseURL)) if err != nil { t.Fatalf("open pool: %v", err) } t.Cleanup(admin.Close) if _, err := admin.Exec(ctx, `DROP SCHEMA IF EXISTS `+platformUsersSchema+` CASCADE; CREATE SCHEMA `+platformUsersSchema); err != nil { t.Fatalf("create schema: %v", err) } t.Cleanup(func() { _, _ = admin.Exec(context.Background(), `DROP SCHEMA IF EXISTS `+platformUsersSchema+` CASCADE`) }) pool, err := postgres.Open(ctx, postgres.DefaultConfig(withSearchPath(t, databaseURL, platformUsersSchema))) if err != nil { t.Fatalf("open pool: %v", err) } t.Cleanup(pool.Close) if _, err := pool.Exec(ctx, ` CREATE TABLE users ( id BIGSERIAL PRIMARY KEY, email TEXT NOT NULL UNIQUE, username TEXT, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'user', disabled BOOLEAN NOT NULL DEFAULT FALSE, last_login_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() )`); err != nil { t.Fatalf("create users table: %v", err) } service := New(pool, "session", false, "", "testproject") if _, err := service.CreateUser(ctx, "not-an-email", "x", "password123", "user"); err == nil { t.Fatal("CreateUser accepted an invalid email") } if _, err := service.CreateUser(ctx, "platform-test-bad@example.com", "x@y", "password123", "user"); err == nil { t.Fatal("CreateUser accepted a username containing @") } if _, err := service.CreateUser(ctx, "platform-test-bad@example.com", "x", strings.Repeat("p", 73), "user"); err == nil { t.Fatal("CreateUser accepted a password longer than 72 bytes") } alice, err := service.CreateUser(ctx, " Platform-Test-Alice@Example.com ", "alice-platform", "password123", "MODERATOR") if err != nil { t.Fatalf("CreateUser(alice) error = %v", err) } if alice.Email != "platform-test-alice@example.com" || alice.Username != "alice-platform" || alice.Role != "moderator" { t.Fatalf("created user = %+v, want a lower-cased email and the normalized moderator role", alice) } bob, err := service.CreateUser(ctx, "platform-test-bob@example.com", "bob-platform", "password123", "superuser") if err != nil { t.Fatalf("CreateUser(bob) error = %v", err) } if bob.Role != "user" { t.Fatalf("an unknown role was stored as %q, want it reduced to user", bob.Role) } if _, err := service.CreateUser(ctx, "platform-test-alice@example.com", "other", "password123", "user"); err == nil { t.Fatal("CreateUser accepted a duplicate email") } var storedHash string if err := pool.QueryRow(ctx, `SELECT password_hash FROM users WHERE id=$1`, alice.ID).Scan(&storedHash); err != nil { t.Fatal(err) } if !strings.HasPrefix(storedHash, bcryptScheme) || !VerifyPassword(storedHash, "password123") { t.Fatalf("stored hash %q is not a verifiable versioned hash", storedHash) } listed, total, err := service.ListUsers(ctx, "platform-test-", 1, 0) if err != nil || total != 2 || len(listed) != 1 { t.Fatalf("ListUsers page 1 = %d rows, total %d, %v; want 1 row of 2", len(listed), total, err) } if listed[0]["id"] != bob.ID { t.Fatalf("first row = %v, want the newest user (ordered by id descending)", listed[0]["id"]) } if page, _, _ := service.ListUsers(ctx, "platform-test-", 1, 1); len(page) != 1 || page[0]["id"] != alice.ID { t.Fatalf("second page = %v, want alice", page) } if found, total, _ := service.ListUsers(ctx, "ALICE-platform", 50, 0); total != 1 || len(found) != 1 || found[0]["email"] != "platform-test-alice@example.com" { t.Fatalf("search by username = %v (total %d), want alice, matched ignoring case", found, total) } if found, total, _ := service.ListUsers(ctx, "no-such-person-anywhere", 50, 0); total != 0 || len(found) != 0 { t.Fatalf("search with no match = %v (total %d)", found, total) } disabled := true if err := service.UpdateUser(ctx, alice.ID, "", "alice-renamed", "", &disabled); err != nil { t.Fatalf("UpdateUser error = %v", err) } account, err := service.managedAccount(ctx, alice.ID) if err != nil || account == nil { t.Fatalf("managedAccount = %v, %v", account, err) } if account.Username != "alice-renamed" || account.Email != "platform-test-alice@example.com" || account.Role != "moderator" || !account.Disabled { t.Fatalf("after a partial update = %+v, want only the username and disabled flag changed", account) } if err := service.UpdateUser(ctx, alice.ID, "", "", " ADMIN ", nil); err != nil { t.Fatal(err) } if account, _ := service.managedAccount(ctx, alice.ID); account.Role != "admin" || !account.Disabled { t.Fatalf("after a role-only update = %+v, want the admin role and the disabled flag kept", account) } if err := service.UpdateUser(ctx, alice.ID, "", "", "wizard", nil); err != nil { t.Fatal(err) } if account, _ := service.managedAccount(ctx, alice.ID); account.Role != "user" { t.Fatalf("an unknown role was stored as %q, want it reduced to user", account.Role) } if missing, err := service.managedAccount(ctx, -1); err != nil || missing != nil { t.Fatalf("managedAccount of a missing id = %v, %v; want nil, nil", missing, err) } if err := service.SetPassword(ctx, bob.ID, "short"); err == nil { t.Fatal("SetPassword accepted a short password") } if err := service.SetPassword(ctx, bob.ID, "a-new-password-1"); err != nil { t.Fatalf("SetPassword error = %v", err) } if err := pool.QueryRow(ctx, `SELECT password_hash FROM users WHERE id=$1`, bob.ID).Scan(&storedHash); err != nil { t.Fatal(err) } if !VerifyPassword(storedHash, "a-new-password-1") || VerifyPassword(storedHash, "password123") { t.Fatal("SetPassword did not replace the stored hash") } if err := service.DeleteUser(ctx, alice.ID); err != nil { t.Fatal(err) } if gone, _ := service.managedAccount(ctx, alice.ID); gone != nil { t.Fatal("DeleteUser left the account in place") } }