config

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package config handles configuration loading and validation for fred.

Configuration Sources

Configuration is loaded from multiple sources with the following precedence (highest to lowest):

  1. Environment variables (PROVIDER_ prefix)
  2. Configuration file (YAML)
  3. Default values

Environment Variables

All configuration options can be set via environment variables with the PROVIDER_ prefix. Nested options use underscores:

PROVIDER_CHAIN_ID=manifest-1
PROVIDER_GRPC_ENDPOINT=localhost:9090
PROVIDER_PROVIDER_UUID=01234567-89ab-cdef-0123-456789abcdef

Validation

The Validate method performs comprehensive validation:

  • Required fields must be non-empty
  • UUIDs must be valid format
  • URLs must be absolute http/https URLs
  • Durations must be positive
  • Backend names must be unique
  • Callback secret must be at least 32 characters
  • TLS cert and key must both be specified or neither
  • gas_adjustment must be in [1.0, 3.0]; max_gas_limit, if set, must be ≥ gas_limit

The daemon will fail to start with a clear error message if validation fails.

Production Mode

Setting production_mode=true tightens startup checks beyond basic validation:

  • token_tracker_db_path must be configured (replay protection cannot be silently disabled)
  • grpc_tls_skip_verify must be false when grpc_tls_enabled is true
  • callback_base_url and backend URLs are run through an SSRF check that rejects IP literals for loopback, link-local, and unspecified addresses as well as the hostname "localhost"

CORS

cors_origins defaults to ["*"]. This is safe because cookie-bearing credentials are disabled on the API — tenants must send their bearer token in the Authorization header, so there is no ambient-authority risk from allowing all origins. Set an explicit list to restrict, or set an empty list to disable CORS middleware entirely.

Parallel Signing

sub_signer_count > 0 enables authz-based parallel signing for lease acknowledgments. Each sub-signer holds a granted authz authorization and gets topped up from the primary key on its own schedule (see sub_signer_min_balance, sub_signer_top_up_amount, sub_signer_fund_check_interval).

Backend Configuration

Multiple backends can be configured with SKU-based routing:

backends:
  - name: docker-1
    url: "http://docker-backend:9000"
    timeout: 30s
    skus:
      - "a1b2c3d4-e5f6-7890-abcd-1234567890ab"
    default: true

At least one backend with default: true should be configured as a fallback.

Index

Constants

View Source
const (
	DefaultMaxRequestBodySize int64 = 1 << 20 // 1MB
)

Default values for configuration.

Variables

This section is empty.

Functions

func IsValidUUID

func IsValidUUID(s string) bool

IsValidUUID checks if a string is a valid UUID format (RFC 4122).

func ParseLogLevel

func ParseLogLevel(s string) (slog.Level, error)

ParseLogLevel converts a string log level to slog.Level.

Types

type BackendConfig

type BackendConfig struct {
	Name      string        `mapstructure:"name"`
	URL       string        `mapstructure:"url"`
	Timeout   time.Duration `mapstructure:"timeout"`
	SKUs      []string      `mapstructure:"skus"`
	IsDefault bool          `mapstructure:"default"`

	// TLS for the providerd -> backend hop (ENG-103). Empty fields fall back to
	// Go defaults (system root CAs, no client certificate).
	TLSCAFile         string `mapstructure:"tls_ca_file"`          // private CA that signed the backend's server cert
	TLSSkipVerify     bool   `mapstructure:"tls_skip_verify"`      // DEV ONLY; rejected when production_mode is true
	TLSClientCertFile string `mapstructure:"tls_client_cert_file"` // client cert for mTLS (set with key)
	TLSClientKeyFile  string `mapstructure:"tls_client_key_file"`  // client key for mTLS (set with cert)
}

BackendConfig configures a single provisioning backend.

type Config

