internal/config/config.go

8ff79f104466ce76ae50fb73fd4169750b88deed
gitbay/internal/config/config.go history · blame · raw

227 lines · 7155 bytes

  1// Package config loads and validates the gitbayd server configuration.
  2package config
  3
  4import (
  5	"errors"
  6	"fmt"
  7	"net"
  8	"os"
  9	"strconv"
 10	"strings"
 11
 12	"github.com/BurntSushi/toml"
 13)
 14
 15type Config struct {
 16	Server       Server       `toml:"server"`
 17	SSH          SSH          `toml:"ssh"`
 18	HTTP         HTTP         `toml:"http"`
 19	GitDaemon    GitDaemon    `toml:"git_daemon"`
 20	Web          Web          `toml:"web"`
 21	Registration Registration `toml:"registration"`
 22	API          API          `toml:"api"`
 23	Limits       Limits       `toml:"limits"`
 24	Mail         Mail         `toml:"mail"`
 25}
 26
 27type Server struct {
 28	Root    string `toml:"root"`
 29	SiteURL string `toml:"site_url"`
 30}
 31
 32type SSH struct {
 33	Mode     string   `toml:"mode"` // embedded | system
 34	Port     int      `toml:"port"`
 35	HostKeys []string `toml:"host_keys"`
 36}
 37
 38type HTTP struct {
 39	Addr     string `toml:"addr"`
 40	TLS      string `toml:"tls"` // acme | files | off
 41	CertFile string `toml:"cert_file"`
 42	KeyFile  string `toml:"key_file"`
 43	// ACME (Let's Encrypt by default). Certificates are cached under
 44	// server.root/acme. acme_http_addr serves HTTP-01 challenges and
 45	// redirects to HTTPS; "off" disables it (TLS-ALPN-01 on the HTTPS
 46	// port still works).
 47	ACMEEmail    string `toml:"acme_email"`
 48	ACMEHTTPAddr string `toml:"acme_http_addr"`
 49}
 50
 51type GitDaemon struct {
 52	Enabled bool `toml:"enabled"`
 53	Port    int  `toml:"port"`
 54}
 55
 56type Web struct {
 57	Mode         string `toml:"mode"` // view_only | accounts
 58	PasswordAuth bool   `toml:"password_auth"`
 59}
 60
 61type Registration struct {
 62	Mode string `toml:"mode"` // closed | invite | open
 63}
 64
 65// API controls the HTTPS/JSON control-plane API (bearer tokens minted over
 66// SSH). Off by default: an instance that never enables it has no
 67// credential-bearing HTTP surface at all.
 68type API struct {
 69	Enabled bool `toml:"enabled"`
 70}
 71
 72type Limits struct {
 73	MaxPackBytes    int64 `toml:"max_pack_bytes"`
 74	MaxBlobBytes    int64 `toml:"max_blob_bytes"`
 75	CloneTimeoutSec int   `toml:"clone_timeout"`
 76	SSHAuthRate     int   `toml:"ssh_auth_rate"`
 77}
 78
 79type Mail struct {
 80	SMTPHost string `toml:"smtp_host"` // host:port (port defaults to 587)
 81	From     string `toml:"from"`
 82	SMTPUser string `toml:"smtp_user,omitempty"`
 83	SMTPPass string `toml:"smtp_pass,omitempty"`
 84}
 85
 86// Default returns the configuration used when a key is absent from the file.
 87func Default() Config {
 88	return Config{
 89		Server: Server{Root: "/var/lib/gitbay"},
 90		SSH:    SSH{Mode: "embedded", Port: 22},
 91		HTTP:   HTTP{Addr: ":443", TLS: "acme", ACMEHTTPAddr: ":80"},
 92		Web:    Web{Mode: "view_only"},
 93		Registration: Registration{
 94			Mode: "closed",
 95		},
 96		GitDaemon: GitDaemon{Port: 9418},
 97		Limits: Limits{
 98			MaxPackBytes:    2 << 30, // 2 GiB
 99			MaxBlobBytes:    100 << 20,
100			CloneTimeoutSec: 3600,
101			SSHAuthRate:     10,
102		},
103	}
104}
105
106// Load reads path, applies defaults, and validates. It does not probe the
107// host (see CheckHost) so it is safe in tests and on non-target machines.
108func Load(path string) (Config, error) {
109	cfg := Default()
110	md, err := toml.DecodeFile(path, &cfg)
111	if err != nil {
112		return cfg, err
113	}
114	if u := md.Undecoded(); len(u) > 0 {
115		return cfg, fmt.Errorf("unknown config key %q", u[0].String())
116	}
117	return cfg, cfg.Validate()
118}
119
120func oneOf(field, val string, allowed ...string) error {
121	for _, a := range allowed {
122		if val == a {
123			return nil
124		}
125	}
126	return fmt.Errorf("%s must be one of %v, got %q", field, allowed, val)
127}
128
129// Validate applies the static contradiction checks from the plan.
130func (c Config) Validate() error {
131	var errs []error
132
133	if c.Server.Root == "" {
134		errs = append(errs, errors.New("server.root is required"))
135	}
136	if c.Server.SiteURL == "" {
137		errs = append(errs, errors.New("server.site_url is required"))
138	}
139	if err := oneOf("ssh.mode", c.SSH.Mode, "embedded", "system"); err != nil {
140		errs = append(errs, err)
141	}
142	if c.SSH.Port < 1 || c.SSH.Port > 65535 {
143		errs = append(errs, fmt.Errorf("ssh.port %d out of range", c.SSH.Port))
144	}
145	if err := oneOf("http.tls", c.HTTP.TLS, "acme", "files", "off"); err != nil {
146		errs = append(errs, err)
147	}
148	if c.HTTP.TLS == "files" && (c.HTTP.CertFile == "" || c.HTTP.KeyFile == "") {
149		errs = append(errs, errors.New("http.tls = \"files\" requires cert_file and key_file"))
150	}
151	if c.HTTP.TLS == "acme" {
152		host := c.SiteHost()
153		switch {
154		case !strings.HasPrefix(c.Server.SiteURL, "https://"):
155			errs = append(errs, errors.New("http.tls = \"acme\" requires an https:// site_url: certificates are issued for that host"))
156		case host == "" || host == "localhost" || net.ParseIP(host) != nil:
157			errs = append(errs, fmt.Errorf("http.tls = \"acme\" cannot issue a certificate for %q: use a public DNS name in site_url", host))
158		}
159	}
160	if err := oneOf("web.mode", c.Web.Mode, "view_only", "accounts"); err != nil {
161		errs = append(errs, err)
162	}
163	if err := oneOf("registration.mode", c.Registration.Mode, "closed", "invite", "open"); err != nil {
164		errs = append(errs, err)
165	}
166
167	// Contradictions.
168	if c.Mail.SMTPHost != "" && c.Mail.From == "" {
169		errs = append(errs, errors.New("[mail] from is required when smtp_host is set"))
170	}
171	if c.Registration.Mode != "closed" && c.Mail.SMTPHost == "" {
172		errs = append(errs, fmt.Errorf(
173			"registration.mode = %q requires [mail] smtp_host: email verification cannot run without SMTP",
174			c.Registration.Mode))
175	}
176	if c.SSH.Mode == "system" && c.Registration.Mode != "closed" {
177		errs = append(errs, fmt.Errorf(
178			"ssh.mode = \"system\" requires registration.mode = \"closed\": host sshd rejects unknown keys before the dispatcher runs, so registration by unknown key is impossible"))
179	}
180	if c.Web.PasswordAuth && c.Web.Mode == "view_only" {
181		errs = append(errs, errors.New(
182			"web.password_auth = true is meaningless with web.mode = \"view_only\": no login route exists"))
183	}
184	if c.Web.PasswordAuth && c.Web.Mode == "accounts" {
185		errs = append(errs, errors.New(
186			"web.password_auth is not implemented yet; browser sessions are minted over SSH (gitbay web login)"))
187	}
188
189	return errors.Join(errs...)
190}
191
192// SiteHost returns the bare hostname from site_url (no scheme, port, path).
193func (c Config) SiteHost() string {
194	h := strings.TrimPrefix(strings.TrimPrefix(c.Server.SiteURL, "https://"), "http://")
195	h = strings.TrimSuffix(h, "/")
196	if i := strings.IndexByte(h, '/'); i >= 0 {
197		h = h[:i]
198	}
199	if host, _, err := net.SplitHostPort(h); err == nil {
200		return host
201	}
202	return h
203}
204
205// CheckHost performs environment probes that only make sense on the target
206// machine: port availability for the embedded listener and root existence.
207func (c Config) CheckHost() error {
208	var errs []error
209
210	if st, err := os.Stat(c.Server.Root); err != nil {
211		errs = append(errs, fmt.Errorf("server.root: %w", err))
212	} else if !st.IsDir() {
213		errs = append(errs, fmt.Errorf("server.root %q is not a directory", c.Server.Root))
214	}
215
216	if c.SSH.Mode == "embedded" {
217		addr := net.JoinHostPort("", strconv.Itoa(c.SSH.Port))
218		ln, err := net.Listen("tcp", addr)
219		if err != nil {
220			errs = append(errs, fmt.Errorf("ssh.port %d is not bindable (already in use by another daemon?): %w", c.SSH.Port, err))
221		} else {
222			ln.Close()
223		}
224	}
225
226	return errors.Join(errs...)
227}