internal/config/config.go
782 lines · 28617 bytes
1// Package config loads and validates the gitbayd server configuration.
2package config
3
4import (
5 "crypto/ecdsa"
6 "crypto/x509"
7 "encoding/pem"
8 "errors"
9 "fmt"
10 "io"
11 "math"
12 "net"
13 "os"
14 "path/filepath"
15 "strconv"
16 "strings"
17 "time"
18
19 "filippo.io/age"
20 "github.com/BurntSushi/toml"
21)
22
23// DefaultWriteRate is the per-account write budget when the config leaves
24// write_rate at zero: generous for a person at a terminal, and a bound on
25// what one account can enqueue — every write also queues notification mail
26// and webhook deliveries.
27const DefaultWriteRate = 60
28
29// Pack generation defaults for a four-core host: a full clone of a large
30// repository runs git at about 1.5 cores (Performance wiki page).
31const (
32 DefaultPackConcurrency = 3
33 DefaultPackPerPrincipal = 2
34 DefaultPackQueue = 32
35 DefaultPackQueueWait = time.Minute
36)
37
38type Config struct {
39 Server Server `toml:"server"`
40 SSH SSH `toml:"ssh"`
41 HTTP HTTP `toml:"http"`
42 GitDaemon GitDaemon `toml:"git_daemon"`
43 Web Web `toml:"web"`
44 Registration Registration `toml:"registration"`
45 API API `toml:"api"`
46 Webhooks Webhooks `toml:"webhooks"`
47 Pages Pages `toml:"pages"`
48 LFS LFS `toml:"lfs"`
49 Limits Limits `toml:"limits"`
50 Mail Mail `toml:"mail"`
51 Mirrors Mirrors `toml:"mirrors"`
52 Deps Deps `toml:"deps"`
53 Retention Retention `toml:"retention"`
54 Push Push `toml:"push"`
55 Backup Backup `toml:"backup"`
56 // GoImport maps vanity Go module paths to repositories, e.g.
57 // "gitbay.org/gitbay" = "krz/gitbay". Requests carrying ?go-get=1
58 // under a mapped path get a go-import meta tag.
59 GoImport map[string]string `toml:"go_import"`
60}
61
62type Server struct {
63 Root string `toml:"root"`
64 SiteURL string `toml:"site_url"`
65
66 // SourceRepo names the repository this instance develops itself in, as
67 // "owner/name". When set, startup warns if the running build's commit is
68 // not on that repository's default branch. Empty disables the check, which
69 // is right for any instance that does not host its own source.
70 SourceRepo string `toml:"source_repo"`
71
72 // SecretKeyFile holds the keys that seal the secret columns of the
73 // database (internal/seal). It lives outside Root, so neither a
74 // backup archive nor a snapshot of Root carries it.
75 SecretKeyFile string `toml:"secret_key_file"`
76}
77
78type SSH struct {
79 Mode string `toml:"mode"` // embedded | system
80 Port int `toml:"port"`
81 HostKeys []string `toml:"host_keys"`
82}
83
84type HTTP struct {
85 Addr string `toml:"addr"`
86 TLS string `toml:"tls"` // acme | files | off
87 CertFile string `toml:"cert_file"`
88 KeyFile string `toml:"key_file"`
89 // ACME (Let's Encrypt by default). Certificates are cached under
90 // server.root/acme. acme_http_addr serves HTTP-01 challenges and
91 // redirects to HTTPS; "off" disables it (TLS-ALPN-01 on the HTTPS
92 // port still works).
93 ACMEEmail string `toml:"acme_email"`
94 ACMEHTTPAddr string `toml:"acme_http_addr"`
95 // TrustedProxies are the addresses or CIDRs of reverse proxies in front
96 // of this process. A request from one of them is attributed to the
97 // last X-Forwarded-For hop that is not itself a trusted proxy; from
98 // anyone else the peer address is the client and the header is
99 // ignored. Empty means no proxy, which is how gitbayd is deployed by
100 // default: it terminates TLS itself.
101 TrustedProxies []string `toml:"trusted_proxies,omitempty"`
102}
103
104type GitDaemon struct {
105 Enabled bool `toml:"enabled"`
106 Port int `toml:"port"`
107}
108
109type Web struct {
110 Mode string `toml:"mode"` // view_only | accounts
111 PasswordAuth bool `toml:"password_auth"`
112 // Title is the instance's display name in the header and page titles.
113 // Empty falls back to the site host.
114 Title string `toml:"title"`
115 // PrivacyNotice is operator-provided text shown on /privacy under the
116 // fixed project-level statement. Plain text; blank paragraphs split.
117 PrivacyNotice string `toml:"privacy_notice"`
118}
119
120type Registration struct {
121 Mode string `toml:"mode"` // closed | invite | open
122 // PendingExpiry is how long a self-registered account may stay
123 // unverified before it is removed, as a duration ("168h"). Empty
124 // keeps such accounts forever.
125 PendingExpiry string `toml:"pending_expiry"`
126 // NotifyAdmin mails the instance's admins when an account becomes
127 // active: an invite redeemed, or an open-mode signup that verified
128 // its address. The unverified row an open signup creates is not
129 // reported — anyone can post the form, so mailing on that would
130 // aim a flood at the admins (#234).
131 NotifyAdmin bool `toml:"notify_admin"`
132}
133
134// PendingExpiryDuration parses PendingExpiry; zero means never.
135func (r Registration) PendingExpiryDuration() time.Duration {
136 d, _ := time.ParseDuration(r.PendingExpiry)
137 return d
138}
139
140// Retention is how long the append-only tables keep a row. Each is a
141// duration string ("2160h"); empty or zero keeps forever, which is what
142// an instance that has never configured this gets. Expired sessions and
143// tokens are swept regardless: they are dead weight the moment they
144// expire and no setting makes them worth keeping.
145type Retention struct {
146 Audit string `toml:"audit"`
147 Events string `toml:"events"`
148 WebhookDeliveries string `toml:"webhook_deliveries"`
149 // Mail is the outbound queue: rows already sent or given up on.
150 Mail string `toml:"mail"`
151 // Push is the outbound device queue: rows already sent or given up on.
152 Push string `toml:"push"`
153}
154
155// Durations parses the five, mapping each to zero when unset or bad.
156func (r Retention) Durations() (audit, events, deliveries, mail, push time.Duration) {
157 parse := func(s string) time.Duration {
158 d, err := time.ParseDuration(s)
159 if err != nil || d < 0 {
160 return 0
161 }
162 return d
163 }
164 return parse(r.Audit), parse(r.Events), parse(r.WebhookDeliveries), parse(r.Mail), parse(r.Push)
165}
166
167// LFS stores large-file objects content-addressed under Root (default
168// <server.root>/lfs). MaxObjectBytes caps a single object; 0 means the
169// 512MB default.
170type LFS struct {
171 Root string `toml:"root"`
172 MaxObjectBytes int64 `toml:"max_object_bytes"`
173}
174
175// Pages serves each public repo's `pages` branch as a static site on
176// <owner>.<domain> — a separate origin, so page-authored scripts never run
177// on the forge's own host. Empty domain disables the feature.
178type Pages struct {
179 Domain string `toml:"domain"`
180}
181
182// API controls the HTTPS/JSON control-plane API (bearer tokens minted over
183// SSH). Off by default: an instance that never enables it has no
184// credential-bearing HTTP surface at all.
185type API struct {
186 Enabled bool `toml:"enabled"`
187}
188
189// Webhooks controls outbound delivery. AllowLocal permits endpoints on
190// loopback/private addresses (off by default: SSRF).
191type Webhooks struct {
192 AllowLocal bool `toml:"allow_local"`
193}
194
195type Mirrors struct {
196 PullIntervalMinutes int `toml:"pull_interval_minutes"`
197}
198
199// Deps configures the dependency-update sweep. It runs only for repos that
200// have opted in with `repo deps enable`, because checking a private repo
201// tells a public registry what it depends on.
202type Deps struct {
203 CheckIntervalHours int `toml:"check_interval_hours"`
204}
205
206type Limits struct {
207 MaxPackBytes int64 `toml:"max_pack_bytes"`
208 MaxBlobBytes int64 `toml:"max_blob_bytes"`
209 MaxAssetBytes int64 `toml:"max_asset_bytes"` // per release asset
210 MaxSnippetBytes int64 `toml:"max_snippet_bytes"` // per snippet file
211 // MaxSnippetsPerUser caps snippets an account may own. 0 means
212 // unlimited, like MaxReposPerUser.
213 MaxSnippetsPerUser int `toml:"max_snippets_per_user"`
214 CloneTimeoutSec int `toml:"clone_timeout"`
215 SSHAuthRate int `toml:"ssh_auth_rate"`
216 // APIRate is sustained JSON-API requests per minute per caller; writes
217 // draw on a tenth of it. 0 uses the default.
218 APIRate int `toml:"api_rate"`
219 // WriteRate is sustained mutating commands per minute per account,
220 // counted in the dispatcher so every surface shares one budget. 0 uses
221 // the default; a negative value turns the limit off.
222 WriteRate int `toml:"write_rate"`
223 // Per-account quotas on what a user owns directly (organizations are
224 // not capped). 0 means unlimited; admin user limits overrides per
225 // account.
226 MaxReposPerUser int `toml:"max_repos_per_user"`
227 MaxBytesPerUser int64 `toml:"max_bytes_per_user"`
228 // PackConcurrency caps git pack generation (upload-pack and
229 // upload-archive) running at once across SSH, smart HTTP and git://.
230 // PackPerPrincipal caps it per account, or per client address on the
231 // anonymous transports. PackQueue is how many may wait for a slot,
232 // for at most PackQueueWait ("60s"). For the three counts 0 takes the
233 // default and a negative value turns that bound off.
234 PackConcurrency int `toml:"pack_concurrency"`
235 PackPerPrincipal int `toml:"pack_per_principal"`
236 PackQueue int `toml:"pack_queue"`
237 PackQueueWait string `toml:"pack_queue_wait"`
238}
239
240// PackLimits resolves the pack_* settings for packlimit.New. A zero
241// max or per is no bound; an unbounded queue is math.MaxInt, since
242// packlimit reads a zero queue as no queue at all.
243func (l Limits) PackLimits() (max, per, queue int, wait time.Duration) {
244 pick := func(v, def int) int {
245 switch {
246 case v == 0:
247 return def
248 case v < 0:
249 return 0
250 }
251 return v
252 }
253 queue = pick(l.PackQueue, DefaultPackQueue)
254 if l.PackQueue < 0 {
255 queue = math.MaxInt
256 }
257 wait = DefaultPackQueueWait
258 if d, err := time.ParseDuration(l.PackQueueWait); err == nil && d > 0 {
259 wait = d
260 }
261 return pick(l.PackConcurrency, DefaultPackConcurrency),
262 pick(l.PackPerPrincipal, DefaultPackPerPrincipal), queue, wait
263}
264
265type Mail struct {
266 SMTPHost string `toml:"smtp_host"` // host:port (port defaults to 587, 465 with tls = "implicit")
267 From string `toml:"from"`
268 SMTPUser string `toml:"smtp_user,omitempty"`
269 SMTPPass string `toml:"smtp_pass,omitempty"`
270 // RequireTLS fails delivery when the relay does not offer STARTTLS,
271 // instead of sending in clear. Unset, it is on for any relay but
272 // localhost or a loopback address (TLSRequired).
273 RequireTLS *bool `toml:"require_tls,omitempty"`
274 // TLS is "starttls" (the default, also when empty) or "implicit":
275 // TLS from the first byte, as relays on port 465 expect.
276 TLS string `toml:"tls,omitempty"`
277 // Inbound polls a mailbox for replies to notification mail (#295).
278 Inbound MailInbound `toml:"inbound"`
279}
280
281// MailInbound is the IMAP mailbox replies to notification mail arrive
282// in. Off unless enabled. The connection is always encrypted; there is
283// no setting for plaintext.
284type MailInbound struct {
285 Enabled bool `toml:"enabled"`
286 // IMAPHost is host:port; the port defaults to 993 with tls =
287 // "implicit" (the default) and 143 with tls = "starttls".
288 IMAPHost string `toml:"imap_host"`
289 TLS string `toml:"tls"`
290 User string `toml:"user"`
291 // PasswordFile holds the mailbox password, read at each connection.
292 // Never inline in this file.
293 PasswordFile string `toml:"password_file"`
294 Mailbox string `toml:"mailbox"` // default INBOX
295 PollInterval string `toml:"poll_interval"` // default 1m
296 // ReplyAddress is the address a notification's Reply-To is built
297 // from: reply@example.org becomes reply+<token>@example.org, so the
298 // mailbox must receive plus-addressed mail for it (or a catch-all).
299 ReplyAddress string `toml:"reply_address"`
300 // TrustedAuthservID is the authserv-id the mail host writes in its
301 // Authentication-Results header. When set, a reply must carry DMARC
302 // pass, or an aligned DKIM pass, in the topmost such header. Only
303 // safe when the mail host removes incoming headers claiming its id.
304 TrustedAuthservID string `toml:"trusted_authserv_id"`
305 // RequireDKIM makes a reply need a DKIM signature, verified by
306 // gitbayd, that covers From and whose d= is in relaxed alignment
307 // with the From domain. With TrustedAuthservID also set, either
308 // passing is enough.
309 RequireDKIM bool `toml:"require_dkim"`
310}
311
312// Authenticated reports whether a reply's From is checked at all.
313func (m MailInbound) Authenticated() bool {
314 return m.TrustedAuthservID != "" || m.RequireDKIM
315}
316
317// DefaultInboundPoll is the poll interval when poll_interval is unset.
318const DefaultInboundPoll = time.Minute
319
320// Poll is the configured poll interval.
321func (m MailInbound) Poll() time.Duration {
322 if d, err := time.ParseDuration(m.PollInterval); err == nil && d > 0 {
323 return d
324 }
325 return DefaultInboundPoll
326}
327
328// Addr is IMAPHost with the default port filled in.
329func (m MailInbound) Addr() string {
330 if _, _, err := net.SplitHostPort(m.IMAPHost); err == nil {
331 return m.IMAPHost
332 }
333 if m.TLS == "starttls" {
334 return net.JoinHostPort(m.IMAPHost, "143")
335 }
336 return net.JoinHostPort(m.IMAPHost, "993")
337}
338
339// MailboxName is Mailbox, INBOX when unset.
340func (m MailInbound) MailboxName() string {
341 if m.Mailbox == "" {
342 return "INBOX"
343 }
344 return m.Mailbox
345}
346
347// Password reads PasswordFile: its first line, which must be all it
348// holds. The file must be readable by its owner alone.
349func (m MailInbound) Password() (string, error) {
350 f, err := os.Open(m.PasswordFile)
351 if err != nil {
352 return "", fmt.Errorf("mail.inbound.password_file: %w", err)
353 }
354 defer f.Close()
355 fi, err := f.Stat()
356 if err != nil {
357 return "", fmt.Errorf("mail.inbound.password_file: %w", err)
358 }
359 if perm := fi.Mode().Perm(); perm&0o077 != 0 {
360 return "", fmt.Errorf("mail.inbound.password_file %s is mode %04o; it must be readable by its owner alone (0600)", m.PasswordFile, perm)
361 }
362 raw, err := io.ReadAll(io.LimitReader(f, 4097))
363 if err != nil {
364 return "", fmt.Errorf("mail.inbound.password_file: %w", err)
365 }
366 pass := strings.TrimRight(string(raw), "\r\n")
367 if pass == "" || len(raw) > 4096 || strings.ContainsAny(pass, "\r\n") {
368 return "", fmt.Errorf("mail.inbound.password_file %s must hold the password on one line", m.PasswordFile)
369 }
370 return pass, nil
371}
372
373func (m MailInbound) validate() []error {
374 if !m.Enabled {
375 return nil
376 }
377 var errs []error
378 for _, f := range []struct{ name, val string }{
379 {"mail.inbound.imap_host", m.IMAPHost},
380 {"mail.inbound.user", m.User},
381 {"mail.inbound.password_file", m.PasswordFile},
382 {"mail.inbound.reply_address", m.ReplyAddress},
383 } {
384 if f.val == "" {
385 errs = append(errs, fmt.Errorf("%s is required when mail.inbound.enabled", f.name))
386 }
387 }
388 if t := m.TLS; t != "" && t != "implicit" && t != "starttls" {
389 errs = append(errs, fmt.Errorf("mail.inbound.tls must be implicit or starttls, got %q: IMAP in clear is not supported", t))
390 }
391 if m.PollInterval != "" {
392 if d, err := time.ParseDuration(m.PollInterval); err != nil || d < 10*time.Second {
393 errs = append(errs, fmt.Errorf("mail.inbound.poll_interval %q must be a duration of at least 10s", m.PollInterval))
394 }
395 }
396 if id := m.TrustedAuthservID; id != "" && strings.ContainsAny(id, " \t;()\"\r\n") {
397 errs = append(errs, fmt.Errorf("mail.inbound.trusted_authserv_id %q must be a bare host name such as mx.google.com", id))
398 }
399 if a := m.ReplyAddress; a != "" {
400 local, domain, ok := strings.Cut(a, "@")
401 if !ok || local == "" || domain == "" || strings.ContainsAny(a, "+ <>\"\r\n") || strings.Contains(domain, "@") {
402 errs = append(errs, fmt.Errorf("mail.inbound.reply_address %q must be a bare address such as reply@example.org, with no + in it", a))
403 }
404 }
405 return errs
406}
407
408// TLSRequired reports whether mail must not go to the relay in clear.
409func (m Mail) TLSRequired() bool {
410 if m.RequireTLS != nil {
411 return *m.RequireTLS
412 }
413 host := m.SMTPHost
414 if h, _, err := net.SplitHostPort(host); err == nil {
415 host = h
416 }
417 host = strings.Trim(host, "[]")
418 if host == "localhost" {
419 return false
420 }
421 ip := net.ParseIP(host)
422 return ip == nil || !ip.IsLoopback()
423}
424
425// Push is APNs delivery to registered Apple devices. A key belongs to a
426// bundle ID, so an instance pushes to the app built under the topic named
427// here and no other; a self-hoster points this at their own key and their
428// own build.
429type Push struct {
430 Enabled bool `toml:"enabled"`
431 KeyFile string `toml:"key_file"`
432 KeyID string `toml:"key_id"`
433 TeamID string `toml:"team_id"`
434 Topic string `toml:"topic"` // the app's bundle identifier
435 // Environment is a name rather than a URL so a typo cannot aim the
436 // key at a host that is not Apple's.
437 Environment string `toml:"environment"` // production | sandbox
438}
439
440// Host is the APNs endpoint for the configured environment.
441// GITBAY_APNS_HOST overrides it for tests, as GITBAY_SWEEP_TICK does for
442// the retention sweep.
443func (p Push) Host() string {
444 if h := os.Getenv("GITBAY_APNS_HOST"); h != "" {
445 return h
446 }
447 if p.Environment == "sandbox" {
448 return "api.sandbox.push.apple.com"
449 }
450 return "api.push.apple.com"
451}
452
453// LoadAPNSKey reads Apple's .p8 provider key: a PEM-wrapped PKCS#8
454// P-256 private key. Read at startup and validated there, so a
455// misconfigured [push] refuses to start rather than filling a queue
456// nobody is watching.
457func LoadAPNSKey(path string) (*ecdsa.PrivateKey, error) {
458 data, err := os.ReadFile(path)
459 if err != nil {
460 return nil, err
461 }
462 block, _ := pem.Decode(data)
463 if block == nil {
464 return nil, errors.New("not PEM")
465 }
466 any, err := x509.ParsePKCS8PrivateKey(block.Bytes)
467 if err != nil {
468 return nil, err
469 }
470 key, ok := any.(*ecdsa.PrivateKey)
471 if !ok {
472 return nil, errors.New("not an EC private key")
473 }
474 return key, nil
475}
476
477// Backup configures gitbayd admin backup.
478type Backup struct {
479 // AgeRecipients, when set, encrypts every archive to these age
480 // public keys (age1...). The matching identities stay off the host,
481 // so the host writes archives it cannot read.
482 AgeRecipients []string `toml:"age_recipients"`
483}
484
485// Recipients parses AgeRecipients.
486func (b Backup) Recipients() ([]age.Recipient, error) {
487 var rs []age.Recipient
488 for _, s := range b.AgeRecipients {
489 r, err := age.ParseX25519Recipient(s)
490 if err != nil {
491 return nil, fmt.Errorf("backup.age_recipients: %q: %w", s, err)
492 }
493 rs = append(rs, r)
494 }
495 return rs, nil
496}
497
498// Default returns the configuration used when a key is absent from the file.
499func Default() Config {
500 return Config{
501 Server: Server{Root: "/var/lib/gitbay", SecretKeyFile: "/etc/gitbay/secret.key"},
502 SSH: SSH{Mode: "embedded", Port: 22},
503 HTTP: HTTP{Addr: ":443", TLS: "acme", ACMEHTTPAddr: ":80"},
504 Web: Web{Mode: "view_only"},
505 Registration: Registration{
506 Mode: "closed",
507 },
508 GitDaemon: GitDaemon{Port: 9418},
509 Mirrors: Mirrors{PullIntervalMinutes: 15},
510 Deps: Deps{CheckIntervalHours: 24},
511 Limits: Limits{
512 MaxPackBytes: 2 << 30, // 2 GiB
513 MaxBlobBytes: 100 << 20,
514 MaxAssetBytes: 512 << 20,
515 MaxSnippetBytes: 1 << 20,
516 CloneTimeoutSec: 3600,
517 SSHAuthRate: 10,
518 APIRate: 120,
519 },
520 }
521}
522
523// Load reads path, applies defaults, and validates. It does not probe the
524// host (see CheckHost) so it is safe in tests and on non-target machines.
525func Load(path string) (Config, error) {
526 cfg := Default()
527 md, err := toml.DecodeFile(path, &cfg)
528 if err != nil {
529 return cfg, err
530 }
531 if u := md.Undecoded(); len(u) > 0 {
532 return cfg, fmt.Errorf("unknown config key %q", u[0].String())
533 }
534 return cfg, cfg.Validate()
535}
536
537// Within reports whether path is dir or below it. Both are compared as
538// cleaned absolute paths (a relative path resolves against the working
539// directory, same as every other path in this config), with symlinks
540// resolved where the path exists on disk, so a path that reaches into dir
541// through a symlink, or through "..", is still reported as inside.
542func Within(dir, path string) bool {
543 dir, path = resolvePath(dir), resolvePath(path)
544 rel, err := filepath.Rel(dir, path)
545 return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
546}
547
548// resolvePath returns path as a cleaned absolute path, resolving symlinks in
549// it. The secret key file commonly does not exist yet (it is created by
550// `gitbayd admin secrets init`), and on this platform /var itself is a
551// symlink, so a whole-path resolution is tried first and, failing that, each
552// ancestor directory in turn, walking up to the nearest one that exists and
553// reattaching the missing suffix — a symlinked ancestor still resolves even
554// though the leaf, or several levels above it, does not exist.
555func resolvePath(path string) string {
556 abs, err := filepath.Abs(path)
557 if err != nil {
558 return filepath.Clean(path)
559 }
560 dir := abs
561 var suffix []string
562 for {
563 if resolved, err := filepath.EvalSymlinks(dir); err == nil {
564 for i := len(suffix) - 1; i >= 0; i-- {
565 resolved = filepath.Join(resolved, suffix[i])
566 }
567 return resolved
568 }
569 parent := filepath.Dir(dir)
570 if parent == dir {
571 return abs
572 }
573 suffix = append(suffix, filepath.Base(dir))
574 dir = parent
575 }
576}
577
578func oneOf(field, val string, allowed ...string) error {
579 for _, a := range allowed {
580 if val == a {
581 return nil
582 }
583 }
584 return fmt.Errorf("%s must be one of %v, got %q", field, allowed, val)
585}
586
587// Validate applies the static contradiction checks from the plan.
588func (c Config) Validate() error {
589 var errs []error
590
591 if c.Server.Root == "" {
592 errs = append(errs, errors.New("server.root is required"))
593 }
594 if d := c.Pages.Domain; d != "" {
595 if d == c.SiteHost() {
596 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"))
597 }
598 if strings.HasSuffix(c.SiteHost(), "."+d) {
599 errs = append(errs, errors.New("pages.domain must not be a parent of the site host"))
600 }
601 }
602 if c.Server.SiteURL == "" {
603 errs = append(errs, errors.New("server.site_url is required"))
604 }
605 switch {
606 case c.Server.SecretKeyFile == "":
607 errs = append(errs, errors.New("server.secret_key_file is required"))
608 case Within(c.Server.Root, c.Server.SecretKeyFile):
609 errs = append(errs, fmt.Errorf("server.secret_key_file %q is inside server.root: backups of the root would carry the key beside the values it seals", c.Server.SecretKeyFile))
610 }
611 if err := oneOf("ssh.mode", c.SSH.Mode, "embedded", "system"); err != nil {
612 errs = append(errs, err)
613 }
614 if c.Registration.PendingExpiry != "" {
615 if d, err := time.ParseDuration(c.Registration.PendingExpiry); err != nil || d <= 0 {
616 errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry))
617 }
618 }
619 if c.Limits.MaxReposPerUser < 0 || c.Limits.MaxBytesPerUser < 0 || c.Limits.MaxSnippetsPerUser < 0 {
620 errs = append(errs, errors.New("limits.max_repos_per_user, max_bytes_per_user and max_snippets_per_user must not be negative"))
621 }
622 if w := c.Limits.PackQueueWait; w != "" {
623 if d, err := time.ParseDuration(w); err != nil || d <= 0 {
624 errs = append(errs, fmt.Errorf("limits.pack_queue_wait %q must be a positive duration such as 60s", w))
625 }
626 }
627 if c.Push.Enabled {
628 for _, f := range []struct{ name, val string }{
629 {"push.key_file", c.Push.KeyFile},
630 {"push.key_id", c.Push.KeyID},
631 {"push.team_id", c.Push.TeamID},
632 {"push.topic", c.Push.Topic},
633 } {
634 if f.val == "" {
635 errs = append(errs, fmt.Errorf("%s is required when push.enabled", f.name))
636 }
637 }
638 if err := oneOf("push.environment", c.Push.Environment, "production", "sandbox"); err != nil {
639 errs = append(errs, err)
640 }
641 if c.Push.KeyFile != "" {
642 if _, err := LoadAPNSKey(c.Push.KeyFile); err != nil {
643 errs = append(errs, fmt.Errorf("push.key_file: %w", err))
644 }
645 }
646 }
647 if c.SSH.Port < 1 || c.SSH.Port > 65535 {
648 errs = append(errs, fmt.Errorf("ssh.port %d out of range", c.SSH.Port))
649 }
650 if err := oneOf("http.tls", c.HTTP.TLS, "acme", "files", "off"); err != nil {
651 errs = append(errs, err)
652 }
653 if _, err := c.HTTP.TrustedProxyNets(); err != nil {
654 errs = append(errs, err)
655 }
656 if c.HTTP.TLS == "files" && (c.HTTP.CertFile == "" || c.HTTP.KeyFile == "") {
657 errs = append(errs, errors.New("http.tls = \"files\" requires cert_file and key_file"))
658 }
659 if c.HTTP.TLS == "acme" {
660 host := c.SiteHost()
661 switch {
662 case !strings.HasPrefix(c.Server.SiteURL, "https://"):
663 errs = append(errs, errors.New("http.tls = \"acme\" requires an https:// site_url: certificates are issued for that host"))
664 case host == "" || host == "localhost" || net.ParseIP(host) != nil:
665 errs = append(errs, fmt.Errorf("http.tls = \"acme\" cannot issue a certificate for %q: use a public DNS name in site_url", host))
666 }
667 }
668 if err := oneOf("web.mode", c.Web.Mode, "view_only", "accounts"); err != nil {
669 errs = append(errs, err)
670 }
671 if err := oneOf("registration.mode", c.Registration.Mode, "closed", "invite", "open"); err != nil {
672 errs = append(errs, err)
673 }
674
675 for module, repo := range c.GoImport {
676 host, _, ok := strings.Cut(module, "/")
677 if !ok || host == "" || !strings.Contains(host, ".") {
678 errs = append(errs, fmt.Errorf("go_import key %q must be host/path (e.g. gitbay.org/gitbay)", module))
679 }
680 if parts := strings.Split(repo, "/"); len(parts) != 2 || parts[0] == "" || parts[1] == "" {
681 errs = append(errs, fmt.Errorf("go_import value %q must be owner/name", repo))
682 }
683 }
684
685 if _, err := c.Backup.Recipients(); err != nil {
686 errs = append(errs, err)
687 }
688
689 // Contradictions.
690 if c.Mail.SMTPHost != "" && c.Mail.From == "" {
691 errs = append(errs, errors.New("[mail] from is required when smtp_host is set"))
692 }
693 if t := c.Mail.TLS; t != "" && t != "starttls" && t != "implicit" {
694 errs = append(errs, fmt.Errorf("mail.tls must be starttls or implicit, got %q", t))
695 }
696 errs = append(errs, c.Mail.Inbound.validate()...)
697 if c.Mail.Inbound.Enabled && c.Mail.SMTPHost == "" {
698 errs = append(errs, errors.New("mail.inbound.enabled requires [mail] smtp_host: replies answer notification mail, which is not sent without SMTP"))
699 }
700 if c.Registration.Mode != "closed" && c.Mail.SMTPHost == "" {
701 errs = append(errs, fmt.Errorf(
702 "registration.mode = %q requires [mail] smtp_host: email verification cannot run without SMTP",
703 c.Registration.Mode))
704 }
705 if c.Registration.NotifyAdmin && c.Mail.SMTPHost == "" {
706 errs = append(errs, errors.New(
707 "registration.notify_admin = true requires [mail] smtp_host: there is nowhere to send the notice"))
708 }
709 if c.SSH.Mode == "system" && c.Registration.Mode != "closed" {
710 errs = append(errs, fmt.Errorf(
711 "ssh.mode = \"system\" requires registration.mode = \"closed\": host sshd rejects unknown keys before the dispatcher runs, so registration by unknown key is impossible"))
712 }
713 if c.Web.PasswordAuth && c.Web.Mode == "view_only" {
714 errs = append(errs, errors.New(
715 "web.password_auth = true is meaningless with web.mode = \"view_only\": no login route exists"))
716 }
717 if c.Web.PasswordAuth && c.Web.Mode == "accounts" {
718 errs = append(errs, errors.New(
719 "web.password_auth is not implemented yet; browser sessions are minted over SSH (gitbay web login)"))
720 }
721
722 return errors.Join(errs...)
723}
724
725// SiteHost returns the bare hostname from site_url (no scheme, port, path).
726func (c Config) SiteHost() string {
727 h := strings.TrimPrefix(strings.TrimPrefix(c.Server.SiteURL, "https://"), "http://")
728 h = strings.TrimSuffix(h, "/")
729 if i := strings.IndexByte(h, '/'); i >= 0 {
730 h = h[:i]
731 }
732 if host, _, err := net.SplitHostPort(h); err == nil {
733 return host
734 }
735 return h
736}
737
738// CheckHost performs environment probes that only make sense on the target
739// machine: port availability for the embedded listener and root existence.
740func (c Config) CheckHost() error {
741 var errs []error
742
743 if st, err := os.Stat(c.Server.Root); err != nil {
744 errs = append(errs, fmt.Errorf("server.root: %w", err))
745 } else if !st.IsDir() {
746 errs = append(errs, fmt.Errorf("server.root %q is not a directory", c.Server.Root))
747 }
748
749 if c.SSH.Mode == "embedded" {
750 addr := net.JoinHostPort("", strconv.Itoa(c.SSH.Port))
751 ln, err := net.Listen("tcp", addr)
752 if err != nil {
753 errs = append(errs, fmt.Errorf("ssh.port %d is not bindable (already in use by another daemon?): %w", c.SSH.Port, err))
754 } else {
755 ln.Close()
756 }
757 }
758
759 return errors.Join(errs...)
760}
761
762// TrustedProxyNets parses http.trusted_proxies; a bare address is a /32
763// or /128.
764func (h HTTP) TrustedProxyNets() ([]*net.IPNet, error) {
765 var nets []*net.IPNet
766 for _, p := range h.TrustedProxies {
767 if _, n, err := net.ParseCIDR(p); err == nil {
768 nets = append(nets, n)
769 continue
770 }
771 ip := net.ParseIP(p)
772 if ip == nil {
773 return nil, fmt.Errorf("http.trusted_proxies: %q is not an address or CIDR", p)
774 }
775 bits := 32
776 if ip.To4() == nil {
777 bits = 128
778 }
779 nets = append(nets, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)})
780 }
781 return nets, nil
782}