Documentation
¶
Overview ¶
Package csrf implements the double-submit cookie pattern for plain HTML forms on cacheable pages.
Issue wraps the page handler so every GET/HEAD leaves a random token in a cookie (sliding expiry). The token is never embedded in the HTML, so pages stay cacheable; a small script copies the cookie into a hidden form field at submit time (uikit ships one: js/public/csrf.js). Verify then checks that the posted field equals the cookie. A cross-site attacker can make the browser send the cookie but cannot read it to fill the field, and the cookie is SameSite=Strict on top.
guard := csrf.New(csrf.Options{}) // Secure cookie unless HB_ENV=local
mux.Handle("/", guard.Issue(pages))
// in the POST handler:
if err := guard.Verify(r); err != nil { ... reject ... }
Index ¶
Constants ¶
const ( DefaultCookie = "hbl_csrf" DefaultField = "_csrf" DefaultMaxAge = 30 * 24 * time.Hour )
Defaults applied by New.
Variables ¶
var ( ErrCookieMissing = errors.New("csrf: cookie missing") ErrFieldEmpty = errors.New("csrf: form field empty") ErrMismatch = errors.New("csrf: cookie and form field differ") )
Verification errors.
Functions ¶
This section is empty.
Types ¶
type Guard ¶
type Guard struct {
// contains filtered or unexported fields
}
Guard issues and verifies double-submit tokens. Safe for concurrent use.
func New ¶
New applies defaults to opts. Whether the cookie is Secure is decided here, from opts.Insecure and HB_ENV.
type Options ¶
type Options struct {
// Cookie is the token cookie name. It must match what the
// client-side copy script reads.
Cookie string
// Field is the hidden form field name.
Field string
// Insecure drops the cookie's Secure flag. The flag is set by
// default and dropped automatically in local dev
// (siteurl.IsDev(), HB_ENV=local), where pages run on plain
// http://localhost; set Insecure only for another non-TLS setup.
Insecure bool
// MaxAge is the sliding cookie lifetime.
MaxAge time.Duration
}
Options configures a Guard. Zero values take the defaults above.