type Config struct {
	ChainID              string        `mapstructure:"chain_id"`
	GRPCEndpoint         string        `mapstructure:"grpc_endpoint"`
	WebSocketURL         string        `mapstructure:"websocket_url"`
	ProviderUUID         string        `mapstructure:"provider_uuid"`
	ProviderAddress      string        `mapstructure:"provider_address"`
	KeyringBackend       string        `mapstructure:"keyring_backend"`
	KeyringDir           string        `mapstructure:"keyring_dir"`
	KeyName              string        `mapstructure:"key_name"`
	APIListenAddr        string        `mapstructure:"api_listen_addr"`
	WithdrawInterval     time.Duration `mapstructure:"withdraw_interval"`
	TLSCertFile          string        `mapstructure:"tls_cert_file"`
	TLSKeyFile           string        `mapstructure:"tls_key_file"`
	Bech32Prefix         string        `mapstructure:"bech32_prefix"`
	RateLimitRPS         float64       `mapstructure:"rate_limit_rps"`
	RateLimitBurst       int           `mapstructure:"rate_limit_burst"`
	TenantRateLimitRPS   float64       `mapstructure:"tenant_rate_limit_rps"`   // Per-tenant rate limit (requests per second)
	TenantRateLimitBurst int           `mapstructure:"tenant_rate_limit_burst"` // Per-tenant burst limit
	TrustedProxies       []string      `mapstructure:"trusted_proxies"`         // CIDR blocks of trusted proxies for X-Forwarded-For
	CORSOrigins          []string      `mapstructure:"cors_origins"`            // Allowed CORS origins for browser clients. Defaults to ["*"] (all origins).
	GRPCTLSEnabled       bool          `mapstructure:"grpc_tls_enabled"`
	GRPCTLSCAFile        string        `mapstructure:"grpc_tls_ca_file"`
	GRPCTLSSkipVerify    bool          `mapstructure:"grpc_tls_skip_verify"`
	// GasLimit is the Simulate-failure fallback gas ceiling. Steady-state gas is
	// simulated per tx; this value is used only when Simulate is unavailable.
	GasLimit uint64 `mapstructure:"gas_limit"`
	// MaxGasLimit (0 = no cap) is an absolute reject-cap: a per-tx simulated
	// estimate (gas_adjustment * GasUsed) exceeding it is refused, not submitted.
	// It also caps the gas on the OOG-retry / Simulate-failure fallback paths.
	MaxGasLimit uint64 `mapstructure:"max_gas_limit"`
	GasPrice    int64  `mapstructure:"gas_price"`
	// GasAdjustment is the multiplier applied to the simulated GasUsed (and, on
	// the Simulate-failure fallback path, to gas_limit) when signing a tx,
	// providing headroom above the estimate and reducing OOG retries.
	// Matches the Cosmos SDK CLI flag of the same name. Default: 1.2.
	// Must satisfy 1.0 <= GasAdjustment <= 3.0 (see Validate).
	GasAdjustment float64 `mapstructure:"gas_adjustment"`
	FeeDenom      string  `mapstructure:"fee_denom"`

	// Timeout configuration
	HTTPReadTimeout       time.Duration `mapstructure:"http_read_timeout"`
	HTTPWriteTimeout      time.Duration `mapstructure:"http_write_timeout"`
	HTTPIdleTimeout       time.Duration `mapstructure:"http_idle_timeout"`
	WebSocketPingInterval time.Duration `mapstructure:"websocket_ping_interval"`
	TxPollInterval        time.Duration `mapstructure:"tx_poll_interval"`
	TxTimeout             time.Duration `mapstructure:"tx_timeout"`

	// Query and pagination limits
	QueryPageLimit        int `mapstructure:"query_page_limit"`
	MaxWithdrawIterations int `mapstructure:"max_withdraw_iterations"`
	// WithdrawLimit is the number of active leases settled per provider-wide
	// MsgWithdraw page (sent as MsgWithdraw.Limit). The withdraw scheduler
	// paginates across pages regardless, so this only trades settlement-tx count
	// against per-tx gas. Must be 1..MaxBatchLeaseSize (the chain rejects more).
	WithdrawLimit int `mapstructure:"withdraw_limit"`

	// WebSocket reconnection backoff
	WebSocketReconnectInitial time.Duration `mapstructure:"websocket_reconnect_initial"`
	WebSocketReconnectMax     time.Duration `mapstructure:"websocket_reconnect_max"`

	// API limits
	MaxRequestBodySize int64 `mapstructure:"max_request_body_size"`

	// Credit check thresholds
	CreditCheckErrorThreshold int           `mapstructure:"credit_check_error_threshold"`
	CreditCheckRetryInterval  time.Duration `mapstructure:"credit_check_retry_interval"`
	CreditCheckInterval       time.Duration `mapstructure:"credit_check_interval"` // 0 = coupled to withdraw_interval (resolved by the scheduler).

	// Backend configuration
	Backends                    []BackendConfig `mapstructure:"backends"`
	CallbackBaseURL             string          `mapstructure:"callback_base_url"`
	CallbackSecret              Secret          `mapstructure:"callback_secret"`                // HMAC secret for callback authentication
	CallbackCanonicalPathPrefix string          `mapstructure:"callback_canonical_path_prefix"` // Path prefix prepended to inbound URIs before HMAC verification (set when fred is behind a path-stripping reverse proxy)

	// Parallel signing (authz sub-signers)
	SubSignerCount             int           `mapstructure:"sub_signer_count"`               // 0 = single signer (default)
	SubSignerMinBalance        string        `mapstructure:"sub_signer_min_balance"`         // Top-up when below this (default: "10000000umfx")
	SubSignerTopUpAmount       string        `mapstructure:"sub_signer_top_up_amount"`       // Amount per top-up (default: "50000000umfx")
	SubSignerFundCheckInterval time.Duration `mapstructure:"sub_signer_fund_check_interval"` // Balance check interval (default: 1h)

	// Reconciliation configuration
	ReconciliationInterval time.Duration `mapstructure:"reconciliation_interval"`

	// Production mode enforces security requirements at startup
	ProductionMode bool `mapstructure:"production_mode"`

	// Token replay protection
	TokenTrackerDBPath string `mapstructure:"token_tracker_db_path"`

	// Payload store configuration
	PayloadStoreDBPath string `mapstructure:"payload_store_db_path"`

	// Placement store configuration (enables round-robin backend routing)
	PlacementStoreDBPath string `mapstructure:"placement_store_db_path"`

	// Shutdown configuration
	ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"`

	// Logging
	LogLevel string `mapstructure:"log_level"`
}

Config holds all configuration for the provider daemon.

func Load

func Load(configPath string) (*Config, error)

Load reads configuration from a YAML file and/or environment variables. Environment variables use the PROVIDER_ prefix (e.g., PROVIDER_CHAIN_ID).

func (*Config) TLSEnabled

func (c *Config) TLSEnabled() bool

TLSEnabled returns true if TLS is configured.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that required configuration fields are set and valid.

type Secret

type Secret string

Secret is a string type that redacts its value in fmt, JSON, and slog output. Use string(s) to access the raw value when needed (e.g., for HMAC computation).

func (Secret) GoString

func (Secret) GoString() string

func (Secret) LogValue

func (Secret) LogValue() slog.Value

func (Secret) MarshalJSON

func (Secret) MarshalJSON() ([]byte, error)

func (Secret) MarshalText

func (Secret) MarshalText() ([]byte, error)

func (Secret) String

func (Secret) String() string

Jump to

Keyboard shortcuts

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