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