csrf

package module
v0.0.0-...-67d642e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2025 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultCookieName     = "csrf_token"
	DefaultHeaderName     = "X-CSRF-Token"
	DefaultSameSite       = "strict"
	DefaultPath           = "/"
	DefaultDomain         = ""
	DefaultTokenLength    = 32
	DefaultHTTPOnlyCookie = true
	DefaultSecureCookie   = true
)

Variables

View Source
var (
	ErrInvalidExcludedRoutes = errors.New("csrf.excluded_routes must not be nil")
	ErrInvalidExcludedRoute  = errors.New("csrf.excluded_route must be absolute and not end with a slash")
	ErrNoSecretKey           = errors.New("csrf.secret_key must not be empty")
	ErrInvalidCookieName     = errors.New("csrf.cookie_name must not be empty or contain invalid characters")
	ErrInvalidHeaderName     = errors.New("csrf.header_name must not be empty or contain invalid characters")
	ErrInvalidSameSite       = errors.New("csrf.same_site is not valid")
	ErrInvalidPath           = errors.New("csrf.path must be absolute and not end with a slash")
	ErrInvalidTokenLength    = errors.New("csrf.token_length must be greater than 0")
	ErrNoSigner              = errors.New("csrf.signer must not be nil")
	ErrNoLogger              = errors.New("csrf.logger cannot be empty")

	//nolint:gochecknoglobals // Maintain a set of predefined http.SameSite that are used throughout the application.
	SameSites = map[string]http.SameSite{
		"lax":    http.SameSiteLaxMode,
		"strict": http.SameSiteStrictMode,
		"none":   http.SameSiteNoneMode,
	}
)
View Source
var (
	ErrTokenGeneration             = errors.New("failed to generate CSRF token")
	ErrCookieRetrieval             = errors.New("failed to retrieve CSRF cookie")
	ErrTokenDecoding               = errors.New("failed to decode CSRF token")
	ErrInvalidSubmittedTokenLength = errors.New("submitted CSRF token length is invalid")
	ErrInvalidTokenSignature       = errors.New("token signature is invalid")
)

Functions

func HeaderToken

func HeaderToken(ctx *gin.Context) (headerName, encodedToken string)

HeaderToken retrieves the CSRF token and its associated header name from the context. It returns the header name and the encoded token if they are present in the context, otherwise it returns empty strings.

func New

func New(config *Config, routerGroup *gin.RouterGroup) gin.HandlerFunc

Types

type Config

type Config struct {

	// ExcludedRoutes is a list of routes that are excluded from CSRF protection.
	ExcludedRoutes []string `json:"excluded_routes" yaml:"excluded_routes" mapstructure:"excluded_routes"`

	// SecretKey is used to generate and validate CSRF tokens.
	SecretKey []byte `json:"secret_key" yaml:"secret_key" mapstructure:"secret_key"`

	// CookieName is the name of the cookie where the CSRF token will be stored.
	CookieName string `json:"cookie_name" yaml:"cookie_name" mapstructure:"cookie_name"`

	// HeaderName is the name of the header where the CSRF token will be expected in requests.
	HeaderName string `json:"header_name" yaml:"header_name" mapstructure:"header_name"`

	// SameSite is the SameSite policy for the CSRF cookie.
	SameSite string `json:"same_site" yaml:"same_site" mapstructure:"same_site"`

	// Path is the path for which the CSRF cookie is valid.
	Path string `json:"path" yaml:"path" mapstructure:"path"`

	// Domain is the domain for which the CSRF cookie is valid.
	Domain string `json:"domain" yaml:"domain" mapstructure:"domain"`

	// TokenLength is the length of the CSRF token.
	TokenLength int `json:"token_length" yaml:"token_length" mapstructure:"token_length"`

	// Signer is a function that returns a new hash.Hash to be used for signing CSRF tokens.
	Signer func() hash.Hash

	// Logger specifies the used logger instance.
	Logger *logger.Logger

	// HTTPOnlyCookie indicates whether the CSRF cookie should be marked as HTTP only.
	HTTPOnlyCookie bool `json:"http_only_cookie" yaml:"http_only_cookie" mapstructure:"http_only_cookie"`

	// SecureCookie indicates whether the CSRF cookie should be marked as secure (HTTPS only).
	SecureCookie bool `json:"secure_cookie" yaml:"secure_cookie" mapstructure:"secure_cookie"`
	// contains filtered or unexported fields
}

Config holds configuration related to CSRF protection.

func NewConfig

func NewConfig(log *logger.Logger) *Config

NewConfig creates and returns a new Config having default values.

func (*Config) SetSameSite

func (r *Config) SetSameSite(sameSite string) error

SetSameSite sets the SameSite attribute for the Config struct. It takes a string parameter SameSite and returns an error if the value is invalid. If SameSite is an empty string, it uses the existing value in the Config struct.

func (*Config) Validate

func (r *Config) Validate() error

Validate ensures the all necessary configurations are filled and within valid confines. Any misconfiguration results in well-defined standardized errors.

type Token

type Token struct {
	Message   []byte
	Signature []byte
	// contains filtered or unexported fields
}

Token represents a signed cookie-based token with a randomly generated message, its signature, and a URL-friendly string.

func NewToken

func NewToken(config *Config) (*Token, error)

NewToken generates a new CSRF token using the provided configuration.

func NewTokenFromCookie

func NewTokenFromCookie(config *Config, ctx *gin.Context) (*Token, error)

NewTokenFromCookie retrieves and validates a CSRF token from a cookie.

func (*Token) Compare

func (r *Token) Compare(token string) bool

Compare securely compares the provided token with the stored token.

func (*Token) String

func (r *Token) String() string

String returns the encoded token as a string.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL