Harden auth: same-origin check, live admin flag, 90-day refresh
Test and deploy / test (push) Failing after 28s
Test and deploy / deploy (push) Has been skipped

- Refuse non-GET requests whose Origin (or Sec-Fetch-Site) is not the
  apex or www. SameSite=Lax lets sibling subdomains such as radar. and
  git. send the auth cookies. The WebSocket check shares the helper and
  no longer accepts localhost in production.
- Take the admin flag from the user row the token check already loads,
  so a demotion applies on the next request, not on token expiry.
- Cut the refresh token lifetime from 365 to 90 days; refreshes renew it.
- Docs: fix the stale revocation notes in backend/README.md and the
  Cloudflare Access comment in routes.caddy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-26 16:12:01 +00:00
co-authored by Claude Opus 5.5
parent 3139e8e239
commit d383774e97
10 changed files with 140 additions and 34 deletions
+1 -1
View File
@@ -95,7 +95,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
## Key Patterns ## Key Patterns
- **GraphQL models vs GORM models**: `gqlgen.yml` maps GraphQL types directly to GORM models in `backend/models`. The `graph/model/` package has only generated input/payload types. - **GraphQL models vs GORM models**: `gqlgen.yml` maps GraphQL types directly to GORM models in `backend/models`. The `graph/model/` package has only generated input/payload types.
- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded). - **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (90 days, renewed on every refresh) as HTTP-only cookies (`backend/main.go`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. The admin flag is read from the user row on every request (`AuthenticateTokenWithClaims` overwrites the claim), so a demotion applies at once. `services.RequireSameOrigin` refuses any non-GET request whose `Origin` is not the apex or www, since SameSite=Lax lets sibling subdomains (radar., git.) send the cookies. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded).
- **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`. - **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`.
- **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`. - **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`.
- **Per-service permissions**: a non-admin account can be granted individual gated services (today only `receipt`, for `/receipt/`) in the admin panel's Manage Users tab. The keys are the registry `services.PermissionTypes` (`backend/services/permissions.go`), stored in `User.Permissions`; admins hold them all. Caddy's *permission gate* (`import permission_gate <key>` in a route, see `caddy/routes.caddy` and the snippet in `caddy/Caddyfile`) asks `GET /auth/validate/<key>`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its route from `import admin_gate` to `import permission_gate <key>`. `/auth/validate-admin` and the admin gate are unchanged. - **Per-service permissions**: a non-admin account can be granted individual gated services (today only `receipt`, for `/receipt/`) in the admin panel's Manage Users tab. The keys are the registry `services.PermissionTypes` (`backend/services/permissions.go`), stored in `User.Permissions`; admins hold them all. Caddy's *permission gate* (`import permission_gate <key>` in a route, see `caddy/routes.caddy` and the snippet in `caddy/Caddyfile`) asks `GET /auth/validate/<key>`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its route from `import admin_gate` to `import permission_gate <key>`. `/auth/validate-admin` and the admin gate are unchanged.
+12 -9
View File
@@ -55,12 +55,12 @@ graph/ GraphQL layer
- `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets - `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets
two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`: two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`:
- `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary - `access_token` (7 days) carries `id`, `username`, `admin` and `tv`;
requests authorise without a database hit; - `refresh_token` (90 days) carries `id` and `tv`.
- `refresh_token` (365 days) carries only `id`. Every check loads the user row (one SELECT) to compare `tv`, and takes
`admin` from the row, not the token.
- `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh - `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh
token for a new pair, re-reading the user — and therefore the admin flag — token for a new pair, so the 90 days slide while the account is in use.
from the database.
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401) - `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
and will transparently refresh, so returning admins are recognised without a and will transparently refresh, so returning admins are recognised without a
visible re-login. visible re-login.
@@ -74,10 +74,13 @@ graph/ GraphQL layer
check reads the user row, not the token, so a grant or revoke applies on check reads the user row, not the token, so a grant or revoke applies on
the next request. On 200 it returns the username in `X-Auth-User`, which the next request. On 200 it returns the username in `X-Auth-User`, which
Caddy forwards to the gated service as `X-Remote-User`. Caddy forwards to the gated service as `X-Remote-User`.
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing - Revocation is by `User.TokenVersion`: logout and a password change bump it,
is revoked server-side, and a token that has already been issued stays valid which invalidates every token already issued to that user. Demoting an admin
until it expires. The same is true of demoting an admin: it takes effect on applies on their next request.
their next refresh, not immediately. - Any request that is not GET/HEAD/OPTIONS must come from the site's own
origin (`services.RequireSameOrigin`). SameSite=Lax alone would let a page on
a sibling subdomain such as radar. or git. post with the cookies. Requests
without `Origin` or `Sec-Fetch-Site` (curl, server-to-server) pass.
The two implementations (REST in `handlers/handle_auth.go`, GraphQL in The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
`graph/auth.resolvers.go`) are parallel by design, since the front end uses `graph/auth.resolvers.go`) are parallel by design, since the front end uses
+1 -1
View File
@@ -40,7 +40,7 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
return uint(idF), true return uint(idF), true
} }
// IsAdminFromCtx reads the token, so a revoked flag applies on expiry. // IsAdminFromCtx reads the claims, whose admin flag comes from the user row.
func IsAdminFromCtx(ctx context.Context) bool { func IsAdminFromCtx(ctx context.Context) bool {
claims := UserClaimsFromCtx(ctx) claims := UserClaimsFromCtx(ctx)
if claims == nil { if claims == nil {
+4 -9
View File
@@ -40,8 +40,8 @@ func (store *Store) AuthMiddleware(ctx *gin.Context) {
ctx.Next() ctx.Next()
} }
// AdminMiddleware must follow AuthMiddleware. Admin comes from the token, so // AdminMiddleware must follow AuthMiddleware, whose claims carry the row's
// a revoked flag applies once the access token expires. // admin flag.
func (store *Store) AdminMiddleware(ctx *gin.Context) { func (store *Store) AdminMiddleware(ctx *gin.Context) {
claims, exists := ctx.Get("userClaims") claims, exists := ctx.Get("userClaims")
if !exists { if !exists {
@@ -69,13 +69,8 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
// gate and the jobs container. It falls back to the refresh token and may // 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. // mint new cookies, so a returning admin needn't log in again.
func (store *Store) ValidateAdmin(ctx *gin.Context) { func (store *Store) ValidateAdmin(ctx *gin.Context) {
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool { store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
// The refresh path has no admin claim, so it reads the row. return user.Admin
if claims == nil {
return user.Admin
}
admin, ok := (*claims)["admin"].(bool)
return ok && admin
}) })
} }
+3 -1
View File
@@ -61,6 +61,7 @@ func main() {
// Used for both the WebSocket origin check and the cookie domain. // Used for both the WebSocket origin check and the cookie domain.
domainName := os.Getenv("DOMAIN") domainName := os.Getenv("DOMAIN")
services.InitWebSocket(db, domainName) services.InitWebSocket(db, domainName)
r.Use(services.RequireSameOrigin(domainName))
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI") spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID") spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
@@ -71,7 +72,8 @@ func main() {
authSecret := os.Getenv("BACKEND_SECRET") authSecret := os.Getenv("BACKEND_SECRET")
backendEndpoint := os.Getenv("BACKEND_ENDPOINT") backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
accessTokenLifetime := 7 * 24 * time.Hour accessTokenLifetime := 7 * 24 * time.Hour
refreshTokenLifetime := 365 * 24 * time.Hour // Sliding: every refresh, including the gates', mints a new one.
refreshTokenLifetime := 90 * 24 * time.Hour
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint} authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
auth := services.InitAuth(&authConfig) auth := services.InitAuth(&authConfig)
+6 -2
View File
@@ -41,8 +41,8 @@ func InitAuth(config *AuthConfig) *Auth {
return &Auth{Config: config} return &Auth{Config: config}
} }
// GenerateJWT issues an access/refresh pair. Only the access token carries // GenerateJWT issues an access/refresh pair. The admin claim is informational:
// admin; refresh re-reads the row, so a revoked admin flag applies then. // AuthenticateTokenWithClaims overwrites it from the user row.
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) { func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username, "username": user.Username,
@@ -140,6 +140,10 @@ func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*mo
return nil, nil, ErrTokenRevoked return nil, nil, ErrTokenRevoked
} }
// The row is already loaded, so it decides admin: a demotion applies on
// the next request rather than when the token expires.
(*claims)["admin"] = user.Admin
return &user, claims, nil return &user, claims, nil
} }
+44
View File
@@ -0,0 +1,44 @@
package services
import (
"net/http"
"net/url"
"github.com/gin-gonic/gin"
)
// IsSiteOrigin reports whether an Origin header names the site itself (the
// apex or www). In dev DOMAIN is localhost, which covers Vite on any port.
func IsSiteOrigin(origin, domain string) bool {
u, err := url.Parse(origin)
if err != nil {
return false
}
host := u.Hostname()
return domain != "" && (host == domain || host == "www."+domain)
}
// RequireSameOrigin refuses state-changing requests a browser sent from
// elsewhere. SameSite=Lax does not cover this: radar. and git. are the same
// site, so their pages get the auth cookies. A request with neither header is
// not from a browser and passes.
func RequireSameOrigin(domain string) gin.HandlerFunc {
return func(c *gin.Context) {
switch c.Request.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
c.Next()
return
}
allowed := true
if origin := c.GetHeader("Origin"); origin != "" {
allowed = IsSiteOrigin(origin, domain)
} else if site := c.GetHeader("Sec-Fetch-Site"); site != "" {
allowed = site == "same-origin" || site == "none"
}
if !allowed {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "cross-origin request refused"})
return
}
c.Next()
}
}
+67
View File
@@ -0,0 +1,67 @@
package services
import (
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestIsSiteOrigin(t *testing.T) {
cases := []struct {
origin, domain string
want bool
}{
{"https://www.example.com", "example.com", true},
{"https://example.com", "example.com", true},
{"https://radar.example.com", "example.com", false},
{"https://git.example.com", "example.com", false},
{"https://www.example.com.evil.test", "example.com", false},
{"https://evilexample.com", "example.com", false},
{"null", "example.com", false},
{"http://localhost:5173", "localhost", true},
{"http://localhost:5173", "example.com", false},
{"https://anything", "", false},
}
for _, c := range cases {
if got := IsSiteOrigin(c.origin, c.domain); got != c.want {
t.Errorf("IsSiteOrigin(%q, %q) = %v, want %v", c.origin, c.domain, got, c.want)
}
}
}
func TestRequireSameOrigin(t *testing.T) {
gin.SetMode(gin.TestMode)
cases := []struct {
name string
method string
headers map[string]string
want int
}{
{"GET is never checked", "GET", map[string]string{"Origin": "https://evil.test"}, 200},
{"POST from www", "POST", map[string]string{"Origin": "https://www.example.com"}, 200},
{"POST from a sibling subdomain", "POST", map[string]string{"Origin": "https://radar.example.com"}, 403},
{"POST from another site", "POST", map[string]string{"Origin": "https://evil.test"}, 403},
{"POST with an opaque origin", "POST", map[string]string{"Origin": "null"}, 403},
{"DELETE from another site", "DELETE", map[string]string{"Origin": "https://evil.test"}, 403},
{"no Origin, same-site fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-site"}, 403},
{"no Origin, same-origin fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-origin"}, 200},
{"no browser headers (curl, server to server)", "POST", nil, 200},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := gin.New()
r.Use(RequireSameOrigin("example.com"))
r.Handle(c.method, "/x", func(ctx *gin.Context) { ctx.Status(200) })
req := httptest.NewRequest(c.method, "/x", nil)
for k, v := range c.headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != c.want {
t.Fatalf("status %d, want %d", rec.Code, c.want)
}
})
}
}
+1 -10
View File
@@ -3,7 +3,6 @@ package services
import ( import (
"log" "log"
"net/http" "net/http"
"net/url"
"sync" "sync"
"time" "time"
@@ -28,15 +27,7 @@ var Upgrader = websocket.Upgrader{
WriteBufferSize: 1024, WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin") origin := r.Header.Get("Origin")
if origin == "" { return origin != "" && IsSiteOrigin(origin, allowedDomain)
return false
}
u, err := url.Parse(origin)
if err != nil {
return false
}
host := u.Hostname()
return host == allowedDomain || host == "www."+allowedDomain || host == "localhost"
}, },
} }
+1 -1
View File
@@ -153,7 +153,7 @@ handle /radio/admin/* {
} }
} }
# The notes editor is on stppriv, behind Cloudflare Access. # The notes editor is on stppriv, behind its admin gate.
handle /sb/* { handle /sb/* {
redir https://priv.{$DOMAIN}{uri} 301 redir https://priv.{$DOMAIN}{uri} 301
} }