config

package
v0.10.0 Latest Latest
Warning

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

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

Documentation

Overview

Package config provides application configuration management.

Index

Constants

View Source
const (
	EnvProduction  = "production"
	EnvDevelopment = "development"
)

Deployment environment names returned by AppEnv.

View Source
const GeneratedTestDataPath = "schema/seed/generated_test_data.postgres.sql"

GeneratedTestDataPath is where `goatflow synthesize` writes the development test data. It is PostgreSQL SQL loaded by `make db-apply-test-data`, not a migration, so it must stay outside migrations/ (golang-migrate would treat it as a duplicate version).

View Source
const JWTPlaceholderSecret = "development-placeholder-not-for-production"

JWTPlaceholderSecret is a well-known value that must never sign tokens. Older config/default.yaml files shipped it as auth.jwt.secret.

View Source
const MinJWTSecretLength = 32

MinJWTSecretLength is the shortest JWT signing secret accepted in production.

Variables

This section is empty.

Functions

func AppEnv added in v0.10.0

func AppEnv(c *Config) string

AppEnv is the single source of the deployment environment. The APP_ENV environment variable wins over app.env from the config files (whose shipped default is "development"), so APP_ENV=production can never be downgraded by config. "prod" is an alias for "production". Empty means development.

func CustomerFEOnly added in v0.10.0

func CustomerFEOnly() bool

CustomerFEOnly reports whether this instance serves only the customer portal (CUSTOMER_FE_ONLY). Every reader of the flag must use this so that the guard, redirects and scheduler agree: "1", "true", "yes" and "on" (any case, surrounding spaces ignored) enable it; anything else disables it.

func InitializeDashboardManager

func InitializeDashboardManager(configPath string)

InitializeDashboardManager initializes the global dashboard manager.

func IsProductionEnv added in v0.10.0

func IsProductionEnv(c *Config) bool

IsProductionEnv reports whether AppEnv(c) is production.

func JWTSecret added in v0.10.0

func JWTSecret(c *Config) string

JWTSecret resolves the token signing secret: JWT_SECRET, then auth.jwt.secret (settable via GOATFLOW_AUTH_JWT_SECRET or config.yaml). Known placeholder values resolve to "" so callers treat them as unset.

func Load

func Load(configPath string) error

Load initializes the configuration with hot reload support.

func LoadFromFile

func LoadFromFile(configFile string) error

LoadFromFile loads configuration from a specific file (useful for testing).

func MustLoad

func MustLoad(configPath string)

MustLoad loads configuration and panics on error.

func ValidateSecrets

func ValidateSecrets(cfg *Config) error

ValidateSecrets fails in production when a required secret is missing, a published placeholder, or too weak. Call it at startup before serving.

Types

type AppConfig

type AppConfig struct {
	Name     string `mapstructure:"name"`
	Version  string `mapstructure:"version"`
	Env      string `mapstructure:"env"`
	Debug    bool   `mapstructure:"debug"`
	Timezone string `mapstructure:"timezone"`
	DemoMode bool   `mapstructure:"demo_mode"`
}

func (*AppConfig) IsDevelopment

func (c *AppConfig) IsDevelopment() bool

IsDevelopment returns true if running in development mode.

func (*AppConfig) IsProduction

func (c *AppConfig) IsProduction() bool

IsProduction returns true if running in production mode.

type AuthConfig

type AuthConfig struct {
	JWT struct {
		Secret          string        `mapstructure:"secret"`
		Issuer          string        `mapstructure:"issuer"`
		Audience        string        `mapstructure:"audience"`
		AccessTokenTTL  time.Duration `mapstructure:"access_token_ttl"`
		RefreshTokenTTL time.Duration `mapstructure:"refresh_token_ttl"`
	} `mapstructure:"jwt"`
	Session struct {
		CookieName         string `mapstructure:"cookie_name"`
		Secure             bool   `mapstructure:"secure"`
		HTTPOnly           bool   `mapstructure:"http_only"`
		SameSite           string `mapstructure:"same_site"`
		MaxAge             int    `mapstructure:"max_age"`
		SessionMaxTime     int    `mapstructure:"SessionMaxTime"`
		SessionMaxIdleTime int    `mapstructure:"SessionMaxIdleTime"`
	} `mapstructure:"session"`
	Password struct {
		MinLength        int  `mapstructure:"min_length"`
		RequireUppercase bool `mapstructure:"require_uppercase"`
		RequireLowercase bool `mapstructure:"require_lowercase"`
		RequireNumber    bool `mapstructure:"require_number"`
		RequireSpecial   bool `mapstructure:"require_special"`
		BcryptCost       int  `mapstructure:"bcrypt_cost"`
	} `mapstructure:"password"`
}

type CORSConfig

