2026-11-01 21:48:05 +01:00
package media
2026-10-19 07:48:07 +00:00
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
2026-11-18 14:00:13 +01:00
"net/url"
2026-10-19 07:48:07 +00:00
"strings"
"testing"
"github.com/go-chi/chi/v5"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// 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 )
}
}
}
2026-11-18 14:00:13 +01:00
func TestStreamUpstreamPathForwardsOnlyLiveTranscodeOptions ( t * testing . T ) {
for _ , tc := range [] struct {
name string
query url . Values
want string
}{
{ "plain stream" , url . Values { "mediaKey" : { "abc" }}, "/media/Videos/clip.mp4" },
{ "blank options are dropped" , url . Values { "quality" : { " " }, "start" : { "" }}, "/media/Videos/clip.mp4" },
{ "quality and start are forwarded" , url . Values { "mediaKey" : { "abc" }, "quality" : { "1080" }, "start" : { " 12.5 " }}, "/media/Videos/clip.mp4?quality=1080&start=12.5" },
{ "quality alone" , url . Values { "quality" : { "720" }}, "/media/Videos/clip.mp4?quality=720" },
} {
if got := streamUpstreamPath ( "Videos/clip.mp4" , tc . query ); got != tc . want {
t . Errorf ( "%s: streamUpstreamPath() = %q, want %q" , tc . name , got , tc . want )
}
}
}