internal/config/config.go

72920bdf0504bcee3d15305abc0724ae216d088c
gitbay/internal/config/config.go history · blame · raw

403 lines · 14554 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	MaxSnippetBytes int64 `toml:"max_snippet_bytes"` // per snippet file
180	// MaxSnippetsPerUser caps snippets an account may own. 0 means
181	// unlimited, like MaxReposPerUser.
182	MaxSnippetsPerUser int `toml:"max_snippets_per_user"`
183	CloneTimeoutSec    int `toml:"clone_timeout"`
184	SSHAuthRate        int `toml:"ssh_auth_rate"`
185	// APIRate is sustained JSON-API requests per minute per caller; writes
186	// draw on a tenth of it. 0 uses the default.
187	APIRate int `toml:"api_rate"`
188	// WriteRate is sustained mutating commands per minute per account,
189	// counted in the dispatcher so every surface shares one budget. 0 uses
190	// the default; a negative value turns the limit off.
191	WriteRate int `toml:"write_rate"`
192	// Per-account quotas on what a user owns directly (organizations are
193	// not capped). 0 means unlimited; admin user limits overrides per
194	// account.
195	MaxReposPerUser int   `toml:"max_repos_per_user"`
196	MaxBytesPerUser int64 `toml:"max_bytes_per_user"`
197}
198
199type Mail struct {
200	SMTPHost string `toml:"smtp_host"` // host:port (port defaults to 587)
201	From     string `toml:"from"`
202	SMTPUser string `toml:"smtp_user,omitempty"`
203	SMTPPass string `toml:"smtp_pass,omitempty"`
204}
205
206// Default returns the configuration used when a key is absent from the file.
207func Default() Config {
208	return Config{
209		Server: Server{Root: "/var/lib/gitbay"},
210		SSH:    SSH{Mode: "embedded", Port: 22},
211		HTTP:   HTTP{Addr: ":443", TLS: "acme", ACMEHTTPAddr: ":80"},
212		Web:    Web{Mode: "view_only"},
213		Registration: Registration{
214			Mode: "closed",
215		},
216		GitDaemon: GitDaemon{Port: 9418},
217		Mirrors:   Mirrors{PullIntervalMinutes: 15},
218		Deps:      Deps{CheckIntervalHours: 24},
219		Limits: Limits{
220			MaxPackBytes:    2 << 30, // 2 GiB
221			MaxBlobBytes:    100 << 20,
222			MaxAssetBytes:   512 << 20,
223			MaxSnippetBytes: 1 << 20,
224			CloneTimeoutSec: 3600,
225			SSHAuthRate:     10,
226			APIRate:         120,
227		},
228	}
229}
230
231// Load reads path, applies defaults, and validates. It does not probe the
232// host (see CheckHost) so it is safe in tests and on non-target machines.
233func Load(path string) (Config, error) {
234	cfg := Default()
235	md, err := toml.DecodeFile(path, &cfg)
236	if err != nil {
237		return cfg, err
238	}
239	if u := md.Undecoded(); len(u) > 0 {
240		return cfg, fmt.Errorf("unknown config key %q", u[0].String())
241	}
242	return cfg, cfg.Validate()
243}
244
245func oneOf(field, val string, allowed ...string) error {
246	for _, a := range allowed {
247		if val == a {
248			return nil
249		}
250	}
251	return fmt.Errorf("%s must be one of %v, got %q", field, allowed, val)
252}
253
254// Validate applies the static contradiction checks from the plan.
255func (c Config) Validate() error {
256	var errs []error
257
258	if c.Server.Root == "" {
259		errs = append(errs, errors.New("server.root is required"))
260	}
261	if d := c.Pages.Domain; d != "" {
262		if d == c.SiteHost() {
263			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"))
264		}
265		if strings.HasSuffix(c.SiteHost(), "."+d) {
266			errs = append(errs, errors.New("pages.domain must not be a parent of the site host"))
267		}
268	}
269	if c.Server.SiteURL == "" {
270		errs = append(errs, errors.New("server.site_url is required"))
271	}
272	if err := oneOf("ssh.mode", c.SSH.Mode, "embedded", "system"); err != nil {
273		errs = append(errs, err)
274	}
275	if c.Registration.PendingExpiry != "" {
276		if d, err := time.ParseDuration(c.Registration.PendingExpiry); err != nil || d <= 0 {
277			errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry))
278		}
279	}
280	if c.Limits.MaxReposPerUser < 0 || c.Limits.MaxBytesPerUser < 0 || c.Limits.MaxSnippetsPerUser < 0 {
281		errs = append(errs, errors.New("limits.max_repos_per_user, max_bytes_per_user and max_snippets_per_user must not be negative"))
282	}
283	if c.SSH.Port < 1 || c.SSH.Port > 65535 {
284		errs = append(errs, fmt.Errorf("ssh.port %d out of range", c.SSH.Port))
285	}
286	if err := oneOf("http.tls", c.HTTP.TLS, "acme", "files", "off"); err != nil {
287		errs = append(errs, err)
288	}
289	if _, err := c.HTTP.TrustedProxyNets(); err != nil {
290		errs = append(errs, err)
291	}
292	if c.HTTP.TLS == "files" && (c.HTTP.CertFile == "" || c.HTTP.KeyFile == "") {
293		errs = append(errs, errors.New("http.tls = \"files\" requires cert_file and key_file"))
294	}
295	if c.HTTP.TLS == "acme" {
296		host := c.SiteHost()
297		switch {
298		case !strings.HasPrefix(c.Server.SiteURL, "https://"):
299			errs = append(errs, errors.New("http.tls = \"acme\" requires an https:// site_url: certificates are issued for that host"))
300		case host == "" || host == "localhost" || net.ParseIP(host) != nil:
301			errs = append(errs, fmt.Errorf("http.tls = \"acme\" cannot issue a certificate for %q: use a public DNS name in site_url", host))
302		}
303	}
304	if err := oneOf("web.mode", c.Web.Mode, "view_only", "accounts"); err != nil {
305		errs = append(errs, err)
306	}
307	if err := oneOf("registration.mode", c.Registration.Mode, "closed", "invite", "open"); err != nil {
308		errs = append(errs, err)
309	}
310
311	for module, repo := range c.GoImport {
312		host, _, ok := strings.Cut(module, "/")
313		if !ok || host == "" || !strings.Contains(host, ".") {
314			errs = append(errs, fmt.Errorf("go_import key %q must be host/path (e.g. gitbay.org/gitbay)", module))
315		}
316		if parts := strings.Split(repo, "/"); len(parts) != 2 || parts[0] == "" || parts[1] == "" {
317			errs = append(errs, fmt.Errorf("go_import value %q must be owner/name", repo))
318		}
319	}
320
321	// Contradictions.
322	if c.Mail.SMTPHost != "" && c.Mail.From == "" {
323		errs = append(errs, errors.New("[mail] from is required when smtp_host is set"))
324	}
325	if c.Registration.Mode != "closed" && c.Mail.SMTPHost == "" {
326		errs = append(errs, fmt.Errorf(
327			"registration.mode = %q requires [mail] smtp_host: email verification cannot run without SMTP",
328			c.Registration.Mode))
329	}
330	if c.SSH.Mode == "system" && c.Registration.Mode != "closed" {
331		errs = append(errs, fmt.Errorf(
332			"ssh.mode = \"system\" requires registration.mode = \"closed\": host sshd rejects unknown keys before the dispatcher runs, so registration by unknown key is impossible"))
333	}
334	if c.Web.PasswordAuth && c.Web.Mode == "view_only" {
335		errs = append(errs, errors.New(
336			"web.password_auth = true is meaningless with web.mode = \"view_only\": no login route exists"))
337	}
338	if c.Web.PasswordAuth && c.Web.Mode == "accounts" {
339		errs = append(errs, errors.New(
340			"web.password_auth is not implemented yet; browser sessions are minted over SSH (gitbay web login)"))
341	}
342
343	return errors.Join(errs...)
344}
345
346// SiteHost returns the bare hostname from site_url (no scheme, port, path).
347func (c Config) SiteHost() string {
348	h := strings.TrimPrefix(strings.TrimPrefix(c.Server.SiteURL, "https://"), "http://")
349	h = strings.TrimSuffix(h, "/")
350	if i := strings.IndexByte(h, '/'); i >= 0 {
351		h = h[:i]
352	}
353	if host, _, err := net.SplitHostPort(h); err == nil {
354		return host
355	}
356	return h
357}
358
359// CheckHost performs environment probes that only make sense on the target
360// machine: port availability for the embedded listener and root existence.
361func (c Config) CheckHost() error {
362	var errs []error
363
364	if st, err := os.Stat(c.Server.Root); err != nil {
365		errs = append(errs, fmt.Errorf("server.root: %w", err))
366	} else if !st.IsDir() {
367		errs = append(errs, fmt.Errorf("server.root %q is not a directory", c.Server.Root))
368	}
369
370	if c.SSH.Mode == "embedded" {
371		addr := net.JoinHostPort("", strconv.Itoa(c.SSH.Port))
372		ln, err := net.Listen("tcp", addr)
373		if err != nil {
374			errs = append(errs, fmt.Errorf("ssh.port %d is not bindable (already in use by another daemon?): %w", c.SSH.Port, err))
375		} else {
376			ln.Close()
377		}
378	}
379
380	return errors.Join(errs...)
381}
382
383// TrustedProxyNets parses http.trusted_proxies; a bare address is a /32
384// or /128.
385func (h HTTP) TrustedProxyNets() ([]*net.IPNet, error) {
386	var nets []*net.IPNet
387	for _, p := range h.TrustedProxies {
388		if _, n, err := net.ParseCIDR(p); err == nil {
389			nets = append(nets, n)
390			continue
391		}
392		ip := net.ParseIP(p)
393		if ip == nil {
394			return nil, fmt.Errorf("http.trusted_proxies: %q is not an address or CIDR", p)
395		}
396		bits := 32
397		if ip.To4() == nil {
398			bits = 128
399		}
400		nets = append(nets, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)})
401	}
402	return nets, nil
403}