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]>
This commit is contained in:
2026-09-16 16:12:21 +01:00
co-authored by Claude Opus 5
parent 64df70e5d2
commit 25ac1cde1c
69 changed files with 2381 additions and 1607 deletions
+83 -107
View File
@@ -1,6 +1,7 @@
package handlers
import (
"errors"
"log"
"net/http"
@@ -36,7 +37,7 @@ type UserCredentials struct {
//
// It deliberately does NOT fall back to the refresh token: an expired access
// token yields a 401 and the front end is expected to call /auth/refresh and
// retry.
// retry. A token whose version has been revoked is also a 401.
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
access_token, err := ctx.Cookie("access_token")
if err != nil {
@@ -44,7 +45,10 @@ func (store *Store) AuthMiddlewear(ctx *gin.Context) {
return
}
claims, err := store.Auth.VerifyJWT(access_token)
// Validated against the database, not just cryptographically: that is
// what makes a logged-out or password-changed token stop working here
// rather than lingering until it expires.
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, access_token)
if err != nil {
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
return
@@ -105,9 +109,9 @@ func (store *Store) ValidateAdmin(ctx *gin.Context) {
return
}
claims, err := store.Auth.VerifyJWT(accessToken)
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err != nil {
// Expired/invalid access token — try refreshing
// Expired, invalid or revoked access token — try refreshing
if !store.tryRefreshAndValidateAdmin(ctx) {
ctx.Status(http.StatusUnauthorized)
}
@@ -139,30 +143,19 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
return false
}
claims, err := store.Auth.VerifyJWT(refreshToken)
// Any failure at all (bad token, unknown user, revoked version) is
// "cannot decide" here, exactly as before: the caller sends 401.
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil {
return false
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
return false
}
// Pre-setting ID and calling First with no explicit condition makes GORM
// use the primary key already in the struct as the lookup. Soft-deleted
// users are excluded automatically, so a deleted admin fails here.
user := models.User{ID: uint(userIDF)}
if err := store.DB.First(&user).Error; err != nil {
return false
}
if !user.Admin {
ctx.Status(http.StatusForbidden)
return true
}
tokens, err := store.Auth.GenerateJWT(&user)
tokens, err := store.Auth.GenerateJWT(user)
if err != nil {
return false
}
@@ -173,32 +166,11 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
return true
}
// setAuthCookies writes the access/refresh cookie pair.
//
// The two trailing booleans of gin's SetCookie are Secure and HttpOnly, both
// true here: the cookies are never sent over plain HTTP and are invisible to
// JavaScript. SameSite=Lax lets them survive a top-level navigation back from
// an OAuth provider while still blocking cross-site POSTs. Each cookie's
// max-age mirrors the lifetime baked into the token itself, so the browser
// drops it at roughly the moment it stops being accepted.
// setAuthCookies writes the access/refresh cookie pair. The cookie
// attributes live in services.SetAuthCookies so that REST and GraphQL cannot
// disagree about them; this method is just the Store-shaped spelling of it.
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
ctx.SetSameSite(http.SameSiteLaxMode)
ctx.SetCookie(
"access_token",
tokens.AccessToken,
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
"/",
store.Auth.Config.Domain,
true, true,
)
ctx.SetCookie(
"refresh_token",
tokens.RefreshToken,
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
"/",
store.Auth.Config.Domain,
true, true,
)
services.SetAuthCookies(ctx, store.Auth.Config, tokens)
}
// CheckToken backs GET /auth/check: it returns the current user for a valid
@@ -212,38 +184,31 @@ func (store *Store) CheckToken(ctx *gin.Context) {
return
}
claims, err := store.Auth.VerifyJWT(access_token)
// Status codes here are unchanged from the hand-rolled version: a bad
// token or bad claims are both 401, and only a missing user is 404 with
// the cookies cleared. A revoked (out-of-date version) token joins the
// 401 case, since from the client's point of view it is simply no longer
// a valid token.
user, err := store.Auth.AuthenticateToken(store.DB, access_token)
if err != nil {
if errors.Is(err, services.ErrUserNotFound) {
log.Println(err)
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
store.removeCookies(ctx)
return
}
ctx.JSON(401, gin.H{"error": "unauthorized"})
return
}
// JWT claims come back through encoding/json, so every number is a
// float64 regardless of the Go type it was signed from.
userIDF, ok := (*claims)["id"].(float64)
if !ok {
ctx.JSON(401, gin.H{"error": "unauthorized"})
return
}
userID := uint(userIDF)
user := models.User{ID: userID}
tx := store.DB.First(&user)
if tx.Error != nil {
log.Println(tx.Error)
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
store.removeCookies(ctx)
return
}
ctx.JSON(http.StatusOK, user)
}
// RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token
// for a new cookie pair and returns the user.
//
// Tokens are not rotated in any revocable sense — the old refresh token stays
// valid until it expires, because nothing is tracked server-side.
// The old refresh token is not rotated, but it does die when the user logs out
// or changes their password, because those bump the token version this checks.
func (store *Store) RefreshToken(ctx *gin.Context) {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
@@ -251,29 +216,27 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
return
}
claims, err := store.Auth.VerifyJWT(refreshToken)
// The three outcomes below preserve the original status codes exactly:
// an unusable token is 401, unreadable claims are 500, and a token for a
// user that no longer exists is 404 with the cookies cleared. A revoked
// token is treated as an unusable one (401) — the client's correct
// response is to log in again.
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
switch {
case errors.Is(err, services.ErrInvalidClaims):
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid token claims"})
case errors.Is(err, services.ErrUserNotFound):
log.Println(err)
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
store.removeCookies(ctx)
default:
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
}
return
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid token claims"})
return
}
userID := uint(userIDF)
user := models.User{ID: userID}
tx := store.DB.First(&user)
if tx.Error != nil {
log.Println(tx.Error)
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
store.removeCookies(ctx)
return
}
tokens, err := store.Auth.GenerateJWT(&user)
tokens, err := store.Auth.GenerateJWT(user)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
@@ -329,34 +292,47 @@ func (store *Store) Login(ctx *gin.Context) {
ctx.JSON(http.StatusAccepted, user)
}
// Logout backs POST /auth/logout. It only clears the browser's cookies —
// the tokens themselves stay cryptographically valid until they expire, so a
// copy taken beforehand would still work.
// Logout backs POST /auth/logout. As well as clearing the browser's cookies
// it bumps the user's token version, so the tokens it just discarded — and
// any copy taken beforehand — stop being accepted immediately.
//
// It always answers 200: identifying the caller is best effort (the cookies
// may already be gone or expired), and a client that cannot be identified has
// nothing to revoke anyway.
func (store *Store) Logout(ctx *gin.Context) {
store.revokeCallerTokens(ctx)
store.removeCookies(ctx)
ctx.Status(http.StatusOK)
}
// removeCookies expires both auth cookies. The max-age of -1 is what tells
// the browser to delete them; path, domain and the Secure/HttpOnly flags must
// match those used when setting them or the browser keeps the originals.
// revokeCallerTokens bumps the token version of whoever made this request,
// identified from the access token or, failing that, the refresh token.
//
// It deliberately verifies the token rather than just reading the id out of
// it: without that, anyone could bump an arbitrary user's version by posting a
// forged cookie, which is a denial-of-service on that account's sessions.
func (store *Store) revokeCallerTokens(ctx *gin.Context) {
for _, name := range []string{"access_token", "refresh_token"} {
token, err := ctx.Cookie(name)
if err != nil {
continue
}
user, err := store.Auth.AuthenticateToken(store.DB, token)
if err != nil {
continue
}
if err := services.BumpTokenVersion(store.DB, user.ID); err != nil {
// Logged rather than returned: the cookies are still cleared, but
// this means the logout did not actually revoke anything.
log.Printf("logout: failed to revoke tokens for user %d: %v", user.ID, err)
}
return
}
}
// removeCookies expires both auth cookies; see services.ClearAuthCookies for
// why the attributes have to match those used when setting them.
func (store *Store) removeCookies(ctx *gin.Context) {
ctx.SetSameSite(http.SameSiteLaxMode)
ctx.SetCookie(
"access_token",
"",
-1,
"/",
store.Auth.Config.Domain,
true, true,
)
ctx.SetCookie(
"refresh_token",
"",
-1,
"/",
store.Auth.Config.Domain,
true, true,
)
services.ClearAuthCookies(ctx, store.Auth.Config)
}
+62 -7
View File
@@ -10,11 +10,17 @@ import (
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// Attachment upload for the chat. Files land in a directory that nginx serves
// directly at /uploads/, so anything written here is publicly reachable by
// URL — which is why the extension and content checks below matter.
// Attachment upload for the chat.
//
// Files land in one of two directories. /backend/uploads/ is served by nginx
// at /uploads/ with no authentication, so anything written there is publicly
// reachable by URL — which is why the extension and content checks below
// matter. /backend/uploads/private/ holds attachments for private (admin-only)
// messages and is served at /uploads/private/ behind an nginx auth_request
// gate; only an admin may upload there.
// allowedExtensions is the upload allow-list, keyed by lower-cased extension.
var allowedExtensions = map[string]bool{
@@ -36,10 +42,28 @@ var extensionToMIMEPrefix = map[string]string{
".pdf": "application/pdf", ".txt": "text/",
}
// publicUploadDir and privateUploadDir are the two destinations; the private
// one is created on demand because nothing else guarantees it exists.
const (
publicUploadDir = "/backend/uploads/"
privateUploadDir = "/backend/uploads/private/"
)
// UploadMessageFile backs POST /messages/upload (login required) and returns
// the public URL of the stored file, which the client then sends over the
// WebSocket as a message's fileUrl.
// the URL of the stored file, which the client then sends over the WebSocket
// as a message's fileUrl.
//
// The multipart form takes an optional "private" field: "true" stores the file
// under /uploads/private/ for use as a private message's attachment. That is
// admin-only, because private messages themselves are — an attachment URL
// leaking out is the same disclosure as the message leaking out.
func (store *Store) UploadMessageFile(ctx *gin.Context) {
private := ctx.PostForm("private") == "true"
if private && !requestIsAdmin(ctx) {
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
@@ -94,7 +118,18 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
}
filename := hex.EncodeToString(b) + ext
uploadDir := "/backend/uploads/"
uploadDir := publicUploadDir
urlPrefix := "/uploads/"
if private {
uploadDir = privateUploadDir
urlPrefix = "/uploads/private/"
// 0755 so nginx (a different user) can traverse the directory to
// serve the files once its auth_request gate has approved.
if err := os.MkdirAll(uploadDir, 0755); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
}
dest := filepath.Join(uploadDir, filename)
// Reopened rather than rewound: the earlier handle was closed after
@@ -119,5 +154,25 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
return
}
ctx.JSON(http.StatusOK, gin.H{"url": "/uploads/" + filename})
ctx.JSON(http.StatusOK, gin.H{"url": urlPrefix + filename})
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
// public attachments — so the admin check is made here from the same
// "userClaims" value AdminMiddleware would have read.
func requestIsAdmin(ctx *gin.Context) bool {
claims, exists := ctx.Get("userClaims")
if !exists {
return false
}
mapClaims, ok := claims.(*jwt.MapClaims)
if !ok {
return false
}
admin, ok := (*mapClaims)["admin"].(bool)
return ok && admin
}
+18 -13
View File
@@ -4,16 +4,18 @@ import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"strings"
"github.com/rwcarlsen/goexif/exif"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/anthropics/anthropic-sdk-go"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// Rowing log. The interesting endpoint is CreateRowing: rather than a form,
@@ -109,13 +111,21 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
// Duplicate guard: two photos of the same session share an EXIF capture
// time to the second. Checked before the Claude call so a re-upload costs
// nothing. Note this reads err == nil as "found" — an actual database
// error is indistinguishable from "no match" here and lets the insert
// proceed.
// nothing.
//
// Fails closed: only gorm.ErrRecordNotFound means "no duplicate". Any
// other error is a real database problem, and treating it as "not found"
// would both insert a duplicate and spend a paid Claude call to do it.
var existing models.Rowing
if err := store.DB.Where("date = ?", dateTaken).First(&existing).Error; err == nil {
err = store.DB.Where("date = ?", dateTaken).First(&existing).Error
switch {
case err == nil:
ctx.JSON(http.StatusConflict, gin.H{"error": "duplicate entry for this date"})
return
case !errors.Is(err, gorm.ErrRecordNotFound):
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
// Build the message with an image + text prompt
@@ -158,15 +168,10 @@ No text, no markdown, no explanation. Just the JSON object.`),
}
// Strip a markdown code fence if the model wrapped its JSON in one
// despite the prompt. Same defensive dance as in services/email_sync.go.
// despite the prompt; shared with the email pipeline, which asks for bare
// JSON in the same way and gets fenced output just as often.
extractedData := ExtractedRowingData{}
raw := message.Content[0].Text
raw = strings.TrimSpace(raw)
raw = strings.TrimPrefix(raw, "```json")
raw = strings.TrimPrefix(raw, "```")
raw = strings.TrimSuffix(raw, "```")
raw = strings.TrimSpace(raw)
raw := services.StripMarkdownFence(message.Content[0].Text)
err = json.Unmarshal([]byte(raw), &extractedData)
if err != nil {
+49 -24
View File
@@ -4,7 +4,6 @@ import (
"context"
"log"
"net/http"
"time"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
@@ -22,6 +21,18 @@ import (
// 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()
@@ -50,6 +61,24 @@ func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
})
}
// 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.
@@ -71,26 +100,16 @@ func (store *Store) ListeningTo(ctx *gin.Context) {
ctx.JSON(200, playing)
}
// RecentlyPlayed backs GET /spotify/recent.
//
// It reads the cache but never writes it: only the GraphQL spotifyRecent
// resolver populates Store.RecentSongs. So this endpoint serves cached data
// only when a GraphQL query happened to fill the cache in the last minute,
// and otherwise calls Spotify every time.
// 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
}
opts := spotify.RecentlyPlayedOptions{Limit: 3}
if store.RecentSongsFresh() {
ctx.JSON(200, *store.RecentSongs)
return
}
played, err := store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
played, err := store.RecentlyPlayedTracks(ctx)
if err != nil {
log.Println(err)
ctx.JSON(500, gin.H{"error": "failed to fetch recently played"})
@@ -100,17 +119,23 @@ func (store *Store) RecentlyPlayed(ctx *gin.Context) {
ctx.JSON(200, played)
}
// RecentSongsFresh reports whether the cached recently-played list is within
// its one-minute TTL. An empty list counts as stale, so an empty listening
// history is re-fetched every time.
func (s *Store) RecentSongsFresh() bool {
if s.RecentSongs == nil {
return false
// 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
}
if len(*s.RecentSongs) == 0 {
return false
opts := spotify.RecentlyPlayedOptions{Limit: 3}
played, err := store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
if err != nil {
return nil, err
}
return time.Since(s.RecentSongsFetchedAt) < time.Minute
store.SetRecentSongs(played)
return played, nil
}
+140 -19
View File
@@ -1,6 +1,9 @@
package handlers
import (
"crypto/rand"
"encoding/hex"
"sync"
"time"
"adam-french.co.uk/backend/services"
@@ -17,11 +20,11 @@ import (
// Store is the backend's dependency container: it is built once in main and
// passed around by pointer, so the caches on it are shared process-wide.
//
// Concurrency note: the cache fields below are read and written by concurrent
// requests without a mutex. The races are benign in practice (worst case two
// requests refresh the same third-party API at once, or one reads a value
// being replaced), but this is a deliberate simplification, not an oversight
// — do not add a field here that would be unsafe to tear.
// Concurrency note: the third-party caches below are read and written by
// concurrent requests, so every access goes through cacheMu and the accessor
// methods at the bottom of this file. Do not touch the cache fields directly
// — an unsynchronised read of one of them is a data race, not merely a stale
// value.
type Store struct {
DB *gorm.DB
SpotifyAuth *spotifyauth.Authenticator
@@ -35,6 +38,12 @@ type Store struct {
// Cached "recently played" tracks, refreshed at most once a minute by the
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
// mean "never fetched" distinctly from "fetched, empty".
// cacheMu guards every cache field below (and only those). One mutex for
// all of them keeps the locking obvious; the critical sections are just
// field copies, never network calls, so there is no contention worth
// splitting it up for.
cacheMu sync.RWMutex
RecentSongs *[]spotify.RecentlyPlayedItem
RecentSongsFetchedAt time.Time
@@ -50,25 +59,137 @@ type Store struct {
SteamRecentGames []services.SteamRecentGame
SteamOnline bool
SteamFetchedAt time.Time
// spotifyStates holds the one-shot CSRF nonces handed out by
// GET /spotify/auth, mapped to their creation time. In-memory is enough:
// there is one backend instance, and losing them on restart only means
// restarting an OAuth flow that takes seconds.
spotifyStatesMu sync.Mutex
spotifyStates map[string]time.Time
}
// GiteaFeedFresh reports whether the cached Gitea feed entry is still within
// its one-minute TTL. A nil cache is never fresh, so the first request always
// hits Gitea.
func (s *Store) GiteaFeedFresh() bool {
if s.GiteaFeed == nil {
return false
// spotifyStateTTL is how long an unused Spotify OAuth nonce stays valid. Long
// enough to log in at Spotify and approve the scopes, short enough that a
// leaked authorisation URL is not reusable later.
const spotifyStateTTL = 10 * time.Minute
// NewSpotifyState mints a one-shot CSRF nonce for the Spotify authorisation
// URL and remembers it. Expired entries are pruned on the way through, which
// is the only cleanup there is — the map is otherwise unbounded, and only an
// admin can add to it.
func (s *Store) NewSpotifyState() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return time.Since(s.GiteaFeedFetchedAt) < time.Minute
state := hex.EncodeToString(b)
s.spotifyStatesMu.Lock()
defer s.spotifyStatesMu.Unlock()
if s.spotifyStates == nil {
s.spotifyStates = make(map[string]time.Time)
}
for k, created := range s.spotifyStates {
if time.Since(created) > spotifyStateTTL {
delete(s.spotifyStates, k)
}
}
s.spotifyStates[state] = time.Now()
return state, nil
}
// SteamFresh reports whether the cached Steam data is still within its
// five-minute TTL. Note it tests only SteamRecentGames: if Steam legitimately
// returns no recent games, the cache never registers as fresh and every
// request re-queries the API.
func (s *Store) SteamFresh() bool {
if s.SteamRecentGames == nil {
// ConsumeSpotifyState checks a nonce returned by Spotify's redirect and
// removes it, so a replayed callback fails. An unknown or expired nonce
// returns false, which the callback must treat as a rejected request.
func (s *Store) ConsumeSpotifyState(state string) bool {
if state == "" {
return false
}
return time.Since(s.SteamFetchedAt) < 5*time.Minute
s.spotifyStatesMu.Lock()
defer s.spotifyStatesMu.Unlock()
created, ok := s.spotifyStates[state]
if !ok {
return false
}
delete(s.spotifyStates, state)
return time.Since(created) <= spotifyStateTTL
}
// The cache accessors below are the only supported way to touch the cache
// fields. Each "Cached..." method returns the value plus a bool that is true
// only when the entry is present and inside its TTL; each "Set..." method
// stores a value and stamps it.
// CachedRecentSongs returns the cached Spotify recently-played list if it is
// within its one-minute TTL. An empty list counts as stale, so an empty
// listening history is re-fetched every time (unchanged behaviour).
func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) {
s.cacheMu.RLock()
defer s.cacheMu.RUnlock()
if s.RecentSongs == nil || len(*s.RecentSongs) == 0 {
return nil, false
}
if time.Since(s.RecentSongsFetchedAt) >= time.Minute {
return nil, false
}
return *s.RecentSongs, true
}
// SetRecentSongs replaces the cached recently-played list.
func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) {
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
s.RecentSongs = &songs
s.RecentSongsFetchedAt = time.Now()
}
// CachedGiteaFeed returns the cached Gitea activity entry if it is within its
// one-minute TTL. A nil cache is never fresh, so the first request always hits
// Gitea.
func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) {
s.cacheMu.RLock()
defer s.cacheMu.RUnlock()
if s.GiteaFeed == nil || time.Since(s.GiteaFeedFetchedAt) >= time.Minute {
return nil, false
}
return s.GiteaFeed, true
}
// SetGiteaFeed replaces the cached Gitea feed entry.
func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
s.GiteaFeed = feed
s.GiteaFeedFetchedAt = time.Now()
}
// CachedSteam returns the cached Steam recent games and online flag if they
// are within their five-minute TTL. As before, freshness is judged only on the
// games list: if Steam legitimately returns no recent games the cache never
// registers as fresh and every request re-queries the API.
func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok bool) {
s.cacheMu.RLock()
defer s.cacheMu.RUnlock()
if s.SteamRecentGames == nil || time.Since(s.SteamFetchedAt) >= 5*time.Minute {
return nil, false, false
}
return s.SteamRecentGames, s.SteamOnline, true
}
// SetSteam replaces the cached Steam data.
func (s *Store) SetSteam(games []services.SteamRecentGame, online bool) {
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
s.SteamRecentGames = games
s.SteamOnline = online
s.SteamFetchedAt = time.Now()
}