1package config
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"os"
  7	"path/filepath"
  8	"strings"
  9
 10	"github.com/caarlos0/env/v7"
 11	"github.com/charmbracelet/log"
 12	"github.com/charmbracelet/soft-serve/server/backend"
 13	"gopkg.in/yaml.v3"
 14)
 15
 16// SSHConfig is the configuration for the SSH server.
 17type SSHConfig struct {
 18	// ListenAddr is the address on which the SSH server will listen.
 19	ListenAddr string `env:"LISTEN_ADDR" yaml:"listen_addr"`
 20
 21	// PublicURL is the public URL of the SSH server.
 22	PublicURL string `env:"PUBLIC_URL" yaml:"public_url"`
 23
 24	// KeyPath is the path to the SSH server's private key.
 25	KeyPath string `env:"KEY_PATH" yaml:"key_path"`
 26
 27	// ClientKeyPath is the path to the SSH server's client private key.
 28	ClientKeyPath string `env:"CLIENT_KEY_PATH" yaml:"client_key_path"`
 29
 30	// InternalKeyPath is the path to the SSH server's internal private key.
 31	InternalKeyPath string `env:"INTERNAL_KEY_PATH" yaml:"internal_key_path"`
 32
 33	// MaxTimeout is the maximum number of seconds a connection can take.
 34	MaxTimeout int `env:"MAX_TIMEOUT" yaml:"max_timeout`
 35
 36	// IdleTimeout is the number of seconds a connection can be idle before it is closed.
 37	IdleTimeout int `env:"IDLE_TIMEOUT" yaml:"idle_timeout"`
 38}
 39
 40// GitConfig is the Git daemon configuration for the server.
 41type GitConfig struct {
 42	// ListenAddr is the address on which the Git daemon will listen.
 43	ListenAddr string `env:"LISTEN_ADDR" yaml:"listen_addr"`
 44
 45	// MaxTimeout is the maximum number of seconds a connection can take.
 46	MaxTimeout int `env:"MAX_TIMEOUT" yaml:"max_timeout"`
 47
 48	// IdleTimeout is the number of seconds a connection can be idle before it is closed.
 49	IdleTimeout int `env:"IDLE_TIMEOUT" yaml:"idle_timeout"`
 50
 51	// MaxConnections is the maximum number of concurrent connections.
 52	MaxConnections int `env:"MAX_CONNECTIONS" yaml:"max_connections"`
 53}
 54
 55// HTTPConfig is the HTTP configuration for the server.
 56type HTTPConfig struct {
 57	// ListenAddr is the address on which the HTTP server will listen.
 58	ListenAddr string `env:"LISTEN_ADDR" yaml:"listen_addr"`
 59
 60	// TLSKeyPath is the path to the TLS private key.
 61	TLSKeyPath string `env:"TLS_KEY_PATH" yaml:"tls_key_path"`
 62
 63	// TLSCertPath is the path to the TLS certificate.
 64	TLSCertPath string `env:"TLS_CERT_PATH" yaml:"tls_cert_path"`
 65
 66	// PublicURL is the public URL of the HTTP server.
 67	PublicURL string `env:"PUBLIC_URL" yaml:"public_url"`
 68}
 69
 70// StatsConfig is the configuration for the stats server.
 71type StatsConfig struct {
 72	// ListenAddr is the address on which the stats server will listen.
 73	ListenAddr string `env:"LISTEN_ADDR" yaml:"listen_addr"`
 74}
 75
 76// Config is the configuration for Soft Serve.
 77type Config struct {
 78	// Name is the name of the server.
 79	Name string `env:"NAME" yaml:"name"`
 80
 81	// SSH is the configuration for the SSH server.
 82	SSH SSHConfig `envPrefix:"SSH_" yaml:"ssh"`
 83
 84	// Git is the configuration for the Git daemon.
 85	Git GitConfig `envPrefix:"GIT_" yaml:"git"`
 86
 87	// HTTP is the configuration for the HTTP server.
 88	HTTP HTTPConfig `envPrefix:"HTTP_" yaml:"http"`
 89
 90	// Stats is the configuration for the stats server.
 91	Stats StatsConfig `envPrefix:"STATS_" yaml:"stats"`
 92
 93	// InitialAdminKeys is a list of public keys that will be added to the list of admins.
 94	InitialAdminKeys []string `env:"INITIAL_ADMIN_KEYS" envSeparator:"\n" yaml:"initial_admin_keys"`
 95
 96	// DataPath is the path to the directory where Soft Serve will store its data.
 97	DataPath string `env:"DATA_PATH" yaml:"-"`
 98
 99	// Backend is the Git backend to use.
100	Backend backend.Backend `yaml:"-"`
101
102	// InternalPublicKey is the public key of the internal SSH key.
103	InternalPublicKey string `yaml:"-"`
104
105	// ClientPublicKey is the public key of the client SSH key.
106	ClientPublicKey string `yaml:"-"`
107}
108
109func parseConfig(path string) (*Config, error) {
110	dataPath := filepath.Dir(path)
111	cfg := &Config{
112		Name:     "Soft Serve",
113		DataPath: dataPath,
114		SSH: SSHConfig{
115			ListenAddr:      ":23231",
116			PublicURL:       "ssh://localhost:23231",
117			KeyPath:         filepath.Join("ssh", "soft_serve_host_ed25519"),
118			ClientKeyPath:   filepath.Join("ssh", "soft_serve_client_ed25519"),
119			InternalKeyPath: filepath.Join("ssh", "soft_serve_internal_ed25519"),
120			MaxTimeout:      0,
121			IdleTimeout:     120,
122		},
123		Git: GitConfig{
124			ListenAddr:     ":9418",
125			MaxTimeout:     0,
126			IdleTimeout:    3,
127			MaxConnections: 32,
128		},
129		HTTP: HTTPConfig{
130			ListenAddr: ":8080",
131			PublicURL:  "http://localhost:8080",
132		},
133		Stats: StatsConfig{
134			ListenAddr: ":8081",
135		},
136	}
137
138	f, err := os.Open(path)
139	if err != nil {
140		return cfg, err
141	}
142
143	defer f.Close() // nolint: errcheck
144	if err := yaml.NewDecoder(f).Decode(cfg); err != nil {
145		return cfg, fmt.Errorf("decode config: %w", err)
146	}
147
148	// Override with environment variables
149	if err := env.Parse(cfg, env.Options{
150		Prefix: "SOFT_SERVE_",
151	}); err != nil {
152		return cfg, fmt.Errorf("parse environment variables: %w", err)
153	}
154
155	// Reset datapath to config dir.
156	// This is necessary because the environment variable may be set to
157	// a different directory.
158	cfg.DataPath = dataPath
159
160	return cfg, nil
161}
162
163// ParseConfig parses the configuration from the given file.
164func ParseConfig(path string) (*Config, error) {
165	cfg, err := parseConfig(path)
166	if err != nil {
167		return nil, err
168	}
169
170	if err := cfg.validate(); err != nil {
171		return nil, err
172	}
173
174	return cfg, nil
175}
176
177// WriteConfig writes the configuration to the given file.
178func WriteConfig(path string, cfg *Config) error {
179	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
180		return err
181	}
182	return os.WriteFile(path, []byte(newConfigFile(cfg)), 0o600) // nolint: errcheck
183}
184
185// DefaultConfig returns a Config with the values populated with the defaults
186// or specified environment variables.
187func DefaultConfig() *Config {
188	dataPath := os.Getenv("SOFT_SERVE_DATA_PATH")
189	if dataPath == "" {
190		dataPath = "data"
191	}
192
193	cp := filepath.Join(dataPath, "config.yaml")
194	cfg, err := parseConfig(cp)
195	if err != nil && !errors.Is(err, os.ErrNotExist) {
196		log.Errorf("failed to parse config: %v", err)
197	}
198
199	// Write config if it doesn't exist
200	if _, err := os.Stat(cp); os.IsNotExist(err) {
201		if err := WriteConfig(cp, cfg); err != nil {
202			log.Fatal("failed to write config", "err", err)
203		}
204	}
205
206	if err := cfg.validate(); err != nil {
207		log.Fatal(err)
208	}
209
210	return cfg
211}
212
213// WithBackend sets the backend for the configuration.
214func (c *Config) WithBackend(backend backend.Backend) *Config {
215	c.Backend = backend
216	return c
217}
218
219func (c *Config) validate() error {
220	// Use absolute paths
221	if !filepath.IsAbs(c.DataPath) {
222		dp, err := filepath.Abs(c.DataPath)
223		if err != nil {
224			return err
225		}
226		c.DataPath = dp
227	}
228
229	c.SSH.PublicURL = strings.TrimSuffix(c.SSH.PublicURL, "/")
230	c.HTTP.PublicURL = strings.TrimSuffix(c.HTTP.PublicURL, "/")
231
232	if c.SSH.KeyPath != "" && !filepath.IsAbs(c.SSH.KeyPath) {
233		c.SSH.KeyPath = filepath.Join(c.DataPath, c.SSH.KeyPath)
234	}
235
236	if c.SSH.ClientKeyPath != "" && !filepath.IsAbs(c.SSH.ClientKeyPath) {
237		c.SSH.ClientKeyPath = filepath.Join(c.DataPath, c.SSH.ClientKeyPath)
238	}
239
240	if c.SSH.InternalKeyPath != "" && !filepath.IsAbs(c.SSH.InternalKeyPath) {
241		c.SSH.InternalKeyPath = filepath.Join(c.DataPath, c.SSH.InternalKeyPath)
242	}
243
244	if c.HTTP.TLSKeyPath != "" && !filepath.IsAbs(c.HTTP.TLSKeyPath) {
245		c.HTTP.TLSKeyPath = filepath.Join(c.DataPath, c.HTTP.TLSKeyPath)
246	}
247
248	if c.HTTP.TLSCertPath != "" && !filepath.IsAbs(c.HTTP.TLSCertPath) {
249		c.HTTP.TLSCertPath = filepath.Join(c.DataPath, c.HTTP.TLSCertPath)
250	}
251
252	return nil
253}