internal/config/config.go

794702c58d07759975699235f4408486305f8008
gitbay/internal/config/config.go history · blame · raw

259 lines · 8512 bytes

  1// Package config loads and validates the gitbayd server configuration.
  2package config
  3
  4import (
  5	"errors"
  6	"fmt"
  7	"net"
  8	"os"
  9	"strconv"
 10	"strings"
 11
 12	"github.com/BurntSushi/toml"
 13)
 14
 15type Config struct {
 16	Server       Server       `toml:"server"`
 17	SSH          SSH          `toml:"ssh"`
 18	HTTP         HTTP         `toml:"http"`
 19	GitDaemon    GitDaemon    `toml:"git_daemon"`
 20	Web          Web          `toml:"web"`
 21	Registration Registration `toml:"registration"`
 22	API          API          `toml:"api"`
 23	Webhooks     Webhooks     `toml:"webhooks"`
 24	Limits       Limits       `toml:"limits"`
 25	Mail         Mail         `toml:"mail"`
 26	Mirrors      Mirrors      `toml:"mirrors"`
 27	// GoImport maps vanity Go module paths to repositories, e.g.
 28	// "gitbay.org/gitbay" = "krz/gitbay". Requests carrying ?go-get=1
 29	// under a mapped path get a go-import meta tag.
 30	GoImport map[string]string `toml:"go_import"`
 31}
 32
 33type Server struct {
 34	Root    string `toml:"root"`
 35	SiteURL string `toml:"site_url"`
 36}
 37
 38type SSH struct {
 39	Mode     string   `toml:"mode"` // embedded | system
 40	Port     int      `toml:"port"`
 41	HostKeys []string `toml:"host_keys"`
 42}
 43
 44type HTTP struct {
 45	Addr     string `toml:"addr"`
 46	TLS      string `toml:"tls"` // acme | files | off
 47	CertFile string `toml:"cert_file"`
 48	KeyFile  string `toml:"key_file"`
 49	// ACME (Let's Encrypt by default). Certificates are cached under
 50	// server.root/acme. acme_http_addr serves HTTP-01 challenges and
 51	// redirects to HTTPS; "off" disables it (TLS-ALPN-01 on the HTTPS
 52	// port still works).
 53	ACMEEmail    string `toml:"acme_email"`
 54	ACMEHTTPAddr string `toml:"acme_http_addr"`
 55}
 56
 57type GitDaemon struct {
 58	Enabled bool `toml:"enabled"`
 59	Port    int  `toml:"port"`
 60}
 61
 62type Web struct {
 63	Mode         string `toml:"mode"` // view_only | accounts
 64	PasswordAuth bool   `toml:"password_auth"`
 65	// PrivacyNotice is operator-provided text shown on /privacy under the
 66	// fixed project-level statement. Plain text; blank paragraphs split.
 67	PrivacyNotice string `toml:"privacy_notice"`
 68}
 69
 70type Registration struct {
 71	Mode string `toml:"mode"` // closed | invite | open
 72}
 73
 74// API controls the HTTPS/JSON control-plane API (bearer tokens minted over
 75// SSH). Off by default: an instance that never enables it has no
 76// credential-bearing HTTP surface at all.
 77type API struct {
 78	Enabled bool `toml:"enabled"`
 79}
 80
 81// Webhooks controls outbound delivery. AllowLocal permits endpoints on
 82// loopback/private addresses (off by default: SSRF).
 83type Webhooks struct {
 84	AllowLocal bool `toml:"allow_local"`
 85}
 86
 87type Mirrors struct {
 88	PullIntervalMinutes int `toml:"pull_interval_minutes"`
 89}
 90
 91type Limits struct {
 92	MaxPackBytes    int64 `toml:"max_pack_bytes"`
 93	MaxBlobBytes    int64 `toml:"max_blob_bytes"`
 94	MaxAssetBytes   int64 `toml:"max_asset_bytes"` // per release asset
 95	CloneTimeoutSec int   `toml:"clone_timeout"`
 96	SSHAuthRate     int   `toml:"ssh_auth_rate"`
 97}
 98
 99type Mail struct {
100	SMTPHost string `toml:"smtp_host"` // host:port (port defaults to 587)
101	From     string `toml:"from"`
102	SMTPUser string `toml:"smtp_user,omitempty"`
103	SMTPPass string `toml:"smtp_pass,omitempty"`
104}
105
106// Default returns the configuration used when a key is absent from the file.
107func Default() Config {
108	return Config{
109		Server: Server{Root: "/var/lib/gitbay"},
110		SSH:    SSH{Mode: "embedded", Port: 22},
111		HTTP:   HTTP{Addr: ":443", TLS: "acme", ACMEHTTPAddr: ":80"},
112		Web:    Web{Mode: "view_only"},
113		Registration: Registration{
114			Mode: "closed",
115		},
116		GitDaemon: GitDaemon{Port: 9418},
117		Mirrors:   Mirrors{PullIntervalMinutes: 15},
118		Limits: Limits{
119			MaxPackBytes:    2 << 30, // 2 GiB
120			MaxBlobBytes:    100 << 20,
121			MaxAssetBytes:   512 << 20,
122			CloneTimeoutSec: 3600,
123			SSHAuthRate:     10,
124		},
125	}
126}
127
128// Load reads path, applies defaults, and validates. It does not probe the
129// host (see CheckHost) so it is safe in tests and on non-target machines.
130func Load(path string) (Config, error) {
131	cfg := Default()
132	md, err := toml.DecodeFile(path, &cfg)
133	if err != nil {
134		return cfg, err
135	}
136	if u := md.Undecoded(); len(u) > 0 {
137		return cfg, fmt.Errorf("unknown config key %q", u[0].String())
138	}
139	return cfg, cfg.Validate()
140}
141
142func oneOf(field, val string, allowed ...string) error {
143	for _, a := range allowed {
144		if val == a {
145			return nil
146		}
147	}
148	return fmt.Errorf("%s must be one of %v, got %q", field, allowed, val)
149}
150
151// Validate applies the static contradiction checks from the plan.
152func (c Config) Validate() error {
153	var errs []error
154
155	if c.Server.Root == "" {
156		errs = append(errs, errors.New("server.root is required"))
157	}
158	if c.Server.SiteURL == "" {
159		errs = append(errs, errors.New("server.site_url is required"))
160	}
161	if err := oneOf("ssh.mode", c.SSH.Mode, "embedded", "system"); err != nil {
162		errs = append(errs, err)
163	}
164	if c.SSH.Port < 1 || c.SSH.Port > 65535 {
165		errs = append(errs, fmt.Errorf("ssh.port %d out of range", c.SSH.Port))
166	}
167	if err := oneOf("http.tls", c.HTTP.TLS, "acme", "files", "off"); err != nil {
168		errs = append(errs, err)
169	}
170	if c.HTTP.TLS == "files" && (c.HTTP.CertFile == "" || c.HTTP.KeyFile == "") {
171		errs = append(errs, errors.New("http.tls = \"files\" requires cert_file and key_file"))
172	}
173	if c.HTTP.TLS == "acme" {
174		host := c.SiteHost()
175		switch {
176		case !strings.HasPrefix(c.Server.SiteURL, "https://"):
177			errs = append(errs, errors.New("http.tls = \"acme\" requires an https:// site_url: certificates are issued for that host"))
178		case host == "" || host == "localhost" || net.ParseIP(host) != nil:
179			errs = append(errs, fmt.Errorf("http.tls = \"acme\" cannot issue a certificate for %q: use a public DNS name in site_url", host))
180		}
181	}
182	if err := oneOf("web.mode", c.Web.Mode, "view_only", "accounts"); err != nil {
183		errs = append(errs, err)
184	}
185	if err := oneOf("registration.mode", c.Registration.Mode, "closed", "invite", "open"); err != nil {
186		errs = append(errs, err)
187	}
188
189	for module, repo := range c.GoImport {
190		host, _, ok := strings.Cut(module, "/")
191		if !ok || host == "" || !strings.Contains(host, ".") {
192			errs = append(errs, fmt.Errorf("go_import key %q must be host/path (e.g. gitbay.org/gitbay)", module))
193		}
194		if parts := strings.Split(repo, "/"); len(parts) != 2 || parts[0] == "" || parts[1] == "" {
195			errs = append(errs, fmt.Errorf("go_import value %q must be owner/name", repo))
196		}
197	}
198
199	// Contradictions.
200	if c.Mail.SMTPHost != "" && c.Mail.From == "" {
201		errs = append(errs, errors.New("[mail] from is required when smtp_host is set"))
202	}
203	if c.Registration.Mode != "closed" && c.Mail.SMTPHost == "" {
204		errs = append(errs, fmt.Errorf(
205			"registration.mode = %q requires [mail] smtp_host: email verification cannot run without SMTP",
206			c.Registration.Mode))
207	}
208	if c.SSH.Mode == "system" && c.Registration.Mode != "closed" {
209		errs = append(errs, fmt.Errorf(
210			"ssh.mode = \"system\" requires registration.mode = \"closed\": host sshd rejects unknown keys before the dispatcher runs, so registration by unknown key is impossible"))
211	}
212	if c.Web.PasswordAuth && c.Web.Mode == "view_only" {
213		errs = append(errs, errors.New(
214			"web.password_auth = true is meaningless with web.mode = \"view_only\": no login route exists"))
215	}
216	if c.Web.PasswordAuth && c.Web.Mode == "accounts" {
217		errs = append(errs, errors.New(
218			"web.password_auth is not implemented yet; browser sessions are minted over SSH (gitbay web login)"))
219	}
220
221	return errors.Join(errs...)
222}
223
224// SiteHost returns the bare hostname from site_url (no scheme, port, path).
225func (c Config) SiteHost() string {
226	h := strings.TrimPrefix(strings.TrimPrefix(c.Server.SiteURL, "https://"), "http://")
227	h = strings.TrimSuffix(h, "/")
228	if i := strings.IndexByte(h, '/'); i >= 0 {
229		h = h[:i]
230	}
231	if host, _, err := net.SplitHostPort(h); err == nil {
232		return host
233	}
234	return h
235}
236
237// CheckHost performs environment probes that only make sense on the target
238// machine: port availability for the embedded listener and root existence.
239func (c Config) CheckHost() error {
240	var errs []error
241
242	if st, err := os.Stat(c.Server.Root); err != nil {
243		errs = append(errs, fmt.Errorf("server.root: %w", err))
244	} else if !st.IsDir() {
245		errs = append(errs, fmt.Errorf("server.root %q is not a directory", c.Server.Root))
246	}
247
248	if c.SSH.Mode == "embedded" {
249		addr := net.JoinHostPort("", strconv.Itoa(c.SSH.Port))
250		ln, err := net.Listen("tcp", addr)
251		if err != nil {
252			errs = append(errs, fmt.Errorf("ssh.port %d is not bindable (already in use by another daemon?): %w", c.SSH.Port, err))
253		} else {
254			ln.Close()
255		}
256	}
257
258	return errors.Join(errs...)
259}