webhook

package
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package webhook provides event filtering functionality.

Package webhook provides the webhook manager implementation.

Package webhook provides HTTP delivery functionality.

Package webhook provides webhook alerting functionality for the AegisGate AI Security Gateway. It supports configurable webhooks with retry logic, authentication, event filtering, and delivery tracking.

Features:

  • Multiple authentication methods (Basic, Bearer, API Key, HMAC)
  • Configurable retry with exponential backoff
  • Event filtering by severity, category, and source
  • HMAC signature generation for payload integrity
  • TLS/SSL support with certificate verification
  • Delivery status tracking and history
  • Batch delivery support
  • Concurrent webhook delivery with worker pools

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InitGlobalManager

func InitGlobalManager(config ManagerConfig) error

InitGlobalManager initializes the global webhook manager.

func SetGlobalManager

func SetGlobalManager(m *Manager)

SetGlobalManager sets the global webhook manager.

func ValidateConfig

func ValidateConfig(config *WebhookConfig) error

ValidateConfig validates a webhook configuration.

func VerifySignature

func VerifySignature(body []byte, signature string, secret string, algorithm string) bool

VerifySignature verifies an HMAC signature.

Types

type AttributeCondition

type AttributeCondition struct {
	// Attribute key
	Key string
	// Operator (eq, ne, contains, regex, gt, lt, gte, lte, exists)
	Operator string
	// Value to compare
	Value interface{}
	// Case sensitive matching
	CaseSensitive bool
}

AttributeCondition defines a condition for attribute matching.

type AttributeFilter

type AttributeFilter struct {
	// Conditions for attribute matching
	Conditions []AttributeCondition
}

AttributeFilter filters events based on attributes.

func NewAttributeFilter

func NewAttributeFilter() *AttributeFilter

NewAttributeFilter creates a new attribute filter.

func (*AttributeFilter) Allow

func (f *AttributeFilter) Allow(event *siem.Event) bool

Allow implements Filter interface.

func (*AttributeFilter) Match

func (f *AttributeFilter) Match(event *siem.Event) bool

Match implements Filter interface.

func (*AttributeFilter) WithCondition

func (f *AttributeFilter) WithCondition(key, operator string, value interface{}) *AttributeFilter

WithCondition adds a condition.

type Authentication

type Authentication struct {
	// Type of authentication
	Type AuthenticationType `json:"type"`
	// Username for basic auth
	Username string `json:"username,omitempty"`
	// Password for basic auth
	Password string `json:"password,omitempty"`
	// Token for bearer auth
	Token string `json:"token,omitempty"`
	// API key for api_key auth
	APIKey string `json:"api_key,omitempty"`
	// Header name for API key (default: X-API-Key)
	APIKeyHeader string `json:"api_key_header,omitempty"`
	// HMAC configuration for hmac auth
	HMAC *HMACConfig `json:"hmac,omitempty"`
	// OAuth2 configuration
	OAuth2 *OAuth2Config `json:"oauth2,omitempty"`
}

Authentication contains authentication settings for a webhook.

type AuthenticationType

type AuthenticationType string

AuthenticationType represents the type of authentication for a webhook.

const (
	AuthNone   AuthenticationType = "none"    // No authentication
	AuthBasic  AuthenticationType = "basic"   // HTTP Basic authentication
	AuthBearer AuthenticationType = "bearer"  // Bearer token authentication
	AuthAPIKey AuthenticationType = "api_key" // API key authentication
	AuthHMAC   AuthenticationType = "hmac"    // HMAC signature authentication
	AuthOAuth2 AuthenticationType = "oauth2"  // OAuth2 authentication
)

type BatchDeliveryConfig

type BatchDeliveryConfig struct {
	// Enable batch delivery
	Enabled bool `json:"enabled"`
	// Maximum batch size (number of events)
	MaxSize int `json:"max_size"`
	// Maximum batch wait time
	MaxWait time.Duration `json:"max_wait"`
	// Maximum batch size in bytes
	MaxBytes int `json:"max_bytes"`
	// Batch events by webhook
	BatchByWebhook bool `json:"batch_by_webhook"`
}

BatchDeliveryConfig contains settings for batch delivery.

func DefaultBatchDeliveryConfig

func DefaultBatchDeliveryConfig() BatchDeliveryConfig

DefaultBatchDeliveryConfig returns default batch delivery configuration.

type BatchPayload

type BatchPayload struct {
	// Batch ID
	ID string `json:"id"`
	// Timestamp
	Timestamp time.Time `json:"timestamp"`
	// Webhook ID
	WebhookID string `json:"webhook_id"`
	// Events in this batch
	Events []*WebhookPayload `json:"events"`
	// Batch size in bytes
	Size int `json:"size"`
	// Signature for the batch
	Signature string `json:"signature,omitempty"`
}

