BlueGit

timfa bluegit

Files

bluegit / internal / config / config.go

config.go

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