Files
stpweb/backend/handlers/handlers_pure_test.go
T
adamfandClaude Opus 5.5 4530cb8dc4
Test and deploy / test (push) Successful in 28s
Test and deploy / deploy (push) Successful in 31s
Trim comments to the non-obvious why
Drop narration, history and restated-code comments across the repo,
keep short ones for security boundaries, upstream quirks and ordering
constraints, and record the convention in CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:49:03 +00:00

266 lines
7.8 KiB
Go

package handlers
import (
"net/http/httptest"
"strings"
"testing"
"time"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/zmb3/spotify/v2"
)
// Handlers needing a live DB, multipart requests or container paths aren't
// covered here.
// --- Spotify OAuth CSRF nonces -------------------------------------------
func TestSpotifyStateSingleUse(t *testing.T) {
s := &Store{}
state, err := s.NewSpotifyState()
if err != nil {
t.Fatalf("NewSpotifyState: %v", err)
}
if !s.ConsumeSpotifyState(state) {
t.Fatal("a freshly minted state must be accepted")
}
// The whole point of the nonce: a replayed callback must not authenticate
// a second time.
if s.ConsumeSpotifyState(state) {
t.Fatal("a consumed state must not be accepted again")
}
}
func TestConsumeSpotifyStateRejections(t *testing.T) {
cases := []struct {
name string
// setup returns the state string to present to ConsumeSpotifyState.
setup func(s *Store) string
want bool
}{
{
name: "empty state is rejected before the map is even consulted",
setup: func(*Store) string { return "" },
want: false,
},
{
name: "a state this process never minted is rejected",
setup: func(*Store) string { return "deadbeef" },
want: false,
},
{
name: "a state minted within the TTL is accepted",
setup: func(s *Store) string {
st, _ := s.NewSpotifyState()
return st
},
want: true,
},
{
name: "a state older than the TTL is rejected",
setup: func(s *Store) string {
st, _ := s.NewSpotifyState()
// Backdating beats sleeping for ten minutes; the map is in the
// same package so the creation stamp is writable here.
s.spotifyStates[st] = time.Now().Add(-spotifyStateTTL - time.Second)
return st
},
want: false,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := &Store{}
state := c.setup(s)
if got := s.ConsumeSpotifyState(state); got != c.want {
t.Fatalf("ConsumeSpotifyState = %v, want %v", got, c.want)
}
})
}
}
// An expired nonce must also be removed, not merely refused: otherwise the map
// grows without bound for any flow that is started and abandoned.
func TestNewSpotifyStatePrunesExpired(t *testing.T) {
s := &Store{}
stale, _ := s.NewSpotifyState()
s.spotifyStates[stale] = time.Now().Add(-spotifyStateTTL - time.Second)
if _, err := s.NewSpotifyState(); err != nil {
t.Fatalf("NewSpotifyState: %v", err)
}
if _, ok := s.spotifyStates[stale]; ok {
t.Fatal("minting a new state should have pruned the expired one")
}
}
// --- Cache TTL rules ------------------------------------------------------
// Empty counts as stale on purpose; pinned so it isn't "fixed".
func TestCachedRecentSongsFreshness(t *testing.T) {
song := []spotify.RecentlyPlayedItem{{}}
cases := []struct {
name string
setup func(s *Store)
wantOK bool
}{
{"never fetched", func(*Store) {}, false},
{"fetched but empty counts as stale", func(s *Store) {
s.SetRecentSongs([]spotify.RecentlyPlayedItem{})
}, false},
{"just fetched", func(s *Store) { s.SetRecentSongs(song) }, true},
{"inside the one-minute TTL", func(s *Store) {
s.SetRecentSongs(song)
s.RecentSongsFetchedAt = time.Now().Add(-59 * time.Second)
}, true},
{"past the one-minute TTL", func(s *Store) {
s.SetRecentSongs(song)
s.RecentSongsFetchedAt = time.Now().Add(-time.Minute - time.Second)
}, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := &Store{}
c.setup(s)
if _, ok := s.CachedRecentSongs(); ok != c.wantOK {
t.Fatalf("fresh = %v, want %v", ok, c.wantOK)
}
})
}
}
func TestCachedGiteaFeedFreshness(t *testing.T) {
feed := &services.GiteaFeedResponse{}
cases := []struct {
name string
setup func(s *Store)
wantOK bool
}{
{"never fetched", func(*Store) {}, false},
{"just fetched", func(s *Store) { s.SetGiteaFeed(feed) }, true},
{"past the one-minute TTL", func(s *Store) {
s.SetGiteaFeed(feed)
s.GiteaFeedFetchedAt = time.Now().Add(-time.Minute - time.Second)
}, false},
// Unlike the songs cache, a nil feed is the only "empty" here, and a
// nil stored feed must never read as fresh.
{"explicitly cached nil is never fresh", func(s *Store) { s.SetGiteaFeed(nil) }, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := &Store{}
c.setup(s)
if _, ok := s.CachedGiteaFeed(); ok != c.wantOK {
t.Fatalf("fresh = %v, want %v", ok, c.wantOK)
}
})
}
}
func TestCachedSteamFreshness(t *testing.T) {
games := []services.SteamRecentGame{{}}
cases := []struct {
name string
setup func(s *Store)
wantOK bool
wantOnline bool
}{
{"never fetched", func(*Store) {}, false, false},
{"just fetched, online flag preserved", func(s *Store) { s.SetSteam(games, true) }, true, true},
{"just fetched, offline", func(s *Store) { s.SetSteam(games, false) }, true, false},
{"nil games list counts as stale even when online", func(s *Store) { s.SetSteam(nil, true) }, false, false},
{"past the five-minute TTL", func(s *Store) {
s.SetSteam(games, true)
s.SteamFetchedAt = time.Now().Add(-5*time.Minute - time.Second)
}, false, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := &Store{}
c.setup(s)
_, online, ok := s.CachedSteam()
if ok != c.wantOK {
t.Fatalf("fresh = %v, want %v", ok, c.wantOK)
}
if online != c.wantOnline {
t.Fatalf("online = %v, want %v", online, c.wantOnline)
}
})
}
}
// --- Upload trust boundary ------------------------------------------------
func TestRequestIsAdmin(t *testing.T) {
gin.SetMode(gin.TestMode)
claims := func(m jwt.MapClaims) any { return &m }
cases := []struct {
name string
// set is nil when nothing should be put in the context at all.
set any
want bool
}{
{"no claims in context at all", nil, false},
{"claims of the wrong type are not trusted", "not-claims", false},
// A by-value jwt.MapClaims is not what AuthMiddleware stores; accepting
// it would mean the type assertion had been loosened.
{"claims stored by value rather than by pointer", jwt.MapClaims{"admin": true}, false},
{"pre-admin-claim token has no admin key", claims(jwt.MapClaims{"id": 1.0}), false},
{"admin false", claims(jwt.MapClaims{"admin": false}), false},
{"admin as a string is not a truthy admin", claims(jwt.MapClaims{"admin": "true"}), false},
{"admin true", claims(jwt.MapClaims{"admin": true}), true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
if c.set != nil {
ctx.Set("userClaims", c.set)
}
if got := requestIsAdmin(ctx); got != c.want {
t.Fatalf("requestIsAdmin = %v, want %v", got, c.want)
}
})
}
}
// --- Permission gate ------------------------------------------------------
// Must 404 before any session lookup (a nil Store would panic).
func TestValidatePermissionUnknownKey(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Store{}
for _, key := range []string{"no-such-service", "admin", ""} {
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "permission", Value: key}}
ctx.Request = httptest.NewRequest("GET", "/auth/validate/"+key, nil)
s.ValidatePermission(ctx)
if ctx.Writer.Status() != 404 {
t.Errorf("key %q: status %d, want 404", key, ctx.Writer.Status())
}
}
}
func TestRadioAllowList(t *testing.T) {
for ext := range allowedAudioExtensions {
// The handler looks up strings.ToLower(filepath.Ext(...)), so a key in
// any other shape is unreachable.
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
t.Errorf("malformed allow-list key %q", ext)
}
}
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
if allowedAudioExtensions[ext] {
t.Errorf("%q must not be an allowed radio upload extension", ext)
}
}
}