BatchPayload contains multiple events in a single payload.

func (*BatchPayload) GetID

func (p *BatchPayload) GetID() string

GetID returns the batch ID.

func (*BatchPayload) GetTimestamp

func (p *BatchPayload) GetTimestamp() time.Time

GetTimestamp returns the batch timestamp.

func (*BatchPayload) ToJSON

func (p *BatchPayload) ToJSON() ([]byte, error)

ToJSON returns the JSON representation of BatchPayload.

type CategoryFilter

type CategoryFilter struct {
	// Categories to include (empty = all)
	IncludeCategories []siem.EventCategory
	// Categories to exclude
	ExcludeCategories []siem.EventCategory
}

CategoryFilter filters events based on category.

func NewCategoryFilter

func NewCategoryFilter() *CategoryFilter

NewCategoryFilter creates a new category filter.

func (*CategoryFilter) Allow

func (f *CategoryFilter) Allow(event *siem.Event) bool

Allow implements Filter interface.

func (*CategoryFilter) Match

func (f *CategoryFilter) Match(event *siem.Event) bool

Match implements Filter interface.

func (*CategoryFilter) WithExcludeCategories

func (f *CategoryFilter) WithExcludeCategories(categories ...siem.EventCategory) *CategoryFilter

WithExcludeCategories sets the categories to exclude.

func (*CategoryFilter) WithIncludeCategories

func (f *CategoryFilter) WithIncludeCategories(categories ...siem.EventCategory) *CategoryFilter

WithIncludeCategories sets the categories to include.

type CompositeFilter

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

CompositeFilter combines multiple filters.

func NewCompositeFilter

func NewCompositeFilter() *CompositeFilter

NewCompositeFilter creates a new composite filter.

func (*CompositeFilter) Allow

func (f *CompositeFilter) Allow(event *siem.Event) bool

Allow implements Filter interface.

func (*CompositeFilter) Match

func (f *CompositeFilter) Match(event *siem.Event) bool

Match implements Filter interface.

func (*CompositeFilter) WithFilters

func (f *CompositeFilter) WithFilters(filters ...Filter) *CompositeFilter

WithFilters adds filters.

func (*CompositeFilter) WithMode

func (f *CompositeFilter) WithMode(mode string) *CompositeFilter

WithMode sets the combine mode.

type DeliveryAttempt

type DeliveryAttempt struct {
	// Attempt number
	Attempt int `json:"attempt"`
	// Timestamp of the attempt
	Timestamp time.Time `json:"timestamp"`
	// HTTP status code received
	StatusCode int `json:"status_code,omitempty"`
	// Response body (truncated if too long)
	ResponseBody string `json:"response_body,omitempty"`
	// Response headers
	ResponseHeaders map[string]string `json:"response_headers,omitempty"`
	// Error message if failed
	Error string `json:"error,omitempty"`
	// Duration of the attempt
	Duration time.Duration `json:"duration"`
	// Whether this was the final successful attempt
	Success bool `json:"success"`
	// Whether a retry is pending
	RetryPending bool `json:"retry_pending"`
	// Next retry time if retry pending
	NextRetry time.Time `json:"next_retry,omitempty"`
}

DeliveryAttempt represents a single delivery attempt.

type DeliveryResponse

type DeliveryResponse struct {
	StatusCode  int               `json:"status_code"`
	Headers     map[string]string `json:"headers"`
	Body        string            `json:"body,omitempty"`
	ContentType string            `json:"content_type,omitempty"`
}

DeliveryResponse contains the final response details.

type DeliveryStatus

type DeliveryStatus struct {
	// Webhook ID
	WebhookID string `json:"webhook_id"`
	// Payload ID
	PayloadID string `json:"payload_id"`
	// Current status
	Status WebhookStatus `json:"status"`
	// All delivery attempts
	Attempts []DeliveryAttempt `json:"attempts"`
	// Total attempts made
	TotalAttempts int `json:"total_attempts"`
	// Last attempt timestamp
	LastAttempt time.Time `json:"last_attempt,omitempty"`
	// Last successful delivery
	LastSuccess time.Time `json:"last_success,omitempty"`
	// Created timestamp
	CreatedAt time.Time `json:"created_at"`
	// Final response (after success or max retries)
	FinalResponse *DeliveryResponse `json:"final_response,omitempty"`
}

DeliveryStatus tracks the delivery status of a webhook.

type Error

type Error struct {
	WebhookID string    `json:"webhook_id"`
	Operation string    `json:"operation"`
	Message   string    `json:"message"`
	Retryable bool      `json:"retryable"`
	Cause     error     `json:"cause,omitempty"`
	Timestamp time.Time `json:"timestamp"`
}

