internal/config/config.go

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