type CORSConfig struct {
	Enabled bool     `mapstructure:"enabled"`
	Origins []string `mapstructure:"origins"`
	Methods []string `mapstructure:"methods"`
	Headers []string `mapstructure:"headers"`
}

type ColorScheme

type ColorScheme struct {
	Background string `yaml:"bg"`
	Text       string `yaml:"text"`
	Button     string `yaml:"button"`
}

ColorScheme represents CSS classes for different color states.

type Config

type Config struct {
	App         AppConfig         `mapstructure:"app"`
	Server      ServerConfig      `mapstructure:"server"`
	Valkey      ValkeyConfig      `mapstructure:"valkey"`
	Auth        AuthConfig        `mapstructure:"auth"`
	Email       EmailConfig       `mapstructure:"email"`
	Storage     StorageConfig     `mapstructure:"storage"`
	Ticket      TicketConfig      `mapstructure:"ticket"`
	Features    FeaturesConfig    `mapstructure:"features"`
	Maintenance MaintenanceConfig `mapstructure:"maintenance"`
	Runner      RunnerConfig      `mapstructure:"runner"`
	Push        PushConfig        `mapstructure:"push"`
}

Config represents the application configuration. The database connection, logging and metrics are configured by environment variables (DB_*, LOG_*, METRICS_*), not by this file.

func Get

func Get() *Config

Get returns the current configuration (thread-safe).

type Dashboard

type Dashboard struct {
	Title        string        `yaml:"title"`
	Subtitle     string        `yaml:"subtitle"`
	Theme        string        `yaml:"theme"`
	Stats        []Stat        `yaml:"stats"`
	Tiles        []Tile        `yaml:"tiles"`
	QuickActions []QuickAction `yaml:"quick_actions"`
}

Dashboard represents the main dashboard configuration.

type DashboardConfig

type DashboardConfig struct {
	APIVersion string `yaml:"apiVersion"`
	Kind       string `yaml:"kind"`
	Metadata   struct {
		Name        string `yaml:"name"`
		Version     string `yaml:"version"`
		Created     string `yaml:"created"`
		Description string `yaml:"description"`
	} `yaml:"metadata"`
	Spec DashboardSpec `yaml:"spec"`
}

DashboardConfig represents the complete YAML configuration for a dashboard.

type DashboardManager

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

DashboardManager manages dashboard configurations.

var DefaultDashboardManager *DashboardManager

Global dashboard manager instance.

func NewDashboardManager

func NewDashboardManager(configPath string) *DashboardManager

NewDashboardManager creates a new dashboard manager.

func (*DashboardManager) GetColorScheme

func (dm *DashboardManager) GetColorScheme(config *DashboardConfig, color string) ColorScheme

GetColorScheme returns the CSS classes for a color.

func (*DashboardManager) GetIconPath

func (dm *DashboardManager) GetIconPath(config *DashboardConfig, icon string) string

GetIconPath returns the SVG path for an icon.

func (*DashboardManager) GetTilesByCategory

func (dm *DashboardManager) GetTilesByCategory(config *DashboardConfig) map[string][]Tile

GetTilesByCategory returns tiles grouped by category.

func (*DashboardManager) LoadDashboard

func (dm *DashboardManager) LoadDashboard(name string) (*DashboardConfig, error)

LoadDashboard loads a dashboard configuration from YAML.

func (*DashboardManager) ReloadDashboard

func (dm *DashboardManager) ReloadDashboard(name string) error

ReloadDashboard forces a reload of a dashboard configuration.

type DashboardSpec

type DashboardSpec struct {
	Dashboard Dashboard              `yaml:"dashboard"`
	Colors    map[string]ColorScheme `yaml:"colors"`
	Icons     map[string]string      `yaml:"icons"`
}

DashboardSpec contains the actual dashboard configuration.

type EmailConfig

type EmailConfig struct {
	Enabled  bool   `mapstructure:"enabled"`
	From     string `mapstructure:"from"`
	FromName string `mapstructure:"from_name"`
	SMTP     struct {
		Host       string `mapstructure:"host"`
		Port       int    `mapstructure:"port"`
		User       string `mapstructure:"user"`
		Password   string `mapstructure:"password"`
		AuthType   string `mapstructure:"auth_type"`
		TLS        bool   `mapstructure:"tls"`
		TLSMode    string `mapstructure:"tls_mode"`
		SkipVerify bool   `mapstructure:"skip_verify"`
	} `mapstructure:"smtp"`
	Templates struct {
		Path string `mapstructure:"path"`
	} `mapstructure:"templates"`
	Queue struct {
		Workers       int           `mapstructure:"workers"`
		BufferSize    int           `mapstructure:"buffer_size"`
		RetryAttempts int           `mapstructure:"retry_attempts"`
		RetryDelay    time.Duration `mapstructure:"retry_delay"`
	} `mapstructure:"queue"`
	Inbound EmailInboundConfig `mapstructure:"inbound"`
}

