basculehttp

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2020 License: Apache-2.0 Imports: 16 Imported by: 20

README

basculehttp

The package for auth related middleware, implemented as alice-style http decorators.

GoDoc

Summary

This package makes it easy to validate the Authorization of an incoming http request.

Decorators

This packages has three http decorators (which act as middleware):

  1. Constructor: Parses the Authorization header into a Token and runs some basic validation using a TokenFactory. The basic validation varies and is determined by the TokenFactory. Basic and JWT TokenFactories are included in the package, but the consumer can also create its own TokenFactory.
    After the Token is created, it is added to the request context.
  2. Enforcer: Gets the Token from the request context and then validates that the Token is authorized using validator functions provided by the consumer.
  3. Listener: Gets the Token from the request context and then provides it to a function set by the consumer and called by the decorator. Some examples of using the Listener is to log a statement related to the Token found, or to add to some metrics based on something in the Token.

Documentation

Overview

package basculehttp contains some basic http middleware (in the form of Alice-style decorators) that can be used to extract and parse a Token from an http header, validate the Token, and allow for the consumer to add additional logs or metrics upon an error or a valid Token.

Index

Constants

View Source
const (
	// DefaultHeaderName is the http header to get the authorization
	// information from.
	DefaultHeaderName = "Authorization"

	// DefaultHeaderDelimiter is the character between the authorization and
	// its key.
	DefaultHeaderDelimiter = " "
)

Variables

View Source
var (
	ErrorMalformedValue    = errors.New("expected <user>:<password> in decoded value")
	ErrorPrincipalNotFound = errors.New("principal not found")
	ErrorInvalidPassword   = errors.New("invalid password")
	ErrorNoProtectedHeader = errors.New("missing protected header")
	ErrorNoSigningMethod   = errors.New("signing method (alg) is missing or unrecognized")
	ErrorUnexpectedPayload = errors.New("payload isn't a map of strings to interfaces")
	ErrorInvalidPrincipal  = errors.New("principal must be a non-empty string")
	ErrorInvalidToken      = errors.New("token isn't valid")
	ErrorUnexpectedClaims  = errors.New("claims wasn't MapClaims as expected")
)

Functions

func DefaultOnErrorResponse

func DefaultOnErrorResponse(_ ErrorResponseReason, _ error)

default function does nothing

func DefaultParseURLFunc added in v0.7.0

func DefaultParseURLFunc(u *url.URL) (*url.URL, error)

DefaultParseURLFunc does nothing. It returns the same url it received.

func NewConstructor

func NewConstructor(options ...COption) func(http.Handler) http.Handler

NewConstructor creates an Alice-style decorator function that acts as middleware: parsing the http request to get a Token, which is added to the context.

func NewEnforcer

func NewEnforcer(options ...EOption) func(http.Handler) http.Handler

NewListenerDecorator creates an Alice-style decorator function that acts as middleware, allowing for Listeners to be called after a token has been authenticated.

func NewErrorHeaderer

func NewErrorHeaderer(err error, headers map[string][]string) error

func NewListenerDecorator

func NewListenerDecorator(listeners ...Listener) func(http.Handler) http.Handler

NewListenerDecorator creates an Alice-style decorator function that acts as middleware, allowing for Listeners to be called after a token has been authenticated.

func WriteResponse

func WriteResponse(response http.ResponseWriter, defaultStatusCode int, v interface{})

WriteResponse performs some basic reflection on v to allow it to modify responses written to an HTTP response. Useful mainly for errors.

Types

type BasicTokenFactory

type BasicTokenFactory map[string]string

BasicTokenFactory parses a basic auth and verifies it is in a map of valid basic auths.

func (BasicTokenFactory) ParseAndValidate

func (btf BasicTokenFactory) ParseAndValidate(ctx context.Context, _ *http.Request, _ bascule.Authorization, value string) (bascule.Token, error)

ParseAndValidate expects the given value to be a base64 encoded string with the username followed by a colon and then the password. The function checks that the username password pair is in the map and returns a Token if it is.

type BearerTokenFactory

type BearerTokenFactory struct {
	DefaultKeyId string
	Resolver     key.Resolver
	Parser       bascule.JWTParser
	Leeway       bascule.Leeway
}

BearerTokenFactory parses and does basic validation for a JWT token.

func (BearerTokenFactory) ParseAndValidate

func (btf BearerTokenFactory) ParseAndValidate(ctx context.Context, _ *http.Request, _ bascule.Authorization, value string) (bascule.Token, error)

ParseAndValidate expects the given value to be a JWT with a kid header. The kid should be resolvable by the Resolver and the JWT should be Parseable and pass any basic validation checks done by the Parser. If everything goes well, a Token of type "jwt" is returned.

