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
+1 -8
View File
@@ -39,14 +39,7 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
if err := r.Store.DB.Order("created_at DESC").Find(&activities).Error; err != nil {
return nil, err
}
// Copy to a slice of pointers because the schema returns a list of
// nullable objects. Taking &activities[i] is safe: the slice is never
// appended to after this point, so the backing array cannot move.
result := make([]*models.Activity, len(activities))
for i := range activities {
result[i] = &activities[i]
}
return result, nil
return ptrs(activities), nil
}
// Activity returns ActivityResolver implementation.
+33 -27
View File
@@ -7,11 +7,13 @@ package graph
import (
"context"
"errors"
"fmt"
"net/http"
"log"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"golang.org/x/crypto/bcrypt"
)
@@ -48,7 +50,7 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
return nil, fmt.Errorf("failed to generate tokens")
}
setAuthCookies(gc, r.Store.Auth.Config, tokens)
services.SetAuthCookies(gc, r.Store.Auth.Config, tokens)
// The payload carries no token: the tokens only ever travel as HttpOnly
// cookies, so client JavaScript never sees them.
@@ -62,12 +64,18 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
return false, fmt.Errorf("could not get gin context")
}
// Max-age -1 tells the browser to drop the cookies. Nothing is
// invalidated server-side, so a token captured beforehand still works
// until it expires.
gc.SetSameSite(http.SameSiteLaxMode)
gc.SetCookie("access_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
gc.SetCookie("refresh_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
// Bumping the token version is what actually revokes the tokens; clearing
// the cookies only stops the browser presenting them. Both are best
// effort and logout always reports success, matching the REST endpoint.
if userID, ok := UserIDFromCtx(ctx); ok {
// The context only carries claims from a token that already
// verified, so this cannot be used to revoke someone else's sessions.
if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil {
log.Printf("logout: failed to revoke tokens for user %d: %v", userID, err)
}
}
services.ClearAuthCookies(gc, r.Store.Auth.Config)
return true, nil
}
@@ -84,33 +92,31 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
return nil, fmt.Errorf("unauthorized")
}
claims, err := r.Store.Auth.VerifyJWT(refreshToken)
// Shared with the REST refresh endpoint, but the messages below are the
// ones this resolver already returned, so the GraphQL error strings are
// unchanged. Admin status and the token version are both re-read from the
// database here, which is what lets a revoked admin flag or a logout take
// effect on refresh.
user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken)
if err != nil {
return nil, fmt.Errorf("unauthorized")
switch {
case errors.Is(err, services.ErrInvalidClaims):
return nil, fmt.Errorf("invalid token claims")
case errors.Is(err, services.ErrUserNotFound):
return nil, fmt.Errorf("user not found")
default:
return nil, fmt.Errorf("unauthorized")
}
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
return nil, fmt.Errorf("invalid token claims")
}
// Setting the primary key and calling First with no condition makes GORM
// look the row up by that key. Admin status is re-read from the database
// here, which is what lets a revoked admin flag take effect on refresh.
var user models.User
user.ID = uint(userIDF)
if err := r.Store.DB.First(&user).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
tokens, err := r.Store.Auth.GenerateJWT(&user)
tokens, err := r.Store.Auth.GenerateJWT(user)
if err != nil {
return nil, fmt.Errorf("failed to generate tokens")
}
setAuthCookies(gc, r.Store.Auth.Config, tokens)
services.SetAuthCookies(gc, r.Store.Auth.Config, tokens)
return &model.AuthPayload{User: &user}, nil
return &model.AuthPayload{User: user}, nil
}
// Me is the resolver for the me field.
-43
View File
@@ -1,43 +0,0 @@
package graph
import (
"net/http"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
)
// setAuthCookies writes the access/refresh cookie pair on a GraphQL response.
//
// This mirrors handlers.Store.setAuthCookies — the two cannot be shared
// because importing graph from handlers would be a cycle, so any change to
// cookie attributes has to be made in both places or login via REST and login
// via GraphQL will disagree.
//
// gin's SetCookie takes Secure and HttpOnly as its two trailing booleans, both
// true here: the cookies never travel over plain HTTP and are invisible to
// JavaScript. SameSite=Lax survives a top-level navigation back from an OAuth
// provider while still blocking cross-site POSTs. Each max-age mirrors the
// lifetime baked into the token itself.
//
// It lives in its own file rather than in auth.resolvers.go because gqlgen may
// relocate hand-written code in the files it regenerates.
func setAuthCookies(gc *gin.Context, config *services.AuthConfig, tokens *services.Tokens) {
gc.SetSameSite(http.SameSiteLaxMode)
gc.SetCookie(
"access_token",
tokens.AccessToken,
int(config.AccessTokenLifetime.Seconds()),
"/",
config.Domain,
true, true,
)
gc.SetCookie(
"refresh_token",
tokens.RefreshToken,
int(config.RefreshTokenLifetime.Seconds()),
"/",
config.Domain,
true, true,
)
}
+1 -8
View File
@@ -54,14 +54,7 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
if err := r.Store.DB.Order("category ASC, created_at ASC").Find(&bookmarks).Error; err != nil {
return nil, err
}
// Copy to a slice of pointers because the schema returns a list of
// nullable objects. Taking &bookmarks[i] is safe: the slice is never
// appended to after this point, so the backing array cannot move.
result := make([]*models.Bookmark, len(bookmarks))
for i := range bookmarks {
result[i] = &bookmarks[i]
}
return result, nil
return ptrs(bookmarks), nil
}
// Bookmark returns BookmarkResolver implementation.
+1 -8
View File
@@ -38,14 +38,7 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
if err := r.Store.DB.Order("created_at DESC").Find(&favorites).Error; err != nil {
return nil, err
}
// Copy to a slice of pointers because the schema returns a list of
// nullable objects. Taking &favorites[i] is safe: the slice is never
// appended to after this point, so the backing array cannot move.
result := make([]*models.Favorite, len(favorites))
for i := range favorites {
result[i] = &favorites[i]
}
return result, nil
return ptrs(favorites), nil
}
// Favorite returns FavoriteResolver implementation.
+3 -5
View File
@@ -7,7 +7,6 @@ package graph
import (
"context"
"time"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/services"
@@ -17,8 +16,8 @@ import (
func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, error) {
// One-minute cache on the Store, shared by every visitor, so a busy home
// page does not hammer the Gitea container.
if r.Store.GiteaFeedFresh() {
return mapGiteaFeed(r.Store.GiteaFeed), nil
if cached, ok := r.Store.CachedGiteaFeed(); ok {
return mapGiteaFeed(cached), nil
}
feed, err := services.FetchLatestFeed(r.Store.GiteaHost, r.Store.GiteaPort)
@@ -33,8 +32,7 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er
return nil, nil
}
r.Store.GiteaFeed = feed
r.Store.GiteaFeedFetchedAt = time.Now()
r.Store.SetGiteaFeed(feed)
return mapGiteaFeed(feed), nil
}
+1 -8
View File
@@ -40,14 +40,7 @@ func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error)
if err := query.Find(&messages).Error; err != nil {
return nil, err
}
// Copy to a slice of pointers because the schema returns a list of
// nullable objects. Taking &messages[i] is safe: the slice is never
// appended to after this point, so the backing array cannot move.
result := make([]*models.Message, len(messages))
for i := range messages {
result[i] = &messages[i]
}
return result, nil
return ptrs(messages), nil
}
// Message returns MessageResolver implementation.
+9 -2
View File
@@ -5,6 +5,7 @@ import (
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// AuthContextMiddleware prepares the request context for the GraphQL handler.
@@ -16,16 +17,22 @@ import (
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
// errors are swallowed for exactly that reason.
//
// It takes the database because validating a token means loading the user to
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
//
// Unlike the REST path there is no refresh-token fallback here, so once the
// access token expires GraphQL treats the caller as anonymous until the front
// end refreshes.
func AuthContextMiddleware(auth *services.Auth) gin.HandlerFunc {
func AuthContextMiddleware(auth *services.Auth, db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
accessToken, err := c.Cookie("access_token")
if err == nil {
claims, err := auth.VerifyJWT(accessToken)
// The database is needed to check the token version, so a
// revoked token (logout, password change) leaves the request
// anonymous instead of continuing to authorise mutations.
_, claims, err := auth.AuthenticateTokenWithClaims(db, accessToken)
if err == nil {
ctx = context.WithValue(ctx, userClaimsKey, claims)
}
+1 -5
View File
@@ -111,11 +111,7 @@ func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
return nil, err
}
result := make([]*models.Place, len(places))
for i := range places {
result[i] = &places[i]
}
return result, nil
return ptrs(places), nil
}
// Place returns PlaceResolver implementation.
+8 -11
View File
@@ -85,9 +85,13 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
return nil, fmt.Errorf("you can only delete your own posts")
}
// Soft delete; the error is dropped, so a failed delete still reports
// success to the client.
r.Store.DB.Delete(&post)
// Soft delete. The error is propagated: reporting success for a delete
// that did not happen would leave the client showing the post as gone
// until the next reload.
if err := r.Store.DB.Delete(&post).Error; err != nil {
return nil, err
}
return &post, nil
}
@@ -105,14 +109,7 @@ func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
return nil, err
}
// Copy to a slice of pointers because the schema returns a list of
// nullable objects. Taking &posts[i] is safe: the slice is never
// appended to after this point, so the backing array cannot move.
result := make([]*models.Post, len(posts))
for i := range posts {
result[i] = &posts[i]
}
return result, nil
return ptrs(posts), nil
}
// Post is the resolver for the post field.
+1 -8
View File
@@ -17,14 +17,7 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
if err := r.Store.DB.Order("created_at DESC").Find(&rows).Error; err != nil {
return nil, err
}
// Copy to a slice of pointers because the schema returns a list of
// nullable objects. Taking &rows[i] is safe: the slice is never
// appended to after this point, so the backing array cannot move.
result := make([]*models.Rowing, len(rows))
for i := range rows {
result[i] = &rows[i]
}
return result, nil
return ptrs(rows), nil
}
// ID is the resolver for the id field.
+22
View File
@@ -0,0 +1,22 @@
package graph
// This file is hand-written and is never regenerated by gqlgen — it is not
// named after a schema file, so `gqlgen generate` leaves it alone.
// ptrs copies a slice of values into a slice of pointers to those values.
//
// Every list query loads rows with Find(&xs) into a []T and then has to hand
// gqlgen a []*T, because the schema returns lists of nullable objects. Taking
// &xs[i] is safe: the slice is never appended to after this point, so the
// backing array cannot move and the pointers stay valid.
//
// Loading straight into a []*T would avoid the copy but changes the query
// GORM emits, so the copy is kept deliberately.
func ptrs[T any](xs []T) []*T {
result := make([]*T, len(xs))
for i := range xs {
result[i] = &xs[i]
}
return result
}
+3 -13
View File
@@ -7,10 +7,8 @@ package graph
import (
"context"
"time"
"adam-french.co.uk/backend/graph/model"
spotify "github.com/zmb3/spotify/v2"
)
// SpotifyListening is the resolver for the spotifyListening field.
@@ -40,20 +38,12 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
return []*model.SpotifyRecentItem{}, nil
}
// One-minute cache. This resolver is the only writer of that cache; the
// REST /spotify/recent endpoint reads it but never fills it.
if r.Store.RecentSongsFresh() {
return mapRecentItems(*r.Store.RecentSongs), nil
}
opts := spotify.RecentlyPlayedOptions{Limit: 3}
played, err := r.Store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
// Shared one-minute cache, filled by whichever of this resolver and the
// REST /spotify/recent endpoint misses it first.
played, err := r.Store.RecentlyPlayedTracks(ctx)
if err != nil {
return nil, err
}
r.Store.RecentSongs = &played
r.Store.RecentSongsFetchedAt = time.Now()
return mapRecentItems(played), nil
}
+4 -7
View File
@@ -7,7 +7,6 @@ package graph
import (
"context"
"time"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/services"
@@ -21,10 +20,10 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
// Five-minute cache across both Steam calls, which are made together and
// expire together.
if r.Store.SteamFresh() {
if games, online, ok := r.Store.CachedSteam(); ok {
return &model.SteamStatus{
Online: r.Store.SteamOnline,
RecentGames: mapSteamGames(r.Store.SteamRecentGames),
Online: online,
RecentGames: mapSteamGames(games),
}, nil
}
@@ -45,9 +44,7 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
online = summary.PersonaState > 0
}
r.Store.SteamRecentGames = games
r.Store.SteamOnline = online
r.Store.SteamFetchedAt = time.Now()
r.Store.SetSteam(games, online)
return &model.SteamStatus{
Online: online,
+1 -8
View File
@@ -92,14 +92,7 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
if err := r.Store.DB.Find(&users).Error; err != nil {
return nil, err
}
// Copy to a slice of pointers because the schema returns a list of
// nullable objects. Taking &users[i] is safe: the slice is never
// appended to after this point, so the backing array cannot move.
result := make([]*models.User, len(users))
for i := range users {
result[i] = &users[i]
}
return result, nil
return ptrs(users), nil
}
// User is the resolver for the user field.