BlueGit

timfa bluegit

Files

bluegit / internal / config / config.go

config.go

config.go 11.1 KiB Download Raw
1// Package config leest het YAML-configuratiebestand van BlueGit.
2package config
3
4import (
5 "fmt"
6 "net"
7 "net/url"
8 "os"
9 "path/filepath"
10 "strconv"
11 "strings"
12
13 "gitlab.com/Timfa/bluegit/internal/images"
14 "gitlab.com/Timfa/bluegit/internal/realip"
15 "gopkg.in/yaml.v3"
16)
17
18// Config is de installatie op de mini-PC.
19type Config struct {
20 BaseURL string `yaml:"base_url"`
21 Listen string `yaml:"listen"`
22 // StatePath is de kleine map met database, sleutel en het gekozen
23 // opslagpad. Leeg wordt /var/lib/bluegit.
24 StatePath string `yaml:"state_path"`
25 // StoragePath is optioneel. Leeg betekent dat de beheerder het pad
26 // in de webinterface kiest. Er is geen standaardpad.
27 StoragePath string `yaml:"storage_path"`
28 // CachePath is de optionele leescache (bij voorkeur op een SSD).
29 // Leeg betekent geen cache. Beheer kan het overschrijven.
30 CachePath string `yaml:"cache_path"`
31 CacheMaxMB int64 `yaml:"cache_max_mb"`
32 TrustedProxies []string `yaml:"trusted_proxies"`
33 // BehindProxy is het oude veld. Het wordt geweigerd: één boolean
34 // vertrouwt ofwel iedereen, ofwel niemand. De lijst hierboven beslist.
35 BehindProxy bool `yaml:"behind_proxy"`
36 Auth Auth `yaml:"auth"`
37 Git Git `yaml:"git"`
38 SSH SSH `yaml:"ssh"`
39 Runner Runner `yaml:"runner"`
40 CI CI `yaml:"ci"`
41
42 proxies *realip.Set
43}
44
45// Auth wijst naar auth.timfalken.com of naar de lokale ontwikkelmodus.
46type Auth struct {
47 Mode string `yaml:"mode"`
48 BaseURL string `yaml:"base_url"`
49 ClientID string `yaml:"client_id"`
50 ClientSecret string `yaml:"client_secret"`
51 ClientSecretFile string `yaml:"client_secret_file"`
52 RedirectPath string `yaml:"redirect_path"`
53 UserAgent string `yaml:"user_agent"`
54 DevUser string `yaml:"dev_user"`
55 DevAuthID int64 `yaml:"dev_auth_id"`
56}
57
58// Git wijst naar de git-binary en de standaardbranch van nieuwe repositories.
59type Git struct {
60 Binary string `yaml:"binary"`
61 DefaultBranch string `yaml:"default_branch"`
62 HookBinary string `yaml:"hook_binary"`
63}
64
65// SSH is de git-over-SSH-listener en het adres dat in clone-URL's staat.
66// Listen is waar dit proces bindt. PublicHost en PublicPort zijn wat
67// een gebruiker ziet; de ingress kan daar een andere poort voor gebruiken.
68type SSH struct {
69 Enabled bool `yaml:"enabled"`
70 Listen string `yaml:"listen"`
71 PublicHost string `yaml:"public_host"`
72 PublicPort int `yaml:"public_port"`
73}
74
75// Runner is de ingebouwde Docker-runner.
76type Runner struct {
77 Name string `yaml:"name"`
78}
79
80// CI stuurt de Docker-runner.
81type CI struct {
82 Enabled bool `yaml:"enabled"`
83 Docker string `yaml:"docker_binary"`
84 Concurrency int `yaml:"concurrency"`
85 Network string `yaml:"network"`
86 TimeoutSec int `yaml:"timeout_seconds"`
87 Presets map[string]PresetConfig `yaml:"presets"`
88}
89
90// PresetConfig is één image-alias. image mapt direct. dockerfile wordt
91// door Steve gebouwd. from herschrijft de eerste FROM van een Dockerfile.
92type PresetConfig struct {
93 Image string `yaml:"image"`
94 Dockerfile string `yaml:"dockerfile"`
95 From string `yaml:"from"`
96}
97
98// ImageOverrides is de vorm die de runner en de infopagina lezen.
99func (c CI) ImageOverrides() map[string]images.Override {
100 if len(c.Presets) == 0 {
101 return nil
102 }
103 out := make(map[string]images.Override, len(c.Presets))
104 for name, p := range c.Presets {
105 out[name] = images.Override{Image: p.Image, Dockerfile: p.Dockerfile, From: p.From}
106 }
107 return out
108}
109
110// Load leest path en vult ontbrekende waarden aan.
111func Load(path string) (Config, error) {
112 raw, err := os.ReadFile(path)
113 if err != nil {
114 return Config{}, fmt.Errorf("config lezen: %w", err)
115 }
116 var c Config
117 if err := yaml.Unmarshal(raw, &c); err != nil {
118 return Config{}, fmt.Errorf("config: %w", err)
119 }
120 c.applyDefaults()
121 if v := os.Getenv("BLUEGIT_STATE_PATH"); v != "" {
122 c.StatePath = v
123 }
124 if v := os.Getenv("BLUEGIT_STORAGE_PATH"); v != "" {
125 c.StoragePath = v
126 }
127 if v := os.Getenv("BLUEGIT_CACHE_PATH"); v != "" {
128 c.CachePath = v
129 }
130 if v := os.Getenv("BLUEGIT_LISTEN"); v != "" {
131 c.Listen = v
132 }
133 if v := os.Getenv("BLUEGIT_AUTH_CLIENT_SECRET"); v != "" {
134 c.Auth.ClientSecret = v
135 }
136 if c.Auth.ClientSecret == "" && c.Auth.ClientSecretFile != "" {
137 b, err := os.ReadFile(c.Auth.ClientSecretFile)
138 if err != nil {
139 return Config{}, fmt.Errorf("clientgeheim: %w", err)
140 }
141 c.Auth.ClientSecret = strings.TrimSpace(string(b))
142 }
143 c.resolvePresetPaths(path)
144 if err := c.Validate(); err != nil {
145 return Config{}, err
146 }
147 return c, nil
148}
149
150func (c *Config) resolvePresetPaths(configFile string) {
151 if len(c.CI.Presets) == 0 {
152 return
153 }
154 base := filepath.Dir(configFile)
155 for name, p := range c.CI.Presets {
156 if p.Dockerfile != "" && !filepath.IsAbs(p.Dockerfile) {
157 p.Dockerfile = filepath.Join(base, p.Dockerfile)
158 c.CI.Presets[name] = p
159 }
160 }
161}
162
163func (c *Config) applyDefaults() {
164 if c.Listen == "" {
165 c.Listen = "127.0.0.1:8080"
166 }
167 if c.StatePath == "" {
168 c.StatePath = "/var/lib/bluegit"
169 }
170 if c.Auth.Mode == "" {
171 c.Auth.Mode = "oauth"
172 }
173 if c.Auth.BaseURL == "" {
174 c.Auth.BaseURL = "https://auth.timfalken.com"
175 }
176 if c.Auth.RedirectPath == "" {
177 c.Auth.RedirectPath = "/auth/callback"
178 }
179 if c.Auth.UserAgent == "" {
180 c.Auth.UserAgent = "BlueGitAccountClient/0.1"
181 }
182 if c.Auth.DevUser == "" {
183 c.Auth.DevUser = "tim"
184 }
185 if c.Auth.DevAuthID == 0 {
186 c.Auth.DevAuthID = 1
187 }
188 if c.Git.Binary == "" {
189 c.Git.Binary = "git"
190 }
191 if c.Git.DefaultBranch == "" {
192 c.Git.DefaultBranch = "master"
193 }
194 if c.SSH.Listen == "" {
195 c.SSH.Listen = "0.0.0.0:2222"
196 }
197 if c.CI.Docker == "" {
198 c.CI.Docker = "docker"
199 }
200 if c.CI.Concurrency <= 0 {
201 c.CI.Concurrency = 1
202 }
203 if c.CI.Network == "" {
204 c.CI.Network = "bridge"
205 }
206 if c.CI.TimeoutSec <= 0 {
207 c.CI.TimeoutSec = 1800
208 }
209 if strings.TrimSpace(c.Runner.Name) == "" {
210 c.Runner.Name = "Steve"
211 } else {
212 c.Runner.Name = strings.TrimSpace(c.Runner.Name)
213 }
214 c.Auth.BaseURL = strings.TrimRight(c.Auth.BaseURL, "/")
215 c.BaseURL = strings.TrimRight(c.BaseURL, "/")
216}
217
218// Validate keurt een configuratie goed of af.
219func (c *Config) Validate() error {
220 if c.BaseURL == "" {
221 return fmt.Errorf("base_url ontbreekt")
222 }
223 u, err := url.Parse(c.BaseURL)
224 if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
225 return fmt.Errorf("base_url moet een absolute http(s)-URL zijn")
226 }
227 if strings.TrimSpace(c.StatePath) == "" {
228 return fmt.Errorf("state_path ontbreekt")
229 }
230 if !strings.HasPrefix(c.Auth.RedirectPath, "/") {
231 return fmt.Errorf("auth.redirect_path moet met / beginnen")
232 }
233 switch c.Auth.Mode {
234 case "oauth":
235 if c.Auth.ClientID == "" || c.Auth.ClientSecret == "" {
236 return fmt.Errorf("oauth vereist auth.client_id en een clientgeheim (veld, bestand of BLUEGIT_AUTH_CLIENT_SECRET)")
237 }
238 if c.Auth.BaseURL == "" {
239 return fmt.Errorf("auth.base_url ontbreekt")
240 }
241 case "dev":
242 if strings.EqualFold(u.Hostname(), "git.timfalken.com") {
243 return fmt.Errorf("auth.mode dev is geweigerd voor git.timfalken.com")
244 }
245 default:
246 return fmt.Errorf("auth.mode moet oauth of dev zijn")
247 }
248 if c.BehindProxy {
249 return fmt.Errorf("behind_proxy doet niets meer; zet trusted_proxies op het IP of CIDR van de ingress en haal behind_proxy weg")
250 }
251 set, err := realip.Parse(c.TrustedProxies)
252 if err != nil {
253 return err
254 }
255 c.proxies = set
256 if c.SSH.PublicPort < 0 || c.SSH.PublicPort > 65535 {
257 return fmt.Errorf("ssh.public_port moet tussen 0 en 65535 liggen")
258 }
259 if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
260 if strings.Contains(h, "://") || strings.ContainsAny(h, " /") || (strings.Contains(h, ":") && net.ParseIP(h) == nil) {
261 return fmt.Errorf("ssh.public_host moet een hostnaam of IP zijn, zonder schema of poort")
262 }
263 }
264 if _, _, err := net.SplitHostPort(c.SSH.Listen); err != nil {
265 return fmt.Errorf("ssh.listen moet host:poort zijn")
266 }
267 if _, err := images.Effective(c.CI.ImageOverrides()); err != nil {
268 return err
269 }
270 return nil
271}
272
273// ProxySet is de geparsede trusted_proxies-lijst. Nil betekent dat
274// niemand vertrouwd wordt.
275func (c Config) ProxySet() *realip.Set { return c.proxies }
276
277// SSHPublicHost is de host in een SSH-clone-URL.
278// Leeg in de config: de host van base_url.
279func (c Config) SSHPublicHost() string {
280 if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
281 return h
282 }
283 u, err := url.Parse(c.BaseURL)
284 if err != nil {
285 return ""
286 }
287 return u.Hostname()
288}
289
290// SSHPublicPort is de poort in een SSH-clone-URL.
291// 0 in de config: de poort van ssh.listen.
292func (c Config) SSHPublicPort() int {
293 if c.SSH.PublicPort > 0 {
294 return c.SSH.PublicPort
295 }
296 _, port, err := net.SplitHostPort(c.SSH.Listen)
297 if err != nil {
298 return 22
299 }
300 n, err := strconv.Atoi(port)
301 if err != nil || n <= 0 {
302 return 22
303 }
304 return n
305}
306
307// CloneSSH is de URL die een gebruiker kloont. Leeg als SSH uit staat.
308func (c Config) CloneSSH(repoPath string) string {
309 if !c.SSH.Enabled {
310 return ""
311 }
312 host := c.SSHPublicHost()
313 if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {
314 host = "[" + host + "]"
315 }
316 return fmt.Sprintf("ssh://git@%s:%d/%s.git", host, c.SSHPublicPort(), repoPath)
317}
318
319// RedirectURI is de callback die bij de auth-server geregistreerd moet staan.
320func (c Config) RedirectURI() string {
321 return c.BaseURL + c.Auth.RedirectPath
322}
323
324// Example is een startconfiguratie voor de mini-PC.
325func Example() string {
326 return `# BlueGit op de mini-PC. Kopieer naar /etc/bluegit/config.yml.
327# Plain HTTP. TLS en de publieke SSH-poort doet de ingress, zie docs/INGRESS.md.
328base_url: https://git.timfalken.com
329listen: 0.0.0.0:8080
330# Database, sleutel en het gekozen opslagpad. Dit is niet de datadisk.
331state_path: /var/lib/bluegit
332# storage_path blijft leeg. De installatiebeheerder kiest de datadisk
333# bij de eerste aanmelding. Er is geen standaardpad.
334# Alleen deze adressen mogen X-Forwarded-For en X-Real-IP zetten.
335# Zet hier het IP van de ingress, zoals de mini-PC die verbinding ziet.
336trusted_proxies:
337 - 10.0.0.2
338
339auth:
340 mode: oauth
341 base_url: https://auth.timfalken.com
342 # Het domein is de client_id. Registreer het pad /auth/callback bij /admin.
343 client_id: git.timfalken.com
344 # Laat leeg en zet BLUEGIT_AUTH_CLIENT_SECRET, of gebruik client_secret_file.
345 client_secret: ""
346 client_secret_file: /etc/bluegit/client_secret
347 redirect_path: /auth/callback
348 user_agent: BlueGitAccountClient/0.1
349
350git:
351 binary: git
352 default_branch: master
353
354ssh:
355 enabled: true
356 # Waar dit proces git-SSH aanneemt. De SSH van het besturingssysteem blijft vrij.
357 listen: 0.0.0.0:2222
358 # Wat gebruikers in de clone-URL zien. De ingress stuurt poort 22 hiernaartoe.
359 public_host: git.timfalken.com
360 public_port: 22
361
362runner:
363 name: Steve
364
365ci:
366 enabled: true
367 docker_binary: docker
368 concurrency: 1
369 network: bridge
370 timeout_seconds: 1800
371 # Image-aliassen voor jobs. bluegit/base, bluegit/node, bluegit/python,
372 # bluegit/go, bluegit/rust, bluegit/java en bluegit/dotnet zijn ingebouwd.
373 # Een eigen alias wijst naar een Dockerfile of naar een kant-en-klaar image.
374 # presets:
375 # team/tools:
376 # image: alpine:3.20
377 # team/build:
378 # dockerfile: /etc/bluegit/images/build/Dockerfile
379 # bluegit/node:
380 # from: node:22-bookworm
381`
382}