func (*EmailConfig) EffectiveTLSMode

func (c *EmailConfig) EffectiveTLSMode() string

EffectiveTLSMode normalizes the TLS mode for outbound SMTP connections. Supported values: "none", "starttls", "smtps" (implicit TLS). If TLSMode is empty we fall back to the legacy TLS boolean flag.

type EmailInboundConfig

type EmailInboundConfig struct {
	Enabled        bool          `mapstructure:"enabled"`
	PollInterval   time.Duration `mapstructure:"poll_interval"`
	WorkerCount    int           `mapstructure:"worker_count"`
	MaxAccounts    int           `mapstructure:"max_accounts"`
	TrustedHeaders []string      `mapstructure:"trusted_headers"`
}

type EnvVariable

type EnvVariable struct {
	Key         string
	Value       string
	Type        string
	Generated   bool
	Description string
}

type FeaturesConfig

type FeaturesConfig struct {
	Registration bool `mapstructure:"registration"`
	LostPassword bool `mapstructure:"lost_password"`
}

FeaturesConfig holds the feature switches GoatFlow reads.

type MaintenanceConfig

type MaintenanceConfig struct {
	Mode                      bool     `mapstructure:"mode"`
	Message                   string   `mapstructure:"message"`
	AllowedIPs                []string `mapstructure:"allowed_ips"`
	TimeNotifyUpcomingMinutes int      `mapstructure:"time_notify_upcoming_minutes"` // Minutes before maintenance to show notification
	DefaultNotifyMessage      string   `mapstructure:"default_notify_message"`       // Default notification message
	DefaultLoginMessage       string   `mapstructure:"default_login_message"`        // Default login page message
}

type PushConfig

type PushConfig struct {
	Enabled         bool   `mapstructure:"enabled"`
	VAPIDPublicKey  string `mapstructure:"vapid_public_key"`
	VAPIDPrivateKey string `mapstructure:"vapid_private_key"`
	VAPIDContact    string `mapstructure:"vapid_contact"`
}

type QuickAction

type QuickAction struct {
	Name     string `yaml:"name"`
	Action   string `yaml:"action,omitempty"`
	URL      string `yaml:"url,omitempty"`
	Endpoint string `yaml:"endpoint,omitempty"`
	Icon     string `yaml:"icon"`
	Color    string `yaml:"color"`
	Confirm  string `yaml:"confirm,omitempty"`
}

QuickAction represents a quick action button.

type RunnerConfig

type RunnerConfig struct {
	SessionCleanup struct {
		Interval time.Duration `mapstructure:"interval"`
	} `mapstructure:"session_cleanup"`
}

RunnerConfig contains configuration for background task runner.

type SecretType

type SecretType string
const (
	SecretTypeHex      SecretType = "hex"
	SecretTypeAlphaNum SecretType = "alphanum"
	SecretTypeMixed    SecretType = "mixed"
	SecretTypeAPIKey   SecretType = "apikey"
	SecretTypePassword SecretType = "password"
)

type SecretValidator

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

func NewSecretValidator

func NewSecretValidator(cfg *Config) *SecretValidator

func (*SecretValidator) Validate

func (v *SecretValidator) Validate() error

Validate checks secrets. In production a missing, placeholder or weak secret is an error; elsewhere it is logged as a warning.

type ServerConfig

type ServerConfig struct {
	Host            string        `mapstructure:"host"`
	Port            int           `mapstructure:"port"`
	ReadTimeout     time.Duration `mapstructure:"read_timeout"`
	WriteTimeout    time.Duration `mapstructure:"write_timeout"`
	ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"`
	CORS            CORSConfig    `mapstructure:"cors"`
	Swagger         SwaggerConfig `mapstructure:"swagger"`
}

func (*ServerConfig) GetServerAddr

func (c *ServerConfig) GetServerAddr() string

GetServerAddr returns the server listen address.

type Stat

type Stat struct {
	Name    string `yaml:"name"`
	Query   string `yaml:"query,omitempty"`
	Command string `yaml:"command,omitempty"`
	Parser  string `yaml:"parser,omitempty"`
	Suffix  string `yaml:"suffix,omitempty"`
	Icon    string `yaml:"icon"`
	Color   string `yaml:"color"`
}

Stat represents a dashboard statistic.

type StorageConfig

