internal/config/config.go

617b05d09be747ad310179ce5432dec98ebe2c17
gitbay/internal/config/config.go history · blame · raw

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