BlueGit

timfa bluegit

Files

bluegit / internal / config / config.go

config.go

config.go 15.7 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 applyEnv(&c)
173 if err := fillSecretFromFile(&c); err != nil {
174 return Config{}, err
175 }
176 c.resolvePresetPaths(path)
177 if err := c.Validate(); err != nil {
178 return Config{}, err
179 }
180 return c, nil
181}
182
183// applyEnv laat omgevingsvariabelen winnen van bestandswaarden.
184func applyEnv(c *Config) {
185 if v := os.Getenv("BLUEGIT_STATE_PATH"); v != "" {
186 c.StatePath = v
187 }
188 if v := os.Getenv("BLUEGIT_STORAGE_PATH"); v != "" {
189 c.StoragePath = v
190 }
191 if v := os.Getenv("BLUEGIT_CACHE_PATH"); v != "" {
192 c.CachePath = v
193 }
194 if v := os.Getenv("BLUEGIT_LISTEN"); v != "" {
195 c.Listen = v
196 }
197 if v := os.Getenv("BLUEGIT_AUTH_CLIENT_SECRET"); v != "" {
198 c.Auth.ClientSecret = v
199 }
200}
201
202// fillSecretFromFile vult een leeg clientgeheim uit auth.client_secret_file.
203func fillSecretFromFile(c *Config) error {
204 if c.Auth.ClientSecret != "" || strings.TrimSpace(c.Auth.ClientSecretFile) == "" {
205 return nil
206 }
207 b, err := os.ReadFile(c.Auth.ClientSecretFile)
208 if err != nil {
209 return fmt.Errorf("clientgeheim: %w", err)
210 }
211 c.Auth.ClientSecret = strings.TrimSpace(string(b))
212 return nil
213}
214
215func (c *Config) resolvePresetPaths(configFile string) {
216 if len(c.CI.Presets) == 0 {
217 return
218 }
219 base := filepath.Dir(configFile)
220 for name, p := range c.CI.Presets {
221 if p.Dockerfile != "" && !filepath.IsAbs(p.Dockerfile) {
222 p.Dockerfile = filepath.Join(base, p.Dockerfile)
223 c.CI.Presets[name] = p
224 }
225 }
226}
227
228func (c *Config) applyDefaults() {
229 if c.Listen == "" {
230 c.Listen = "127.0.0.1:8080"
231 }
232 if c.StatePath == "" {
233 c.StatePath = apppaths.DataDir("/var/lib/bluegit", "BlueGit")
234 }
235 if c.Auth.Mode == "" {
236 c.Auth.Mode = "oauth"
237 }
238 // base_url hoort bij oauth (auth.timfalken.com). Entra gebruikt issuer/tenant.
239 if c.Auth.Mode == "oauth" && c.Auth.BaseURL == "" {
240 c.Auth.BaseURL = "https://auth.timfalken.com"
241 }
242 if c.Auth.RedirectPath == "" {
243 c.Auth.RedirectPath = "/auth/callback"
244 }
245 if c.Auth.UserAgent == "" {
246 c.Auth.UserAgent = "BlueGitAccountClient/0.1"
247 }
248 if c.Auth.DevUser == "" {
249 c.Auth.DevUser = "tim"
250 }
251 if c.Auth.DevAuthID == 0 {
252 c.Auth.DevAuthID = 1
253 }
254 if c.Git.Binary == "" {
255 c.Git.Binary = "git"
256 }
257 if c.Git.DefaultBranch == "" {
258 c.Git.DefaultBranch = "master"
259 }
260 if c.SSH.Listen == "" {
261 c.SSH.Listen = "0.0.0.0:2222"
262 }
263 if c.CI.Docker == "" {
264 c.CI.Docker = "docker"
265 }
266 if c.CI.Concurrency <= 0 {
267 c.CI.Concurrency = 1
268 }
269 if c.CI.Network == "" {
270 c.CI.Network = "bridge"
271 }
272 if c.CI.TimeoutSec <= 0 {
273 c.CI.TimeoutSec = 1800
274 }
275 if strings.TrimSpace(c.Runner.Name) == "" {
276 c.Runner.Name = "Steve"
277 } else {
278 c.Runner.Name = strings.TrimSpace(c.Runner.Name)
279 }
280 c.Auth.BaseURL = strings.TrimRight(c.Auth.BaseURL, "/")
281 c.Auth.Issuer = strings.TrimRight(strings.TrimSpace(c.Auth.Issuer), "/")
282 c.Auth.TenantID = strings.TrimSpace(c.Auth.TenantID)
283 c.BaseURL = strings.TrimRight(c.BaseURL, "/")
284}
285
286// Validate keurt een configuratie goed of af.
287func (c *Config) Validate() error {
288 if c.BaseURL == "" {
289 return fmt.Errorf("base_url ontbreekt")
290 }
291 u, err := url.Parse(c.BaseURL)
292 if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
293 return fmt.Errorf("base_url moet een absolute http(s)-URL zijn")
294 }
295 if strings.TrimSpace(c.StatePath) == "" {
296 return fmt.Errorf("state_path ontbreekt")
297 }
298 if !strings.HasPrefix(c.Auth.RedirectPath, "/") {
299 return fmt.Errorf("auth.redirect_path moet met / beginnen")
300 }
301 switch c.Auth.Mode {
302 case "oauth":
303 if c.Auth.ClientID == "" || c.Auth.ClientSecret == "" {
304 return fmt.Errorf("oauth vereist auth.client_id en een clientgeheim (veld, bestand of BLUEGIT_AUTH_CLIENT_SECRET)")
305 }
306 if c.Auth.BaseURL == "" {
307 return fmt.Errorf("auth.base_url ontbreekt")
308 }
309 case "entra":
310 if c.Auth.TenantID == "" {
311 return fmt.Errorf("entra vereist auth.tenant_id")
312 }
313 if c.Auth.ClientID == "" || c.Auth.ClientSecret == "" {
314 return fmt.Errorf("entra vereist auth.client_id en een clientgeheim (veld, bestand of BLUEGIT_AUTH_CLIENT_SECRET)")
315 }
316 if c.Auth.Issuer != "" {
317 if err := validateIssuer(c.Auth.Issuer); err != nil {
318 return err
319 }
320 }
321 case "dev":
322 if strings.EqualFold(u.Hostname(), "git.timfalken.com") {
323 return fmt.Errorf("auth.mode dev is geweigerd voor git.timfalken.com")
324 }
325 default:
326 return fmt.Errorf("auth.mode moet oauth, entra of dev zijn")
327 }
328 if c.BehindProxy {
329 return fmt.Errorf("behind_proxy doet niets meer; zet trusted_proxies op het IP of CIDR van de ingress en haal behind_proxy weg")
330 }
331 set, err := realip.Parse(c.TrustedProxies)
332 if err != nil {
333 return err
334 }
335 c.proxies = set
336 if c.SSH.PublicPort < 0 || c.SSH.PublicPort > 65535 {
337 return fmt.Errorf("ssh.public_port moet tussen 0 en 65535 liggen")
338 }
339 if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
340 if strings.Contains(h, "://") || strings.ContainsAny(h, " /") || (strings.Contains(h, ":") && net.ParseIP(h) == nil) {
341 return fmt.Errorf("ssh.public_host moet een hostnaam of IP zijn, zonder schema of poort")
342 }
343 }
344 if _, _, err := net.SplitHostPort(c.SSH.Listen); err != nil {
345 return fmt.Errorf("ssh.listen moet host:poort zijn")
346 }
347 if _, err := images.Effective(c.CI.ImageOverrides()); err != nil {
348 return err
349 }
350 if _, _, err := c.Git.MaintenanceEvery(); err != nil {
351 return err
352 }
353 return nil
354}
355
356// ProxySet is de geparsede trusted_proxies-lijst. Nil betekent dat
357// niemand vertrouwd wordt.
358func (c Config) ProxySet() *realip.Set { return c.proxies }
359
360// SSHPublicHost is de host in een SSH-clone-URL.
361// Leeg in de config: de host van base_url.
362func (c Config) SSHPublicHost() string {
363 if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
364 return h
365 }
366 u, err := url.Parse(c.BaseURL)
367 if err != nil {
368 return ""
369 }
370 return u.Hostname()
371}
372
373// SSHPublicPort is de poort in een SSH-clone-URL.
374// 0 in de config: de poort van ssh.listen.
375func (c Config) SSHPublicPort() int {
376 if c.SSH.PublicPort > 0 {
377 return c.SSH.PublicPort
378 }
379 _, port, err := net.SplitHostPort(c.SSH.Listen)
380 if err != nil {
381 return 22
382 }
383 n, err := strconv.Atoi(port)
384 if err != nil || n <= 0 {
385 return 22
386 }
387 return n
388}
389
390// CloneSSH is de URL die een gebruiker kloont. Leeg als SSH uit staat.
391// Poort 22 geeft git@host:pad.git, een andere poort ssh://git@host:poort/pad.git.
392func (c Config) CloneSSH(repoPath string) string {
393 if !c.SSH.Enabled {
394 return ""
395 }
396 host := c.SSHPublicHost()
397 if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {
398 host = "[" + host + "]"
399 }
400 if c.SSHPublicPort() == 22 {
401 // Korte scp-vorm, zoals GitHub en GitLab. Die kent geen poort.
402 return fmt.Sprintf("git@%s:%s.git", host, repoPath)
403 }
404 return fmt.Sprintf("ssh://git@%s:%d/%s.git", host, c.SSHPublicPort(), repoPath)
405}
406
407// RedirectURI is de callback die bij de auth-server geregistreerd moet staan.
408func (c Config) RedirectURI() string {
409 return c.BaseURL + c.Auth.RedirectPath
410}
411
412// validateIssuer eist een absolute URL. HTTP is alleen toegestaan op localhost.
413func validateIssuer(issuer string) error {
414 iu, err := url.Parse(issuer)
415 if err != nil || (iu.Scheme != "https" && iu.Scheme != "http") || iu.Host == "" {
416 return fmt.Errorf("auth.issuer moet een absolute http(s)-URL zijn")
417 }
418 if iu.Scheme != "https" && !issuerLoopback(iu.Hostname()) {
419 return fmt.Errorf("auth.issuer moet HTTPS zijn (HTTP alleen op localhost)")
420 }
421 return nil
422}
423
424func issuerLoopback(host string) bool {
425 if strings.EqualFold(host, "localhost") {
426 return true
427 }
428 ip := net.ParseIP(host)
429 return ip != nil && ip.IsLoopback()
430}
431
432// EntraIssuer is de OIDC-issuer voor mode entra.
433func (c Config) EntraIssuer() string {
434 if c.Auth.Issuer != "" {
435 return c.Auth.Issuer
436 }
437 return "https://login.microsoftonline.com/" + c.Auth.TenantID + "/v2.0"
438}
439
440// Example is een startconfiguratie voor de mini-PC.
441func Example() string {
442 return `# BlueGit op de mini-PC. Kopieer naar /etc/bluegit/config.yml voor de eerste start.
443# Daarna: Beheer → Instellingen. Dit bestand blijft ongewijzigd als terugval.
444# Plain HTTP. TLS en de publieke SSH-poort doet de ingress, zie docs/INGRESS.md.
445base_url: https://git.timfalken.com
446listen: 0.0.0.0:8080
447# Database, sleutel en het gekozen opslagpad. Dit is niet de datadisk.
448state_path: /var/lib/bluegit
449# storage_path blijft leeg. De installatiebeheerder kiest de datadisk
450# bij de eerste aanmelding. Er is geen standaardpad.
451# Alleen deze adressen mogen X-Forwarded-For en X-Real-IP zetten.
452# Zet hier het IP van de ingress, zoals de mini-PC die verbinding ziet.
453trusted_proxies:
454 - 10.0.0.2
455
456auth:
457 mode: oauth
458 base_url: https://auth.timfalken.com
459 # Het domein is de client_id. Registreer het pad /auth/callback bij /admin.
460 client_id: git.timfalken.com
461 # Laat leeg en zet BLUEGIT_AUTH_CLIENT_SECRET, of gebruik client_secret_file.
462 client_secret: ""
463 client_secret_file: /etc/bluegit/client_secret
464 redirect_path: /auth/callback
465 user_agent: BlueGitAccountClient/0.1
466 # Alternatief: Microsoft Entra ID (OIDC, één tenant). Zet mode op entra
467 # en vul tenant_id + client_id; geheim hetzelfde als hierboven.
468 # mode: entra
469 # tenant_id: 00000000-0000-0000-0000-000000000000
470 # client_id: 11111111-1111-1111-1111-111111111111
471 # issuer blijft leeg, tenzij je een andere cloud of testissuer nodig hebt.
472
473git:
474 binary: git
475 default_branch: master
476 # Periodiek onderhoud van bare repositories (git maintenance of
477 # git gc --auto). Standaard 24h. Zet op off om uit te schakelen.
478 # Nooit --prune=now; één repo tegelijk, met gits eigen locking.
479 # maintenance_interval: 24h
480
481ssh:
482 enabled: true
483 # Waar dit proces git-SSH aanneemt. De SSH van het besturingssysteem blijft vrij.
484 listen: 0.0.0.0:2222
485 # Wat gebruikers in de clone-URL zien. De ingress stuurt poort 22 hiernaartoe.
486 public_host: git.timfalken.com
487 public_port: 22
488
489runner:
490 name: Steve
491
492ci:
493 enabled: true
494 docker_binary: docker
495 concurrency: 1
496 network: bridge
497 timeout_seconds: 1800
498 # Image-aliassen voor jobs. bluegit/base, bluegit/node, bluegit/python,
499 # bluegit/go, bluegit/rust, bluegit/java en bluegit/dotnet zijn ingebouwd.
500 # Een eigen alias wijst naar een Dockerfile of naar een kant-en-klaar image.
501 # presets:
502 # team/tools:
503 # image: alpine:3.20
504 # team/build:
505 # dockerfile: /etc/bluegit/images/build/Dockerfile
506 # bluegit/node:
507 # from: node:22-bookworm
508`
509}