krz/gitbay

A CLI-first git forge.

clone: git clone https://gitbay.org/krz/gitbay.git

main: internal/config/config.go · raw

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