internal/config/config.go
330 lines · 11607 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 "time"
12
13 "github.com/BurntSushi/toml"
14)
15
16type Config struct {
17 Server Server `toml:"server"`
18 SSH SSH `toml:"ssh"`
19 HTTP HTTP `toml:"http"`
20 GitDaemon GitDaemon `toml:"git_daemon"`
21 Web Web `toml:"web"`
22 Registration Registration `toml:"registration"`
23 API API `toml:"api"`
24 Webhooks Webhooks `toml:"webhooks"`
25 Pages Pages `toml:"pages"`
26 LFS LFS `toml:"lfs"`
27 Limits Limits `toml:"limits"`
28 Mail Mail `toml:"mail"`
29 Mirrors Mirrors `toml:"mirrors"`
30 Deps Deps `toml:"deps"`
31 // GoImport maps vanity Go module paths to repositories, e.g.
32 // "gitbay.org/gitbay" = "krz/gitbay". Requests carrying ?go-get=1
33 // under a mapped path get a go-import meta tag.
34 GoImport map[string]string `toml:"go_import"`
35}
36
37type Server struct {
38 Root string `toml:"root"`
39 SiteURL string `toml:"site_url"`
40
41 // SourceRepo names the repository this instance develops itself in, as
42 // "owner/name". When set, startup warns if the running build's commit is
43 // not on that repository's default branch. Empty disables the check, which
44 // is right for any instance that does not host its own source.
45 SourceRepo string `toml:"source_repo"`
46}
47
48type SSH struct {
49 Mode string `toml:"mode"` // embedded | system
50 Port int `toml:"port"`
51 HostKeys []string `toml:"host_keys"`
52}
53
54type HTTP struct {
55 Addr string `toml:"addr"`
56 TLS string `toml:"tls"` // acme | files | off
57 CertFile string `toml:"cert_file"`
58 KeyFile string `toml:"key_file"`
59 // ACME (Let's Encrypt by default). Certificates are cached under
60 // server.root/acme. acme_http_addr serves HTTP-01 challenges and
61 // redirects to HTTPS; "off" disables it (TLS-ALPN-01 on the HTTPS
62 // port still works).
63 ACMEEmail string `toml:"acme_email"`
64 ACMEHTTPAddr string `toml:"acme_http_addr"`
65}
66
67type GitDaemon struct {
68 Enabled bool `toml:"enabled"`
69 Port int `toml:"port"`
70}
71
72type Web struct {
73 Mode string `toml:"mode"` // view_only | accounts
74 PasswordAuth bool `toml:"password_auth"`
75 // Title is the instance's display name in the header and page titles.
76 // Empty falls back to the site host.
77 Title string `toml:"title"`
78 // PrivacyNotice is operator-provided text shown on /privacy under the
79 // fixed project-level statement. Plain text; blank paragraphs split.
80 PrivacyNotice string `toml:"privacy_notice"`
81}
82
83type Registration struct {
84 Mode string `toml:"mode"` // closed | invite | open
85 // PendingExpiry is how long a self-registered account may stay
86 // unverified before it is removed, as a duration ("168h"). Empty
87 // keeps such accounts forever.
88 PendingExpiry string `toml:"pending_expiry"`
89}
90
91// PendingExpiryDuration parses PendingExpiry; zero means never.
92func (r Registration) PendingExpiryDuration() time.Duration {
93 d, _ := time.ParseDuration(r.PendingExpiry)
94 return d
95}
96
97// LFS stores large-file objects content-addressed under Root (default
98// <server.root>/lfs). MaxObjectBytes caps a single object; 0 means the
99// 512MB default.
100type LFS struct {
101 Root string `toml:"root"`
102 MaxObjectBytes int64 `toml:"max_object_bytes"`
103}
104
105// Pages serves each public repo's `pages` branch as a static site on
106// <owner>.<domain> — a separate origin, so page-authored scripts never run
107// on the forge's own host. Empty domain disables the feature.
108type Pages struct {
109 Domain string `toml:"domain"`
110}
111
112// API controls the HTTPS/JSON control-plane API (bearer tokens minted over
113// SSH). Off by default: an instance that never enables it has no
114// credential-bearing HTTP surface at all.
115type API struct {
116 Enabled bool `toml:"enabled"`
117}
118
119// Webhooks controls outbound delivery. AllowLocal permits endpoints on
120// loopback/private addresses (off by default: SSRF).
121type Webhooks struct {
122 AllowLocal bool `toml:"allow_local"`
123}
124
125type Mirrors struct {
126 PullIntervalMinutes int `toml:"pull_interval_minutes"`
127}
128
129// Deps configures the dependency-update sweep. It runs only for repos that
130// have opted in with `repo deps enable`, because checking a private repo
131// tells a public registry what it depends on.
132type Deps struct {
133 CheckIntervalHours int `toml:"check_interval_hours"`
134}
135
136type Limits struct {
137 MaxPackBytes int64 `toml:"max_pack_bytes"`
138 MaxBlobBytes int64 `toml:"max_blob_bytes"`
139 MaxAssetBytes int64 `toml:"max_asset_bytes"` // per release asset
140 CloneTimeoutSec int `toml:"clone_timeout"`
141 SSHAuthRate int `toml:"ssh_auth_rate"`
142 // APIRate is sustained JSON-API requests per minute per caller; writes
143 // draw on a tenth of it. 0 uses the default.
144 APIRate int `toml:"api_rate"`
145 // Per-account quotas on what a user owns directly (organizations are
146 // not capped). 0 means unlimited; admin user limits overrides per
147 // account.
148 MaxReposPerUser int `toml:"max_repos_per_user"`
149 MaxBytesPerUser int64 `toml:"max_bytes_per_user"`
150}
151
152type Mail struct {
153 SMTPHost string `toml:"smtp_host"` // host:port (port defaults to 587)
154 From string `toml:"from"`
155 SMTPUser string `toml:"smtp_user,omitempty"`
156 SMTPPass string `toml:"smtp_pass,omitempty"`
157}
158
159// Default returns the configuration used when a key is absent from the file.
160func Default() Config {
161 return Config{
162 Server: Server{Root: "/var/lib/gitbay"},
163 SSH: SSH{Mode: "embedded", Port: 22},
164 HTTP: HTTP{Addr: ":443", TLS: "acme", ACMEHTTPAddr: ":80"},
165 Web: Web{Mode: "view_only"},
166 Registration: Registration{
167 Mode: "closed",
168 },
169 GitDaemon: GitDaemon{Port: 9418},
170 Mirrors: Mirrors{PullIntervalMinutes: 15},
171 Deps: Deps{CheckIntervalHours: 24},
172 Limits: Limits{
173 MaxPackBytes: 2 << 30, // 2 GiB
174 MaxBlobBytes: 100 << 20,
175 MaxAssetBytes: 512 << 20,
176 CloneTimeoutSec: 3600,
177 SSHAuthRate: 10,
178 APIRate: 120,
179 },
180 }
181}
182
183// Load reads path, applies defaults, and validates. It does not probe the
184// host (see CheckHost) so it is safe in tests and on non-target machines.
185func Load(path string) (Config, error) {
186 cfg := Default()
187 md, err := toml.DecodeFile(path, &cfg)
188 if err != nil {
189 return cfg, err
190 }
191 if u := md.Undecoded(); len(u) > 0 {
192 return cfg, fmt.Errorf("unknown config key %q", u[0].String())
193 }
194 return cfg, cfg.Validate()
195}
196
197func oneOf(field, val string, allowed ...string) error {
198 for _, a := range allowed {
199 if val == a {
200 return nil
201 }
202 }
203 return fmt.Errorf("%s must be one of %v, got %q", field, allowed, val)
204}
205
206// Validate applies the static contradiction checks from the plan.
207func (c Config) Validate() error {
208 var errs []error
209
210 if c.Server.Root == "" {
211 errs = append(errs, errors.New("server.root is required"))
212 }
213 if d := c.Pages.Domain; d != "" {
214 if d == c.SiteHost() {
215 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"))
216 }
217 if strings.HasSuffix(c.SiteHost(), "."+d) {
218 errs = append(errs, errors.New("pages.domain must not be a parent of the site host"))
219 }
220 }
221 if c.Server.SiteURL == "" {
222 errs = append(errs, errors.New("server.site_url is required"))
223 }
224 if err := oneOf("ssh.mode", c.SSH.Mode, "embedded", "system"); err != nil {
225 errs = append(errs, err)
226 }
227 if c.Registration.PendingExpiry != "" {
228 if d, err := time.ParseDuration(c.Registration.PendingExpiry); err != nil || d <= 0 {
229 errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry))
230 }
231 }
232 if c.Limits.MaxReposPerUser < 0 || c.Limits.MaxBytesPerUser < 0 {
233 errs = append(errs, errors.New("limits.max_repos_per_user and max_bytes_per_user must not be negative"))
234 }
235 if c.SSH.Port < 1 || c.SSH.Port > 65535 {
236 errs = append(errs, fmt.Errorf("ssh.port %d out of range", c.SSH.Port))
237 }
238 if err := oneOf("http.tls", c.HTTP.TLS, "acme", "files", "off"); err != nil {
239 errs = append(errs, err)
240 }
241 if c.HTTP.TLS == "files" && (c.HTTP.CertFile == "" || c.HTTP.KeyFile == "") {
242 errs = append(errs, errors.New("http.tls = \"files\" requires cert_file and key_file"))
243 }
244 if c.HTTP.TLS == "acme" {
245 host := c.SiteHost()
246 switch {
247 case !strings.HasPrefix(c.Server.SiteURL, "https://"):
248 errs = append(errs, errors.New("http.tls = \"acme\" requires an https:// site_url: certificates are issued for that host"))
249 case host == "" || host == "localhost" || net.ParseIP(host) != nil:
250 errs = append(errs, fmt.Errorf("http.tls = \"acme\" cannot issue a certificate for %q: use a public DNS name in site_url", host))
251 }
252 }
253 if err := oneOf("web.mode", c.Web.Mode, "view_only", "accounts"); err != nil {
254 errs = append(errs, err)
255 }
256 if err := oneOf("registration.mode", c.Registration.Mode, "closed", "invite", "open"); err != nil {
257 errs = append(errs, err)
258 }
259
260 for module, repo := range c.GoImport {
261 host, _, ok := strings.Cut(module, "/")
262 if !ok || host == "" || !strings.Contains(host, ".") {
263 errs = append(errs, fmt.Errorf("go_import key %q must be host/path (e.g. gitbay.org/gitbay)", module))
264 }
265 if parts := strings.Split(repo, "/"); len(parts) != 2 || parts[0] == "" || parts[1] == "" {
266 errs = append(errs, fmt.Errorf("go_import value %q must be owner/name", repo))
267 }
268 }
269
270 // Contradictions.
271 if c.Mail.SMTPHost != "" && c.Mail.From == "" {
272 errs = append(errs, errors.New("[mail] from is required when smtp_host is set"))
273 }
274 if c.Registration.Mode != "closed" && c.Mail.SMTPHost == "" {
275 errs = append(errs, fmt.Errorf(
276 "registration.mode = %q requires [mail] smtp_host: email verification cannot run without SMTP",
277 c.Registration.Mode))
278 }
279 if c.SSH.Mode == "system" && c.Registration.Mode != "closed" {
280 errs = append(errs, fmt.Errorf(
281 "ssh.mode = \"system\" requires registration.mode = \"closed\": host sshd rejects unknown keys before the dispatcher runs, so registration by unknown key is impossible"))
282 }
283 if c.Web.PasswordAuth && c.Web.Mode == "view_only" {
284 errs = append(errs, errors.New(
285 "web.password_auth = true is meaningless with web.mode = \"view_only\": no login route exists"))
286 }
287 if c.Web.PasswordAuth && c.Web.Mode == "accounts" {
288 errs = append(errs, errors.New(
289 "web.password_auth is not implemented yet; browser sessions are minted over SSH (gitbay web login)"))
290 }
291
292 return errors.Join(errs...)
293}
294
295// SiteHost returns the bare hostname from site_url (no scheme, port, path).
296func (c Config) SiteHost() string {
297 h := strings.TrimPrefix(strings.TrimPrefix(c.Server.SiteURL, "https://"), "http://")
298 h = strings.TrimSuffix(h, "/")
299 if i := strings.IndexByte(h, '/'); i >= 0 {
300 h = h[:i]
301 }
302 if host, _, err := net.SplitHostPort(h); err == nil {
303 return host
304 }
305 return h
306}
307
308// CheckHost performs environment probes that only make sense on the target
309// machine: port availability for the embedded listener and root existence.
310func (c Config) CheckHost() error {
311 var errs []error
312
313 if st, err := os.Stat(c.Server.Root); err != nil {
314 errs = append(errs, fmt.Errorf("server.root: %w", err))
315 } else if !st.IsDir() {
316 errs = append(errs, fmt.Errorf("server.root %q is not a directory", c.Server.Root))
317 }
318
319 if c.SSH.Mode == "embedded" {
320 addr := net.JoinHostPort("", strconv.Itoa(c.SSH.Port))
321 ln, err := net.Listen("tcp", addr)
322 if err != nil {
323 errs = append(errs, fmt.Errorf("ssh.port %d is not bindable (already in use by another daemon?): %w", c.SSH.Port, err))
324 } else {
325 ln.Close()
326 }
327 }
328
329 return errors.Join(errs...)
330}