internal/config/config.go

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