Files
Veyra/internal/config/config.go
T

130 lines
5.1 KiB
Go

// Package config loads and validates application configuration without logging secrets.
package config
import (
"bufio"
"fmt"
"git.sundynix.cn/Blizzard/Veyra/internal/logging"
"net"
"net/url"
"os"
"strconv"
"strings"
)
type Config struct {
PythonExecutable string
PublicOrigin string
Logging logging.Options
Environment, HTTPAddr string
PGHost, PGPort, PGDatabase, PGUser, PGPassword, PGSSLMode, PGAdminDatabase string
RedisAddr, RedisUsername, RedisPassword string
SecretEncryptionKey string
RedisDB int
}
// LoadEnvFile reads literal KEY=VALUE entries. Existing environment values win.
// It never evaluates shell expressions or prints values.
func LoadEnvFile(path string) error {
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("open configuration file: %w", err)
}
defer f.Close()
s := bufio.NewScanner(f)
for line := 1; s.Scan(); line++ {
v := strings.TrimSpace(s.Text())
if v == "" || strings.HasPrefix(v, "#") {
continue
}
key, value, ok := strings.Cut(v, "=")
key = strings.TrimSpace(key)
if !ok || key == "" {
return fmt.Errorf("invalid configuration at line %d", line)
}
for i, r := range key {
if !(r == '_' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || i > 0 && r >= '0' && r <= '9') {
return fmt.Errorf("invalid key at line %d", line)
}
}
value = strings.TrimSpace(value)
if len(value) >= 2 && (value[0] == '\'' && value[len(value)-1] == '\'' || value[0] == '"' && value[len(value)-1] == '"') {
value = value[1 : len(value)-1]
}
if _, exists := os.LookupEnv(key); !exists {
if err := os.Setenv(key, value); err != nil {
return fmt.Errorf("set configuration at line %d: %w", line, err)
}
}
}
return s.Err()
}
func Load() (Config, error) {
c := Config{Environment: env("APP_ENV", "local"), HTTPAddr: env("HTTP_ADDR", "127.0.0.1:8080"), PGHost: env("PGHOST", "192.168.100.127"), PGPort: env("PGPORT", "5432"), PGDatabase: env("PGDATABASE", "veyra"), PGUser: os.Getenv("PGUSER"), PGPassword: os.Getenv("PGPASSWORD"), PGSSLMode: env("PGSSLMODE", "disable"), PGAdminDatabase: env("PGADMIN_DATABASE", "postgres"), RedisAddr: env("REDIS_ADDR", "192.168.100.127:6379"), RedisUsername: os.Getenv("REDIS_USERNAME"), RedisPassword: os.Getenv("REDIS_PASSWORD")}
c.PythonExecutable = env("PYTHON_EXECUTABLE", "python3")
c.PublicOrigin = os.Getenv("PUBLIC_ORIGIN")
if c.PublicOrigin != "" {
origin, err := url.Parse(c.PublicOrigin)
if err != nil || (origin.Scheme != "http" && origin.Scheme != "https") || origin.Hostname() == "" || origin.User != nil || origin.Path != "" || origin.RawQuery != "" || origin.Fragment != "" || origin.Opaque != "" || origin.Scheme+"://"+origin.Host != c.PublicOrigin {
return Config{}, fmt.Errorf("PUBLIC_ORIGIN must be an http or https origin without a path")
}
}
c.Logging = logging.Options{Directory: env("LOG_DIR", "logs"), Level: env("LOG_LEVEL", "info"), MaxSizeMB: 50, MaxBackups: 10, MaxAgeDays: 14}
for key, dest := range map[string]*int{"LOG_MAX_SIZE_MB": &c.Logging.MaxSizeMB, "LOG_MAX_BACKUPS": &c.Logging.MaxBackups, "LOG_MAX_AGE_DAYS": &c.Logging.MaxAgeDays} {
if value := os.Getenv(key); value != "" {
n, err := strconv.Atoi(value)
if err != nil || n < 1 {
return Config{}, fmt.Errorf("%s must be a positive integer", key)
}
*dest = n
}
}
c.SecretEncryptionKey = os.Getenv("SECRET_ENCRYPTION_KEY")
var err error
c.RedisDB, err = strconv.Atoi(env("REDIS_DB", "0"))
if err != nil || c.RedisDB < 0 {
return Config{}, fmt.Errorf("REDIS_DB must be a nonnegative integer")
}
port, err := strconv.Atoi(c.PGPort)
if err != nil || port < 1 || port > 65535 {
return Config{}, fmt.Errorf("PGPORT must be a valid port")
}
if _, _, err := net.SplitHostPort(c.HTTPAddr); err != nil {
return Config{}, fmt.Errorf("invalid HTTP_ADDR")
}
if _, _, err := net.SplitHostPort(c.RedisAddr); err != nil {
return Config{}, fmt.Errorf("invalid REDIS_ADDR")
}
switch c.PGSSLMode {
case "disable", "allow", "prefer", "require", "verify-ca", "verify-full":
default:
return Config{}, fmt.Errorf("invalid PGSSLMODE")
}
return c, nil
}
func (c Config) ValidateDatabase() error {
if c.PGUser == "" {
return fmt.Errorf("PGUSER is required; configure the local configs/.env file")
}
if c.PGHost == "" || c.PGDatabase == "" || c.PGAdminDatabase == "" {
return fmt.Errorf("database host and names are required")
}
return nil
}
func (c Config) DatabaseURL(database string) string {
u := url.URL{Scheme: "postgres", Host: net.JoinHostPort(c.PGHost, c.PGPort), User: url.UserPassword(c.PGUser, c.PGPassword), Path: "/" + database}
q := url.Values{"sslmode": {c.PGSSLMode}, "connect_timeout": {"5"}}
u.RawQuery = q.Encode()
return u.String()
}
func env(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}