Trim comments to the non-obvious why
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:
+32
-126
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user