internal/httpd/settings.go
552 lines · 18603 bytes
1package httpd
2
3import (
4 "fmt"
5 "net/http"
6 "net/url"
7 "slices"
8 "strings"
9
10 "gitbay.org/gitbay/internal/control"
11 "gitbay.org/gitbay/internal/gitutil"
12 "gitbay.org/gitbay/internal/store"
13)
14
15// Repository settings for repo admins. Every control dispatches the
16// command the CLI runs; the page only groups them. Delete and transfer
17// ask for the repository's path to be typed first.
18
19type settingsPage struct {
20 repoPage
21 Topics []string
22 Branches []gitutil.Ref
23 DepsEnabled bool
24 Deps control.DepsOut
25 Security control.SecurityOut
26 // ScanAvailable is whether the instance has a code scanning image;
27 // without one the toggle would only ever be refused.
28 ScanAvailable bool
29 // ScanFrequencies are the frequencies the instance allows, ScanFrequency
30 // the one this repository scans at, and ScanHour the hour UTC.
31 ScanFrequencies []string
32 ScanFrequency string
33 ScanHour int
34 Runners []store.RepoRunner
35 Secrets []string
36 DeployKeys []deployKeyRow
37 Mirrors []mirrorRow
38 Domains []domainRow
39 Access []accessRow
40 Hooks []hookRow
41 Deliveries []deliveryRow
42 Notice string
43 Saved bool
44 Reauth bool // Notice is the stale-session refusal: link to sign in
45 Submitted map[string]string
46}
47
48type deployKeyRow struct {
49 Fingerprint string `json:"fingerprint"`
50 Algo string `json:"algo"`
51 Mode string `json:"mode"`
52 Label string `json:"label"`
53 LastUsedAt string `json:"last_used_at"`
54 ExpiresAt string `json:"expires_at"`
55}
56
57type mirrorRow struct {
58 ID int64 `json:"id"`
59 Direction string `json:"direction"`
60 URL string `json:"url"`
61 Username string `json:"username"`
62 Pending bool `json:"pending"`
63 LastSync string `json:"last_sync"`
64 LastError string `json:"last_error"`
65}
66
67type domainRow struct {
68 Domain string `json:"domain"`
69 State string `json:"state"`
70 Verified string `json:"verified_at"`
71}
72
73type accessRow struct {
74 User string `json:"user"`
75 Role string `json:"role"`
76 Source string `json:"source"`
77}
78
79type hookRow struct {
80 ID int64 `json:"id"`
81 URL string `json:"url"`
82 Events string `json:"events"`
83 Secret bool `json:"has_secret"`
84}
85
86type deliveryRow struct {
87 ID int64 `json:"id"`
88 URL string `json:"url"`
89 Event string `json:"event"`
90 Status string `json:"status"`
91 Attempts int `json:"attempts"`
92 LastStatus int `json:"last_status"`
93 LastError string `json:"last_error"`
94}
95
96func (s *Server) settingsForm(w http.ResponseWriter, r *http.Request, u store.User) {
97 s.settingsFormWith(w, r, u, s.takeFlash(w, r), nil)
98}
99
100// settingsFormWith renders the page with the given notice. submitted is
101// nil on a plain GET; on a failed POST it carries the values the visitor
102// typed, so a rejected value is not silently dropped.
103func (s *Server) settingsFormWith(w http.ResponseWriter, r *http.Request, u store.User, notice string, submitted url.Values) {
104 repo, ok := s.repoForUser(w, r, u, policyCanAdmin)
105 if !ok {
106 return
107 }
108 p, ok := s.repoFor(w, r, "")
109 if !ok {
110 return
111 }
112 p.Tab = "settings"
113 topics, _ := s.st.ListTopics(repo.ID)
114 branches, _ := gitutil.Refs(p.Dir, "heads")
115 // The toggle's state comes from the store; what the last run found
116 // comes from the command, so the page shows the same report the CLI
117 // prints (#164).
118 var deps control.DepsOut
119 s.runControlInto(u, []string{"repo", "deps", "status", repo.Path()}, &deps)
120 var security control.SecurityOut
121 s.runControlInto(u, []string{"repo", "security", "status", repo.Path()}, &security)
122 var runners []store.RepoRunner
123 s.runControlInto(u, []string{"repo", "runner", "list", repo.Path()}, &runners)
124 var secrets []string
125 s.runControlInto(u, []string{"repo", "secret", "list", repo.Path()}, &secrets)
126 var deployKeys []deployKeyRow
127 s.runControlInto(u, []string{"repo", "deploy-key", "list", repo.Path()}, &deployKeys)
128 var mirrors []mirrorRow
129 s.runControlInto(u, []string{"repo", "mirror", "list", repo.Path()}, &mirrors)
130 var domains []domainRow
131 s.runControlInto(u, []string{"repo", "domain", "list", repo.Path()}, &domains)
132 var access []accessRow
133 s.runControlInto(u, []string{"repo", "access", "list", repo.Path()}, &access)
134 var hooks []hookRow
135 s.runControlInto(u, []string{"webhook", "list", repo.Path()}, &hooks)
136 var deliveries []deliveryRow
137 s.runControlInto(u, []string{"webhook", "deliveries", repo.Path(), "--limit", "20"}, &deliveries)
138 var subm map[string]string
139 if submitted != nil {
140 subm = map[string]string{
141 "description": submitted.Get("description"),
142 "website": submitted.Get("website"),
143 "topics": submitted.Get("topics"),
144 "key": submitted.Get("key"),
145 "deploy-key": submitted.Get("deploy-key"),
146 "user": submitted.Get("user"),
147 "role": submitted.Get("role"),
148 "url": submitted.Get("url"),
149 "events": submitted.Get("events"),
150 "name": submitted.Get("name"),
151 "new-owner": submitted.Get("new-owner"),
152 "jobs": submitted.Get("jobs"),
153 "secret-name": submitted.Get("secret-name"),
154 "mirror-url": submitted.Get("mirror-url"),
155 "mirror-user": submitted.Get("mirror-user"),
156 "domain": submitted.Get("domain"),
157 }
158 }
159 s.render(w, "settings.html", settingsPage{
160 repoPage: p, Topics: topics, Branches: branches,
161 DepsEnabled: deps.Enabled, Deps: deps,
162 Security: security, ScanAvailable: s.cfg.Security.Image != "",
163 ScanFrequencies: s.cfg.Security.Frequencies(),
164 ScanFrequency: s.cfg.Security.Frequency(repo.Settings.SecurityFrequency),
165 ScanHour: s.cfg.Security.Hour,
166 Runners: runners,
167 Secrets: secrets,
168 DeployKeys: deployKeys,
169 Mirrors: mirrors,
170 Domains: domains,
171 Access: access, Hooks: hooks, Deliveries: deliveries,
172 Notice: notice,
173 Saved: strings.HasPrefix(notice, "Saved "),
174 Reauth: s.reauthNotice(w, notice, r.URL.Path),
175 Submitted: subm,
176 })
177}
178
179func (s *Server) settingsRedirect(w http.ResponseWriter, r *http.Request, msg string) {
180 dest := fmt.Sprintf("/%s/%s/settings", r.PathValue("owner"), r.PathValue("repo"))
181 s.setFlash(w, msg)
182 http.Redirect(w, r, dest, http.StatusSeeOther)
183}
184
185// settingsSubmit routes one form to its command. Keeping the mapping in
186// one place makes what the page can reach obvious.
187func (s *Server) settingsSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
188 row, ok := s.repoForUser(w, r, u, policyCanAdmin)
189 if !ok {
190 return
191 }
192 repo := r.PathValue("owner") + "/" + r.PathValue("repo")
193 v := func(k string) string { return strings.TrimSpace(r.FormValue(k)) }
194 field := r.FormValue("field")
195
196 var argv []string
197 switch field {
198 case "description":
199 argv = []string{"repo", "settings", "description", repo, v("description")}
200 case "website":
201 argv = []string{"repo", "settings", "website", repo, v("website")}
202 case "visibility":
203 argv = []string{"repo", "settings", "visibility", repo, v("visibility")}
204 case "default-branch":
205 argv = []string{"repo", "settings", "default-branch", repo, v("default-branch")}
206 case "git-daemon":
207 argv = []string{"repo", "settings", "git-daemon", repo, onOff(v("git-daemon"))}
208 case "require-checks":
209 argv = []string{"repo", "settings", "require-checks", repo, onOff(v("require-checks"))}
210 case "require-contexts":
211 argv = append([]string{"repo", "settings", "require-contexts", repo}, strings.Fields(v("contexts"))...)
212 case "require-resolved":
213 argv = []string{"repo", "settings", "require-resolved", repo, onOff(v("require-resolved"))}
214 case "require-codeowners":
215 argv = []string{"repo", "settings", "require-codeowners", repo, onOff(v("require-codeowners"))}
216 case "require-mr":
217 argv = []string{"repo", "settings", "require-mr", repo, onOff(v("require-mr"))}
218 case "require-signed":
219 argv = []string{"repo", "settings", "require-signed", repo, onOff(v("require-signed"))}
220 case "security":
221 verb := "disable"
222 if v("security") == "on" {
223 verb = "enable"
224 }
225 argv = []string{"repo", "security", verb, repo}
226 case "security-frequency":
227 argv = []string{"repo", "settings", "security-frequency", repo, v("security-frequency")}
228 case "deps-dismiss":
229 argv = []string{"repo", "deps", "dismiss", repo, v("advisory"), "--reason", v("reason")}
230 case "deps-reopen":
231 argv = []string{"repo", "deps", "reopen", repo, v("advisory")}
232 case "security-dismiss":
233 argv = []string{"repo", "security", "dismiss", repo, v("fingerprint"), "--reason", v("reason")}
234 case "security-reopen":
235 argv = []string{"repo", "security", "reopen", repo, v("fingerprint")}
236 case "security-ignore":
237 argv = append([]string{"repo", "settings", "security-ignore", repo}, strings.Fields(v("security-ignore"))...)
238 case "security-exclude-rule":
239 argv = append([]string{"repo", "settings", "security-exclude-rule", repo}, strings.Fields(v("security-exclude-rule"))...)
240 case "secret-scan":
241 argv = []string{"repo", "settings", "secret-scan", repo, v("secret-scan")}
242 case "secret-scan-allow":
243 argv = append([]string{"repo", "settings", "secret-scan-allow", repo}, strings.Fields(v("secret-scan-allow"))...)
244 case "require-approvals":
245 argv = []string{"repo", "settings", "require-approvals", repo, v("approvals")}
246 case "protect":
247 argv = []string{"repo", "settings", "protect", repo, v("branch")}
248 case "unprotect":
249 argv = []string{"repo", "settings", "unprotect", repo, v("branch")}
250 case "protect-tag":
251 argv = []string{"repo", "settings", "protect-tag", repo, v("glob")}
252 case "unprotect-tag":
253 argv = []string{"repo", "settings", "unprotect-tag", repo, v("glob")}
254 case "deps":
255 verb := "disable"
256 if v("deps") == "on" {
257 verb = "enable"
258 }
259 argv = []string{"repo", "deps", verb, repo}
260 case "archive":
261 verb := "archive"
262 if v("archive") != "on" {
263 verb = "unarchive"
264 }
265 argv = []string{"repo", verb, repo}
266 case "topics":
267 want := map[string]bool{}
268 var order []string
269 for _, t := range strings.Split(v("topics"), ",") {
270 if t = strings.ToLower(strings.TrimSpace(t)); t != "" && !want[t] {
271 want[t] = true
272 order = append(order, t)
273 }
274 }
275 have, err := s.st.ListTopics(row.ID)
276 if err != nil {
277 s.settingsRedirect(w, r, err.Error())
278 return
279 }
280 var add, remove []string
281 for _, t := range order {
282 if !slices.Contains(have, t) {
283 add = append(add, t)
284 }
285 }
286 for _, t := range have {
287 if !want[t] {
288 remove = append(remove, t)
289 }
290 }
291 removed := false
292 if len(remove) > 0 {
293 if _, msg, ok := s.runControl(u, append([]string{"repo", "topics", "remove", repo}, remove...)); !ok {
294 s.settingsFormWith(w, r, u, msg, r.Form)
295 return
296 }
297 removed = true
298 }
299 if len(add) > 0 {
300 argv = append([]string{"repo", "topics", "add", repo}, add...)
301 } else {
302 s.settingsRedirect(w, r, "Saved the topics.")
303 return
304 }
305 if removed {
306 if _, msg, ok := s.runControl(u, argv); !ok {
307 s.settingsFormWith(w, r, u, "Removed "+strings.Join(remove, ", ")+"; "+msg, r.Form)
308 return
309 }
310 s.settingsRedirect(w, r, "Saved the "+fieldLabel(field)+".")
311 return
312 }
313 case "runner-add":
314 body := v("key")
315 if body == "" {
316 s.settingsRedirect(w, r, "paste the runner's public key")
317 return
318 }
319 argv := []string{"repo", "runner", "add", repo}
320 if jobs := strings.Join(strings.Fields(strings.ReplaceAll(v("jobs"), ",", " ")), ","); jobs != "" {
321 argv = append(argv, "--jobs", jobs)
322 }
323 msg, ok := s.runControlStdin(u, argv, body+"\n")
324 if !ok {
325 s.settingsFormWith(w, r, u, msg, r.Form)
326 return
327 }
328 s.settingsRedirect(w, r, "Saved the runner.")
329 return
330 case "runner-remove":
331 argv = []string{"repo", "runner", "remove", repo, v("fingerprint")}
332 case "secret-set":
333 // Secret value travels on stdin only, never in argv, flash, or re-rendered HTML.
334 name := v("secret-name")
335 val := strings.TrimRight(r.FormValue("secret-value"), "\r\n")
336 if val == "" {
337 s.settingsFormWith(w, r, u, "enter a value for the build secret", r.Form)
338 return
339 }
340 if msg, ok := s.runControlStdin(u, []string{"repo", "secret", "set", repo, name}, val+"\n"); !ok {
341 s.settingsFormWith(w, r, u, msg, r.Form)
342 return
343 }
344 s.settingsRedirect(w, r, "Saved the build secret.")
345 return
346 case "secret-remove":
347 argv = []string{"repo", "secret", "remove", repo, v("secret-name")}
348 case "deploykey-add":
349 body := v("deploy-key")
350 if body == "" {
351 s.settingsFormWith(w, r, u, "paste a public key in authorized_keys format", r.Form)
352 return
353 }
354 argv := []string{"repo", "deploy-key", "add", repo}
355 if v("rw") == "on" {
356 argv = append(argv, "--rw")
357 }
358 if ttl := v("ttl"); ttl != "" {
359 argv = append(argv, "--ttl", ttl)
360 }
361 if msg, ok := s.runControlStdin(u, argv, body+"\n"); !ok {
362 s.settingsFormWith(w, r, u, msg, r.Form)
363 return
364 }
365 s.settingsRedirect(w, r, "Saved the deploy key.")
366 return
367 case "deploykey-remove":
368 argv = []string{"repo", "deploy-key", "remove", repo, v("fingerprint")}
369 case "mirror-add":
370 // Mirror token travels on stdin only, never in argv, flash, or re-rendered HTML.
371 argv := []string{"repo", "mirror", "add", repo, v("mirror-url"), "--direction", v("direction")}
372 if usr := v("mirror-user"); usr != "" {
373 argv = append(argv, "--username", usr)
374 }
375 var stdin string
376 if tok := strings.TrimSpace(r.FormValue("mirror-token")); tok != "" {
377 argv = append(argv, "--token-stdin")
378 stdin = tok + "\n"
379 }
380 if msg, ok := s.runControlStdin(u, argv, stdin); !ok {
381 s.settingsFormWith(w, r, u, msg, r.Form)
382 return
383 }
384 s.settingsRedirect(w, r, "Saved the mirror.")
385 return
386 case "mirror-remove":
387 argv = []string{"repo", "mirror", "remove", repo, v("id")}
388 case "mirror-sync":
389 if _, msg, ok := s.runControl(u, []string{"repo", "mirror", "sync", repo}); !ok {
390 s.settingsFormWith(w, r, u, msg, r.Form)
391 return
392 }
393 s.settingsRedirect(w, r, "Saved the mirror sync schedule.")
394 return
395 case "domain-add":
396 var claimed struct {
397 Domain string `json:"domain"`
398 ChallengeName string `json:"challenge_name"`
399 ChallengeValue string `json:"challenge_value"`
400 }
401 if msg, ok := s.runControlInto(u, []string{"repo", "domain", "add", repo, v("domain")}, &claimed); !ok {
402 s.settingsFormWith(w, r, u, msg, r.Form)
403 return
404 }
405 s.settingsRedirect(w, r, fmt.Sprintf("Saved the custom domain %s: add TXT %s = %s, then press Verify.", claimed.Domain, claimed.ChallengeName, claimed.ChallengeValue))
406 return
407 case "domain-verify":
408 argv = []string{"repo", "domain", "verify", repo, v("domain")}
409 case "domain-remove":
410 argv = []string{"repo", "domain", "remove", repo, v("domain")}
411 case "access-grant":
412 argv = []string{"repo", "access", "grant", repo, v("user"), v("role")}
413 case "access-revoke":
414 argv = []string{"repo", "access", "revoke", repo, v("user")}
415 case "webhook-add":
416 // The secret goes to the command on stdin and nowhere else: not
417 // argv, not the re-rendered form, not the notice.
418 argv = []string{"webhook", "add", repo, v("url")}
419 if ev := strings.ReplaceAll(v("events"), " ", ""); ev != "" {
420 argv = append(argv, "--events", ev)
421 }
422 var stdin string
423 if secret := strings.TrimRight(r.FormValue("secret"), "\r\n"); secret != "" {
424 argv = append(argv, "--secret", "-")
425 stdin = secret + "\n"
426 }
427 msg, ok := s.runControlStdin(u, argv, stdin)
428 if !ok {
429 s.settingsFormWith(w, r, u, msg, r.Form)
430 return
431 }
432 s.settingsRedirect(w, r, "Saved the webhook.")
433 return
434 case "webhook-remove":
435 argv = []string{"webhook", "remove", repo, v("id")}
436 case "webhook-redeliver":
437 if _, msg, ok := s.runControl(u, []string{"webhook", "redeliver", repo, v("delivery")}); !ok {
438 s.settingsFormWith(w, r, u, msg, r.Form)
439 return
440 }
441 s.settingsRedirect(w, r, "Queued the delivery again.")
442 return
443 case "rename":
444 if _, msg, ok := s.runControl(u, []string{"repo", "rename", repo, v("name")}); !ok {
445 s.settingsFormWith(w, r, u, msg, r.Form)
446 return
447 }
448 s.setFlash(w, "Saved the name.")
449 http.Redirect(w, r, "/"+r.PathValue("owner")+"/"+v("name")+"/settings", http.StatusSeeOther)
450 return
451 case "transfer":
452 if ok, msg := confirmed(r, repo); !ok {
453 s.settingsFormWith(w, r, u, msg, r.Form)
454 return
455 }
456 if _, msg, ok := s.runControl(u, []string{"repo", "transfer", repo, v("new-owner")}); !ok {
457 s.settingsFormWith(w, r, u, msg, r.Form)
458 return
459 }
460 s.setFlash(w, "Saved the owner: transferred to "+v("new-owner")+".")
461 http.Redirect(w, r, "/"+v("new-owner")+"/"+r.PathValue("repo")+"/settings", http.StatusSeeOther)
462 return
463 case "delete":
464 if ok, msg := confirmed(r, repo); !ok {
465 s.settingsFormWith(w, r, u, msg, r.Form)
466 return
467 }
468 if _, msg, ok := s.runControl(u, []string{"repo", "delete", repo, "--yes"}); !ok {
469 s.settingsFormWith(w, r, u, msg, r.Form)
470 return
471 }
472 s.setFlash(w, "Deleted "+repo+".")
473 http.Redirect(w, r, "/"+r.PathValue("owner"), http.StatusSeeOther)
474 return
475 default:
476 s.settingsRedirect(w, r, "unknown setting")
477 return
478 }
479
480 _, msg, ok := s.runControl(u, argv)
481 if ok {
482 s.settingsRedirect(w, r, "Saved the "+fieldLabel(field)+".")
483 return
484 }
485 s.settingsFormWith(w, r, u, msg, r.Form)
486}
487
488// fieldLabel names a settings field for the saved flash and, on
489// rejection, the error notice — lower case, matching the label beside
490// its control.
491func fieldLabel(field string) string {
492 switch field {
493 case "description":
494 return "description"
495 case "website":
496 return "website"
497 case "visibility":
498 return "visibility"
499 case "default-branch":
500 return "default branch"
501 case "git-daemon":
502 return "git:// serving"
503 case "require-checks":
504 return "required checks"
505 case "require-contexts":
506 return "required contexts"
507 case "require-approvals":
508 return "approvals"
509 case "require-resolved":
510 return "review threads"
511 case "require-codeowners":
512 return "CODEOWNERS"
513 case "require-mr":
514 return "merge request requirement"
515 case "require-signed":
516 return "signed commits"
517 case "protect", "unprotect":
518 return "protected branch"
519 case "protect-tag", "unprotect-tag":
520 return "protected tag"
521 case "deps":
522 return "dependency scanning"
523 case "archive":
524 return "archived state"
525 case "topics":
526 return "topics"
527 case "runner-add", "runner-remove":
528 return "runner"
529 case "secret-remove":
530 return "build secret"
531 case "deploykey-remove":
532 return "deploy key"
533 case "mirror-remove":
534 return "mirror"
535 case "domain-verify", "domain-remove":
536 return "custom domain"
537 case "access-grant", "access-revoke":
538 return "access"
539 case "webhook-remove":
540 return "webhook"
541 default:
542 return field
543 }
544}
545
546// onOff normalises a checkbox to the on|off the commands take.
547func onOff(v string) string {
548 if v == "on" || v == "true" {
549 return "on"
550 }
551 return "off"
552}