Error represents a webhook delivery error.

func NewError

func NewError(webhookID, operation, message string, retryable bool, cause error) *Error

NewError creates a new webhook error.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause.

type EventMatcher

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

EventMatcher matches events against trigger conditions.

func NewEventMatcher

func NewEventMatcher() *EventMatcher

NewEventMatcher creates a new event matcher.

func (*EventMatcher) AddFilter

func (m *EventMatcher) AddFilter(name string, filter Filter)

AddFilter adds a filter with a name.

func (*EventMatcher) Match

func (m *EventMatcher) Match(event *siem.Event) bool

Match checks if an event matches any registered filter.

func (*EventMatcher) MatchAll

func (m *EventMatcher) MatchAll(event *siem.Event) bool

MatchAll checks if an event matches all registered filters.

func (*EventMatcher) MatchNamed

func (m *EventMatcher) MatchNamed(event *siem.Event, name string) bool

MatchNamed checks if an event matches a specific named filter.

func (*EventMatcher) MatchTriggers

func (m *EventMatcher) MatchTriggers(event *siem.Event, triggers []TriggerCondition) bool

MatchTriggers checks if an event matches trigger conditions.

func (*EventMatcher) RemoveFilter

func (m *EventMatcher) RemoveFilter(name string)

RemoveFilter removes a filter.

type EventTypeFilter

type EventTypeFilter struct {
	// Event types to include (empty = all)
	IncludeTypes []string
	// Event types to exclude
	ExcludeTypes []string
	// Use regex for matching
	UseRegex bool
	// Case sensitive matching
	CaseSensitive bool
}

EventTypeFilter filters events based on event type.

func NewEventTypeFilter

func NewEventTypeFilter() *EventTypeFilter

NewEventTypeFilter creates a new event type filter.

func (*EventTypeFilter) Allow

func (f *EventTypeFilter) Allow(event *siem.Event) bool

Allow implements Filter interface.

func (*EventTypeFilter) Match

func (f *EventTypeFilter) Match(event *siem.Event) bool

Match implements Filter interface.

func (*EventTypeFilter) WithCaseSensitive

func (f *EventTypeFilter) WithCaseSensitive(sensitive bool) *EventTypeFilter

WithCaseSensitive sets case sensitivity.

func (*EventTypeFilter) WithExcludeTypes

func (f *EventTypeFilter) WithExcludeTypes(types ...string) *EventTypeFilter

WithExcludeTypes sets the event types to exclude.

func (*EventTypeFilter) WithIncludeTypes

func (f *EventTypeFilter) WithIncludeTypes(types ...string) *EventTypeFilter

WithIncludeTypes sets the event types to include.

func (*EventTypeFilter) WithRegex

func (f *EventTypeFilter) WithRegex(useRegex bool) *EventTypeFilter

WithRegex enables regex matching.

type Filter

type Filter interface {
	// Allow determines if an event should be allowed through
	Allow(event *siem.Event) bool
	// Match determines if an event matches the filter criteria
	Match(event *siem.Event) bool
}

Filter is the interface for event filters.

func BuildFilterFromTrigger

func BuildFilterFromTrigger(trigger TriggerCondition) Filter

BuildFilterFromTrigger builds a filter from a trigger condition.

type FilterBuilder

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

FilterBuilder provides a fluent interface for building filters.

func NewFilterBuilder

func NewFilterBuilder() *FilterBuilder

NewFilterBuilder creates a new filter builder.

func (*FilterBuilder) Build

func (b *FilterBuilder) Build() Filter

Build builds the filter.

func (*FilterBuilder) BuildOr

func (b *FilterBuilder) BuildOr() Filter

BuildOr builds an OR filter.

func (*FilterBuilder) WithCategoryFilter

func (b *FilterBuilder) WithCategoryFilter(include []siem.EventCategory, exclude []siem.EventCategory) *FilterBuilder

WithCategoryFilter adds a category filter.

func (*FilterBuilder) WithEventTypeFilter

func (b *FilterBuilder) WithEventTypeFilter(include []string, exclude []string) *FilterBuilder

WithEventTypeFilter adds an event type filter.

func (*FilterBuilder) WithFilter

func (b *FilterBuilder) WithFilter(filter Filter) *FilterBuilder

WithFilter adds a custom filter.

func (*FilterBuilder) WithSeverityFilter

func (b *FilterBuilder) WithSeverityFilter(minSeverity siem.Severity) *FilterBuilder

WithSeverityFilter adds a severity filter.

func (*FilterBuilder) WithSourceFilter

func (b *FilterBuilder) WithSourceFilter(include []string, exclude []string) *FilterBuilder

WithSourceFilter adds a source filter.

type HMACConfig

