Documentation
¶
Overview ¶
Package network provides utilities for network operations, particularly for downloading files with progress tracking.
Features:
- File downloading with progress reporting
- Support for authenticated downloads using tokens
- Human-readable progress display
- Safe file writing with temporary files
Package network provides utilities for OpenZiti network operations including a generic configuration-driven proxy server with enterprise features.
The proxy package includes:
- JSON-based configuration for routes, backends, and policies
- Multiple load balancing strategies (round-robin, weighted, least-connections)
- Automatic health checks with failover
- Retry logic with exponential backoff
- Authentication (API key, JWT, basic auth)
- CORS support
- Request logging
- Hot configuration reload
Example usage:
proxy, err := network.NewZitiProxy("config.json")
if err != nil {
log.Fatal(err)
}
proxy.Start()
Package network provides utilities for secure network operations, particularly SSH connections with certificate-based authentication.
Features:
- SSH key and certificate parsing
- Support for both regular private keys and certificate-based authentication
- SSH command execution on remote hosts
- Support for various key types (RSA, EC, DSA)
- Handling of encrypted PEM blocks
Package network provides utilities for secure network operations ¶
Package network provides utilities for interacting with OpenZiti networks. It includes functions for authenticating with Ziti controllers, managing services, creating policies, and handling configurations.
Features:
- Ziti authentication and session management
- Service creation and configuration
- Service policy management
- Edge router policy management
- Configuration type querying
- Identity management
- HTTP client creation with Ziti context
- Context caching for efficient resource usage
Context Caching:
The package implements automatic context caching to optimize resource usage when multiple routes/backends use the same Ziti identity. When ZitiSetup() is called with an identity file that has already been initialized, it returns the cached context instead of creating a new one.
This means you may see "closing duplicate connection" messages from the Ziti SDK during startup - this is EXPECTED and CORRECT behavior. The SDK detects when multiple components try to establish connections using the same identity and automatically closes the duplicates, keeping only one active connection.
Example: If you have 3 routes all using the same identity and service, they will all share a single Ziti context and connection, which is efficient and correct.
All functions use the Ziti REST API and require appropriate authentication tokens. The package handles JSON serialization/deserialization for Ziti API interactions.
Index ¶
- func ChainMiddleware(handler http.Handler, middlewares ...Middleware) http.Handler
- func DownloadFile(token string, url string, filepath string) error
- func HttpClientDownloadFile(url, localPath string) error
- func LogCompatibilityCheck(identityFile string) error
- func MustBeCompatible(identityFile string)
- func RewritePath(originalPath string, route *RouteConfig, params map[string]string) string
- func SshExec(address string, username string, keyfile string, certfile string, cmd string) error
- func WriteZitiControllerConfig(filename string, cfg ZitiControllerConfig) error
- func WriteZitiRouterConfig(filename string, cfg ZitiRouterConfig) error
- func ZitiAuthenticate(url, user, pass string) (string, error)
- func ZitiClient(id string) *http.Client
- func ZitiCreateEdgeRouterPolicy(url, token, name string, routers, services, roles []string) error
- func ZitiCreateService(url, token, name, hostV1, interceptV1 string) (string, error)
- func ZitiCreateServiceConfig(url, token, name, configType string, config map[string]interface{}) (string, error)
- func ZitiCreateServicePolicy(url, token, name, policyType, serviceID, identity string) (string, error)
- func ZitiGenerateCtrlConfig(outFile string) error
- func ZitiGenerateRouterConfig(outFile string) error
- func ZitiGetConfigTypes(url, token, name string) (string, error)
- func ZitiGetIdentity(urlSrc, token, name string) (string, error)
- func ZitiIdentities(urlSrc, token string) error
- func ZitiServicePolicies(url, token string) error
- func ZitiSetup(identityFile, serviceName string) (*http.Transport, error)
- type AuthConfig
- type Backend
- type BackendConfig
- type CORSConfig
- type CircuitBreakerConfig
- type ControllerVersionResponse
- type Duration
- type HealthCheckConfig
- type HealthChecker
- type JWTAuthConfig
- type LoadBalancer
- func (lb *LoadBalancer) DecrementConnections(backend *Backend)
- func (lb *LoadBalancer) GetHealthyBackendCount() int
- func (lb *LoadBalancer) IncrementConnections(backend *Backend)
- func (lb *LoadBalancer) RecordFailure(backend *Backend)
- func (lb *LoadBalancer) RecordSuccess(backend *Backend)
- func (lb *LoadBalancer) SelectBackend() *Backend
- func (lb *LoadBalancer) Stop()
- type LoadBalancingStrategy
- type LoggingConfig
- type Middleware
- type ProxyConfig
- type RetryConfig
- type RouteConfig
- type RouteMatch
- type Router
- type SSHTunnel
- type VersionInfo
- type WriteCounter
- type ZitiAPIBinding
- type ZitiBindPoint
- type ZitiCSR
- type ZitiConfig
- type ZitiControllerConfig
- type ZitiCtrlEndpoint
- type ZitiCtrlListener
- type ZitiDialer
- type ZitiEdgeCSR
- type ZitiEdgeEnroll
- type ZitiEnrollment
- type ZitiIdentity
- type ZitiLinkConfig
- type ZitiLinkListener
- type ZitiListener
- type ZitiProxy
- type ZitiResult
- type ZitiRouterConfig
- type ZitiSANs
- type ZitiServiceConfig
- type ZitiServiceConfigsResult
- type ZitiSigningCert
- type ZitiToken
- type ZitiWebListener
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ChainMiddleware ¶ added in v0.0.9
func ChainMiddleware(handler http.Handler, middlewares ...Middleware) http.Handler
ChainMiddleware chains multiple middleware functions
func DownloadFile ¶
DownloadFile downloads a file from a URL to a local path with progress tracking. This function:
- Creates a temporary file for safe downloading
- Makes an authenticated HTTP GET request
- Downloads the file while tracking progress
- Renames the temporary file to the final destination on success
Parameters:
- token: Authentication token for the request (can be empty if no auth needed)
- url: The URL to download from
- filepath: The local path to save the file to
Returns:
- error: If any step in the download process fails
The function uses a temporary file (.tmp extension) during download and only renames it to the final destination after successful completion. This prevents corrupted files if the download is interrupted.
func HttpClientDownloadFile ¶
func LogCompatibilityCheck ¶ added in v0.0.11
LogCompatibilityCheck performs a compatibility check and logs the results
func MustBeCompatible ¶ added in v0.0.11
func MustBeCompatible(identityFile string)
MustBeCompatible checks compatibility and panics if incompatible Use this during initialization to enforce version requirements
func RewritePath ¶ added in v0.0.9
func RewritePath(originalPath string, route *RouteConfig, params map[string]string) string
RewritePath rewrites the request path based on route configuration
func SshExec ¶
SshExec executes a command on a remote host via SSH. This function establishes an SSH connection to the specified host and executes the given command, returning its output.
Parameters:
- address: The remote host address in "host:port" format
- username: The username for SSH authentication
- keyfile: Path to the private key file
- certfile: Path to the certificate file (optional, can be empty)
- cmd: The command to execute on the remote host
The function:
- Creates an SSH signer from the provided key and certificate files
- Configures the SSH client with the signer
- Establishes a connection to the remote host
- Creates a new session
- Executes the command and captures its output
- Prints the command output to stdout
Note: This function uses InsecureIgnoreHostKey() for host key verification, which is not secure for production use. In production, you should implement proper host key verification.
func WriteZitiControllerConfig ¶
func WriteZitiControllerConfig(filename string, cfg ZitiControllerConfig) error
func WriteZitiRouterConfig ¶
func WriteZitiRouterConfig(filename string, cfg ZitiRouterConfig) error
func ZitiAuthenticate ¶
ZitiAuthenticate authenticates with a Ziti controller and obtains a session token. This function is the first step in interacting with a Ziti network.
Parameters:
- url: The base URL of the Ziti controller
- user: The username for authentication
- pass: The password for authentication
Returns:
- string: The Ziti session token
- error: If authentication fails
The function:
- Creates a JSON payload with the credentials
- Makes a POST request to the authenticate endpoint
- Decodes the response to extract the session token
func ZitiClient ¶
ZitiClient creates a new HTTP client that routes traffic through the Ziti network. This client can be used to make HTTP requests that will be tunneled through the Ziti overlay network.
Parameters:
- id: The Ziti identity configuration file path
Returns:
- *http.Client: An HTTP client configured with the Ziti context
The function:
- Creates a Ziti configuration from the specified file
- Creates a Ziti context from the configuration
- Returns an HTTP client that uses the Ziti context
func ZitiCreateEdgeRouterPolicy ¶
ZitiCreateEdgeRouterPolicy creates a new Ziti edge router policy. Edge router policies define which edge routers can access which services.
Parameters:
- url: The base URL of the Ziti controller
- token: The Ziti session token
- name: The name of the policy to create
- routers: Array of edge router role IDs
- services: Array of service role IDs
- roles: Array of permission roles
Returns:
- error: If policy creation fails
The function:
- Creates a payload with the policy configuration
- Makes a POST request to the service-edge-router-policies endpoint
func ZitiCreateService ¶
ZitiCreateService creates a new Ziti service with the specified configuration. Services define what network resources are available through the Ziti network.
Parameters:
- url: The base URL of the Ziti controller
- token: The Ziti session token
- name: The name of the service to create
- hostV1: The host.v1 configuration ID
- interceptV1: The intercept.v1 configuration ID
Returns:
- string: The ID of the created service
- error: If service creation fails
The function:
- Creates a payload with the service configuration
- Makes a POST request to the services endpoint
- Returns the ID of the created service
func ZitiCreateServiceConfig ¶
func ZitiCreateServiceConfig(url, token, name, configType string, config map[string]interface{}) (string, error)
ZitiCreateServiceConfig creates a new Ziti service configuration. Service configurations define how services behave in the Ziti network.
Parameters:
- url: The base URL of the Ziti controller
- token: The Ziti session token
- name: The name of the configuration to create
- configType: The type of configuration (e.g., "host.v1", "intercept.v1")
- config: The configuration data as a map
Returns:
- string: The ID of the created configuration
- error: If configuration creation fails
The function:
- Creates a payload with the configuration data
- Makes a POST request to the configs endpoint
- Returns the ID of the created configuration
func ZitiCreateServicePolicy ¶
func ZitiCreateServicePolicy(url, token, name, policyType, serviceID, identity string) (string, error)
ZitiCreateServicePolicy creates a new Ziti service policy. Service policies define which identities can access which services.
Parameters:
- url: The base URL of the Ziti controller
- token: The Ziti session token
- name: The name of the policy to create
- policyType: The type of policy (Dial or Bind)
- serviceID: The service role ID
- identity: The identity role ID
Returns:
- string: The ID of the created policy
- error: If policy creation fails
The function:
- Creates a payload with the policy configuration
- Makes a POST request to the service-policies endpoint
- Returns the ID of the created policy
func ZitiGenerateCtrlConfig ¶
func ZitiGetConfigTypes ¶
ZitiGetConfigTypes retrieves the ID of a specific Ziti configuration type. This function queries all available configuration types and finds the one with the specified name.
Parameters:
- url: The base URL of the Ziti controller
- token: The Ziti session token
- name: The name of the configuration type to find
Returns:
- string: The ID of the found configuration type
- error: If the configuration type is not found or if the request fails
func ZitiGetIdentity ¶
ZitiGetIdentity finds a Ziti identity by name and returns its ID. This function queries all identities and searches for one with the specified name.
Parameters:
- urlSrc: The base URL of the Ziti controller
- token: The Ziti session token
- name: The name of the identity to find
Returns:
- string: The ID of the found identity
- error: If the identity is not found or if the request fails
func ZitiIdentities ¶
ZitiIdentities retrieves all Ziti identities and logs them. This function queries the identities endpoint and logs all found identities.
Parameters:
- urlSrc: The base URL of the Ziti controller
- token: The Ziti session token
The function:
- Makes a GET request to the identities endpoint with a large limit
- Decodes the response and logs each identity's ID and name
func ZitiServicePolicies ¶
ZitiServicePolicies retrieves all Ziti service policies. This function queries the service policies endpoint and logs the raw response.
Parameters:
- url: The base URL of the Ziti controller
- token: The Ziti session token
The function:
- Makes a GET request to the service-policies endpoint
- Logs the raw response body
func ZitiSetup ¶ added in v0.0.5
ZitiSetup initializes a Ziti network connection and returns an HTTP transport configured to route traffic through the Ziti overlay network. This function establishes the zero-trust networking foundation for secure service communication.
Initialization Process:
- Loads and parses the Ziti identity file containing cryptographic credentials
- Creates a Ziti context for network operations and policy enforcement
- Constructs an HTTP transport with custom dialer for Ziti routing
- Returns the transport ready for use with HTTP clients
Identity File Requirements:
The identity file must be a valid Ziti identity containing: - Cryptographic certificates for authentication - Network configuration and controller information - Service access policies and permissions - Enrollment and authentication tokens
Service Name Resolution:
The serviceName parameter specifies the Ziti service to connect to. This service must be: - Defined in the Ziti network configuration - Accessible according to current identity policies - Running and available on the Ziti overlay network
Parameters:
- identityFile: Filesystem path to the Ziti identity file (JSON format)
- serviceName: Name of the Ziti service to connect to
Returns:
- *http.Transport: HTTP transport configured for Ziti network routing
- error: Configuration parsing, context creation, or validation errors
Error Conditions:
- Identity file not found, corrupted, or invalid format
- Network connectivity issues to Ziti controllers
- Authentication failures with provided identity
- Service not found or access denied by policies
- Invalid service name or configuration parameters
HTTP Transport Configuration:
The returned transport replaces the standard TCP dialer with a Ziti-aware dialer that: - Establishes connections through the Ziti overlay network - Enforces identity-based access policies automatically - Provides end-to-end encryption for all communications - Handles service discovery and routing transparently
Usage with HTTP Clients:
The transport can be used with any standard HTTP client:
transport, err := ZitiSetup("/path/to/identity.json", "database-service")
if err != nil {
log.Fatal("Ziti setup failed:", err)
}
client := &http.Client{Transport: transport}
resp, err := client.Get("http://database-service/api/v1/data")
Network Invisibility:
Services accessed through Ziti are not visible on traditional networks. They exist only within the Ziti overlay, providing "dark" networking where services cannot be discovered or accessed without proper identity.
Policy Enforcement:
All connections are subject to real-time policy evaluation: - Identity verification for every connection attempt - Service access authorization based on current policies - Dynamic policy updates without service interruption - Automatic connection termination on policy revocation
Performance Considerations:
- Initial connection establishment may have higher latency
- Subsequent connections benefit from connection pooling
- Encryption overhead is minimal with modern hardware
- Network routing may add latency depending on overlay topology
Security Features:
- Mutual TLS authentication for all connections
- Certificate-based identity verification
- Automatic key rotation and certificate management
- Protection against man-in-the-middle attacks
- Network traffic analysis resistance
Production Deployment:
- Store identity files securely (encrypted storage, secret management)
- Implement proper certificate lifecycle management
- Monitor connection health and policy compliance
- Plan for identity rotation and revocation scenarios
- Configure appropriate timeouts and retry logic
Example Integration:
// Database connection through Ziti
transport, err := ZitiSetup("/etc/ziti/db-client.json", "postgres-db")
if err != nil {
return fmt.Errorf("failed to setup Ziti: %w", err)
}
// Use with database HTTP API
client := &http.Client{
Transport: transport,
Timeout: 30 * time.Second,
}
// All requests now go through Ziti zero-trust network
resp, err := client.Post("http://postgres-db/query", "application/json", queryBody)
Troubleshooting:
Common issues and solutions: - Identity file errors: Verify file format and certificate validity - Service not found: Check service configuration and network policies - Connection failures: Verify Ziti controller connectivity - Permission denied: Review identity access policies and service permissions
Types ¶
type AuthConfig ¶ added in v0.0.9
type AuthConfig struct {
Type string `json:"type"` // "api-key", "jwt", "basic", "none"
Header string `json:"header"` // Header name for auth token
Keys []string `json:"keys"` // Valid API keys or secrets
Bypass []string `json:"bypass"` // Paths that bypass authentication
JWT *JWTAuthConfig `json:"jwt"` // JWT-specific configuration
Ziti *ZitiConfig `json:"ziti"` // Global Ziti identity configuration
}
AuthConfig defines authentication requirements
type Backend ¶ added in v0.0.9
type Backend struct {
Config *BackendConfig
Client *http.Client
Transport *http.Transport
Healthy atomic.Bool
Connections atomic.Int64
LastCheck time.Time
FailCount int
SuccessCount int
// contains filtered or unexported fields
}
Backend represents a backend service with its state
type BackendConfig ¶ added in v0.0.9
type BackendConfig struct {
ZitiService string `json:"ziti_service"` // Ziti service name
Port int `json:"port"` // Backend service port (optional, default: 80 for http)
IdentityFile string `json:"identity_file"` // Path to Ziti identity file
Weight int `json:"weight"` // Weight for weighted load balancing (default: 1)
Priority int `json:"priority"` // Priority for failover (higher = preferred)
Timeout Duration `json:"timeout"` // Request timeout
MaxRetries int `json:"max_retries"` // Maximum retry attempts
}
BackendConfig represents a single backend service in the Ziti network
type CORSConfig ¶ added in v0.0.9
type CORSConfig struct {
Enabled bool `json:"enabled"` // Enable CORS
AllowedOrigins []string `json:"allowed_origins"` // Allowed origins
AllowedMethods []string `json:"allowed_methods"` // Allowed HTTP methods
AllowedHeaders []string `json:"allowed_headers"` // Allowed headers
ExposedHeaders []string `json:"exposed_headers"` // Exposed headers
AllowCredentials bool `json:"allow_credentials"` // Allow credentials
MaxAge int `json:"max_age"` // Preflight cache duration
}
CORSConfig defines CORS settings
type CircuitBreakerConfig ¶ added in v0.0.9
type CircuitBreakerConfig struct {
Enabled bool `json:"enabled"` // Enable circuit breaker
FailureThreshold int `json:"failure_threshold"` // Failures before opening
SuccessThreshold int `json:"success_threshold"` // Successes to close circuit
Timeout Duration `json:"timeout"` // Timeout before half-open
HalfOpenRequests int `json:"half_open_requests"` // Test requests in half-open state
}
CircuitBreakerConfig defines circuit breaker parameters
type ControllerVersionResponse ¶ added in v0.0.11
type ControllerVersionResponse struct {
Data struct {
Version string `json:"version"`
} `json:"data"`
}
ControllerVersionResponse represents the controller version API response
type Duration ¶ added in v0.0.9
Duration is a custom type for unmarshaling duration strings from JSON
func (*Duration) UnmarshalJSON ¶ added in v0.0.9
UnmarshalJSON implements json.Unmarshaler for Duration
type HealthCheckConfig ¶ added in v0.0.9
type HealthCheckConfig struct {
Enabled bool `json:"enabled"` // Enable health checks
Interval Duration `json:"interval"` // Check interval (e.g., "30s")
Timeout Duration `json:"timeout"` // Health check timeout
Path string `json:"path"` // Health check endpoint path
ExpectedStatus int `json:"expected_status"` // Expected HTTP status code
FailureCount int `json:"failure_count"` // Failed checks before marking unhealthy
SuccessCount int `json:"success_count"` // Successful checks before marking healthy
}
HealthCheckConfig defines health check parameters for backends
type HealthChecker ¶ added in v0.0.9
type HealthChecker struct {
// contains filtered or unexported fields
}
HealthChecker performs periodic health checks on backends
func NewHealthChecker ¶ added in v0.0.9
func NewHealthChecker(backends []*Backend, config *HealthCheckConfig) *HealthChecker
NewHealthChecker creates a new health checker
func (*HealthChecker) Start ¶ added in v0.0.9
func (hc *HealthChecker) Start()
Start starts the health checking routine
func (*HealthChecker) Stop ¶ added in v0.0.9
func (hc *HealthChecker) Stop()
Stop stops the health checking routine
type JWTAuthConfig ¶ added in v0.0.9
type JWTAuthConfig struct {
Secret string `json:"secret"` // JWT signing secret
PublicKeyFile string `json:"public_key_file"` // Path to public key for verification
Algorithm string `json:"algorithm"` // Signing algorithm (e.g., "HS256", "RS256")
Issuer string `json:"issuer"` // Expected issuer
Audience []string `json:"audience"` // Expected audience
RequiredClaims []string `json:"required_claims"` // Claims that must be present
}
JWTAuthConfig defines JWT authentication parameters
type LoadBalancer ¶ added in v0.0.9
type LoadBalancer struct {
// contains filtered or unexported fields
}
LoadBalancer manages backend selection and health
func NewLoadBalancer ¶ added in v0.0.9
func NewLoadBalancer(route *RouteConfig) (*LoadBalancer, error)
NewLoadBalancer creates a new load balancer for a route
func (*LoadBalancer) DecrementConnections ¶ added in v0.0.9
func (lb *LoadBalancer) DecrementConnections(backend *Backend)
DecrementConnections decrements active connection count
func (*LoadBalancer) GetHealthyBackendCount ¶ added in v0.0.9
func (lb *LoadBalancer) GetHealthyBackendCount() int
GetHealthyBackendCount returns the number of healthy backends
func (*LoadBalancer) IncrementConnections ¶ added in v0.0.9
func (lb *LoadBalancer) IncrementConnections(backend *Backend)
IncrementConnections increments active connection count
func (*LoadBalancer) RecordFailure ¶ added in v0.0.9
func (lb *LoadBalancer) RecordFailure(backend *Backend)
RecordFailure records a failed request to a backend
func (*LoadBalancer) RecordSuccess ¶ added in v0.0.9
func (lb *LoadBalancer) RecordSuccess(backend *Backend)
RecordSuccess records a successful request to a backend
func (*LoadBalancer) SelectBackend ¶ added in v0.0.9
func (lb *LoadBalancer) SelectBackend() *Backend
SelectBackend selects a backend based on the load balancing strategy
func (*LoadBalancer) Stop ¶ added in v0.0.9
func (lb *LoadBalancer) Stop()
Stop stops the load balancer and health checker
type LoadBalancingStrategy ¶ added in v0.0.9
type LoadBalancingStrategy string
LoadBalancingStrategy defines the load balancing algorithm
const ( RoundRobin LoadBalancingStrategy = "round-robin" WeightedRoundRobin LoadBalancingStrategy = "weighted-round-robin" LeastConnections LoadBalancingStrategy = "least-connections" )
type LoggingConfig ¶ added in v0.0.9
type LoggingConfig struct {
Enabled bool `json:"enabled"` // Enable request logging
Level string `json:"level"` // Log level (debug, info, warn, error)
Format string `json:"format"` // Log format (json, text)
IncludeBody bool `json:"include_body"` // Include request/response bodies
ExcludePaths []string `json:"exclude_paths"` // Paths to exclude from logging
}
LoggingConfig defines logging behavior
type Middleware ¶ added in v0.0.9
Middleware represents an HTTP middleware function
func AuthMiddleware ¶ added in v0.0.9
func AuthMiddleware(config *AuthConfig) Middleware
AuthMiddleware creates authentication middleware
func CORSMiddleware ¶ added in v0.0.9
func CORSMiddleware(config *CORSConfig) Middleware
CORSMiddleware creates CORS middleware
func LoggingMiddleware ¶ added in v0.0.9
func LoggingMiddleware(config *LoggingConfig) Middleware
LoggingMiddleware creates request logging middleware
func RecoveryMiddleware ¶ added in v0.0.9
func RecoveryMiddleware() Middleware
RecoveryMiddleware creates panic recovery middleware
func TimeoutMiddleware ¶ added in v0.0.9
func TimeoutMiddleware(timeout time.Duration) Middleware
TimeoutMiddleware creates request timeout middleware
type ProxyConfig ¶ added in v0.0.9
type ProxyConfig struct {
Server struct {
Host string `json:"host"` // Server bind address
Port int `json:"port"` // Server bind port
ReadTimeout Duration `json:"read_timeout"` // Read timeout
WriteTimeout Duration `json:"write_timeout"` // Write timeout
IdleTimeout Duration `json:"idle_timeout"` // Idle timeout
} `json:"server"`
Auth *AuthConfig `json:"auth"` // Global authentication config
CORS *CORSConfig `json:"cors"` // CORS configuration
Logging *LoggingConfig `json:"logging"` // Logging configuration
Routes []RouteConfig `json:"routes"` // Route configurations
Defaults struct {
Timeout Duration `json:"timeout"` // Default timeout
MaxRetries int `json:"max_retries"` // Default max retries
LoadBalancing LoadBalancingStrategy `json:"load_balancing"` // Default load balancing
HealthCheck *HealthCheckConfig `json:"health_check"` // Default health check
Retry *RetryConfig `json:"retry"` // Default retry config
CircuitBreaker *CircuitBreakerConfig `json:"circuit_breaker"` // Default circuit breaker
} `json:"defaults"`
}
ProxyConfig is the root configuration structure
func LoadProxyConfig ¶ added in v0.0.9
func LoadProxyConfig(configPath string) (*ProxyConfig, error)
LoadProxyConfig loads proxy configuration from a JSON file
type RetryConfig ¶ added in v0.0.9
type RetryConfig struct {
MaxAttempts int `json:"max_attempts"` // Maximum retry attempts
InitialInterval Duration `json:"initial_interval"` // Initial backoff interval
MaxInterval Duration `json:"max_interval"` // Maximum backoff interval
Multiplier float64 `json:"multiplier"` // Backoff multiplier
RetryableStatus []int `json:"retryable_status"` // HTTP status codes to retry
}
RetryConfig defines retry behavior for failed requests
type RouteConfig ¶ added in v0.0.9
type RouteConfig struct {
Path string `json:"path"` // Route path pattern
Methods []string `json:"methods"` // Allowed HTTP methods
Backends []BackendConfig `json:"backends"` // Backend services
LoadBalancing LoadBalancingStrategy `json:"load_balancing"` // Load balancing strategy
HealthCheck *HealthCheckConfig `json:"health_check"` // Health check configuration
Retry *RetryConfig `json:"retry"` // Retry configuration
CircuitBreaker *CircuitBreakerConfig `json:"circuit_breaker"` // Circuit breaker config
StripPrefix bool `json:"strip_prefix"` // Strip path prefix before forwarding
AddPrefix string `json:"add_prefix"` // Add prefix before forwarding
RewriteHost bool `json:"rewrite_host"` // Rewrite Host header
Timeout Duration `json:"timeout"` // Route-specific timeout
Auth *AuthConfig `json:"auth"` // Route-specific auth (overrides global)
}
RouteConfig defines a single proxy route
type RouteMatch ¶ added in v0.0.9
type RouteMatch struct {
Route *RouteConfig
Params map[string]string
}
RouteMatch represents a matched route with its configuration
type Router ¶ added in v0.0.9
type Router struct {
// contains filtered or unexported fields
}
Router handles route matching for the proxy
func NewRouter ¶ added in v0.0.9
func NewRouter(config *ProxyConfig) *Router
NewRouter creates a new router from proxy configuration
func (*Router) AddRoute ¶ added in v0.0.9
func (r *Router) AddRoute(route *RouteConfig)
AddRoute adds a route to the router
func (*Router) GetAllowedMethods ¶ added in v0.0.9
GetAllowedMethods returns all allowed methods for a path
type SSHTunnel ¶ added in v0.0.13
type SSHTunnel struct {
// contains filtered or unexported fields
}
SSHTunnel represents an SSH tunnel for port forwarding. It maintains the SSH connection and provides methods to create forwarded connections.
func NewSSHTunnel ¶ added in v0.0.13
func NewSSHTunnel(address string, username string, keyfile string, certfile string) (*SSHTunnel, error)
NewSSHTunnel creates a new SSH tunnel to a remote host. This establishes an SSH connection that can be used for port forwarding.
Parameters:
- address: The remote SSH server address in "host:port" format
- username: The username for SSH authentication
- keyfile: Path to the private key file
- certfile: Path to the certificate file (optional, can be empty)
Returns:
- *SSHTunnel: The established tunnel
- error: If connection fails
Example:
tunnel, err := NewSSHTunnel("192.168.1.100:22", "user", "/home/user/.ssh/id_rsa", "")
if err != nil {
log.Fatal(err)
}
defer tunnel.Close()
func (*SSHTunnel) Close ¶ added in v0.0.13
Close closes the SSH tunnel and all associated connections.
func (*SSHTunnel) Dial ¶ added in v0.0.13
Dial creates a connection through the SSH tunnel to a remote address. This is typically used to connect to services on the remote host.
Parameters:
- network: The network type ("tcp", "unix", etc.)
- address: The address to connect to on the remote host
Returns:
- net.Conn: The tunneled connection
- error: If the connection fails
Example:
conn, err := tunnel.Dial("unix", "/var/run/docker.sock")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
func (*SSHTunnel) ForwardConnection ¶ added in v0.0.13
ForwardConnection forwards data between a local connection and a remote address through the SSH tunnel. This is useful for setting up bidirectional port forwarding.
Parameters:
- local: The local connection
- remoteNetwork: The network type for the remote connection ("tcp", "unix", etc.)
- remoteAddress: The address on the remote host
Returns:
- error: If forwarding fails
type VersionInfo ¶ added in v0.0.11
type VersionInfo struct {
ControllerVersion string
SDKVersion string
Compatible bool
Warnings []string
Recommendations []string
}
VersionInfo holds controller and SDK version information
func CheckCompatibility ¶ added in v0.0.11
func CheckCompatibility(identityFile string) (*VersionInfo, error)
CheckCompatibility verifies OpenZiti controller and SDK version compatibility Returns version information, compatibility status, and recommendations
type WriteCounter ¶
type WriteCounter struct {
Total uint64
}
WriteCounter counts the number of bytes written to it and provides progress reporting functionality. It implements the io.Writer interface and is used to track download progress.
Fields:
- Total: The total number of bytes written so far
func (WriteCounter) PrintProgress ¶
func (wc WriteCounter) PrintProgress()
PrintProgress displays the current download progress. It shows the total bytes downloaded in a human-readable format and updates the display in place.
func (*WriteCounter) Write ¶
func (wc *WriteCounter) Write(p []byte) (int, error)
Write implements the io.Writer interface for WriteCounter. It updates the byte count and returns the number of bytes written.
Parameters:
- p: The byte slice being written
Returns:
- int: The number of bytes written (same as len(p))
- error: Always nil, as this is just a counter
type ZitiAPIBinding ¶
type ZitiAPIBinding struct {
Binding string `yaml:"binding"`
}
type ZitiBindPoint ¶
type ZitiConfig ¶ added in v0.0.12
type ZitiConfig struct {
IdentityFile string `json:"identity_file"` // Path to Ziti identity file
}
ZitiConfig defines global Ziti identity configuration
type ZitiControllerConfig ¶
type ZitiControllerConfig struct {
Version int `yaml:"v"`
DB string `yaml:"db"`
Identity ZitiIdentity `yaml:"identity"`
Ctrl ZitiCtrlListener `yaml:"ctrl"`
Edge ZitiEdgeEnroll `yaml:"edge"`
Web []ZitiWebListener `yaml:"web"`
}
type ZitiCtrlEndpoint ¶
type ZitiCtrlEndpoint struct {
Endpoint string `yaml:"endpoint"`
}
type ZitiCtrlListener ¶
type ZitiCtrlListener struct {
Listener string `yaml:"listener"`
}
type ZitiDialer ¶
type ZitiDialer struct {
Binding string `yaml:"binding"`
}
type ZitiEdgeCSR ¶
type ZitiEdgeCSR struct {
CSR ZitiCSR `yaml:"csr"`
}
type ZitiEdgeEnroll ¶
type ZitiEdgeEnroll struct {
Enrollment ZitiEnrollment `yaml:"enrollment"`
}
type ZitiEnrollment ¶
type ZitiEnrollment struct {
SigningCert ZitiSigningCert `yaml:"signingCert"`
}
type ZitiIdentity ¶
type ZitiLinkConfig ¶
type ZitiLinkConfig struct {
Listeners []ZitiLinkListener `yaml:"listeners"`
Dialers []ZitiDialer `yaml:"dialers"`
}
type ZitiLinkListener ¶
type ZitiListener ¶
type ZitiProxy ¶ added in v0.0.9
type ZitiProxy struct {
// contains filtered or unexported fields
}
ZitiProxy represents the main proxy server
func NewZitiProxy ¶ added in v0.0.9
NewZitiProxy creates a new Ziti proxy server from configuration
func (*ZitiProxy) Reload ¶ added in v0.0.9
Reload reloads the proxy configuration without stopping the server
type ZitiResult ¶
type ZitiResult struct {
Data ZitiToken `json:"data"` // The response data
}
ZitiResult represents a generic Ziti API response. Used to store the data portion of Ziti API responses.
type ZitiRouterConfig ¶
type ZitiRouterConfig struct {
Version int `yaml:"v"`
Identity ZitiIdentity `yaml:"identity"`
Ctrl ZitiCtrlEndpoint `yaml:"ctrl"`
Dialers []ZitiDialer `yaml:"dialers"`
Edge ZitiEdgeCSR `yaml:"edge"`
Link ZitiLinkConfig `yaml:"link"`
Listeners []ZitiListener `yaml:"listeners"`
}
type ZitiServiceConfig ¶
type ZitiServiceConfig struct {
ID string `json:"id"` // The service configuration ID
Name string `json:"name"` // The service configuration name
}
ZitiServiceConfig represents a Ziti service configuration. Used to store information about Ziti services.
type ZitiServiceConfigsResult ¶
type ZitiServiceConfigsResult struct {
Data []ZitiServiceConfig `json:"data"` // Array of service configurations
}
ZitiServiceConfigsResult represents a collection of Ziti service configurations. Used to store API responses containing multiple service configurations.
type ZitiSigningCert ¶
type ZitiToken ¶
type ZitiToken struct {
Token string `json:"token"` // The authentication token
ID string `json:"id"` // The token ID
}
ZitiToken represents a Ziti authentication token. Used to store authentication tokens returned by the Ziti controller.
type ZitiWebListener ¶
type ZitiWebListener struct {
Name string `yaml:"name"`
BindPoints []ZitiBindPoint `yaml:"bindPoints"`
APIs []ZitiAPIBinding `yaml:"apis"`
}