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