type HMACConfig struct {
	// Secret key for signing
	Secret string `json:"secret"`
	// Algorithm (sha256, sha384, sha512)
	Algorithm string `json:"algorithm"`
	// Header name for signature (default: X-Signature)
	Header string `json:"header"`
	// Include timestamp in signature
	IncludeTimestamp bool `json:"include_timestamp"`
	// Timestamp header name (default: X-Timestamp)
	TimestampHeader string `json:"timestamp_header"`
	// Signature prefix (e.g., "sha256=")
	SignaturePrefix string `json:"signature_prefix"`
}

HMACConfig contains HMAC signature settings.

type HTTPClient

type HTTPClient struct {
	*http.Client
	// contains filtered or unexported fields
}

HTTPClient wraps http.Client with webhook-specific functionality.

func NewHTTPClient

func NewHTTPClient(config *HTTPClientConfig) (*HTTPClient, error)

NewHTTPClient creates a new HTTP client for webhook delivery.

type HTTPClientConfig

type HTTPClientConfig struct {
	// TLS configuration
	TLS *TLSConfig
	// Request timeout
	Timeout time.Duration
	// Maximum idle connections
	MaxIdleConns int
	// Maximum idle connections per host
	MaxIdleConnsPerHost int
	// Idle connection timeout
	IdleConnTimeout time.Duration
	// Response header timeout
	ResponseHeaderTimeout time.Duration
	// Expect continue timeout
	ExpectContinueTimeout time.Duration
	// Disable keep-alive
	DisableKeepAlives bool
	// Disable compression
	DisableCompression bool
}

HTTPClientConfig contains HTTP client settings.

func DefaultHTTPClientConfig

func DefaultHTTPClientConfig() *HTTPClientConfig

DefaultHTTPClientConfig returns default HTTP client configuration.

type HTTPSender

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

HTTPSender implements Sender using HTTP.

func NewHTTPSender

func NewHTTPSender(client *HTTPClient, retry RetryConfig) *HTTPSender

NewHTTPSender creates a new HTTP sender.

func (*HTTPSender) Send

func (s *HTTPSender) Send(ctx context.Context, config *WebhookConfig, payload Payload) (*DeliveryResponse, error)

Send sends a webhook payload.

func (*HTTPSender) SendWithRetry

func (s *HTTPSender) SendWithRetry(ctx context.Context, config *WebhookConfig, payload Payload, retry RetryConfig) (*DeliveryResponse, error)

SendWithRetry sends a webhook payload with custom retry settings.

type Manager

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

Manager manages webhook registrations and deliveries.

func GlobalManager

func GlobalManager() *Manager

GlobalManager returns the global webhook manager.

func NewManager

func NewManager(config ManagerConfig) (*Manager, error)

NewManager creates a new webhook manager.

func (*Manager) Disable

func (m *Manager) Disable(webhookID string) error

Disable disables a webhook.

func (*Manager) Enable

func (m *Manager) Enable(webhookID string) error

Enable enables a webhook.

func (*Manager) Errors

func (m *Manager) Errors() <-chan error

Errors returns the error channel.

func (*Manager) GetManagerStats

func (m *Manager) GetManagerStats() *ManagerStats

GetManagerStats returns overall manager statistics.

func (*Manager) GetStats

func (m *Manager) GetStats(webhookID string) (*WebhookStats, error)

GetStats returns webhook statistics.

func (*Manager) GetStatus

func (m *Manager) GetStatus(webhookID string) (*DeliveryStatus, error)

GetStatus returns the delivery status for a webhook.

func (*Manager) GetWebhook

func (m *Manager) GetWebhook(webhookID string) (*WebhookConfig, error)

GetWebhook retrieves a webhook by ID.

func (*Manager) ListWebhooks

func (m *Manager) ListWebhooks() []*WebhookConfig

ListWebhooks returns all registered webhooks.

func (*Manager) Register

func (m *Manager) Register(config WebhookConfig) error

Register registers a new webhook.

func (*Manager) Send

func (m *Manager) Send(ctx context.Context, event *siem.Event) error

Send sends an event to matching webhooks.

func (*Manager) SendBatch

func (m *Manager) SendBatch(ctx context.Context, events []*siem.Event) error

SendBatch sends multiple events to matching webhooks.

func (*Manager) SendSync

func (m *Manager) SendSync(ctx context.Context, event *siem.Event) error

SendSync sends an event synchronously to matching webhooks.

func (*Manager) SendToWebhook

func (m *Manager) SendToWebhook(ctx context.Context, webhookID string, event *siem.Event) error

SendToWebhook sends an event to a specific webhook.

func (*Manager) Start

func (m *Manager) Start()

Start starts the webhook manager.

func (*Manager) Stop

func (m *Manager) Stop()

Stop stops the webhook manager.

func (*Manager) Test

