plugin

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: 8 Imported by: 0

Documentation

Overview

Package plugin provides the plugin hook system for AegisGate extensibility.

Package plugin provides the plugin manager for loading and managing plugins.

Package plugin provides the plugin system for AegisGate extensibility. It defines the Plugin interface, hook system, and plugin manager.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ClientCertInfo

type ClientCertInfo struct {
	Subject   string
	Issuer    string
	NotBefore time.Time
	NotAfter  time.Time
	Serial    string
}

ClientCertInfo contains client certificate information

type ConnectionContext

type ConnectionContext struct {
	// LocalAddr is the local address
	LocalAddr string
	// RemoteAddr is the remote client address
	RemoteAddr string
	// RemotePort is the remote client port
	RemotePort int
	// LocalPort is the local server port
	LocalPort int
	// IsEncrypted indicates if the connection is TLS encrypted
	IsEncrypted bool
	// ConnectionID is a unique identifier for this connection
	ConnectionID string
	// Metadata is additional context metadata
	Metadata map[string]interface{}
}

ConnectionContext holds connection-level information

func NewConnectionContext

func NewConnectionContext(localAddr, remoteAddr string, isEncrypted bool) *ConnectionContext

NewConnectionContext creates a new ConnectionContext

type ConnectionHandler

type ConnectionHandler interface {
	// OnConnectionOpen is called when a connection opens
	OnConnectionOpen(ctx context.Context, connCtx *ConnectionContext) error
	// OnConnectionClose is called when a connection closes
	OnConnectionClose(ctx context.Context, connCtx *ConnectionContext) error
}

ConnectionHandler is implemented by plugins that handle connection events

type ErrorContext

type ErrorContext struct {
	// Error is the actual error
	Error error
	// Hook is the hook type where the error occurred
	Hook HookType
	// Request is the associated request (if available)
	Request *http.Request
	// ConnectionID is the connection where error occurred
	ConnectionID string
	// Timestamp when the error occurred
	Timestamp time.Time
	// Metadata is additional context metadata
	Metadata map[string]interface{}
}

ErrorContext holds error information passed to error hooks

func NewErrorContext

func NewErrorContext(err error, hook HookType, req *http.Request, connID string) *ErrorContext

NewErrorContext creates a new ErrorContext

type ErrorHandler

type ErrorHandler interface {
	// OnError is called when an error occurs
	OnError(ctx context.Context, errCtx *ErrorContext) error
}

ErrorHandler is implemented by plugins that handle errors

type FilterPlugin

type FilterPlugin interface {
	Plugin
	RequestProcessor
	ResponseProcessor
}

FilterPlugin is a convenience type for filter plugins

type HookResult

type HookResult struct {
	// Continue indicates whether to continue to the next plugin/hook
	Continue bool
	// Stop indicates whether to stop the entire pipeline
	Stop bool
	// Error contains any error that occurred
	Error error
	// ModifiedRequest is a modified request (for request hooks)
	ModifiedRequest *http.Request
	// ModifiedBody is a modified body (for body-processing hooks)
	ModifiedBody []byte
	// Metadata is additional data to pass to subsequent hooks
	Metadata map[string]interface{}
	// ResponseHeaders headers to add/modify
	ResponseHeaders http.Header
	// StatusCode to set (for response hooks)
	StatusCode int
}

HookResult represents the result of a plugin hook execution

func DefaultHookResult

func DefaultHookResult() HookResult

DefaultHookResult returns a default successful hook result

func ErrorHookResult

func ErrorHookResult(err error) HookResult

ErrorHookResult returns a hook result indicating an error

func StopHookResult

func StopHookResult() HookResult

StopHookResult returns a hook result that stops the pipeline

type HookType

type HookType string

HookType defines when a plugin hook is invoked

const (
	// HookRequestReceived When request is first received
	HookRequestReceived HookType = "request_received"
	// HookBeforeForward Before forwarding to upstream
	HookBeforeForward HookType = "before_forward"
	// HookAfterResponse After response received from upstream
	HookAfterResponse HookType = "after_response"
	// HookResponseSent Before response is sent to client
	HookResponseSent HookType = "response_sent"
	// HookConnectionOpen When a new connection is opened
	HookConnectionOpen HookType = "connection_open"
	// HookConnectionClose When a connection is closed
	HookConnectionClose HookType = "connection_close"
	// HookError When an error occurs in the proxy
	HookError HookType = "error"
	// HookPeriodic Run on a periodic interval
	HookPeriodic HookType = "periodic"
)

type Manager

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

Manager handles the lifecycle of plugins

func NewManager

func NewManager(config *ManagerConfig) *Manager

NewManager creates a new plugin manager

func (*Manager) ExecuteHook

func (m *Manager) ExecuteHook(ctx context.Context, hookType HookType, fn func(ctx context.Context, state *PluginState) (*HookResult, error)) (*HookResult, error)

ExecuteHook executes a hook across all registered plugins

func (*Manager) GetPlugin

func (m *Manager) GetPlugin(id string) (*PluginState, bool)

