internal/config/config.go

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