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