BlueGit

timfa bluegit

Files

bluegit / internal / server / admin_instance.go

admin_instance.go

admin_instance.go 12.9 KiB Download Raw
1package server
2
3import (
4 "net/http"
5 "path/filepath"
6 "strconv"
7 "strings"
8
9 "gitlab.com/Timfa/bluegit/internal/auth"
10 "gitlab.com/Timfa/bluegit/internal/config"
11 "gitlab.com/Timfa/bluegit/internal/i18n"
12)
13
14// ApplySSH past een wijziging van de git-SSH-listener live toe.
15// Nil: alleen opslaan; de listener verandert bij de volgende start.
16type ApplySSHFunc func(enabled bool, listen string) error
17
18// InstanceView is de machineconfiguratie voor de UI en API, zonder geheimen.
19type InstanceView struct {
20 BaseURL string `json:"base_url"`
21 Listen string `json:"listen"`
22 Listening string `json:"listening,omitempty"`
23 ListenNotice string `json:"listen_notice,omitempty"`
24 StatePath string `json:"state_path"`
25 ConfigPath string `json:"config_path,omitempty"`
26 SettingsPath string `json:"settings_path,omitempty"`
27 StoragePath string `json:"storage_path,omitempty"`
28 TrustedProxies []string `json:"trusted_proxies"`
29 Auth InstanceAuthView `json:"auth"`
30 Git InstanceGitView `json:"git"`
31 SSH InstanceSSHView `json:"ssh"`
32 Runner InstanceRunnerView `json:"runner"`
33 CI InstanceCIView `json:"ci"`
34}
35
36// InstanceAuthView is auth zonder het clientgeheim zelf.
37type InstanceAuthView struct {
38 Mode string `json:"mode"`
39 BaseURL string `json:"base_url"`
40 ClientID string `json:"client_id"`
41 ClientSecretSet bool `json:"client_secret_set"`
42 ClientSecretFile string `json:"client_secret_file,omitempty"`
43 RedirectPath string `json:"redirect_path"`
44 UserAgent string `json:"user_agent"`
45 TenantID string `json:"tenant_id,omitempty"`
46 Issuer string `json:"issuer,omitempty"`
47 DevUser string `json:"dev_user,omitempty"`
48 DevAuthID int64 `json:"dev_auth_id,omitempty"`
49}
50
51// InstanceGitView is het git-blok.
52type InstanceGitView struct {
53 Binary string `json:"binary"`
54 DefaultBranch string `json:"default_branch"`
55 HookBinary string `json:"hook_binary,omitempty"`
56 MaintenanceInterval string `json:"maintenance_interval,omitempty"`
57}
58
59// InstanceSSHView is het ssh-blok.
60type InstanceSSHView struct {
61 Enabled bool `json:"enabled"`
62 Listen string `json:"listen"`
63 PublicHost string `json:"public_host,omitempty"`
64 PublicPort int `json:"public_port"`
65}
66
67// InstanceRunnerView is de naam van de ingebouwde runner.
68type InstanceRunnerView struct {
69 Name string `json:"name"`
70}
71
72// InstanceCIView is het ci-blok zonder presets (die staan onder Beheer → Runner).
73type InstanceCIView struct {
74 Enabled bool `json:"enabled"`
75 Docker string `json:"docker_binary"`
76 Concurrency int `json:"concurrency"`
77 Network string `json:"network"`
78 TimeoutSec int `json:"timeout_seconds"`
79 UpdateMaxWaitMin int `json:"update_max_wait_minutes"`
80}
81
82func (s *Server) instanceView() InstanceView {
83 c := s.Cfg
84 return InstanceView{
85 BaseURL: c.BaseURL,
86 Listen: c.Listen,
87 Listening: s.BoundAddr(),
88 ListenNotice: s.ListenNotice,
89 StatePath: c.StatePath,
90 ConfigPath: s.ConfigPath,
91 SettingsPath: s.SettingsPath,
92 StoragePath: s.StoragePath(),
93 TrustedProxies: append([]string(nil), c.TrustedProxies...),
94 Auth: InstanceAuthView{
95 Mode: c.Auth.Mode,
96 BaseURL: c.Auth.BaseURL,
97 ClientID: c.Auth.ClientID,
98 ClientSecretSet: strings.TrimSpace(c.Auth.ClientSecret) != "",
99 ClientSecretFile: c.Auth.ClientSecretFile,
100 RedirectPath: c.Auth.RedirectPath,
101 UserAgent: c.Auth.UserAgent,
102 TenantID: c.Auth.TenantID,
103 Issuer: c.Auth.Issuer,
104 DevUser: c.Auth.DevUser,
105 DevAuthID: c.Auth.DevAuthID,
106 },
107 Git: InstanceGitView{
108 Binary: c.Git.Binary,
109 DefaultBranch: c.Git.DefaultBranch,
110 HookBinary: c.Git.HookBinary,
111 MaintenanceInterval: c.Git.MaintenanceInterval,
112 },
113 SSH: InstanceSSHView{
114 Enabled: c.SSH.Enabled,
115 Listen: c.SSH.Listen,
116 PublicHost: c.SSH.PublicHost,
117 PublicPort: c.SSH.PublicPort,
118 },
119 Runner: InstanceRunnerView{Name: c.Runner.Name},
120 CI: InstanceCIView{
121 Enabled: c.CI.Enabled,
122 Docker: c.CI.Docker,
123 Concurrency: c.CI.Concurrency,
124 Network: c.CI.Network,
125 TimeoutSec: c.CI.TimeoutSec,
126 UpdateMaxWaitMin: c.CI.UpdateMaxWaitMin,
127 },
128 }
129}
130
131func (s *Server) adminSettings(w http.ResponseWriter, r *http.Request) {
132 if ok, _ := s.adminOnly(w, r); !ok {
133 return
134 }
135 v := s.view(w, r, "title.adminSettings")
136 v.Page = "adminsettings"
137 iv := s.instanceView()
138 v.Instance = &iv
139 s.render(w, "adminsettings", v)
140}
141
142func (s *Server) adminSettingsSave(w http.ResponseWriter, r *http.Request) {
143 if ok, _ := s.adminOnly(w, r); !ok || !s.csrfOK(w, r) {
144 return
145 }
146 _ = r.ParseForm()
147 patch := patchFromForm(r)
148 bound, err := s.ApplyInstance(patch)
149 if err != nil {
150 s.redirect(w, r, "/admin/settings", "", s.trErr(r, err))
151 return
152 }
153 msg := s.tr(r, "admin.settings.saved")
154 if bound != "" {
155 msg = s.tr(r, "admin.settings.listenNow", bound)
156 }
157 s.redirect(w, r, "/admin/settings", msg, "")
158}
159
160func (s *Server) apiAdminSettings(w http.ResponseWriter, r *http.Request) {
161 if !apiUser(r).InstanceAdmin {
162 s.writeAPIErr(w, r, fail(403, i18n.E("err.forbidden")))
163 return
164 }
165 switch r.Method {
166 case http.MethodGet:
167 writeJSON(w, http.StatusOK, s.instanceView())
168 case http.MethodPut:
169 var in instancePatchJSON
170 if err := readJSON(r, &in); err != nil {
171 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
172 return
173 }
174 notice, err := s.ApplyInstance(in.toPatch())
175 if !s.apiOK(w, r, err) {
176 return
177 }
178 out := s.instanceView()
179 out.ListenNotice = notice
180 writeJSON(w, http.StatusOK, out)
181 default:
182 w.WriteHeader(http.StatusMethodNotAllowed)
183 }
184}
185
186// ApplyInstance valideert, bindt listen/SSH indien nodig, slaat settings.yml
187// op en zet de nieuwe waarden live. config.yml blijft ongemoeid.
188func (s *Server) ApplyInstance(patch config.Persisted) (string, error) {
189 next, saved := config.MergeUpdate(s.Cfg, patch)
190 if err := next.Validate(); err != nil {
191 return "", fail(400, err)
192 }
193 notice := ""
194 if next.Listen != s.Cfg.Listen && s.isServing() {
195 if err := s.Relisten(next.Listen); err != nil {
196 return "", fail(400, err)
197 }
198 notice = s.BoundAddr()
199 s.ListenNotice = notice
200 }
201 if s.ApplySSH != nil && (next.SSH.Enabled != s.Cfg.SSH.Enabled || next.SSH.Listen != s.Cfg.SSH.Listen) {
202 if err := s.ApplySSH(next.SSH.Enabled, next.SSH.Listen); err != nil {
203 return notice, fail(400, err)
204 }
205 }
206 if dir := s.StateDir; dir != "" {
207 if err := config.SaveSettings(dir, saved); err != nil {
208 return notice, err
209 }
210 s.SettingsPath = filepath.Join(dir, config.SettingsFile)
211 }
212 s.Cfg = next
213 if next.Git.Binary != "" {
214 s.Git = next.Git.Binary
215 }
216 if next.Git.HookBinary != "" {
217 s.HookBin = next.Git.HookBinary
218 }
219 s.applyAuth(next)
220 if s.Runner != nil {
221 s.Runner.BaseURL = next.BaseURL
222 if next.Runner.Name != "" {
223 s.Runner.Name = next.Runner.Name
224 }
225 if next.CI.Docker != "" {
226 s.Runner.Docker = next.CI.Docker
227 }
228 }
229 return notice, nil
230}
231
232func (s *Server) applyAuth(cfg config.Config) {
233 switch cfg.Auth.Mode {
234 case "dev":
235 s.Auth = auth.Dev{Username: cfg.Auth.DevUser, AuthID: cfg.Auth.DevAuthID}
236 s.Dev = true
237 case "entra":
238 s.Auth = auth.NewEntra(cfg.EntraIssuer(), cfg.Auth.TenantID, cfg.Auth.ClientID, cfg.Auth.ClientSecret, cfg.Auth.UserAgent)
239 s.Dev = false
240 default:
241 s.Auth = auth.NewTimFalken(cfg.Auth.BaseURL, cfg.Auth.ClientID, cfg.Auth.ClientSecret, cfg.Auth.UserAgent)
242 s.Dev = false
243 }
244 if m, ok := s.Auth.(auth.Mailer); ok && cfg.Auth.ClientSecret != "" {
245 s.Mail = m
246 } else {
247 s.Mail = nil
248 }
249}
250
251func formLast(r *http.Request, name string) (string, bool) {
252 vals, ok := r.Form[name]
253 if !ok || len(vals) == 0 {
254 return "", false
255 }
256 return strings.TrimSpace(vals[len(vals)-1]), true
257}
258
259func patchFromForm(r *http.Request) config.Persisted {
260 str := func(name string) *string {
261 v, ok := formLast(r, name)
262 if !ok {
263 return nil
264 }
265 return &v
266 }
267 boolp := func(name string) *bool {
268 v, ok := formLast(r, name)
269 if !ok {
270 return nil
271 }
272 b := v == "1" || v == "on" || v == "true"
273 return &b
274 }
275 intp := func(name string) *int {
276 v, ok := formLast(r, name)
277 if !ok {
278 return nil
279 }
280 n, err := strconv.Atoi(v)
281 if err != nil {
282 return nil
283 }
284 return &n
285 }
286 int64p := func(name string) *int64 {
287 v, ok := formLast(r, name)
288 if !ok {
289 return nil
290 }
291 n, err := strconv.ParseInt(v, 10, 64)
292 if err != nil {
293 return nil
294 }
295 return &n
296 }
297 var proxies *[]string
298 if _, ok := r.Form["trusted_proxies"]; ok {
299 var list []string
300 for _, line := range strings.Split(r.FormValue("trusted_proxies"), "\n") {
301 line = strings.TrimSpace(line)
302 if line != "" {
303 list = append(list, line)
304 }
305 }
306 if list == nil {
307 list = []string{}
308 }
309 proxies = &list
310 }
311 p := config.Persisted{
312 BaseURL: str("base_url"),
313 Listen: str("listen"),
314 TrustedProxies: proxies,
315 Auth: &config.PersistedAuth{
316 Mode: str("auth.mode"),
317 BaseURL: str("auth.base_url"),
318 ClientID: str("auth.client_id"),
319 ClientSecret: str("auth.client_secret"),
320 ClientSecretFile: str("auth.client_secret_file"),
321 RedirectPath: str("auth.redirect_path"),
322 UserAgent: str("auth.user_agent"),
323 DevUser: str("auth.dev_user"),
324 DevAuthID: int64p("auth.dev_auth_id"),
325 TenantID: str("auth.tenant_id"),
326 Issuer: str("auth.issuer"),
327 },
328 Git: &config.PersistedGit{
329 Binary: str("git.binary"),
330 DefaultBranch: str("git.default_branch"),
331 HookBinary: str("git.hook_binary"),
332 MaintenanceInterval: str("git.maintenance_interval"),
333 },
334 SSH: &config.PersistedSSH{
335 Enabled: boolp("ssh.enabled"),
336 Listen: str("ssh.listen"),
337 PublicHost: str("ssh.public_host"),
338 PublicPort: intp("ssh.public_port"),
339 },
340 Runner: &config.PersistedRunner{Name: str("runner.name")},
341 CI: &config.PersistedCI{
342 Enabled: boolp("ci.enabled"),
343 Docker: str("ci.docker_binary"),
344 Concurrency: intp("ci.concurrency"),
345 Network: str("ci.network"),
346 TimeoutSec: intp("ci.timeout_seconds"),
347 UpdateMaxWaitMin: intp("ci.update_max_wait_minutes"),
348 },
349 }
350 return p
351}
352
353type instancePatchJSON struct {
354 BaseURL *string `json:"base_url"`
355 Listen *string `json:"listen"`
356 TrustedProxies *[]string `json:"trusted_proxies"`
357 Auth *struct {
358 Mode *string `json:"mode"`
359 BaseURL *string `json:"base_url"`
360 ClientID *string `json:"client_id"`
361 ClientSecret *string `json:"client_secret"`
362 ClientSecretFile *string `json:"client_secret_file"`
363 RedirectPath *string `json:"redirect_path"`
364 UserAgent *string `json:"user_agent"`
365 DevUser *string `json:"dev_user"`
366 DevAuthID *int64 `json:"dev_auth_id"`
367 TenantID *string `json:"tenant_id"`
368 Issuer *string `json:"issuer"`
369 } `json:"auth"`
370 Git *struct {
371 Binary *string `json:"binary"`
372 DefaultBranch *string `json:"default_branch"`
373 HookBinary *string `json:"hook_binary"`
374 MaintenanceInterval *string `json:"maintenance_interval"`
375 } `json:"git"`
376 SSH *struct {
377 Enabled *bool `json:"enabled"`
378 Listen *string `json:"listen"`
379 PublicHost *string `json:"public_host"`
380 PublicPort *int `json:"public_port"`
381 } `json:"ssh"`
382 Runner *struct {
383 Name *string `json:"name"`
384 } `json:"runner"`
385 CI *struct {
386 Enabled *bool `json:"enabled"`
387 Docker *string `json:"docker_binary"`
388 Concurrency *int `json:"concurrency"`
389 Network *string `json:"network"`
390 TimeoutSec *int `json:"timeout_seconds"`
391 UpdateMaxWaitMin *int `json:"update_max_wait_minutes"`
392 } `json:"ci"`
393}
394
395func (in instancePatchJSON) toPatch() config.Persisted {
396 p := config.Persisted{BaseURL: in.BaseURL, Listen: in.Listen, TrustedProxies: in.TrustedProxies}
397 if a := in.Auth; a != nil {
398 p.Auth = &config.PersistedAuth{
399 Mode: a.Mode, BaseURL: a.BaseURL, ClientID: a.ClientID, ClientSecret: a.ClientSecret,
400 ClientSecretFile: a.ClientSecretFile, RedirectPath: a.RedirectPath, UserAgent: a.UserAgent,
401 DevUser: a.DevUser, DevAuthID: a.DevAuthID, TenantID: a.TenantID, Issuer: a.Issuer,
402 }
403 }
404 if g := in.Git; g != nil {
405 p.Git = &config.PersistedGit{Binary: g.Binary, DefaultBranch: g.DefaultBranch, HookBinary: g.HookBinary, MaintenanceInterval: g.MaintenanceInterval}
406 }
407 if h := in.SSH; h != nil {
408 p.SSH = &config.PersistedSSH{Enabled: h.Enabled, Listen: h.Listen, PublicHost: h.PublicHost, PublicPort: h.PublicPort}
409 }
410 if r := in.Runner; r != nil {
411 p.Runner = &config.PersistedRunner{Name: r.Name}
412 }
413 if c := in.CI; c != nil {
414 p.CI = &config.PersistedCI{Enabled: c.Enabled, Docker: c.Docker, Concurrency: c.Concurrency, Network: c.Network, TimeoutSec: c.TimeoutSec, UpdateMaxWaitMin: c.UpdateMaxWaitMin}
415 }
416 return p
417}