GetPlugin returns a plugin by ID

func (*Manager) GetPluginsByCapability

func (m *Manager) GetPluginsByCapability(capability string) []*PluginState

GetPluginsByCapability returns all plugins providing a capability

func (*Manager) GetPluginsByHook

func (m *Manager) GetPluginsByHook(hookType HookType) []*PluginState

GetPluginsByHook returns all plugins registered for a specific hook

func (*Manager) GetStatus

func (m *Manager) GetStatus() map[string]Status

GetStatus returns the overall status of all plugins

func (*Manager) HasCapability

func (m *Manager) HasCapability(capability string) bool

HasCapability checks if a capability is available

func (*Manager) Init

func (m *Manager) Init(ctx context.Context) error

Init initializes all registered plugins

func (*Manager) ListPlugins

func (m *Manager) ListPlugins() []*PluginState

ListPlugins returns all registered plugins

func (*Manager) LoadGoPlugin

func (m *Manager) LoadGoPlugin(path string) error

LoadGoPlugin loads a plugin from a Go plugin file (.so)

func (*Manager) Register

func (m *Manager) Register(p Plugin) error

Register registers a plugin with the manager

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start starts all initialized plugins

func (*Manager) Stop

func (m *Manager) Stop(ctx context.Context) error

Stop stops all running plugins gracefully

func (*Manager) UpdateConfig

func (m *Manager) UpdateConfig(pluginID string, config PluginConfig) error

UpdateConfig updates a plugin's configuration at runtime

type ManagerConfig

type ManagerConfig struct {
	// PluginDirs directories to search for plugins
	PluginDirs []string
	// PluginConfig configuration for each plugin
	PluginConfig map[string]PluginConfig
	// EnabledPluginTypes only load plugins of these types (empty = all)
	EnabledPluginTypes []Type
	// DisabledPlugins list of plugin IDs to skip loading
	DisabledPlugins []string
	// WatchDir watch for plugin changes (development)
	WatchDir bool
	// PluginTimeout default timeout for plugin operations
	PluginTimeout time.Duration
	// EnablePeriodic enable periodic hook processing
	EnablePeriodic bool
}

ManagerConfig contains configuration for the plugin manager

func DefaultManagerConfig

func DefaultManagerConfig() *ManagerConfig

DefaultManagerConfig returns sensible defaults

type PeriodicContext

type PeriodicContext struct {
	// Timestamp is when the hook is being executed
	Timestamp time.Time
	// Interval is the configured interval
	Interval time.Duration
	// Metadata is additional context metadata
	Metadata map[string]interface{}
}

PeriodicContext holds context for periodic hook execution

type PeriodicTask

type PeriodicTask interface {
	// OnPeriodic is called at regular intervals
	OnPeriodic(ctx context.Context, periodicCtx *PeriodicContext) error
	// Interval returns the interval at which OnPeriodic should be called
	Interval() time.Duration
}

PeriodicTask is implemented by plugins that run periodic tasks

type Plugin

type Plugin interface {
	// Metadata returns plugin information
	Metadata() PluginMetadata

	// Init is called once when the plugin is loaded
	Init(ctx context.Context, config PluginConfig) error

	// Start is called when the plugin should begin operation
	Start(ctx context.Context) error

	// Stop is called when the plugin should gracefully shut down
	Stop(ctx context.Context) error

	// Hooks returns the hooks this plugin implements
	Hooks() []HookType
}

Plugin is the core interface that all AegisGate plugins must implement. Each plugin can hook into various stages of the proxy lifecycle.

type PluginConfig

type PluginConfig struct {
	Enabled     bool                   `json:"enabled" yaml:"enabled"`
	Priority    int                    `json:"priority" yaml:"priority"` // Lower = earlier execution
	Settings    map[string]interface{} `json:"settings" yaml:"settings"`
	Timeout     time.Duration          `json:"timeout" yaml:"timeout"`
	RetryConfig *RetryConfig           `json:"retry,omitempty" yaml:"retry,omitempty"`
}

PluginConfig contains configuration for a specific plugin instance

func (*PluginConfig) GetBool

func (p *PluginConfig) GetBool(key string, defaultValue bool) bool

GetBool retrieves a bool setting

func (*PluginConfig) GetDuration

func (p *PluginConfig) GetDuration(key string, defaultValue time.Duration) time.Duration

GetDuration retrieves a duration setting (supports "30s", "1m", etc.)

func (*PluginConfig) GetInt

func (p *PluginConfig) GetInt(key string, defaultValue int) int

GetInt retrieves an int setting

func (*PluginConfig) GetSetting

func (p *PluginConfig) GetSetting(key string, defaultValue interface{}) interface{}

GetSetting retrieves a setting value with type safety

func (*PluginConfig) GetString

func (p *PluginConfig) GetString(key string, defaultValue string) string

GetString retrieves a string setting

func (*PluginConfig) Validate

func (p *PluginConfig) Validate() error

Validate validates the plugin configuration

type PluginMetadata

