Files
CollabTable/shared/media-backend/internal/auth/auth_authguard_test.go
T

252 lines
9.2 KiB
Go
Raw Normal View History

2026-09-02 21:45:19 +02:00
package auth
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"mediacollection/internal/database"
)
// testPool returns a connection pool against a real (throwaway) Postgres
// instance, and a cleanup function. DATABASE_URL is expected to point at
// one - these tests are skipped (not failed) when it is unset, mirroring
// the workspace's existing convention for DB-backed test suites (see
// Forks/HordeWorker/tests/conftest.py's identical approach).
func testPool(t *testing.T) *pgxpool.Pool {
t.Helper()
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if dsn == "" {
t.Skip("DATABASE_URL not set; skipping AuthGuard-proxy auth tests that need a real Postgres")
}
ctx := context.Background()
pool, err := database.Open(ctx, dsn)
if err != nil {
t.Fatalf("open test database: %v", err)
}
if err := database.Migrate(ctx, pool); err != nil {
t.Fatalf("migrate test database: %v", err)
}
if _, err := pool.Exec(ctx, `DELETE FROM settings`); err != nil {
t.Fatalf("reset settings table: %v", err)
}
if _, err := pool.Exec(ctx, `DELETE FROM users`); err != nil {
t.Fatalf("reset users table: %v", err)
}
t.Cleanup(pool.Close)
return pool
}
// fakeAuthGuard is a minimal stateful in-memory AuthGuard double: enough of
// setup-status/register/login/me/logout to exercise Service's proxy
// behavior end-to-end, mirroring the httptest-server pattern already used
// by shared/backend/authclient's own tests.
type fakeAuthGuard struct {
server *httptest.Server
hasAccount bool
username string
email string
role string
password string
sessions map[string]bool
}
func newFakeAuthGuard() *fakeAuthGuard {
f := &fakeAuthGuard{sessions: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("GET /api/setup-status", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"setup_required": !f.hasAccount})
})
mux.HandleFunc("POST /api/register", func(w http.ResponseWriter, r *http.Request) {
if f.hasAccount {
writeJSON(w, http.StatusConflict, map[string]string{"error": "setup already completed"})
return
}
var body struct{ Username, Email, Password string }
_ = json.NewDecoder(r.Body).Decode(&body)
f.hasAccount = true
f.username, f.email, f.role, f.password = body.Username, body.Email, "superadmin", body.Password
token := "tok-" + body.Username
f.sessions[token] = true
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: token})
writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{
"id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false,
}})
})
mux.HandleFunc("POST /api/login", func(w http.ResponseWriter, r *http.Request) {
var body struct {
UsernameOrEmail string `json:"username_or_email"`
Password string `json:"password"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if !f.hasAccount || body.UsernameOrEmail != f.username && body.UsernameOrEmail != f.email || body.Password != f.password {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Invalid username or password."})
return
}
token := "tok-" + f.username
f.sessions[token] = true
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: token})
writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{
"id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false,
}})
})
mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) {
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if !f.sessions[token] {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid session"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{
"id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false,
}})
})
mux.HandleFunc("POST /api/logout", func(w http.ResponseWriter, r *http.Request) {
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
delete(f.sessions, token)
http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "", MaxAge: -1})
writeJSON(w, http.StatusOK, map[string]any{})
})
f.server = httptest.NewServer(mux)
return f
}
func (f *fakeAuthGuard) close() { f.server.Close() }
func newRequest(method, target string, body string) *http.Request {
var r *http.Request
if body != "" {
r = httptest.NewRequest(method, target, strings.NewReader(body))
} else {
r = httptest.NewRequest(method, target, nil)
}
return r
}
func TestCurrentUserDisabledModeReturnsLocalSuperadmin(t *testing.T) {
svc := New(nil, "mediacollection_session", false, "")
user, err := svc.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
if err != nil {
t.Fatalf("CurrentUser() error = %v", err)
}
if user == nil || user.Role != "superadmin" || !user.CanManageUsers {
t.Fatalf("CurrentUser() = %+v, want local superadmin placeholder", user)
}
}
func TestSignupLoginLogoutProxyToAuthGuard(t *testing.T) {
pool := testPool(t)
guard := newFakeAuthGuard()
defer guard.close()
svc := New(pool, "mediacollection_session", false, guard.server.URL)
ctx := context.Background()
// Signup
req := newRequest(http.MethodPost, "/auth/signup", `{"email":"a@example.com","username":"admin","password":"correct horse battery staple"}`)
rec := httptest.NewRecorder()
svc.Signup(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("Signup() status = %d, body = %s", rec.Code, rec.Body.String())
}
cookie := firstSetCookie(t, rec)
if cookie == "" {
t.Fatal("Signup() did not forward AuthGuard's Set-Cookie")
}
claimed, err := svc.isSetupClaimed(ctx)
if err != nil || !claimed {
t.Fatalf("isSetupClaimed() = %v, %v, want true, nil", claimed, err)
}
// A second signup attempt must be rejected (setup already completed).
req2 := newRequest(http.MethodPost, "/auth/signup", `{"email":"b@example.com","username":"other","password":"correct horse battery staple"}`)
rec2 := httptest.NewRecorder()
svc.Signup(rec2, req2)
if rec2.Code != http.StatusConflict {
t.Fatalf("second Signup() status = %d, want 409", rec2.Code)
}
// CurrentUser resolves via the forwarded cookie.
authedReq := httptest.NewRequest(http.MethodGet, "/auth/me", nil)
authedReq.Header.Set("Cookie", "auth_session="+cookie)
user, err := svc.CurrentUser(authedReq)
if err != nil {
t.Fatalf("CurrentUser() error = %v", err)
}
if user == nil || user.Username != "admin" || user.Role != "superadmin" {
t.Fatalf("CurrentUser() = %+v, want the AuthGuard-registered admin", user)
}
// Login with wrong password is rejected.
badLogin := newRequest(http.MethodPost, "/auth/login", `{"identifier":"admin","password":"wrong"}`)
badRec := httptest.NewRecorder()
svc.Login(badRec, badLogin)
if badRec.Code != http.StatusUnauthorized {
t.Fatalf("Login() with wrong password status = %d, want 401", badRec.Code)
}
// Logout clears the session.
logoutReq := httptest.NewRequest(http.MethodPost, "/auth/logout", nil)
logoutReq.Header.Set("Cookie", "auth_session="+cookie)
logoutRec := httptest.NewRecorder()
svc.Logout(logoutRec, logoutReq)
if logoutRec.Code != http.StatusOK {
t.Fatalf("Logout() status = %d", logoutRec.Code)
}
}
func TestSecondProjectSetupIsRejectedWhenAuthGuardAlreadyHasAnAccount(t *testing.T) {
pool := testPool(t)
guard := newFakeAuthGuard()
defer guard.close()
guard.hasAccount = true // simulate a different project (or AuthGuard's own web UI) having already created one
guard.username, guard.email, guard.role, guard.password = "existing", "existing@example.com", "superadmin", "hunter2!!"
svc := New(pool, "mediacollection_session", false, guard.server.URL)
req := newRequest(http.MethodPost, "/auth/signup", `{"email":"new@example.com","username":"new","password":"correct horse battery staple"}`)
rec := httptest.NewRecorder()
svc.Signup(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("Signup() status = %d, body = %s, want 409 (AuthGuard already has an account)", rec.Code, rec.Body.String())
}
// The local claim must have been released again so a later legitimate flow isn't locked out.
claimed, err := svc.isSetupClaimed(context.Background())
if err != nil || claimed {
t.Fatalf("isSetupClaimed() = %v, %v, want false after a rejected signup", claimed, err)
}
}
func TestLoginRequiredToggleIsIndependentOfAuthGuard(t *testing.T) {
pool := testPool(t)
svc := New(pool, "mediacollection_session", false, "")
required, err := svc.LoginRequired(context.Background())
if err != nil || !required {
t.Fatalf("LoginRequired() default = %v, %v, want true, nil", required, err)
}
rec := httptest.NewRecorder()
svc.UpdateAccessSettings(rec, newRequest(http.MethodPut, "/api/auth/access", `{"loginRequired":false}`))
if rec.Code != http.StatusOK {
t.Fatalf("UpdateAccessSettings() status = %d", rec.Code)
}
required, err = svc.LoginRequired(context.Background())
if err != nil || required {
t.Fatalf("LoginRequired() after disabling = %v, %v, want false, nil", required, err)
}
}
func firstSetCookie(t *testing.T, rec *httptest.ResponseRecorder) string {
t.Helper()
for _, raw := range rec.Result().Cookies() {
if raw.Name == "auth_session" && raw.Value != "" {
return raw.Value
}
}
return ""
}