func (m *Manager) Test(ctx context.Context, config *WebhookConfig) error

Test tests a webhook configuration by sending a test request.

func (*Manager) Unregister

func (m *Manager) Unregister(webhookID string) error

Unregister removes a webhook.

func (*Manager) Update

func (m *Manager) Update(config WebhookConfig) error

Update updates an existing webhook.

func (*Manager) Validate

func (m *Manager) Validate(config *WebhookConfig) error

Validate validates a webhook configuration.

type ManagerConfig

type ManagerConfig struct {
	// HTTP client configuration
	HTTPClient *HTTPClientConfig
	// Worker pool configuration
	WorkerPool WorkerPoolConfig
	// Batch delivery configuration
	Batch BatchDeliveryConfig
	// Default retry configuration
	DefaultRetry RetryConfig
	// Enable metrics collection
	EnableMetrics bool
	// Maximum delivery history per webhook
	MaxHistorySize int
}

ManagerConfig contains manager configuration.

func DefaultManagerConfig

func DefaultManagerConfig() ManagerConfig

DefaultManagerConfig returns default manager configuration.

type ManagerStats

type ManagerStats struct {

	// Total webhooks registered
	TotalWebhooks int `json:"total_webhooks"`
	// Enabled webhooks
	EnabledWebhooks int `json:"enabled_webhooks"`
	// Total deliveries across all webhooks
	TotalDeliveries int64 `json:"total_deliveries"`
	// Successful deliveries
	SuccessCount int64 `json:"success_count"`
	// Failed deliveries
	FailureCount int64 `json:"failure_count"`
	// Events filtered out
	EventsFiltered int64 `json:"events_filtered"`
	// Per-webhook statistics
	WebhookStats map[string]*WebhookStats `json:"webhook_stats"`
	// contains filtered or unexported fields
}

ManagerStats contains statistics for the webhook manager.

type MatchCondition

type MatchCondition struct {
	// Field to match against
	Field string `json:"field"`
	// Operator (eq, ne, contains, regex, gt, lt, gte, lte)
	Operator string `json:"operator"`
	// Value to compare
	Value interface{} `json:"value"`
	// Case-sensitive matching
	CaseSensitive bool `json:"case_sensitive"`
}

MatchCondition defines a condition for matching events.

type OAuth2Config

type OAuth2Config struct {
	// Token endpoint URL
	TokenURL string `json:"token_url"`
	// Client ID
	ClientID string `json:"client_id"`
	// Client secret
	ClientSecret string `json:"client_secret"`
	// OAuth scopes
	Scopes []string `json:"scopes,omitempty"`
	// Cached access token
	AccessToken string `json:"-"`
	// Token expiration
	TokenExpiry time.Time `json:"-"`
}

OAuth2Config contains OAuth2 client credentials flow settings.

type Payload

type Payload interface {
	// ToJSON returns the JSON representation
	ToJSON() ([]byte, error)
	// GetID returns the payload ID
	GetID() string
	// GetTimestamp returns the payload timestamp
	GetTimestamp() time.Time
}

Payload represents a payload that can be sent via webhook.

type RateLimitConfig

type RateLimitConfig struct {
	// Maximum number of triggers per window
	MaxTriggers int `json:"max_triggers"`
	// Time window for rate limiting
	Window time.Duration `json:"window"`
	// Burst allowance
	Burst int `json:"burst"`
}

RateLimitConfig defines rate limiting for webhook triggers.

type RequestBuilder

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

RequestBuilder provides a fluent interface for building webhook requests.

func NewRequestBuilder

func NewRequestBuilder(config *WebhookConfig) *RequestBuilder

NewRequestBuilder creates a new request builder.

func (*RequestBuilder) Build

func (b *RequestBuilder) Build() *WebhookPayload

Build returns the configured payload.

func (*RequestBuilder) WithCategory

func (b *RequestBuilder) WithCategory(category siem.EventCategory) *RequestBuilder

WithCategory sets the category.

func (*RequestBuilder) WithData

func (b *RequestBuilder) WithData(key string, value interface{}) *RequestBuilder

WithData adds data to the payload.

func (*RequestBuilder) WithEvent

func (b *RequestBuilder) WithEvent(event *siem.Event) *RequestBuilder

WithEvent sets the SIEM event.

func (*RequestBuilder) WithEventType

func (b *RequestBuilder) WithEventType(eventType string) *RequestBuilder

WithEventType sets the event type.

func (*RequestBuilder) WithMessage

func (b *RequestBuilder) WithMessage(message string) *RequestBuilder

WithMessage sets the message.

func (*RequestBuilder) WithMetadata

func (b *RequestBuilder) WithMetadata(key, value string) *RequestBuilder

WithMetadata adds metadata to the payload.

