proxy

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

Documentation

Overview

Package proxy provides proxy server capabilities for AegisGate This file adds types needed by the grpc package

Index

Constants

This section is empty.

Variables

View Source
var (
	StatusBadGateway     = http.StatusText(http.StatusBadGateway)
	StatusForbidden      = http.StatusText(http.StatusForbidden)
	StatusTextBadGateway = "502 Bad Gateway"
	StatusTextForbidden  = "403 Forbidden"
)

Common status text to avoid runtime lookups

View Source
var BufferPool = sync.Pool{
	New: func() interface{} {
		buf := make([]byte, 0, 8192)
		return &buf
	},
}

BufferPool pools []byte buffers for reading request/response bodies

View Source
var ResponseHeaderPool = sync.Pool{
	New: func() interface{} {
		return make(http.Header, 4)
	},
}

ResponseHeaderPool pools http.Header for response objects

View Source
var StringBuilderPool = sync.Pool{
	New: func() interface{} {
		return &strings.Builder{}
	},
}

StringBuilderPool pools strings.Builder for string concatenation

Functions

func ContainsCI

func ContainsCI(s, substr string) bool

ContainsCI is a case-insensitive contains check

func CreateOptimizedBlockedResponse

func CreateOptimizedBlockedResponse(patterns []string) *http.Response

CreateOptimizedBlockedResponse creates a blocked response with pooled resources This replaces createBlockedResponse in hot paths

func CreateOptimizedErrorResponse

func CreateOptimizedErrorResponse(err error) *http.Response

CreateOptimizedErrorResponse creates an error response with pooled resources This replaces createErrorResponse in hot paths

func GetBuffer

func GetBuffer() *[]byte

GetBuffer returns a pooled buffer

func GetClientTLSConfig

func GetClientTLSConfig() *tls.Config

GetClientTLSConfig returns client TLS configuration

func GetHeaderPool

func GetHeaderPool() http.Header

GetHeaderPool returns a pooled header

func GetStringBuilder

func GetStringBuilder() *strings.Builder

GetStringBuilder returns a pooled strings.Builder

func GetTenantFromRequest

func GetTenantFromRequest(mgr *tenant.Manager, r *http.Request) (*tenant.Tenant, error)

GetTenantFromRequest extracts tenant from HTTP request

func HTTP3SupportCheck

func HTTP3SupportCheck() error

HTTP3SupportCheck checks if HTTP/3 support is available

func MiddlewareWithContext

func MiddlewareWithContext(ctx context.Context, config *MLMiddlewareConfig) func(http.Handler) http.Handler

MiddlewareWithContext returns an ML middleware that uses context for configuration

func PrintBenchmarkResults

func PrintBenchmarkResults(name string, result BenchmarkResult) string

PrintBenchmarkResults prints formatted benchmark results

func PutBuffer

func PutBuffer(b *[]byte)

PutBuffer returns buffer to pool

func PutHeaderPool

func PutHeaderPool(h http.Header)

PutHeaderPool returns header to pool

func PutStringBuilder

func PutStringBuilder(b *strings.Builder)

PutStringBuilder returns builder to pool

func ReadBodyOptimized

func ReadBodyOptimized(body io.Reader) ([]byte, error)

ReadBodyOptimized reads body with pooled buffer

func SafeString

func SafeString(s string) string

SafeString returns empty string if s is empty

func SplitHostPort

func SplitHostPort(host string) (string, string)

SplitHostPort splits host:port efficiently

func TestALPNNegotiation_H1Only

func TestALPNNegotiation_H1Only(t *testing.T)

func TestALPNNegotiation_H2Preferred

func TestALPNNegotiation_H2Preferred(t *testing.T)

func TestConfigureTLSForH2

func TestConfigureTLSForH2(t *testing.T)

func TestHTTP2BodyScanning

func TestHTTP2BodyScanning(t *testing.T)

func TestHTTP2BodyScanning_Empty

func TestHTTP2BodyScanning_Empty(t *testing.T)

func TestHTTP2BodyScanning_LargeBody

func TestHTTP2BodyScanning_LargeBody(t *testing.T)

func TestHTTP2ConcurrentStreams_Integration

func TestHTTP2ConcurrentStreams_Integration(t *testing.T)

func TestHTTP2Config_MaxValues

func TestHTTP2Config_MaxValues(t *testing.T)

func TestHTTP2Config_ZeroValues

func TestHTTP2Config_ZeroValues(t *testing.T)

func TestHTTP2ConnectTunneling

func TestHTTP2ConnectTunneling(t *testing.T)

func TestHTTP2ConnectionTimeout

func TestHTTP2ConnectionTimeout(t *testing.T)

func TestHTTP2EnableHTTP2_NoServer

func TestHTTP2EnableHTTP2_NoServer(t *testing.T)

TestHTTP2EnableHTTP2Method tests the EnableHTTP2 method when server is not set

func TestHTTP2EndToEnd_Integration

func TestHTTP2EndToEnd_Integration(t *testing.T)

