Harden auth: same-origin check, live admin flag, 90-day refresh
- 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:
@@ -95,7 +95,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
|
||||
## 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.
|
||||
- **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`.
|
||||
- **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.
|
||||
|
||||
+12
-9
@@ -55,12 +55,12 @@ graph/ GraphQL layer
|
||||
|
||||
- `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets
|
||||
two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`:
|
||||
- `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary
|
||||
requests authorise without a database hit;
|
||||
- `refresh_token` (365 days) carries only `id`.
|
||||
- `access_token` (7 days) carries `id`, `username`, `admin` and `tv`;
|
||||
- `refresh_token` (90 days) carries `id` and `tv`.
|
||||
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
|
||||
token for a new pair, re-reading the user — and therefore the admin flag —
|
||||
from the database.
|
||||
token for a new pair, so the 90 days slide while the account is in use.
|
||||
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
|
||||
and will transparently refresh, so returning admins are recognised without a
|
||||
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
|
||||
the next request. On 200 it returns the username in `X-Auth-User`, which
|
||||
Caddy forwards to the gated service as `X-Remote-User`.
|
||||
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
|
||||
is revoked server-side, and a token that has already been issued stays valid
|
||||
until it expires. The same is true of demoting an admin: it takes effect on
|
||||
their next refresh, not immediately.
|
||||
- Revocation is by `User.TokenVersion`: logout and a password change bump it,
|
||||
which invalidates every token already issued to that user. Demoting an admin
|
||||
applies on their next request.
|
||||
- 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
|
||||
`graph/auth.resolvers.go`) are parallel by design, since the front end uses
|
||||
|
||||
@@ -40,7 +40,7 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
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 {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
|
||||
@@ -40,8 +40,8 @@ func (store *Store) AuthMiddleware(ctx *gin.Context) {
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// AdminMiddleware must follow AuthMiddleware. Admin comes from the token, so
|
||||
// a revoked flag applies once the access token expires.
|
||||
// AdminMiddleware must follow AuthMiddleware, whose claims carry the row's
|
||||
// admin flag.
|
||||
func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
||||
claims, exists := ctx.Get("userClaims")
|
||||
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
|
||||
// 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 {
|
||||
// The refresh path has no admin claim, so it reads the row.
|
||||
if claims == nil {
|
||||
return user.Admin
|
||||
}
|
||||
admin, ok := (*claims)["admin"].(bool)
|
||||
return ok && admin
|
||||
store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
|
||||
return user.Admin
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -61,6 +61,7 @@ func main() {
|
||||
// Used for both the WebSocket origin check and the cookie domain.
|
||||
domainName := os.Getenv("DOMAIN")
|
||||
services.InitWebSocket(db, domainName)
|
||||
r.Use(services.RequireSameOrigin(domainName))
|
||||
|
||||
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
|
||||
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
|
||||
@@ -71,7 +72,8 @@ func main() {
|
||||
authSecret := os.Getenv("BACKEND_SECRET")
|
||||
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
|
||||
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}
|
||||
auth := services.InitAuth(&authConfig)
|
||||
|
||||
|
||||
@@ -41,8 +41,8 @@ func InitAuth(config *AuthConfig) *Auth {
|
||||
return &Auth{Config: config}
|
||||
}
|
||||
|
||||
// GenerateJWT issues an access/refresh pair. Only the access token carries
|
||||
// admin; refresh re-reads the row, so a revoked admin flag applies then.
|
||||
// GenerateJWT issues an access/refresh pair. The admin claim is informational:
|
||||
// AuthenticateTokenWithClaims overwrites it from the user row.
|
||||
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
|
||||
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"username": user.Username,
|
||||
@@ -140,6 +140,10 @@ func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*mo
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package services
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -28,15 +27,7 @@ var Upgrader = websocket.Upgrader{
|
||||
WriteBufferSize: 1024,
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
u, err := url.Parse(origin)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
host := u.Hostname()
|
||||
return host == allowedDomain || host == "www."+allowedDomain || host == "localhost"
|
||||
return origin != "" && IsSiteOrigin(origin, allowedDomain)
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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/* {
|
||||
redir https://priv.{$DOMAIN}{uri} 301
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user