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