Trim comments to the non-obvious why
Test and deploy / test (push) Successful in 28s
Test and deploy / deploy (push) Successful in 31s

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]>
This commit is contained in:
2026-11-24 20:49:03 +00:00
co-authored by Claude Opus 5.5
parent effddd2794
commit 4530cb8dc4
222 changed files with 1173 additions and 5423 deletions
+36 -122
View File
@@ -11,20 +11,13 @@ import (
"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 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.
// Auth mints and verifies HS256 JWTs. Revocation is by User.TokenVersion:
// every token carries it as "tv", and bumping it kills them all.
type Auth struct {
Config *AuthConfig
}
// AuthConfig carries the signing secret and cookie/token lifetimes. Domain is
// the cookie domain; Endpoint is the backend's public base URL.
// Domain is the cookie domain; Endpoint is the backend's public base URL.
type AuthConfig struct {
Secret []byte
Domain string
@@ -33,16 +26,13 @@ type AuthConfig struct {
Endpoint string
}
// Tokens is a freshly minted access/refresh token pair, both already signed.
type Tokens struct {
AccessToken string
RefreshToken string
}
// InitAuth builds the Auth service from config. An absent or too-short
// secret is fatal: HS256 happily signs and verifies with a zero-length key,
// so starting up with an empty BACKEND_SECRET would let anyone forge admin
// tokens. Fail loudly at boot rather than serving a forgeable auth system.
// InitAuth panics on a short secret: HS256 accepts a zero-length key, which
// would make admin tokens forgeable.
func InitAuth(config *AuthConfig) *Auth {
if len(config.Secret) < 32 {
panic("auth secret must be set and at least 32 bytes (check BACKEND_SECRET)")
@@ -51,18 +41,8 @@ func InitAuth(config *AuthConfig) *Auth {
return &Auth{Config: config}
}
// GenerateJWT issues an access/refresh pair for user.
//
// 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 (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.
// GenerateJWT issues an access/refresh pair. Only the access token carries
// admin; refresh re-reads the row, so a revoked admin flag applies then.
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username,
@@ -91,20 +71,13 @@ func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
return &Tokens{AccessToken: accessTokenString, RefreshToken: refreshTokenString}, nil
}
// keyFunc supplies the HMAC secret to the JWT parser. The token argument is
// ignored because only one key is ever in use; VerifyJWT separately pins the
// algorithm, which is what actually prevents the "alg: none"/algorithm
// confusion attack.
// The key is fixed; VerifyJWT pins the algorithm, which is what stops
// algorithm-confusion attacks.
func (auth *Auth) keyFunc(_ *jwt.Token) (any, error) {
return auth.Config.Secret, nil
}
// VerifyJWT parses and validates a signed token, returning its claims.
// Expiry is checked by the jwt library. Note the *jwt.MapClaims return: a
// pointer to a map is unusual, but every caller in this codebase expects it,
// so the type is part of the internal contract. Numeric claims come back as
// float64 because that is what encoding/json produces, hence the
// `(*claims)["id"].(float64)` conversions at the call sites.
// VerifyJWT returns the claims. Numbers decode as float64.
func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
token, err := jwt.Parse(tokenStr, auth.keyFunc, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
if err != nil {
@@ -119,31 +92,16 @@ 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).
// Distinct so REST and GraphQL can each map them to their own status codes.
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.
ErrInvalidToken = errors.New("invalid token")
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")
ErrUserNotFound = errors.New("user not found")
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.
// tokenVersionOf treats 0 (old rows, tokens without "tv") as 1, the column
// default, so introducing versioning logged nobody out.
func tokenVersionOf(v uint) uint {
if v == 0 {
return 1
@@ -151,51 +109,32 @@ func tokenVersionOf(v uint) uint {
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.tryRefreshAndValidate 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.
// AuthenticateToken turns a token into a user, checking signature, expiry,
// the user row and the token version. Errors are always the sentinels above.
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.
// AuthenticateTokenWithClaims also returns the claims, for "admin". It costs
// one SELECT per request, which is the price of revocation.
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.
// Soft-deleted users are excluded, 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
@@ -204,13 +143,8 @@ func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*mo
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.
// BumpTokenVersion revokes all of userID's tokens. COALESCE treats a NULL
// version as 1.
func BumpTokenVersion(db *gorm.DB, userID uint) error {
return db.Model(&models.User{}).
Where("id = ?", userID).
@@ -218,43 +152,23 @@ func BumpTokenVersion(db *gorm.DB, userID uint) error {
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.
const (
secure = true
httpOnly = true
)
// SetAuthCookies lives in services so REST and GraphQL share one copy.
// SameSite=Lax survives the redirect back from an OAuth provider.
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,
)
gc.SetCookie("access_token", tokens.AccessToken, int(config.AccessTokenLifetime.Seconds()), "/", config.Domain, secure, httpOnly)
gc.SetCookie("refresh_token", tokens.RefreshToken, int(config.RefreshTokenLifetime.Seconds()), "/", config.Domain, secure, httpOnly)
}
// 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.
// ClearAuthCookies must match SetAuthCookies' attributes, 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)
gc.SetCookie("access_token", "", -1, "/", config.Domain, secure, httpOnly)
gc.SetCookie("refresh_token", "", -1, "/", config.Domain, secure, httpOnly)
}
+4 -20
View File
@@ -10,20 +10,8 @@ import (
"github.com/gin-gonic/gin"
)
// Companion to auth_test.go, covering the two pure things it leaves out: the
// expiry the minting code bakes into each token, and the cookie attributes
// SetAuthCookies/ClearAuthCookies emit.
//
// DELIBERATELY NOT COVERED HERE:
// - AuthenticateToken past the id claim, and BumpTokenVersion: both need a
// live *gorm.DB and the only driver in go.mod is postgres.
// - Everything auth_test.go already covers (tokenVersionOf, the claim split,
// the VerifyJWT rejection table) — not duplicated.
// - Password hashing: there is none in this package; handlers own it.
//
// Cookie assertions go through a real gin context because gin, not this
// package, is what turns the SetCookie arguments into a header — asserting on
// the arguments alone would test nothing.
// Token expiry and cookie attributes. Cookies are checked through a real gin
// context, since gin builds the header.
// cookiesFrom runs fn against a throwaway gin context and returns what it set,
// keyed by cookie name.
@@ -40,9 +28,7 @@ func cookiesFrom(fn func(*gin.Context)) map[string]*http.Cookie {
return out
}
// exp must track the configured lifetime, because the cookie max-age is derived
// from the same number: if they disagreed the browser would hold a dead cookie
// or drop a live one.
// Cookie max-age is derived from the same lifetime.
func TestGenerateJWTExpiryMatchesConfiguredLifetime(t *testing.T) {
auth := testAuth()
issued := time.Now()
@@ -124,9 +110,7 @@ func TestSetAuthCookies(t *testing.T) {
}
}
// A browser only replaces a cookie when path, domain and flags match the
// original, so a deletion that differs in any of them silently leaves the user
// logged in. Hence asserting the attributes, not just the negative max-age.
// A deletion that differs in path, domain or flags silently fails.
func TestClearAuthCookiesMatchesTheCookiesItDeletes(t *testing.T) {
config := testAuth().Config
set := cookiesFrom(func(gc *gin.Context) {
+3 -15
View File
@@ -9,12 +9,8 @@ import (
"github.com/golang-jwt/jwt/v5"
)
// The tests below deliberately stop short of AuthenticateToken's happy path:
// that branch needs a live *gorm.DB and the only driver in go.mod is postgres,
// so exercising it would mean a database in CI. Everything that runs before the
// row lookup (parsing, signature, claim extraction) is covered here, and the
// revocation rule itself is covered through tokenVersionOf, which is the whole
// of the comparison AuthenticateTokenWithClaims performs.
// Stops short of the row lookup (no DB in CI); revocation is covered via
// tokenVersionOf.
func testAuth() *Auth {
return InitAuth(&AuthConfig{
@@ -47,9 +43,6 @@ func TestTokenVersionOf(t *testing.T) {
}
}
// The comparison AuthenticateTokenWithClaims makes is tokenVersionOf(claim) vs
// tokenVersionOf(row). The table therefore encodes the revocation contract: an
// absent claim (0) must still match an un-bumped user, and any bump must not.
func TestTokenVersionMatch(t *testing.T) {
cases := []struct {
name string
@@ -104,9 +97,6 @@ func TestGenerateJWTTokenVersionClaim(t *testing.T) {
}
}
// The split of claims is load-bearing: admin lives in the access token so most
// requests need no row, and is absent from the refresh token so that revoking
// admin takes effect on the next refresh.
func TestGenerateJWTClaimSplit(t *testing.T) {
auth := testAuth()
tokens, err := auth.GenerateJWT(&models.User{ID: 7, Username: "adam", Admin: true, TokenVersion: 1})
@@ -191,9 +181,7 @@ func TestVerifyJWTRejections(t *testing.T) {
}
}
// A verified token with no usable id is a server-side inconsistency, not a
// client error, so it gets its own sentinel. Both cases below return before the
// row lookup, which is why a nil *gorm.DB is safe here.
// Both return before the row lookup, so a nil DB is safe.
func TestAuthenticateTokenInvalidClaims(t *testing.T) {
auth := testAuth()
cases := []struct {
+4 -14
View File
@@ -18,9 +18,7 @@ type SQLConfig struct {
Port string
}
// connectToPostgreSQL opens the GORM connection. sslmode=disable is safe
// only because Postgres is reachable exclusively on the private Docker
// network, never over the internet.
// sslmode=disable: Postgres is only on the Docker network.
func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
dsn := fmt.Sprintf(
"user=%s password=%s dbname=%s host=%s port=%s sslmode=disable",
@@ -35,12 +33,8 @@ func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
return db, nil
}
// migrateDatabase brings the schema up to date. This project has no
// migration files: GORM's AutoMigrate is the only schema source, so it will
// add tables, columns and indexes but never drop or rename anything. Removing
// a field from a model therefore leaves the column behind, and a renamed
// field appears as a brand-new column with no data. Any model added to
// models.go must also be listed here or its table will never be created.
// AutoMigrate never drops or renames, so removed fields leave columns and
// renamed ones start empty. New models must be listed here.
func migrateDatabase(db *gorm.DB) error {
err := db.AutoMigrate(
&models.User{},
@@ -66,11 +60,7 @@ func migrateDatabase(db *gorm.DB) error {
return ensureStpPage(db)
}
// ensureStpPage turns the home page (/stp) into an ordinary canvas Page once.
// It used to be a built-in canvas with its own route; its boxes and
// background were already keyed "stp", so a Page row with that slug is all
// it takes. Unscoped, so that deleting the page on purpose sticks rather than
// bringing it back on the next start.
// ensureStpPage creates the /stp Page row once. Unscoped, so deleting it sticks.
func ensureStpPage(db *gorm.DB) error {
var count int64
if err := db.Unscoped().Model(&models.Page{}).Where("slug = ?", "stp").Count(&count).Error; err != nil {
+7 -23
View File
@@ -8,35 +8,27 @@ import (
"time"
)
// This file talks to the self-hosted Gitea instance over the private Docker
// network to surface "what did Adam push most recently" on the home page.
// The response is cached by the caller (handlers.Store, 1 minute TTL).
// The latest Gitea push, for the home page.
// GiteaFeedCommit is one commit inside a push event's Content payload.
// The capitalised JSON keys are Gitea's, not a typo.
// Gitea's own capitalised keys.
type GiteaFeedCommit struct {
Message string `json:"Message"`
}
// GiteaFeedContent is the shape of the JSON *string* stored in
// GiteaFeedResponse.Content for push events; see ParseCommitMessage.
// Push events' Content is this, as a JSON string; see ParseCommitMessage.
type GiteaFeedContent struct {
Commits []GiteaFeedCommit `json:"Commits"`
}
// GiteaFeedUser is the acting user on a feed entry.
type GiteaFeedUser struct {
AvatarURL string `json:"avatar_url"`
}
// GiteaFeedRepo is the repository a feed entry belongs to.
type GiteaFeedRepo struct {
FullName string `json:"full_name"`
HTMLURL string `json:"html_url"`
}
// GiteaFeedResponse is a single Gitea activity feed entry. Only the fields
// the front end renders are declared; the rest of the payload is discarded.
type GiteaFeedResponse struct {
ActUser GiteaFeedUser `json:"act_user"`
Repo GiteaFeedRepo `json:"repo"`
@@ -45,13 +37,8 @@ type GiteaFeedResponse struct {
Created time.Time `json:"created"`
}
// FetchLatestFeed returns the single most recent public activity entry for
// user "adamf", or (nil, nil) when the feed is empty — callers must handle
// that nil-without-error case.
//
// The username is hard-coded and the call is plain HTTP with no token: this
// only ever reaches the Gitea container over the internal Docker network,
// where the public feed needs no authentication.
// FetchLatestFeed returns (nil, nil) for an empty feed. Unauthenticated: the
// public feed needs no token.
func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) {
url := fmt.Sprintf("http://%s:%s/api/v1/users/adamf/activities/feeds?limit=1", host, port)
@@ -79,11 +66,8 @@ func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) {
return &items[0], nil
}
// ParseCommitMessage pulls the first commit message out of a feed entry's
// Content field, which Gitea delivers as JSON encoded inside a JSON string
// (so it needs a second Unmarshal). Non-push events have Content in a
// different shape entirely, so any parse failure is intentionally swallowed
// and reported as "no commit message".
// ParseCommitMessage decodes JSON-in-a-string. Non-push events don't parse,
// which yields "".
func ParseCommitMessage(content string) string {
var c GiteaFeedContent
if err := json.Unmarshal([]byte(content), &c); err != nil {
+2 -7
View File
@@ -26,13 +26,8 @@ func InitNotes(config *NotesConfig) *Notes {
}
}
// ParsePath resolves a user-supplied request path to an absolute path inside
// the notes directory, or returns an error if it would escape.
//
// The traversal guard is the prefix check at the end. filepath.Join already
// cleans "..", but the separator is appended to baseDir before comparing so
// that a sibling directory whose name merely starts with the same characters
// (e.g. /backend/notes-private next to /backend/notes) cannot pass the check.
// ParsePath appends the separator before the prefix check, so a sibling such
// as /backend/notes-private can't pass.
func (notes *Notes) ParsePath(path string) (string, error) {
// The route is /notes/*path, so a bare /notes/ arrives as "" or "/";
// treat both as a request for the wiki index.
+5 -21
View File
@@ -6,44 +6,28 @@ import (
"adam-french.co.uk/backend/models"
)
// Per-service permissions: how a non-admin account is let into one gated
// service (the receipt printer, say) without being made an admin.
//
// A permission is a key from PermissionTypes stored in models.User.Permissions.
// Caddy gates a service on one key by asking GET /auth/validate/<key>
// (handlers.Store.ValidatePermission); admins pass every such check, so
// moving a service from the admin gate to a permission gate never locks an
// admin out. Services that are not listed here stay admin-only.
//
// Adding a grantable service is one entry below plus swapping its route in
// caddy/routes.caddy from `import admin_gate` to `import permission_gate
// <key>` (the snippet is in caddy/Caddyfile).
// Grantable per-service permissions for non-admins; admins pass every check.
// To add one: an entry below, then `import permission_gate <key>` on its
// route in caddy/routes.caddy.
// PermissionType describes one grantable service. Key is what is stored and
// what Caddy names; Label and Path are for the admin panel's checkboxes and
// the signed-in user's /account list of links.
type PermissionType struct {
Key string
Label string
Path string
}
// PermissionTypes is the full set of grantable permissions, in display order.
// Removing an entry leaves the key in users' rows, where it is inert: the
// validate endpoint 404s an unknown key, so nothing can be gated on it.
// Removed keys are inert: the validate endpoint 404s them.
var PermissionTypes = []PermissionType{
{Key: "receipt", Label: "Receipt printer", Path: "/receipt/"},
}
// ValidPermission reports whether key names a permission in PermissionTypes.
func ValidPermission(key string) bool {
return slices.ContainsFunc(PermissionTypes, func(p PermissionType) bool {
return p.Key == key
})
}
// HasPermission reports whether user may use the service gated on key. It
// reads the row, not a token, so Admin here is the current database value.
// HasPermission reads the row, not the token.
func HasPermission(user *models.User, key string) bool {
return user.Admin || slices.Contains(user.Permissions, key)
}
+11 -40
View File
@@ -10,49 +10,25 @@ import (
"time"
)
// Every Claude call the site makes lives in the Python service, behind an
// /internal/ route. This file is the one way the Go backend reaches those
// routes. The only caller now is the rowing photo reader
// (handlers/handle_rowing.go); the job posting reader, email classifier and
// lead scorer went with the job tracker to its own repo.
//
// The routes are internal in a specific sense: Caddy answers 404 for
// /py/internal/, and each route itself refuses a request carrying a proxy
// header, so the only way in is this direct container-to-container call. That
// is why the request below sets nothing but Content-Type.
// CallPython is how the backend reaches the Python service's /internal/
// routes, container to container (Caddy refuses them, and they refuse
// proxied requests).
// pythonClient bounds the wait on the Python service. Two minutes sits above
// that side's own worst case (a 30s Claude timeout, retried twice with
// backoff), so a slow Claude surfaces as Python's error rather than as a
// timeout here. One client for every route, so they share a connection pool.
// Above Python's own worst case (30s Claude timeout, two retries), so a slow
// Claude surfaces as Python's error.
var pythonClient = &http.Client{Timeout: 2 * time.Minute}
// PythonError is a failure the Python service reported in words that are safe
// and useful to show a person: the string `detail` of a 502, which is always
// one of that route's own fixed messages ("failed to parse image data", ...).
//
// Everything else — a refused connection, a 422, a 503 for a missing API key,
// a reply that will not decode — comes back as an ordinary error instead. The
// distinction is the point: a caller relays a PythonError and only logs the
// rest, because the rest describe plumbing the user can do nothing about and
// may quote internals.
// PythonError is the `detail` of a 502: one of the route's fixed messages,
// safe to show a user. Every other failure is a plain error, for the log only.
type PythonError struct{ Detail string }
func (e *PythonError) Error() string { return e.Detail }
// CallPython POSTs body as JSON to baseURL+path and decodes a 200 reply into
// T. baseURL is the service's address on the Docker network with no trailing
// slash (handlers.Store.PythonURL); path is the route, starting with a slash.
//
// Any non-200 is an error. See PythonError for which ones are relayable. A
// cancelled ctx is wrapped, not replaced, so errors.Is(err, context.Canceled)
// still holds.
// CallPython POSTs body as JSON and decodes a 200 into T; anything else is an
// error. baseURL has no trailing slash.
func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T, error) {
var out T
// Note for callers sending bytes: encoding/json writes a []byte as
// standard base64, which is the form the Anthropic API wants and so what
// the Python side passes straight through.
payload, err := json.Marshal(body)
if err != nil {
return out, fmt.Errorf("encoding request for %s: %w", path, err)
@@ -71,12 +47,8 @@ func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T,
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
// FastAPI errors are {"detail": ...}. Only a 502 carries one of the
// route's own fixed messages; a 422's detail is a list, which fails
// to decode into the string and falls through to the generic error,
// and a 503's detail names an environment variable, which is for the
// log rather than the page. The body is capped because it is only
// ever quoted in a log line.
// Only a 502's detail is user-facing: a 422's is a list (fails to
// decode) and a 503's names an env var.
var failure struct {
Detail string `json:"detail"`
}
@@ -88,7 +60,6 @@ func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T,
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
// A fresh zero value, so a half-decoded T never escapes with an error.
var zero T
return zero, fmt.Errorf("decoding %s response: %w", path, err)
}
+6 -23
View File
@@ -1,7 +1,5 @@
// Package services holds the backend's stateful collaborators: the database
// handle, JWT signing, the chat WebSocket hub, third-party API clients
// (Spotify, Steam, Gitea, Claude) and the email-sync pipeline. Handlers and
// GraphQL resolvers reach them through handlers.Store.
// Package services holds the backend's stateful collaborators, reached
// through handlers.Store.
package services
import (
@@ -9,24 +7,15 @@ import (
"time"
)
// RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary
// string (in practice the client IP). It is process-local: restarting the
// backend clears every window, and a multi-replica deployment would limit
// per replica rather than globally. Caddy applies its own rate limits in
// front of this, so this layer is a second line of defence, not the only one.
// RateLimiter is an in-memory sliding window per key, behind Caddy's limits.
type RateLimiter struct {
mu sync.Mutex
// attempts holds the timestamps of recent allowed attempts per key.
// Keys are never evicted, so memory grows with the number of distinct
// client IPs seen since start-up; acceptable for a personal site, but
// worth knowing before reusing this elsewhere.
// Never evicted; grows with distinct client IPs.
attempts map[string][]time.Time
max int
window time.Duration
}
// NewRateLimiter returns a limiter allowing at most max calls to Allow per
// key within any window-length period.
func NewRateLimiter(max int, window time.Duration) *RateLimiter {
return &RateLimiter{
attempts: make(map[string][]time.Time),
@@ -35,9 +24,7 @@ func NewRateLimiter(max int, window time.Duration) *RateLimiter {
}
}
// Allow records an attempt for key and reports whether it is within the
// limit. A rejected attempt is deliberately NOT recorded, so a caller that
// keeps hammering does not extend its own lockout indefinitely.
// Allow doesn't record rejected attempts, so hammering doesn't extend a lockout.
func (rl *RateLimiter) Allow(key string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
@@ -45,11 +32,7 @@ func (rl *RateLimiter) Allow(key string) bool {
now := time.Now()
cutoff := now.Add(-rl.window)
// Filter in place: slicing to [:0] reuses the existing backing array, so
// the append below overwrites the old timestamps instead of allocating a
// new slice on every request. Safe here because we only ever write an
// element at an index we have already read past. A missing key yields a
// nil slice, and nil[:0] is legal and yields nil.
// Filtered in place, reusing the backing array.
valid := rl.attempts[key][:0]
for _, t := range rl.attempts[key] {
if t.After(cutoff) {
+1 -4
View File
@@ -9,10 +9,7 @@ import (
"gorm.io/gorm"
)
// SeedDatabase populates an empty database with demo content for local
// development. It is called from main only when SEED_DB=true, which
// docker-compose.dev.yml sets; it must never run in production because it
// creates an admin account with the password "password".
// SeedDatabase is dev only: it creates an admin with password "password".
func SeedDatabase(db *gorm.DB) {
// "Any user exists" is the whole idempotency check — if the users table
// has a row, nothing is seeded, even if the other tables were emptied.
+1 -12
View File
@@ -8,18 +8,7 @@ import (
"time"
)
// Covered here: the pure logic in ratelimit.go, notes.go and gitea.go —
// sliding-window arithmetic, the path-traversal guard, and the two-stage JSON
// decoding of a Gitea feed entry (from a hand-written fixture).
//
// Deliberately not covered:
// - FetchLatestFeed: it is an HTTP call to the Gitea container. Its only
// logic beyond the request is the empty-feed nil,nil case, and testing it
// would mean either a network or an injected client that does not exist.
// - The 1-minute Gitea cache TTL: it lives in handlers.Store, not here.
// - RateLimiter's window expiry uses the real clock (Allow calls time.Now
// directly and there is no injectable clock), so the expiry case below
// uses a deliberately tiny window rather than a long sleep.
// Expiry uses the real clock, hence the tiny window.
func TestRateLimiterAllow(t *testing.T) {
t.Run("calls up to max are allowed", func(t *testing.T) {
+8 -39
View File
@@ -13,26 +13,17 @@ import (
"golang.org/x/oauth2"
)
// SpotifyConfig holds the OAuth app credentials.
//
// There is no state value here any more: the `state` parameter is a one-shot
// CSRF nonce minted per authorisation request by handlers.Store, so a fixed
// configured value would defeat the point.
type SpotifyConfig struct {
RedirectURL string
ClientID string
ClientSecret string
}
// SPOTIFY_TOKEN_JSON_PATH is inside a Docker volume, so the refresh token
// survives container restarts and the OAuth dance only has to be done once.
// On a mounted volume, so the OAuth dance survives rebuilds.
const SPOTIFY_TOKEN_JSON_PATH = "/backend/token/spotify_token.json"
// SaveSpotifyToken persists an OAuth token to disk.
//
// It copies the fields into a local anonymous struct rather than marshalling
// oauth2.Token directly, so the on-disk format stays stable regardless of what
// the oauth2 package adds to its own struct or its JSON tags.
// SaveSpotifyToken writes its own struct so the file format doesn't follow
// oauth2.Token's.
func SaveSpotifyToken(path string, tok *oauth2.Token) error {
data := struct {
AccessToken string `json:"access_token"`
@@ -55,13 +46,9 @@ func SaveSpotifyToken(path string, tok *oauth2.Token) error {
return err
}
// 0600 ensures only your user can read/write the file
return os.WriteFile(path, jsonBytes, 0600)
}
// LoadSpotifyToken reads a token previously written by SaveSpotifyToken.
// A missing file returns an error, which callers treat as "not yet
// authenticated" rather than a fault.
func LoadSpotifyToken(path string) (*oauth2.Token, error) {
data, err := os.ReadFile(path)
if err != nil {
@@ -89,16 +76,8 @@ func LoadSpotifyToken(path string) (*oauth2.Token, error) {
return tok, nil
}
// InitSpotifyAuth builds the OAuth authenticator and, if a saved token
// exists, an authenticated client.
//
// Start-up never fails on Spotify problems: when there is no token or the
// refresh is rejected it logs how to authenticate and returns a nil client.
// Every Spotify handler and resolver therefore has to nil-check
// Store.SpotifyClient. The authorisation URL can no longer be printed here
// because its state nonce is per-request (see handlers.Store.StartSpotifyAuth);
// following it sends the browser to /spotify/callback, which fills the client
// in at runtime.
// InitSpotifyAuth never fails startup: with no usable token it returns a nil
// client, so every caller must nil-check Store.SpotifyClient.
func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotify.Client) {
auth := spotifyauth.New(
spotifyauth.WithRedirectURL(config.RedirectURL),
@@ -111,14 +90,12 @@ func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotif
),
)
// check if token exists locally
token, err := LoadSpotifyToken(SPOTIFY_TOKEN_JSON_PATH)
if err != nil || token == nil {
fmt.Println("No Spotify token saved. Authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.")
return auth, nil
}
// refresh token and client
client, err := RefreshClient(auth, token)
if err != nil {
fmt.Println("Failed to refresh Spotify token. Re-authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.")
@@ -128,18 +105,10 @@ func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotif
return auth, client
}
// RefreshClient exchanges a stored token for a fresh one and returns a client
// using it.
//
// Spotify may issue a new refresh token during this exchange, so the result is
// written straight back to disk; the write error is ignored because a failed
// save only costs a re-authentication later, and failing the whole start-up
// over it would be worse. The returned client also holds the token source
// internally and keeps refreshing on its own — but those later refreshes are
// NOT persisted, so after a long uptime the file on disk can be stale.
// RefreshClient saves the new token, ignoring write errors. The client's
// later automatic refreshes are not persisted.
func RefreshClient(auth *spotifyauth.Authenticator, token *oauth2.Token) (*spotify.Client, error) {
// context.Background rather than a request context: the resulting client
// is long-lived and must outlive whichever request triggered this.
// The client outlives the request that created it.
ctx := context.Background()
token, err := auth.RefreshToken(ctx, token)
+3 -13
View File
@@ -8,10 +8,6 @@ import (
"time"
)
// This file wraps the two public Steam Web API endpoints used by the home
// page. Results are cached by the caller (handlers.Store, 5 minute TTL) to
// stay well inside Steam's rate limits.
// SteamRecentGame is one game from GetRecentlyPlayedGames. Playtimes are in
// minutes.
type SteamRecentGame struct {
@@ -30,10 +26,7 @@ type SteamRecentGamesResponse struct {
} `json:"response"`
}
// SteamPlayerSummary is the subset of GetPlayerSummaries we care about.
// PersonaState is Steam's online status enum: 0 = offline, anything higher
// is some flavour of online (online, busy, away, snooze, looking to trade or
// play), which is why the caller treats "> 0" as online.
// PersonaState > 0 is some kind of online.
type SteamPlayerSummary struct {
PersonaState int `json:"personastate"`
}
@@ -45,11 +38,8 @@ type SteamPlayerSummariesResponse struct {
} `json:"response"`
}
// FetchRecentlyPlayedGames returns the three most recently played games.
//
// Steam answers with HTTP 200 and an empty envelope for a private profile or
// a bad key, so an empty slice and no error is the normal "nothing to show"
// result rather than a failure.
// Steam answers 200 with nothing for a private profile or bad key, so empty
// is not an error.
func FetchRecentlyPlayedGames(apiKey, steamID string) ([]SteamRecentGame, error) {
url := fmt.Sprintf("https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v1/?key=%s&steamid=%s&count=3", apiKey, steamID)
+5 -36
View File
@@ -7,42 +7,21 @@ import (
"github.com/gin-gonic/gin"
)
// This file replaces gin.Logger with a formatter tuned for one reader: the
// site owner scanning the log for "who is using my site". Two goals:
//
// 1. Quietness. The log is flooded by traffic that is not a human visit:
// Caddy forward_auth subrequests (/auth/validate-admin, re-run for every
// admin page hit), the front end's own polling (`/auth/refresh_token`,
// home-data refreshes), and Vite dev asset fetches. Each is collapsed to
// a single terse line, or dropped entirely when repeated in a short
// window — a 200 on a poll says nothing worth a line each time.
//
// 2. Salience. A request that matters (an external IP, an error status, a
// slow response) gets a line that stands out and carries the pieces that
// answer "who": client IP, path, status, latency.
// TrafficLogFormatter replaces gin.Logger: heartbeat and forward_auth traffic
// is dropped or terse, while external IPs, errors and slow requests stand out.
// logQuietDrop lists paths whose 2xx responses are dropped outright. These
// are all heartbeat-style endpoints: identical every few seconds, no signal.
var logQuietDrop = map[string]bool{
"/auth/validate-admin": true, // Caddy forward_auth subrequest
"/auth/refresh": true, // front-end token refresh
"/auth/check": true, // front-end session check
}
// logQuietDropPrefix is the permission gate's auth_request subrequest
// (/auth/validate/<key>), dropped on 2xx for the same reason as
// /auth/validate-admin above: it repeats on every request to a gated page.
// The permission gate's subrequests, as for /auth/validate-admin.
const logQuietDropPrefix = "/auth/validate/"
// TrafficLogFormatter renders gin's log line. Signed to gin's LogFormatter
// signature so it plugs into gin.LoggerWithFormatter.
func TrafficLogFormatter(params gin.LogFormatterParams) string {
// gin hands the full URL (path + query) in Path; Query is split off
// params.ErrorMessage... not needed — just use Path which carries both.
path := params.Path
// Latency is human-scaled rather than raw nanoseconds: "1.2ms" scans
// faster than "1230689ns" when you are skimming.
latency := params.Latency
unit := "ns"
switch {
@@ -56,8 +35,6 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
unit, latency = "µs", latency/time.Microsecond
}
// Errors (>=500) are marked so they survive even a fast scroll; the
// literal marker also makes them greppable in a rotated log.
marker := ""
if params.StatusCode >= 500 {
marker = " !!! SERVER ERROR"
@@ -65,9 +42,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
marker = " !!"
}
// All-quiet: drop heartbeat endpoints that succeeded. A 4xx/5xx on them
// is still interesting (an expired session raging against refresh, a
// broken admin gate) and is kept.
// Failures on these are still worth seeing.
if (logQuietDrop[path] || startsWith(path, logQuietDropPrefix)) && params.StatusCode < 400 {
return ""
}
@@ -75,9 +50,6 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
line := fmt.Sprintf("%s %s %d %s%s", params.Method, path, params.StatusCode,
fmt.Sprintf("%.0f%s", float64(latency), unit), marker)
// Visitor traffic gets the IP appended — the "who". Infrastructure
// traffic (the edge's own feet on the internal subnet) already has its IP
// implied and is left lean.
if params.StatusCode >= 400 || logIsInterestingClient(params.ClientIP) {
line += " " + params.ClientIP
}
@@ -85,11 +57,8 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
return line + "\n"
}
// logIsInterestingClient reports whether a client IP is likely an actual
// visitor rather than infrastructure. Caddy proxies everything, so the IPs
// that appear are either forwarded-from-humans or the ingress itself.
func logIsInterestingClient(ip string) bool {
// Docker's bridge network: the edge's own feet. Not a visitor.
// The Docker bridge: infrastructure, not a visitor.
return !startsWith(ip, "172.28.")
}
+28 -100
View File
@@ -22,51 +22,25 @@ import (
"github.com/aws/aws-sdk-go-v2/service/s3"
)
// Uploaded files: everything the site stores from a user and serves back at
// /uploads/. One entry point for any handler that takes a file:
//
// url, err := store.Uploads.Save(ctx, fileHeader, private)
//
// Save validates the file against UploadTypes and MaxUploadSize, gives it a
// random name, stores it, and returns the URL to put in the page. An
// *UploadError is the uploader's fault and its message is safe to show them;
// any other error is ours (log it, answer 500).
//
// WHERE FILES GO
// Public files go to the Garage bucket `uploads` (garage/garage.toml), with
// the `uploads` volume as a fallback for when Garage refuses a write. Caddy
// mirrors that: /uploads/<name> is fetched from the bucket first and the
// volume second (caddy/routes.caddy), so the URL is the same wherever the
// file landed. With S3_ENDPOINT unset there is no bucket and the volume is
// the only store.
// Private files (admin-only chat attachments) always go to the volume, under
// /uploads/private/, which Caddy gates behind an admin check. Caddy can't
// sign S3 requests, so it has no way to gate a bucket.
//
// Everything public is reachable by anyone who has the URL, with no login.
// That is why the type checks below are strict, and why names are random.
// Every stored file goes through Uploads.Save. An *UploadError is the
// uploader's fault and safe to show; any other error is ours.
// Public files go to Garage, falling back to the volume; private files
// always go to the volume, because Caddy can gate a path but can't sign S3.
// MaxUploadSize caps one upload. It bounds how fast one account can fill the
// disk or the bucket; Caddy rate-limits the route as well.
const MaxUploadSize = 10 << 20 // 10MB
// UploadType describes one allowed file extension.
type UploadType struct {
// ContentType is stored with the file and served back with it. Garage
// returns exactly this, and the browser renders by it: Caddy adds
// `nosniff`, so a wrong type means the file doesn't display.
// Served back as-is, and Caddy sends nosniff, so it must be right.
ContentType string
// SniffPrefix is what http.DetectContentType must report for the file's
// first 512 bytes, so that e.g. HTML can't be uploaded as a .png. Empty
// means "not checked": DetectContentType is too unreliable for audio and
// gif files, and checking would reject legitimate ones.
// What http.DetectContentType must report. Empty skips the check, which
// is unreliable for audio and gif.
SniffPrefix string
}
// UploadTypes is the allow-list, keyed by lower-cased extension with its dot.
// Nothing a browser would execute or render as markup (.html, .svg, .js, ...)
// may ever be added: these files are served from our own origin. The
// frontend's file pickers (vue/src/uploads.js, ACCEPT) list the same types.
// UploadTypes is the allow-list. Never add anything a browser would execute
// or render as markup: these are served from our origin. Mirrored by
// vue/src/uploads.js's ACCEPT.
var UploadTypes = map[string]UploadType{
".jpg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
".jpeg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
@@ -81,8 +55,6 @@ var UploadTypes = map[string]UploadType{
".txt": {ContentType: "text/plain; charset=utf-8", SniffPrefix: "text/"},
}
// UploadError is a rejected upload: the uploader's mistake, with a message
// meant for them. The handler answers 400 with it.
type UploadError struct{ Message string }
func (e *UploadError) Error() string { return e.Message }
@@ -94,26 +66,17 @@ var (
ErrUploadUnreadable = &UploadError{"failed to read file content"}
)
// Uploads stores files. Build it with NewUploads.
type Uploads struct {
public FileStore
private FileStore
}
// URL prefixes the files are served under; Caddy owns both paths.
const (
publicURLPrefix = "/uploads/"
privateURLPrefix = "/uploads/private/"
)
// NewUploads picks the stores. publicDir and privateDir are directories on the
// shared `uploads` volume (/backend/uploads/ and its private/ subdirectory in
// the container).
//
// With no S3 endpoint the public store is the volume alone, the behaviour
// before Garage. An endpoint with missing credentials is a configuration
// mistake: it is logged and the volume is used rather than failing every
// upload.
// NewUploads falls back to the volume alone when S3 is unset or misconfigured.
func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
disk := DiskFileStore{Dir: publicDir}
u := &Uploads{public: disk, private: DiskFileStore{Dir: privateDir}}
@@ -130,9 +93,7 @@ func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
return u
}
// Save validates and stores one uploaded file and returns its URL
// (/uploads/<name>, or /uploads/private/<name>). Authorisation is the
// caller's job: only an admin may save a private file.
// Save stores one file and returns its URL. Only admins may save private files.
func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bool) (string, error) {
if fh.Size > MaxUploadSize {
return "", ErrUploadTooLarge
@@ -150,8 +111,7 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
defer f.Close()
if kind.SniffPrefix != "" {
// 512 bytes is all http.DetectContentType looks at. A short read is
// fine; sniffing works on a prefix, so only an empty file is an error.
// A short read is fine; only an empty file fails.
buf := make([]byte, 512)
n, err := io.ReadFull(f, buf)
if n == 0 {
@@ -168,9 +128,8 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
}
}
// The uploaded name is thrown away for 16 random bytes. That rules out
// path traversal and collisions in one go, and makes the URL unguessable.
// Only the extension survives, and it is on the allow-list.
// A random name rules out traversal and collisions, and makes the URL
// unguessable.
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generating filename: %w", err)
@@ -187,7 +146,6 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
return prefix + name, nil
}
// StoredFile is one public upload, as listed for the admin's upload picker.
type StoredFile struct {
Name string `json:"name"`
URL string `json:"url"`
@@ -195,16 +153,8 @@ type StoredFile struct {
Modified time.Time `json:"modified"`
}
// List returns every public upload, newest first. Private files are never
// listed: they live in their own store, which this doesn't touch.
//
// The caller must be an admin. An upload's URL is public but unguessable, and
// that is the only thing keeping a file nobody linked to from being found; a
// listing anyone could read would hand every one of them out.
//
// Only names with an extension on the allow-list are returned, so anything
// else that ends up in the bucket or the directory (by hand, through
// garage-webui) never reaches a page through the picker.
// List returns public uploads, newest first. Admin only: unguessable URLs are
// the only protection for unlinked files. Off-list extensions are dropped.
func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
files, err := u.public.List(ctx)
if err != nil {
@@ -223,22 +173,17 @@ func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
// ---- Stores ----------------------------------------------------------------
// FileStore stores one file under key, and lists what it holds. r is a
// ReadSeeker because the S3 client must hash the body before sending it over
// plain HTTP, and because FallbackFileStore rewinds it to retry; a
// multipart.File satisfies it.
//
// List returns top-level files only, with URL unset (Uploads.List fills it).
// FileStore takes a ReadSeeker because S3 hashes the body before sending and
// FallbackFileStore rewinds it to retry. List returns top-level files only.
type FileStore interface {
Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error
List(ctx context.Context) ([]StoredFile, error)
}
// DiskFileStore writes files into Dir, creating it if needed.
type DiskFileStore struct{ Dir string }
func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error {
// 0755 and 0644 so the edge, in another container, can reach and read the files.
// World-readable so Caddy, in another container, can serve them.
if err := os.MkdirAll(d.Dir, 0755); err != nil {
return err
}
@@ -253,9 +198,7 @@ func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _
return out.Close()
}
// List skips subdirectories, which is what keeps the private/ directory
// (inside the public one on the volume) out of the listing. A directory that
// doesn't exist yet just holds nothing.
// List skips directories, which keeps private/ out of the listing.
func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) {
entries, err := os.ReadDir(d.Dir)
if errors.Is(err, fs.ErrNotExist) {
@@ -278,13 +221,11 @@ func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) {
return files, nil
}
// S3FileStore writes files into one bucket of an S3-compatible server.
type S3FileStore struct {
client *s3.Client
bucket string
}
// S3Config is the S3_* block of .env.
type S3Config struct {
Endpoint string // e.g. http://garage:3900
Region string // must match garage.toml's s3_region
@@ -293,9 +234,7 @@ type S3Config struct {
SecretAccessKey string
}
// s3Timeout bounds one upload. Uploads are capped at 10MB and Garage is on
// the same Docker network, so anything near this is a hang, and the fallback
// to disk is better than holding the request open.
// Garage is on the same network, so anything near this is a hang.
const s3Timeout = 30 * time.Second
func NewS3FileStore(cfg S3Config) *S3FileStore {
@@ -303,12 +242,9 @@ func NewS3FileStore(cfg S3Config) *S3FileStore {
BaseEndpoint: aws.String(cfg.Endpoint),
Region: cfg.Region,
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""),
// Garage addresses buckets by path (/bucket/key); virtual-host style
// would need a DNS name per bucket.
// Garage needs path-style addressing.
UsePathStyle: true,
// Recent SDKs add CRC32 checksums to every PUT by default. Only send
// them where S3 requires them, which is what third-party servers
// handle reliably.
// Default CRC32 checksums aren't reliably supported by non-AWS servers.
RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
})
@@ -332,9 +268,7 @@ func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.Rea
return nil
}
// List pages through the whole bucket. Keys containing "/" are skipped: they
// are not uploads (Save never makes one) but something put under a prefix by
// hand, and Caddy's /uploads/<name> only ever serves a top-level name anyway.
// List skips keys under a prefix: those were put there by hand.
func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
defer cancel()
@@ -357,10 +291,8 @@ func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
return files, nil
}
// FallbackFileStore tries Primary and, if that fails, logs it and writes to
// Fallback instead. The upload still succeeds and its URL still works (Caddy
// looks in both places), so a Garage outage costs a log line rather than
// broken uploads.
// FallbackFileStore writes to Fallback when Primary fails. Caddy serves from
// both, so the URL still works.
type FallbackFileStore struct {
Primary FileStore
Fallback FileStore
@@ -378,11 +310,7 @@ func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r i
return f.Fallback.Put(ctx, key, contentType, r, size)
}
// List is the union of both stores, since Caddy serves from both: the
// fallback holds whatever was written while the primary was down (and, on
// the live volume, the pre-Garage copies). A name in both is listed once,
// with the primary's details. A primary that can't list is logged and the
// fallback's files are returned alone, as for Put.
// List merges both stores, primary first, since Caddy serves from both.
func (f FallbackFileStore) List(ctx context.Context) ([]StoredFile, error) {
primary, err := f.Primary.List(ctx)
if err != nil {
+1 -7
View File
@@ -17,13 +17,7 @@ import (
"time"
)
// Covered here: the type table (the upload trust boundary's data), Save's
// validation, naming and routing, which store NewUploads picks, and the
// fallback — including against a real S3 client talking to a server that
// refuses the write, since "Garage said no" is the case it exists for.
//
// Not covered: a successful PutObject or ListObjectsV2 against Garage. That needs the garage
// container; it is checked by hand in the stack (DEPLOYMENT.md, "Garage").
// A successful Garage write is checked by hand (DEPLOYMENT.md, "Garage").
// fileHeader builds the *multipart.FileHeader a handler would get from
// ctx.FormFile, by round-tripping a real multipart body.
+16 -58
View File
@@ -12,27 +12,16 @@ import (
"github.com/gorilla/websocket"
)
// This file is the chat hub behind GET /ws. It is deliberately a package-level
// singleton (one process, one chat room) rather than an injectable type, so the
// connection set, the database handle and the allowed origin all live in
// package vars initialised once by InitWebSocket.
// The chat hub behind GET /ws: one process, one room, so package-level state.
// maxMessages is both the size of the history replayed to a new client and the
// number of rows kept in the database: every insert trims older messages.
// History replayed on connect, and rows kept in the database.
const maxMessages = 50
// allowedDomain is the site's domain, set by InitWebSocket and read by
// Upgrader.CheckOrigin. It is a package var because the Upgrader is one too.
var allowedDomain string
// Upgrader turns the HTTP request into a WebSocket.
//
// CheckOrigin is the only cross-origin defence on this endpoint: the browser
// sends cookies with a WebSocket handshake regardless of origin and there is
// no preflight, so without this check any site could open a socket as a
// logged-in visitor. Default gorilla behaviour (same-host only) is too strict
// here because the site is reached as both example.com and www.example.com,
// and "localhost" is allowed for the Vite dev server.
// CheckOrigin is the only cross-origin defence: browsers send cookies on a
// WebSocket handshake with no preflight. Gorilla's same-host default would
// reject the apex/www split and the Vite dev server.
var Upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
@@ -51,29 +40,20 @@ var Upgrader = websocket.Upgrader{
}
var (
// clients maps each open connection to whether it belongs to an admin.
clients = make(map[*websocket.Conn]bool)
// mu guards clients AND serialises the write-then-broadcast sequence, so
// that two concurrent senders cannot interleave and deliver messages to
// different clients in different orders.
// Also serialises write-then-broadcast so all clients see one order.
mu sync.Mutex
wsDB *gorm.DB
// nextAuthorID is a per-process counter handed out on connect. It is NOT
// a user id and has no meaning across restarts: the chat is pseudonymous,
// and the front end only uses it to colour/group consecutive messages
// from the same connection.
// Per-process connection number, not a user id; chat is pseudonymous.
nextAuthorID uint
)
// Per-connection flood limit, separate from services.RateLimiter because it
// counts frames on one socket rather than requests from one IP.
// Per-socket flood limit (frames, not requests per IP).
const (
rateLimitWindow = time.Second
rateLimitMaxMsgs = 10
)
// wsIncoming is the envelope clients send over the socket. A plain chat
// message carries text/fileUrl/private; an admin delete carries action+id.
type wsIncoming struct {
Action string `json:"action,omitempty"`
ID uint `json:"id,omitempty"`
@@ -82,37 +62,28 @@ type wsIncoming struct {
Private bool `json:"private,omitempty"`
}
// wsDeleteEvent is broadcast to every client when a message is removed.
type wsDeleteEvent struct {
Action string `json:"action"`
ID uint `json:"id"`
}
// wsHistoryEvent is sent once on connect with the recent messages the client
// may see. Sending it as a single batch lets the client replace its list
// atomically, so a reconnect does not blank the chat and reload every image.
// Sent as one batch so a reconnect replaces the list without blanking it.
type wsHistoryEvent struct {
Action string `json:"action"`
Messages []models.Message `json:"messages"`
}
// InitWebSocket wires the package-level hub to the database and the origin
// allow-list. Call it once, before serving.
func InitWebSocket(database *gorm.DB, domain string) {
wsDB = database
allowedDomain = domain
}
// HandleWebSocket serves one chat connection. isAdmin controls whether the
// connection may see private messages, send them, and delete messages.
// isAdmin allows seeing, sending and deleting private messages.
func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
defer conn.Close()
// Registration, history read and history send all happen under one lock.
// That is the point: it guarantees the client is already in `clients`
// before its snapshot is taken, so a message broadcast concurrently is
// either in the history or delivered afterwards — never dropped in the
// gap, and never delivered before the history that would overwrite it.
// Register and snapshot under one lock, so a concurrent broadcast is
// either in the history or delivered after it, never lost or reordered.
mu.Lock()
clients[conn] = isAdmin
nextAuthorID++
@@ -132,15 +103,12 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
}
mu.Unlock()
// Fixed-window flood limit. Over-limit frames are dropped silently with
// no error to the client and without resetting the window.
// Over-limit frames are dropped silently.
msgCount := 0
windowStart := time.Now()
for {
var incoming wsIncoming
// Any read error — clean close, network drop or malformed JSON —
// ends the connection; there is no attempt to resynchronise.
if err := conn.ReadJSON(&incoming); err != nil {
break
}
@@ -166,24 +134,16 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
Content: incoming.Text,
FileURL: incoming.FileURL,
AuthorID: authorID,
// Only admins may mark a message private.
Private: incoming.Private && isAdmin,
Private: incoming.Private && isAdmin,
}
mu.Lock()
wsDB.Create(&msg)
// Keep only the newest maxMessages rows. This is a soft delete
// (models.Message has gorm.DeletedAt), so the rows stay in the table
// with deleted_at set and GORM filters them out of later reads; the
// table therefore grows forever even though the chat does not.
// The subquery is itself soft-delete filtered, so already-trimmed
// rows are not re-deleted.
// Soft delete, so the table still grows; the chat does not.
wsDB.Where("id NOT IN (?)",
wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages),
).Delete(&models.Message{})
// Deleting from a map while ranging over it is explicitly allowed in
// Go, so pruning dead clients inline here is safe.
for client, clientAdmin := range clients {
if msg.Private && !clientAdmin {
continue
@@ -201,9 +161,7 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
mu.Unlock()
}
// deleteMessage soft-deletes a message and tells every client to drop it.
// Clients that never received the message (non-admins for a private one)
// simply ignore the unknown id.
// deleteMessage soft-deletes and broadcasts; clients ignore unknown ids.
func deleteMessage(id uint) {
mu.Lock()
defer mu.Unlock()