internal/config/config.go

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

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