BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

server.go 30.4 KiB Download Raw
1// Package server is de webinterface, de git-HTTP-server en de API.
2package server
3
4import (
5 "context"
6 "crypto/rand"
7 "embed"
8 "encoding/hex"
9 "fmt"
10 "gitlab.com/Timfa/bluegit/internal/langpick"
11 "gitlab.com/Timfa/bluegit/internal/readcache"
12 "gitlab.com/Timfa/bluegit/internal/runnercfg"
13 "html/template"
14 "io/fs"
15 "log/slog"
16 "net/http"
17 "net/url"
18 "strings"
19 "sync"
20 "time"
21 "unicode/utf8"
22
23 "gitlab.com/Timfa/bluegit/internal/access"
24 "gitlab.com/Timfa/bluegit/internal/activity"
25 "gitlab.com/Timfa/bluegit/internal/auth"
26 "gitlab.com/Timfa/bluegit/internal/card"
27 "gitlab.com/Timfa/bluegit/internal/cispec"
28 "gitlab.com/Timfa/bluegit/internal/config"
29 "gitlab.com/Timfa/bluegit/internal/i18n"
30 "gitlab.com/Timfa/bluegit/internal/realip"
31 "gitlab.com/Timfa/bluegit/internal/runner"
32 "gitlab.com/Timfa/bluegit/internal/store"
33)
34
35//go:embed templates/*.html static/*.css static/*.js static/*.svg static/*.ttf static/*.txt
36var webFS embed.FS
37
38// Server bedient BlueGit.
39type Server struct {
40 Cfg config.Config
41 Store *store.Store
42 Auth auth.Provider
43 Mail auth.Mailer
44 Dev bool
45 Git string
46 HookBin string
47 Runner *runner.Runner
48 Log *slog.Logger
49 // hookSink vangt de JSON-body af in tests, vóór het HTTP-verzoek.
50 hookSink func([]byte)
51 // StateDir is de map met database en het bestand storage_path.
52 StateDir string
53 // AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
54 AfterStorage func(path string)
55 // UpdateStarter start bluegit-update.service. Nil gebruikt systemctl.
56 UpdateStarter UpdateStarter
57 updateHits updateLimiter
58 tmpl *template.Template
59 byLang map[string]*template.Template
60
61 storageMu sync.RWMutex
62 storage string
63 storageSet bool
64 usageMu sync.Mutex
65 usage dirUsage
66 usageDone chan struct{}
67 cards *card.Cache
68 // mergingMR zijn merge requests die opMergeMR nu zelf afrondt.
69 // AfterPush mag hun bronbranch niet alvast verwijderen.
70 mergingMR sync.Map
71
72 cacheMu sync.RWMutex
73 rcache *readcache.Cache
74}
75
76type principal struct {
77 User store.User
78 Session store.Session
79 OK bool
80}
81
82type ctxKey struct{}
83
84// Handler is de HTTP-handler met sessies en koppen.
85func (s *Server) Handler() http.Handler {
86 s.mustTemplates()
87 mux := http.NewServeMux()
88 mux.HandleFunc("GET /assets/{file}", s.asset)
89 mux.HandleFunc("GET /-/info", s.infoPage)
90 mux.HandleFunc("GET /help", s.helpIndex)
91 mux.HandleFunc("GET /help/{doc}", s.helpPage)
92 s.mountRunnerAdmin(mux)
93 s.mountAdmin(mux)
94 mux.HandleFunc("POST /-/lang", s.switchLang)
95 mux.HandleFunc("GET /-/card.png", s.cardPNG)
96 mux.HandleFunc("GET /api/v1/oembed", s.oembed)
97 s.mountAPI(mux)
98 mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
99 mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
100 mux.HandleFunc("GET /api/v1/webhooks/openapi.json", s.webhookSpec)
101 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
102 w.WriteHeader(http.StatusOK)
103 _, _ = w.Write([]byte("ok\n"))
104 })
105 mux.HandleFunc("GET /login", s.login)
106 mux.HandleFunc("GET /auth/callback", s.callback)
107 mux.HandleFunc("POST /logout", s.logout)
108 mux.HandleFunc("GET /{$}", s.home)
109 mux.HandleFunc("GET /new", s.newPage)
110 mux.HandleFunc("GET /new/slug", s.slugPreview)
111 mux.HandleFunc("POST /new/repo", s.createRepo)
112 mux.HandleFunc("POST /new/group", s.createGroup)
113 mux.HandleFunc("GET /setup", s.setupPage)
114 mux.HandleFunc("POST /setup", s.setupSave)
115 mux.HandleFunc("POST /setup/cache", s.setupCacheSave)
116 mux.HandleFunc("POST /setup/cache/clear", s.setupCacheClear)
117 s.routeRunners(mux)
118 mux.HandleFunc("GET /settings", s.account)
119 mux.HandleFunc("POST /settings/language", s.saveLanguage)
120 mux.HandleFunc("POST /settings/profile", s.saveProfile)
121 mux.HandleFunc("POST /settings/tokens", s.createToken)
122 mux.HandleFunc("POST /settings/tokens/delete", s.deleteToken)
123 mux.HandleFunc("POST /settings/ssh", s.addSSH)
124 mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
125 mux.HandleFunc("GET /settings/export", s.export)
126 mux.HandleFunc("GET /users/{username}", s.profile)
127 mux.HandleFunc("GET /{name}", s.userShort)
128 mux.HandleFunc("GET /groups/{path}", s.groupPage)
129 mux.HandleFunc("GET /groups/{path}/logo", s.groupLogo)
130 mux.HandleFunc("POST /groups/{path}/settings", s.saveGroup)
131 mux.HandleFunc("POST /groups/{path}/approvals", s.saveGroupApproval)
132 mux.HandleFunc("POST /groups/{path}/owner", s.transferGroup)
133 mux.HandleFunc("POST /groups/{path}/logo", s.uploadGroupLogo)
134 mux.HandleFunc("POST /groups/{path}/members", s.groupMember)
135 mux.HandleFunc("POST /groups/{path}/members/remove", s.groupMemberRemove)
136 mux.HandleFunc("POST /groups/{path}/secrets", s.groupSecret)
137 mux.HandleFunc("POST /groups/{path}/secrets/reveal", s.groupSecretReveal)
138 mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
139 mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
140 mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)
141
142 mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
143 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
144 mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
145 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
146 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI)
147 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff", s.commitDiffAPI)
148 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/merge-requests/{number}/diff", s.mrDiffAPI)
149 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI)
150 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI)
151 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
152 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
153 mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
154 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues/{number}/notes", s.issueNoteAPI)
155 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI)
156 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI)
157 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI)
158 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI)
159 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)
160 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)
161 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)
162 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretsAPI)
163 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretCreateAPI)
164 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretRevealAPI)
165 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretUpdateAPI)
166 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets/{name}/replace", s.repoSecretReplaceAPI)
167 mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretDeleteAPI)
168 mux.HandleFunc("GET /api/v1/groups/{path}/webhook-secrets", s.groupWebhookSecrets)
169 mux.HandleFunc("POST /api/v1/groups/{path}/hooks", s.groupWebhookAPI)
170 mux.HandleFunc("PUT /api/v1/groups/{path}/hooks/{id}", s.groupWebhookUpdate)
171 mux.HandleFunc("GET /api/v1/groups/{path}/secrets", s.groupSecretsAPI)
172 mux.HandleFunc("POST /api/v1/groups/{path}/secrets", s.groupSecretCreateAPI)
173 mux.HandleFunc("GET /api/v1/groups/{path}/secrets/{name}", s.groupSecretRevealAPI)
174 mux.HandleFunc("PUT /api/v1/groups/{path}/secrets/{name}", s.groupSecretUpdateAPI)
175 mux.HandleFunc("POST /api/v1/groups/{path}/secrets/{name}/replace", s.groupSecretReplaceAPI)
176 mux.HandleFunc("DELETE /api/v1/groups/{path}/secrets/{name}", s.groupSecretDeleteAPI)
177 mux.HandleFunc("GET /{owner}/{repo}", s.repoHome)
178 mux.HandleFunc("GET /{owner}/{repo}/-/tree", s.treeRoot)
179 mux.HandleFunc("GET /{owner}/{repo}/-/tree/{path...}", s.tree)
180 mux.HandleFunc("GET /{owner}/{repo}/-/blob/{path...}", s.blob)
181 mux.HandleFunc("GET /{owner}/{repo}/-/commits", s.commits)
182 mux.HandleFunc("GET /{owner}/{repo}/-/tags", s.tags)
183 mux.HandleFunc("POST /{owner}/{repo}/-/tags", s.createTag)
184 mux.HandleFunc("POST /{owner}/{repo}/-/tags/delete", s.deleteTag)
185 mux.HandleFunc("GET /{owner}/{repo}/-/tags/archive", s.tagArchive)
186 mux.HandleFunc("GET /{owner}/{repo}/-/archive/{rev}/{file}", s.commitArchive)
187 mux.HandleFunc("GET /{owner}/{repo}/-/commit/{sha}", s.commit)
188 mux.HandleFunc("GET /{owner}/{repo}/-/branches/archive", s.branchArchive)
189 mux.HandleFunc("GET /{owner}/{repo}/-/branches", s.branches)
190 mux.HandleFunc("POST /{owner}/{repo}/-/branches", s.createBranch)
191 mux.HandleFunc("POST /{owner}/{repo}/-/branches/delete", s.deleteBranch)
192 mux.HandleFunc("POST /{owner}/{repo}/-/branches/rename", s.renameBranch)
193 mux.HandleFunc("GET /{owner}/{repo}/-/compare", s.compare)
194 mux.HandleFunc("POST /{owner}/{repo}/-/markdown", s.previewMarkdown)
195 mux.HandleFunc("POST /{owner}/{repo}/-/tasks", s.toggleTask)
196 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests)
197 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/new", s.newMR)
198 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR)
199 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR)
200 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}", s.updateMR)
201 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR)
202 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR)
203 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reopen", s.reopenMR)
204 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews", s.postReview)
205 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews/dismiss", s.dismissReview)
206 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/notes", s.createNote)
207 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/suggestions", s.applySuggestions)
208 mux.HandleFunc("GET /{owner}/{repo}/-/issues", s.issuesPage)
209 mux.HandleFunc("GET /{owner}/{repo}/-/issues/new", s.newIssue)
210 mux.HandleFunc("POST /{owner}/{repo}/-/issues", s.createIssue)
211 mux.HandleFunc("POST /{owner}/{repo}/-/issues/labels", s.createIssueLabel)
212 mux.HandleFunc("POST /{owner}/{repo}/-/issues/milestones", s.createIssueMilestone)
213 mux.HandleFunc("GET /{owner}/{repo}/-/issues/{number}", s.showIssue)
214 mux.HandleFunc("POST /{owner}/{repo}/-/issues/{number}", s.postIssue)
215 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines)
216 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline)
217 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline)
218 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}", s.showJob)
219 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/log", s.jobLog)
220 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/play", s.playJob)
221 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/retry", s.retryPipeline)
222 mux.HandleFunc("GET /{owner}/{repo}/-/ci/editor", s.ciEditor)
223 mux.HandleFunc("POST /{owner}/{repo}/-/ci/editor", s.saveCIEditor)
224 mux.HandleFunc("POST /{owner}/{repo}/-/ci/lint", s.lintCI)
225 mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases)
226 mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
227 mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
228 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
229 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
230 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
231 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
232 mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
233 mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember)
234 mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove)
235 mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected)
236 mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected)
237 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags", s.addProtectedTag)
238 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags/remove", s.removeProtectedTag)
239 mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret)
240 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/reveal", s.repoSecretReveal)
241 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
242 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
243 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
244 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
245
246 return s.realIP(s.withSession(s.secure(s.gate(mux))))
247}
248
249func (s *Server) realIP(next http.Handler) http.Handler {
250 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
251 realip.Apply(r, s.Cfg.ProxySet())
252 next.ServeHTTP(w, r)
253 })
254}
255
256func (s *Server) mustTemplates() {
257 if s.byLang != nil {
258 return
259 }
260 s.byLang = map[string]*template.Template{}
261 for _, lang := range i18n.All() {
262 l := lang
263 s.byLang[string(l)] = template.Must(template.New("web").Funcs(template.FuncMap{
264 "tip": func(key string) template.HTML { return runnercfg.Tip(l, key) },
265 "admintabs": adminTabs,
266 "adminpage": isAdminPage,
267 "short": func(v string) string {
268 if len(v) > 10 {
269 return v[:10]
270 }
271 return v
272 },
273 "join": strings.Join,
274 "initial": func(s string) string {
275 s = strings.TrimSpace(s)
276 if s == "" {
277 return "?"
278 }
279 r, _ := utf8.DecodeRuneInString(s)
280 return strings.ToUpper(string(r))
281 },
282 "tileHue": tileHue,
283 "splitPath": func(p string) []string {
284 if p == "" {
285 return nil
286 }
287 return strings.Split(p, "/")
288 },
289 "iconOf": func(name string) string { return fileIcon(name, "blob") },
290 "t": func(key string, args ...any) string { return i18n.T(l, key, args...) },
291 "date": func(t time.Time) string { return i18n.FormatDate(l, t) },
292 "tn": func(n int, one, many string) string {
293 key := many
294 if n == 1 {
295 key = one
296 }
297 return i18n.T(l, key, n)
298 },
299 "roleName": func(r access.Role) string { return i18n.T(l, "role."+string(r)) },
300 "visName": func(v string) string { return i18n.T(l, "vis."+v) },
301 "presetName": func(id string) string {
302 label := i18n.T(l, "set.preset."+id)
303 if label == "set.preset."+id {
304 return id
305 }
306 return label
307 },
308 "printf": fmt.Sprintf,
309 "dict": func(kv ...any) (map[string]any, error) {
310 if len(kv)%2 != 0 {
311 return nil, fmt.Errorf("dict")
312 }
313 m := make(map[string]any, len(kv)/2)
314 for i := 0; i < len(kv); i += 2 {
315 key, ok := kv[i].(string)
316 if !ok {
317 return nil, fmt.Errorf("dict")
318 }
319 m[key] = kv[i+1]
320 }
321 return m, nil
322 },
323 }).ParseFS(webFS, "templates/*.html"))
324 }
325 s.tmpl = s.byLang[string(i18n.EN)]
326}
327
328func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
329 name := r.PathValue("file")
330 if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") {
331 http.NotFound(w, r)
332 return
333 }
334 sub, err := fs.Sub(webFS, "static")
335 if err != nil {
336 http.Error(w, "assets", http.StatusInternalServerError)
337 return
338 }
339 http.ServeFileFS(w, r, sub, name)
340}
341
342func (s *Server) secure(next http.Handler) http.Handler {
343 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
344 w.Header().Set("X-Content-Type-Options", "nosniff")
345 w.Header().Set("X-Frame-Options", "DENY")
346 w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
347 w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src 'self' https://auth.timfalken.com data:; style-src 'self'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'")
348 next.ServeHTTP(w, r)
349 })
350}
351
352func (s *Server) withSession(next http.Handler) http.Handler {
353 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
354 p := principal{}
355 if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" {
356 sess, err := s.Store.Session(r.Context(), c.Value)
357 if err == nil && sess.ExpiresAt.After(time.Now()) {
358 p.Session = sess
359 p.User = sess.User
360 p.OK = true
361 s.maybeExtend(r.Context(), sess)
362 }
363 }
364 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
365 })
366}
367
368func (s *Server) maybeExtend(ctx context.Context, sess store.Session) {
369 if time.Until(sess.ExpiresAt) > 6*time.Hour {
370 return
371 }
372 sec, err := s.Auth.Extend(ctx, sess.AccessToken)
373 if err != nil || sec <= 0 {
374 return
375 }
376 _ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second))
377}
378
379func (s *Server) who(r *http.Request) principal {
380 p, _ := r.Context().Value(ctxKey{}).(principal)
381 return p
382}
383
384func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool {
385 if err := r.ParseForm(); err != nil {
386 http.Error(w, s.tr(r, "err.badForm"), http.StatusBadRequest)
387 return false
388 }
389 p := s.who(r)
390 if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
391 http.Error(w, s.tr(r, "err.badCSRF"), http.StatusBadRequest)
392 return false
393 }
394 return true
395}
396
397func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) {
398 p := s.who(r)
399 if !p.OK {
400 http.Redirect(w, r, "/login", http.StatusFound)
401 return store.User{}, false
402 }
403 return p.User, true
404}
405
406func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) {
407 http.SetCookie(w, &http.Cookie{
408 Name: "bluegit_session",
409 Value: id,
410 Path: "/",
411 HttpOnly: true,
412 SameSite: http.SameSiteLaxMode,
413 Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://"),
414 Expires: exp,
415 })
416}
417
418func (s *Server) flash(w http.ResponseWriter, notice, problem string) {
419 secure := strings.HasPrefix(s.Cfg.BaseURL, "https://")
420 if notice != "" {
421 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: url.QueryEscape(notice), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
422 }
423 if problem != "" {
424 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: url.QueryEscape(problem), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
425 }
426}
427
428func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) {
429 notice, problem := flashVal(r, "bluegit_notice"), flashVal(r, "bluegit_error")
430 if notice != "" {
431 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1})
432 }
433 if problem != "" {
434 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1})
435 }
436 return notice, problem
437}
438
439func cookieVal(r *http.Request, name string) string {
440 c, err := r.Cookie(name)
441 if err != nil {
442 return ""
443 }
444 return c.Value
445}
446
447func flashVal(r *http.Request, name string) string {
448 raw := cookieVal(r, name)
449 if raw == "" {
450 return ""
451 }
452 v, err := url.QueryUnescape(raw)
453 if err != nil {
454 return raw
455 }
456 return v
457}
458
459func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) {
460 s.flash(w, notice, problem)
461 http.Redirect(w, r, path, http.StatusSeeOther)
462}
463
464func (s *Server) langOf(r *http.Request) i18n.Lang {
465 if p := s.who(r); p.OK {
466 return i18n.Parse(p.User.Language)
467 }
468 if c, err := r.Cookie("bluegit_lang"); err == nil {
469 return i18n.Parse(c.Value)
470 }
471 return i18n.EN
472}
473
474// switchLang is de taalkiezer in de kopbalk: ingelogd slaat hij de taal op
475// het account op, anoniem in een cookie. back is altijd een lokaal pad.
476func (s *Server) switchLang(w http.ResponseWriter, r *http.Request) {
477 lang := i18n.Parse(r.FormValue("lang"))
478 back := langpick.SafeBack(r.FormValue("back"))
479 if p := s.who(r); p.OK {
480 if !s.csrfOK(w, r) {
481 return
482 }
483 if _, err := s.opSetLanguage(r.Context(), p.User, string(lang)); err != nil {
484 s.redirect(w, r, back, "", s.trErr(r, err))
485 return
486 }
487 } else {
488 http.SetCookie(w, &http.Cookie{Name: "bluegit_lang", Value: string(lang), Path: "/", MaxAge: 365 * 86400, HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://")})
489 }
490 http.Redirect(w, r, back, http.StatusSeeOther)
491}
492
493func (s *Server) tr(r *http.Request, key string, args ...any) string {
494 return i18n.T(s.langOf(r), key, args...)
495}
496
497func (s *Server) trErr(r *http.Request, err error) string {
498 return i18n.Text(s.langOf(r), err)
499}
500
501func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View {
502 notice, problem := s.takeFlash(w, r)
503 lang := s.langOf(r)
504 if strings.HasPrefix(title, "title.") {
505 title = i18n.T(lang, title)
506 }
507 name := strings.TrimSpace(s.Cfg.Runner.Name)
508 if name == "" {
509 name = "Steve"
510 }
511 v := View{
512 Title: title, BaseURL: s.Cfg.BaseURL, RunnerName: name, Notice: notice, Err: problem,
513 StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang),
514 Cunei: lang == i18n.Cuneiform,
515 }
516 for _, l := range i18n.All() {
517 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
518 }
519 if p := s.who(r); p.OK && !isCrawler(r) {
520 u := p.User
521 v.User = &u
522 v.CSRF = p.Session.CSRF
523 }
524 back := r.URL.Path
525 if r.URL.RawQuery != "" {
526 back += "?" + r.URL.RawQuery
527 }
528 csrfField := ""
529 if v.User != nil {
530 csrfField = "csrf"
531 }
532 v.LangPick = langpick.HTML(lang, "/-/lang", back, csrfField, v.CSRF)
533 pic := s.cardForPath(r.Context(), r.URL.Path, r.URL.RawQuery, r.URL.Fragment)
534 v.Social = &pic.Meta
535 return v
536}
537
538func htmlLang(l i18n.Lang) string {
539 switch l {
540 case i18n.NL:
541 return "nl"
542 case i18n.DE:
543 return "de"
544 case i18n.FR:
545 return "fr"
546 default:
547 return "en"
548 }
549}
550
551func (s *Server) render(w http.ResponseWriter, name string, v View) {
552 w.Header().Set("Content-Type", "text/html; charset=utf-8")
553 tmpl := s.byLang[v.Lang]
554 if tmpl == nil {
555 tmpl = s.tmpl
556 }
557 if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
558 s.Log.Error("sjabloon", "name", name, "err", err)
559 }
560}
561
562func randomState() (string, error) {
563 b := make([]byte, 32)
564 if _, err := rand.Read(b); err != nil {
565 return "", err
566 }
567 return hex.EncodeToString(b), nil
568}
569
570// View is de gegevensset voor elk scherm.
571type View struct {
572 RunnerList []RunnerView
573 RunnerPref string
574 NewRunnerToken string
575 BuiltinFirst bool
576 RunnerOptIn bool
577 OptInNames []string
578 Title string
579 BaseURL string
580 RunnerName string
581 User *store.User
582 CSRF string
583 Notice string
584 Err string
585 Repos []store.Repo
586 Groups []store.Group
587 Repo *store.Repo
588 Role access.Role
589 CanWrite bool
590 CanAdmin bool
591 CanMerge bool
592 CanForce bool
593 CanComment bool
594 CanApply bool
595 Commits []CommitRow
596 CommitDays []CommitDay
597 CommitPrev string
598 CommitNext string
599 Commit *CommitRow
600 CommitDiff *CommitDiff
601 Entries []EntryRow
602 TreePath string
603 Blob string
604 BlobPath string
605 Binary bool
606 Branches []BranchRow
607 Branch *BranchBoard
608 MRs []store.MergeRequest
609 Flow *FlowBoard
610 MR *store.MergeRequest
611 Banner *MRBanner
612 MRPipe *PipeRow
613 MergeBlocks []string
614 Approval *ApprovalView
615 Reviews []ReviewRow
616 CanReview bool
617 CanApprove bool
618 CanDismiss bool
619 CanClose bool
620 CanReopen bool
621 IsOwner bool
622 Candidates []store.Member
623 Diff string
624 DiffFiles []DiffFileView
625 Pipes []store.Pipeline
626 PipeRows []PipeRow
627 Pipe *store.Pipeline
628 PipeSource string
629 PipeStatus string
630 PipeLabel string
631 PipeJobs []JobLink
632 PipeStages []StageView
633 PipeFailed bool
634 Live bool
635 LiveURL string
636 Jobs []store.Job
637 JobPage *JobPage
638 Editor *CIEditor
639 Releases []store.Release
640 Members []store.Member
641 Secrets []store.SecretMeta
642 HookSecrets []SecretChoice
643 Hooks []HookView
644 HookEdit HookDraft
645 Patterns []string
646 TagPatterns []string
647 Tags []TagRow
648 Tokens []store.TokenInfo
649 ShowExpiry bool
650 Keys []store.SSHKey
651 CloneHTTP string
652 CloneSSH string
653 Group *store.Group
654 Tab string
655 Rev string
656 NewToken string
657 StorageUnset bool
658 StoragePath string
659 StorageFree string
660 StorageUsed string
661 StorageTotal string
662 StoragePercent int
663 StorageBlueGit string
664 StoragePartial bool
665 Cache map[string]any
666 StorageReserved string
667 HasReserved bool
668 MinFree string
669 Wide bool
670 Info bool
671 Help bool
672 HelpDocs []HelpDoc
673 HelpDoc *HelpDoc
674 RunnerUI template.HTML
675 AdminUsers []AdminUserRow
676 ReleaseOnly bool
677 ShowReleases bool
678 ReleaseRepos []store.Repo
679 LangPick template.HTML
680 ShowUpdate bool
681 Update *UpdateView
682 HookDoc string
683 Spec cispec.Doc
684 SpecJSON template.JS
685 APIJSON template.JS
686 Page string
687 Lang string
688 HTMLLang string
689 Cunei bool
690 Langs []LangChoice
691 Query string
692 SortDir string
693 FlipDir string
694 Cards []RepoCard
695 Head *CommitRow
696 Files []FileRow
697 Tree []FileRow
698 Readme template.HTML
699 ReadmeName string
700 LicensePath string
701 NCommits int
702 NBranches int
703 NTags int
704 NReleases int
705 Created string
706 Lines []CodeLine
707 BlobSize string
708 FileName string
709 RevProtected bool
710 Heat *activity.Calendar
711 Notes []NoteRow
712 Profile *store.User
713 Card *ProfileCard
714 DescHTML template.HTML
715 Timeline []TimelineItem
716 CompareFrom string
717 CompareTo string
718 FormTitle string
719 Labels []string
720 CanEditMR bool
721 Issues *IssueBoard
722 IssueDoc string
723 DescTpls []string
724 TplPick string
725 FormBody string
726 Social *card.Meta
727}
728
729// LangChoice is één taal in de instellingen.
730type LangChoice struct {
731 Code, Label string
732}
733
734// RepoCard is een repository in een groepslijst.
735type RepoCard struct {
736 Repo store.Repo
737 Stars int
738 Starred bool
739 When string
740}
741
742// AccountLink is een naam die naar een profiel wijst.
743type AccountLink struct {
744 Name string
745 URL string
746}
747
748// ProfileCard is het blok over een gebruiker, boven de activiteitenkalender.
749type ProfileCard struct {
750 User store.User
751 Name, Since, Bio, URL string
752 Heading string
753 Repos, Groups, Contrib int
754 Own bool
755}
756
757// NoteRow is een reactie in de interface.
758type NoteRow struct {
759 ID int64
760 Author, AuthorURL, Body, When, Path string
761 Start, End int
762 HasSuggestion bool
763 ParentID int64
764 HTML template.HTML
765 Replies []NoteRow
766 At time.Time
767}
768
769// DiffFileView is één bestand in de merge-request-diff.
770type DiffFileView struct {
771 Path string
772 Lines []DiffLineView
773}
774
775// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
776type DiffLineView struct {
777 Kind string
778 Text string
779 Old int
780 New int
781 Notes []NoteRow
782}
783
784// TagRow is één tag op de tagspagina.
785type TagRow struct {
786 Name, Message, SHA, Short, Subject, Date, When string
787 Annotated, Protected, HasRelease, CanDelete bool
788 ZipURL, TarURL string
789}
790
791// FileRow is een rij in de bestandstabel of de boom.
792type FileRow struct {
793 Name, Path, Icon, Subject, When, SHA string
794 Dir bool
795 Depth int
796 Active bool
797 // Open geldt voor een map die het huidige pad bevat. De browser
798 // onthoudt afwijkingen daarvan per repository.
799 Open bool
800}
801
802// CodeLine is één regel broncode.
803type CodeLine struct {
804 N int
805 HTML template.HTML
806}
807
808// CommitRow is een commit in de interface.
809// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
810// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
811type CommitRow struct {
812 SHA, Short, Author, Who, Date, Subject, Body, When string
813 UserURL, WhoURL, Avatar, Initial, RawName, PushedBy string
814 Ident template.HTML
815 PipeID int64
816 PipeStatus, PipeLabel, PipeDuration string
817 PipeStages []StageView
818 PipeLive, PipeFailed bool
819}
820
821// CommitDay is één dag op de commitlijst, nieuwste dag eerst.
822type CommitDay struct {
823 Label string
824 Items []CommitRow
825}
826
827// EntryRow is een bestand of map.
828type EntryRow struct {
829 Name, Type, Path string
830}
831
832// BranchRow is een branch, met of zonder bescherming.
833type BranchRow struct {
834 Name, SHA, Short, Subject, When, WhenTitle string
835 RepoPath, ZipURL, TarURL string
836 Protected, Default, CanEdit bool
837 Target string
838 Ahead, Behind int
839 Unix int64
840 PipeID int64
841 PipeStatus, PipeLabel string
842 OpenMRs []int64
843}
844
845// BranchBoard is de gegroepeerde branches-pagina.
846type BranchBoard struct {
847 State string
848 ShowActive, ShowStale bool
849 Active, Stale []BranchRow
850}
851
852// TimelineItem is één gebeurtenis of reactie op een merge request.
853type TimelineItem struct {
854 ID int64
855 Kind string
856 Actor, ActorURL, Text string
857 When string
858 Body string
859 HTML template.HTML
860 URL string
861 Replies []TimelineItem
862 At time.Time
863 Rank int
864}
865
866// HookView is een webhook plus de laatste pogingen.
867type HookView struct {
868 ID int64
869 Name string
870 Preset string
871 URL string
872 Method string
873 Filter string
874 Events string
875 Badges []string
876 Deliveries []store.Delivery
877}
878
879// HookDraft vult het webhookformulier bij bewerken. ID 0 is een nieuw formulier.
880type HookDraft struct {
881 ID int64
882 Name string
883 Preset string
884 Filter string
885 URL string
886 Username string
887 Avatar string
888 Icon string
889 Alias string
890 Token string
891 Chat string
892 Server string
893 Topic string
894 Home string
895 Room string
896 Method string
897 CType string
898 Headers string
899 Body string
900 OnPush bool
901 OnMR bool
902 OnOK bool
903 OnFail bool
904 OnRel bool
905 OnIssue bool
906 Extra []HookEventChoice
907}
908
909// HookEventChoice is een fijner event als vinkje in het webhookformulier.
910type HookEventChoice struct {
911 Name string
912 Key string
913 On bool
914}
915
916func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }