internal/config/config.go

4744c629ed4f0158bdea7d0f1d207fdccb1f7f99
gitbay/internal/config/config.go history · blame · raw

291 lines · 9808 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	// APIRate is sustained JSON-API requests per minute per caller; writes
118	// draw on a tenth of it. 0 uses the default.
119	APIRate int `toml:"api_rate"`
120}
121
122type Mail struct {
123	SMTPHost string `toml:"smtp_host"` // host:port (port defaults to 587)
124	From     string `toml:"from"`
125	SMTPUser string `toml:"smtp_user,omitempty"`
126	SMTPPass string `toml:"smtp_pass,omitempty"`
127}
128
129// Default returns the configuration used when a key is absent from the file.
130func Default() Config {
131	return Config{
132		Server: Server{Root: "/var/lib/gitbay"},
133		SSH:    SSH{Mode: "embedded", Port: 22},
134		HTTP:   HTTP{Addr: ":443", TLS: "acme", ACMEHTTPAddr: ":80"},
135		Web:    Web{Mode: "view_only"},
136		Registration: Registration{
137			Mode: "closed",
138		},
139		GitDaemon: GitDaemon{Port: 9418},
140		Mirrors:   Mirrors{PullIntervalMinutes: 15},
141		Limits: Limits{
142			MaxPackBytes:    2 << 30, // 2 GiB
143			MaxBlobBytes:    100 << 20,
144			MaxAssetBytes:   512 << 20,
145			CloneTimeoutSec: 3600,
146			SSHAuthRate:     10,
147			APIRate:         120,
148		},
149	}
150}
151
152// Load reads path, applies defaults, and validates. It does not probe the
153// host (see CheckHost) so it is safe in tests and on non-target machines.
154func Load(path string) (Config, error) {
155	cfg := Default()
156	md, err := toml.DecodeFile(path, &cfg)
157	if err != nil {
158		return cfg, err
159	}
160	if u := md.Undecoded(); len(u) > 0 {
161		return cfg, fmt.Errorf("unknown config key %q", u[0].String())
162	}
163	return cfg, cfg.Validate()
164}
165
166func oneOf(field, val string, allowed ...string) error {
167	for _, a := range allowed {
168		if val == a {
169			return nil
170		}
171	}
172	return fmt.Errorf("%s must be one of %v, got %q", field, allowed, val)
173}
174
175// Validate applies the static contradiction checks from the plan.
176func (c Config) Validate() error {
177	var errs []error
178
179	if c.Server.Root == "" {
180		errs = append(errs, errors.New("server.root is required"))
181	}
182	if d := c.Pages.Domain; d != "" {
183		if d == c.SiteHost() {
184			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"))
185		}
186		if strings.HasSuffix(c.SiteHost(), "."+d) {
187			errs = append(errs, errors.New("pages.domain must not be a parent of the site host"))
188		}
189	}
190	if c.Server.SiteURL == "" {
191		errs = append(errs, errors.New("server.site_url is required"))
192	}
193	if err := oneOf("ssh.mode", c.SSH.Mode, "embedded", "system"); err != nil {
194		errs = append(errs, err)
195	}
196	if c.SSH.Port < 1 || c.SSH.Port > 65535 {
197		errs = append(errs, fmt.Errorf("ssh.port %d out of range", c.SSH.Port))
198	}
199	if err := oneOf("http.tls", c.HTTP.TLS, "acme", "files", "off"); err != nil {
200		errs = append(errs, err)
201	}
202	if c.HTTP.TLS == "files" && (c.HTTP.CertFile == "" || c.HTTP.KeyFile == "") {
203		errs = append(errs, errors.New("http.tls = \"files\" requires cert_file and key_file"))
204	}
205	if c.HTTP.TLS == "acme" {
206		host := c.SiteHost()
207		switch {
208		case !strings.HasPrefix(c.Server.SiteURL, "https://"):
209			errs = append(errs, errors.New("http.tls = \"acme\" requires an https:// site_url: certificates are issued for that host"))
210		case host == "" || host == "localhost" || net.ParseIP(host) != nil:
211			errs = append(errs, fmt.Errorf("http.tls = \"acme\" cannot issue a certificate for %q: use a public DNS name in site_url", host))
212		}
213	}
214	if err := oneOf("web.mode", c.Web.Mode, "view_only", "accounts"); err != nil {
215		errs = append(errs, err)
216	}
217	if err := oneOf("registration.mode", c.Registration.Mode, "closed", "invite", "open"); err != nil {
218		errs = append(errs, err)
219	}
220
221	for module, repo := range c.GoImport {
222		host, _, ok := strings.Cut(module, "/")
223		if !ok || host == "" || !strings.Contains(host, ".") {
224			errs = append(errs, fmt.Errorf("go_import key %q must be host/path (e.g. gitbay.org/gitbay)", module))
225		}
226		if parts := strings.Split(repo, "/"); len(parts) != 2 || parts[0] == "" || parts[1] == "" {
227			errs = append(errs, fmt.Errorf("go_import value %q must be owner/name", repo))
228		}
229	}
230
231	// Contradictions.
232	if c.Mail.SMTPHost != "" && c.Mail.From == "" {
233		errs = append(errs, errors.New("[mail] from is required when smtp_host is set"))
234	}
235	if c.Registration.Mode != "closed" && c.Mail.SMTPHost == "" {
236		errs = append(errs, fmt.Errorf(
237			"registration.mode = %q requires [mail] smtp_host: email verification cannot run without SMTP",
238			c.Registration.Mode))
239	}
240	if c.SSH.Mode == "system" && c.Registration.Mode != "closed" {
241		errs = append(errs, fmt.Errorf(
242			"ssh.mode = \"system\" requires registration.mode = \"closed\": host sshd rejects unknown keys before the dispatcher runs, so registration by unknown key is impossible"))
243	}
244	if c.Web.PasswordAuth && c.Web.Mode == "view_only" {
245		errs = append(errs, errors.New(
246			"web.password_auth = true is meaningless with web.mode = \"view_only\": no login route exists"))
247	}
248	if c.Web.PasswordAuth && c.Web.Mode == "accounts" {
249		errs = append(errs, errors.New(
250			"web.password_auth is not implemented yet; browser sessions are minted over SSH (gitbay web login)"))
251	}
252
253	return errors.Join(errs...)
254}
255
256// SiteHost returns the bare hostname from site_url (no scheme, port, path).
257func (c Config) SiteHost() string {
258	h := strings.TrimPrefix(strings.TrimPrefix(c.Server.SiteURL, "https://"), "http://")
259	h = strings.TrimSuffix(h, "/")
260	if i := strings.IndexByte(h, '/'); i >= 0 {
261		h = h[:i]
262	}
263	if host, _, err := net.SplitHostPort(h); err == nil {
264		return host
265	}
266	return h
267}
268
269// CheckHost performs environment probes that only make sense on the target
270// machine: port availability for the embedded listener and root existence.
271func (c Config) CheckHost() error {
272	var errs []error
273
274	if st, err := os.Stat(c.Server.Root); err != nil {
275		errs = append(errs, fmt.Errorf("server.root: %w", err))
276	} else if !st.IsDir() {
277		errs = append(errs, fmt.Errorf("server.root %q is not a directory", c.Server.Root))
278	}
279
280	if c.SSH.Mode == "embedded" {
281		addr := net.JoinHostPort("", strconv.Itoa(c.SSH.Port))
282		ln, err := net.Listen("tcp", addr)
283		if err != nil {
284			errs = append(errs, fmt.Errorf("ssh.port %d is not bindable (already in use by another daemon?): %w", c.SSH.Port, err))
285		} else {
286			ln.Close()
287		}
288	}
289
290	return errors.Join(errs...)
291}