internal/config/config.go

f9845abbc93ead5d74684a56f2e677be71c69587
gitbay/internal/config/config.go history · blame · raw

398 lines · 14236 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	"time"
 12
 13	"github.com/BurntSushi/toml"
 14)
 15
 16// DefaultWriteRate is the per-account write budget when the config leaves
 17// write_rate at zero: generous for a person at a terminal, and a bound on
 18// what one account can enqueue — every write also queues notification mail
 19// and webhook deliveries.
 20const DefaultWriteRate = 60
 21
 22type Config struct {
 23	Server       Server       `toml:"server"`
 24	SSH          SSH          `toml:"ssh"`
 25	HTTP         HTTP         `toml:"http"`
 26	GitDaemon    GitDaemon    `toml:"git_daemon"`
 27	Web          Web          `toml:"web"`
 28	Registration Registration `toml:"registration"`
 29	API          API          `toml:"api"`
 30	Webhooks     Webhooks     `toml:"webhooks"`
 31	Pages        Pages        `toml:"pages"`
 32	LFS          LFS          `toml:"lfs"`
 33	Limits       Limits       `toml:"limits"`
 34	Mail         Mail         `toml:"mail"`
 35	Mirrors      Mirrors      `toml:"mirrors"`
 36	Deps         Deps         `toml:"deps"`
 37	Retention    Retention    `toml:"retention"`
 38	// GoImport maps vanity Go module paths to repositories, e.g.
 39	// "gitbay.org/gitbay" = "krz/gitbay". Requests carrying ?go-get=1
 40	// under a mapped path get a go-import meta tag.
 41	GoImport map[string]string `toml:"go_import"`
 42}
 43
 44type Server struct {
 45	Root    string `toml:"root"`
 46	SiteURL string `toml:"site_url"`
 47
 48	// SourceRepo names the repository this instance develops itself in, as
 49	// "owner/name". When set, startup warns if the running build's commit is
 50	// not on that repository's default branch. Empty disables the check, which
 51	// is right for any instance that does not host its own source.
 52	SourceRepo string `toml:"source_repo"`
 53}
 54
 55type SSH struct {
 56	Mode     string   `toml:"mode"` // embedded | system
 57	Port     int      `toml:"port"`
 58	HostKeys []string `toml:"host_keys"`
 59}
 60
 61type HTTP struct {
 62	Addr     string `toml:"addr"`
 63	TLS      string `toml:"tls"` // acme | files | off
 64	CertFile string `toml:"cert_file"`
 65	KeyFile  string `toml:"key_file"`
 66	// ACME (Let's Encrypt by default). Certificates are cached under
 67	// server.root/acme. acme_http_addr serves HTTP-01 challenges and
 68	// redirects to HTTPS; "off" disables it (TLS-ALPN-01 on the HTTPS
 69	// port still works).
 70	ACMEEmail    string `toml:"acme_email"`
 71	ACMEHTTPAddr string `toml:"acme_http_addr"`
 72	// TrustedProxies are the addresses or CIDRs of reverse proxies in front
 73	// of this process. A request from one of them is attributed to the
 74	// last X-Forwarded-For hop that is not itself a trusted proxy; from
 75	// anyone else the peer address is the client and the header is
 76	// ignored. Empty means no proxy, which is how gitbayd is deployed by
 77	// default: it terminates TLS itself.
 78	TrustedProxies []string `toml:"trusted_proxies,omitempty"`
 79}
 80
 81type GitDaemon struct {
 82	Enabled bool `toml:"enabled"`
 83	Port    int  `toml:"port"`
 84}
 85
 86type Web struct {
 87	Mode         string `toml:"mode"` // view_only | accounts
 88	PasswordAuth bool   `toml:"password_auth"`
 89	// Title is the instance's display name in the header and page titles.
 90	// Empty falls back to the site host.
 91	Title string `toml:"title"`
 92	// PrivacyNotice is operator-provided text shown on /privacy under the
 93	// fixed project-level statement. Plain text; blank paragraphs split.
 94	PrivacyNotice string `toml:"privacy_notice"`
 95}
 96
 97type Registration struct {
 98	Mode string `toml:"mode"` // closed | invite | open
 99	// PendingExpiry is how long a self-registered account may stay
100	// unverified before it is removed, as a duration ("168h"). Empty
101	// keeps such accounts forever.
102	PendingExpiry string `toml:"pending_expiry"`
103}
104
105// PendingExpiryDuration parses PendingExpiry; zero means never.
106func (r Registration) PendingExpiryDuration() time.Duration {
107	d, _ := time.ParseDuration(r.PendingExpiry)
108	return d
109}
110
111// Retention is how long the append-only tables keep a row. Each is a
112// duration string ("2160h"); empty or zero keeps forever, which is what
113// an instance that has never configured this gets. Expired sessions and
114// tokens are swept regardless: they are dead weight the moment they
115// expire and no setting makes them worth keeping.
116type Retention struct {
117	Audit             string `toml:"audit"`
118	Events            string `toml:"events"`
119	WebhookDeliveries string `toml:"webhook_deliveries"`
120	// Mail is the outbound queue: rows already sent or given up on.
121	Mail string `toml:"mail"`
122}
123
124// Durations parses the four, mapping each to zero when unset or bad.
125func (r Retention) Durations() (audit, events, deliveries, mail time.Duration) {
126	parse := func(s string) time.Duration {
127		d, err := time.ParseDuration(s)
128		if err != nil || d < 0 {
129			return 0
130		}
131		return d
132	}
133	return parse(r.Audit), parse(r.Events), parse(r.WebhookDeliveries), parse(r.Mail)
134}
135
136// LFS stores large-file objects content-addressed under Root (default
137// <server.root>/lfs). MaxObjectBytes caps a single object; 0 means the
138// 512MB default.
139type LFS struct {
140	Root           string `toml:"root"`
141	MaxObjectBytes int64  `toml:"max_object_bytes"`
142}
143
144// Pages serves each public repo's `pages` branch as a static site on
145// <owner>.<domain> — a separate origin, so page-authored scripts never run
146// on the forge's own host. Empty domain disables the feature.
147type Pages struct {
148	Domain string `toml:"domain"`
149}
150
151// API controls the HTTPS/JSON control-plane API (bearer tokens minted over
152// SSH). Off by default: an instance that never enables it has no
153// credential-bearing HTTP surface at all.
154type API struct {
155	Enabled bool `toml:"enabled"`
156}
157
158// Webhooks controls outbound delivery. AllowLocal permits endpoints on
159// loopback/private addresses (off by default: SSRF).
160type Webhooks struct {
161	AllowLocal bool `toml:"allow_local"`
162}
163
164type Mirrors struct {
165	PullIntervalMinutes int `toml:"pull_interval_minutes"`
166}
167
168// Deps configures the dependency-update sweep. It runs only for repos that
169// have opted in with `repo deps enable`, because checking a private repo
170// tells a public registry what it depends on.
171type Deps struct {
172	CheckIntervalHours int `toml:"check_interval_hours"`
173}
174
175type Limits struct {
176	MaxPackBytes    int64 `toml:"max_pack_bytes"`
177	MaxBlobBytes    int64 `toml:"max_blob_bytes"`
178	MaxAssetBytes   int64 `toml:"max_asset_bytes"` // per release asset
179	CloneTimeoutSec int   `toml:"clone_timeout"`
180	SSHAuthRate     int   `toml:"ssh_auth_rate"`
181	// APIRate is sustained JSON-API requests per minute per caller; writes
182	// draw on a tenth of it. 0 uses the default.
183	APIRate int `toml:"api_rate"`
184	// WriteRate is sustained mutating commands per minute per account,
185	// counted in the dispatcher so every surface shares one budget. 0 uses
186	// the default; a negative value turns the limit off.
187	WriteRate int `toml:"write_rate"`
188	// Per-account quotas on what a user owns directly (organizations are
189	// not capped). 0 means unlimited; admin user limits overrides per
190	// account.
191	MaxReposPerUser int   `toml:"max_repos_per_user"`
192	MaxBytesPerUser int64 `toml:"max_bytes_per_user"`
193}
194
195type Mail struct {
196	SMTPHost string `toml:"smtp_host"` // host:port (port defaults to 587)
197	From     string `toml:"from"`
198	SMTPUser string `toml:"smtp_user,omitempty"`
199	SMTPPass string `toml:"smtp_pass,omitempty"`
200}
201
202// Default returns the configuration used when a key is absent from the file.
203func Default() Config {
204	return Config{
205		Server: Server{Root: "/var/lib/gitbay"},
206		SSH:    SSH{Mode: "embedded", Port: 22},
207		HTTP:   HTTP{Addr: ":443", TLS: "acme", ACMEHTTPAddr: ":80"},
208		Web:    Web{Mode: "view_only"},
209		Registration: Registration{
210			Mode: "closed",
211		},
212		GitDaemon: GitDaemon{Port: 9418},
213		Mirrors:   Mirrors{PullIntervalMinutes: 15},
214		Deps:      Deps{CheckIntervalHours: 24},
215		Limits: Limits{
216			MaxPackBytes:    2 << 30, // 2 GiB
217			MaxBlobBytes:    100 << 20,
218			MaxAssetBytes:   512 << 20,
219			CloneTimeoutSec: 3600,
220			SSHAuthRate:     10,
221			APIRate:         120,
222		},
223	}
224}
225
226// Load reads path, applies defaults, and validates. It does not probe the
227// host (see CheckHost) so it is safe in tests and on non-target machines.
228func Load(path string) (Config, error) {
229	cfg := Default()
230	md, err := toml.DecodeFile(path, &cfg)
231	if err != nil {
232		return cfg, err
233	}
234	if u := md.Undecoded(); len(u) > 0 {
235		return cfg, fmt.Errorf("unknown config key %q", u[0].String())
236	}
237	return cfg, cfg.Validate()
238}
239
240func oneOf(field, val string, allowed ...string) error {
241	for _, a := range allowed {
242		if val == a {
243			return nil
244		}
245	}
246	return fmt.Errorf("%s must be one of %v, got %q", field, allowed, val)
247}
248
249// Validate applies the static contradiction checks from the plan.
250func (c Config) Validate() error {
251	var errs []error
252
253	if c.Server.Root == "" {
254		errs = append(errs, errors.New("server.root is required"))
255	}
256	if d := c.Pages.Domain; d != "" {
257		if d == c.SiteHost() {
258			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"))
259		}
260		if strings.HasSuffix(c.SiteHost(), "."+d) {
261			errs = append(errs, errors.New("pages.domain must not be a parent of the site host"))
262		}
263	}
264	if c.Server.SiteURL == "" {
265		errs = append(errs, errors.New("server.site_url is required"))
266	}
267	if err := oneOf("ssh.mode", c.SSH.Mode, "embedded", "system"); err != nil {
268		errs = append(errs, err)
269	}
270	if c.Registration.PendingExpiry != "" {
271		if d, err := time.ParseDuration(c.Registration.PendingExpiry); err != nil || d <= 0 {
272			errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry))
273		}
274	}
275	if c.Limits.MaxReposPerUser < 0 || c.Limits.MaxBytesPerUser < 0 {
276		errs = append(errs, errors.New("limits.max_repos_per_user and max_bytes_per_user must not be negative"))
277	}
278	if c.SSH.Port < 1 || c.SSH.Port > 65535 {
279		errs = append(errs, fmt.Errorf("ssh.port %d out of range", c.SSH.Port))
280	}
281	if err := oneOf("http.tls", c.HTTP.TLS, "acme", "files", "off"); err != nil {
282		errs = append(errs, err)
283	}
284	if _, err := c.HTTP.TrustedProxyNets(); err != nil {
285		errs = append(errs, err)
286	}
287	if c.HTTP.TLS == "files" && (c.HTTP.CertFile == "" || c.HTTP.KeyFile == "") {
288		errs = append(errs, errors.New("http.tls = \"files\" requires cert_file and key_file"))
289	}
290	if c.HTTP.TLS == "acme" {
291		host := c.SiteHost()
292		switch {
293		case !strings.HasPrefix(c.Server.SiteURL, "https://"):
294			errs = append(errs, errors.New("http.tls = \"acme\" requires an https:// site_url: certificates are issued for that host"))
295		case host == "" || host == "localhost" || net.ParseIP(host) != nil:
296			errs = append(errs, fmt.Errorf("http.tls = \"acme\" cannot issue a certificate for %q: use a public DNS name in site_url", host))
297		}
298	}
299	if err := oneOf("web.mode", c.Web.Mode, "view_only", "accounts"); err != nil {
300		errs = append(errs, err)
301	}
302	if err := oneOf("registration.mode", c.Registration.Mode, "closed", "invite", "open"); err != nil {
303		errs = append(errs, err)
304	}
305
306	for module, repo := range c.GoImport {
307		host, _, ok := strings.Cut(module, "/")
308		if !ok || host == "" || !strings.Contains(host, ".") {
309			errs = append(errs, fmt.Errorf("go_import key %q must be host/path (e.g. gitbay.org/gitbay)", module))
310		}
311		if parts := strings.Split(repo, "/"); len(parts) != 2 || parts[0] == "" || parts[1] == "" {
312			errs = append(errs, fmt.Errorf("go_import value %q must be owner/name", repo))
313		}
314	}
315
316	// Contradictions.
317	if c.Mail.SMTPHost != "" && c.Mail.From == "" {
318		errs = append(errs, errors.New("[mail] from is required when smtp_host is set"))
319	}
320	if c.Registration.Mode != "closed" && c.Mail.SMTPHost == "" {
321		errs = append(errs, fmt.Errorf(
322			"registration.mode = %q requires [mail] smtp_host: email verification cannot run without SMTP",
323			c.Registration.Mode))
324	}
325	if c.SSH.Mode == "system" && c.Registration.Mode != "closed" {
326		errs = append(errs, fmt.Errorf(
327			"ssh.mode = \"system\" requires registration.mode = \"closed\": host sshd rejects unknown keys before the dispatcher runs, so registration by unknown key is impossible"))
328	}
329	if c.Web.PasswordAuth && c.Web.Mode == "view_only" {
330		errs = append(errs, errors.New(
331			"web.password_auth = true is meaningless with web.mode = \"view_only\": no login route exists"))
332	}
333	if c.Web.PasswordAuth && c.Web.Mode == "accounts" {
334		errs = append(errs, errors.New(
335			"web.password_auth is not implemented yet; browser sessions are minted over SSH (gitbay web login)"))
336	}
337
338	return errors.Join(errs...)
339}
340
341// SiteHost returns the bare hostname from site_url (no scheme, port, path).
342func (c Config) SiteHost() string {
343	h := strings.TrimPrefix(strings.TrimPrefix(c.Server.SiteURL, "https://"), "http://")
344	h = strings.TrimSuffix(h, "/")
345	if i := strings.IndexByte(h, '/'); i >= 0 {
346		h = h[:i]
347	}
348	if host, _, err := net.SplitHostPort(h); err == nil {
349		return host
350	}
351	return h
352}
353
354// CheckHost performs environment probes that only make sense on the target
355// machine: port availability for the embedded listener and root existence.
356func (c Config) CheckHost() error {
357	var errs []error
358
359	if st, err := os.Stat(c.Server.Root); err != nil {
360		errs = append(errs, fmt.Errorf("server.root: %w", err))
361	} else if !st.IsDir() {
362		errs = append(errs, fmt.Errorf("server.root %q is not a directory", c.Server.Root))
363	}
364
365	if c.SSH.Mode == "embedded" {
366		addr := net.JoinHostPort("", strconv.Itoa(c.SSH.Port))
367		ln, err := net.Listen("tcp", addr)
368		if err != nil {
369			errs = append(errs, fmt.Errorf("ssh.port %d is not bindable (already in use by another daemon?): %w", c.SSH.Port, err))
370		} else {
371			ln.Close()
372		}
373	}
374
375	return errors.Join(errs...)
376}
377
378// TrustedProxyNets parses http.trusted_proxies; a bare address is a /32
379// or /128.
380func (h HTTP) TrustedProxyNets() ([]*net.IPNet, error) {
381	var nets []*net.IPNet
382	for _, p := range h.TrustedProxies {
383		if _, n, err := net.ParseCIDR(p); err == nil {
384			nets = append(nets, n)
385			continue
386		}
387		ip := net.ParseIP(p)
388		if ip == nil {
389			return nil, fmt.Errorf("http.trusted_proxies: %q is not an address or CIDR", p)
390		}
391		bits := 32
392		if ip.To4() == nil {
393			bits = 128
394		}
395		nets = append(nets, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)})
396	}
397	return nets, nil
398}