feat(auth): add session middleware and csrf protection
Unsafe methods require the session's synchronizer token and a matching Origin, which also covers login requests that have no session yet. Refs #5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
dae55d8c18
commit
9667e121f1
2 files changed
+176
No files matched your search
@@ -0,0 +1,113 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
CookieName = "__Host-session"
|
||||||
|
CSRFHeader = "X-CSRF-Token"
|
||||||
|
CSRFField = "_csrf"
|
||||||
|
ctxKey = "auth.session"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetCookie(c *gin.Context, sess *Session, maxAge int) {
|
||||||
|
http.SetCookie(c.Writer, &http.Cookie{
|
||||||
|
Name: CookieName,
|
||||||
|
Value: sess.Token,
|
||||||
|
Path: "/",
|
||||||
|
MaxAge: maxAge,
|
||||||
|
Secure: true,
|
||||||
|
HttpOnly: true,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ClearCookie(c *gin.Context) {
|
||||||
|
http.SetCookie(c.Writer, &http.Cookie{Name: CookieName, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load attaches the session if one exists. It never rejects; use Require for that.
|
||||||
|
func (s *Sessions) Load() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
token, err := c.Cookie(CookieName)
|
||||||
|
if err != nil {
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sess, err := s.Get(c.Request.Context(), token)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, ErrNoSession):
|
||||||
|
ClearCookie(c)
|
||||||
|
case err != nil:
|
||||||
|
_ = c.Error(err)
|
||||||
|
c.AbortWithStatus(http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
c.Set(ctxKey, sess)
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Require() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
if Current(c) == nil {
|
||||||
|
c.AbortWithStatus(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CSRF uses the synchronizer token stored in the session. SameSite=Lax alone
|
||||||
|
// does not cover same-site subdomains such as customer status pages.
|
||||||
|
func CSRF() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
switch c.Request.Method {
|
||||||
|
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Covers requests without a session (login CSRF) as well.
|
||||||
|
if !sameOrigin(c.Request) {
|
||||||
|
c.AbortWithStatus(http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sess := Current(c)
|
||||||
|
if sess == nil {
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token := c.GetHeader(CSRFHeader)
|
||||||
|
if token == "" {
|
||||||
|
token = c.PostForm(CSRFField)
|
||||||
|
}
|
||||||
|
if !sess.CheckCSRF(token) {
|
||||||
|
c.AbortWithStatus(http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameOrigin(r *http.Request) bool {
|
||||||
|
origin := r.Header.Get("Origin")
|
||||||
|
if origin == "" || origin == "null" {
|
||||||
|
return origin == ""
|
||||||
|
}
|
||||||
|
u, err := url.Parse(origin)
|
||||||
|
return err == nil && u.Host == r.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
func Current(c *gin.Context) *Session {
|
||||||
|
v, ok := c.Get(ctxKey)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return v.(*Session)
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func csrfRouter(sess *Session) *gin.Engine {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
r := gin.New()
|
||||||
|
r.Use(func(c *gin.Context) {
|
||||||
|
if sess != nil {
|
||||||
|
c.Set(ctxKey, sess)
|
||||||
|
}
|
||||||
|
}, CSRF())
|
||||||
|
r.Any("/x", func(c *gin.Context) { c.Status(http.StatusNoContent) })
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCSRF(t *testing.T) {
|
||||||
|
sess := &Session{CSRF: "good"}
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
sess *Session
|
||||||
|
method string
|
||||||
|
header string
|
||||||
|
origin string
|
||||||
|
form string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"safe method", sess, http.MethodGet, "", "", "", 204},
|
||||||
|
{"missing token", sess, http.MethodPost, "", "", "", 403},
|
||||||
|
{"wrong token", sess, http.MethodPost, "bad", "", "", 403},
|
||||||
|
{"header token", sess, http.MethodPost, "good", "", "", 204},
|
||||||
|
{"form token", sess, http.MethodPost, "", "", "_csrf=good", 204},
|
||||||
|
{"no session", nil, http.MethodPost, "", "", "", 204},
|
||||||
|
{"same origin", nil, http.MethodPost, "", "http://example.com", "", 204},
|
||||||
|
{"foreign origin without session", nil, http.MethodPost, "", "https://evil.test", "", 403},
|
||||||
|
{"foreign origin with token", sess, http.MethodPost, "good", "https://evil.test", "", 403},
|
||||||
|
{"opaque origin", nil, http.MethodPost, "", "null", "", 403},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
req := httptest.NewRequest(tc.method, "/x", strings.NewReader(tc.form))
|
||||||
|
if tc.form != "" {
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
}
|
||||||
|
if tc.origin != "" {
|
||||||
|
req.Header.Set("Origin", tc.origin)
|
||||||
|
}
|
||||||
|
if tc.header != "" {
|
||||||
|
req.Header.Set(CSRFHeader, tc.header)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
csrfRouter(tc.sess).ServeHTTP(w, req)
|
||||||
|
if w.Code != tc.want {
|
||||||
|
t.Errorf("%s: got %d want %d", tc.name, w.Code, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user