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
+160 -6
View File
@@ -2,16 +2,23 @@ package services
import (
"errors"
"net/http"
"time"
"adam-french.co.uk/backend/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"gorm.io/gorm"
)
// Auth mints and verifies the HS256 JWTs that back the site's login. Tokens
// are handed to the browser as HTTP-only cookies (see handlers.Store.Login);
// there is no server-side session or token blacklist, so a token stays valid
// until it expires even after logout.
// are handed to the browser as HTTP-only cookies (see handlers.Store.Login).
//
// There is no token blacklist, but there is coarse server-side revocation:
// every token carries the user's models.User.TokenVersion in a "tv" claim,
// and AuthenticateToken rejects a token whose version has moved on. Bumping
// that column (BumpTokenVersion) therefore kills all of a user's outstanding
// tokens at once — which is what logout and a password change do.
type Auth struct {
Config *AuthConfig
}
@@ -43,19 +50,26 @@ func InitAuth(config *AuthConfig) *Auth {
//
// The access token carries the authorisation data the API needs (id, admin)
// so that most requests can be authorised without touching the database. The
// refresh token deliberately carries only the id: admin status is re-read
// from the database when refreshing, so revoking someone's admin flag takes
// effect on their next refresh rather than only when they log in again.
// refresh token deliberately carries only the id (plus the version): admin
// status is re-read from the database when refreshing, so revoking someone's
// admin flag takes effect on their next refresh rather than only when they
// log in again.
//
// Both tokens carry "tv", the user's TokenVersion at minting time. Anything
// that validates a token against the database checks it, so the pair dies the
// moment the column is bumped.
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username,
"id": user.ID,
"admin": user.Admin,
"tv": tokenVersionOf(user.TokenVersion),
"exp": time.Now().Add(auth.Config.AccessTokenLifetime).Unix(),
})
refreshToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": user.ID,
"tv": tokenVersionOf(user.TokenVersion),
"exp": time.Now().Add(auth.Config.RefreshTokenLifetime).Unix(),
})
@@ -99,3 +113,143 @@ func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
return &claims, nil
}
// Typed errors returned by AuthenticateToken so each call site can keep its
// own response for each case — the REST and GraphQL entry points deliberately
// answer differently (401 vs 500 vs 404-plus-cookie-clear).
var (
// ErrInvalidToken means the token is missing, malformed, expired or not
// correctly signed.
ErrInvalidToken = errors.New("invalid token")
// ErrInvalidClaims means the token verified but its "id" claim is absent
// or not a number — a server-side inconsistency, not a client error.
ErrInvalidClaims = errors.New("invalid token claims")
// ErrUserNotFound means the token named a user that no longer exists (or
// has been soft deleted).
ErrUserNotFound = errors.New("user not found")
// ErrTokenRevoked means the token is otherwise valid but was minted
// before the user's TokenVersion was bumped, i.e. logout or a password
// change has invalidated it.
ErrTokenRevoked = errors.New("token revoked")
)
// tokenVersionOf normalises a stored or claimed token version.
//
// Zero means "unset": either a row that predates the token_version column, or
// a token minted before the "tv" claim existed. Both are normalised to 1, the
// column's default, so introducing versioning logs nobody out. The first
// BumpTokenVersion moves a user to 2 and invalidates every older token.
func tokenVersionOf(v uint) uint {
if v == 0 {
return 1
}
return v
}
// AuthenticateToken is the one place a token string is turned into a user: it
// verifies the signature and expiry, reads the id claim, loads the row, and
// checks the token version. Every caller that used to hand-roll this sequence
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
// handlers.Store.tryRefreshAndValidateAdmin and the GraphQL refreshToken
// resolver) now goes through here, so the checks cannot drift apart.
//
// The returned error is always one of the sentinels above, wrapped or not, so
// call sites can map each case onto whatever status code they already used.
func (auth *Auth) AuthenticateToken(db *gorm.DB, tokenStr string) (*models.User, error) {
user, _, err := auth.AuthenticateTokenWithClaims(db, tokenStr)
return user, err
}
// AuthenticateTokenWithClaims is AuthenticateToken plus the raw claims, for
// the middlewares that go on to read claims the User struct does not carry
// (notably "admin", which is authoritative from the token rather than the
// row — see handlers.AdminMiddleware).
//
// Note this costs one primary-key SELECT per authenticated request. That is
// the price of revocation: without loading the row there is no version to
// compare against, and logout could not kill a live access token.
func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*models.User, *jwt.MapClaims, error) {
claims, err := auth.VerifyJWT(tokenStr)
if err != nil {
return nil, nil, ErrInvalidToken
}
// Claims are decoded by encoding/json, so every number arrives as a
// float64 regardless of the Go type it was signed from.
userIDF, ok := (*claims)["id"].(float64)
if !ok {
return nil, nil, ErrInvalidClaims
}
// Pre-setting the primary key and calling First with no explicit
// condition makes GORM look the row up by that key. Soft-deleted users
// are excluded automatically, so a deleted account fails here.
user := models.User{ID: uint(userIDF)}
if err := db.First(&user).Error; err != nil {
return nil, nil, ErrUserNotFound
}
// A token with no "tv" claim reads as 0 and is normalised to 1, matching
// an un-bumped user — see tokenVersionOf.
claimedVersion, _ := (*claims)["tv"].(float64)
if tokenVersionOf(uint(claimedVersion)) != tokenVersionOf(user.TokenVersion) {
return nil, nil, ErrTokenRevoked
}
return &user, claims, nil
}
// BumpTokenVersion invalidates every token previously issued to userID by
// incrementing the user's version counter. Callers treat a failure as
// non-fatal (logout still clears the cookies), but it must be logged: a
// silent failure here means a logout that did not actually revoke anything.
//
// COALESCE covers a pre-migration row sitting at 0 or NULL: it is treated as
// 1, so the bump lands on 2 and invalidates tokens claiming either.
func BumpTokenVersion(db *gorm.DB, userID uint) error {
return db.Model(&models.User{}).
Where("id = ?", userID).
UpdateColumn("token_version", gorm.Expr("COALESCE(token_version, 1) + 1")).
Error
}
// SetAuthCookies writes the access/refresh cookie pair.
//
// It lives in services because both handlers and graph need it and handlers
// cannot import graph (that would be an import cycle); keeping one copy is
// what stops REST login and GraphQL login drifting apart.
//
// 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 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.
func SetAuthCookies(gc *gin.Context, config *AuthConfig, tokens *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,
)
}
// ClearAuthCookies 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.
func ClearAuthCookies(gc *gin.Context, config *AuthConfig) {
gc.SetSameSite(http.SameSiteLaxMode)
gc.SetCookie("access_token", "", -1, "/", config.Domain, true, true)
gc.SetCookie("refresh_token", "", -1, "/", config.Domain, true, true)
}