Files
stpweb/backend/handlers/handle_spotify.go
T
adamfandClaude Opus 5 25ac1cde1c Fix security issues, bugs, and convoluted code across the stack
Security:
- Token revocation. User gains a TokenVersion counter embedded in both
  tokens as a "tv" claim; AuthenticateToken rejects a token whose version
  no longer matches the row. Logout bumps it, so logging out now kills
  outstanding tokens rather than only clearing cookies. Costs one
  primary-key SELECT per authenticated request, which is the price of
  having revocation at all.
- Spotify OAuth CSRF. The fixed SPOTIFY_AUTH_STATE constant is replaced by
  a per-request one-shot nonce, verified and consumed on callback.
- Private chat attachments. Attachments on private messages are written to
  /backend/uploads/private/ and served at /uploads/private/, gated by the
  same nginx auth_request admin check used for /hasura/ and /notes/.
  Private uploads are rejected from non-admin callers.
- The icecast admin UI (/radio/admin/) is behind the admin gate; listener
  traffic is untouched.
- Store caches are mutex-guarded, so -race is clean.

Bugs:
- The email pipeline no longer drops emails permanently on transient
  failure. Failures record an attempt counter and are retried up to 3
  times; the fetch window rewinds to the oldest retryable email's
  ReceivedAt, without which a retry could never re-fetch it.
- Rowing duplicate detection distinguishes ErrRecordNotFound from a real
  DB error, so a transient failure no longer causes a duplicate insert
  plus a paid Claude call.
- DeletePost propagates its delete error instead of reporting success.
- RecentlyPlayed populates the cache it reads.
- main.go exits non-zero if r.Run fails, so a port conflict is visible.
- Python: the scan truncation flag is set on every deadline path;
  timed_out is reported by the worker rather than inferred from the clock;
  date validation uses Europe/London rather than server-local time.
- Vue: Time.vue and Radio.vue intervals are cleared on unmount; Feed.vue
  guards a missing author; Timer.vue gets an explicit state machine and
  compares total elapsed seconds; Elle.vue's comma-operator call and
  per-frame console.log are fixed.

Simplification:
- One TTLCache replaces three near-identical cache implementations, with
  the differing eviction rules as explicit parameters.
- run_scan's transport index no longer uses one object as both ordering
  record and live output; its three phases are separate functions.
- _price_hotels submits all work to a single pool, so the nested-executor
  deadlock hazard is gone by construction.
- The NDJSON event generators share one implementation.
- IMAP FETCH responses pair each line with its literal in the type, so
  callers no longer hand-skip alternate entries.
- Shared helpers for slice-of-pointers, markdown fences and auth cookies.
- Vue: useHotelSearch, createMirrorStore, useRotation, useCreateForm,
  useLinkAttrs, ListWidget and LinkTableItems replace duplicated blocks.
- nginx dev config's duplicated :80/:443 bodies share one partial.

Infra: certbot passes --deploy-hook touching a sentinel that nginx's
watcher reloads on, so renewed certs are served without a restart, and the
watcher also removes the manual restart after first issuance. db is gated
on service_healthy, autoheal is pinned, and the unused envsubst entries
are dropped.

Verified: go build/vet, npx vite build, py_compile, docker compose config
for both overlays, bash -n on all scripts, and an envsubst render of every
nginx template (no leftover placeholders, runtime vars preserved, braces
balanced).

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-16 16:12:21 +01:00

142 lines
4.6 KiB
Go

package handlers
import (
"context"
"log"
"net/http"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"github.com/zmb3/spotify/v2"
)
// These REST endpoints predate the equivalent GraphQL queries in
// graph/spotify.resolvers.go and are kept for the OAuth callback (which must
// be REST, because Spotify redirects a browser to it) and for direct use.
// CompleteSpotifyAuth handles Spotify's OAuth redirect to
// GET /spotify/callback. It swaps the code for a token, saves it so the
// authorisation survives restarts, and installs the authenticated client on
// the Store — which is how Store.SpotifyClient becomes non-nil without a
// restart.
func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
state := ctx.Query("state")
// CSRF check: the state must be a nonce this process handed out from
// StartSpotifyAuth and has not seen come back yet. Without it, anyone who
// could get the site owner's browser to hit this URL with an attacker's
// authorisation code would bind the site to the attacker's Spotify
// account. The library also compares the state to the value passed below,
// but since that value is the one just received, this check is the real
// one.
if !store.ConsumeSpotifyState(state) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid state"})
return
}
// context.Background, not the request context: the client built below
// outlives this request and would otherwise be cancelled when it ends.
c := context.Background()
// The library pulls the `code` out of the request itself and checks the
// state parameter matches the one passed here.
token, err := store.SpotifyAuth.Token(c, state, ctx.Request)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "authentication failed"})
return
}
if err := services.SaveSpotifyToken(services.SPOTIFY_TOKEN_JSON_PATH, token); err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
client := spotify.New(store.SpotifyAuth.Client(c, token))
store.SpotifyClient = client
ctx.JSON(http.StatusOK, gin.H{
"message": "Authentication successful",
})
}
// StartSpotifyAuth backs the admin-only GET /spotify/auth. It returns the
// Spotify authorisation URL carrying a freshly minted one-shot state nonce,
// which CompleteSpotifyAuth then verifies and consumes.
//
// This exists because the state has to be per-request to be a CSRF defence,
// and the start of the flow therefore has to be a request rather than a line
// printed at start-up.
func (store *Store) StartSpotifyAuth(ctx *gin.Context) {
state, err := store.NewSpotifyState()
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
ctx.JSON(http.StatusOK, gin.H{"url": store.SpotifyAuth.AuthURL(state)})
}
// ListeningTo backs GET /spotify/listening with the currently playing track.
// A nil client means the OAuth flow has never been completed, reported here
// as a 500.
func (store *Store) ListeningTo(ctx *gin.Context) {
c := ctx.Request.Context()
if store.SpotifyClient == nil {
ctx.JSON(500, gin.H{"error": "Spotify not authenticated"})
return
}
playing, err := store.SpotifyClient.PlayerCurrentlyPlaying(c)
if err != nil {
log.Println(err)
ctx.JSON(500, gin.H{"error": "failed to fetch currently playing"})
return
}
ctx.JSON(200, playing)
}
// RecentlyPlayed backs GET /spotify/recent, serving the shared one-minute
// cache. Both this endpoint and the GraphQL spotifyRecent resolver go through
// RecentlyPlayedTracks, so either one can fill the cache for the other.
func (store *Store) RecentlyPlayed(ctx *gin.Context) {
if store.SpotifyClient == nil {
ctx.JSON(500, gin.H{"error": "Spotify not authenticated"})
return
}
played, err := store.RecentlyPlayedTracks(ctx)
if err != nil {
log.Println(err)
ctx.JSON(500, gin.H{"error": "failed to fetch recently played"})
return
}
ctx.JSON(200, played)
}
// RecentlyPlayedTracks returns the last few played tracks, from the cache when
// it is fresh and from Spotify otherwise — populating the cache in that case.
//
// This is the single fetch-and-cache path for recently-played data; the caller
// must have checked SpotifyClient is non-nil.
func (store *Store) RecentlyPlayedTracks(ctx context.Context) ([]spotify.RecentlyPlayedItem, error) {
if cached, ok := store.CachedRecentSongs(); ok {
return cached, nil
}
opts := spotify.RecentlyPlayedOptions{Limit: 3}
played, err := store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
if err != nil {
return nil, err
}
store.SetRecentSongs(played)
return played, nil
}