func (*RequestBuilder) WithSeverity

func (b *RequestBuilder) WithSeverity(severity siem.Severity) *RequestBuilder

WithSeverity sets the severity.

func (*RequestBuilder) WithSource

func (b *RequestBuilder) WithSource(source string) *RequestBuilder

WithSource sets the source.

type RetryConfig

type RetryConfig struct {
	// Enable retry on failure
	Enabled bool `json:"enabled"`
	// Maximum retry attempts
	MaxAttempts int `json:"max_attempts"`
	// Initial backoff duration
	InitialBackoff time.Duration `json:"initial_backoff"`
	// Maximum backoff duration
	MaxBackoff time.Duration `json:"max_backoff"`
	// Backoff multiplier (default: 2.0)
	BackoffMultiplier float64 `json:"backoff_multiplier"`
	// Add jitter to backoff
	Jitter bool `json:"jitter"`
	// Retry on these HTTP status codes
	RetryOnStatusCodes []int `json:"retry_on_status_codes,omitempty"`
	// Retry on network errors
	RetryOnNetworkError bool `json:"retry_on_network_error"`
	// Retry on timeout
	RetryOnTimeout bool `json:"retry_on_timeout"`
	// Maximum total retry duration
	MaxTotalDuration time.Duration `json:"max_total_duration"`
}

RetryConfig contains retry settings for webhook delivery.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns the default retry configuration.

type Sender

type Sender interface {
	// Send sends a webhook payload
	Send(ctx context.Context, config *WebhookConfig, payload Payload) (*DeliveryResponse, error)
	// SendWithRetry sends with custom retry settings
	SendWithRetry(ctx context.Context, config *WebhookConfig, payload Payload, retry RetryConfig) (*DeliveryResponse, error)
}

Sender is the interface for webhook senders.

type SeverityFilter

type SeverityFilter struct {
	// Minimum severity required
	MinSeverity siem.Severity
	// Severities to include (empty = all above min)
	IncludeSeverities []siem.Severity
	// Severities to exclude
	ExcludeSeverities []siem.Severity
}

SeverityFilter filters events based on severity level.

func NewSeverityFilter

func NewSeverityFilter() *SeverityFilter

NewSeverityFilter creates a new severity filter.

func (*SeverityFilter) Allow

func (f *SeverityFilter) Allow(event *siem.Event) bool

Allow implements Filter interface.

func (*SeverityFilter) Match

func (f *SeverityFilter) Match(event *siem.Event) bool

Match implements Filter interface.

func (*SeverityFilter) WithExcludeSeverities

func (f *SeverityFilter) WithExcludeSeverities(severities ...siem.Severity) *SeverityFilter

WithExcludeSeverities sets the severities to exclude.

func (*SeverityFilter) WithIncludeSeverities

func (f *SeverityFilter) WithIncludeSeverities(severities ...siem.Severity) *SeverityFilter

WithIncludeSeverities sets the severities to include.

func (*SeverityFilter) WithMinSeverity

func (f *SeverityFilter) WithMinSeverity(severity siem.Severity) *SeverityFilter

WithMinSeverity sets the minimum severity.

type SourceFilter

type SourceFilter struct {
	// Sources to include (empty = all)
	IncludeSources []string
	// Sources to exclude
	ExcludeSources []string
	// Use regex for matching
	UseRegex bool
	// Case sensitive matching
	CaseSensitive bool
}

SourceFilter filters events based on source.

func NewSourceFilter

func NewSourceFilter() *SourceFilter

NewSourceFilter creates a new source filter.

func (*SourceFilter) Allow

func (f *SourceFilter) Allow(event *siem.Event) bool

Allow implements Filter interface.

func (*SourceFilter) Match

func (f *SourceFilter) Match(event *siem.Event) bool

Match implements Filter interface.

func (*SourceFilter) WithCaseSensitive

func (f *SourceFilter) WithCaseSensitive(sensitive bool) *SourceFilter

WithCaseSensitive sets case sensitivity.

func (*SourceFilter) WithExcludeSources

func (f *SourceFilter) WithExcludeSources(sources ...string) *SourceFilter

WithExcludeSources sets the sources to exclude.

func (*SourceFilter) WithIncludeSources

func (f *SourceFilter) WithIncludeSources(sources ...string) *SourceFilter

WithIncludeSources sets the sources to include.

func (*SourceFilter) WithRegex

func (f *SourceFilter) WithRegex(useRegex bool) *SourceFilter

WithRegex enables regex matching.

type StatusTracker

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

StatusTracker tracks delivery status for webhooks.

func NewStatusTracker

func NewStatusTracker(maxSize int) *StatusTracker

NewStatusTracker creates a new status tracker.

func (*StatusTracker) Clear

func (t *StatusTracker) Clear(webhookID string)

