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