func TestHTTP2Forwarding

func TestHTTP2Forwarding(t *testing.T)

func TestHTTP2GetHTTP2Server

func TestHTTP2GetHTTP2Server(t *testing.T)

TestHTTP2GetHTTP2Server returns the HTTP/2 server instance

func TestHTTP2Integration_Suite

func TestHTTP2Integration_Suite(t *testing.T)

func TestHTTP2MITMFlow

func TestHTTP2MITMFlow(t *testing.T)

func TestHTTP2MetricsCollection

func TestHTTP2MetricsCollection(t *testing.T)

func TestHTTP2ProxyTunnel

func TestHTTP2ProxyTunnel(t *testing.T)

TestHTTP2ProxyTunnel simulates a proxy tunnel via HTTP/2 CONNECT

func TestHTTP2RateLimiterCleanup_Integration

func TestHTTP2RateLimiterCleanup_Integration(t *testing.T)

TestHTTP2RateLimiterCleanup_Integration tests Cleanup with many clients

func TestHTTP2RequestHandling

func TestHTTP2RequestHandling(t *testing.T)

TestHTTP2RequestHandling tests the ServeHTTP method's protocol detection

func TestHTTP2RequestProcessing

func TestHTTP2RequestProcessing(t *testing.T)

func TestHTTP2ServeHTTP_ProtocolRouting

func TestHTTP2ServeHTTP_ProtocolRouting(t *testing.T)

Types

type BenchmarkResult

type BenchmarkResult struct {
	OpsPerSec   float64
	NsPerOp     int64
	BytesPerOp  int64
	AllocsPerOp int64
}

BenchmarkResult holds benchmark results

type HTTP2AwareProxy

type HTTP2AwareProxy struct {
	*MITMProxy
	// contains filtered or unexported fields
}

HTTP2AwareProxy wraps the MITM proxy with HTTP/2 capabilities

func NewHTTP2AwareProxy

func NewHTTP2AwareProxy(config *MITMConfig, h2Config *HTTP2Config) (*HTTP2AwareProxy, error)

NewHTTP2AwareProxy creates an MITM proxy with HTTP/2 support

func (*HTTP2AwareProxy) EnableHTTP2

func (p *HTTP2AwareProxy) EnableHTTP2() error

EnableHTTP2 enables HTTP/2 support on the base server

func (*HTTP2AwareProxy) GetH2Stats

func (p *HTTP2AwareProxy) GetH2Stats() map[string]interface{}

GetH2Stats returns HTTP/2 specific statistics

func (*HTTP2AwareProxy) GetHTTP2Server

func (p *HTTP2AwareProxy) GetHTTP2Server() *http2.Server

GetHTTP2Server returns the configured HTTP/2 server instance

func (*HTTP2AwareProxy) ServeHTTP

