Sync shared snapshot from 9589d07
This commit is contained in:
1 parent
49e3c7d561
commit
d3fff0a495
7 files changed
+1055
-560
No files matched your search
@@ -18,5 +18,6 @@ ANALYZER_MODELS_URL=http://127.0.0.1:8801
|
||||
CORS_ORIGIN=http://localhost:5173
|
||||
SESSION_COOKIE=mediacollection_session
|
||||
COOKIE_SECURE=false
|
||||
AUTHGUARD_URL=
|
||||
INTERNAL_SERVICE_SECRET=
|
||||
MAX_UPLOAD_BYTES=50gb
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,252 @@
|
||||
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 ""
|
||||
}
|
||||
@@ -39,6 +39,11 @@ type Config struct {
|
||||
PublicURL string
|
||||
SessionCookie string
|
||||
SecureCookies bool
|
||||
// AuthGuardURL is AuthGuard's base URL (see Web/Central/AuthGuard);
|
||||
// empty means auth-disabled mode (see internal/auth's package doc
|
||||
// comment). Read raw via os.Getenv rather than envOr since "" is a
|
||||
// meaningful, distinct value here (not a fallback-worthy blank).
|
||||
AuthGuardURL string
|
||||
InternalServiceSecret string
|
||||
FFmpeg string
|
||||
FFprobe string
|
||||
@@ -94,6 +99,7 @@ func Load() (*Config, error) {
|
||||
PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"),
|
||||
SessionCookie: envOr("SESSION_COOKIE", "mediacollection_session"),
|
||||
SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""),
|
||||
AuthGuardURL: strings.TrimSpace(os.Getenv("AUTHGUARD_URL")),
|
||||
InternalServiceSecret: strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")),
|
||||
FFmpeg: envOr("FFMPEG_PATH", "ffmpeg"),
|
||||
FFprobe: envOr("FFPROBE_PATH", "ffprobe"),
|
||||
|
||||
@@ -138,7 +138,7 @@ func New(cfg *config.Config, db *pgxpool.Pool) *Server {
|
||||
return &Server{
|
||||
cfg: cfg,
|
||||
db: db,
|
||||
auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies),
|
||||
auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies, cfg.AuthGuardURL),
|
||||
startedAt: time.Now(),
|
||||
media: make(map[string]MediaRecord),
|
||||
jobs: make(map[string]*WorkflowJob),
|
||||
@@ -167,8 +167,6 @@ func (s *Server) Handler() http.Handler {
|
||||
r.Post("/signup", s.auth.Signup)
|
||||
r.Post("/login", s.auth.Login)
|
||||
r.Post("/logout", s.auth.Logout)
|
||||
r.Post("/reset/request", s.auth.RequestAdminReset)
|
||||
r.Post("/reset/confirm", s.auth.ConfirmAdminReset)
|
||||
r.Get("/me", s.auth.Me)
|
||||
r.With(s.auth.Require).Put("/me", s.auth.UpdateMe)
|
||||
r.Get("/status", s.auth.Status)
|
||||
|
||||
@@ -139,13 +139,6 @@
|
||||
auth = { ...auth, user: data.user, setupRequired: false, loading: false, error: null }
|
||||
}
|
||||
|
||||
const requestReset = () => post('/auth/reset/request')
|
||||
|
||||
async function confirmReset(code: string) {
|
||||
await post('/auth/reset/confirm', { code })
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await post('/auth/logout')
|
||||
@@ -199,8 +192,6 @@
|
||||
error={auth.error || ''}
|
||||
onLogin={login}
|
||||
onSetup={setup}
|
||||
onRequestReset={requestReset}
|
||||
onConfirmReset={confirmReset}
|
||||
/>
|
||||
{:else}
|
||||
<div class="sc-root sc-app-shell min-h-screen bg-bg text-fg mediacollection-shell">
|
||||
|
||||
@@ -1,43 +1,22 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
AuthPage as SharedAuthPage,
|
||||
type AuthLoginInput,
|
||||
type AuthResetConfirm,
|
||||
type AuthResetRequest,
|
||||
type AuthSetupInput,
|
||||
} from '@gabriel20xx/web-ui'
|
||||
import { AuthPage as SharedAuthPage, type AuthLoginInput, type AuthSetupInput } from '@gabriel20xx/web-ui'
|
||||
import type { AppConfig } from '$lib/types'
|
||||
|
||||
let {
|
||||
app,
|
||||
error = '',
|
||||
loading = false,
|
||||
onConfirmReset,
|
||||
onLogin,
|
||||
onRequestReset,
|
||||
onSetup,
|
||||
setupRequired,
|
||||
}: {
|
||||
app: AppConfig
|
||||
error?: string
|
||||
loading?: boolean
|
||||
onConfirmReset: AuthResetConfirm
|
||||
onLogin: (input: AuthLoginInput) => void | Promise<void>
|
||||
onRequestReset: AuthResetRequest
|
||||
onSetup: (input: AuthSetupInput) => void | Promise<void>
|
||||
setupRequired: boolean
|
||||
} = $props()
|
||||
</script>
|
||||
|
||||
<SharedAuthPage
|
||||
brand={app.name}
|
||||
tagline={app.eyebrow}
|
||||
{setupRequired}
|
||||
{loading}
|
||||
{error}
|
||||
showTotp
|
||||
{onLogin}
|
||||
{onSetup}
|
||||
{onRequestReset}
|
||||
{onConfirmReset}
|
||||
/>
|
||||
<SharedAuthPage brand={app.name} tagline={app.eyebrow} {setupRequired} {loading} {error} showTotp {onLogin} {onSetup} />
|
||||
Reference in new issue
Block a user