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
+3 -33
View File
@@ -1,32 +1,5 @@
# =============================================================================
# Go backend image — multi-stage: build with the full toolchain, ship a slim
# runtime containing one static binary.
#
# STAGE 1 (golang:1.26)
# go.mod/go.sum are copied and downloaded BEFORE the rest of the source, so
# the dependency layer is cached and only re-runs when the module files
# change — a meaningful saving when building on a Raspberry Pi.
#
# The `--mount=type=cache` lines are BuildKit cache mounts: the module cache
# and the Go build cache persist BETWEEN builds on the host without being
# baked into any image layer. This is the single biggest reason a rebuild on
# the Pi takes minutes rather than much longer. They require BuildKit, which
# is the default in modern `docker compose build`.
#
# CGO_ENABLED=0 produces a fully static binary with no libc dependency, which
# is what lets a golang-built binary run on a different, slimmer base image.
#
# STAGE 2 (debian:bookworm-slim)
# Carries only the binary plus ca-certificates — needed because the backend
# makes outbound HTTPS calls (Spotify, Claude, Steam, the Gitea feed) and
# would fail certificate verification without a trust store.
#
# EXPOSE 8080 is documentation only; the port is never published to the host.
# Caddy reaches it over app-network as BACKEND_HOST:BACKEND_PORT.
#
# Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and
# amd64 (a dev laptop) with no platform pin.
# =============================================================================
# Static binary (CGO_ENABLED=0) on a slim base. ca-certificates for outbound
# HTTPS; the cache mounts keep rebuilds fast.
FROM golang:1.26 AS builder
WORKDIR /backend
@@ -44,10 +17,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \
FROM debian:bookworm-slim
# wget is not just for humans: the compose healthcheck probes the server with
# `wget -qO- http://localhost:8080/`, and without it in the image every probe
# fails as "executable file not found" and Docker marks the container
# unhealthy.
# For the compose healthcheck.
RUN apt-get update \
&& apt-get install --yes --no-install-recommends ca-certificates wget \
&& rm -rf /var/lib/apt/lists/*
+1 -1
View File
@@ -38,7 +38,7 @@ graph/ GraphQL layer
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
that `ClientIP()` — which the login rate limiter keys on — cannot be
spoofed via `X-Forwarded-For`.
3. **REST**: the route's middleware chain runs. `AuthMiddlewear` requires a
3. **REST**: the route's middleware chain runs. `AuthMiddleware` requires a
valid access token and stashes the claims in the Gin context;
`AdminMiddleware` then requires `admin: true` in those claims. A handler
reached through the `admin` group can assume both.
-3
View File
@@ -14,9 +14,6 @@ import (
// CreateActivity is the resolver for the createActivity field.
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
// Admin-only, but there is no check to see here: the field is marked
// @admin in the schema and the directive (directives.go) has already
// refused anyone else by the time this runs.
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
if err := r.Store.DB.Create(&activity).Error; err != nil {
return nil, err
+6 -25
View File
@@ -19,12 +19,7 @@ import (
// Login is the resolver for the login field.
func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) {
// The Gin context is needed for two things GraphQL cannot express: the
// client IP for rate limiting, and setting response cookies. It is
// smuggled in by AuthContextMiddleware.
//
// This mutation mirrors handlers.Store.Login; the two share the limiter
// and services.Auth, so the same 5/min budget covers both entry points.
// Gin context for the client IP and cookies. Shares the REST login's limiter.
gc := GinContextFromCtx(ctx)
if gc == nil {
return nil, fmt.Errorf("could not get gin context")
@@ -34,8 +29,6 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
return nil, fmt.Errorf("too many login attempts, please try again later")
}
// Identical message for unknown user and wrong password, so the API
// cannot be used to enumerate usernames.
var user models.User
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
return nil, fmt.Errorf("invalid credentials")
@@ -52,8 +45,7 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
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.
// Tokens travel only as HttpOnly cookies.
return &model.AuthPayload{User: &user}, nil
}
@@ -64,12 +56,9 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
return false, fmt.Errorf("could not get gin context")
}
// 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.
// Best effort, always succeeds, like 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.
// Claims in ctx are already verified, so this can't target others.
if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil {
log.Printf("logout: failed to revoke tokens for user %d: %v", userID, err)
}
@@ -92,11 +81,7 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
return nil, fmt.Errorf("unauthorized")
}
// 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.
// Re-reads admin and token version from the DB.
user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken)
if err != nil {
switch {
@@ -121,16 +106,12 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
// Me is the resolver for the me field.
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
// Checked here rather than with @signedIn because the message differs:
// this query has always answered "unauthorized", and the directive's is
// "authentication required".
// Not @signedIn: this query's error has always been "unauthorized".
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
}
// Read fresh from the database rather than returned from the token
// claims, so `me` reflects the current username and admin flag.
var user models.User
user.ID = userID
if err := r.Store.DB.First(&user).Error; err != nil {
+2 -4
View File
@@ -12,10 +12,8 @@ import (
"adam-french.co.uk/backend/models"
)
// The SPA puts these values straight into a style binding, as
// `background-color` and `url("<image>")`. Vue sets them through the CSSOM,
// so nothing can escape into other properties, but a quote or bracket in the
// image could still end the url() early — hence the narrow shapes.
// These go into a style binding; a quote or bracket in the image could still
// end url() early, hence the narrow shapes.
var (
// A hex colour, a colour name, or one of the colour functions — named,
// so that url() and friends don't pass as a "function".
+1 -3
View File
@@ -23,9 +23,7 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat
// DeleteBookmark is the resolver for the deleteBookmark field.
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
// Loaded first so the deleted record can be returned to the client, and
// so a missing id is a clean "not found" rather than a silent no-op.
// Delete is a soft delete: deleted_at is set and the row stays.
// Loaded first so the deleted record can be returned and a bad id is "not found".
var bookmark models.Bookmark
if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
return nil, err
+7 -17
View File
@@ -15,9 +15,7 @@ import (
// CreateBox is the resolver for the createBox field.
func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxInput) (*models.Box, error) {
// Framed defaults to true here rather than in the gorm tag — see the
// comment on models.Box.Framed. Sizes not supplied fall back to the
// same 300x200 the column defaults use.
// Framed defaults here, not in the gorm tag; see models.Box.Framed.
box := models.Box{
Page: input.Page,
Kind: input.Kind,
@@ -45,8 +43,7 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI
if input.AdminOnly != nil {
box.AdminOnly = *input.AdminOnly
}
// A linked box takes its html from the component, so its own is
// dropped rather than stored as a copy that would quietly go stale.
// A linked box's own html would only go stale.
if input.ComponentID != nil {
id := uint(*input.ComponentID)
exists, err := componentExists(r.Store.DB, id)
@@ -75,10 +72,8 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI
// UpdateBox is the resolver for the updateBox field.
func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.UpdateBoxInput) (*models.Box, error) {
// Partial update: nil fields are left alone. The canvas sends only the
// geometry after a drag and only the html after an edit, so this is
// what keeps the two from overwriting each other. Kind is not
// updatable — switching a widget box to html is a delete and create.
// Partial: the canvas sends only geometry after a drag and only html after
// an edit, so neither overwrites the other.
var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err
@@ -87,8 +82,7 @@ func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.Up
box.Widget = input.Widget
}
if input.HTML != nil {
// A linked box's html is the component's; changing it here would
// only fork a copy. The editor sends it to updateComponent instead.
// Edit linked html via updateComponent, or it forks a copy.
if box.ComponentID != nil {
return nil, errors.New("that box is linked to a component: edit the component, or detach the box first")
}
@@ -140,12 +134,8 @@ func (r *mutationResolver) DeleteBox(ctx context.Context, id int) (*models.Box,
// Boxes is the resolver for the boxes field.
func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box, error) {
// Public: this is the page layout every visitor loads. Ordered by z so
// DOM order matches stacking order, which keeps tab order sensible.
//
// What is admin-only is filtered here rather than hidden in the browser,
// so a private note never reaches anyone else: an adminOnly page answers
// with no boxes at all, and adminOnly boxes are left out of the rest.
// Ordered by z so DOM and tab order match stacking. Admin-only content is
// filtered server-side so it never reaches anyone else.
hidden, err := pageHiddenFrom(ctx, r.Store.DB, page)
if err != nil {
return nil, err
+3 -9
View File
@@ -1,8 +1,6 @@
package graph
// Hand-written helpers for box.resolvers.go. Kept out of that file because
// gqlgen moves unknown code in a resolvers file to the end, under a warning
// comment, on every regenerate.
// Helpers live outside *.resolvers.go because gqlgen moves unknown code there.
import (
"errors"
@@ -26,9 +24,7 @@ func setInt(dst *int, src *int) {
}
}
// validateBox checks the fields a box needs to render and clamps geometry
// rather than rejecting it, because a drag that overshoots the canvas edge
// should land at the edge, not fail.
// validateBox clamps geometry, so an overshooting drag lands at the edge.
func validateBox(box *models.Box) error {
if !validPageKey(box.Page) {
return errors.New("a box needs a valid page")
@@ -59,9 +55,7 @@ func validateBox(box *models.Box) error {
return nil
}
// validateShadow trims a box-shadow value and bounds its length. The value is
// not parsed: the front end sets it through a style binding, so it can only
// ever be the one property, and an invalid value just draws no shadow.
// validateShadow doesn't parse: a style binding confines it to one property.
func validateShadow(shadow *string) error {
*shadow = strings.TrimSpace(*shadow)
if len(*shadow) > maxShadowLen {
+4 -13
View File
@@ -16,8 +16,6 @@ import (
// Uses is the resolver for the uses field.
func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (int, error) {
// One count per component, which is fine for an admin-only list of a
// handful; soft-deleted boxes are excluded by GORM's default scope.
var count int64
if err := r.Store.DB.Model(&models.Box{}).Where("component_id = ?", obj.ID).Count(&count).Error; err != nil {
return 0, err
@@ -27,7 +25,6 @@ func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (in
// CreateComponent is the resolver for the createComponent field.
func (r *mutationResolver) CreateComponent(ctx context.Context, input model.CreateComponentInput) (*models.Component, error) {
// Framed defaults to true and the size to 300x200, as for a new box.
name, err := usableComponentName(r.Store.DB, input.Name, 0)
if err != nil {
return nil, err
@@ -57,8 +54,7 @@ func (r *mutationResolver) CreateComponent(ctx context.Context, input model.Crea
// UpdateComponent is the resolver for the updateComponent field.
func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input model.UpdateComponentInput) (*models.Component, error) {
// Partial, like updateBox. Nothing to do for the linked boxes: they
// read the html from here every time they are fetched.
// Linked boxes read the html from here, so nothing else to update.
var c models.Component
if err := r.Store.DB.First(&c, id).Error; err != nil {
return nil, err
@@ -100,9 +96,7 @@ func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input mo
// DeleteComponent is the resolver for the deleteComponent field.
func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models.Component, error) {
// The linked boxes keep showing what they showed, as copies, so
// deleting a component never changes a page. One transaction, so a
// failure can't leave boxes linked to a deleted component.
// Linked boxes become copies, so deleting never changes a page.
var c models.Component
if err := r.Store.DB.First(&c, id).Error; err != nil {
return nil, err
@@ -121,9 +115,8 @@ func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models
// SaveBoxAsComponent is the resolver for the saveBoxAsComponent field.
func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name string) (*models.Box, error) {
// The box becomes the component's first linked instance, so carrying
// on editing it edits the component. A box that is already linked
// would make a component of a component's html; detach it first.
// The box becomes the first linked instance. A linked box must be
// detached first.
var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err
@@ -161,8 +154,6 @@ func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name
// DetachBox is the resolver for the detachBox field.
func (r *mutationResolver) DetachBox(ctx context.Context, id int) (*models.Box, error) {
// The html is filled in from the component and then saved, which is
// exactly the copy fillLinked otherwise never lets reach the row.
var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err
+2 -9
View File
@@ -27,9 +27,6 @@ func cleanComponentName(name string) (string, error) {
return name, nil
}
// componentNameTaken reports whether a live component other than exceptID
// has this name. Checked up front, like layoutNameTaken, so the admin gets a
// sentence rather than a constraint violation.
func componentNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.Component{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
@@ -53,12 +50,8 @@ func usableComponentName(db *gorm.DB, name string, exceptID uint) (string, error
return name, nil
}
// fillLinked sets each linked box's in-memory HTML to its component's, with
// one query for all of them. Only for boxes about to be returned or
// snapshotted: a linked row's own HTML is nil, and saving a filled box would
// freeze a copy of the component into it. A box whose component has gone
// (deleted outside deleteComponent, which detaches first) is left with
// empty HTML rather than failing the whole page.
// fillLinked sets linked boxes' HTML in memory only: saving a filled box would
// freeze a copy into it. A missing component leaves the HTML empty.
func fillLinked(db *gorm.DB, boxes []models.Box) error {
var ids []uint
for _, b := range boxes {
+7 -30
View File
@@ -7,17 +7,10 @@ import (
"github.com/golang-jwt/jwt/v5"
)
// This file is the bridge between Gin's request handling and gqlgen's
// resolvers. gqlgen resolvers receive only a context.Context, so
// AuthContextMiddleware (middleware.go) smuggles the verified JWT claims and
// the *gin.Context itself into that context, and these accessors read them
// back out.
// Resolvers get only a context.Context; AuthContextMiddleware puts the
// verified claims and the *gin.Context into it.
// contextKey is a private named type so that these keys can never collide
// with a key set by another package — the reason the standard library warns
// against using bare strings as context keys. Note the string value
// "userClaims" happens to match the key handlers.AuthMiddlewear uses in the
// *Gin* context, but the two are unrelated and do not see each other.
// Unrelated to the "userClaims" key handlers.AuthMiddleware sets on Gin's context.
type contextKey string
const (
@@ -25,10 +18,8 @@ const (
ginContextKey contextKey = "ginContext"
)
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request
// is anonymous. nil means "not authenticated": a missing or invalid token is
// not an error here, because many queries are public. Turning "anonymous"
// into a refusal is the job of the schema directives, per field.
// UserClaimsFromCtx returns nil for anonymous requests; refusing is the
// directives' job.
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
if !ok {
@@ -37,12 +28,6 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
return claims
}
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
// float64 because claims are decoded by encoding/json, hence the conversion.
//
// ok is also the test behind the @signedIn directive. A resolver calls this
// itself when it needs the id for more than a gate: to record a post's
// author, or to compare the caller with a row's owner.
func UserIDFromCtx(ctx context.Context) (uint, bool) {
claims := UserClaimsFromCtx(ctx)
if claims == nil {
@@ -55,12 +40,7 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
return uint(idF), true
}
// IsAdminFromCtx reports whether the request carries an admin token. It is
// what the @admin directive tests (directives.go), which is how nearly every
// mutation is authorised; resolvers call it directly only for the softer
// cases a directive cannot express, such as the messages query filtering
// rather than refusing. Admin comes from the token, not the database, so a
// revoked admin flag only bites once the access token expires.
// IsAdminFromCtx reads the token, so a revoked flag applies on expiry.
func IsAdminFromCtx(ctx context.Context) bool {
claims := UserClaimsFromCtx(ctx)
if claims == nil {
@@ -70,10 +50,7 @@ func IsAdminFromCtx(ctx context.Context) bool {
return ok && admin
}
// GinContextFromCtx returns the underlying *gin.Context, which resolvers need
// for things that live outside GraphQL's model: setting auth cookies and
// reading the client IP. Returns nil if the middleware was not installed,
// which the auth resolvers surface as an error rather than panicking.
// GinContextFromCtx is nil if the middleware wasn't installed.
func GinContextFromCtx(ctx context.Context) *gin.Context {
gc, ok := ctx.Value(ginContextKey).(*gin.Context)
if !ok {
+3 -9
View File
@@ -36,18 +36,14 @@ func cleanCoverLetterName(name string) (string, error) {
return name, nil
}
// coverLetterNameTaken reports whether a live letter other than exceptID has
// this name. Checked up front, like layoutNameTaken, so the admin gets a
// sentence rather than a constraint violation.
func coverLetterNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.CoverLetter{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err
}
// checkCoverLetterBody reports why body can't be stored. The server never
// reads inside it, so it only has to be a JSON object of a sane size — an
// array or a bare string would be a frontend bug worth refusing early.
// checkCoverLetterBody: the server never reads inside it, so it need only be a
// JSON object of sane size.
func checkCoverLetterBody(body string) error {
if len(body) > maxCoverLetterBodyLen {
return fmt.Errorf("a cover letter is at most %d KB", maxCoverLetterBodyLen/1024)
@@ -60,9 +56,7 @@ func checkCoverLetterBody(body string) error {
return nil
}
// cleanSnippetText trims text and reports why it can't be a bank paragraph.
// Counted in characters, not bytes, since the limit is about how much prose
// fits rather than storage.
// cleanSnippetText counts characters, not bytes.
func cleanSnippetText(text string) (string, error) {
text = strings.TrimSpace(text)
if text == "" {
+4 -28
View File
@@ -7,34 +7,16 @@ import (
"github.com/99designs/gqlgen/graphql"
)
// The schema's two authorisation directives. A field marked @admin or
// @signedIn in graph/schema/*.graphql has the matching function here run
// before its resolver; if it returns an error the resolver is never called
// and the error is what the client receives for that field.
//
// This replaces a check that used to be copied into the top of every guarded
// resolver. The rule itself is unchanged — it is the same IsAdminFromCtx /
// UserIDFromCtx test against the claims AuthContextMiddleware verified — but
// it is now declared next to the field, where a missing one can be seen and
// tested for (directives_test.go), instead of being a line someone has to
// remember to paste.
//
// The two error strings are part of the contract with the front end, which
// shows them as they are; the tracker page, for one, explains "admin access
// required" as a lapsed session. Do not reword them.
//
// This file is hand-written and never touched by gqlgen.
// The @admin and @signedIn directives. The front end shows these error
// strings verbatim (the tracker reads "admin access required" as a lapsed
// session), so don't reword them.
const (
errAdminRequired = "admin access required"
errSignedInRequired = "authentication required"
)
// Directives is the set gqlgen needs in graph.Config. It is a function so
// that main and the tests wire exactly the same implementations.
//
// Leaving a directive nil in the Config does not open the fields that use it:
// the generated code answers "directive admin is not implemented" for each.
// Directives is shared by main and the tests. A nil directive fails closed.
func Directives() DirectiveRoot {
return DirectiveRoot{
Admin: requireAdmin,
@@ -42,9 +24,6 @@ func Directives() DirectiveRoot {
}
}
// requireAdmin implements @admin: the request must carry an access token
// whose admin claim is true. Admin comes from the token, not the database, so
// demoting a user only bites once their access token is replaced.
func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf(errAdminRequired)
@@ -52,9 +31,6 @@ func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error
return next(ctx)
}
// requireSignedIn implements @signedIn: any verified access token will do,
// admin or not. An admin is signed in, so this never needs pairing with
// @admin.
func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf(errSignedInRequired)
+11 -42
View File
@@ -20,15 +20,8 @@ import (
"adam-french.co.uk/backend/handlers"
)
// Authorisation is declared in the schema (@admin / @signedIn) and enforced
// by directives.go. These tests cover both halves: that the two functions
// decide correctly, and that the schema marks the fields it should — the
// second being the one that matters day to day, since the way this goes
// wrong is a new field added without a directive.
//
// Nothing here needs a database: a refused field never reaches its resolver,
// and the tests only ever drive fields that are refused or that return before
// touching the Store.
// Covers both the directive functions and which fields carry them. No
// database: refused fields never reach their resolvers.
// withClaims builds the context AuthContextMiddleware would for a verified
// token. Claims are decoded from JSON in production, hence float64 for the id.
@@ -100,9 +93,7 @@ func TestDirectivesAreAllImplemented(t *testing.T) {
}
}
// guardOf reports which authorisation directive a field carries: "admin",
// "signedIn", or "" for none. Carrying both is a mistake (@signedIn adds
// nothing to @admin) and fails the test rather than being quietly accepted.
// guardOf fails on both directives at once: @signedIn adds nothing to @admin.
func guardOf(t *testing.T, field *ast.FieldDefinition) string {
t.Helper()
admin := field.Directives.ForName("admin") != nil
@@ -123,14 +114,8 @@ func schemaUnderTest() *ast.Schema {
return NewExecutableSchema(Config{}).Schema()
}
// publicMutations is the complete list of mutations that anyone may call.
// A mutation is public only by being named here, so adding one to the schema
// without a directive fails TestEveryMutationIsGuarded until it is either
// guarded or deliberately listed.
//
// All three are how a session is obtained or given up, so they cannot require
// one: login checks a password, refreshToken checks the refresh cookie, and
// logout is a no-op for a visitor who is not signed in.
// publicMutations is the allow-list; any other unguarded mutation fails
// TestEveryMutationIsGuarded.
var publicMutations = []string{"login", "logout", "refreshToken"}
func TestEveryMutationIsGuarded(t *testing.T) {
@@ -159,9 +144,7 @@ func TestEveryMutationIsGuarded(t *testing.T) {
}
}
// The mutations that need only a session rather than an admin. Pinned so that
// loosening a mutation from @admin to @signedIn — which the test above would
// accept — has to be done here too.
// Pinned so loosening @admin to @signedIn needs a change here.
func TestSignedInMutationsArePinned(t *testing.T) {
want := []string{"createPlace", "deletePlace", "updatePlace"}
var got []string
@@ -176,15 +159,8 @@ func TestSignedInMutationsArePinned(t *testing.T) {
}
}
// Queries are public by default — the home page is built from them — so the
// rule cannot be "every field is guarded". Instead the guarded set is pinned
// exactly: removing a directive from one of these, or adding a query that
// exposes private data without one, has to be a visible change to this map.
//
// Three queries are sensitive to who is asking without being in it, because
// they answer rather than refuse: `me` returns "unauthorized" itself,
// `messages` filters out private rows for non-admins, and
// `spotifyNeedsReauth` is false for non-admins.
// Queries are public by default, so the guarded set is pinned exactly.
// me, messages and spotifyNeedsReauth vary by caller without a directive.
func TestGuardedQueriesArePinned(t *testing.T) {
want := map[string]string{
"users": "admin",
@@ -217,9 +193,7 @@ func TestGuardedQueriesArePinned(t *testing.T) {
}
}
// The directives are FIELD_DEFINITION only and are meant for the two root
// types. One on an object's field would be enforced, but nothing above would
// notice it being removed, so keep them where the tests look.
// Keep directives on root fields: the tests above only look there.
func TestDirectivesOnlyOnRootFields(t *testing.T) {
schema := schemaUnderTest()
for name, def := range schema.Types {
@@ -234,10 +208,7 @@ func TestDirectivesOnlyOnRootFields(t *testing.T) {
}
}
// execute runs one operation through the real executable schema, wired the
// way main wires it, and returns the response's error messages. The Store is
// empty: every operation below is refused, or returns, before its resolver
// would touch the database.
// execute runs an operation as main wires it, with an empty Store.
func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string {
t.Helper()
srv := handler.New(NewExecutableSchema(Config{
@@ -298,9 +269,7 @@ func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
}
}
// IDs: the wire form must be what it was when every type had a hand-written
// resolver returning int. Both marshallers write a quoted decimal string and
// both read a string or a number.
// IDs stay quoted decimal strings on the wire, accepting strings or numbers.
func TestUintIDWireFormatMatchesIntID(t *testing.T) {
for _, id := range []uint{0, 1, 12, 4294967295} {
var asUint, asInt bytes.Buffer
+11 -47
View File
@@ -1,51 +1,15 @@
// Package graph is the GraphQL layer: the single POST /graphql endpoint that
// serves most of the site's data.
// Package graph is the GraphQL layer behind POST /graphql.
//
// How the pieces fit:
// graph/schema/*.graphql is the source of truth; gqlgen regenerates
// generated.go and model/models_gen.go (never edit them). gqlgen.yml maps
// object types onto the GORM structs in backend/models.
//
// - graph/schema/*.graphql is the source of truth. Running
// `go run github.com/99designs/gqlgen generate` regenerates generated.go
// and model/models_gen.go, and adds stubs for any new field to the
// matching *.resolvers.go. Never edit those two generated files.
// - gqlgen.yml maps most GraphQL object types straight onto the GORM
// structs in backend/models, so model/ holds only input and payload
// types. A model's `ID uint` binds to `id: ID!` directly, because
// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is
// needed for it. A field resolver is only written where the Go type has
// no binding (Message.authorId and Rowing's time/distance are unsigned in
// Go and Int in the schema).
// - Resolvers reach the database and the third-party caches through
// Resolver.Store, the same handlers.Store the REST endpoints use.
// - context.go and middleware.go carry the caller's identity from Gin into
// the plain context.Context a resolver receives.
// Nothing guards the endpoint itself. A field is protected only by an
// @admin or @signedIn directive (directives.go); a field with neither is
// public. directives_test.go fails if a mutation has neither and isn't on its
// public allow-list. Finer rules (post ownership, hiding private messages)
// live in resolvers via IsAdminFromCtx / UserIDFromCtx.
//
// Authorisation, which is the thing most likely to catch out a newcomer:
// there is NO middleware guarding this endpoint. AuthContextMiddleware only
// annotates the context and lets everything through. What guards a field is a
// directive on it in the schema:
//
// createUser(input: CreateUserInput!): User! @admin
// places: [Place!]! @signedIn
//
// @admin requires an admin's access token, @signedIn any valid one. Both are
// implemented once, in directives.go, and run before the resolver, so a
// guarded resolver contains no check of its own. A field with NEITHER
// directive is fully public.
//
// The rule of thumb in this schema is that queries are public and mutations
// are @admin, with these exceptions: login, logout and refreshToken are
// public; the places mutations and query are @signedIn; and the users
// queries are @admin (they are private data).
// directives_test.go holds that list and fails when the schema departs from
// it — in particular when a mutation is added with no directive.
//
// A directive is only a gate. Anything finer stays in the resolver and uses
// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its
// author, `me` answers for the caller (with its own "unauthorized" error),
// the messages query hides private messages from non-admins rather than
// refusing, and spotifyNeedsReauth is simply false for non-admins.
//
// The files ending in _helpers.go are hand-written and are not touched by
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
// them by hand may be moved to the end of the file on the next generate.
// gqlgen may move hand-written code in *.resolvers.go; _helpers.go files are
// untouched.
package graph
+1 -4
View File
@@ -24,10 +24,7 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er
if err != nil {
return nil, err
}
// FetchLatestFeed returns (nil, nil) for an empty feed; mapGiteaFeed
// would dereference it, so return null to the client instead. The cache
// is deliberately not written in that case, so an empty feed is retried
// on the next request.
// Not cached, so an empty feed is retried next time.
if feed == nil {
return nil, nil
}
+1 -4
View File
@@ -5,10 +5,7 @@ import (
"adam-french.co.uk/backend/services"
)
// mapGiteaFeed flattens a Gitea feed entry into the GraphQL shape, pulling the
// commit message out of the doubly-encoded Content field as it goes. It
// dereferences feed, so callers must rule out the (nil, nil) that
// FetchLatestFeed returns for an empty feed.
// mapGiteaFeed requires a non-nil feed.
func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem {
return &model.GiteaFeedItem{
AvatarURL: feed.ActUser.AvatarURL,
+8 -33
View File
@@ -1,8 +1,5 @@
package graph
// Hand-written helpers for layout.resolvers.go, kept out of the resolver file
// for the same reason as box_helpers.go.
import (
"encoding/json"
"errors"
@@ -17,9 +14,7 @@ import (
const maxLayoutNameLen = 100
// layoutBox is one box as a layout stores it: what makes it look the way it
// does, without the id and page that tie a row to one canvas. Changing these
// field names would make older layouts load with the renamed fields empty.
// layoutBox is a box minus id and page. Renaming fields breaks saved layouts.
type layoutBox struct {
Kind string `json:"kind"`
Widget *string `json:"widget,omitempty"`
@@ -34,9 +29,7 @@ type layoutBox struct {
Shadow string `json:"shadow,omitempty"`
HideOnMobile bool `json:"hideOnMobile"`
AdminOnly bool `json:"adminOnly"`
// ComponentID is the component a linked box was linked to. HTML is
// stored too, so that a layout outlives the component: loading links the
// box again if the component is still there and uses HTML if not.
// HTML is kept too, so a layout outlives a deleted component.
ComponentID *uint `json:"componentId,omitempty"`
}
@@ -46,7 +39,6 @@ type layoutBackground struct {
Fit string `json:"fit"`
}
// cleanLayoutName trims name and reports why it can't be a layout's name.
func cleanLayoutName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" {
@@ -58,18 +50,14 @@ func cleanLayoutName(name string) (string, error) {
return name, nil
}
// layoutNameTaken reports whether a live layout other than exceptID has this
// name. Checked up front, like slugTaken, so the admin gets a sentence rather
// than a constraint violation.
// Checked up front so the admin gets a sentence, not a constraint violation.
func layoutNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.Layout{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err
}
// canvasExists reports whether page is a canvas boxes can be put on: the
// landing page, or a live Page. Loading a layout onto any other key would
// leave its boxes where nothing shows them.
// canvasExists: boxes on any other key would never be shown.
func canvasExists(db *gorm.DB, page string) (bool, error) {
if page == "index" {
return true, nil
@@ -82,16 +70,13 @@ func canvasExists(db *gorm.DB, page string) (bool, error) {
return count > 0, err
}
// pageBoxes is every box on page, adminOnly ones included, in the order the
// boxes query returns them. Only for admin-only callers.
// pageBoxes includes adminOnly boxes; admin callers only.
func pageBoxes(db *gorm.DB, page string) ([]models.Box, error) {
var boxes []models.Box
err := db.Where("page = ?", page).Order("z ASC, id ASC").Find(&boxes).Error
return boxes, err
}
// snapshotPage is an unsaved Layout holding page's boxes and background as
// they are now. empty is true when there was nothing to keep.
func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty bool, err error) {
boxes, err := pageBoxes(db, page)
if err != nil {
@@ -139,7 +124,6 @@ func decodeLayoutBoxes(layout *models.Layout) ([]layoutBox, error) {
return boxes, nil
}
// pageLabel is how a page key reads in a generated layout name.
func pageLabel(page string) string {
if page == "index" {
return "/"
@@ -147,7 +131,6 @@ func pageLabel(page string) string {
return "/" + page
}
// uniqueLayoutName is base, or base with " (2)", " (3)"… if that is taken.
func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
name := base
for n := 2; ; n++ {
@@ -159,22 +142,17 @@ func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
}
}
// applyLayoutTo copies layout onto page inside tx; see applyLayout in
// layout.graphql for what replace does. The copies are new rows, so the page
// owns them outright.
// applyLayoutTo creates new rows, so nothing stays linked to the layout.
func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool) error {
stored, err := decodeLayoutBoxes(layout)
if err != nil {
return err
}
// Added on top, the copies keep their own stacking order but all sit
// above what the page already has.
// Added copies stack above the page's existing boxes.
zShift := 0
if replace {
// What is being replaced is kept first, so a replace can be undone by
// loading that layout back. A page with nothing on it has nothing to
// keep.
// Save what's being replaced first, so a replace can be undone.
name, err := uniqueLayoutName(tx, fmt.Sprintf("%s before %s, %s",
pageLabel(page), layout.Name, time.Now().Format("2 Jan 2006 15:04")))
if err != nil {
@@ -234,7 +212,6 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool
}
}
// Adding on top leaves the page's own background alone.
if replace && layout.Background != nil {
var saved layoutBackground
if err := json.Unmarshal([]byte(*layout.Background), &saved); err != nil {
@@ -251,8 +228,6 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool
return nil
}
// liveComponents is the set of components the stored boxes were linked to
// that still exist, so applyLayoutTo knows which boxes to link again.
func liveComponents(db *gorm.DB, stored []layoutBox) (map[uint]bool, error) {
var ids []uint
for _, b := range stored {
+3 -9
View File
@@ -12,21 +12,15 @@ import (
)
// AuthorID is the resolver for the authorId field.
// AuthorID is the resolver for the authorId field. The value is the chat
// hub's per-connection counter, not a User id — see models.Message.
// The chat hub's connection number, not a User id.
func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) {
return int(obj.AuthorID), nil
}
// Messages is the resolver for the messages field.
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
// Non-admins get the public subset rather than an error, so the chat
// history loads for everyone. The same filter is applied to the history
// replayed over the WebSocket (services.HandleWebSocket) — change one and
// the other must change too.
//
// Note the ordering differs between the two: newest first here, oldest
// first over the socket.
// Non-admins get the public subset. Keep in step with the WebSocket
// history filter (services.HandleWebSocket), which is oldest first.
var messages []models.Message
query := r.Store.DB.Order("created_at DESC")
if !IsAdminFromCtx(ctx) {
+2 -21
View File
@@ -8,39 +8,20 @@ import (
"gorm.io/gorm"
)
// AuthContextMiddleware prepares the request context for the GraphQL handler.
//
// It always attaches the *gin.Context, and attaches the JWT claims only when a
// valid access token is present. Crucially it never rejects a request: a
// missing, expired or forged token simply leaves the context anonymous, which
// is what lets public queries work and leaves every authorisation decision
// to the field being resolved — the @admin / @signedIn directives on it (see
// directives.go), or the resolver itself for anything finer. 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.
// AuthContextMiddleware never rejects: a bad or missing token leaves the
// context anonymous and the directives decide. No refresh fallback.
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 {
// 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)
}
}
// The context is immutable, so the enriched one has to be written
// back onto the request for the gqlgen handler to see it.
c.Request = c.Request.WithContext(ctx)
c.Next()
}
+2 -6
View File
@@ -45,9 +45,7 @@ func (r *mutationResolver) CreatePage(ctx context.Context, input model.CreatePag
// UpdatePage is the resolver for the updatePage field.
func (r *mutationResolver) UpdatePage(ctx context.Context, id int, input model.UpdatePageInput) (*models.Page, error) {
// Partial update, like updateBox. A new slug moves the page's boxes and
// background with it in the same transaction, since both find their page
// by slug.
// Partial. A new slug moves the boxes and background in the same transaction.
var page models.Page
if err := r.Store.DB.First(&page, id).Error; err != nil {
return nil, err
@@ -134,9 +132,7 @@ func (r *queryResolver) Pages(ctx context.Context) ([]*models.Page, error) {
// Page is the resolver for the page field.
func (r *queryResolver) Page(ctx context.Context, slug string) (*models.Page, error) {
// Null, not an error, for a missing page: the SPA's catch-all route asks
// this for every unknown path and shows its 404 on null. An adminOnly
// page reads as missing to everyone else, so its existence isn't leaked.
// Null for missing or hidden pages: the SPA shows its 404 on null.
var page models.Page
err := r.Store.DB.Where("slug = ?", slug).First(&page).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
+5 -16
View File
@@ -13,20 +13,13 @@ import (
"gorm.io/gorm"
)
// pageKeyPattern is the shape of a box's page key and of a page slug: lower
// case words joined by hyphens, in one or more /-separated segments. It is
// URL-safe as it stands, so the front end can use a slug as a path without
// escaping it.
// Slugs are URL-safe as they stand.
var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-z0-9]+)*)*$`)
const maxSlugLen = 100
// reservedFirstSegments are paths a page could never be reached at, because
// Caddy or one of the SPA's own routes answers them first (see
// caddy/routes.caddy and vue/src/router/index.js), plus the
// landing page's key "index", whose boxes a page of the same slug would
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
// pages under it and the home page /stp are all canvas pages.
// Paths Caddy or the SPA's routes answer first, plus "index". "shrines" and
// "stp" are canvas pages, so not reserved.
var reservedFirstSegments = map[string]bool{
"stp2": true, "index": true, "admin": true, "cv": true,
"automata": true, "hotels": true, "api": true, "py": true, "radio": true,
@@ -51,9 +44,7 @@ func validateSlug(slug string) error {
return nil
}
// pageHiddenFrom reports whether the page with this key is an adminOnly page
// and the caller is not an admin. A key with no Page row (the landing page,
// or a page that doesn't exist) is not hidden.
// A key with no Page row is never hidden.
func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) {
if IsAdminFromCtx(ctx) {
return false, nil
@@ -63,9 +54,7 @@ func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error)
return count > 0, err
}
// slugTaken reports whether a live page other than exceptID has this slug.
// Checked up front so the admin gets a sentence rather than a constraint
// violation; the partial unique index still backs it up.
// Checked up front for a readable error; the partial unique index backs it.
func slugTaken(db *gorm.DB, slug string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.Page{}).Where("slug = ? AND id <> ?", slug, exceptID).Count(&count).Error
+1 -4
View File
@@ -14,10 +14,7 @@ import (
// CreatePlace is the resolver for the createPlace field.
func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) {
// Any signed-in user, not just an admin — places are the one shared,
// collaboratively edited list on the site, so the schema marks these
// fields @signedIn rather than @admin. There is no per-user ownership, so
// any signed-in user can edit or delete any place.
// @signedIn: places are the site's one shared list, with no ownership.
place := models.Place{
Title: input.Title,
Location: input.Location,
+4 -16
View File
@@ -16,16 +16,12 @@ import (
// CreatePost is the resolver for the createPost field.
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
// @admin has already established that there is a session; the id is read
// here because the post needs an author, not as a second gate. The !ok
// branch is only reachable with a token that has admin but no usable id.
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
}
// The admin form submits whatever is in its fields, so an accidental click
// on an empty form would otherwise publish a blank post to the feed.
// Stops a stray click publishing a blank post.
if strings.TrimSpace(input.Title) == "" {
return nil, fmt.Errorf("a post needs a title")
}
@@ -50,15 +46,12 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
return nil, fmt.Errorf("post not found")
}
// Admin alone (the @admin on the field) is not enough: a post may only be
// edited by its author, so one admin cannot rewrite another's posts. This
// is the kind of rule a directive cannot express, so it stays here.
// Only the author may edit, even among admins.
if post.AuthorID != userID {
return nil, fmt.Errorf("you can only update your own posts")
}
// Both fields are non-pointer in the input, so this is a full replace —
// omitting one in the mutation blanks it rather than leaving it alone.
// Full replace: an omitted field is blanked.
post.Title = input.Title
post.Content = input.Content
if err := r.Store.DB.Save(&post).Error; err != nil {
@@ -84,9 +77,6 @@ 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 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
}
@@ -96,9 +86,7 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
// Posts is the resolver for the posts field.
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
// Preload issues a second query for the authors and fills in Post.Author.
// Without it the field is nil and the schema's author field resolves to
// null — there is no lazy loading and no error to tell you why.
// Without Preload, author resolves to null silently.
var posts []models.Post
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
return nil, err
+1 -11
View File
@@ -7,17 +7,7 @@ import "adam-french.co.uk/backend/handlers"
// It serves as dependency injection for your app, add any dependencies you require
// here.
// Resolver is the root of the GraphQL schema and the only dependency every
// resolver has. Rather than listing dependencies individually it holds the
// same handlers.Store the REST handlers use, so GraphQL and REST share one
// database handle and one set of third-party caches.
//
// The generated code embeds *Resolver in per-type resolver structs, which is
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
// resolvers files. A type only gets one when a field of it needs a resolver:
// queryResolver and mutationResolver always, messageResolver and
// rowingResolver for their unsigned-to-Int fields. Most object types bind
// every field straight to the model and have none.
// Resolver holds the same handlers.Store the REST handlers use.
type Resolver struct {
Store *handlers.Store
}
-2
View File
@@ -21,8 +21,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
}
// Time is the resolver for the time field.
// Time is the resolver for the time field: total session seconds, narrowed
// from uint64 to GraphQL's Int.
func (r *rowingResolver) Time(ctx context.Context, obj *models.Rowing) (int, error) {
return int(obj.Time), nil
}
+1 -7
View File
@@ -1,10 +1,4 @@
# The background behind a canvas page, keyed by the same page key as its
# boxes ("index" for the landing page, or a Page's slug), so the landing
# page and every other canvas page are set the same way. Edited from the
# canvas's "Background" button; see models.Background.
#
# Anyone may read it, as part of the page, except that an adminOnly page's
# background is null to everyone but an admin.
# A page key's background; null for an adminOnly page unless admin.
type Background {
id: ID!
+2 -10
View File
@@ -1,13 +1,5 @@
# Boxes on a canvas page: the landing page (page "index") or an
# admin-created Page (page = its slug; the home page /stp is the Page "stp").
# Anyone may read a page's layout — it is the page — but only an admin may
# change it, and adminOnly boxes are only ever returned to an admin. x/y/w/h
# are px on a fixed 1400px-wide design canvas; see models.Box.
#
# kind is "widget" (a built-in Vue component named by `widget`) or "html"
# (`html` rendered in a sandboxed iframe on the front end). An html box with a
# componentId is linked to that Component: its html is the component's, and
# updateBox refuses to change it (component.graphql).
# Boxes on a page key. Public reads, admin writes; adminOnly boxes go to
# admins only. kind is "widget" or "html" (sandboxed iframe).
type Box {
id: ID!
+2 -10
View File
@@ -1,13 +1,5 @@
# Components: named HTML boxes that can be placed on any canvas page, either
# as a copy (an ordinary box) or linked (a Box whose componentId is set).
# Linked boxes share only the html — editing a component changes every box
# linked to it — while title, geometry, frame and visibility stay each box's
# own. title, w, h, framed, shadow and adminOnly here are what a newly placed box
# starts with. See models.Component and graph/component_helpers.go.
#
# Admin only throughout, reads included, because a component may have been
# saved from an adminOnly note. A linked box's html still reaches visitors
# through the boxes query, which is the point.
# Named HTML boxes, placed as copies or linked (Box.componentId); linked boxes
# share only the html. Admin only, reads included.
type Component {
id: ID!
+3 -14
View File
@@ -1,12 +1,5 @@
# Saved layouts: a named copy of one canvas page's boxes and background,
# which can be loaded onto any canvas page — the landing page ("index") or a
# Page's slug. Loading copies: the new boxes belong to the target page, so
# editing a page afterwards never changes the layout or another page. Moving
# a layout is saving it on one page and loading it on another with
# replace: true. See models.Layout and graph/layout_helpers.go.
#
# Admin only throughout, reads included, because a layout keeps a page's
# adminOnly boxes along with the rest.
# Saved snapshots of a page's boxes and background; loading copies them.
# Admin only, reads included, since layouts keep adminOnly boxes.
type Layout {
id: ID!
@@ -39,10 +32,6 @@ extend type Mutation {
# Renames it; what a layout holds never changes after it is saved.
updateLayout(id: ID!, input: UpdateLayoutInput!): Layout! @admin
deleteLayout(id: ID!): Layout! @admin
# Copies the layout onto `page` and answers with that page's boxes.
# replace: false adds the copies on top of what is there, leaving the
# background alone. replace: true first saves the page as a layout named
# "<page> before <layout>, <time>", then swaps its boxes and background
# for the layout's.
# replace: true first saves the page as a layout, then swaps in this one.
applyLayout(id: ID!, page: String!, replace: Boolean!): [Box!]! @admin
}
+4 -29
View File
@@ -1,35 +1,10 @@
# Root of the GraphQL schema.
#
# Query and Mutation are declared here with no fields; every other file in this
# directory adds to them with `extend type Query` / `extend type Mutation`.
# That is what lets the schema be split one file per domain, matching the
# one-file-per-domain resolver layout (gqlgen.yml uses layout: follow-schema).
#
# Time is mapped to Go's time.Time by gqlgen's default scalar handling and is
# serialised as RFC 3339.
#
# These files are the source of truth: after editing one, run
# go run github.com/99designs/gqlgen generate
# from backend/ to regenerate graph/generated.go and graph/model/models_gen.go.
# Note that `#` comments like this one are invisible to clients; a `"""` block
# would become a schema description and show up in introspection.
# Root types; each file extends Query and Mutation. Use # comments, not """
# (descriptions show up in introspection).
scalar Time
# Authorisation. There is no middleware in front of /graphql, so a field is
# PUBLIC unless it carries one of these. Each is implemented once, in
# graph/directives.go, and runs before the field's resolver:
#
# @admin the request must carry an admin's access token
# (error: "admin access required")
# @signedIn any valid access token will do
# (error: "authentication required")
#
# Every mutation needs one of them unless it is deliberately public (login,
# logout, refreshToken); graph/directives_test.go fails otherwise, and pins
# which queries are guarded. Rules that are not a plain gate stay in the
# resolver: a post is only editable by its author, `me` answers for whoever is
# signed in, and `messages` filters private rows rather than refusing.
# A field is public unless it has @admin or @signedIn (graph/directives.go).
# directives_test.go enforces this for mutations.
directive @admin on FIELD_DEFINITION
directive @signedIn on FIELD_DEFINITION
+2 -9
View File
@@ -3,15 +3,8 @@ 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.
// ptrs turns []T into []*T for gqlgen. Loading into []*T directly would
// change the SQL GORM emits.
func ptrs[T any](xs []T) []*T {
result := make([]*T, len(xs))
for i := range xs {
+1 -5
View File
@@ -51,11 +51,7 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
}
// SpotifyNeedsReauth is the resolver for the spotifyNeedsReauth field.
//
// Admin-gated: false for everyone else, so this query leaks nothing. Admin is
// read from the access-token claims the AuthContextMiddleware resolved, not
// the database — the same trade-off AdminMiddleware makes (revocation waits
// for token expiry).
// False for non-admins.
func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
if r.Store.SpotifyClient != nil {
return false, nil
+1 -8
View File
@@ -5,10 +5,6 @@ import (
"github.com/zmb3/spotify/v2"
)
// Converters from the Spotify library's rich types to the deliberately narrow
// GraphQL types — the schema exposes only the handful of fields the home page
// renders.
// mapSpotifyImages keeps just the URLs of a set of album images.
func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
result := make([]*model.SpotifyImage, len(images))
@@ -35,10 +31,7 @@ func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
}
// mapRecentItems converts recently played history entries.
//
// It rebuilds the track inline instead of calling mapSpotifyTrack because a
// RecentlyPlayedItem holds a SimpleTrack, not the FullTrack that function
// takes — the duplication is forced by the library's types.
// A RecentlyPlayedItem holds a SimpleTrack, so mapSpotifyTrack can't be reused.
func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem {
result := make([]*model.SpotifyRecentItem, len(items))
for i, item := range items {
+1 -4
View File
@@ -8,10 +8,7 @@ import (
)
// mapSteamGames converts Steam API games into the GraphQL shape.
//
// HeaderImageURL is synthesised rather than returned by the API: Steam's CDN
// serves every game's cover art at a predictable path keyed by app id, so
// building the URL here saves an extra API call per game.
// Header images follow a predictable CDN path, saving an API call per game.
func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame {
result := make([]*model.SteamGame, len(games))
for i, g := range games {
+4 -12
View File
@@ -18,9 +18,6 @@ import (
// CreateUser is the resolver for the createUser field.
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
// Only an existing admin can create accounts (@admin in the schema) —
// there is no public sign-up. New users are created non-admin;
// setUserAdmin promotes them.
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
if err != nil {
return nil, err
@@ -55,8 +52,7 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
return nil, fmt.Errorf("unauthorized")
}
// Guards against the last admin demoting themselves and locking everyone
// out of the admin UI.
// Stops the last admin locking everyone out.
if uint(id) == callerID {
return nil, fmt.Errorf("cannot change your own admin status")
}
@@ -76,10 +72,8 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
// SetUserPermissions is the resolver for the setUserPermissions field.
func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) {
// The whole list is replaced, so the admin panel sends every ticked box
// each time. An unknown key is refused rather than dropped, so a stale
// front end cannot silently save less than it showed. The stored list is
// rebuilt in registry order, which also drops duplicates.
// Full replace. Unknown keys are refused so a stale UI can't silently
// save less than it showed.
want := map[string]bool{}
for _, key := range permissions {
if !services.ValidPermission(key) {
@@ -99,8 +93,7 @@ func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permi
return nil, fmt.Errorf("user not found")
}
// No token bump needed: the permission gate reads this column on every
// request, so the change applies to the user's next one.
// No token bump: the gate reads this column on every request.
user.Permissions = granted
if err := r.Store.DB.Save(&user).Error; err != nil {
return nil, err
@@ -129,6 +122,5 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
// PermissionTypes is the resolver for the permissionTypes field.
func (r *queryResolver) PermissionTypes(ctx context.Context) ([]*services.PermissionType, error) {
// A copy, so nothing downstream can write through to the registry.
return ptrs(slices.Clone(services.PermissionTypes)), nil
}
+32 -126
View File
@@ -12,62 +12,36 @@ import (
"golang.org/x/crypto/bcrypt"
)
// This file holds the REST authentication endpoints and the Gin middleware
// that guards the other REST routes. GraphQL has its own parallel
// implementation of login/logout/refresh in graph/auth.resolvers.go; both
// mint the same cookies through services.Auth.
//
// Cookie model: `access_token` is short-lived and carries id + admin, so most
// requests authorise without a database hit; `refresh_token` carries only the
// id and is exchanged for a fresh pair. Both are set HttpOnly and Secure, so
// JavaScript cannot read them and the browser attaches them automatically.
// REST auth endpoints and middleware. GraphQL's login/logout/refresh live in
// graph/auth.resolvers.go; both mint cookies through services.Auth.
// UserCredentials is the JSON body of POST /auth/login. The binding tags make
// Gin reject a request missing either field.
type UserCredentials struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// AuthMiddlewear requires a valid access token on a REST route and stashes
// the claims for AdminMiddleware to read.
//
// (The name is misspelled but it is exported and referenced from main.go, so
// it is left alone rather than renamed.)
//
// It deliberately does NOT fall back to the refresh token: an expired access
// token yields a 401 and the front end is expected to call /auth/refresh and
// retry. A token whose version has been revoked is also a 401.
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
// AuthMiddleware requires a valid, unrevoked access token. It does not fall
// back to the refresh token: the client refreshes and retries on 401.
func (store *Store) AuthMiddleware(ctx *gin.Context) {
access_token, err := ctx.Cookie("access_token")
if err != nil {
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
return
}
// Validated against the database, not just cryptographically: that is
// what makes a logged-out or password-changed token stop working here
// rather than lingering until it expires.
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, access_token)
if err != nil {
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
return
}
// Stored under a plain string key in the *Gin* context. This is a
// different mechanism from graph/context.go, which puts the same claims
// into the standard library request context under an unexported typed
// key; the two do not see each other's values.
// Gin context key; graph/context.go uses its own, separate mechanism.
ctx.Set("userClaims", claims)
ctx.Next()
}
// AdminMiddleware requires the access token to carry admin=true. It must be
// chained after AuthMiddlewear, which is what populates "userClaims"; on its
// own it always rejects.
//
// Admin is read from the token, not the database, so revoking someone's admin
// flag only takes effect once their current access token expires.
// AdminMiddleware must follow AuthMiddleware. Admin comes from the token, so
// a revoked flag applies once the access token expires.
func (store *Store) AdminMiddleware(ctx *gin.Context) {
claims, exists := ctx.Get("userClaims")
if !exists {
@@ -81,8 +55,7 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
return
}
// A token minted before the admin claim existed simply has no "admin"
// key, so a failed type assertion is treated as "not an admin".
// Tokens minted before the admin claim have none: not an admin.
admin, ok := (*mapClaims)["admin"].(bool)
if !ok || !admin {
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
@@ -92,20 +65,12 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
ctx.Next()
}
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
// decide whether to show admin UI, Caddy's admin gate calls as an
// auth_request, and the jobs container calls with the visitor's cookies. It
// answers with a bare status code and no body: 200 admin, 403 authenticated
// but not admin, 401 not authenticated.
//
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
// new cookie pair as a side effect, so a returning admin is recognised
// without a visible re-login.
// ValidateAdmin answers 200/403/401 with no body, for the SPA, Caddy's admin
// gate and the jobs container. It falls back to the refresh token and may
// mint new cookies, so a returning admin needn't log in again.
func (store *Store) ValidateAdmin(ctx *gin.Context) {
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
// On the access-token path admin is read from the token, as
// everywhere else; on the refresh path there is no admin claim, and
// the row is what makes that path pick up a revoked admin flag.
// The refresh path has no admin claim, so it reads the row.
if claims == nil {
return user.Admin
}
@@ -114,15 +79,9 @@ func (store *Store) ValidateAdmin(ctx *gin.Context) {
})
}
// ValidatePermission backs GET /auth/validate/:permission, Caddy's permission
// gate (see services/permissions.go). Same bare-status contract and refresh
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the
// permission, 401 not signed in — plus 404 for a key that is not in
// services.PermissionTypes, so a typo in a Caddy route fails closed and
// visibly rather than as a 403 that looks like a missing grant.
//
// The decision reads the user row, not the token, for admins as well: a
// grant, a revoke or a demotion applies on the very next request.
// ValidatePermission backs Caddy's permission gate, like ValidateAdmin but
// reading the user row. An unknown key is 404, so a typo in a Caddy route
// fails visibly rather than looking like a missing grant.
func (store *Store) ValidatePermission(ctx *gin.Context) {
key := ctx.Param("permission")
if !services.ValidPermission(key) {
@@ -134,17 +93,9 @@ func (store *Store) ValidatePermission(ctx *gin.Context) {
})
}
// validateSession is the body shared by the two validate endpoints: identify
// the caller from the access token, or failing that the refresh token, and
// answer 200 / 403 / 401 according to allow.
//
// allow receives the access token's claims, or nil when the caller was
// identified from the refresh token (which carries no authorisation claims).
//
// On 200 the username goes back in X-Auth-User, which Caddy's forward_auth
// copies onto the proxied request (as X-Remote-User for /receipt/), so the
// service behind the gate knows who is using it without having accounts of
// its own.
// validateSession identifies the caller by access token, else refresh token
// (allow then gets nil claims), and answers 200/403/401. On 200 the username
// goes in X-Auth-User for Caddy to pass upstream.
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
accessToken, err := ctx.Cookie("access_token")
if err == nil {
@@ -160,27 +111,19 @@ func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *
}
}
// No access token, or an expired, invalid or revoked one — try refreshing.
if !store.tryRefreshAndValidate(ctx, allow) {
ctx.Status(http.StatusUnauthorized)
}
}
// tryRefreshAndValidate re-authenticates from the refresh token.
//
// The bool does not mean "allowed" — it means "this function already wrote
// the response". It returns true both for a successful refresh (200, new
// cookies set) and for a valid but unauthorised user (403, no new cookies),
// and false only when it could not decide, leaving the caller to send 401.
// Getting this backwards would send two status codes for one request.
// tryRefreshAndValidate returns whether it wrote the response (200 or 403),
// not whether access is allowed. On false the caller sends 401.
func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
return false
}
// Any failure at all (bad token, unknown user, revoked version) is
// "cannot decide" here, exactly as before: the caller sends 401.
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil {
return false
@@ -203,17 +146,12 @@ func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.U
return true
}
// setAuthCookies writes the access/refresh cookie pair. The cookie
// attributes live in services.SetAuthCookies so that REST and GraphQL cannot
// disagree about them; this method is just the Store-shaped spelling of it.
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
services.SetAuthCookies(ctx, store.Auth.Config, tokens)
}
// CheckToken backs GET /auth/check: it returns the current user for a valid
// access token, or 401. If the token is valid but the user no longer exists
// it answers 404 and clears the cookies, so the browser stops presenting a
// token for a deleted account.
// CheckToken returns the current user. A valid token for a deleted user gets
// 404 and cleared cookies.
func (store *Store) CheckToken(ctx *gin.Context) {
access_token, err := ctx.Cookie("access_token")
if err != nil {
@@ -221,11 +159,6 @@ func (store *Store) CheckToken(ctx *gin.Context) {
return
}
// Status codes here are unchanged from the hand-rolled version: a bad
// token or bad claims are both 401, and only a missing user is 404 with
// the cookies cleared. A revoked (out-of-date version) token joins the
// 401 case, since from the client's point of view it is simply no longer
// a valid token.
user, err := store.Auth.AuthenticateToken(store.DB, access_token)
if err != nil {
if errors.Is(err, services.ErrUserNotFound) {
@@ -241,11 +174,8 @@ func (store *Store) CheckToken(ctx *gin.Context) {
ctx.JSON(http.StatusOK, user)
}
// RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token
// for a new cookie pair and returns the user.
//
// The old refresh token is not rotated, but it does die when the user logs out
// or changes their password, because those bump the token version this checks.
// RefreshToken exchanges the refresh token for a new pair. It is not rotated,
// but logout and password changes revoke it via the token version.
func (store *Store) RefreshToken(ctx *gin.Context) {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
@@ -253,11 +183,6 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
return
}
// The three outcomes below preserve the original status codes exactly:
// an unusable token is 401, unreadable claims are 500, and a token for a
// user that no longer exists is 404 with the cookies cleared. A revoked
// token is treated as an unusable one (401) — the client's correct
// response is to log in again.
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil {
switch {
@@ -285,13 +210,9 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
ctx.JSON(http.StatusAccepted, user)
}
// Login backs POST /auth/login. The user object it returns omits the password
// because models.User tags that field `json:"-"`.
func (store *Store) Login(ctx *gin.Context) {
// Per-IP limit (5/min) on top of Caddy's own login rate limit.
// ctx.ClientIP is only trustworthy because main.go pins the trusted
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
// client talking through Caddy.
// On top of Caddy's limit. ClientIP is trustworthy because main.go pins
// the trusted proxy range.
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
return
@@ -303,9 +224,7 @@ func (store *Store) Login(ctx *gin.Context) {
return
}
// Unknown user and wrong password return the identical message, so the
// response cannot be used to enumerate usernames. (The timing does
// differ, since only the second path runs bcrypt.)
// Same message for unknown user and wrong password.
user := models.User{}
if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
@@ -329,13 +248,8 @@ func (store *Store) Login(ctx *gin.Context) {
ctx.JSON(http.StatusAccepted, user)
}
// Logout backs POST /auth/logout. As well as clearing the browser's cookies
// it bumps the user's token version, so the tokens it just discarded — and
// any copy taken beforehand — stop being accepted immediately.
//
// It always answers 200: identifying the caller is best effort (the cookies
// may already be gone or expired), and a client that cannot be identified has
// nothing to revoke anyway.
// Logout clears the cookies and bumps the token version, revoking every copy
// of the tokens. Always 200.
func (store *Store) Logout(ctx *gin.Context) {
store.revokeCallerTokens(ctx)
store.removeCookies(ctx)
@@ -343,12 +257,8 @@ func (store *Store) Logout(ctx *gin.Context) {
ctx.Status(http.StatusOK)
}
// revokeCallerTokens bumps the token version of whoever made this request,
// identified from the access token or, failing that, the refresh token.
//
// It deliberately verifies the token rather than just reading the id out of
// it: without that, anyone could bump an arbitrary user's version by posting a
// forged cookie, which is a denial-of-service on that account's sessions.
// revokeCallerTokens verifies the token before bumping, or a forged cookie
// could revoke any user's sessions.
func (store *Store) revokeCallerTokens(ctx *gin.Context) {
for _, name := range []string{"access_token", "refresh_token"} {
token, err := ctx.Cookie(name)
@@ -360,16 +270,12 @@ func (store *Store) revokeCallerTokens(ctx *gin.Context) {
continue
}
if err := services.BumpTokenVersion(store.DB, user.ID); err != nil {
// Logged rather than returned: the cookies are still cleared, but
// this means the logout did not actually revoke anything.
log.Printf("logout: failed to revoke tokens for user %d: %v", user.ID, err)
}
return
}
}
// removeCookies expires both auth cookies; see services.ClearAuthCookies for
// why the attributes have to match those used when setting them.
func (store *Store) removeCookies(ctx *gin.Context) {
services.ClearAuthCookies(ctx, store.Auth.Config)
}
+2 -7
View File
@@ -7,10 +7,7 @@ import (
"github.com/gin-gonic/gin"
)
// GetNoteFile serves one file from the notes directory for the admin-only
// route GET /notes/*path. The wildcard means `path` arrives with a leading
// slash and may contain further slashes, so it has to be validated rather
// than trusted — Notes.ParsePath does the containment check.
// GetNoteFile: Notes.ParsePath does the containment check.
func (store *Store) GetNoteFile(ctx *gin.Context) {
path := ctx.Param("path")
@@ -29,9 +26,7 @@ func (store *Store) GetNoteFile(ctx *gin.Context) {
return
}
// The SPA reads Last-Modified to show a note's edit date. Browsers hide
// non-safelisted headers from cross-origin fetch() unless they are listed
// in Access-Control-Expose-Headers, hence the second header.
// Exposed so cross-origin fetch() can read it.
ctx.Header("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
ctx.Header("Access-Control-Expose-Headers", "Content-Disposition, Last-Modified")
+13 -41
View File
@@ -9,27 +9,18 @@ import (
"github.com/gin-gonic/gin"
)
// Admin management of the radio's fallback music. These handlers only move
// files around on disk; the Python service is what actually streams them, and
// it picks up the directory contents on its own.
//
// Disabling a song moves it into a "disabled" subdirectory rather than
// deleting it — so presence in that directory IS the disabled flag, and there
// is no database state for the radio at all.
// Radio fallback music management. Disabled songs live in a "disabled"
// subdirectory: that is the whole of the radio's state.
// fallbackMusicDir is a shared volume, also mounted by the radio service.
const fallbackMusicDir = "/backend/fallback_music"
// allowedAudioExtensions is the upload allow-list, keyed by lower-cased
// extension. Unlike chat uploads, the content is not sniffed: the route is
// admin-only and audio formats sniff unreliably.
// Not sniffed: admin-only, and audio sniffs unreliably.
var allowedAudioExtensions = map[string]bool{
".mp3": true, ".ogg": true, ".flac": true, ".wav": true, ".m4a": true, ".opus": true,
}
// UploadRadioSong backs the admin-only POST /radio/upload. Unlike chat
// uploads the original filename is kept, because it is what the admin sees in
// the song list — hence the sanitisation below.
// UploadRadioSong keeps the original filename, which the admin sees, so it is
// sanitised.
func (store *Store) UploadRadioSong(ctx *gin.Context) {
file, err := ctx.FormFile("file")
if err != nil {
@@ -49,22 +40,18 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
return
}
// filepath.Base strips any directory component, so "../../etc/passwd"
// becomes "passwd". The absolute-path check below is a second, redundant
// guard in case Base ever fails to neutralise some input.
// Base strips traversal; the absolute-path check below is a second guard.
filename := filepath.Base(file.Filename)
dest := filepath.Join(fallbackMusicDir, filename)
// The separator is appended before comparing so a sibling directory whose
// name merely starts with the same characters cannot pass.
// The trailing separator stops a same-prefix sibling directory passing.
absDest, err := filepath.Abs(dest)
if err != nil || !strings.HasPrefix(absDest, fallbackMusicDir+string(os.PathSeparator)) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
return
}
// Refuse to overwrite. There is a check-then-write race here, but the
// route is admin-only and single-user in practice.
// Check-then-write race accepted: admin-only.
if _, err := os.Stat(dest); err == nil {
ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"})
return
@@ -78,11 +65,7 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"name": filename})
}
// ListRadioSongs backs the admin-only GET /radio/songs, returning both the
// enabled songs and those parked in the disabled subdirectory, flagged.
func (store *Store) ListRadioSongs(ctx *gin.Context) {
// Declared inside the function because it is purely the JSON shape of
// this one response.
type songInfo struct {
Name string `json:"name"`
Size int64 `json:"size"`
@@ -90,17 +73,15 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
Disabled bool `json:"disabled"`
}
// Initialised empty rather than nil so the response is [] and not null.
// [] not null in the JSON.
songs := []songInfo{}
// Read enabled songs
entries, err := os.ReadDir(fallbackMusicDir)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read music directory"})
return
}
// Skipping directories is also what keeps the "disabled" subdirectory out
// of the enabled list; dotfiles skip editor and OS cruft.
// Skipping directories also skips "disabled".
for _, entry := range entries {
if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
continue
@@ -117,9 +98,7 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
})
}
// The disabled directory is created lazily by DisableRadioSong, so a read
// failure here is normally just "nothing has ever been disabled" and is
// ignored rather than reported.
// Created lazily, so a missing directory just means none disabled.
disabledDir := filepath.Join(fallbackMusicDir, "disabled")
disabledEntries, err := os.ReadDir(disabledDir)
if err == nil {
@@ -143,12 +122,8 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"songs": songs})
}
// DisableRadioSong moves a song into the disabled subdirectory so the radio
// stops playing it, keeping the file.
func (store *Store) DisableRadioSong(ctx *gin.Context) {
// filepath.Base neutralises traversal in the :filename route parameter.
// It returns "." for an empty input and "/" for "/", neither of which is
// a real file, so both are rejected explicitly.
// Base returns "." or "/" for degenerate input; both are rejected.
filename := filepath.Base(ctx.Param("filename"))
if filename == "." || filename == "/" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
@@ -176,7 +151,6 @@ func (store *Store) DisableRadioSong(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"disabled": filename})
}
// EnableRadioSong moves a song back out of the disabled subdirectory.
func (store *Store) EnableRadioSong(ctx *gin.Context) {
filename := filepath.Base(ctx.Param("filename"))
if filename == "." || filename == "/" {
@@ -199,9 +173,7 @@ func (store *Store) EnableRadioSong(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"enabled": filename})
}
// DeleteRadioSong permanently removes an enabled song. It cannot reach the
// disabled subdirectory, so a disabled song must be enabled before it can be
// deleted.
// DeleteRadioSong can't reach disabled songs; enable one first.
func (store *Store) DeleteRadioSong(ctx *gin.Context) {
filename := filepath.Base(ctx.Param("filename"))
if filename == "." || filename == "/" {
+22 -68
View File
@@ -15,51 +15,30 @@ import (
"gorm.io/gorm"
)
// Rowing log. The interesting endpoint is CreateRowing: rather than a form,
// the admin uploads a photo of the rowing machine display and Claude reads the
// numbers off it. The session date comes from the photo's EXIF metadata, which
// also doubles as the deduplication key.
//
// The Claude call itself lives in the Python service (python/app/rowing.py),
// reached directly over the Docker network. Everything that needs the session
// or the database — the admin gate, EXIF, the duplicate check, the sanity
// bounds, the insert — stays here.
// CreateRowing reads a photo of the rowing machine display. The Claude call
// is in python/app/rowing.py; auth, EXIF, dedup and bounds checks stay here.
// ExtractedRowingData is the JSON contract for what Claude reads off the
// display: the body of the Python service's reply, whose keys are the ones
// its prompt asks the model for (RowingReading in python/app/rowing.py).
// ExtractedRowingData matches RowingReading in python/app/rowing.py.
type ExtractedRowingData struct {
TimeMinutes uint64 `json:"timeMinutes"`
TimeSeconds uint64 `json:"timeSeconds"`
Distance uint64 `json:"distance"`
}
// rowingReadPath is the Python route. It is internal: Caddy refuses
// /py/internal/ and the route itself refuses anything Caddy forwarded, so the
// only way in is the direct container-to-container call services.CallPython
// makes.
// Internal: Caddy refuses /py/internal/, so only a direct container call works.
const rowingReadPath = "/internal/rowing/read"
// readRowingDisplay sends the image to the Python service and returns what
// Claude read off it. No plausibility checking happens on either side of this
// call; that is CreateRowing's job. A failure the reader described in its own
// words comes back as a *services.PythonError (see services.CallPython).
func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) {
// Data is a []byte so that it is sent as standard base64, the encoding
// the Anthropic API expects.
// []byte marshals as standard base64, as the Anthropic API expects.
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
MediaType string `json:"media_type"`
Data []byte `json:"data"`
}{mediaType, image})
}
// GetRowing backs the public GET /rowing with every logged session, newest
// first.
func (store *Store) GetRowing(ctx *gin.Context) {
var rowing []models.Rowing
// "Created_At" works because Postgres folds unquoted identifiers to lower
// case; the column is created_at.
if err := store.DB.Order("Created_At DESC").Find(&rowing).Error; err != nil {
if err := store.DB.Order("created_at DESC").Find(&rowing).Error; err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
@@ -67,13 +46,8 @@ func (store *Store) GetRowing(ctx *gin.Context) {
ctx.JSON(http.StatusOK, rowing)
}
// CreateRowing backs the admin-only POST /rowing: it takes a photo of the
// rowing machine display, dates it from EXIF, has Claude read the time and
// distance (via the Python service), sanity-checks the result and stores a
// session.
//
// Note it is admin-gated and costs a paid API call once per request, so the
// validation below exists to catch misreadings rather than hostile input.
// CreateRowing is admin-only, so its checks target misreadings, not hostile
// input.
func (store *Store) CreateRowing(ctx *gin.Context) {
file, err := ctx.FormFile("image")
if err != nil {
@@ -88,9 +62,7 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
}
defer f.Close()
// EXIF is required, not optional: it is both the session date and the
// duplicate key, so a stripped-metadata image (anything that has been
// through most messaging apps) is rejected outright.
// EXIF is required: it is both the session date and the duplicate key.
exifData, err := exif.Decode(f)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no EXIF data found"})
@@ -103,19 +75,14 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
return
}
// exif.Decode consumed part of the stream, so rewind before reading the
// bytes to send on for reading.
if _, err := f.Seek(0, io.SeekStart); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"})
return
}
// Cap the upload before buffering it (and then base64-encoding it, 1.33x
// bigger, on its way to the Python service): the route is admin-only but
// an unbounded read would still let a giant file exhaust the Pi's memory
// and produce a huge paid API call. 10MB is well above any photo this
// endpoint is meant to take; the Python side's own limit is sized from it.
if file.Size > 10<<20 {
// Bounded before buffering, to cap memory and the paid API call.
const maxPhotoSize = 10 << 20
if file.Size > maxPhotoSize {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"})
return
}
@@ -132,24 +99,16 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
"image/gif": true,
"image/webp": true,
}
// This is the browser's claimed type, not a sniffed one; it is passed
// straight through to the Anthropic API, so the allow-list is there to
// keep the API call well-formed rather than to police the file. The
// Python service enforces the same list; checking here first gives the
// admin a clear 400 instead of that side's validation error.
// The browser's claimed type, checked only to keep the API call
// well-formed and give a clear 400.
mediaType := file.Header.Get("Content-Type")
if !allowedMediaTypes[mediaType] {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
return
}
// Duplicate guard: two photos of the same session share an EXIF capture
// time to the second. Checked before the Claude call so a re-upload costs
// nothing.
//
// Fails closed: only gorm.ErrRecordNotFound means "no duplicate". Any
// other error is a real database problem, and treating it as "not found"
// would both insert a duplicate and spend a paid Claude call to do it.
// Checked before the paid call. Fails closed: only ErrRecordNotFound
// means "no duplicate".
var existing models.Rowing
err = store.DB.Where("date = ?", dateTaken).First(&existing).Error
switch {
@@ -165,9 +124,7 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data)
if err != nil {
log.Println(err)
// The reader's own messages ("failed to parse image data", ...) are
// passed on; anything else is a plumbing failure the admin can do
// nothing with.
// Pass on the reader's own messages; hide plumbing failures.
msg := "failed to process image"
var readErr *services.PythonError
if errors.As(err, &readErr) {
@@ -184,10 +141,8 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds
// Sanity bounds on what Claude claims to have read. A misread digit
// typically lands far outside human rowing performance, and the pace
// check catches the case where time and distance are individually
// plausible but inconsistent with each other.
// A misread digit usually lands outside human performance; the pace check
// catches plausible time and distance that disagree.
const (
minDistance = 100 // metres
maxDistance = 100000 // metres
@@ -211,10 +166,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
return
}
// Rough calorie estimate from distance alone: roughly 500 kcal per
// 7500 m. Not from the machine and not physiologically derived — it is a
// display figure only.
calories := float64(extractedData.Distance) / 7500.0 * 500.0
// A display-only estimate, ~500 kcal per 7500 m.
const kcalPerMetre = 500.0 / 7500.0
calories := float64(extractedData.Distance) * kcalPerMetre
rowing := models.Rowing{
Date: dateTaken,
+9 -37
View File
@@ -10,35 +10,22 @@ import (
"github.com/zmb3/spotify/v2"
)
// These REST endpoints predate the equivalent GraphQL queries in
// graph/spotify.resolvers.go and are kept for the OAuth callback (which must
// be REST, because Spotify redirects a browser to it) and for direct use.
// The callback must be REST (Spotify redirects a browser to it); the rest
// predate the GraphQL equivalents.
// CompleteSpotifyAuth handles Spotify's OAuth redirect to
// GET /spotify/callback. It swaps the code for a token, saves it so the
// authorisation survives restarts, and installs the authenticated client on
// the Store — which is how Store.SpotifyClient becomes non-nil without a
// restart.
// CompleteSpotifyAuth installs the client on the Store, so no restart is needed.
func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
state := ctx.Query("state")
// CSRF check: the state must be a nonce this process handed out from
// StartSpotifyAuth and has not seen come back yet. Without it, anyone who
// could get the site owner's browser to hit this URL with an attacker's
// authorisation code would bind the site to the attacker's Spotify
// account. The library also compares the state to the value passed below,
// but since that value is the one just received, this check is the real
// one.
// The real CSRF check: the library compares state against the value we
// pass it, which is the one just received.
if !store.ConsumeSpotifyState(state) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid state"})
return
}
// context.Background, not the request context: the client built below
// outlives this request and would otherwise be cancelled when it ends.
// The client outlives this request.
c := context.Background()
// The library pulls the `code` out of the request itself and checks the
// state parameter matches the one passed here.
token, err := store.SpotifyAuth.Token(c, state, ctx.Request)
if err != nil {
log.Println(err)
@@ -61,13 +48,7 @@ func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
})
}
// StartSpotifyAuth backs the admin-only GET /spotify/auth. It returns the
// Spotify authorisation URL carrying a freshly minted one-shot state nonce,
// which CompleteSpotifyAuth then verifies and consumes.
//
// This exists because the state has to be per-request to be a CSRF defence,
// and the start of the flow therefore has to be a request rather than a line
// printed at start-up.
// StartSpotifyAuth returns the authorisation URL with a fresh state nonce.
func (store *Store) StartSpotifyAuth(ctx *gin.Context) {
state, err := store.NewSpotifyState()
if err != nil {
@@ -79,9 +60,6 @@ func (store *Store) StartSpotifyAuth(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"url": store.SpotifyAuth.AuthURL(state)})
}
// ListeningTo backs GET /spotify/listening with the currently playing track.
// A nil client means the OAuth flow has never been completed, reported here
// as a 500.
func (store *Store) ListeningTo(ctx *gin.Context) {
c := ctx.Request.Context()
@@ -100,9 +78,7 @@ func (store *Store) ListeningTo(ctx *gin.Context) {
ctx.JSON(200, playing)
}
// RecentlyPlayed backs GET /spotify/recent, serving the shared one-minute
// cache. Both this endpoint and the GraphQL spotifyRecent resolver go through
// RecentlyPlayedTracks, so either one can fill the cache for the other.
// RecentlyPlayed shares its cache with the GraphQL spotifyRecent resolver.
func (store *Store) RecentlyPlayed(ctx *gin.Context) {
if store.SpotifyClient == nil {
ctx.JSON(500, gin.H{"error": "Spotify not authenticated"})
@@ -119,11 +95,7 @@ func (store *Store) RecentlyPlayed(ctx *gin.Context) {
ctx.JSON(200, played)
}
// RecentlyPlayedTracks returns the last few played tracks, from the cache when
// it is fresh and from Spotify otherwise — populating the cache in that case.
//
// This is the single fetch-and-cache path for recently-played data; the caller
// must have checked SpotifyClient is non-nil.
// RecentlyPlayedTracks requires a non-nil SpotifyClient.
func (store *Store) RecentlyPlayedTracks(ctx context.Context) ([]spotify.RecentlyPlayedItem, error) {
if cached, ok := store.CachedRecentSongs(); ok {
return cached, nil
+5 -25
View File
@@ -10,19 +10,8 @@ import (
"github.com/golang-jwt/jwt/v5"
)
// Upload backs POST /uploads (login required): the one endpoint the frontend
// stores a file through (vue/src/uploads.js). Multipart form:
//
// file the file (required)
// private "true" to store it as an admin-only chat attachment
//
// It answers {"url": "/uploads/<name>"}, or {"error": "..."} with 400 when
// the file was refused (wrong type, too large) and 500 when storing failed.
// Validation, naming and storage are all services.Uploads.Save; this handler
// only reads the form and decides who may use `private`.
//
// `private` is admin-only because private messages themselves are: an
// attachment URL leaking out is the same disclosure as the message leaking.
// Upload stores a multipart `file` via services.Uploads.Save and returns its
// URL. `private` is admin-only, as private messages are.
func (store *Store) Upload(ctx *gin.Context) {
private := ctx.PostForm("private") == "true"
if private && !requestIsAdmin(ctx) {
@@ -49,12 +38,7 @@ func (store *Store) Upload(ctx *gin.Context) {
}
}
// ListUploads backs GET /uploads (admin): every public upload, newest first,
// for the upload picker on the canvas pages (vue/src/components/util/
// UploadPicker.vue). It answers {"files": [{name, url, size, modified}]}.
//
// Admin-only because the listing is the one thing that turns unguessable
// upload URLs into known ones; see services.Uploads.List.
// ListUploads is admin-only: listing is what turns unguessable URLs into known ones.
func (store *Store) ListUploads(ctx *gin.Context) {
files, err := store.Uploads.List(ctx.Request.Context())
if err != nil {
@@ -68,12 +52,8 @@ func (store *Store) ListUploads(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"files": files})
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
// public attachments — so the admin check is made here from the same
// "userClaims" value AdminMiddleware would have read.
// requestIsAdmin: this route is in `protected`, not `admin`, since any
// signed-in user may upload public files.
func requestIsAdmin(ctx *gin.Context) bool {
claims, exists := ctx.Get("userClaims")
if !exists {
+7 -33
View File
@@ -12,24 +12,8 @@ import (
"github.com/zmb3/spotify/v2"
)
// What is deliberately NOT covered here, and why:
//
// - Every handler method (Login, Upload, the radio file movers,
// the Spotify and email endpoints). They all need a live *gorm.DB, a real
// multipart request, the container's /backend/... directories, or a paid
// Claude call. Only postgres is in go.mod, so a DB would mean a server in
// CI.
// - The radio upload's filename sanitisation. It is written inline in the
// handler, so only the extension allow-list it gates on is covered, as a
// table contract below. (The site's general uploads — validation, naming,
// storage — are services.Uploads, tested in services/uploads_test.go.)
// - Store.isAdminRequest, and the validate endpoints past their first
// check: they authenticate against the database. The allow/deny rule the
// permission gate applies is services.HasPermission, tested there.
//
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
// three shared caches, the admin claim check on the upload trust boundary, and
// the radio allow-list.
// Handlers needing a live DB, multipart requests or container paths aren't
// covered here.
// --- Spotify OAuth CSRF nonces -------------------------------------------
@@ -115,15 +99,13 @@ func TestNewSpotifyStatePrunesExpired(t *testing.T) {
// --- Cache TTL rules ------------------------------------------------------
// Each cache treats "empty" as stale, which is deliberate (an empty listening
// history or games list is re-fetched rather than cached). These tables pin
// that down so it cannot be "fixed" into caching emptiness by accident.
// Empty counts as stale on purpose; pinned so it isn't "fixed".
func TestCachedRecentSongsFreshness(t *testing.T) {
song := []spotify.RecentlyPlayedItem{{}}
cases := []struct {
name string
setup func(s *Store)
name string
setup func(s *Store)
wantOK bool
}{
{"never fetched", func(*Store) {}, false},
@@ -215,9 +197,6 @@ func TestCachedSteamFreshness(t *testing.T) {
// --- Upload trust boundary ------------------------------------------------
// requestIsAdmin gates private (admin-only) attachment uploads, so every way
// the claim can be absent or the wrong shape must read as "not admin". No DB
// or network is involved: it only inspects the Gin context.
func TestRequestIsAdmin(t *testing.T) {
gin.SetMode(gin.TestMode)
@@ -231,7 +210,7 @@ func TestRequestIsAdmin(t *testing.T) {
}{
{"no claims in context at all", nil, false},
{"claims of the wrong type are not trusted", "not-claims", false},
// A by-value jwt.MapClaims is not what AuthMiddlewear stores; accepting
// A by-value jwt.MapClaims is not what AuthMiddleware stores; accepting
// it would mean the type assertion had been loosened.
{"claims stored by value rather than by pointer", jwt.MapClaims{"admin": true}, false},
{"pre-admin-claim token has no admin key", claims(jwt.MapClaims{"id": 1.0}), false},
@@ -254,9 +233,7 @@ func TestRequestIsAdmin(t *testing.T) {
// --- Permission gate ------------------------------------------------------
// An unknown key must be refused before any session lookup (Store has no DB
// or Auth here, so reaching one would panic): it is how a typo in a Caddy
// location shows up as a 404 rather than as a missing grant.
// Must 404 before any session lookup (a nil Store would panic).
func TestValidatePermissionUnknownKey(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Store{}
@@ -272,9 +249,6 @@ func TestValidatePermissionUnknownKey(t *testing.T) {
}
}
// The radio allow-list is the radio upload's trust boundary. Testing it as
// data catches the realistic failure: someone adding a non-audio or malformed
// extension.
func TestRadioAllowList(t *testing.T) {
for ext := range allowedAudioExtensions {
// The handler looks up strings.ToLower(filepath.Ext(...)), so a key in
+15 -65
View File
@@ -13,18 +13,8 @@ import (
"gorm.io/gorm"
)
// Package handlers holds the REST endpoints and the shared Store that every
// request handler — and, through graph.Resolver, every GraphQL resolver —
// depends on.
//
// Store is the backend's dependency container: it is built once in main and
// passed around by pointer, so the caches on it are shared process-wide.
//
// Concurrency note: the third-party caches below are read and written by
// concurrent requests, so every access goes through cacheMu and the accessor
// methods at the bottom of this file. Do not touch the cache fields directly
// — an unsynchronised read of one of them is a data race, not merely a stale
// value.
// Store is the dependency container shared by every handler and resolver.
// Cache fields are guarded by cacheMu: use the accessors, never the fields.
type Store struct {
DB *gorm.DB
SpotifyAuth *spotifyauth.Authenticator
@@ -33,63 +23,43 @@ type Store struct {
Notes *services.Notes
LoginLimiter *services.RateLimiter
// Base URL of the Python service on the Docker network, no trailing
// slash. Used for the calls that bypass Caddy, all through
// services.CallPython: reading a rowing display photo (handle_rowing.go).
// The Python service on the Docker network, no trailing slash.
PythonURL string
// Stores uploaded files and says where they are served
// (services.Uploads.Save). Used by the Upload handler.
Uploads *services.Uploads
// Cached "recently played" tracks, refreshed at most once a minute by the
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
// mean "never fetched" distinctly from "fetched, empty".
// cacheMu guards every cache field below (and only those). One mutex for
// all of them keeps the locking obvious; the critical sections are just
// field copies, never network calls, so there is no contention worth
// splitting it up for.
cacheMu sync.RWMutex
RecentSongs *[]spotify.RecentlyPlayedItem
RecentSongsFetchedAt time.Time
// Cached latest Gitea activity entry, 1 minute TTL.
// 1 minute TTL.
GiteaHost string
GiteaPort string
GiteaFeed *services.GiteaFeedResponse
GiteaFeedFetchedAt time.Time
// Cached Steam status and recent games, 5 minute TTL.
// 5 minute TTL.
SteamAPIKey string
SteamID string
SteamRecentGames []services.SteamRecentGame
SteamOnline bool
SteamFetchedAt time.Time
// spotifyStates holds the one-shot CSRF nonces handed out by
// GET /spotify/auth, mapped to their creation time. In-memory is enough:
// there is one backend instance, and losing them on restart only means
// restarting an OAuth flow that takes seconds.
// One-shot OAuth CSRF nonces. In memory: a lost nonce only restarts a
// seconds-long flow.
spotifyStatesMu sync.Mutex
spotifyStates map[string]time.Time
// spotifyNilLoggedAt rate-limits the "Spotify not authenticated" log line:
// every page visit hits spotifyRecent, so an unauthenticated backend would
// otherwise write a flood of identical lines. nil means "recently logged".
// Every page visit would otherwise log "Spotify not authenticated".
spotifyNilLoggedMu sync.Mutex
spotifyNilLoggedAt time.Time
}
// spotifyStateTTL is how long an unused Spotify OAuth nonce stays valid. Long
// enough to log in at Spotify and approve the scopes, short enough that a
// leaked authorisation URL is not reusable later.
const spotifyStateTTL = 10 * time.Minute
// NewSpotifyState mints a one-shot CSRF nonce for the Spotify authorisation
// URL and remembers it. Expired entries are pruned on the way through, which
// is the only cleanup there is — the map is otherwise unbounded, and only an
// admin can add to it.
// NewSpotifyState mints a nonce. Pruning here is the only cleanup; only an
// admin can add entries.
func (s *Store) NewSpotifyState() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
@@ -112,9 +82,7 @@ func (s *Store) NewSpotifyState() (string, error) {
return state, nil
}
// ConsumeSpotifyState checks a nonce returned by Spotify's redirect and
// removes it, so a replayed callback fails. An unknown or expired nonce
// returns false, which the callback must treat as a rejected request.
// ConsumeSpotifyState removes the nonce, so a replayed callback fails.
func (s *Store) ConsumeSpotifyState(state string) bool {
if state == "" {
return false
@@ -131,15 +99,7 @@ func (s *Store) ConsumeSpotifyState(state string) bool {
return time.Since(created) <= spotifyStateTTL
}
// The cache accessors below are the only supported way to touch the cache
// fields. Each "Cached..." method returns the value plus a bool that is true
// only when the entry is present and inside its TTL; each "Set..." method
// stores a value and stamps it.
// LogSpotifyUnauthenticated logs that the Spotify OAuth flow has never been
// completed (or a stored token stopped working), with a where hint. It is
// rate-limited to one line per hour — see spotifyNilLoggedAt — because
// spotifyRecent is hit by every home-page visit.
// LogSpotifyUnauthenticated logs at most once an hour.
func (s *Store) LogSpotifyUnauthenticated(where string) {
s.spotifyNilLoggedMu.Lock()
defer s.spotifyNilLoggedMu.Unlock()
@@ -150,9 +110,7 @@ func (s *Store) LogSpotifyUnauthenticated(where string) {
log.Printf("[Spotify] not authenticated (seen in %s) — an admin can reconnect via GET /api/spotify/auth", where)
}
// CachedRecentSongs returns the cached Spotify recently-played list if it is
// within its one-minute TTL. An empty list counts as stale, so an empty
// listening history is re-fetched every time (unchanged behaviour).
// CachedRecentSongs treats an empty list as stale.
func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) {
s.cacheMu.RLock()
defer s.cacheMu.RUnlock()
@@ -166,7 +124,6 @@ func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) {
return *s.RecentSongs, true
}
// SetRecentSongs replaces the cached recently-played list.
func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) {
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
@@ -175,9 +132,6 @@ func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) {
s.RecentSongsFetchedAt = time.Now()
}
// CachedGiteaFeed returns the cached Gitea activity entry if it is within its
// one-minute TTL. A nil cache is never fresh, so the first request always hits
// Gitea.
func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) {
s.cacheMu.RLock()
defer s.cacheMu.RUnlock()
@@ -188,7 +142,6 @@ func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) {
return s.GiteaFeed, true
}
// SetGiteaFeed replaces the cached Gitea feed entry.
func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
@@ -197,10 +150,8 @@ func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
s.GiteaFeedFetchedAt = time.Now()
}
// CachedSteam returns the cached Steam recent games and online flag if they
// are within their five-minute TTL. As before, freshness is judged only on the
// games list: if Steam legitimately returns no recent games the cache never
// registers as fresh and every request re-queries the API.
// CachedSteam judges freshness on the games list only, so an empty list is
// always re-fetched.
func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok bool) {
s.cacheMu.RLock()
defer s.cacheMu.RUnlock()
@@ -211,7 +162,6 @@ func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok
return s.SteamRecentGames, s.SteamOnline, true
}
// SetSteam replaces the cached Steam data.
func (s *Store) SetSteam(games []services.SteamRecentGame, online bool) {
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
+19 -89
View File
@@ -20,18 +20,9 @@ import (
"adam-french.co.uk/backend/services"
)
// Command backend is the Go API for adam-french.co.uk.
//
// main is the single place everything is wired together: it reads every
// setting from the environment, builds the services, packs them into one
// handlers.Store, and registers the routes. There are three route groups —
// open, `protected` (valid access token) and `admin` (token with admin=true)
// — plus the GraphQL endpoint, which is authorised by the @admin / @signedIn
// directives in its schema instead of by middleware. See backend/README.md
// for the wider picture.
// Command backend is the site's Go API. GraphQL is guarded by schema
// directives, not middleware; see backend/README.md.
func main() {
// Logs go to both stdout (so `docker compose logs` works) and a file in a
// mounted volume (so they survive the container).
logsDir := "/backend/logs"
logFile, err := os.OpenFile(logsDir+"/go.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
@@ -44,16 +35,11 @@ func main() {
}
r := gin.New()
// Custom traffic formatter (services/traffic_log.go) instead of gin's
// default: quiets heartbeat subrequests, surfaces external visitors and
// server errors. Same writer pair as above.
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
r.Use(gin.Recovery())
// Only the Docker network Caddy sits on may set X-Forwarded-For. Without
// this pin any client could spoof its IP and defeat the per-IP login rate
// limiter, which keys on ctx.ClientIP(). The CIDR must match the network
// defined in docker-compose.yml.
// Only the Docker network may set X-Forwarded-For, or clients could spoof
// their IP past the login rate limiter. Must match docker-compose.yml.
err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
if err != nil {
panic(err)
@@ -69,36 +55,21 @@ func main() {
if err != nil {
log.Fatal(err)
}
// Dev only; the seeder creates an admin with a known password.
if os.Getenv("SEED_DB") == "true" {
services.SeedDatabase(db)
}
// DOMAIN does double duty: the WebSocket origin allow-list and the auth
// cookie domain.
// Used for both the WebSocket origin check and the cookie domain.
domainName := os.Getenv("DOMAIN")
// The chat hub is a package-level singleton rather than a value on the
// Store, so it is initialised rather than constructed.
services.InitWebSocket(db, domainName)
// SPOTIFY
// No SPOTIFY_AUTH_STATE: the OAuth `state` is now a one-shot nonce minted
// per authorisation request, so there is nothing to configure.
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
spotifyClientSecret := os.Getenv("SPOTIFY_CLIENT_SECRET")
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
// No Claude client here: the site's one Claude call, the rowing photo
// reader, is made by the Python service, which is the only container of
// the site's own that reads CLAUDE_API_KEY. The backend reaches it at
// pythonURL, below. (The job tracker, a separate container, makes its own.)
authSecret := os.Getenv("BACKEND_SECRET")
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
// Long-lived by design: this is a personal site with a single admin, and
// there is no server-side revocation, so a leaked token stays valid for
// its whole lifetime.
accessTokenLifetime := 7 * 24 * time.Hour
refreshTokenLifetime := 365 * 24 * time.Hour
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
@@ -114,10 +85,7 @@ func main() {
steamAPIKey := os.Getenv("STEAM_API_KEY")
steamID := os.Getenv("STEAM_ID")
// PYTHON SERVICE
// Called directly over the Docker network, not through Caddy, for its
// /internal/ Claude route (services/python_call.go). The defaults
// mirror docker-compose.yml, where both variables are optional.
// Called over the Docker network, not through Caddy.
pythonHost := os.Getenv("PYTHON_HOST")
if pythonHost == "" {
pythonHost = "python"
@@ -128,11 +96,7 @@ func main() {
}
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
// UPLOADS
// Public uploads go to the Garage bucket (and to the shared `uploads`
// volume when Garage refuses a write, or when S3_ENDPOINT is unset);
// private ones to the volume. See services/uploads.go. Region and bucket
// default to what garage/garage.toml and garage/bootstrap.sh set up.
// Defaults match garage/garage.toml and garage/bootstrap.sh.
s3Region := os.Getenv("S3_REGION")
if s3Region == "" {
s3Region = "garage"
@@ -144,24 +108,18 @@ func main() {
s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")}
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
// 5 login attempts per IP per minute, applied by both the REST handler
// and the GraphQL login mutation. Caddy rate-limits the login route too.
// Shared by REST and GraphQL login, on top of Caddy's limit.
loginLimiter := services.NewRateLimiter(5, time.Minute)
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Uploads: uploads}
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
// the Gin context, so the order in the admin group matters.
//
// Paths below have no /api prefix: Caddy strips it before proxying.
protected := r.Group("/", store.AuthMiddlewear)
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
// Caddy strips /api before proxying.
protected := r.Group("/", store.AuthMiddleware)
admin := r.Group("/", store.AuthMiddleware, store.AdminMiddleware)
// ROWING
r.GET("/rowing", store.GetRowing)
admin.POST("/rowing", store.CreateRowing)
// AUTH
r.POST("/auth/login", store.Login)
r.POST("/auth/refresh", store.RefreshToken)
r.GET("/auth/check", store.CheckToken)
@@ -169,47 +127,29 @@ func main() {
r.GET("/auth/validate-admin", store.ValidateAdmin)
r.GET("/auth/validate/:permission", store.ValidatePermission)
// SPOTIFY
// The callback must be open — Spotify redirects a logged-out browser to
// it — and is protected by the state nonce instead. Starting the flow is
// admin-only, since that is what mints the nonce.
// The callback is open (Spotify redirects a logged-out browser) and is
// protected by the state nonce that only the admin-only start mints.
r.GET("/spotify/callback", store.CompleteSpotifyAuth)
admin.GET("/spotify/auth", store.StartSpotifyAuth)
r.GET("/spotify/listening", store.ListeningTo)
r.GET("/spotify/recent", store.RecentlyPlayed)
// r.POST("/spotify", store.SendSong)
// RADIO
admin.POST("/radio/upload", store.UploadRadioSong)
admin.GET("/radio/songs", store.ListRadioSongs)
admin.DELETE("/radio/songs/:filename", store.DeleteRadioSong)
admin.PATCH("/radio/songs/:filename/disable", store.DisableRadioSong)
admin.PATCH("/radio/songs/:filename/enable", store.EnableRadioSong)
// MESSAGES
// /ws is deliberately outside the protected group: chat is public, and
// the handler checks the cookies itself to decide admin privileges.
// Public: the handler reads the cookies itself for admin privileges.
r.GET("/ws", store.ConnectWebSocket)
protected.POST("/uploads", store.Upload)
admin.GET("/uploads", store.ListUploads)
// NOTES
admin.GET("/notes/*path", store.GetNoteFile)
// GRAPHQL
// GraphQL is assembled by hand rather than with handler.NewDefaultServer
// so the transports and extensions below are explicit.
//
// Note the whole API is one POST route with no middleware guard.
// Authorisation is declared in the schema instead: a field marked @admin
// or @signedIn is refused by the matching function in graph.Directives()
// before its resolver runs. A field with neither is PUBLIC, so a new
// mutation needs one — graph/directives_test.go fails until it has one or
// is added to the list of deliberately public fields there.
//
// Directives must stay wired here: gqlgen fails closed on a nil directive
// (the field errors with "directive admin is not implemented"), so
// dropping this line breaks every guarded field rather than opening it.
// One unguarded POST route: authorisation is the schema's @admin and
// @signedIn directives, so a field with neither is public. gqlgen fails
// closed if Directives is dropped.
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
Resolvers: &graph.Resolver{Store: &store},
Directives: graph.Directives(),
@@ -218,20 +158,13 @@ func main() {
gqlSrv.AddTransport(transport.Options{})
gqlSrv.AddTransport(transport.POST{})
gqlSrv.AddTransport(transport.MultipartForm{})
// Caches parsed query documents so repeated queries skip parsing.
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
// Rejects queries above a computed complexity, the standard defence
// against a deeply nested query being used to exhaust the server.
gqlSrv.Use(extension.FixedComplexityLimit(200))
// Introspection and the playground are both off unless DEV_MODE *and*
// their own flag are set, so production does not publish its schema.
// Production never publishes its schema.
devMode := os.Getenv("DEV_MODE") == "true"
if devMode && os.Getenv("GQL_INTROSPECTION") == "true" {
gqlSrv.Use(extension.Introspection{})
}
// AuthContextMiddleware copies the Gin context and any verified claims
// into the request context, which is what resolvers read. The closure is
// needed because gqlgen speaks net/http, not gin.
r.POST("/graphql", graph.AuthContextMiddleware(auth, db), func(c *gin.Context) {
gqlSrv.ServeHTTP(c.Writer, c.Request)
})
@@ -241,15 +174,12 @@ func main() {
})
}
// HELLO WORLD
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Hello World"})
})
port := os.Getenv("BACKEND_PORT")
// Blocks until the server stops. Any return is a failure — a port clash,
// most often — so it must exit non-zero, or Docker sees a clean shutdown
// and reports the container as having succeeded.
// Exit non-zero so Docker doesn't report a port clash as success.
if err := r.Run(fmt.Sprintf(":%s", port)); err != nil {
log.Fatalf("http server stopped: %v", err)
}
+50 -139
View File
@@ -6,64 +6,29 @@ import (
"gorm.io/gorm"
)
// Package models holds the GORM entities, which are also the GraphQL object
// types: gqlgen.yml maps each GraphQL type straight onto the struct here, so
// graph/model/ only contains generated input and payload types. That means
// these structs carry three sets of contracts at once — database columns,
// JSON field names for the REST endpoints, and the shape resolvers return —
// and renaming a field or changing a tag breaks at least one of them.
//
// Conventions across every model:
// - There are no migration files; services.migrateDatabase runs AutoMigrate,
// so a model must be listed there to get a table.
// - A gorm.DeletedAt field means soft delete: Delete sets deleted_at, and
// every subsequent query silently filters those rows out. Rows are never
// actually removed, and a uniqueIndex still sees deleted rows, so a
// soft-deleted username cannot be reused.
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
// On the wire an id is a quoted decimal string, "12".
// These structs are also the GraphQL object types (gqlgen.yml), so a field or
// tag change affects the DB, REST JSON and GraphQL at once.
// User is an account. There is no public sign-up: users are created by an
// existing admin through the createUser mutation, or by the dev seeder.
// User is an account, created only by an admin or the dev seeder.
type User struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Username string `gorm:"uniqueIndex" json:"username"`
// bcrypt hash, never the plaintext. `json:"-"` keeps it out of REST
// responses, and gqlgen.yml marks the GraphQL password field
// resolver:false so it is not exposed there either.
// bcrypt hash; gqlgen.yml hides it from GraphQL too.
Password []byte `json:"-"`
// Admin gates almost every mutation. It is copied into the access token,
// so a change here only takes effect on the user's next token refresh.
// Copied into the access token, so changes apply on the next refresh.
Admin bool `json:"admin"`
// Permissions names the gated services this non-admin user may use, one
// key each from services.PermissionTypes (admins pass every check
// regardless). Unlike Admin it is never copied into a token: the gate
// reads it from the row, which services.Auth loads on every request
// anyway, so a grant or revoke takes effect on the user's next request.
// Stored as a JSON array in one text column; a row from before the
// column existed reads as NULL, i.e. no permissions.
// Keys from services.PermissionTypes. Read from the row on each request,
// not the token, so grants apply immediately.
Permissions []string `gorm:"serializer:json" json:"permissions"`
// TokenVersion is the session generation counter. Every issued JWT
// carries the value current at the time it was minted, and
// services.Auth rejects a token whose value no longer matches, so
// incrementing this column revokes every outstanding token for the user
// at once (logout, password change). It is the only server-side
// revocation mechanism there is.
//
// Pre-migration rows: AutoMigrate adds the column with DEFAULT 1, but a
// row that somehow ends up at 0 is normalised to 1 by
// services.tokenVersionOf, as is a token minted before the "tv" claim
// existed. So the migration invalidates nobody's existing session, and
// the first bump moves a user to 2 and invalidates everything older.
// Every JWT carries this; bumping it revokes all of the user's tokens.
// 0 and a missing claim are both treated as 1 (services.tokenVersionOf).
TokenVersion uint `gorm:"not null;default:1" json:"-"`
}
// Post is a blog entry. Author is loaded with Preload("Author") by the post
// resolvers; without that preload it is nil rather than an error.
// Post is a blog entry. Author is nil unless preloaded.
type Post struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -75,27 +40,20 @@ type Post struct {
Content string `json:"content"`
}
// Message is one chat message. The table is capped at 50 rows by the
// WebSocket hub, which soft-deletes older ones on every insert.
//
// Two things to watch: Content is exposed as "text", not "content"; and
// AuthorID is a per-process connection counter from the WebSocket hub, NOT a
// User ID — chat is pseudonymous and the number is meaningless across
// restarts.
// Message is a chat message; the WebSocket hub keeps only the latest 50.
// AuthorID is the hub's per-process connection number, not a User ID.
type Message struct {
ID uint `gorm:"primarykey" json:"id"`
Content string `json:"text"`
AuthorID uint `json:"authorId"`
FileURL string `json:"fileUrl,omitempty"`
// Private messages are visible only to admins; both the WebSocket
// broadcast and the messages query filter on it.
// Visible only to admins.
Private bool `gorm:"not null;default:false" json:"private"`
CreatedAt time.Time `json:"createdAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
}
// Activity is a "currently doing" entry on the home page. Structurally
// identical to Favorite but kept separate so the two lists can diverge.
// Activity is a "currently doing" entry on the home page.
type Activity struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -117,13 +75,9 @@ type Favorite struct {
Link *string `json:"link"`
}
// Rowing is one rowing machine session, created by uploading a photo of the
// display (see handlers.CreateRowing).
//
// Date is the photo's EXIF capture time and acts as the deduplication key —
// it is not the row's creation time. Time is total seconds; Distance is
// metres; TimePer500m is seconds and derived from the other two; Calories is
// an estimate computed from distance, not read off the machine.
// Rowing is one rowing machine session read from a photo of the display.
// Date is the photo's EXIF time and the dedup key. Time is seconds, Distance
// metres; Calories is estimated from distance.
type Rowing struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -146,9 +100,7 @@ type Bookmark struct {
Link string `gorm:"not null" json:"link"`
}
// Place is an entry on the places-to-go list. Creating or editing one needs
// only a signed-in user, not an admin — the one exception to the
// admin-writes-everything rule.
// Place is a places-to-go entry; any signed-in user may edit it.
type Place struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -164,20 +116,15 @@ type Place struct {
Done bool `gorm:"default:false" json:"done"`
}
// Box is one panel on a canvas page. Page names the canvas it belongs to:
// "index" for the landing page, or a Page.Slug for an admin-created page
// (the home page is the Page "stp") — it is a key, not a foreign key, so the
// built-in landing canvas needs no Page row. Its position and size are in px on a
// fixed 1400px-wide design canvas, which the page scales down on narrower
// screens — so the stored numbers mean the same thing for every visitor. Kind "widget" renders a built-in Vue component named by Widget;
// kind "html" renders HTML in a sandboxed iframe on the front end, which is
// what makes storing admin-authored script here acceptable.
// Box is one panel on a canvas. Page is a page key ("index" or a Page.Slug),
// not a foreign key. Geometry is px on a fixed 1400px-wide canvas. "html"
// boxes render in a sandboxed iframe.
type Box struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
// default:stp is what the boxes that predate pages are migrated to.
// Boxes from before pages existed migrate to "stp".
Page string `gorm:"not null;default:stp;index" json:"page"`
Kind string `gorm:"not null" json:"kind"`
Widget *string `json:"widget"`
@@ -188,30 +135,20 @@ type Box struct {
W int `gorm:"not null;default:300" json:"w"`
H int `gorm:"not null;default:200" json:"h"`
Z int `gorm:"not null;default:0" json:"z"`
// No gorm default on Framed: GORM omits zero values for defaulted columns
// on insert, so default:true would turn an explicit false into true.
// CreateBox applies the true default itself.
// No gorm default: GORM skips zero values on insert, so default:true would
// turn an explicit false into true. CreateBox defaults it.
Framed bool `gorm:"not null" json:"framed"`
// Shadow is a CSS box-shadow value drawn around the box, or "" for none.
// It is independent of Framed, so an unframed box can still cast one.
// A CSS box-shadow, or "".
Shadow string `gorm:"not null;default:''" json:"shadow"`
HideOnMobile bool `gorm:"not null;default:false" json:"hideOnMobile"`
// AdminOnly boxes are never sent to anyone but an admin (the boxes
// resolver filters them out), so they suit private notes.
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
// ComponentID links an html box to a Component, whose HTML it shows
// instead of its own: the row's HTML is nil, and the resolvers fill it in
// from the component before answering (graph/component_helpers.go). There
// is deliberately no association field — with one, DB.Save(&box) would
// write the component back too.
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
// The box shows the component's HTML (its own is nil). No association
// field, or DB.Save(&box) would write the component back too.
ComponentID *uint `gorm:"index" json:"componentId"`
}
// Page is an admin-created canvas page, served by the SPA's catch-all route
// at /<Slug> (e.g. "shrines/evangelion"). Its content is the Boxes whose Page
// equals Slug. The unique index is partial so that a deleted page's slug can
// be reused — a plain uniqueIndex would still collide with the soft-deleted
// row.
// Page is an admin-created canvas page at /<Slug>. The unique index is
// partial so a soft-deleted slug can be reused.
type Page struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -219,60 +156,40 @@ type Page struct {
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Slug string `gorm:"not null;index:idx_pages_slug,unique,where:deleted_at IS NULL" json:"slug"`
Title string `gorm:"not null" json:"title"`
// AdminOnly hides the whole page, boxes included, from everyone else.
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
}
// Background is the page background behind one canvas (Page is the same page
// key a Box has: "index" for the landing page, or a Page's slug), so
// built-in canvases and admin-created pages are set the same way. A page with
// no row shows the theme's halftone; deleting the row is "reset to default".
// The unique index is partial for the same reason as Page's.
// Background is a canvas page's background; no row means the theme default.
type Background struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Page string `gorm:"not null;index:idx_backgrounds_page,unique,where:deleted_at IS NULL" json:"page"`
// Color is a CSS colour, or "" for the theme's page colour.
// "" means the theme colour.
Color string `gorm:"not null;default:''" json:"color"`
// Image is a URL, or "" for none. Drawn over Color.
Image string `gorm:"not null;default:''" json:"image"`
// Fit is how Image fills the window: "cover", "contain" or "tile".
// "cover", "contain" or "tile".
Fit string `gorm:"not null;default:cover" json:"fit"`
}
// Layout is a named copy of one canvas page's boxes and background, saved so
// it can be loaded onto any page later (graph/layout_helpers.go). It is a
// snapshot, not a link: loading it creates new boxes that belong to the
// target page, so editing either page afterwards never touches the other or
// the layout. The content is JSON rather than child rows because nothing
// queries inside it — it is only ever written whole and read whole. The
// unique index is partial for the same reason as Page's.
// Layout is a saved snapshot of a page's boxes and background. Loading it
// creates new boxes, so nothing stays linked. Stored as JSON because it is
// only ever read and written whole.
type Layout struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_layouts_name,unique,where:deleted_at IS NULL" json:"name"`
// SourcePage is the page key it was saved from, for the list only.
SourcePage string `gorm:"not null" json:"sourcePage"`
// Boxes is a JSON array of the boxes' content and geometry, without id
// or page.
Boxes string `gorm:"type:text;not null" json:"-"`
// Background is the page's background as JSON, or nil if it had none.
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_layouts_name,unique,where:deleted_at IS NULL" json:"name"`
SourcePage string `gorm:"not null" json:"sourcePage"`
// JSON array of box content and geometry, without id or page.
Boxes string `gorm:"type:text;not null" json:"-"`
Background *string `gorm:"type:text" json:"-"`
}
// Component is a named HTML box that can be placed on any canvas page, either
// as a copy (an ordinary box) or linked (a box with ComponentID set). Linked
// boxes share only the HTML — editing it changes every one of them at once —
// while title, geometry, frame and visibility stay each box's own, since
// those are about where it sits on a page rather than what it is. Title, W,
// H, Framed, Shadow and AdminOnly are the defaults a newly placed box starts
// with.
// Widgets are not components: a widget box is just a name, with nothing
// worth sharing. The unique index is partial for the same reason as Page's.
// Component is a named HTML box. Linked boxes share only its HTML; the other
// fields are the defaults for a newly placed box.
type Component struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -283,17 +200,13 @@ type Component struct {
HTML string `gorm:"type:text;not null" json:"html"`
W int `gorm:"not null" json:"w"`
H int `gorm:"not null" json:"h"`
// No gorm default on Framed, for the same reason as Box.Framed.
// No gorm default, as for Box.Framed.
Framed bool `gorm:"not null" json:"framed"`
Shadow string `gorm:"not null;default:''" json:"shadow"`
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
}
// CoverLetter is a saved letter from the /cv Cover Letter tab. Body is the
// whole letter as JSON (contact block, sections, paragraphs; the shape is
// views/CV/coverLetter.js's) because only the frontend ever reads inside it —
// the same reasoning as Layout.Boxes. The unique index is partial for the
// same reason as Page's.
// CoverLetter is a saved letter; Body is JSON in views/CV/coverLetter.js's shape.
type CoverLetter struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -303,9 +216,7 @@ type CoverLetter struct {
Body string `gorm:"type:text;not null" json:"body"`
}
// CoverSnippet is a reusable paragraph in the cover-letter bank, dragged into
// a letter as a copy. Section is the title of the section it was written for,
// only used to group the bank; a snippet can be dropped into any section.
// CoverSnippet is a reusable cover-letter paragraph; Section only groups the bank.
type CoverSnippet struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
+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()