BlueGit

timfa bluegit

Files

bluegit / internal / config / config.go

config.go

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