@@ -0,0 +1,105 @@
|
||||
// Package config loads and validates application configuration without logging secrets.
|
||||
package config
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Environment, HTTPAddr string
|
||||
PGHost, PGPort, PGDatabase, PGUser, PGPassword, PGSSLMode, PGAdminDatabase string
|
||||
RedisAddr, RedisUsername, RedisPassword 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")}
|
||||
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 .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
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDatabaseURLPreservesCredentials(t *testing.T) {
|
||||
c := Config{PGHost: "192.168.100.127", PGPort: "5432", PGUser: "user@name", PGPassword: "p@ss:/?#&", PGSSLMode: "require"}
|
||||
u, err := url.Parse(c.DatabaseURL("veyra"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
password, _ := u.User.Password()
|
||||
if password != c.PGPassword || u.User.Username() != c.PGUser || u.Path != "/veyra" || u.Query().Get("sslmode") != "require" {
|
||||
t.Fatal("connection URL changed configuration values")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectInvalidRedisDB(t *testing.T) {
|
||||
t.Setenv("REDIS_DB", "-1")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("negative database must be rejected")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user