Documentation
¶
Overview ¶
Package csrf protects state-changing requests from cross-site request forgery using Go's http.CrossOriginProtection (Fetch Metadata and Origin checks, no tokens needed in modern browsers), with an optional session-token fallback for clients that send neither header.
Middleware is installed by vukem.DefaultMiddleware; Config lists trusted origins and explicit bypasses (webhooks). With the fallback on, forms carry Token in the FieldName field (the csrfField template function) or the HeaderName header.
See https://github.com/AlexGalhardo/vukem/blob/main/docs/http.md.
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/AlexGalhardo/vukem/csrf"
)
func main() {
protect, err := csrf.Middleware(csrf.Config{BypassPatterns: []string{"POST /webhooks/"}})
if err != nil {
fmt.Println(err)
return
}
h := protect(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
send := func(path, fetchSite string) int {
req := httptest.NewRequest(http.MethodPost, "http://example.com"+path, http.NoBody)
req.Header.Set("Sec-Fetch-Site", fetchSite)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec.Code
}
fmt.Println("same-origin form:", send("/posts", "same-origin"))
fmt.Println("cross-site form:", send("/posts", "cross-site"))
fmt.Println("cross-site webhook:", send("/webhooks/stripe", "cross-site"))
}
Output: same-origin form: 204 cross-site form: 403 cross-site webhook: 204
Index ¶
Examples ¶
Constants ¶
const FieldName = "_token"
FieldName is the form field carrying the fallback token.
const HeaderName = "X-CSRF-Token"
HeaderName is the request header carrying the fallback token.
Variables ¶
This section is empty.
Functions ¶
func Middleware ¶
Middleware returns CSRF middleware for the router stack (after session middleware when TokenFallback is enabled). Rejections answer 403 through the error handler and log a "csrf.rejected" security event (A01/A08).
Types ¶
type Config ¶
type Config struct {
// TrustedOrigins are other origins allowed to send unsafe requests,
// e.g. "https://admin.example.com".
TrustedOrigins []string
// BypassPatterns are ServeMux patterns exempt from checks (webhooks).
// Bypasses are explicit and logged at boot by the caller.
BypassPatterns []string
// TokenFallback requires a session token on unsafe requests that carry
// neither Sec-Fetch-Site nor Origin but do carry a session (old
// browsers). API clients without sessions are unaffected.
TokenFallback bool
// SessionCookie is the session cookie name (session.Manager.CookieName)
// that marks a request as carrying a session for TokenFallback. Empty,
// any non-empty cookie counts, which also asks API clients holding
// unrelated cookies for a token.
SessionCookie string
}
Config configures Middleware.