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