ancla

package module
v0.3.12 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2023 License: Apache-2.0 Imports: 31 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 GoDoc

Maintenance Instructions

This repository uses shared-go for it's workflows. Here is documentation for how to best maintain this repository.

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

SPDX-FileCopyrightText: 2022 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

Index

Constants

View Source
const (
	WebhookListSizeGaugeName     = "webhook_list_size"
	WebhookListSizeGaugeHelp     = "Size of the current list of webhooks."
	ChrysomPollsTotalCounterName = chrysom.PollCounter
	ChrysomPollsTotalCounterHelp = "Counter for the number of polls (and their success/failure outcomes) to fetch new items."
)

Names

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

Outcomes

View Source
const (
	OutcomeLabel = "outcome"
)

Labels

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",
	}
)
View Source
var (
	DefaultBasicPartnerIDsHeader = "X-Xmidt-Partner-Ids"
)

Functions

func InternalWebhookToItem added in v0.3.6

func InternalWebhookToItem(now func() time.Time, iw InternalWebhook) (model.Item, error)

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, config HandlerConfig) http.Handler

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

func NewService added in v0.3.10

func NewService(cfg Config, getLogger func(context.Context) *zap.Logger) (*service, error)

NewService builds the Argus client service from the given configuration.

func ProvideMetrics added in v0.3.8

func ProvideMetrics() fx.Option

ProvideMetrics provides the metrics relevant to this package as uber/fx options.

Types

type Config

type Config struct {
	BasicClientConfig chrysom.BasicClientConfig

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

	// 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

	// DisablePartnerIDs, if true, will allow webhooks to register without
	// checking the validity of the partnerIDs in the request
	DisablePartnerIDs bool

	// Validation provides options for validating the webhook's URL and TTL
	// related fields. Some validation happens regardless of the configuration:
	// URLs must be a valid URL structure, the Matcher.DeviceID values must
	// compile into regular expressions, and the Events field must have at
	// least one value and all values must compile into regular expressions.
	Validation ValidatorConfig
}

Config contains information needed to initialize the Argus Client service.

type CustomDuration added in v0.3.9

type CustomDuration time.Duration

func (CustomDuration) MarshalJSON added in v0.3.9

func (cd CustomDuration) MarshalJSON() ([]byte, error)

func (CustomDuration) String added in v0.3.9

func (cd CustomDuration) String() string

func (*CustomDuration) UnmarshalJSON added in v0.3.9

func (cd *CustomDuration) UnmarshalJSON(b []byte) (err error)

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 {
	V                 Validator
	DisablePartnerIDs bool
	GetLogger         func(context.Context) *zap.Logger
}

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

type InternalWebhook added in v0.3.0

type InternalWebhook struct {
	PartnerIDs []string
	Webhook    Webhook
}

func ItemToInternalWebhook added in v0.3.6

func ItemToInternalWebhook(i model.Item) (InternalWebhook, error)

func ItemsToInternalWebhooks added in v0.3.6

func ItemsToInternalWebhooks(items []model.Item) ([]InternalWebhook, error)

type InvalidDurationError added in v0.3.9

type InvalidDurationError struct {
	Value string
}

func (*InvalidDurationError) Error added in v0.3.9

func (ide *InvalidDurationError) Error() string

type ListenerConfig added in v0.3.10

type ListenerConfig struct {
	Config chrysom.ListenerClientConfig

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

	// Measures for instrumenting this package.
	// Gets passed to Argus config before initializing the client.
	Measures Measures
}

ListenerConfig contains information needed to initialize the Listener Client service.

type Measures added in v0.3.8

type Measures struct {
	WebhookListSizeGaugeName     prometheus.Gauge       `name:"webhook_list_size"`
	ChrysomPollsTotalCounterName *prometheus.CounterVec `name:"chrysom_polls_total"`
}

Measures describes the defined metrics that will be used by clients.

type MeasuresIn added in v0.3.8

type MeasuresIn struct {
	fx.In

	Factory *touchstone.Factory `optional:"true"`
}

MeasuresIn is an uber/fx parameter with the webhook registration counter.

type MeasuresOut added in v0.3.11

type MeasuresOut struct {
	fx.Out

	M *Measures
}

func NewMeasures added in v0.3.8

func NewMeasures(in MeasuresIn) (MeasuresOut, error)

NewMeasures realizes desired metrics.

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, iw InternalWebhook) error

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

Service describes the core operations around webhook subscriptions. Initialize() provides a service ready to use and the controls around 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 AlwaysValid added in v0.3.5

func AlwaysValid() ValidatorFunc

AlwaysValid doesn't check anything in the webhook and never returns an error.

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([]InternalWebhook)
}

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

type WatchFunc

type WatchFunc func([]InternalWebhook)

WatchFunc allows bare functions to pass as Watches.

func (WatchFunc) Update

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

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.
	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.

func InternalWebhooksToWebhooks added in v0.3.6

func InternalWebhooksToWebhooks(iws []InternalWebhook) []Webhook

type WebhookRegistration added in v0.3.9

type WebhookRegistration 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.
	Duration CustomDuration `json:"duration"`

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

WebhookRegistration is a special struct for unmarshaling a webhook as part of a webhook registration request. The only difference between this struct and the Webhook struct is the Duration field.

func (WebhookRegistration) ToWebhook added in v0.3.9

func (w WebhookRegistration) ToWebhook() Webhook

Jump to

Keyboard shortcuts

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