csrf

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2023 License: MIT Imports: 9 Imported by: 98

README

mw-csrf

Standard Test Go Reference

Requirements
  • Go 1.16+ but 1.17 and 1.18 are officially supported
  • Go Modules
Installation
$ go get github.com/gobuffalo/mw-csrf
Official Middleware Documentation

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoReferer is returned when a HTTPS request provides an empty Referer
	// header.
	ErrNoReferer = errors.New("referer not supplied")
	// ErrBadReferer is returned when the scheme & host in the URL do not match
	// the supplied Referer header.
	ErrBadReferer = errors.New("referer invalid")
	// ErrNoToken is returned if no CSRF token is supplied in the request.
	ErrNoToken = errors.New("CSRF token not found in request")
	// ErrBadToken is returned if the CSRF token in the request does not match
	// the token in the session, or is otherwise malformed.
	ErrBadToken = errors.New("CSRF token invalid")
)
View Source
var New = func(next buffalo.Handler) buffalo.Handler {

	if envy.Get("GO_ENV", "development") == "test" {
		return func(c buffalo.Context) error {
			c.Logger().Warn("csrf middleware is running in test mode")
			c.Set(tokenKey, "test")
			return next(c)
		}
	}

	return func(c buffalo.Context) error {
		req := c.Request()

		var realToken []byte
		var err error
		rawRealToken := c.Session().Get(tokenKey)

		if rawRealToken == nil || len(rawRealToken.([]byte)) != tokenLength {

			realToken, err = generateRandomBytes(tokenLength)
			if err != nil {
				return err
			}

			c.Session().Set(tokenKey, realToken)
		} else {
			realToken = rawRealToken.([]byte)
		}

		c.Set(fieldName, mask(realToken, req))

		if !contains(safeMethods, req.Method) {

			if req.URL.Scheme == "https" {

				referer, err := url.Parse(req.Referer())
				if err != nil || referer.String() == "" {
					return c.Error(http.StatusForbidden, ErrNoReferer)
				}

				if !sameOrigin(req.URL, referer) {
					return c.Error(http.StatusForbidden, ErrBadReferer)
				}
			}

			requestToken := unmask(requestCSRFToken(req))

			if requestToken == nil {
				return c.Error(http.StatusForbidden, ErrNoToken)
			}

			if !compareTokens(requestToken, realToken) {
				return c.Error(http.StatusForbidden, ErrBadToken)
			}
		}

		return next(c)
	}
}

New enable CSRF protection on routes using this middleware. This middleware is adapted from gorilla/csrf

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

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