package mediacore import ( "context" "fmt" "net/http" "net/http/httptest" "strings" "testing" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgxpool" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" ) func TestSettingValueReturnsDatabaseErrors(t *testing.T) { db, err := pgxpool.New(context.Background(), "postgres://nobody@127.0.0.1:1/none?sslmode=disable&connect_timeout=1") if err != nil { t.Fatalf("pgxpool.New: %v", err) } defer db.Close() value, err := SettingValue(context.Background(), db, "example", "fallback") if err == nil || value != "" { t.Fatalf("SettingValue() = %q, %v; want empty value and database error", value, err) } if got := SettingValueOrFallback(context.Background(), db, "example", "fallback"); got != "fallback" { t.Fatalf("SettingValueOrFallback() = %q, want fallback on error", got) } } // loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be // exercised without a database. type loginRequiredStore struct{} func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil } func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil } func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil } func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil } func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil } // loginOffStore is loginRequiredStore with login switched off for the whole application. type loginOffStore struct{ loginRequiredStore } func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil } // TestMediaStreamAndThumbnailRequireLogin checks that anonymous requests to the media stream and // thumbnail routes are refused when login is required, before any database lookup or CarrierNode // call. The Core in this test has no database and no CarrierNode client, so reaching either would // panic. func TestMediaStreamAndThumbnailRequireLogin(t *testing.T) { auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject") router := chi.NewRouter() New(Config{Auth: auth}).Mount(router) for _, request := range []struct{ method, target string }{ {http.MethodGet, "/media/stream?mediaKey=1"}, {http.MethodHead, "/media/stream?mediaKey=1"}, {http.MethodGet, "/media/thumb?mediaKey=1"}, } { response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(request.method, request.target, nil)) if response.Code != http.StatusUnauthorized { t.Errorf("%s %s status = %d, want %d", request.method, request.target, response.Code, http.StatusUnauthorized) } } } // TestMediaGateAllowsAnonymousWhenLoginIsOff checks the gate the media stream and thumbnail routes // use: with login disabled an anonymous request reaches the handler, as it does for the rest of // the application. The handler here is a stub, so no database or CarrierNode call is made. func TestMediaGateAllowsAnonymousWhenLoginIsOff(t *testing.T) { auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject") reached := false gate := auth.RequireIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached = true })) for _, target := range []string{"/media/stream?mediaKey=1", "/media/thumb?mediaKey=1"} { reached = false response := httptest.NewRecorder() gate.ServeHTTP(response, httptest.NewRequest(http.MethodGet, target, nil)) if !reached || response.Code != http.StatusOK { t.Errorf("GET %s with login off: reached = %v, status = %d; want reached and 200", target, reached, response.Code) } } } // newRoleAuthGuard stands in for AuthGuard's GET /api/me. Each bearer token maps to one role, so a // test can act as a viewer, a moderator or an admin without a database. func newRoleAuthGuard(t *testing.T) *httptest.Server { t.Helper() roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"} server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { role, ok := roles[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")] if !ok || r.URL.Path != "/api/me" { w.WriteHeader(http.StatusUnauthorized) return } w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, `{"user":{"id":1,"username":"tester","role":%q}}`, role) })) t.Cleanup(server.Close) return server } // TestOnlyModeratorsCanSeeHiddenMedia checks which callers get hidden media looked up at all. // Anonymous callers and viewers may not; moderators and admins may. With login off every caller // is the placeholder superadmin, as for the rest of the application. The active = FALSE filter // itself needs a database and is not exercised here. func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) { guard := newRoleAuthGuard(t) login := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject") loginOff := sharedauth.NewWithStore(loginOffStore{}, "session", false, guard.URL, "testproject") for _, tc := range []struct { name string auth *sharedauth.Service token string want string }{ {"anonymous with login required", login, "", "false"}, {"viewer", login, "viewer-token", "false"}, {"moderator", login, "moderator-token", "true"}, {"admin", login, "admin-token", "true"}, {"anonymous with login off", loginOff, "", "true"}, } { router := chi.NewRouter() router.With(tc.auth.Optional).Get("/probe", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, canSeeHidden(r)) }) request := httptest.NewRequest(http.MethodGet, "/probe", nil) if tc.token != "" { request.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: tc.token}) } response := httptest.NewRecorder() router.ServeHTTP(response, request) if got := response.Body.String(); got != tc.want { t.Errorf("%s: canSeeHidden = %q, want %q", tc.name, got, tc.want) } } } // TestSyncWriteRequiresLogin checks that an anonymous PUT /sync is refused before it can change // shared playback state. The Core has no sync hub, so reaching the handler would panic. func TestSyncWriteRequiresLogin(t *testing.T) { auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject") router := chi.NewRouter() New(Config{Auth: auth}).Mount(router) request := httptest.NewRequest(http.MethodPut, "/sync", strings.NewReader(`{"clientId":"c1","mediaId":"m1"}`)) response := httptest.NewRecorder() router.ServeHTTP(response, request) if response.Code != http.StatusUnauthorized { t.Errorf("PUT /sync status = %d, want %d", response.Code, http.StatusUnauthorized) } } // TestSyncScalarKeepsOnlyScalars checks that sync values are limited to null, numbers and // bounded strings, so objects, arrays and booleans are never stored as session state. func TestSyncScalarKeepsOnlyScalars(t *testing.T) { if value, ok := syncScalar(nil); !ok || value != nil { t.Errorf("syncScalar(nil) = %v, %v; want nil, true", value, ok) } if value, ok := syncScalar(float64(7)); !ok || value != float64(7) { t.Errorf("syncScalar(7) = %v, %v; want 7, true", value, ok) } if value, ok := syncScalar(" media-1 "); !ok || value != "media-1" { t.Errorf("syncScalar(string) = %v, %v; want media-1, true", value, ok) } long, ok := syncScalar(strings.Repeat("x", 500)) if text, isText := long.(string); !ok || !isText || len(text) != 128 { t.Errorf("syncScalar(long string) = %v, %v; want a 128-byte string, true", long, ok) } for _, refused := range []any{map[string]any{"a": 1}, []any{1}, true} { if _, ok := syncScalar(refused); ok { t.Errorf("syncScalar(%#v) accepted a non-scalar value", refused) } } }