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