type StorageConfig struct {
	// Type selects the article storage backend: "db" (ArticleStorageDB,
	// default) or "fs" (ArticleStorageFS). The STORAGE_TYPE environment
	// variable overrides it.
	Type  string `mapstructure:"type"`
	Local struct {
		// Path is the storage root (STORAGE_PATH overrides it); the fs
		// backend keeps articles in <Path>/var/article in the OTRS layout.
		Path string `mapstructure:"path"`
	} `mapstructure:"local"`
	Attachments struct {
		MaxSize      int64    `mapstructure:"max_size"`
		AllowedTypes []string `mapstructure:"allowed_types"`
	} `mapstructure:"attachments"`
}

StorageConfig configures article attachment storage (internal/storage).

type SwaggerConfig

type SwaggerConfig struct {
	Enabled bool `mapstructure:"enabled"` // Whether to serve Swagger UI at /swagger/
	Public  bool `mapstructure:"public"`  // If true, no auth required; if false, requires login
}

SwaggerConfig controls API documentation exposure.

type Synthesizer

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

func NewSynthesizer

func NewSynthesizer(outputPath string) *Synthesizer

func (*Synthesizer) GenerateSecret

func (s *Synthesizer) GenerateSecret(secretType SecretType, length int, keyType string, envPrefix string) (string, error)

func (*Synthesizer) GetGeneratedCount

func (s *Synthesizer) GetGeneratedCount() int

func (*Synthesizer) SynthesizeEnv

func (s *Synthesizer) SynthesizeEnv(rotateOnly bool) error

func (*Synthesizer) SynthesizeTestData

func (s *Synthesizer) SynthesizeTestData() error

SynthesizeTestData generates the development test data SQL (GeneratedTestDataPath).

type TestCredential

type TestCredential struct {
	Username  string
	Password  string
	Email     string
	FirstName string
	LastName  string
	Role      string
	Type      string // "agent" or "customer"
}

TestCredential represents a test user credential.

type TestDataGenerator

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

TestDataGenerator generates test data SQL.

func NewTestDataGenerator

func NewTestDataGenerator(synthesizer *Synthesizer) *TestDataGenerator

NewTestDataGenerator creates a new test data generator.

func (*TestDataGenerator) Generate

func (g *TestDataGenerator) Generate() error

Generate creates test data with secure passwords.

type TicketConfig

type TicketConfig struct {
	IDPrefix        string `mapstructure:"id_prefix"`
	IDFormat        string `mapstructure:"id_format"`
	DefaultPriority string `mapstructure:"default_priority"`
	DefaultStatus   string `mapstructure:"default_status"`
	AutoAssign      bool   `mapstructure:"auto_assign"`
	Service         struct {
		DefaultUnknownCustomer bool `mapstructure:"default_unknown_customer"`
	} `mapstructure:"service"`
	SLA struct {
		Enabled       bool          `mapstructure:"enabled"`
		FirstResponse time.Duration `mapstructure:"first_response"`
		Resolution    time.Duration `mapstructure:"resolution"`
	} `mapstructure:"sla"`
	Notifications struct {
		CustomerCreate bool `mapstructure:"customer_create"`
		CustomerUpdate bool `mapstructure:"customer_update"`
		AgentAssign    bool `mapstructure:"agent_assign"`
		AgentMention   bool `mapstructure:"agent_mention"`
	} `mapstructure:"notifications"`
	Frontend struct {
		AgentTicketNote struct {
			RequiredTimeUnits bool `mapstructure:"required_time_units"`
		} `mapstructure:"agent_ticket_note"`
	} `mapstructure:"frontend"`
	BulkActions struct {
		MaxSelectAll int `mapstructure:"max_select_all"`
	} `mapstructure:"bulk_actions"`
}

type Tile

type Tile struct {
	Name        string `yaml:"name"`
	Description string `yaml:"description"`
	URL         string `yaml:"url"`
	Icon        string `yaml:"icon"`
	Color       string `yaml:"color"`
	Category    string `yaml:"category"`
	Featured    bool   `yaml:"featured,omitempty"`
}

Tile represents a dashboard tile/tool.

type ValkeyConfig

type ValkeyConfig struct {
	Host         string `mapstructure:"host"`
	Port         int    `mapstructure:"port"`
	Password     string `mapstructure:"password"`
	DB           int    `mapstructure:"db"`
	MaxRetries   int    `mapstructure:"max_retries"`
	PoolSize     int    `mapstructure:"pool_size"`
	MinIdleConns int    `mapstructure:"min_idle_conns"`
	Session      struct {
		Prefix string        `mapstructure:"prefix"`
		TTL    time.Duration `mapstructure:"ttl"`
	} `mapstructure:"session"`
	Cache struct {
		Prefix string        `mapstructure:"prefix"`
		TTL    time.Duration `mapstructure:"ttl"`
	} `mapstructure:"cache"`
}

func (*ValkeyConfig) GetValkeyAddr

func (c *ValkeyConfig) GetValkeyAddr() string

GetValkeyAddr returns the Valkey server address.

Jump to

Keyboard shortcuts

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