BlueGit

timfa bluegit

Files

bluegit / internal / config / config.go

config.go

config.go 13.0 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 iu, err := url.Parse(c.Auth.Issuer)
261 if err != nil || (iu.Scheme != "https" && iu.Scheme != "http") || iu.Host == "" {
262 return fmt.Errorf("auth.issuer moet een absolute http(s)-URL zijn")
263 }
264 }
265 case "dev":
266 if strings.EqualFold(u.Hostname(), "git.timfalken.com") {
267 return fmt.Errorf("auth.mode dev is geweigerd voor git.timfalken.com")
268 }
269 default:
270 return fmt.Errorf("auth.mode moet oauth, entra of dev zijn")
271 }
272 if c.BehindProxy {
273 return fmt.Errorf("behind_proxy doet niets meer; zet trusted_proxies op het IP of CIDR van de ingress en haal behind_proxy weg")
274 }
275 set, err := realip.Parse(c.TrustedProxies)
276 if err != nil {
277 return err
278 }
279 c.proxies = set
280 if c.SSH.PublicPort < 0 || c.SSH.PublicPort > 65535 {
281 return fmt.Errorf("ssh.public_port moet tussen 0 en 65535 liggen")
282 }
283 if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
284 if strings.Contains(h, "://") || strings.ContainsAny(h, " /") || (strings.Contains(h, ":") && net.ParseIP(h) == nil) {
285 return fmt.Errorf("ssh.public_host moet een hostnaam of IP zijn, zonder schema of poort")
286 }
287 }
288 if _, _, err := net.SplitHostPort(c.SSH.Listen); err != nil {
289 return fmt.Errorf("ssh.listen moet host:poort zijn")
290 }
291 if _, err := images.Effective(c.CI.ImageOverrides()); err != nil {
292 return err
293 }
294 return nil
295}
296
297// ProxySet is de geparsede trusted_proxies-lijst. Nil betekent dat
298// niemand vertrouwd wordt.
299func (c Config) ProxySet() *realip.Set { return c.proxies }
300
301// SSHPublicHost is de host in een SSH-clone-URL.
302// Leeg in de config: de host van base_url.
303func (c Config) SSHPublicHost() string {
304 if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
305 return h
306 }
307 u, err := url.Parse(c.BaseURL)
308 if err != nil {
309 return ""
310 }
311 return u.Hostname()
312}
313
314// SSHPublicPort is de poort in een SSH-clone-URL.
315// 0 in de config: de poort van ssh.listen.
316func (c Config) SSHPublicPort() int {
317 if c.SSH.PublicPort > 0 {
318 return c.SSH.PublicPort
319 }
320 _, port, err := net.SplitHostPort(c.SSH.Listen)
321 if err != nil {
322 return 22
323 }
324 n, err := strconv.Atoi(port)
325 if err != nil || n <= 0 {
326 return 22
327 }
328 return n
329}
330
331// CloneSSH is de URL die een gebruiker kloont. Leeg als SSH uit staat.
332// Poort 22 geeft git@host:pad.git, een andere poort ssh://git@host:poort/pad.git.
333func (c Config) CloneSSH(repoPath string) string {
334 if !c.SSH.Enabled {
335 return ""
336 }
337 host := c.SSHPublicHost()
338 if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {
339 host = "[" + host + "]"
340 }
341 if c.SSHPublicPort() == 22 {
342 // Korte scp-vorm, zoals GitHub en GitLab. Die kent geen poort.
343 return fmt.Sprintf("git@%s:%s.git", host, repoPath)
344 }
345 return fmt.Sprintf("ssh://git@%s:%d/%s.git", host, c.SSHPublicPort(), repoPath)
346}
347
348// RedirectURI is de callback die bij de auth-server geregistreerd moet staan.
349func (c Config) RedirectURI() string {
350 return c.BaseURL + c.Auth.RedirectPath
351}
352
353// EntraIssuer is de OIDC-issuer voor mode entra.
354func (c Config) EntraIssuer() string {
355 if c.Auth.Issuer != "" {
356 return c.Auth.Issuer
357 }
358 return "https://login.microsoftonline.com/" + c.Auth.TenantID + "/v2.0"
359}
360
361// Example is een startconfiguratie voor de mini-PC.
362func Example() string {
363 return `# BlueGit op de mini-PC. Kopieer naar /etc/bluegit/config.yml.
364# Plain HTTP. TLS en de publieke SSH-poort doet de ingress, zie docs/INGRESS.md.
365base_url: https://git.timfalken.com
366listen: 0.0.0.0:8080
367# Database, sleutel en het gekozen opslagpad. Dit is niet de datadisk.
368state_path: /var/lib/bluegit
369# storage_path blijft leeg. De installatiebeheerder kiest de datadisk
370# bij de eerste aanmelding. Er is geen standaardpad.
371# Alleen deze adressen mogen X-Forwarded-For en X-Real-IP zetten.
372# Zet hier het IP van de ingress, zoals de mini-PC die verbinding ziet.
373trusted_proxies:
374 - 10.0.0.2
375
376auth:
377 mode: oauth
378 base_url: https://auth.timfalken.com
379 # Het domein is de client_id. Registreer het pad /auth/callback bij /admin.
380 client_id: git.timfalken.com
381 # Laat leeg en zet BLUEGIT_AUTH_CLIENT_SECRET, of gebruik client_secret_file.
382 client_secret: ""
383 client_secret_file: /etc/bluegit/client_secret
384 redirect_path: /auth/callback
385 user_agent: BlueGitAccountClient/0.1
386 # Alternatief: Microsoft Entra ID (OIDC, één tenant). Zet mode op entra
387 # en vul tenant_id + client_id; geheim hetzelfde als hierboven.
388 # mode: entra
389 # tenant_id: 00000000-0000-0000-0000-000000000000
390 # client_id: 11111111-1111-1111-1111-111111111111
391 # issuer blijft leeg, tenzij je een andere cloud of testissuer nodig hebt.
392
393git:
394 binary: git
395 default_branch: master
396
397ssh:
398 enabled: true
399 # Waar dit proces git-SSH aanneemt. De SSH van het besturingssysteem blijft vrij.
400 listen: 0.0.0.0:2222
401 # Wat gebruikers in de clone-URL zien. De ingress stuurt poort 22 hiernaartoe.
402 public_host: git.timfalken.com
403 public_port: 22
404
405runner:
406 name: Steve
407
408ci:
409 enabled: true
410 docker_binary: docker
411 concurrency: 1
412 network: bridge
413 timeout_seconds: 1800
414 # Image-aliassen voor jobs. bluegit/base, bluegit/node, bluegit/python,
415 # bluegit/go, bluegit/rust, bluegit/java en bluegit/dotnet zijn ingebouwd.
416 # Een eigen alias wijst naar een Dockerfile of naar een kant-en-klaar image.
417 # presets:
418 # team/tools:
419 # image: alpine:3.20
420 # team/build:
421 # dockerfile: /etc/bluegit/images/build/Dockerfile
422 # bluegit/node:
423 # from: node:22-bookworm
424`
425}