BlueGit

timfa bluegit

Files

bluegit / internal / config / config.go

config.go

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