type PluginMetadata struct {
	ID          string   `json:"id" yaml:"id"`
	Name        string   `json:"name" yaml:"name"`
	Version     string   `json:"version" yaml:"version"`
	Description string   `json:"description" yaml:"description"`
	Author      string   `json:"author" yaml:"author"`
	Website     string   `json:"website,omitempty" yaml:"website,omitempty"`
	Type        Type     `json:"type" yaml:"type"`
	Tags        []string `json:"tags,omitempty" yaml:"tags,omitempty"`
	// Dependencies lists plugin IDs that must be loaded before this one
	Dependencies []string `json:"dependencies,omitempty" yaml:"dependencies,omitempty"`
	// Capabilities lists what this plugin provides
	Capabilities []string `json:"capabilities,omitempty" yaml:"capabilities,omitempty"`
}

PluginMetadata contains information about the plugin

type PluginState

type PluginState struct {
	Metadata  PluginMetadata
	Config    PluginConfig
	Status    Status
	Plugin    Plugin
	StartedAt time.Time
	LastError error
}

PluginState holds the runtime state of a plugin

type RequestContext

type RequestContext struct {
	// Request is the HTTP request (may be modified by plugins)
	Request *http.Request
	// ResponseWriter is the response (plugins can write to it)
	ResponseWriter http.ResponseWriter
	// Body is the request body (for request hooks)
	Body []byte
	// Upstream is the target upstream URL
	Upstream string
	// ClientIP is the client's IP address
	ClientIP string
	// Protocol is the protocol used (HTTP/1.1, HTTP/2, HTTP/3)
	Protocol string
	// TLSInfo contains TLS connection details
	TLSInfo *TLSInfo
	// Metadata is additional context metadata
	Metadata map[string]interface{}
	// Timestamp when the request was received
	Timestamp time.Time
}

RequestContext holds the request data passed to plugin hooks

func NewRequestContext

func NewRequestContext(r *http.Request, rw http.ResponseWriter, upstream string) *RequestContext

NewRequestContext creates a new RequestContext

type RequestProcessor

type RequestProcessor interface {
	// ProcessRequest is called for request hooks
	ProcessRequest(ctx context.Context, reqCtx *RequestContext) (*HookResult, error)
}

RequestProcessor is implemented by plugins that process requests

type ResponseContext

type ResponseContext struct {
	// StatusCode is the HTTP status code
	StatusCode int
	// Status is the HTTP status string
	Status string
	// Headers are the response headers
	Headers http.Header
	// Body is the response body
	Body []byte
	// Latency is the time taken to get the response from upstream
	Latency time.Duration
	// Error contains any error that occurred
	Error error
	// Metadata is additional context metadata
	Metadata map[string]interface{}
}

ResponseContext holds the response data passed to plugin hooks

func NewResponseContext

func NewResponseContext(statusCode int, headers http.Header, body []byte, latency time.Duration) *ResponseContext

NewResponseContext creates a new ResponseContext

type ResponseProcessor

type ResponseProcessor interface {
	// ProcessResponse is called for response hooks
	ProcessResponse(ctx context.Context, reqCtx *RequestContext, respCtx *ResponseContext) (*HookResult, error)
}

ResponseProcessor is implemented by plugins that process responses

type RetryConfig

type RetryConfig struct {
	MaxAttempts  int           `json:"max_attempts" yaml:"max_attempts"`
	InitialDelay time.Duration `json:"initial_delay" yaml:"initial_delay"`
	MaxDelay     time.Duration `json:"max_delay" yaml:"max_delay"`
	Multiplier   float64       `json:"multiplier" yaml:"multiplier"`
}

RetryConfig defines retry behavior for plugin operations

func DefaultRetryConfig

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig returns sensible defaults for retry configuration

type Status

type Status int

Status represents the current state of a plugin

const (
	StatusUnregistered Status = iota
	StatusInitialized
	StatusStarting
	StatusRunning
	StatusStopping
	StatusStopped
	StatusError
)

func (Status) String

func (s Status) String() string

type TLSInfo

type TLSInfo struct {
	Version     string
	CipherSuite string
	ServerName  string
	Verified    bool
	// For mTLS - client certificate info
	ClientCert *ClientCertInfo
}

TLSInfo contains TLS connection information

type Type

type Type string

Type defines the category of plugin

const (
	// TypeFilter filters/modifies requests and responses
	TypeFilter Type = "filter"
	// TypeAuth provides authentication providers
	TypeAuth Type = "auth"
	// TypeAnalytics provides analytics/reporting
	TypeAnalytics Type = "analytics"
	// TypeProcessor processes data in pipeline
	TypeProcessor Type = "processor"
	// TypeExporter exports data to external systems
	TypeExporter Type = "exporter"
	// TypeValidator validates data/policies
	TypeValidator Type = "validator"
)

Directories

Path Synopsis
Package examples contains example plugin implementations for AegisGate.
Package examples contains example plugin implementations for AegisGate.

Jump to

Keyboard shortcuts

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