crumb

package
v3.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2025 License: BSD-3-Clause Imports: 24 Imported by: 0

README

go-http/v3/crumb

Go package for creating and validating (HTTP) crumbs.

Example

The following are abbreviated code examples. Error handling has been omitted for the sake of brevity.

Simple (Encypted crumbs)
import (
       "context"
       
       "github.com/aaronland/go-http/v3/crumb"
)

func main() {
	cr_uri := "encrypted://?extra=f3gKgLVX&key=&secret=oK5OFCjBsvAOrfJPnzAJqnkphkuDmyf9&separator=%3A&ttl=3600"
	cr, _ := crumb.NewCrumb(ctx, uri)
}

HTTP (Simple)

Use the crumb.EnsureCrumbHandler middleware handler to automatically generate a new crumb string for all requests and append it to any HTML output as a html/body@data-crumb attribute value.

For POST and PUT requests the (middleware) handler intercept the current handler and look for a crumb form value and validate it before continuing.

import (
       "context"
       "net/http"

       "github.com/aaronland/go-http/v3/crumb"
)

func MyHandler() http.Handler {

	fn := func(rsp http.ResponseWriter, req *http.Request) {
		rsp.Write([]byte("Hello world"))
	}

	return http.HandlerFunc(fn)
}

func main() {

	ctx := context.Background()
	
	uri, _ := crumb.NewRandomEncryptedCrumbURI(ctx, 3600)
	cr, _ := crumb.NewCrumb(ctx, uri)

	mux := http.NewServeMux()
	
	my_handler, _ := MyHandler()
	my_handler = crumb.EnsureCrumbHandler(cr, my_handler)

	mux.Handle("/", my_handler)
}
HTTP (Doing it yourself)
import (
       "context"
       "net/http"

       "github.com/aaronland/go-http/v3/crumb"
)

func CrumbHandler() (http.Handler, error) {

	ctx := context.Background()
	
	uri, _ := crumb.NewRandomEncryptedCrumbURI(ctx, 3600)
	cr, _ := crumb.NewCrumb(ctx, uri)

	fn := func(rsp http.ResponseWriter, req *http.Request) {

		if req.URL.Method == "GET" {
			cr_hash, _ := cr.Generate(req)
			// pass cr_hash to template
		} else {

			// read cr_hash from POST form here
			ok, _ := cr.Validate(req, cr_hash)	
		}
	}

	h := http.HandlerFunc(fn)
	return h, nil
}

Schemes

encrypted:///?secret={SECRET}&extra={EXTRA}&ttl={TTL}&separator={SEPARATOR}

For example:

encrypted:///?secret={SECRET}&extra={EXTRA}&ttl={TTL}&separator={SEPARATOR}
Parameter Description Required
secret A valid AES secret for encrypting the crumb yes
extra A string to include when generating crumb base yes
separator A string to separate crumb parts with yes
ttl Time to live (in seconds) yes
key A string to prepend crumb base with. Default is to use the path of the current HTTP request no

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnsureCrumbHandler

func EnsureCrumbHandler(cr Crumb, next_handler go_http.Handler) go_http.Handler

EnsureCrumbHandler wraps 'next_handler' with a middleware `http.Handler` for assigning and validating crumbs using the default `fomuseum/go-http-fault/v2.FaultHandler` as an error handler. Any errors that trigger the error handler can be retrieved using `sfomuseum/go-http-fault/v2.RetrieveError()`.

func EnsureCrumbHandlerWithErrorHandler

func EnsureCrumbHandlerWithErrorHandler(cr Crumb, next_handler go_http.Handler, error_handler go_http.Handler) go_http.Handler

EnsureCrumbHandlerWithErrorHandler wraps 'next_handler' with a middleware a middleware `http.Handler` for assigning and validating crumbs using a custom error handler. Any errors that trigger the error handler can be retrieved using `sfomuseum/go-http-fault/v2.RetrieveError()`.

func EnsureCrumbHandlerWithFaultWrapper

func EnsureCrumbHandlerWithFaultWrapper(cr Crumb, next_handler go_http.Handler) go_http.Handler

EnsureCrumbHandlerWithFaultWrapper wraps 'next_handler' with a middleware `http.Handler` for assigning and validating crumbs. Error handling is assumed to be handled by a separate middleware handler provided by a `sfomuseum/go-http-fault/v2.FaultWrapper`. instance. Any errors that are triggered as recorded using the `sfomuseum/go-http-fault/v2.AssignError()` method and can be retrieved using `sfomuseum/go-http-fault/v2.RetrieveError()` method.

func Error

func Error(cl ErrorClass, err error) fault.FaultError

New returns a new `CrumbError` instance.

func NewCrumbRewriteFunc

func NewCrumbRewriteFunc(crumb_var string) rewrite.RewriteHTMLFunc

NewCrumbRewriteFunc returns a `aaronland/go-http-rewrite.RewriteHTMLFunc` used to append crumb data to HTML output.

func NewRandomEncryptedCrumbExtra

func NewRandomEncryptedCrumbExtra() (string, error)

