internal/config/config.go

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