internal/config/config.go
772 lines · 28191 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}
306
307// DefaultInboundPoll is the poll interval when poll_interval is unset.
308const DefaultInboundPoll = time.Minute
309
310// Poll is the configured poll interval.
311func (m MailInbound) Poll() time.Duration {
312 if d, err := time.ParseDuration(m.PollInterval); err == nil && d > 0 {
313 return d
314 }
315 return DefaultInboundPoll
316}
317
318// Addr is IMAPHost with the default port filled in.
319func (m MailInbound) Addr() string {
320 if _, _, err := net.SplitHostPort(m.IMAPHost); err == nil {
321 return m.IMAPHost
322 }
323 if m.TLS == "starttls" {
324 return net.JoinHostPort(m.IMAPHost, "143")
325 }
326 return net.JoinHostPort(m.IMAPHost, "993")
327}
328
329// MailboxName is Mailbox, INBOX when unset.
330func (m MailInbound) MailboxName() string {
331 if m.Mailbox == "" {
332 return "INBOX"
333 }
334 return m.Mailbox
335}
336
337// Password reads PasswordFile: its first line, which must be all it
338// holds. The file must be readable by its owner alone.
339func (m MailInbound) Password() (string, error) {
340 f, err := os.Open(m.PasswordFile)
341 if err != nil {
342 return "", fmt.Errorf("mail.inbound.password_file: %w", err)
343 }
344 defer f.Close()
345 fi, err := f.Stat()
346 if err != nil {
347 return "", fmt.Errorf("mail.inbound.password_file: %w", err)
348 }
349 if perm := fi.Mode().Perm(); perm&0o077 != 0 {
350 return "", fmt.Errorf("mail.inbound.password_file %s is mode %04o; it must be readable by its owner alone (0600)", m.PasswordFile, perm)
351 }
352 raw, err := io.ReadAll(io.LimitReader(f, 4097))
353 if err != nil {
354 return "", fmt.Errorf("mail.inbound.password_file: %w", err)
355 }
356 pass := strings.TrimRight(string(raw), "\r\n")
357 if pass == "" || len(raw) > 4096 || strings.ContainsAny(pass, "\r\n") {
358 return "", fmt.Errorf("mail.inbound.password_file %s must hold the password on one line", m.PasswordFile)
359 }
360 return pass, nil
361}
362
363func (m MailInbound) validate() []error {
364 if !m.Enabled {
365 return nil
366 }
367 var errs []error
368 for _, f := range []struct{ name, val string }{
369 {"mail.inbound.imap_host", m.IMAPHost},
370 {"mail.inbound.user", m.User},
371 {"mail.inbound.password_file", m.PasswordFile},
372 {"mail.inbound.reply_address", m.ReplyAddress},
373 } {
374 if f.val == "" {
375 errs = append(errs, fmt.Errorf("%s is required when mail.inbound.enabled", f.name))
376 }
377 }
378 if t := m.TLS; t != "" && t != "implicit" && t != "starttls" {
379 errs = append(errs, fmt.Errorf("mail.inbound.tls must be implicit or starttls, got %q: IMAP in clear is not supported", t))
380 }
381 if m.PollInterval != "" {
382 if d, err := time.ParseDuration(m.PollInterval); err != nil || d < 10*time.Second {
383 errs = append(errs, fmt.Errorf("mail.inbound.poll_interval %q must be a duration of at least 10s", m.PollInterval))
384 }
385 }
386 if id := m.TrustedAuthservID; id != "" && strings.ContainsAny(id, " \t;()\"\r\n") {
387 errs = append(errs, fmt.Errorf("mail.inbound.trusted_authserv_id %q must be a bare host name such as mx.google.com", id))
388 }
389 if a := m.ReplyAddress; a != "" {
390 local, domain, ok := strings.Cut(a, "@")
391 if !ok || local == "" || domain == "" || strings.ContainsAny(a, "+ <>\"\r\n") || strings.Contains(domain, "@") {
392 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))
393 }
394 }
395 return errs
396}
397
398// TLSRequired reports whether mail must not go to the relay in clear.
399func (m Mail) TLSRequired() bool {
400 if m.RequireTLS != nil {
401 return *m.RequireTLS
402 }
403 host := m.SMTPHost
404 if h, _, err := net.SplitHostPort(host); err == nil {
405 host = h
406 }
407 host = strings.Trim(host, "[]")
408 if host == "localhost" {
409 return false
410 }
411 ip := net.ParseIP(host)
412 return ip == nil || !ip.IsLoopback()
413}
414
415// Push is APNs delivery to registered Apple devices. A key belongs to a
416// bundle ID, so an instance pushes to the app built under the topic named
417// here and no other; a self-hoster points this at their own key and their
418// own build.
419type Push struct {
420 Enabled bool `toml:"enabled"`
421 KeyFile string `toml:"key_file"`
422 KeyID string `toml:"key_id"`
423 TeamID string `toml:"team_id"`
424 Topic string `toml:"topic"` // the app's bundle identifier
425 // Environment is a name rather than a URL so a typo cannot aim the
426 // key at a host that is not Apple's.
427 Environment string `toml:"environment"` // production | sandbox
428}
429
430// Host is the APNs endpoint for the configured environment.
431// GITBAY_APNS_HOST overrides it for tests, as GITBAY_SWEEP_TICK does for
432// the retention sweep.
433func (p Push) Host() string {
434 if h := os.Getenv("GITBAY_APNS_HOST"); h != "" {
435 return h
436 }
437 if p.Environment == "sandbox" {
438 return "api.sandbox.push.apple.com"
439 }
440 return "api.push.apple.com"
441}
442
443// LoadAPNSKey reads Apple's .p8 provider key: a PEM-wrapped PKCS#8
444// P-256 private key. Read at startup and validated there, so a
445// misconfigured [push] refuses to start rather than filling a queue
446// nobody is watching.
447func LoadAPNSKey(path string) (*ecdsa.PrivateKey, error) {
448 data, err := os.ReadFile(path)
449 if err != nil {
450 return nil, err
451 }
452 block, _ := pem.Decode(data)
453 if block == nil {
454 return nil, errors.New("not PEM")
455 }
456 any, err := x509.ParsePKCS8PrivateKey(block.Bytes)
457 if err != nil {
458 return nil, err
459 }
460 key, ok := any.(*ecdsa.PrivateKey)
461 if !ok {
462 return nil, errors.New("not an EC private key")
463 }
464 return key, nil
465}
466
467// Backup configures gitbayd admin backup.
468type Backup struct {
469 // AgeRecipients, when set, encrypts every archive to these age
470 // public keys (age1...). The matching identities stay off the host,
471 // so the host writes archives it cannot read.
472 AgeRecipients []string `toml:"age_recipients"`
473}
474
475// Recipients parses AgeRecipients.
476func (b Backup) Recipients() ([]age.Recipient, error) {
477 var rs []age.Recipient
478 for _, s := range b.AgeRecipients {
479 r, err := age.ParseX25519Recipient(s)
480 if err != nil {
481 return nil, fmt.Errorf("backup.age_recipients: %q: %w", s, err)
482 }
483 rs = append(rs, r)
484 }
485 return rs, nil
486}
487
488// Default returns the configuration used when a key is absent from the file.
489func Default() Config {
490 return Config{
491 Server: Server{Root: "/var/lib/gitbay", SecretKeyFile: "/etc/gitbay/secret.key"},
492 SSH: SSH{Mode: "embedded", Port: 22},
493 HTTP: HTTP{Addr: ":443", TLS: "acme", ACMEHTTPAddr: ":80"},
494 Web: Web{Mode: "view_only"},
495 Registration: Registration{
496 Mode: "closed",
497 },
498 GitDaemon: GitDaemon{Port: 9418},
499 Mirrors: Mirrors{PullIntervalMinutes: 15},
500 Deps: Deps{CheckIntervalHours: 24},
501 Limits: Limits{
502 MaxPackBytes: 2 << 30, // 2 GiB
503 MaxBlobBytes: 100 << 20,
504 MaxAssetBytes: 512 << 20,
505 MaxSnippetBytes: 1 << 20,
506 CloneTimeoutSec: 3600,
507 SSHAuthRate: 10,
508 APIRate: 120,
509 },
510 }
511}
512
513// Load reads path, applies defaults, and validates. It does not probe the
514// host (see CheckHost) so it is safe in tests and on non-target machines.
515func Load(path string) (Config, error) {
516 cfg := Default()
517 md, err := toml.DecodeFile(path, &cfg)
518 if err != nil {
519 return cfg, err
520 }
521 if u := md.Undecoded(); len(u) > 0 {
522 return cfg, fmt.Errorf("unknown config key %q", u[0].String())
523 }
524 return cfg, cfg.Validate()
525}
526
527// Within reports whether path is dir or below it. Both are compared as
528// cleaned absolute paths (a relative path resolves against the working
529// directory, same as every other path in this config), with symlinks
530// resolved where the path exists on disk, so a path that reaches into dir
531// through a symlink, or through "..", is still reported as inside.
532func Within(dir, path string) bool {
533 dir, path = resolvePath(dir), resolvePath(path)
534 rel, err := filepath.Rel(dir, path)
535 return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
536}
537
538// resolvePath returns path as a cleaned absolute path, resolving symlinks in
539// it. The secret key file commonly does not exist yet (it is created by
540// `gitbayd admin secrets init`), and on this platform /var itself is a
541// symlink, so a whole-path resolution is tried first and, failing that, each
542// ancestor directory in turn, walking up to the nearest one that exists and
543// reattaching the missing suffix — a symlinked ancestor still resolves even
544// though the leaf, or several levels above it, does not exist.
545func resolvePath(path string) string {
546 abs, err := filepath.Abs(path)
547 if err != nil {
548 return filepath.Clean(path)
549 }
550 dir := abs
551 var suffix []string
552 for {
553 if resolved, err := filepath.EvalSymlinks(dir); err == nil {
554 for i := len(suffix) - 1; i >= 0; i-- {
555 resolved = filepath.Join(resolved, suffix[i])
556 }
557 return resolved
558 }
559 parent := filepath.Dir(dir)
560 if parent == dir {
561 return abs
562 }
563 suffix = append(suffix, filepath.Base(dir))
564 dir = parent
565 }
566}
567
568func oneOf(field, val string, allowed ...string) error {
569 for _, a := range allowed {
570 if val == a {
571 return nil
572 }
573 }
574 return fmt.Errorf("%s must be one of %v, got %q", field, allowed, val)
575}
576
577// Validate applies the static contradiction checks from the plan.
578func (c Config) Validate() error {
579 var errs []error
580
581 if c.Server.Root == "" {
582 errs = append(errs, errors.New("server.root is required"))
583 }
584 if d := c.Pages.Domain; d != "" {
585 if d == c.SiteHost() {
586 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"))
587 }
588 if strings.HasSuffix(c.SiteHost(), "."+d) {
589 errs = append(errs, errors.New("pages.domain must not be a parent of the site host"))
590 }
591 }
592 if c.Server.SiteURL == "" {
593 errs = append(errs, errors.New("server.site_url is required"))
594 }
595 switch {
596 case c.Server.SecretKeyFile == "":
597 errs = append(errs, errors.New("server.secret_key_file is required"))
598 case Within(c.Server.Root, c.Server.SecretKeyFile):
599 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))
600 }
601 if err := oneOf("ssh.mode", c.SSH.Mode, "embedded", "system"); err != nil {
602 errs = append(errs, err)
603 }
604 if c.Registration.PendingExpiry != "" {
605 if d, err := time.ParseDuration(c.Registration.PendingExpiry); err != nil || d <= 0 {
606 errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry))
607 }
608 }
609 if c.Limits.MaxReposPerUser < 0 || c.Limits.MaxBytesPerUser < 0 || c.Limits.MaxSnippetsPerUser < 0 {
610 errs = append(errs, errors.New("limits.max_repos_per_user, max_bytes_per_user and max_snippets_per_user must not be negative"))
611 }
612 if w := c.Limits.PackQueueWait; w != "" {
613 if d, err := time.ParseDuration(w); err != nil || d <= 0 {
614 errs = append(errs, fmt.Errorf("limits.pack_queue_wait %q must be a positive duration such as 60s", w))
615 }
616 }
617 if c.Push.Enabled {
618 for _, f := range []struct{ name, val string }{
619 {"push.key_file", c.Push.KeyFile},
620 {"push.key_id", c.Push.KeyID},
621 {"push.team_id", c.Push.TeamID},
622 {"push.topic", c.Push.Topic},
623 } {
624 if f.val == "" {
625 errs = append(errs, fmt.Errorf("%s is required when push.enabled", f.name))
626 }
627 }
628 if err := oneOf("push.environment", c.Push.Environment, "production", "sandbox"); err != nil {
629 errs = append(errs, err)
630 }
631 if c.Push.KeyFile != "" {
632 if _, err := LoadAPNSKey(c.Push.KeyFile); err != nil {
633 errs = append(errs, fmt.Errorf("push.key_file: %w", err))
634 }
635 }
636 }
637 if c.SSH.Port < 1 || c.SSH.Port > 65535 {
638 errs = append(errs, fmt.Errorf("ssh.port %d out of range", c.SSH.Port))
639 }
640 if err := oneOf("http.tls", c.HTTP.TLS, "acme", "files", "off"); err != nil {
641 errs = append(errs, err)
642 }
643 if _, err := c.HTTP.TrustedProxyNets(); err != nil {
644 errs = append(errs, err)
645 }
646 if c.HTTP.TLS == "files" && (c.HTTP.CertFile == "" || c.HTTP.KeyFile == "") {
647 errs = append(errs, errors.New("http.tls = \"files\" requires cert_file and key_file"))
648 }
649 if c.HTTP.TLS == "acme" {
650 host := c.SiteHost()
651 switch {
652 case !strings.HasPrefix(c.Server.SiteURL, "https://"):
653 errs = append(errs, errors.New("http.tls = \"acme\" requires an https:// site_url: certificates are issued for that host"))
654 case host == "" || host == "localhost" || net.ParseIP(host) != nil:
655 errs = append(errs, fmt.Errorf("http.tls = \"acme\" cannot issue a certificate for %q: use a public DNS name in site_url", host))
656 }
657 }
658 if err := oneOf("web.mode", c.Web.Mode, "view_only", "accounts"); err != nil {
659 errs = append(errs, err)
660 }
661 if err := oneOf("registration.mode", c.Registration.Mode, "closed", "invite", "open"); err != nil {
662 errs = append(errs, err)
663 }
664
665 for module, repo := range c.GoImport {
666 host, _, ok := strings.Cut(module, "/")
667 if !ok || host == "" || !strings.Contains(host, ".") {
668 errs = append(errs, fmt.Errorf("go_import key %q must be host/path (e.g. gitbay.org/gitbay)", module))
669 }
670 if parts := strings.Split(repo, "/"); len(parts) != 2 || parts[0] == "" || parts[1] == "" {
671 errs = append(errs, fmt.Errorf("go_import value %q must be owner/name", repo))
672 }
673 }
674
675 if _, err := c.Backup.Recipients(); err != nil {
676 errs = append(errs, err)
677 }
678
679 // Contradictions.
680 if c.Mail.SMTPHost != "" && c.Mail.From == "" {
681 errs = append(errs, errors.New("[mail] from is required when smtp_host is set"))
682 }
683 if t := c.Mail.TLS; t != "" && t != "starttls" && t != "implicit" {
684 errs = append(errs, fmt.Errorf("mail.tls must be starttls or implicit, got %q", t))
685 }
686 errs = append(errs, c.Mail.Inbound.validate()...)
687 if c.Mail.Inbound.Enabled && c.Mail.SMTPHost == "" {
688 errs = append(errs, errors.New("mail.inbound.enabled requires [mail] smtp_host: replies answer notification mail, which is not sent without SMTP"))
689 }
690 if c.Registration.Mode != "closed" && c.Mail.SMTPHost == "" {
691 errs = append(errs, fmt.Errorf(
692 "registration.mode = %q requires [mail] smtp_host: email verification cannot run without SMTP",
693 c.Registration.Mode))
694 }
695 if c.Registration.NotifyAdmin && c.Mail.SMTPHost == "" {
696 errs = append(errs, errors.New(
697 "registration.notify_admin = true requires [mail] smtp_host: there is nowhere to send the notice"))
698 }
699 if c.SSH.Mode == "system" && c.Registration.Mode != "closed" {
700 errs = append(errs, fmt.Errorf(
701 "ssh.mode = \"system\" requires registration.mode = \"closed\": host sshd rejects unknown keys before the dispatcher runs, so registration by unknown key is impossible"))
702 }
703 if c.Web.PasswordAuth && c.Web.Mode == "view_only" {
704 errs = append(errs, errors.New(
705 "web.password_auth = true is meaningless with web.mode = \"view_only\": no login route exists"))
706 }
707 if c.Web.PasswordAuth && c.Web.Mode == "accounts" {
708 errs = append(errs, errors.New(
709 "web.password_auth is not implemented yet; browser sessions are minted over SSH (gitbay web login)"))
710 }
711
712 return errors.Join(errs...)
713}
714
715// SiteHost returns the bare hostname from site_url (no scheme, port, path).
716func (c Config) SiteHost() string {
717 h := strings.TrimPrefix(strings.TrimPrefix(c.Server.SiteURL, "https://"), "http://")
718 h = strings.TrimSuffix(h, "/")
719 if i := strings.IndexByte(h, '/'); i >= 0 {
720 h = h[:i]
721 }
722 if host, _, err := net.SplitHostPort(h); err == nil {
723 return host
724 }
725 return h
726}
727
728// CheckHost performs environment probes that only make sense on the target
729// machine: port availability for the embedded listener and root existence.
730func (c Config) CheckHost() error {
731 var errs []error
732
733 if st, err := os.Stat(c.Server.Root); err != nil {
734 errs = append(errs, fmt.Errorf("server.root: %w", err))
735 } else if !st.IsDir() {
736 errs = append(errs, fmt.Errorf("server.root %q is not a directory", c.Server.Root))
737 }
738
739 if c.SSH.Mode == "embedded" {
740 addr := net.JoinHostPort("", strconv.Itoa(c.SSH.Port))
741 ln, err := net.Listen("tcp", addr)
742 if err != nil {
743 errs = append(errs, fmt.Errorf("ssh.port %d is not bindable (already in use by another daemon?): %w", c.SSH.Port, err))
744 } else {
745 ln.Close()
746 }
747 }
748
749 return errors.Join(errs...)
750}
751
752// TrustedProxyNets parses http.trusted_proxies; a bare address is a /32
753// or /128.
754func (h HTTP) TrustedProxyNets() ([]*net.IPNet, error) {
755 var nets []*net.IPNet
756 for _, p := range h.TrustedProxies {
757 if _, n, err := net.ParseCIDR(p); err == nil {
758 nets = append(nets, n)
759 continue
760 }
761 ip := net.ParseIP(p)
762 if ip == nil {
763 return nil, fmt.Errorf("http.trusted_proxies: %q is not an address or CIDR", p)
764 }
765 bits := 32
766 if ip.To4() == nil {
767 bits = 128
768 }
769 nets = append(nets, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)})
770 }
771 return nets, nil
772}