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