BlueGit

timfa bluegit

Files

bluegit / internal / config / config.go

config.go

config.go 15.3 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 "time"
13
14 "gitlab.com/Timfa/bluegit/internal/apppaths"
15 "gitlab.com/Timfa/bluegit/internal/images"
16 "gitlab.com/Timfa/bluegit/internal/realip"
17 "gopkg.in/yaml.v3"
18)
19
20// Config is de installatie op de mini-PC.
21type Config struct {
22 BaseURL string `yaml:"base_url"`
23 Listen string `yaml:"listen"`
24 // StatePath is de kleine map met database, sleutel en het gekozen
25 // opslagpad. Leeg wordt /var/lib/bluegit, of %LOCALAPPDATA%\BlueGit op Windows.
26 StatePath string `yaml:"state_path"`
27 // StoragePath is optioneel. Leeg betekent dat de beheerder het pad
28 // in de webinterface kiest. Er is geen standaardpad.
29 StoragePath string `yaml:"storage_path"`
30 // CachePath is de optionele leescache (bij voorkeur op een SSD).
31 // Leeg betekent geen cache. Beheer kan het overschrijven.
32 CachePath string `yaml:"cache_path"`
33 CacheMaxMB int64 `yaml:"cache_max_mb"`
34 TrustedProxies []string `yaml:"trusted_proxies"`
35 // BehindProxy is het oude veld. Het wordt geweigerd: één boolean
36 // vertrouwt ofwel iedereen, ofwel niemand. De lijst hierboven beslist.
37 BehindProxy bool `yaml:"behind_proxy"`
38 Auth Auth `yaml:"auth"`
39 Git Git `yaml:"git"`
40 SSH SSH `yaml:"ssh"`
41 Runner Runner `yaml:"runner"`
42 CI CI `yaml:"ci"`
43
44 proxies *realip.Set
45}
46
47// Auth wijst naar auth.timfalken.com, Microsoft Entra ID, of de lokale ontwikkelmodus.
48type Auth struct {
49 Mode string `yaml:"mode"` // oauth | entra | dev
50 BaseURL string `yaml:"base_url"`
51 ClientID string `yaml:"client_id"`
52 ClientSecret string `yaml:"client_secret"`
53 ClientSecretFile string `yaml:"client_secret_file"`
54 RedirectPath string `yaml:"redirect_path"`
55 UserAgent string `yaml:"user_agent"`
56 DevUser string `yaml:"dev_user"`
57 DevAuthID int64 `yaml:"dev_auth_id"`
58 // TenantID is verplicht bij mode entra (directory-/tenant-id).
59 TenantID string `yaml:"tenant_id"`
60 // Issuer overschrijft de Entra-issuer. Leeg: login.microsoftonline.com/{tenant}/v2.0.
61 // Voor tests of andere clouds (bijv. login.microsoftonline.us).
62 Issuer string `yaml:"issuer"`
63}
64
65// Git wijst naar de git-binary en de standaardbranch van nieuwe repositories.
66type Git struct {
67 Binary string `yaml:"binary"`
68 DefaultBranch string `yaml:"default_branch"`
69 HookBinary string `yaml:"hook_binary"`
70 // MaintenanceInterval is hoe vaak bare repositories onderhouden worden
71 // (git maintenance of git gc --auto). Leeg is 24h. "off" of "0" zet uit.
72 // Gebruik een Go-duur (24h, 168h) of een aantal dagen (7d).
73 MaintenanceInterval string `yaml:"maintenance_interval"`
74}
75
76// DefaultMaintenanceInterval is de standaard: elke nacht.
77const DefaultMaintenanceInterval = 24 * time.Hour
78
79// MaintenanceEvery geeft het interval en of onderhoud aan staat.
80func (g Git) MaintenanceEvery() (time.Duration, bool, error) {
81 return ParseMaintenanceInterval(g.MaintenanceInterval)
82}
83
84// ParseMaintenanceInterval leest een duur. Leeg wordt 24 uur.
85func ParseMaintenanceInterval(s string) (time.Duration, bool, error) {
86 s = strings.TrimSpace(strings.ToLower(s))
87 if s == "" {
88 return DefaultMaintenanceInterval, true, nil
89 }
90 if s == "off" || s == "false" || s == "no" {
91 return 0, false, nil
92 }
93 if s == "0" || s == "0s" || s == "0h" || s == "0d" {
94 return 0, false, nil
95 }
96 if strings.HasSuffix(s, "d") {
97 n, err := strconv.Atoi(strings.TrimSuffix(s, "d"))
98 if err != nil || n <= 0 {
99 return 0, false, fmt.Errorf("ongeldig maintenance_interval %q", s)
100 }
101 return time.Duration(n) * 24 * time.Hour, true, nil
102 }
103 d, err := time.ParseDuration(s)
104 if err != nil {
105 return 0, false, fmt.Errorf("ongeldig maintenance_interval %q", s)
106 }
107 if d <= 0 {
108 return 0, false, nil
109 }
110 return d, true, nil
111}
112
113// SSH is de git-over-SSH-listener en het adres dat in clone-URL's staat.
114// Listen is waar dit proces bindt. PublicHost en PublicPort zijn wat
115// een gebruiker ziet; de ingress kan daar een andere poort voor gebruiken.
116type SSH struct {
117 Enabled bool `yaml:"enabled"`
118 Listen string `yaml:"listen"`
119 PublicHost string `yaml:"public_host"`
120 PublicPort int `yaml:"public_port"`
121}
122
123// Runner is de ingebouwde Docker-runner.
124type Runner struct {
125 Name string `yaml:"name"`
126}
127
128// CI stuurt de Docker-runner.
129type CI struct {
130 Enabled bool `yaml:"enabled"`
131 Docker string `yaml:"docker_binary"`
132 Concurrency int `yaml:"concurrency"`
133 Network string `yaml:"network"`
134 TimeoutSec int `yaml:"timeout_seconds"`
135 // UpdateMaxWaitMin: zo lang wacht een self-update op lopende jobs
136 // (en houdt nieuwe pipelines vast). Standaard 30.
137 UpdateMaxWaitMin int `yaml:"update_max_wait_minutes"`
138 Presets map[string]PresetConfig `yaml:"presets"`
139}
140
141// PresetConfig is één image-alias. image mapt direct. dockerfile wordt
142// door Steve gebouwd. from herschrijft de eerste FROM van een Dockerfile.
143type PresetConfig struct {
144 Image string `yaml:"image"`
145 Dockerfile string `yaml:"dockerfile"`
146 From string `yaml:"from"`
147}
148
149// ImageOverrides is de vorm die de runner en de infopagina lezen.
150func (c CI) ImageOverrides() map[string]images.Override {
151 if len(c.Presets) == 0 {
152 return nil
153 }
154 out := make(map[string]images.Override, len(c.Presets))
155 for name, p := range c.Presets {
156 out[name] = images.Override{Image: p.Image, Dockerfile: p.Dockerfile, From: p.From}
157 }
158 return out
159}
160
161// Load leest path en vult ontbrekende waarden aan.
162func Load(path string) (Config, error) {
163 raw, err := os.ReadFile(path)
164 if err != nil {
165 return Config{}, fmt.Errorf("config lezen: %w", err)
166 }
167 var c Config
168 if err := yaml.Unmarshal(raw, &c); err != nil {
169 return Config{}, fmt.Errorf("config: %w", err)
170 }
171 c.applyDefaults()
172 if v := os.Getenv("BLUEGIT_STATE_PATH"); v != "" {
173 c.StatePath = v
174 }
175 if v := os.Getenv("BLUEGIT_STORAGE_PATH"); v != "" {
176 c.StoragePath = v
177 }
178 if v := os.Getenv("BLUEGIT_CACHE_PATH"); v != "" {
179 c.CachePath = v
180 }
181 if v := os.Getenv("BLUEGIT_LISTEN"); v != "" {
182 c.Listen = v
183 }
184 if v := os.Getenv("BLUEGIT_AUTH_CLIENT_SECRET"); v != "" {
185 c.Auth.ClientSecret = v
186 }
187 if c.Auth.ClientSecret == "" && c.Auth.ClientSecretFile != "" {
188 b, err := os.ReadFile(c.Auth.ClientSecretFile)
189 if err != nil {
190 return Config{}, fmt.Errorf("clientgeheim: %w", err)
191 }
192 c.Auth.ClientSecret = strings.TrimSpace(string(b))
193 }
194 c.resolvePresetPaths(path)
195 if err := c.Validate(); err != nil {
196 return Config{}, err
197 }
198 return c, nil
199}
200
201func (c *Config) resolvePresetPaths(configFile string) {
202 if len(c.CI.Presets) == 0 {
203 return
204 }
205 base := filepath.Dir(configFile)
206 for name, p := range c.CI.Presets {
207 if p.Dockerfile != "" && !filepath.IsAbs(p.Dockerfile) {
208 p.Dockerfile = filepath.Join(base, p.Dockerfile)
209 c.CI.Presets[name] = p
210 }
211 }
212}
213
214func (c *Config) applyDefaults() {
215 if c.Listen == "" {
216 c.Listen = "127.0.0.1:8080"
217 }
218 if c.StatePath == "" {
219 c.StatePath = apppaths.DataDir("/var/lib/bluegit", "BlueGit")
220 }
221 if c.Auth.Mode == "" {
222 c.Auth.Mode = "oauth"
223 }
224 // base_url hoort bij oauth (auth.timfalken.com). Entra gebruikt issuer/tenant.
225 if c.Auth.Mode == "oauth" && c.Auth.BaseURL == "" {
226 c.Auth.BaseURL = "https://auth.timfalken.com"
227 }
228 if c.Auth.RedirectPath == "" {
229 c.Auth.RedirectPath = "/auth/callback"
230 }
231 if c.Auth.UserAgent == "" {
232 c.Auth.UserAgent = "BlueGitAccountClient/0.1"
233 }
234 if c.Auth.DevUser == "" {
235 c.Auth.DevUser = "tim"
236 }
237 if c.Auth.DevAuthID == 0 {
238 c.Auth.DevAuthID = 1
239 }
240 if c.Git.Binary == "" {
241 c.Git.Binary = "git"
242 }
243 if c.Git.DefaultBranch == "" {
244 c.Git.DefaultBranch = "master"
245 }
246 if c.SSH.Listen == "" {
247 c.SSH.Listen = "0.0.0.0:2222"
248 }
249 if c.CI.Docker == "" {
250 c.CI.Docker = "docker"
251 }
252 if c.CI.Concurrency <= 0 {
253 c.CI.Concurrency = 1
254 }
255 if c.CI.Network == "" {
256 c.CI.Network = "bridge"
257 }
258 if c.CI.TimeoutSec <= 0 {
259 c.CI.TimeoutSec = 1800
260 }
261 if strings.TrimSpace(c.Runner.Name) == "" {
262 c.Runner.Name = "Steve"
263 } else {
264 c.Runner.Name = strings.TrimSpace(c.Runner.Name)
265 }
266 c.Auth.BaseURL = strings.TrimRight(c.Auth.BaseURL, "/")
267 c.Auth.Issuer = strings.TrimRight(strings.TrimSpace(c.Auth.Issuer), "/")
268 c.Auth.TenantID = strings.TrimSpace(c.Auth.TenantID)
269 c.BaseURL = strings.TrimRight(c.BaseURL, "/")
270}
271
272// Validate keurt een configuratie goed of af.
273func (c *Config) Validate() error {
274 if c.BaseURL == "" {
275 return fmt.Errorf("base_url ontbreekt")
276 }
277 u, err := url.Parse(c.BaseURL)
278 if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
279 return fmt.Errorf("base_url moet een absolute http(s)-URL zijn")
280 }
281 if strings.TrimSpace(c.StatePath) == "" {
282 return fmt.Errorf("state_path ontbreekt")
283 }
284 if !strings.HasPrefix(c.Auth.RedirectPath, "/") {
285 return fmt.Errorf("auth.redirect_path moet met / beginnen")
286 }
287 switch c.Auth.Mode {
288 case "oauth":
289 if c.Auth.ClientID == "" || c.Auth.ClientSecret == "" {
290 return fmt.Errorf("oauth vereist auth.client_id en een clientgeheim (veld, bestand of BLUEGIT_AUTH_CLIENT_SECRET)")
291 }
292 if c.Auth.BaseURL == "" {
293 return fmt.Errorf("auth.base_url ontbreekt")
294 }
295 case "entra":
296 if c.Auth.TenantID == "" {
297 return fmt.Errorf("entra vereist auth.tenant_id")
298 }
299 if c.Auth.ClientID == "" || c.Auth.ClientSecret == "" {
300 return fmt.Errorf("entra vereist auth.client_id en een clientgeheim (veld, bestand of BLUEGIT_AUTH_CLIENT_SECRET)")
301 }
302 if c.Auth.Issuer != "" {
303 if err := validateIssuer(c.Auth.Issuer); err != nil {
304 return err
305 }
306 }
307 case "dev":
308 if strings.EqualFold(u.Hostname(), "git.timfalken.com") {
309 return fmt.Errorf("auth.mode dev is geweigerd voor git.timfalken.com")
310 }
311 default:
312 return fmt.Errorf("auth.mode moet oauth, entra of dev zijn")
313 }
314 if c.BehindProxy {
315 return fmt.Errorf("behind_proxy doet niets meer; zet trusted_proxies op het IP of CIDR van de ingress en haal behind_proxy weg")
316 }
317 set, err := realip.Parse(c.TrustedProxies)
318 if err != nil {
319 return err
320 }
321 c.proxies = set
322 if c.SSH.PublicPort < 0 || c.SSH.PublicPort > 65535 {
323 return fmt.Errorf("ssh.public_port moet tussen 0 en 65535 liggen")
324 }
325 if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
326 if strings.Contains(h, "://") || strings.ContainsAny(h, " /") || (strings.Contains(h, ":") && net.ParseIP(h) == nil) {
327 return fmt.Errorf("ssh.public_host moet een hostnaam of IP zijn, zonder schema of poort")
328 }
329 }
330 if _, _, err := net.SplitHostPort(c.SSH.Listen); err != nil {
331 return fmt.Errorf("ssh.listen moet host:poort zijn")
332 }
333 if _, err := images.Effective(c.CI.ImageOverrides()); err != nil {
334 return err
335 }
336 if _, _, err := c.Git.MaintenanceEvery(); err != nil {
337 return err
338 }
339 return nil
340}
341
342// ProxySet is de geparsede trusted_proxies-lijst. Nil betekent dat
343// niemand vertrouwd wordt.
344func (c Config) ProxySet() *realip.Set { return c.proxies }
345
346// SSHPublicHost is de host in een SSH-clone-URL.
347// Leeg in de config: de host van base_url.
348func (c Config) SSHPublicHost() string {
349 if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
350 return h
351 }
352 u, err := url.Parse(c.BaseURL)
353 if err != nil {
354 return ""
355 }
356 return u.Hostname()
357}
358
359// SSHPublicPort is de poort in een SSH-clone-URL.
360// 0 in de config: de poort van ssh.listen.
361func (c Config) SSHPublicPort() int {
362 if c.SSH.PublicPort > 0 {
363 return c.SSH.PublicPort
364 }
365 _, port, err := net.SplitHostPort(c.SSH.Listen)
366 if err != nil {
367 return 22
368 }
369 n, err := strconv.Atoi(port)
370 if err != nil || n <= 0 {
371 return 22
372 }
373 return n
374}
375
376// CloneSSH is de URL die een gebruiker kloont. Leeg als SSH uit staat.
377// Poort 22 geeft git@host:pad.git, een andere poort ssh://git@host:poort/pad.git.
378func (c Config) CloneSSH(repoPath string) string {
379 if !c.SSH.Enabled {
380 return ""
381 }
382 host := c.SSHPublicHost()
383 if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {
384 host = "[" + host + "]"
385 }
386 if c.SSHPublicPort() == 22 {
387 // Korte scp-vorm, zoals GitHub en GitLab. Die kent geen poort.
388 return fmt.Sprintf("git@%s:%s.git", host, repoPath)
389 }
390 return fmt.Sprintf("ssh://git@%s:%d/%s.git", host, c.SSHPublicPort(), repoPath)
391}
392
393// RedirectURI is de callback die bij de auth-server geregistreerd moet staan.
394func (c Config) RedirectURI() string {
395 return c.BaseURL + c.Auth.RedirectPath
396}
397
398// validateIssuer eist een absolute URL. HTTP is alleen toegestaan op localhost.
399func validateIssuer(issuer string) error {
400 iu, err := url.Parse(issuer)
401 if err != nil || (iu.Scheme != "https" && iu.Scheme != "http") || iu.Host == "" {
402 return fmt.Errorf("auth.issuer moet een absolute http(s)-URL zijn")
403 }
404 if iu.Scheme != "https" && !issuerLoopback(iu.Hostname()) {
405 return fmt.Errorf("auth.issuer moet HTTPS zijn (HTTP alleen op localhost)")
406 }
407 return nil
408}
409
410func issuerLoopback(host string) bool {
411 if strings.EqualFold(host, "localhost") {
412 return true
413 }
414 ip := net.ParseIP(host)
415 return ip != nil && ip.IsLoopback()
416}
417
418// EntraIssuer is de OIDC-issuer voor mode entra.
419func (c Config) EntraIssuer() string {
420 if c.Auth.Issuer != "" {
421 return c.Auth.Issuer
422 }
423 return "https://login.microsoftonline.com/" + c.Auth.TenantID + "/v2.0"
424}
425
426// Example is een startconfiguratie voor de mini-PC.
427func Example() string {
428 return `# BlueGit op de mini-PC. Kopieer naar /etc/bluegit/config.yml.
429# Plain HTTP. TLS en de publieke SSH-poort doet de ingress, zie docs/INGRESS.md.
430base_url: https://git.timfalken.com
431listen: 0.0.0.0:8080
432# Database, sleutel en het gekozen opslagpad. Dit is niet de datadisk.
433state_path: /var/lib/bluegit
434# storage_path blijft leeg. De installatiebeheerder kiest de datadisk
435# bij de eerste aanmelding. Er is geen standaardpad.
436# Alleen deze adressen mogen X-Forwarded-For en X-Real-IP zetten.
437# Zet hier het IP van de ingress, zoals de mini-PC die verbinding ziet.
438trusted_proxies:
439 - 10.0.0.2
440
441auth:
442 mode: oauth
443 base_url: https://auth.timfalken.com
444 # Het domein is de client_id. Registreer het pad /auth/callback bij /admin.
445 client_id: git.timfalken.com
446 # Laat leeg en zet BLUEGIT_AUTH_CLIENT_SECRET, of gebruik client_secret_file.
447 client_secret: ""
448 client_secret_file: /etc/bluegit/client_secret
449 redirect_path: /auth/callback
450 user_agent: BlueGitAccountClient/0.1
451 # Alternatief: Microsoft Entra ID (OIDC, één tenant). Zet mode op entra
452 # en vul tenant_id + client_id; geheim hetzelfde als hierboven.
453 # mode: entra
454 # tenant_id: 00000000-0000-0000-0000-000000000000
455 # client_id: 11111111-1111-1111-1111-111111111111
456 # issuer blijft leeg, tenzij je een andere cloud of testissuer nodig hebt.
457
458git:
459 binary: git
460 default_branch: master
461 # Periodiek onderhoud van bare repositories (git maintenance of
462 # git gc --auto). Standaard 24h. Zet op off om uit te schakelen.
463 # Nooit --prune=now; één repo tegelijk, met gits eigen locking.
464 # maintenance_interval: 24h
465
466ssh:
467 enabled: true
468 # Waar dit proces git-SSH aanneemt. De SSH van het besturingssysteem blijft vrij.
469 listen: 0.0.0.0:2222
470 # Wat gebruikers in de clone-URL zien. De ingress stuurt poort 22 hiernaartoe.
471 public_host: git.timfalken.com
472 public_port: 22
473
474runner:
475 name: Steve
476
477ci:
478 enabled: true
479 docker_binary: docker
480 concurrency: 1
481 network: bridge
482 timeout_seconds: 1800
483 # Image-aliassen voor jobs. bluegit/base, bluegit/node, bluegit/python,
484 # bluegit/go, bluegit/rust, bluegit/java en bluegit/dotnet zijn ingebouwd.
485 # Een eigen alias wijst naar een Dockerfile of naar een kant-en-klaar image.
486 # presets:
487 # team/tools:
488 # image: alpine:3.20
489 # team/build:
490 # dockerfile: /etc/bluegit/images/build/Dockerfile
491 # bluegit/node:
492 # from: node:22-bookworm
493`
494}