2026-09-01 21:51:15 +02:00
|
|
|
package auth
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2026-10-19 21:46:52 +00:00
|
|
|
"errors"
|
2026-09-01 21:51:15 +02:00
|
|
|
"os"
|
|
|
|
|
"testing"
|
|
|
|
|
"time"
|
|
|
|
|
|
2026-10-19 21:46:52 +00:00
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
|
|
2026-09-01 21:51:15 +02:00
|
|
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// TestStoreIntegration exercises Store against a real PostgreSQL database,
|
|
|
|
|
// covering exactly what the fake stores unit tests (in each consumer's own
|
|
|
|
|
// httpapi package) use instead cannot: a mismatch between a query's column
|
|
|
|
|
// list and Scan's destination count only surfaces against a real driver
|
|
|
|
|
// round-trip. Skipped unless DATABASE_URL points at a scratch database -
|
|
|
|
|
// never run by default in CI; point it at a local/throwaway database to run
|
|
|
|
|
// it, e.g.:
|
|
|
|
|
//
|
|
|
|
|
// DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./auth/... -run TestStoreIntegration
|
|
|
|
|
func TestStoreIntegration(t *testing.T) {
|
|
|
|
|
url := os.Getenv("DATABASE_URL")
|
|
|
|
|
if url == "" {
|
|
|
|
|
t.Skip("DATABASE_URL not set; skipping Postgres integration test")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ctx := context.Background()
|
|
|
|
|
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("open pool: %v", err)
|
|
|
|
|
}
|
|
|
|
|
// Registered before the DeleteAllUsers cleanup below so it runs after
|
|
|
|
|
// that one (t.Cleanup runs in LIFO order).
|
|
|
|
|
t.Cleanup(pool.Close)
|
|
|
|
|
|
|
|
|
|
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false, APITokens: true}); err != nil {
|
|
|
|
|
t.Fatalf("EnsureSchema() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
store := NewStore(pool)
|
|
|
|
|
if err := store.DeleteAllUsers(ctx); err != nil {
|
|
|
|
|
t.Fatalf("DeleteAllUsers() (pre-test cleanup) error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
t.Cleanup(func() {
|
|
|
|
|
if err := store.DeleteAllUsers(context.Background()); err != nil {
|
|
|
|
|
t.Logf("cleanup: DeleteAllUsers() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
hash, err := HashPassword("correct horse battery staple")
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("HashPassword() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// The very first account is promoted to superadmin; this also exercises
|
|
|
|
|
// CreateUser's own Scan (7 RETURNING columns), separately from find's.
|
|
|
|
|
created, err := store.CreateUser(ctx, "root", "root@example.com", hash)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("CreateUser() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if created.Role != RoleSuperAdmin {
|
|
|
|
|
t.Fatalf("first CreateUser() role = %q, want %q", created.Role, RoleSuperAdmin)
|
|
|
|
|
}
|
2026-09-04 15:07:02 +02:00
|
|
|
if created.LastLoginAt != nil {
|
|
|
|
|
t.Fatalf("CreateUser() LastLoginAt = %v, want nil before any login", created.LastLoginAt)
|
|
|
|
|
}
|
2026-09-01 21:51:15 +02:00
|
|
|
|
|
|
|
|
byIdentifier, err := store.FindByIdentifier(ctx, "root")
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("FindByIdentifier() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if byIdentifier == nil || byIdentifier.ID != created.ID || byIdentifier.Role != RoleSuperAdmin {
|
|
|
|
|
t.Fatalf("FindByIdentifier() = %+v, want a superadmin match for %+v", byIdentifier, created)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
byID, err := store.FindByID(ctx, created.ID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("FindByID() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if byID == nil || byID.Username != "root" || byID.Role != RoleSuperAdmin {
|
|
|
|
|
t.Fatalf("FindByID() = %+v, want username %q and superadmin role", byID, "root")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_, hashedToken, err := NewSessionToken()
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("NewSessionToken() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if err := store.CreateSession(ctx, created.ID, hashedToken, time.Now().Add(time.Hour)); err != nil {
|
|
|
|
|
t.Fatalf("CreateSession() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bySession, err := store.FindSessionUser(ctx, hashedToken)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("FindSessionUser() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if bySession == nil || bySession.ID != created.ID {
|
|
|
|
|
t.Fatalf("FindSessionUser() = %+v, want a match for %+v", bySession, created)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
users, err := store.ListUsers(ctx)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("ListUsers() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if len(users) != 1 || users[0].ID != created.ID {
|
|
|
|
|
t.Fatalf("ListUsers() = %+v, want exactly the created user", users)
|
|
|
|
|
}
|
2026-09-04 15:07:02 +02:00
|
|
|
if users[0].LastLoginAt != nil {
|
|
|
|
|
t.Fatalf("ListUsers()[0].LastLoginAt = %v, want nil before any login", users[0].LastLoginAt)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := store.UpdateLastLogin(ctx, created.ID); err != nil {
|
|
|
|
|
t.Fatalf("UpdateLastLogin() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
afterLogin, err := store.FindByID(ctx, created.ID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("FindByID() after UpdateLastLogin error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if afterLogin == nil || afterLogin.LastLoginAt == nil {
|
|
|
|
|
t.Fatalf("FindByID() after UpdateLastLogin = %+v, want LastLoginAt set", afterLogin)
|
|
|
|
|
}
|
2026-09-01 21:51:15 +02:00
|
|
|
}
|
2026-10-19 21:46:52 +00:00
|
|
|
|
|
|
|
|
// openScratchStore opens DATABASE_URL (a scratch database, see TestStoreIntegration), applies the
|
|
|
|
|
// schema and removes every account before and after the test.
|
|
|
|
|
func openScratchStore(t *testing.T) (context.Context, *pgxpool.Pool, *Store) {
|
|
|
|
|
t.Helper()
|
|
|
|
|
url := os.Getenv("DATABASE_URL")
|
|
|
|
|
if url == "" {
|
|
|
|
|
t.Skip("DATABASE_URL not set; skipping Postgres integration test")
|
|
|
|
|
}
|
|
|
|
|
ctx := context.Background()
|
|
|
|
|
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("open pool: %v", err)
|
|
|
|
|
}
|
|
|
|
|
t.Cleanup(pool.Close)
|
|
|
|
|
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
|
|
|
|
|
t.Fatalf("EnsureSchema() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
store := NewStore(pool)
|
|
|
|
|
if err := store.DeleteAllUsers(ctx); err != nil {
|
|
|
|
|
t.Fatalf("DeleteAllUsers() (pre-test cleanup) error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
t.Cleanup(func() {
|
|
|
|
|
if err := store.DeleteAllUsers(context.Background()); err != nil {
|
|
|
|
|
t.Logf("cleanup: DeleteAllUsers() error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
return ctx, pool, store
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestStoreRefusesUsernamesThatDifferOnlyByCase covers the unique index on lower(username).
|
|
|
|
|
func TestStoreRefusesUsernamesThatDifferOnlyByCase(t *testing.T) {
|
|
|
|
|
ctx, _, store := openScratchStore(t)
|
|
|
|
|
hash, err := HashPassword("correct horse battery staple")
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
if _, err := store.CreateUser(ctx, "Admin", "", hash); err != nil {
|
|
|
|
|
t.Fatalf("CreateUser(Admin) error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if _, err := store.CreateUser(ctx, "admin", "", hash); !errors.Is(err, ErrUserExists) {
|
|
|
|
|
t.Fatalf("CreateUser(admin) error = %v, want ErrUserExists", err)
|
|
|
|
|
}
|
|
|
|
|
if _, err := store.CreateManagedUser(ctx, "ADMIN", "", hash, RoleUser); !errors.Is(err, ErrUserExists) {
|
|
|
|
|
t.Fatalf("CreateManagedUser(ADMIN) error = %v, want ErrUserExists", err)
|
|
|
|
|
}
|
|
|
|
|
bob, err := store.CreateUser(ctx, "bob", "", hash)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("CreateUser(bob) error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if err := store.UpdateCredentials(ctx, bob.ID, "admin", "", hash); !errors.Is(err, ErrUserExists) {
|
|
|
|
|
t.Fatalf("UpdateCredentials(admin) error = %v, want ErrUserExists", err)
|
|
|
|
|
}
|
|
|
|
|
role := RoleUser
|
|
|
|
|
if err := store.UpdateUser(ctx, bob.ID, "Admin", "", hash, &role); !errors.Is(err, ErrUserExists) {
|
|
|
|
|
t.Fatalf("UpdateUser(Admin) error = %v, want ErrUserExists", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestEnsureSchemaStartsWithExistingCaseVariantUsernames checks that a database already holding
|
|
|
|
|
// "Admin" and "admin" still starts, gets no index, and gets one after the pair is resolved.
|
|
|
|
|
func TestEnsureSchemaStartsWithExistingCaseVariantUsernames(t *testing.T) {
|
|
|
|
|
ctx, pool, store := openScratchStore(t)
|
|
|
|
|
if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS auth_users_username_lower_idx`); err != nil {
|
|
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
if _, err := pool.Exec(ctx, `INSERT INTO auth_users (username, password_hash) VALUES ('Admin', 'x'), ('admin', 'x')`); err != nil {
|
|
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
indexExists := func() bool {
|
|
|
|
|
var exists bool
|
|
|
|
|
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'auth_users_username_lower_idx')`).Scan(&exists); err != nil {
|
|
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
return exists
|
|
|
|
|
}
|
|
|
|
|
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
|
|
|
|
|
t.Fatalf("EnsureSchema() with clashing usernames error = %v, want it to start", err)
|
|
|
|
|
}
|
|
|
|
|
if indexExists() {
|
|
|
|
|
t.Fatal("the case-insensitive index was created over clashing usernames")
|
|
|
|
|
}
|
|
|
|
|
if err := store.DeleteAllUsers(ctx); err != nil {
|
|
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false}); err != nil {
|
|
|
|
|
t.Fatalf("EnsureSchema() after cleanup error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if !indexExists() {
|
|
|
|
|
t.Fatal("the case-insensitive index was not created once the clash was gone")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestStoreTOTPAndIdentifierPrimitives covers SetTOTPSecret refusing to replace an enabled second
|
|
|
|
|
// factor and FindByIdentifier trying usernames before emails.
|
|
|
|
|
func TestStoreTOTPAndIdentifierPrimitives(t *testing.T) {
|
|
|
|
|
ctx, pool, store := openScratchStore(t)
|
|
|
|
|
hash, err := HashPassword("correct horse battery staple")
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
owner, err := store.CreateUser(ctx, "owner", "owner@example.com", hash)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
if err := store.SetTOTPSecret(ctx, owner.ID, "JBSWY3DPEHPK3PXP"); err != nil {
|
|
|
|
|
t.Fatalf("SetTOTPSecret() while disabled error = %v", err)
|
|
|
|
|
}
|
|
|
|
|
if err := store.EnableTOTP(ctx, owner.ID); err != nil {
|
|
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
if err := store.SetTOTPSecret(ctx, owner.ID, "OTHERSECRET"); !errors.Is(err, ErrTOTPAlreadyEnabled) {
|
|
|
|
|
t.Fatalf("SetTOTPSecret() while enabled error = %v, want ErrTOTPAlreadyEnabled", err)
|
|
|
|
|
}
|
|
|
|
|
if state, err := store.GetTOTPState(ctx, owner.ID); err != nil || !state.Enabled || state.Secret != "JBSWY3DPEHPK3PXP" {
|
|
|
|
|
t.Fatalf("TOTP state after a refused replace = %+v, %v; want the original secret still enabled", state, err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// A username equal to another account's email (a row written outside the store's validation)
|
|
|
|
|
// resolves to the username's own account, not to the email's owner.
|
|
|
|
|
if _, err := pool.Exec(ctx, `INSERT INTO auth_users (username, email, password_hash) VALUES ('owner@example.com', 'second@example.com', 'x')`); err != nil {
|
|
|
|
|
t.Fatal(err)
|
|
|
|
|
}
|
|
|
|
|
found, err := store.FindByIdentifier(ctx, "owner@example.com")
|
|
|
|
|
if err != nil || found == nil || found.Username != "owner@example.com" {
|
|
|
|
|
t.Fatalf("FindByIdentifier() = %+v, %v; want the account whose username matches", found, err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := store.UpdateCredentials(ctx, owner.ID, "owner", "owner@example.com", ""); !errors.Is(err, ErrEmptyPasswordHash) {
|
|
|
|
|
t.Fatalf("UpdateCredentials() with an empty hash error = %v, want ErrEmptyPasswordHash", err)
|
|
|
|
|
}
|
|
|
|
|
}
|