ancla

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2021 License: Apache-2.0 Imports: 28 Imported by: 3

README

ancla

Provides a configurable webhook registry component for XMiDT services. Application code can use the registry directly or as a plug-in for ancla's helper HTTP handlers.

Build Status codecov.io Go Report Card Apache V2 License GitHub release PkgGoDev Quality Gate Status

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

Overview

Package ancla contains the XMiDT event webhook registry. In addition to the main service, ancla provides off the shelf HTTP handlers for both adding and retrieving webhooks.

Index

Constants

View Source
const (
	WebhookListSizeGauge     = "webhook_list_size_value"
	WebhookLegacyDecodeCount = "webhook_legacy_decodings_total"
)

Names

View Source
const (
	OutcomeLabel = "outcome"
	URLLabel     = "url"
)

Labels

View Source
const (
	SuccessOutcome = "success"
	FailureOutcome = "failure"
)

Label Values

Variables

View Source
var (
	SpecialUseIPs = []string{
		"0.0.0.0/8",
		"fe80::/10",
		"255.255.255.255/32",
		"2001::/32",
		"2001:5::/32",
		"2002::/16",
		"fc00::/7",
		"192.0.0.0/24",
		"2001:0000::/23",
		"224.0.0.1/32",
	}
	SpecialUseHosts = []string{
		".example.",
		".invalid.",
		".test.",
		"localhost",
	}
)

Functions

func Metrics

func Metrics() []xmetrics.Metric

Metrics returns the Metrics relevant to this package.

func NewAddWebhookHandler

func NewAddWebhookHandler(s Service, config HandlerConfig) http.Handler

NewAddWebhookHandler returns an HTTP handler for adding a webhook registration.

func NewGetAllWebhooksHandler

func NewGetAllWebhooksHandler(s Service) http.Handler

NewGetAllWebhooksHandler returns an HTTP handler for fetching all the currently registered webhooks.

Types

type Config

type Config struct {
	// Argus contains configuration to initialize an Argus client.
	Argus chrysom.ClientConfig

	// Logger for this package.
	// Gets passed to Argus config before initializing the client.
	// (Optional). Defaults to a no op logger.
	Logger log.Logger

	// MetricsProvider for instrumenting this package.
	// Gets passed to Argus config before initializing the client.
	MetricsProvider xmetrics.Registry

	// JWTParserType establishes which parser type will be used by the JWT token
	// acquirer used by Argus. Options include 'simple' and 'raw'.
	// Simple: parser assumes token payloads have the following structure: https://github.com/xmidt-org/bascule/blob/c011b128d6b95fa8358228535c63d1945347adaa/acquire/bearer.go#L77
	// Raw: parser assumes all of the token payload == JWT token
	// (Optional). Defaults to 'simple'
	JWTParserType jwtAcquireParserType
}

Config contains information needed to initialize the webhook service.

type DeliveryConfig added in v0.1.1

type DeliveryConfig struct {
	// URL is the HTTP URL to deliver messages to.
	URL string `json:"url"`

	// ContentType is content type value to set WRP messages to (unless already specified in the WRP).
	ContentType string `json:"content_type"`

	// Secret is the string value for the SHA1 HMAC.
	// (Optional, set to "" to disable behavior).
	Secret string `json:"secret,omitempty"`

	// AlternativeURLs is a list of explicit URLs that should be round robin through on failure cases to the main URL.
	AlternativeURLs []string `json:"alt_urls,omitempty"`
}

DeliveryConfig is a Webhook substructure with data related to event delivery.

type HandlerConfig added in v0.1.1

type HandlerConfig struct {
	MetricsProvider provider.Provider
	V               Validator
}

HandlerConfig contains configuration for all components that handlers depend on from the service to the transport layers.

type MetadataMatcherConfig added in v0.1.1

type MetadataMatcherConfig struct {
	// DeviceID is the list of regular expressions to match device id type against.
	DeviceID []string `json:"device_id"`
}

MetadataMatcherConfig is Webhook substructure with config to match event metadata.

type Service

type Service interface {
	// Add adds the given owned webhook to the current list of webhooks. If the operation
	// succeeds, a non-nil error is returned.
	Add(ctx context.Context, owner string, w Webhook) error

	// AllWebhooks lists all the current registered webhooks.
	AllWebhooks(ctx context.Context) ([]Webhook, error)
}

Service describes the core operations around webhook subscriptions. Initialize() provides a service ready to use and the controls around watching for updates.

func Initialize

func Initialize(cfg Config, getLogger func(ctx context.Context) log.Logger, setLogger func(context.Context, log.Logger) context.Context, watches ...Watch) (Service, func(), error)

Initialize builds the webhook service from the given configuration. It allows adding watchers for the internal subscription state. Call the returned function when you are done watching for updates.

type TTLVConfig added in v0.2.2

type TTLVConfig struct {
	Max    time.Duration
	Jitter time.Duration
	Now    func() time.Time
}

type URLVConfig added in v0.2.2

type URLVConfig struct {
	HTTPSOnly            bool
	AllowLoopback        bool
	AllowIP              bool
	AllowSpecialUseHosts bool
	AllowSpecialUseIPs   bool
	InvalidHosts         []string
	InvalidSubnets       []string
}

type ValidURLFunc added in v0.2.1

type ValidURLFunc func(*url.URL) error

ValidURLFunc takes URLs and ensures they are valid.

func GoodURLScheme added in v0.2.3

func GoodURLScheme(httpsOnly bool) ValidURLFunc

