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