NewRandomEncryptedCrumbExtra returns a random extra value suitable for `encrypted://` crumb URIs.

func NewRandomEncryptedCrumbSecret

func NewRandomEncryptedCrumbSecret() (string, error)

NewRandomEncryptedCrumbSecret returns a random salt value suitable for `encrypted://` crumb URIs.

func NewRandomEncryptedCrumbURI

func NewRandomEncryptedCrumbURI(ctx context.Context, ttl int, key string) (string, error)

NewRandomEncryptedCrumbURI return a valid `aaronland/go-http-crumb` URI for an encrypted crumb whose key is 'key' and whose time to live is 'ttl'.

func RegisterCrumb

func RegisterCrumb(ctx context.Context, scheme string, f CrumbInitializeFunc) error

RegisterCrumb registers 'scheme' with 'f' for URIs passed to the `NewCrumb` method.

func Schemes

func Schemes() []string

Schemes returns the list of schemes that have registered for use with the `NewCrumb` method.

func SchemesAsString

func SchemesAsString() string

SchemesAsString returns the list of schemes that have registered for use with the `NewCrumb` method as a string.

Types

type Crumb

type Crumb interface {
	// Generate return a new crumb string for an HTTP request.
	Generate(*http.Request, ...string) (string, error)
	// Generate validates a crumb string for an HTTP request.
	Validate(*http.Request, string, ...string) (bool, error)
	// Key returns the unique key used to generate a crumb.
	Key(*http.Request) string
	// Base returns the leading string used to generate a crumb.
	Base(*http.Request, ...string) (string, error)
}

type Crumb is an interface for generating and validating HTTP crumb strings.

func NewCrumb

func NewCrumb(ctx context.Context, uri string) (Crumb, error)

Returns a new `Crumb` instance for 'uri'.

func NewDebugCrumb

func NewDebugCrumb(ctx context.Context, uri string) (Crumb, error)

NewDebugCrumb returns a `EncryptedCrumb` instance with a randomly generated secret and salt valid for 5 minutes configured by 'uri' which should take the form of:

debug://?{QUERY_PARAMETERS}

Where '{QUERY_PARAMETERS}' may be: * `ttl={SECONDS}`. Default is 300

func NewEncryptedCrumb

func NewEncryptedCrumb(ctx context.Context, uri string) (Crumb, error)

NewEncryptedCrumb returns a new `Crumb` instance for 'uri'.

type CrumbError

type CrumbError struct {
	fault.FaultError
	// contains filtered or unexported fields
}

type CrumbError implements the `error` and `fault.FaultError` interfaces for application specific errors.

func (CrumbError) Error

func (e CrumbError) Error() string

String returns an informative string message to be displayed in a public setting.

func (CrumbError) Private

func (e CrumbError) Private() error

Returns the string value of 'e' and of the error passed to 'e' when it was instantiated, if present. These are considered detailed errors not necesarily meant for the general public.

func (CrumbError) Public

func (e CrumbError) Public() error

String returns an informative string message to be displayed in a public setting.

func (CrumbError) Unwrap

func (e CrumbError) Unwrap() error

Unwrap returns the error passed to 'e' when it was instantiated.

type CrumbInitializeFunc

type CrumbInitializeFunc func(context.Context, string) (Crumb, error)

type CrumbInitializeFunc is a function used to initialize packages that implement the `Crumb` interface.

type EncryptedCrumb

type EncryptedCrumb struct {
	Crumb
	// contains filtered or unexported fields
}

type EncryptedCrumb implements the Crumb interface for crumb strings that are encrypted.

func (*EncryptedCrumb) Generate

func (cr *EncryptedCrumb) Generate(req *http.Request, extra ...string) (string, error)

Generate returns a new crumb string for 'req'.

func (*EncryptedCrumb) Key

func (cr *EncryptedCrumb) Key(req *http.Request) string

Key returns the key that 'cr' was instantiated with or, if empty, the path for 'req'.

func (*EncryptedCrumb) Validate

func (cr *EncryptedCrumb) Validate(req *http.Request, enc_var string, extra ...string) (bool, error)

Validates return trues or false if 'enc_var' is a valid crumb for 'req'.

type ErrorClass

type ErrorClass string

type ErrorClass defines application specific error classes (or types)

const ExpiredCrumb ErrorClass = "Crumb has expired."

ExpiredCrumb defines an ErrorClass for crumbs that have expired.

const GenerateCrumb ErrorClass = "Unable to generate crumb"

GenerateCrumb defines an ErrorClass for crumbs that are not able to be generated.

const InvalidCrumb ErrorClass = "Crumb does not validate."

InvalidCrumb defines an ErrorClass for crumbs that do not validate.

const MissingCrumb ErrorClass = "Crumb is missing."

MissingCrumb defines an ErrorClass for crumbs that are missing

const UnsanitizedCrumb ErrorClass = "Crumb supplied is invalid."

UnsanitizedCrumb defines an ErrorClass for crumbs that have failed input validation.

Jump to

Keyboard shortcuts

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