GoodURLScheme creates a ValidURLFunc that checks the scheme of the URL. If httpsOnly is true, then it will only allow URLs with "https" schemes. If httpsOnly is false, it will only allow URLs with "https" and "http" schemes.

func InvalidSubnets added in v0.2.2

func InvalidSubnets(i []string) (ValidURLFunc, error)

InvalidSubnets checks if the given URL is in any subnets we are blocking and returns an error if it is. SpecialIPs will return nil if the URL is not in the subnet.

func RejectAllIPs added in v0.2.1

func RejectAllIPs() ValidURLFunc

RejectALLIPs creates a ValidURLFunc that checks if the URL is an IP and returns an error if it is.

func RejectHosts added in v0.2.1

func RejectHosts(invalidHosts []string) ValidURLFunc

RejectHosts creates a ValidURLFunc that checks the URL and ensures the host does not contain any strings in the list of invalid hosts. It returns an error if the host does include an invalid host name.

func RejectLoopback added in v0.2.1

func RejectLoopback() ValidURLFunc

RejectLoopback creates a ValidURLFunc that returns an error if the given URL is a loopback address.

type Validator added in v0.2.1

type Validator interface {
	Validate(w Webhook) error
}

Validator is a WebhookValidator that allows access to the Validate function.

type ValidatorConfig added in v0.2.2

type ValidatorConfig struct {
	URL URLVConfig
	TTL TTLVConfig
}

type ValidatorFunc added in v0.2.1

type ValidatorFunc func(Webhook) error

ValidatorFunc is a WebhookValidator that takes Webhooks and validates them against functions.

func CheckDeviceID added in v0.2.2

func CheckDeviceID() ValidatorFunc

CheckDeviceID ensures that the DeviceIDs are able to parse into regex.

func CheckDuration added in v0.2.2

func CheckDuration(maxTTL time.Duration) (ValidatorFunc, error)

CheckDuration ensures that 0 <= Duration <= ttl. Duration returns an error if a negative value is given.

func CheckEvents added in v0.2.2

func CheckEvents() ValidatorFunc

CheckEvents makes sure there is at least one value in Events and ensures that all values should parse into regex.

func CheckUntil added in v0.2.2

func CheckUntil(jitter time.Duration, maxTTL time.Duration, now func() time.Time) (ValidatorFunc, error)

CheckUntil ensures that Until, with jitter, is not more than ttl in the future.

func CheckUntilOrDurationExist added in v0.2.2

func CheckUntilOrDurationExist() ValidatorFunc

CheckUntilAndDuration checks if either Until or Duration exists and returns an error if neither exist.

func GoodAlternativeURLs added in v0.2.1

func GoodAlternativeURLs(vs []ValidURLFunc) ValidatorFunc

GoodAlternativeURLs parses the given webhook's Config.AlternativeURLs and returns as soon as the URL is considered invalid. It returns nil if the URL is valid.

func GoodConfigURL added in v0.2.1

func GoodConfigURL(vs []ValidURLFunc) ValidatorFunc

GoodConfigURL parses the given webhook's Config.URL and returns as soon as the URL is considered invalid. It returns nil if the URL is valid.

func GoodFailureURL added in v0.2.1

func GoodFailureURL(vs []ValidURLFunc) ValidatorFunc

GoodFailureURL parses the given webhook's FailureURL and returns as soon as the URL is considered invalid. It returns nil if the URL is valid.

func (ValidatorFunc) Validate added in v0.2.1

func (vf ValidatorFunc) Validate(w Webhook) error

Validate runs the function and returns the result. This allows any ValidatorFunc to implement the Validator interface.

type Validators added in v0.2.1

type Validators []Validator

Validators is a WebhookValidator that ensures the webhook is valid with each validator in the list.

func BuildValidators added in v0.2.2

func BuildValidators(config ValidatorConfig) (Validators, error)

BuildValidators translates the configuration into a list of validators to be run on the webhook.

func (Validators) Validate added in v0.2.1

func (vs Validators) Validate(w Webhook) error

Validate runs the given webhook through each validator in the validators list. It returns as soon as the webhook is considered invalid and returns nil if the webhook is valid.

type Watch

type Watch interface {
	Update([]Webhook)
}

Watch is the interface for listening for webhook subcription updates. Updates represent the latest known list of subscriptions.

type WatchFunc

type WatchFunc func([]Webhook)

WatchFunc allows bare functions to pass as Watches.

func (WatchFunc) Update

func (f WatchFunc) Update(update []Webhook)

type Webhook

type Webhook struct {
	// Address is the subscription request origin HTTP Address.
	Address string `json:"registered_from_address"`

	// Config contains data to inform how events are delivered.
	Config DeliveryConfig `json:"config"`

	// FailureURL is the URL used to notify subscribers when they've been cut off due to event overflow.
	// Optional, set to "" to disable notifications.
	FailureURL string `json:"failure_url"`

	// Events is the list of regular expressions to match an event type against.
	Events []string `json:"events"`

	// Matcher type contains values to match against the metadata.
	Matcher MetadataMatcherConfig `json:"matcher,omitempty"`

	// Duration describes how long the subscription lasts once added.
	// Deprecated. User input is ignored and value is always 5m.
	Duration time.Duration `json:"duration"`

	// Until describes the time this subscription expires.
	Until time.Time `json:"until"`
}

Webhook contains all the information needed to serve events to webhook listeners.

Jump to

Keyboard shortcuts

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