BlueGit

timfa bluegit

Files

bluegit / internal / config / config.go

config.go

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