Files
certman/app/config.go
Steven Tracey 0a78b70821
All checks were successful
Build (artifact) / build (push) Successful in 27s
Refactored config system again
2026-06-30 16:48:05 -04:00

391 lines
9.2 KiB
Go

package app
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"sync"
"git.nevets.tech/Steven/certman/common"
"github.com/google/uuid"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/viper"
)
var (
ErrBlankConfigEntry = errors.New("blank config entry")
ErrConfigNotFound = errors.New("config file not found")
)
// ---------------------------------------------------------------------------
// Generic domain config store
// ---------------------------------------------------------------------------
type DomainConfigStore[T any] struct {
mu sync.RWMutex
configs map[string]*T
}
func NewDomainConfigStore[T any]() *DomainConfigStore[T] {
return &DomainConfigStore[T]{
configs: make(map[string]*T),
}
}
func (s *DomainConfigStore[T]) Get(domain string) (*T, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
v, ok := s.configs[domain]
return v, ok
}
func (s *DomainConfigStore[T]) Set(domain string, v *T) {
s.mu.Lock()
defer s.mu.Unlock()
s.configs[domain] = v
}
// Swap atomically replaces the entire config map (used during reload).
func (s *DomainConfigStore[T]) Swap(newConfigs map[string]*T) {
s.mu.Lock()
defer s.mu.Unlock()
s.configs = newConfigs
}
// Snapshot returns a shallow copy safe to iterate without holding the lock.
func (s *DomainConfigStore[T]) Snapshot() map[string]*T {
s.mu.RLock()
defer s.mu.RUnlock()
snap := make(map[string]*T, len(s.configs))
for k, v := range s.configs {
snap[k] = v
}
return snap
}
// ---------------------------------------------------------------------------
// Global state
// ---------------------------------------------------------------------------
var (
config *common.AppConfig
configMu sync.RWMutex
serverDomainStore = NewDomainConfigStore[common.ServerDomainConfig]()
clientDomainStore = NewDomainConfigStore[common.ClientDomainConfig]()
)
func Config() *common.AppConfig {
configMu.RLock()
defer configMu.RUnlock()
return config
}
func ServerDomainStore() *DomainConfigStore[common.ServerDomainConfig] {
return serverDomainStore
}
func ClientDomainStore() *DomainConfigStore[common.ClientDomainConfig] {
return clientDomainStore
}
// ---------------------------------------------------------------------------
// Loading
// ---------------------------------------------------------------------------
// LoadConfig reads the main certman.conf into config.
func LoadConfig() error {
vConfig := viper.New()
vConfig.SetConfigFile("/etc/certman/certman.conf")
vConfig.SetConfigType("toml")
if err := vConfig.ReadInConfig(); err != nil {
return err
}
if vConfig.GetString("App.mode") == "server" {
vConfig.SetConfigType("toml")
vConfig.SetConfigFile("/etc/certman/server.conf")
if err := vConfig.MergeInConfig(); err != nil {
return err
}
}
if err := vConfig.Unmarshal(&config); err != nil {
return err
}
return nil
}
// loadDomainConfigs walks /etc/certman/domains and unmarshals every .conf file
// into T, keyed by domain.domain_name.
func loadDomainConfigs[T any]() (map[string]*T, error) {
dir := "/etc/certman/domains/"
entries, err := os.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("reading domain config dir: %w", err)
}
out := make(map[string]*T)
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".conf" {
continue
}
path := filepath.Join(dir, entry.Name())
v := viper.New()
v.SetConfigFile(path)
v.SetConfigType("toml")
if err := v.ReadInConfig(); err != nil {
return nil, fmt.Errorf("loading %s: %w", path, err)
}
domain := v.GetString("domain.domain_name")
if domain == "" {
return nil, fmt.Errorf("%s: missing domain.domain_name", path)
}
if _, exists := out[domain]; exists {
fmt.Printf("Duplicate domain in %s, skipping...\n", path)
continue
}
cfg := new(T)
if err = v.Unmarshal(cfg); err != nil {
return nil, fmt.Errorf("unmarshaling %s: %w", path, err)
}
out[domain] = cfg
}
return out, nil
}
// LoadServerDomainConfigs reads every .conf file in the domains directory into
// the server-typed store.
func LoadServerDomainConfigs() error {
configs, err := loadDomainConfigs[common.ServerDomainConfig]()
if err != nil {
return err
}
serverDomainStore.Swap(configs)
return nil
}
// LoadClientDomainConfigs reads every .conf file in the domains directory into
// the client-typed store.
func LoadClientDomainConfigs() error {
configs, err := loadDomainConfigs[common.ClientDomainConfig]()
if err != nil {
return err
}
clientDomainStore.Swap(configs)
return nil
}
// ---------------------------------------------------------------------------
// Saving
// ---------------------------------------------------------------------------
func WriteConfig(filePath string, config *common.AppConfig) error {
buf, err := toml.Marshal(&config)
if err != nil {
return fmt.Errorf("marshaling config: %w", err)
}
if err = os.WriteFile(filePath, buf, 0640); err != nil {
return fmt.Errorf("write config file: %w", err)
}
return nil
}
func writeDomainConfigFile(domainName string, v any) error {
buf, err := toml.Marshal(v)
if err != nil {
return fmt.Errorf("marshaling domain config: %w", err)
}
configPath := filepath.Join("/etc/certman/domains", domainName+".conf")
if err = os.WriteFile(configPath, buf, 0640); err != nil {
return fmt.Errorf("write config file: %w", err)
}
return nil
}
func WriteServerDomainConfig(config *common.ServerDomainConfig) error {
return writeDomainConfigFile(config.Domain.DomainName, config)
}
func WriteClientDomainConfig(config *common.ClientDomainConfig) error {
return writeDomainConfigFile(config.Domain.DomainName, config)
}
// SaveServerDomainConfigs writes every loaded server domain config back to disk.
func SaveServerDomainConfigs() error {
for _, v := range serverDomainStore.Snapshot() {
if err := WriteServerDomainConfig(v); err != nil {
return err
}
}
return nil
}
// SaveClientDomainConfigs writes every loaded client domain config back to disk.
func SaveClientDomainConfigs() error {
for _, v := range clientDomainStore.Snapshot() {
if err := WriteClientDomainConfig(v); err != nil {
return err
}
}
return nil
}
// ---------------------------------------------------------------------------
// Directory bootstrapping
// ---------------------------------------------------------------------------
func MakeDirs() {
dirs := []struct {
path string
perm os.FileMode
}{
{"/etc/certman", 0755},
{"/etc/certman/domains", 0755},
{"/var/local/certman", 0750},
}
for _, d := range dirs {
if err := os.MkdirAll(d.path, d.perm); err != nil {
log.Fatalf("Unable to create directory %s: %v", d.path, err)
}
}
}
func CreateConfig(mode string) {
content := strings.NewReplacer(
"{mode}", mode,
).Replace(defaultConfig)
createFile("/etc/certman/certman.conf", 0640, []byte(content))
switch mode {
case "server":
content = strings.NewReplacer(
"{uuid}", uuid.New().String(),
).Replace(defaultServerConfig)
createFile("/etc/certman/server.conf", 640, []byte(content))
}
}
func CreateDomainConfig(domain string) error {
key, err := common.GenerateKey()
if err != nil {
return fmt.Errorf("unable to generate key: %v", err)
}
localConfig := Config()
var content string
switch localConfig.App.Mode {
case "server":
content = strings.NewReplacer(
"{domain}", domain,
"{key}", key,
).Replace(defaultServerDomainConfig)
case "client":
content = strings.NewReplacer(
"{domain}", domain,
"{key}", key,
).Replace(defaultClientDomainConfig)
default:
return fmt.Errorf("unknown certman mode: %v", localConfig.App.Mode)
}
path := filepath.Join("/etc/certman/domains", domain+".conf")
createFile(path, 0640, []byte(content))
return nil
}
func CreateDomainCertsDir(domain string, dir string, dirOverride bool) {
var target string
if dirOverride {
target = filepath.Join(dir, domain)
} else {
target = filepath.Join("/var/local/certman/certificates", domain)
}
if err := os.MkdirAll(target, 0750); err != nil {
if os.IsExist(err) {
fmt.Println("Directory already exists...")
return
}
log.Fatalf("Error creating certificate directory for %s: %v", domain, err)
}
}
const defaultConfig = `[App]
mode = '{mode}'
tick_rate = 2
[Git]
host = 'gitea'
server = 'https://gitea.instance.com'
username = 'User'
api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
org_name = 'org'
[Certificates]
data_root = '/var/local/certman'
`
const defaultServerConfig = `[App]
uuid = '{uuid}'
[Certificates]
email = 'User@example.com'
ca_dir_url = 'https://acme-v02.api.letsencrypt.org/directory'
[Cloudflare]
cf_email = 'email@example.com'
cf_api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'`
const defaultServerDomainConfig = `[Certificates]
data_root = ''
expiry = 90
request_method = 'dns-01'
renew_period = 30
subdomains = []
crypto_key = '{key}'
[Domain]
domain_name = '{domain}'
enabled = true
dns_server = 'default'
[Repo]
repo_suffix = '-certificates'
[Internal]
last_issued = 0
repo_exists = false
status = 'clean'
`
const defaultClientDomainConfig = `[Certificates]
data_root = ''
cert_symlinks = []
key_symlinks = []
crypto_key = '{key}'
[Domain]
domain_name = '{domain}'
enabled = true
[Hooks.PostPull]
command = []
cwd = "/dev/null"
timeout_seconds = 30
env = { "FOO" = "bar" }
[Repo]
repo_suffix = '-certificates'
`