Clear clears the status history for a webhook.

func (*StatusTracker) Get

func (t *StatusTracker) Get(webhookID string) (*DeliveryStatus, bool)

Get retrieves the delivery status for a webhook.

func (*StatusTracker) GetAll

func (t *StatusTracker) GetAll() map[string]*DeliveryStatus

GetAll retrieves all delivery statuses.

func (*StatusTracker) Record

func (t *StatusTracker) Record(webhookID string, attempt DeliveryAttempt)

Record records a delivery attempt.

type TLSConfig

type TLSConfig struct {
	// Enable TLS (default: true for HTTPS URLs)
	Enabled bool `json:"enabled"`
	// Skip certificate verification (insecure)
	InsecureSkipVerify bool `json:"insecure_skip_verify"`
	// CA certificate file path
	CAFile string `json:"ca_file,omitempty"`
	// CA certificate PEM data
	CAData []byte `json:"ca_data,omitempty"`
	// Client certificate file path
	CertFile string `json:"cert_file,omitempty"`
	// Client certificate PEM data
	CertData []byte `json:"cert_data,omitempty"`
	// Client key file path
	KeyFile string `json:"key_file,omitempty"`
	// Client key PEM data
	KeyData []byte `json:"key_data,omitempty"`
	// Server name for SNI
	ServerName string `json:"server_name,omitempty"`
	// Minimum TLS version (1.2, 1.3)
	MinVersion string `json:"min_version,omitempty"`
	// Maximum TLS version
	MaxVersion string `json:"max_version,omitempty"`
	// Cipher suites (nil for default)
	CipherSuites []string `json:"cipher_suites,omitempty"`
}

TLSConfig contains TLS settings for webhook connections.

func (*TLSConfig) BuildTLSConfig

func (t *TLSConfig) BuildTLSConfig() (*tls.Config, error)

BuildTLSConfig builds a crypto/tls.Config from TLSConfig.

type TriggerCondition

type TriggerCondition struct {
	// Minimum severity level to trigger
	MinSeverity siem.Severity `json:"min_severity,omitempty"`
	// Event categories to trigger on (empty = all)
	Categories []siem.EventCategory `json:"categories,omitempty"`
	// Event sources to trigger on (empty = all)
	Sources []string `json:"sources,omitempty"`
	// Event types to trigger on (empty = all)
	EventTypes []string `json:"event_types,omitempty"`
	// Custom filter expression
	CustomFilter string `json:"custom_filter,omitempty"`
	// Exclude these severities
	ExcludeSeverities []siem.Severity `json:"exclude_severities,omitempty"`
	// Exclude these categories
	ExcludeCategories []siem.EventCategory `json:"exclude_categories,omitempty"`
	// Exclude these sources
	ExcludeSources []string `json:"exclude_sources,omitempty"`
	// Exclude these event types
	ExcludeEventTypes []string `json:"exclude_event_types,omitempty"`
	// Time window for triggering (rate limiting)
	RateLimit *RateLimitConfig `json:"rate_limit,omitempty"`
}

TriggerCondition defines when a webhook should be triggered.

type Webhook

type Webhook struct {
	ID          string             `json:"id"`
	Name        string             `json:"name"`
	Description string             `json:"description"`
	URL         string             `json:"url"`
	Method      string             `json:"method"`
	Enabled     bool               `json:"enabled"`
	Auth        Authentication     `json:"auth"`
	TLS         TLSConfig          `json:"tls"`
	Triggers    []TriggerCondition `json:"triggers"`
	CreatedAt   time.Time          `json:"created_at"`
	UpdatedAt   time.Time          `json:"updated_at"`
}

Webhook represents a webhook configuration

func (*Webhook) GetID

func (w *Webhook) GetID() string

GetID returns the webhook ID

func (*Webhook) GetName

func (w *Webhook) GetName() string

GetName returns the webhook name

func (*Webhook) GetURL

func (w *Webhook) GetURL() string

GetURL returns the webhook URL

func (*Webhook) IsEnabled

func (w *Webhook) IsEnabled() bool

IsEnabled returns whether the webhook is enabled

type WebhookConfig

