1package config
  2
  3import (
  4	"context"
  5	"errors"
  6	"fmt"
  7	"os"
  8	"path/filepath"
  9	"strings"
 10	"time"
 11
 12	"github.com/caarlos0/env/v8"
 13	"github.com/charmbracelet/log"
 14	"github.com/charmbracelet/soft-serve/server/backend"
 15	"golang.org/x/crypto/ssh"
 16	"gopkg.in/yaml.v3"
 17)
 18
 19// SSHConfig is the configuration for the SSH server.
 20type SSHConfig struct {
 21	// ListenAddr is the address on which the SSH server will listen.
 22	ListenAddr string `env:"LISTEN_ADDR" yaml:"listen_addr"`
 23
 24	// PublicURL is the public URL of the SSH server.
 25	PublicURL string `env:"PUBLIC_URL" yaml:"public_url"`
 26
 27	// KeyPath is the path to the SSH server's private key.
 28	KeyPath string `env:"KEY_PATH" yaml:"key_path"`
 29
 30	// ClientKeyPath is the path to the server's client private key.
 31	ClientKeyPath string `env:"CLIENT_KEY_PATH" yaml:"client_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// LogConfig is the logger configuration.
 77type LogConfig struct {
 78	// Format is the format of the logs.
 79	// Valid values are "json", "logfmt", and "text".
 80	Format string `env:"FORMAT" yaml:"format"`
 81
 82	// Time format for the log `ts` field.
 83	// Format must be described in Golang's time format.
 84	TimeFormat string `env:"TIME_FORMAT" yaml:"time_format"`
 85}
 86
 87// Config is the configuration for Soft Serve.
 88type Config struct {
 89	// Name is the name of the server.
 90	Name string `env:"NAME" yaml:"name"`
 91
 92	// SSH is the configuration for the SSH server.
 93	SSH SSHConfig `envPrefix:"SSH_" yaml:"ssh"`
 94
 95	// Git is the configuration for the Git daemon.
 96	Git GitConfig `envPrefix:"GIT_" yaml:"git"`
 97
 98	// HTTP is the configuration for the HTTP server.
 99	HTTP HTTPConfig `envPrefix:"HTTP_" yaml:"http"`
100
101	// Stats is the configuration for the stats server.
102	Stats StatsConfig `envPrefix:"STATS_" yaml:"stats"`
103
104	// Log is the logger configuration.
105	Log LogConfig `envPrefix:"LOG_" yaml:"log"`
106
107	// InitialAdminKeys is a list of public keys that will be added to the list of admins.
108	InitialAdminKeys []string `env:"INITIAL_ADMIN_KEYS" envSeparator:"\n" yaml:"initial_admin_keys"`
109
110	// DataPath is the path to the directory where Soft Serve will store its data.
111	DataPath string `env:"DATA_PATH" yaml:"-"`
112
113	// Backend is the Git backend to use.
114	Backend backend.Backend `yaml:"-"`
115}
116
117func parseConfig(path string) (*Config, error) {
118	dataPath := filepath.Dir(path)
119	cfg := &Config{
120		Name:     "Soft Serve",
121		DataPath: dataPath,
122		SSH: SSHConfig{
123			ListenAddr:    ":23231",
124			PublicURL:     "ssh://localhost:23231",
125			KeyPath:       filepath.Join("ssh", "soft_serve_host_ed25519"),
126			ClientKeyPath: filepath.Join("ssh", "soft_serve_client_ed25519"),
127			MaxTimeout:    0,
128			IdleTimeout:   0,
129		},
130		Git: GitConfig{
131			ListenAddr:     ":9418",
132			MaxTimeout:     0,
133			IdleTimeout:    3,
134			MaxConnections: 32,
135		},
136		HTTP: HTTPConfig{
137			ListenAddr: ":23232",
138			PublicURL:  "http://localhost:23232",
139		},
140		Stats: StatsConfig{
141			ListenAddr: "localhost:23233",
142		},
143		Log: LogConfig{
144			Format:     "text",
145			TimeFormat: time.DateTime,
146		},
147	}
148
149	f, err := os.Open(path)
150	if err == nil {
151		defer f.Close() // nolint: errcheck
152		if err := yaml.NewDecoder(f).Decode(cfg); err != nil {
153			return cfg, fmt.Errorf("decode config: %w", err)
154		}
155	}
156
157	// Merge initial admin keys from both config file and environment variables.
158	initialAdminKeys := append([]string{}, cfg.InitialAdminKeys...)
159
160	// Override with environment variables
161	if err := env.ParseWithOptions(cfg, env.Options{
162		Prefix: "SOFT_SERVE_",
163	}); err != nil {
164		return cfg, fmt.Errorf("parse environment variables: %w", err)
165	}
166
167	// Merge initial admin keys from environment variables.
168	if initialAdminKeysEnv := os.Getenv("SOFT_SERVE_INITIAL_ADMIN_KEYS"); initialAdminKeysEnv != "" {
169		cfg.InitialAdminKeys = append(cfg.InitialAdminKeys, initialAdminKeys...)
170	}
171
172	// Validate keys
173	pks := make([]string, 0)
174	for _, key := range parseAuthKeys(cfg.InitialAdminKeys) {
175		ak := backend.MarshalAuthorizedKey(key)
176		pks = append(pks, ak)
177	}
178
179	cfg.InitialAdminKeys = pks
180
181	// Reset datapath to config dir.
182	// This is necessary because the environment variable may be set to
183	// a different directory.
184	cfg.DataPath = dataPath
185
186	return cfg, nil
187}
188
189// ParseConfig parses the configuration from the given file.
190func ParseConfig(path string) (*Config, error) {
191	cfg, err := parseConfig(path)
192	if err != nil {
193		return cfg, err
194	}
195
196	if err := cfg.validate(); err != nil {
197		return cfg, err
198	}
199
200	return cfg, nil
201}
202
203// WriteConfig writes the configuration to the given file.
204func WriteConfig(path string, cfg *Config) error {
205	if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
206		return err
207	}
208	return os.WriteFile(path, []byte(newConfigFile(cfg)), 0o644) // nolint: errcheck
209}
210
211// DefaultConfig returns a Config with the values populated with the defaults
212// or specified environment variables.
213func DefaultConfig() *Config {
214	dataPath := os.Getenv("SOFT_SERVE_DATA_PATH")
215	if dataPath == "" {
216		dataPath = "data"
217	}
218
219	cp := filepath.Join(dataPath, "config.yaml")
220	cfg, err := parseConfig(cp)
221	if err != nil && !errors.Is(err, os.ErrNotExist) {
222		log.Errorf("failed to parse config: %v", err)
223	}
224
225	// Write config if it doesn't exist
226	if _, err := os.Stat(cp); os.IsNotExist(err) {
227		if err := WriteConfig(cp, cfg); err != nil {
228			log.Fatal("failed to write config", "err", err)
229		}
230	}
231
232	if err := cfg.validate(); err != nil {
233		log.Fatal(err)
234	}
235
236	return cfg
237}
238
239// WithBackend sets the backend for the configuration.
240func (c *Config) WithBackend(backend backend.Backend) *Config {
241	c.Backend = backend
242	return c
243}
244
245func (c *Config) validate() error {
246	// Use absolute paths
247	if !filepath.IsAbs(c.DataPath) {
248		dp, err := filepath.Abs(c.DataPath)
249		if err != nil {
250			return err
251		}
252		c.DataPath = dp
253	}
254
255	c.SSH.PublicURL = strings.TrimSuffix(c.SSH.PublicURL, "/")
256	c.HTTP.PublicURL = strings.TrimSuffix(c.HTTP.PublicURL, "/")
257
258	if c.SSH.KeyPath != "" && !filepath.IsAbs(c.SSH.KeyPath) {
259		c.SSH.KeyPath = filepath.Join(c.DataPath, c.SSH.KeyPath)
260	}
261
262	if c.SSH.ClientKeyPath != "" && !filepath.IsAbs(c.SSH.ClientKeyPath) {
263		c.SSH.ClientKeyPath = filepath.Join(c.DataPath, c.SSH.ClientKeyPath)
264	}
265
266	if c.HTTP.TLSKeyPath != "" && !filepath.IsAbs(c.HTTP.TLSKeyPath) {
267		c.HTTP.TLSKeyPath = filepath.Join(c.DataPath, c.HTTP.TLSKeyPath)
268	}
269
270	if c.HTTP.TLSCertPath != "" && !filepath.IsAbs(c.HTTP.TLSCertPath) {
271		c.HTTP.TLSCertPath = filepath.Join(c.DataPath, c.HTTP.TLSCertPath)
272	}
273
274	return nil
275}
276
277// parseAuthKeys parses authorized keys from either file paths or string authorized_keys.
278func parseAuthKeys(aks []string) []ssh.PublicKey {
279	pks := make([]ssh.PublicKey, 0)
280	for _, key := range aks {
281		if bts, err := os.ReadFile(key); err == nil {
282			// key is a file
283			key = strings.TrimSpace(string(bts))
284		}
285		if pk, _, err := backend.ParseAuthorizedKey(key); err == nil {
286			pks = append(pks, pk)
287		}
288	}
289	return pks
290}
291
292// AdminKeys returns the server admin keys.
293func (c *Config) AdminKeys() []ssh.PublicKey {
294	return parseAuthKeys(c.InitialAdminKeys)
295}
296
297var configCtxKey = struct{ string }{"config"}
298
299// WithContext returns a new context with the configuration attached.
300func WithContext(ctx context.Context, cfg *Config) context.Context {
301	return context.WithValue(ctx, configCtxKey, cfg)
302}
303
304// FromContext returns the configuration from the context.
305func FromContext(ctx context.Context) *Config {
306	if c, ok := ctx.Value(configCtxKey).(*Config); ok {
307		return c
308	}
309
310	return DefaultConfig()
311}