internal/config/config.go

3af6fd1aaf69413d258a4131a627d048d2f1d290
gitbay/internal/config/config.go history · blame · raw

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