type WebhookConfig struct {
	// Unique identifier for this webhook
	ID string `json:"id"`
	// Human-readable name
	Name string `json:"name"`
	// Description of the webhook
	Description string `json:"description,omitempty"`
	// Webhook endpoint URL
	URL string `json:"url"`
	// HTTP method (POST, PUT, PATCH)
	Method string `json:"method"`
	// Custom headers to include in requests
	Headers map[string]string `json:"headers,omitempty"`
	// Authentication configuration
	Auth Authentication `json:"auth"`
	// TLS configuration
	TLS TLSConfig `json:"tls"`
	// Request timeout
	Timeout time.Duration `json:"timeout"`
	// Retry configuration
	Retry RetryConfig `json:"retry"`
	// Trigger conditions for when to send webhooks
	Triggers []TriggerCondition `json:"triggers,omitempty"`
	// Enable/disable this webhook
	Enabled bool `json:"enabled"`
	// Maximum concurrent deliveries
	MaxConcurrency int `json:"max_concurrency"`
	// Content type for request body
	ContentType string `json:"content_type"`
	// Custom template for payload formatting
	PayloadTemplate string `json:"payload_template,omitempty"`
	// Include full event details in payload
	IncludeEventDetails bool `json:"include_event_details"`
	// Created timestamp
	CreatedAt time.Time `json:"created_at"`
	// Last updated timestamp
	UpdatedAt time.Time `json:"updated_at"`
	// Tags for organization
	Tags []string `json:"tags,omitempty"`
}

WebhookConfig contains the complete configuration for a webhook endpoint.

func DefaultWebhookConfig

func DefaultWebhookConfig() WebhookConfig

DefaultWebhookConfig returns a webhook configuration with sensible defaults.

type WebhookPayload

type WebhookPayload struct {
	// Unique identifier for this payload
	ID string `json:"id"`
	// Timestamp when the payload was created
	Timestamp time.Time `json:"timestamp"`
	// Webhook that generated this payload
	WebhookID string `json:"webhook_id"`
	// Event type that triggered this webhook
	EventType string `json:"event_type"`
	// Event severity
	Severity siem.Severity `json:"severity"`
	// Event category
	Category siem.EventCategory `json:"category"`
	// Event source
	Source string `json:"source"`
	// Human-readable message
	Message string `json:"message"`
	// The original event data
	Event *siem.Event `json:"event,omitempty"`
	// Custom data payload
	Data map[string]interface{} `json:"data,omitempty"`
	// HMAC signature (if configured)
	Signature string `json:"signature,omitempty"`
	// Signature timestamp
	SignatureTimestamp time.Time `json:"signature_timestamp,omitempty"`
	// Additional metadata
	Metadata map[string]string `json:"metadata,omitempty"`
}

WebhookPayload contains the data sent in a webhook request.

func (*WebhookPayload) GetID

func (p *WebhookPayload) GetID() string

GetID returns the payload ID.

func (*WebhookPayload) GetTimestamp

func (p *WebhookPayload) GetTimestamp() time.Time

GetTimestamp returns the payload timestamp.

func (*WebhookPayload) ToJSON

func (p *WebhookPayload) ToJSON() ([]byte, error)

ToJSON returns the JSON representation of WebhookPayload.

type WebhookStats

type WebhookStats struct {
	// Total deliveries attempted
	TotalDeliveries int64 `json:"total_deliveries"`
	// Successful deliveries
	SuccessCount int64 `json:"success_count"`
	// Failed deliveries
	FailureCount int64 `json:"failure_count"`
	// Currently pending deliveries
	PendingCount int64 `json:"pending_count"`
	// Average delivery time
	AvgDeliveryTime time.Duration `json:"avg_delivery_time"`
	// Last successful delivery
	LastSuccess time.Time `json:"last_success,omitempty"`
	// Last failed delivery
	LastFailure time.Time `json:"last_failure,omitempty"`
	// Consecutive failures
	ConsecutiveFailures int `json:"consecutive_failures"`
	// Last error message
	LastError string `json:"last_error,omitempty"`
	// Events sent (events delivered)
	EventsSent int64 `json:"events_sent"`
	// Events dropped (due to filtering or errors)
	EventsDropped int64 `json:"events_dropped"`
}

WebhookStats contains statistics for a webhook.

type WebhookStatus

type WebhookStatus string

WebhookStatus represents the status of a webhook delivery.

const (
	StatusPending   WebhookStatus = "pending"
	StatusDelivered WebhookStatus = "delivered"
	StatusFailed    WebhookStatus = "failed"
	StatusRetrying  WebhookStatus = "retrying"
	StatusCancelled WebhookStatus = "cancelled"
	StatusTimeout   WebhookStatus = "timeout"
	StatusDisabled  WebhookStatus = "disabled"
)

type WorkerPoolConfig

type WorkerPoolConfig struct {
	// Number of workers
	Workers int `json:"workers"`
	// Queue size for pending deliveries
	QueueSize int `json:"queue_size"`
	// Shutdown timeout
	ShutdownTimeout time.Duration `json:"shutdown_timeout"`
}

WorkerPoolConfig contains settings for the worker pool.

func DefaultWorkerPoolConfig

func DefaultWorkerPoolConfig() WorkerPoolConfig

DefaultWorkerPoolConfig returns default worker pool configuration.

Jump to

Keyboard shortcuts

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