type COption

type COption func(*constructor)

COption is any function that modifies the constructor - used to configure the constructor.

func WithCErrorResponseFunc

func WithCErrorResponseFunc(f OnErrorResponse) COption

WithCErrorResponseFunc sets the function that is called when an error occurs.

func WithCLogger

func WithCLogger(getLogger func(context.Context) bascule.Logger) COption

WithCLogger sets the function to use to get the logger from the context. If no logger is set, nothing is logged.

func WithHeaderDelimiter added in v0.3.1

func WithHeaderDelimiter(delimiter string) COption

WithHeaderDelimiter sets the value expected between the authorization key and token.

func WithHeaderName

func WithHeaderName(headerName string) COption

WithHeaderName sets the headername and verifies it's valid. The headername is the name of the header to get the authorization information from.

func WithParseURLFunc added in v0.7.0

func WithParseURLFunc(parseURL ParseURL) COption

WithParseURLFunc sets the function to use to make any changes to the URL before it is added to the context.

func WithTokenFactory

func WithTokenFactory(key bascule.Authorization, tf TokenFactory) COption

WithTokenFactory sets the TokenFactory for the constructor to use.

type EOption

type EOption func(*enforcer)

EOption is any function that modifies the enforcer - used to configure the enforcer.

func WithEErrorResponseFunc

func WithEErrorResponseFunc(f OnErrorResponse) EOption

WithEErrorResponseFunc sets the function that is called when an error occurs.

func WithELogger

func WithELogger(getLogger func(context.Context) bascule.Logger) EOption

WithELogger sets the function to use to get the logger from the context. If no logger is set, nothing is logged.

func WithNotFoundBehavior

func WithNotFoundBehavior(behavior NotFoundBehavior) EOption

WithNotFoundBehavior sets the behavior upon not finding the Authorization value in the rules map.

func WithRules

func WithRules(key bascule.Authorization, v bascule.Validator) EOption

WithRules sets the validator to be used for a given Authorization value.

type ErrorHeaderer

type ErrorHeaderer struct {
	// contains filtered or unexported fields
}

ErrorHeaderer implements headerer, allowing an error to supply http headers in an error response.

func (ErrorHeaderer) Error

func (e ErrorHeaderer) Error() string

func (ErrorHeaderer) Headers

func (e ErrorHeaderer) Headers() http.Header

type ErrorResponseReason

type ErrorResponseReason int

ErrorResponseReason is an enum that specifies the reason parsing/validating a token failed. Its primary use is for metrics and logging.

const (
	MissingHeader ErrorResponseReason = iota
	InvalidHeader
	KeyNotSupported
	ParseFailed
	GetURLFailed
	MissingAuthentication
	ChecksNotFound
	ChecksFailed
)

func (ErrorResponseReason) String

func (i ErrorResponseReason) String() string

type Listener

type Listener interface {
	OnAuthenticated(bascule.Authentication)
}

Listener is anything that takes the Authentication information of an authenticated Token.

type NotFoundBehavior

type NotFoundBehavior int

NotFoundBehavior is an enum that specifies what to do when the Authorization used isn't found in the map of rules.

const (
	Forbid NotFoundBehavior = iota
	Allow
)

func (NotFoundBehavior) String

func (i NotFoundBehavior) String() string

type OnErrorResponse

type OnErrorResponse func(ErrorResponseReason, error)

OnErrorResponse is a function that takes the error response reason and the error and can do something with it. This is useful for adding additional metrics or logs.

type ParseURL added in v0.7.0

type ParseURL func(*url.URL) (*url.URL, error)

ParseURL is a function that modifies the url given then returns it.

func CreateRemovePrefixURLFunc added in v0.7.0

func CreateRemovePrefixURLFunc(prefix string, next ParseURL) ParseURL

CreateRemovePrefixURLFunc parses the URL by removing the prefix specified.

type TokenFactory

type TokenFactory interface {
	ParseAndValidate(context.Context, *http.Request, bascule.Authorization, string) (bascule.Token, error)
}

TokenFactory is a strategy interface responsible for creating and validating a secure Token.

type TokenFactoryFunc

type TokenFactoryFunc func(context.Context, *http.Request, bascule.Authorization, string) (bascule.Token, error)

TokenFactoryFunc makes it so any function that has the same signature as TokenFactory's ParseAndValidate function implements TokenFactory.

func (TokenFactoryFunc) ParseAndValidate

func (tff TokenFactoryFunc) ParseAndValidate(ctx context.Context, r *http.Request, a bascule.Authorization, v string) (bascule.Token, error)

Jump to

Keyboard shortcuts

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