func (p *HTTP2AwareProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles HTTP requests, detecting HTTP/2 vs HTTP/1.1

type HTTP2Config

type HTTP2Config struct {
	// EnableHTTP2 enables HTTP/2 support
	EnableHTTP2 bool

	// MaxConcurrentStreams limits concurrent streams per connection
	MaxConcurrentStreams uint32

	// MaxReadFrameSize is the maximum frame size to accept
	MaxReadFrameSize uint32

	// MaxDecoderHeaderTableSize controls header compression table size
	MaxDecoderHeaderTableSize uint32

	// MaxEncoderHeaderTableSize controls response header compression
	MaxEncoderHeaderTableSize uint32

	// IdleTimeout configures the idle connection timeout
	IdleTimeout time.Duration

	// PreferHTTP2Protocol tries to negotiate HTTP/2 first
	PreferHTTP2Protocol bool

	// EnablePush enables HTTP/2 server push (disabled by default for security)
	EnablePush bool
}

HTTP2Config holds HTTP/2 specific configuration options

func DefaultHTTP2Config

func DefaultHTTP2Config() *HTTP2Config

DefaultHTTP2Config returns secure defaults for HTTP/2 configuration

type HTTP2RateLimiter

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

HTTP2RateLimiter manages rate limiting for HTTP/2 streams

func NewHTTP2RateLimiter

func NewHTTP2RateLimiter(maxStreams uint32, window time.Duration) *HTTP2RateLimiter

NewHTTP2RateLimiter creates a rate limiter for HTTP/2 streams

func (*HTTP2RateLimiter) Acquire

func (rl *HTTP2RateLimiter) Acquire(clientID string) (bool, func())

Acquire acquires a rate limit token for the given client. Returns (true, releaseFunc) if the stream is allowed, or (false, nil) if rate limited.

func (*HTTP2RateLimiter) AllowStream

func (rl *HTTP2RateLimiter) AllowStream(clientAddr string) bool

AllowStream checks if a new stream is allowed for the given client FIX: Changed from 0 to 1 for activeStreams and from make([]time.Time, 0) to []time.Time{time.Now()}

func (*HTTP2RateLimiter) Cleanup

func (rl *HTTP2RateLimiter) Cleanup()

Cleanup removes stale entries - fixed to clean up old entries with stale request times

func (*HTTP2RateLimiter) ReleaseStream

func (rl *HTTP2RateLimiter) ReleaseStream(clientAddr string)

ReleaseStream marks a stream as completed

type HTTP3AwareProxy

type HTTP3AwareProxy struct {
	// Embedded proxy for core functionality
	*Proxy

	// HTTP/3 specific config
	HTTP3Config *HTTP3Config
	// contains filtered or unexported fields
}

HTTP3AwareProxy extends the proxy with HTTP/3 capabilities

func NewHTTP3AwareProxy

func NewHTTP3AwareProxy(proxy *Proxy, config *HTTP3Config) *HTTP3AwareProxy

NewHTTP3AwareProxy creates a new proxy with HTTP/3 support

func (*HTTP3AwareProxy) DisableHTTP3

func (h3 *HTTP3AwareProxy) DisableHTTP3()

DisableHTTP3 disables HTTP/3 support

func (*HTTP3AwareProxy) EnableHTTP3

func (h3 *HTTP3AwareProxy) EnableHTTP3()

EnableHTTP3 enables HTTP/3 support

func (*HTTP3AwareProxy) GetHTTP3Config

func (h3 *HTTP3AwareProxy) GetHTTP3Config() *HTTP3Config

GetHTTP3Config returns the HTTP/3 configuration

func (*HTTP3AwareProxy) GetHTTP3Server

func (h3 *HTTP3AwareProxy) GetHTTP3Server() *http.Server

GetHTTP3Server returns the HTTP/3 server for advanced configuration

func (*HTTP3AwareProxy) GetHTTP3Stats

func (h3 *HTTP3AwareProxy) GetHTTP3Stats() HTTP3Metrics

GetHTTP3Stats returns HTTP/3 specific statistics

func (*HTTP3AwareProxy) GetTLSConfig

func (h3 *HTTP3AwareProxy) GetTLSConfig() *tls.Config

GetTLSConfig returns the HTTP/3 TLS configuration

func (*HTTP3AwareProxy) IsHTTP3Enabled

func (h3 *HTTP3AwareProxy) IsHTTP3Enabled() bool

IsHTTP3Enabled returns whether HTTP/3 is enabled

func (*HTTP3AwareProxy) ServeHTTP

func (h3 *HTTP3AwareProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles HTTP requests (for HTTP/3 compatibility)

func (*HTTP3AwareProxy) ServeHTTP3

func (h3 *HTTP3AwareProxy) ServeHTTP3(ctx context.Context) error

ServeHTTP3 starts the HTTP/3 server using TLS with ALPN This provides HTTP/3 over TLS/TCP (not QUIC/UDP)

func (*HTTP3AwareProxy) SetHTTP3Config

func (h3 *HTTP3AwareProxy) SetHTTP3Config(config *HTTP3Config)

SetHTTP3Config sets the HTTP/3 configuration

func (*HTTP3AwareProxy) StopHTTP3

func (h3 *HTTP3AwareProxy) StopHTTP3()

StopHTTP3 stops the HTTP/3 server

type HTTP3Config

type HTTP3Config struct {
	// Enabled enables HTTP/3 support via TLS ALPN
	Enabled bool

	// ListenAddr is the address to listen on for HTTP/3
	ListenAddr string

	// Port is the port for HTTP/3 (default: 8443)
	Port int

	// MaxConcurrentStreams is the max concurrent streams per connection
	MaxConcurrentStreams uint32

	// MaxIdleConns is the max idle connections
	MaxIdleConns int

	// IdleTimeout is the idle connection timeout
	IdleTimeout time.Duration

	// ReadTimeout is the read timeout
	ReadTimeout time.Duration

	// WriteTimeout is the write timeout
	WriteTimeout time.Duration

	// HandleGzip enables gzip handling
	HandleGzip bool
}

HTTP3Config contains HTTP/3 specific configuration

func DefaultHTTP3Config

func DefaultHTTP3Config() *HTTP3Config

DefaultHTTP3Config returns the default HTTP/3 configuration

type HTTP3Metrics

type HTTP3Metrics struct {
	ActiveConnections int64
	TotalRequests     int64
	BytesReceived     int64
	BytesSent         int64
}

HTTP3Metrics holds HTTP/3 specific metrics

type Health

type Health struct {
	Status      string  `json:"status"`
	Uptime      float64 `json:"uptime"`
	MemoryUsage int64   `json:"memory_usage"`
	Goroutines  int32   `json:"goroutines"`
}

Health represents proxy health status

type Inspector

type Inspector interface {
	InspectRequest(req *Request) ([]Violation, error)
	InspectResponse(resp *Response) ([]Violation, error)
}

Inspector interface for request/response inspection

type MITMAttestation

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

MITMAttestation integrates PKI attestation into the MITM proxy

func NewMITMAttestation

func NewMITMAttestation(config *MITMAttestationConfig) (*MITMAttestation, error)

NewMITMAttestation creates a new MITM attestation service

func (*MITMAttestation) AddTrustAnchor

func (m *MITMAttestation) AddTrustAnchor(cert *x509.Certificate) error

AddTrustAnchor adds a new trust anchor to the attestation service

func (*MITMAttestation) AttestConnection

func (m *MITMAttestation) AttestConnection(connState *tls.ConnectionState) (*MITMAttestationResult, error)

AttestConnection validates a TLS connection's peer certificates

func (*MITMAttestation) AttestUpstreamCertificate

func (m *MITMAttestation) AttestUpstreamCertificate(cert *x509.Certificate) *MITMAttestationResult

AttestUpstreamCertificate validates an upstream server certificate

func (*MITMAttestation) ClearCache

func (m *MITMAttestation) ClearCache()

ClearCache clears the attestation result cache

func (*MITMAttestation) FetchAndAttestCertificate

func (m *MITMAttestation) FetchAndAttestCertificate(host string, timeout time.Duration) (*MITMAttestationResult, error)

FetchAndAttestCertificate fetches and attests an upstream certificate

func (*MITMAttestation) GetStats

func (m *MITMAttestation) GetStats() map[string]interface{}

GetStats returns attestation statistics

func (*MITMAttestation) GetTrustAnchors

func (m *MITMAttestation) GetTrustAnchors() []*pkiattest.TrustAnchor

GetTrustAnchors returns configured trust anchors

func (*MITMAttestation) IsEnabled

func (m *MITMAttestation) IsEnabled() bool

IsEnabled returns whether attestation is enabled

func (*MITMAttestation) PreInterceptCheck

func (m *MITMAttestation) PreInterceptCheck(host string, timeout time.Duration) (bool, *MITMAttestationResult, error)

PreInterceptCheck performs attestation before TLS interception Returns true if the connection should be allowed, false if it should be blocked

func (*MITMAttestation) RevokeCertificate

func (m *MITMAttestation) RevokeCertificate(serialNumber, reason string) error

RevokeCertificate marks a certificate as revoked

func (*MITMAttestation) SetEnabled

func (m *MITMAttestation) SetEnabled(enabled bool)

SetEnabled enables or disables attestation

func (*MITMAttestation) ShouldFailClosed

func (m *MITMAttestation) ShouldFailClosed() bool

ShouldFailClosed returns whether the attestation should fail closed

func (*MITMAttestation) ValidateExistingConnection

func (m *MITMAttestation) ValidateExistingConnection(conn *tls.Conn) (*MITMAttestationResult, error)

ValidateExistingConnection validates certificates from an existing TLS connection

type MITMAttestationConfig

type MITMAttestationConfig struct {
	// Enable attestation checks
	Enabled bool

	// Require chain verification before interception
	RequireChainVerification bool

	// Enable CRL checking
	RequireCRL bool

	// Enable OCSP checking
	RequireOCSP bool

	// CRL check timeout
	CRLTimeout time.Duration

	// OCSP check timeout
	OCSPTimeout time.Duration

	// Trust anchors for certificate validation
	TrustAnchors []*pkiattest.TrustAnchor

	// Enable backdoor detection
	BackdoorPrevention bool

	// Fail closed (block on attestation failure)
	FailClosed bool

	// Log attestation results
	LogResults bool

	// Cache attestation results
	CacheResults bool

	// Cache TTL
	CacheTTL time.Duration
}

MITMAttestationConfig holds configuration for MITM attestation

func DefaultMITMAttestationConfig

func DefaultMITMAttestationConfig() *MITMAttestationConfig

DefaultMITMAttestationConfig returns default configuration

type MITMAttestationResult

type MITMAttestationResult struct {
	Valid               bool
	Reason              string
	Certificate         *x509.Certificate
	ChainVerified       bool
	RevocationChecked   bool
	BackdoorChecked     bool
	BackdoorDetected    bool
	AttestationDuration time.Duration
	Timestamp           time.Time
}

MITMAttestationResult represents the result of an attestation check

type MITMConfig

type MITMConfig struct {
	// Enable MITM mode
	Enabled bool

	// Certificate Authority for generating certificates
	CA *tlspkg.CertificateAuthority

	// Listen address for MITM proxy
	BindAddress string

	// Upstream proxy (optional, for chaining)
	UpstreamProxy string

	// Maximum concurrent connections
	MaxConnections int

	// Connection timeout
	Timeout time.Duration

	// Enable TLS 1.3
	EnableTLS13 bool

	// Skip TLS verification for upstream connections
	InsecureSkipVerify bool

	// Enable content scanning
	EnableScanning bool

	// Scanner for content inspection
	Scanner *scanner.Scanner

	// Compliance manager for ATLAS/NIST checks
	ComplianceManager *compliance.ComplianceManager

	// Attestation configuration for PKI certificate validation
	AttestationConfig *MITMAttestationConfig
}

MITMConfig holds configuration for MITM proxy

type MITMProxy

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

MITMProxy implements HTTPS Man-in-the-Middle interception

func NewMITMProxy

func NewMITMProxy(config *MITMConfig) (*MITMProxy, error)

NewMITMProxy creates a new MITM proxy

func (*MITMProxy) AddTrustAnchor

func (m *MITMProxy) AddTrustAnchor(cert *x509.Certificate) error

AddTrustAnchor adds a trust anchor for attestation

func (*MITMProxy) GetAttestation

func (m *MITMProxy) GetAttestation() *MITMAttestation

GetAttestation returns the PKI attestation

func (*MITMProxy) GetCA

GetCA returns the Certificate Authority

func (*MITMProxy) GetHealth

func (m *MITMProxy) GetHealth() map[string]interface{}

GetHealth returns health status

func (*MITMProxy) GetStats

func (m *MITMProxy) GetStats() map[string]interface{}

GetStats returns statistics about the MITM proxy

func (*MITMProxy) Ready

func (m *MITMProxy) Ready() <-chan struct{}

Ready returns a channel that is closed when the server is ready to accept connections

func (*MITMProxy) ServeHTTP

func (m *MITMProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles HTTP requests

func (*MITMProxy) SetAttestation

func (m *MITMProxy) SetAttestation(a *MITMAttestation)

SetAttestation sets the PKI attestation

func (*MITMProxy) SetComplianceManager

func (m *MITMProxy) SetComplianceManager(cm *compliance.ComplianceManager)

SetComplianceManager sets the compliance manager

func (*MITMProxy) SetScanner

func (m *MITMProxy) SetScanner(s *scanner.Scanner)

SetScanner sets the content scanner

func (*MITMProxy) Start

func (m *MITMProxy) Start() error

Start starts the MITM proxy server

func (*MITMProxy) Stop

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

Stop gracefully stops the MITM proxy

type MLAnomalyResult

type MLAnomalyResult struct {
	Anomalies        []ml.Anomaly   `json:"anomalies"`
	SeverityCounts   map[string]int `json:"severity_counts"`
	ShouldBlock      bool           `json:"should_block"`
	BlockingReason   string         `json:"blocking_reason"`
	AnalysisDuration time.Duration  `json:"analysis_duration_ms"`
	Method           string         `json:"method"`
	Path             string         `json:"path"`
	Size             int64          `json:"size"`
}

MLAnomalyResult holds the result of ML anomaly detection

type MLMiddleware

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

MLMiddleware provides ML-based anomaly detection for HTTP traffic

func MLMiddlewareFromPolicy

func MLMiddlewareFromPolicy(policyData map[string]interface{}) (*MLMiddleware, error)

MLMiddlewareFromPolicy creates ML middleware from policy configuration Note: This is a placeholder for future policy integration

func NewMLMiddleware

func NewMLMiddleware(config *MLMiddlewareConfig) (*MLMiddleware, error)

NewMLMiddleware creates a new ML middleware instance

func (*MLMiddleware) Config

func (m *MLMiddleware) Config() *MLMiddlewareConfig

Config returns the ML middleware configuration

func (*MLMiddleware) GetStats

func (m *MLMiddleware) GetStats() *MLStats

GetStats returns current ML statistics

func (*MLMiddleware) Middleware

func (m *MLMiddleware) Middleware(next http.Handler) http.Handler

Middleware returns the HTTP middleware handler

func (*MLMiddleware) ResetStats

func (m *MLMiddleware) ResetStats()

ResetStats resets ML statistics

func (*MLMiddleware) UpdateConfig

func (m *MLMiddleware) UpdateConfig(config *MLMiddlewareConfig) error

UpdateConfig updates the ML middleware configuration

type MLMiddlewareConfig

type MLMiddlewareConfig struct {
	// Enabled toggles ML anomaly detection on/off
	Enabled bool `json:"enabled"`

	// Sensitivity determines the threshold for anomaly detection
	// Options: "low", "medium", "high", "paranoid"
	Sensitivity string `json:"sensitivity"`

	// BlockOnHighSeverity determines if high-severity anomalies should be blocked
	BlockOnHighSeverity bool `json:"block_on_high_severity"`

	// BlockOnCriticalSeverity determines if critical-severity anomalies should be blocked
	BlockOnCriticalSeverity bool `json:"block_on_critical_severity"`

	// MinScoreToBlock minimum score to trigger blocking
	MinScoreToBlock float64 `json:"min_score_to_block"`

	// LogAllAnomalies whether to log all anomalies or only blocked ones
	LogAllAnomalies bool `json:"log_all_anomalies"`

	// SampleRate percentage of requests to analyze (0-100)
	// Use for high-throughput environments
	SampleRate int `json:"sample_rate"`

	// ExcludedPaths URL paths to exclude from ML analysis
	ExcludedPaths []string `json:"excluded_paths"`

	// ExcludedMethods HTTP methods to exclude from ML analysis
	ExcludedMethods []string `json:"excluded_methods"`

	// Detector holds the ML detector instance (set automatically)
	Detector *ml.Detector `json:"-"`
}

MLMiddlewareConfig holds configuration for ML anomaly detection middleware

func DefaultMLMiddlewareConfig

func DefaultMLMiddlewareConfig() *MLMiddlewareConfig

DefaultMLMiddlewareConfig returns sensible defaults for ML middleware

type MLOptions

type MLOptions struct {
	// ML Detection settings
	EnableMLDetection         bool
	MLSensitivity             string
	MLBlockOnCriticalSeverity bool
	MLBlockOnHighSeverity     bool
	MLMinScoreToBlock         float64
	MLSampleRate              int
	MLExcludedPaths           []string
	MLExcludedMethods         []string

	// Advanced ML features
	EnablePromptInjectionDetection bool
	PromptInjectionSensitivity     int
	EnableContentAnalysis          bool
	EnableBehavioralAnalysis       bool
}

MLOptions extends proxy.Options with ML-specific configuration

func ConvertConfigToMLOptions

func ConvertConfigToMLOptions(cfg *config.Config) *MLOptions

ConvertConfigToMLOptions converts config.MLConfig to MLOptions

type MLStats

type MLStats struct {
	TotalRequests    int64            `json:"total_requests"`
	AnalyzedRequests int64            `json:"analyzed_requests"`
	BlockedRequests  int64            `json:"blocked_requests"`
	AnomalyCounts    map[string]int64 `json:"anomaly_counts"`
	LastUpdate       time.Time        `json:"last_update"`
	// contains filtered or unexported fields
}

MLStats holds statistics about ML detection

type Metrics

type Metrics interface {
	RecordRequest(duration time.Duration, statusCode int)
	RecordViolation(violation Violation)
}

Metrics interface for metrics collection

type Options

type Options struct {
	BindAddress    string
	Upstream       string
	TLS            *TLSConfig
	MaxBodySize    int64         // Default: 10MB
	Timeout        time.Duration // Default: 30s
	RateLimit      int           // Requests per minute, default: 100
	HTTP2          *HTTP2Config  // HTTP/2 configuration
	HTTP3          *HTTP3Config  // HTTP/3 configuration
	CircuitBreaker *resilience.CircuitBreakerConfig

	// ML Configuration - Integrated in v0.41.0
	EnableMLDetection              bool
	MLSensitivity                  string
	MLBlockOnCriticalSeverity      bool
	MLBlockOnHighSeverity          bool
	MLMinScoreToBlock              float64
	MLSampleRate                   int
	MLExcludedPaths                []string
	MLExcludedMethods              []string
	EnablePromptInjectionDetection bool
	PromptInjectionSensitivity     int
	EnableContentAnalysis          bool
	EnableBehavioralAnalysis       bool
}

Options contains proxy configuration

type PKIAttestationIntegrator

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

PKIAttestationIntegrator integrates PKI attestation with MITM proxy

func NewPKIAttestationIntegrator

func NewPKIAttestationIntegrator(config *PKIConfig) (*PKIAttestationIntegrator, error)

NewPKIAttestationIntegrator creates a new PKI attestation integrator

func (*PKIAttestationIntegrator) AddTrustAnchor

func (p *PKIAttestationIntegrator) AddTrustAnchor(cert *x509.Certificate) (*pkiattest.TrustAnchor, error)

AddTrustAnchor adds a new trust anchor to the integrator

func (*PKIAttestationIntegrator) GetAttestationStatus

func (p *PKIAttestationIntegrator) GetAttestationStatus() map[string]interface{}

GetAttestationStatus returns the current attestation status

func (*PKIAttestationIntegrator) GetTrustStoreStats

func (p *PKIAttestationIntegrator) GetTrustStoreStats() map[string]interface{}

GetTrustStoreStats returns trust store statistics

func (*PKIAttestationIntegrator) RevokeCertificate

func (p *PKIAttestationIntegrator) RevokeCertificate(serialNumber, reason string) error

RevokeCertificate revokes a certificate by serial number

func (*PKIAttestationIntegrator) VerifyCertificateChain

func (p *PKIAttestationIntegrator) VerifyCertificateChain(cert *x509.Certificate) ([]x509.Certificate, error)

VerifyCertificateChain verifies a complete certificate chain

func (*PKIAttestationIntegrator) VerifyClientCertificate

func (p *PKIAttestationIntegrator) VerifyClientCertificate(cert *x509.Certificate) (bool, string, error)

VerifyClientCertificate verifies a client certificate using PKI attestation

type PKIConfig

type PKIConfig struct {
	Enabled      bool
	RequireCRL   bool
	RequireOCSP  bool
	VerifyChain  bool
	TrustAnchors []*pkiattest.TrustAnchor
}

PKIConfig holds configuration for PKI attestation integration

type Proxy

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

Proxy represents the reverse proxy

func New

func New(opts *Options) *Proxy

New creates a new hardened proxy

func (*Proxy) GetCircuitBreaker

func (p *Proxy) GetCircuitBreaker() *resilience.CircuitBreaker

GetCircuitBreaker returns the circuit breaker

func (*Proxy) GetComplianceManager

func (p *Proxy) GetComplianceManager() *compliance.ComplianceManager

GetComplianceManager returns the compliance manager

func (*Proxy) GetHealth

func (p *Proxy) GetHealth() map[string]interface{}

GetHealth returns health status

func (*Proxy) GetMLMiddleware

func (p *Proxy) GetMLMiddleware() *MLMiddleware

GetMLMiddleware returns the ML middleware

func (*Proxy) GetScanner

func (p *Proxy) GetScanner() *scanner.Scanner

GetScanner returns the scanner instance

func (*Proxy) GetStats

func (p *Proxy) GetStats() map[string]interface{}

GetStats returns proxy statistics

func (*Proxy) GetStatsStruct

func (p *Proxy) GetStatsStruct() *StatsStruct

GetStatsStruct returns proxy statistics as a struct

func (*Proxy) IsEnabled

func (p *Proxy) IsEnabled() bool

IsEnabled returns whether proxy is enabled

func (*Proxy) ServeHTTP

func (p *Proxy) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP handles incoming requests with security features and content inspection

func (*Proxy) SetScanner

func (p *Proxy) SetScanner(s *scanner.Scanner)

SetScanner sets the scanner instance

func (*Proxy) Start

func (p *Proxy) Start() error

Start starts the hardened proxy server

func (*Proxy) Stop

func (p *Proxy) Stop(ctx context.Context) error

Stop gracefully stops the proxy server

type ProxyMetrics

type ProxyMetrics struct {
	// Request counts
	TotalRequests   int64
	BlockedRequests int64
	AllowedRequests int64

	// Latency
	AvgLatency time.Duration
	P99Latency time.Duration

	// TLS metrics
	TLSVersions  map[string]int64
	CipherSuites map[string]int64

	// Connection metrics
	ActiveConnections int64
	TotalConnections  int64
}

ProxyMetrics holds proxy performance metrics

func NewProxyMetrics

func NewProxyMetrics() *ProxyMetrics

NewProxyMetrics creates new proxy metrics

func (*ProxyMetrics) RecordCipherSuite

func (m *ProxyMetrics) RecordCipherSuite(suite string)

RecordCipherSuite records a cipher suite usage

func (*ProxyMetrics) RecordTLSVersion

func (m *ProxyMetrics) RecordTLSVersion(version string)

RecordTLSVersion records a TLS version usage

type ProxyOptions

type ProxyOptions = Options

ProxyOptions represents proxy options (alias for Options for grpc compatibility)

type ProxyTLSConfig

type ProxyTLSConfig struct {
	// Enable FIPS mode
	FIPSMode bool

	// Minimum TLS version
	MinTLSVersion uint16

	// Client certificate required
	RequireClientCert bool

	// Allowed cipher suites
	CipherSuites []uint16
}

ProxyTLSConfig holds TLS configuration for the proxy

func DefaultProxyTLSConfig

func DefaultProxyTLSConfig() *ProxyTLSConfig

DefaultProxyTLSConfig returns default TLS configuration for proxy

func (*ProxyTLSConfig) GetTLSConfig

func (p *ProxyTLSConfig) GetTLSConfig() *tls.Config

GetTLSConfig returns a TLS config for the proxy

type ProxyViolation

type ProxyViolation struct {
	ID        string        `json:"id"`
	Type      ViolationType `json:"type"`
	Severity  Severity      `json:"severity"`
	Message   string        `json:"message"`
	ClientIP  string        `json:"client_ip"`
	Method    string        `json:"method"`
	Path      string        `json:"path"`
	Blocked   bool          `json:"blocked"`
	Timestamp time.Time     `json:"timestamp"`
}

ProxyViolation represents a detailed security violation

type ProxyWithML

type ProxyWithML struct {
	*Proxy
	MLMiddleware            *MLMiddleware
	PromptInjectionDetector *ml.PromptInjectionDetector
	ContentAnalyzer         *ml.ContentAnalyzer
	BehavioralAnalyzer      *ml.BehavioralAnalyzer
}

ProxyWithML extends Proxy with ML capabilities This is the recommended way to create a proxy with ML detection enabled

func NewProxyWithConfig

func NewProxyWithConfig(cfg *config.Config) (*ProxyWithML, error)

NewProxyWithConfig creates a new proxy from config.Config with ML enabled This is the main entry point for creating a production-ready proxy

func NewProxyWithMLOptions

func NewProxyWithMLOptions(opts *Options, mlOpts *MLOptions) (*ProxyWithML, error)

NewProxyWithMLOptions creates a new proxy with ML options

func (*ProxyWithML) GetHealth

func (p *ProxyWithML) GetHealth() map[string]interface{}

GetHealth returns health status including ML

func (*ProxyWithML) GetMLStats

func (p *ProxyWithML) GetMLStats() map[string]interface{}

GetMLStats returns ML detection statistics

func (*ProxyWithML) ResetMLStats

func (p *ProxyWithML) ResetMLStats()

ResetMLStats resets all ML statistics

func (*ProxyWithML) Start

func (p *ProxyWithML) Start() error

Start starts the proxy server with ML middleware in the pipeline

func (*ProxyWithML) Stop

func (p *ProxyWithML) Stop() error

Stop stops the proxy

type RateLimiter

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

RateLimiter implements token bucket rate limiting

func NewRateLimiter

func NewRateLimiter(ratePerMinute int) *RateLimiter

NewRateLimiter creates a token bucket rate limiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow() bool

Allow checks if request is allowed under rate limit

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop stops the rate limiter

type Request

type Request struct {
	Method    string
	URL       string
	Headers   http.Header
	Body      []byte
	SourceIP  string
	Timestamp time.Time
}

Request represents an incoming request

type Response

type Response struct {
	StatusCode int
	Headers    http.Header
	Body       []byte
	Timestamp  time.Time
	Duration   time.Duration
}

Response represents an outgoing response

type Severity

type Severity string

Severity represents violation severity levels

const (
	SeverityCritical Severity = "critical"
	SeverityHigh     Severity = "high"
	SeverityMedium   Severity = "medium"
	SeverityLow      Severity = "low"
	SeverityInfo     Severity = "info"
)

Severity constants

type Stats

type Stats struct {
	RequestsTotal     int64   `json:"requests_total"`
	RequestsBlocked   int64   `json:"requests_blocked"`
	RequestsAllowed   int64   `json:"requests_allowed"`
	BytesIn           int64   `json:"bytes_in"`
	BytesOut          int64   `json:"bytes_out"`
	ActiveConnections int32   `json:"active_connections"`
	AvgLatencyMs      float64 `json:"avg_latency_ms"`
	P99LatencyMs      float64 `json:"p99_latency_ms"`
	Errors            int64   `json:"errors"`
}

Stats represents proxy statistics

type StatsStruct

type StatsStruct struct {
	RequestsTotal     int64
	RequestsBlocked   int64
	RequestsAllowed   int64
	BytesIn           int64
	BytesOut          int64
	ActiveConnections int64
	AvgLatencyMs      float64
	P99LatencyMs      float64
	Errors            int64
}

StatsStruct represents proxy statistics in a structured format

type StreamLimiter

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

StreamLimiter tracks rate limiting for a single client's streams

type TLSConfig

type TLSConfig struct {
	CertFile string
	KeyFile  string
	Config   *tls.Config
}

TLSConfig holds TLS settings

type TenantAwareProxy

type TenantAwareProxy struct {
	*Proxy
	// contains filtered or unexported fields
}

TenantAwareProxy wraps a proxy with tenant awareness

func NewTenantAwareProxy

func NewTenantAwareProxy(proxy *Proxy, manager *tenant.Manager, logger *slog.Logger) *TenantAwareProxy

NewTenantAwareProxy creates a new tenant-aware proxy

func (*TenantAwareProxy) GetTenantMiddleware

func (tap *TenantAwareProxy) GetTenantMiddleware() *TenantMiddleware

GetTenantMiddleware returns the tenant middleware

func (*TenantAwareProxy) ServeHTTP

func (tap *TenantAwareProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles HTTP requests with tenant awareness

func (*TenantAwareProxy) WithTenantMiddleware

func (tap *TenantAwareProxy) WithTenantMiddleware(handler http.Handler) http.Handler

WithTenantMiddleware wraps a handler with tenant middleware

type TenantMiddleware

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

TenantMiddleware provides tenant-aware proxy functionality

func NewTenantMiddleware

func NewTenantMiddleware(manager *tenant.Manager, logger *slog.Logger) *TenantMiddleware

NewTenantMiddleware creates a new tenant middleware

func (*TenantMiddleware) Middleware

func (tm *TenantMiddleware) Middleware(next http.Handler) http.Handler

Middleware returns an HTTP middleware that handles tenant isolation

func (*TenantMiddleware) RegisterDomainMapping

func (tm *TenantMiddleware) RegisterDomainMapping(domain, tenantID string)

RegisterDomainMapping registers a domain to tenant mapping

type Violation

type Violation struct {
	Type     string
	Message  string
	Severity string
}

Violation represents a security violation

type ViolationType

type ViolationType string

ViolationType represents types of security violations

const (
	ViolationTypeMaliciousRequest ViolationType = "malicious_request"
	ViolationTypeSQLInjection     ViolationType = "sql_injection"
	ViolationTypeXSS              ViolationType = "xss"
	ViolationTypeCSRF             ViolationType = "csrf"
	ViolationTypePathTraversal    ViolationType = "path_traversal"
	ViolationTypeCommandInjection ViolationType = "command_injection"
	ViolationTypeAtlasTechnique   ViolationType = "atlas_technique"
	ViolationTypeCustomPattern    ViolationType = "custom_pattern"
)

ViolationType constants

Jump to

Keyboard shortcuts

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