listener

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2023 License: Apache-2.0 Imports: 19 Imported by: 10

README

wrp-listener

wrp-listener is a library that provides a webhook registerer and a validation function to be used for authentication.

Build Status codecov.io Go Report Card Apache V2 License GitHub Release GoDoc

Summary

`wrp-listener`` provides a package to help a consumer register to a webhook and authenticate messages received. Registering to a webhook can be done directly or set up to run at an interval.

Details

The below code snippet gets you registered to the webhook and events flowing to you.

	l, err := listener.New("https://example.com",
		&webhook.Registration{
			Config: webhook.DeliveryConfig{
				ReceiverURL: receiverURL,
				ContentType: contentType,
			},
			Events:   []string{events},
			Duration: webhook.CustomDuration(5 * time.Minute),
		},		
		listener.AcceptSHA1(),
		listener.Interval(1 * time.Minute),
		listener.AcceptedSecrets(sharedSecrets...),
	)
	if err != nil {
		panic(err)
	}

    err = l.Register(context.Background(), sharedSecrets[0])
	if err != nil {
		panic(err)
	}

Authorization that the information from the webhook likstener provider is also pretty simple.

func (el *eventListener) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	token, err := el.l.Tokenize(r)
    if err != nil {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	err = el.l.Authorize(r, token)
	if err != nil {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	// ... do more stuff ...

	w.WriteHeader(http.StatusOK)
}

The full example found in cmd/bearerListener/main.go is a working command line example that shows how to use the library from end to end.

Additional examples can be found in the example_test.go file.

Functional tests are found in functional_test.go

Code of Conduct

This project and everyone participating in it are governed by the XMiDT Code Of Conduct. By participating, you agree to this Code.

Contributing

Refer to CONTRIBUTING.md.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInput is returned when an invalid input is provided.
	ErrInput = errors.New("invalid input")

	// ErrInvalidTokenHeader is returned when the token header is invalid.
	ErrInvalidTokenHeader = errors.New("invalid token header")

	// ErrRegistrationFailed is returned when the webhook registration fails.
	ErrRegistrationFailed = errors.New("registration failed")

	// ErrRegistrationNotAttempted is returned when the webhook registration
	// was not attempted.
	ErrRegistrationNotAttempted = errors.New("registration not attempted")

	// ErrNotAcceptedHash is returned when the hash is not accepted, because it
	// is not in the list of accepted hashes.
	ErrNotAcceptedHash = errors.New("not accepted hash")

	// ErrDecoratorFailed is returned when the decorator returns an error.
	ErrDecoratorFailed = errors.New("decorator failed")

	// ErrNewRequestFailed is returned when the request cannot be created.
	ErrNewRequestFailed = errors.New("new request failed")

	// ErrInvalidHeaderFormat is returned when the header is not in the correct
	// format.
	ErrInvalidHeaderFormat = errors.New("invalid header format")

	// ErrInvalidAlgorithm is returned when the algorithm is not supported.
	ErrAlgorithmNotFound = errors.New("algorithm not found")

	// ErrNoToken is returned when the token is not found.
	ErrNoToken = errors.New("no token")

	// ErrInvalidSignature is returned when the signature is invalid.
	ErrInvalidSignature = errors.New("invalid signature")

	// ErrUnableToReadBody is returned when the body cannot be read.
	ErrUnableToReadBody = errors.New("unable to read body")
)

Functions

This section is empty.

Types

type CancelEventListenerFunc added in v0.5.0

type CancelEventListenerFunc func()

CancelEventListenerFunc removes the listener it's associated with and cancels any future events sent to that listener.

A CancelEventListenerFunc is idempotent: after the first invocation, calling this closure will have no effect.

type Decorator added in v0.5.0

type Decorator interface {
	fmt.Stringer
	Decorate(*http.Request) error
}

A Decorator decorates an http request before it is sent to the webhook registration endpoint.

type DecoratorFunc added in v0.5.0

type DecoratorFunc func(*http.Request) error

The Decorator type is an adapter to allow the use of ordinary functions as decorators. If f is a function with the appropriate signature, DecoratorFunc(f) is a Decorator that calls f.

func (DecoratorFunc) Decorate added in v0.5.0

func (d DecoratorFunc) Decorate(r *http.Request) error

func (DecoratorFunc) String added in v0.5.0

func (d DecoratorFunc) String() string

type Listener added in v0.4.0

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

Listener provides a way to register a webhook and validate the callbacks. It can be configured to register the webhook at a given interval, as well as it can also be configured to accept multiple secrets and hash algorithms.

func New added in v0.4.0

func New(url string, r *webhook.Registration, opts ...Option) (*Listener, error)

New creates a new webhook listener with the given registration and options.

func (*Listener) Accept added in v0.4.0

func (l *Listener) Accept(secrets []string)

Accept defines the entire list of secrets to accept for the webhook callbacks. If any of the secrets match the secret in the token, the request will be authorized.

func (*Listener) AddAuthorizeEventListener added in v0.5.0

func (l *Listener) AddAuthorizeEventListener(listener event.AuthorizeListener) CancelEventListenerFunc

AddAuthorizeEventListener adds an event listener to the webhook listener. The listener will be called for each event that occurs. The returned function can be called to remove the listener.

func (*Listener) AddRegistrationEventListener added in v0.5.0

func (l *Listener) AddRegistrationEventListener(listener event.RegistrationListener) CancelEventListenerFunc

AddRegistrationEventListener adds an event listener to the webhook listener. The listener will be called for each event that occurs. The returned function can be called to remove the listener.

func (*Listener) AddTokenizeEventListener added in v0.5.0

func (l *Listener) AddTokenizeEventListener(listener event.TokenizeListener) CancelEventListenerFunc

AddTokenizeEventListener adds an event listener to the webhook listener. The listener will be called for each event that occurs. The returned function can be called to remove the listener.

func (*Listener) Authorize added in v0.4.0

func (l *Listener) Authorize(r *http.Request, t Token) error

Authorize validates that the request body matches the hash and secret provided in the token.

func (*Listener) Register added in v0.4.0

func (l *Listener) Register(ctx context.Context, secret ...string) error

Register registers the webhook listener using the optional specified secret. If the interval is greater than 0 the registrations will continue until Stop() is called or the parent context is canceled. If the listener is already running, the secret will be updated immediately. If the secret is not provided, the current secret will be used. Only the first secret will be used if multiple secrets are provided.

func (*Listener) Stop added in v0.4.0

func (l *Listener) Stop()

Stop stops the webhook listener. If the listener is not running, this is a no-op.

func (*Listener) String added in v0.4.0

func (l *Listener) String() string

String returns a string representation of the webhook listener and the options used to configure it.

func (*Listener) Tokenize added in v0.4.0

func (l *Listener) Tokenize(r *http.Request) (*token, error)

Tokenize parses the token from the request header. If the token is not found or is invalid, an error is returned.

type Option added in v0.4.0

type Option interface {
	fmt.Stringer
	// contains filtered or unexported methods
}

Option is an interface that is used to configure the webhook listener.

func AcceptCustom added in v0.4.0

func AcceptCustom(name string, h func() hash.Hash) Option

AcceptCustom is an option that sets the hash to use for the webhook callback validation to use. A nil hash is not accepted.

func AcceptNoHash added in v0.4.0

func AcceptNoHash() Option

AcceptNoHash enables the use of no hash for the webhook listener callback validation.

USE WITH CAUTION.

func AcceptSHA1 added in v0.4.0

func AcceptSHA1() Option

AcceptSHA1 enables the use of the sha1 hash for the webhook listener callback validation.

func AcceptSHA256 added in v0.4.0

func AcceptSHA256() Option

AcceptSHA256 enables the use of the sha256 hash for the webhook listener callback validation.

func AcceptedSecrets added in v0.4.0

func AcceptedSecrets(secrets ...string) Option

AcceptedSecrets is an option that provides the list of secrets accepted by the webhook listener when validating the callback event. A valid hash (or multiple) must be provided as well.

func DecorateRequest added in v0.5.0

func DecorateRequest(d Decorator) Option

DecorateRequest is an option that provides the function to use to decorate the http request before it is sent to the webhook registration endpoint. This is useful for adding headers or other information to the request.

Examples of this include adding an authorization header, or additional headers to the request.

Multiple DecorateRequest options can be provided. They will be called in the order they are provided.

func HTTPClient added in v0.4.0

func HTTPClient(c *http.Client) Option

HTTPClient is an option that provides the http client to use for the webhook listener registration to use. A nil value will cause the default http client to be used.

func Interval added in v0.4.0

func Interval(i time.Duration) Option

Interval is an option that sets the interval to wait between webhook registration attempts. The default is to only register once. This option must be greater than or equal to 0. A value of 0 will cause the webhook to only be registered once.

func Once added in v0.4.0

func Once() Option

Once is an option that sets the webhook to only be registered once. This is the default behavior.

func WebhookOpts added in v0.4.0

func WebhookOpts(opts ...webhook.Option) Option

WebhookOpts is an option that provides the webhook.Options to apply during the validation of the registration of the webhook.

func WithAuthorizeEventListener added in v0.6.0

func WithAuthorizeEventListener(listener event.AuthorizeListener, cancel ...*CancelEventListenerFunc) Option

WithRegistrationEventListener is an option that provides the listener to use for webhook registration events. If the optional cancel parameter is provided, it will be set to a function that can be used to cancel the listener.

func WithRegistrationEventListener added in v0.6.0

func WithRegistrationEventListener(listener event.RegistrationListener, cancel ...*CancelEventListenerFunc) Option

WithRegistrationEventListener is an option that provides the listener to use for webhook registration events. If the optional cancel parameter is provided, it will be set to a function that can be used to cancel the listener.

func WithTokenizeEventListener added in v0.6.0

func WithTokenizeEventListener(listener event.TokenizeListener, cancel ...*CancelEventListenerFunc) Option

WithTokenizeEventListener is an option that provides the listener to use for webhook tokenize events. If the optional cancel parameter is provided, it will be set to a function that can be used to cancel the listener.

type Token added in v0.4.0

type Token interface {
	Type() string
	Principal() string
}

Token represents the information needed to authenticate the flow of incoming webhook callbacks.

Directories

Path Synopsis
cmd
examples
basicListener Module
timedListener Module

Jump to

Keyboard shortcuts

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