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 LangPick template.HTML
677 ShowUpdate bool
678 Update *UpdateView
679 HookDoc string
680 Spec cispec.Doc
681 SpecJSON template.JS
682 APIJSON template.JS
683 Page string
684 Lang string
685 HTMLLang string
686 Cunei bool
687 Langs []LangChoice
688 Query string
689 SortDir string
690 FlipDir string
691 Cards []RepoCard
692 Head *CommitRow
693 Files []FileRow
694 Tree []FileRow
695 Readme template.HTML
696 ReadmeName string
697 LicensePath string
698 NCommits int
699 NBranches int
700 NTags int
701 NReleases int
702 Created string
703 Lines []CodeLine
704 BlobSize string
705 FileName string
706 RevProtected bool
707 Heat *activity.Calendar
708 Notes []NoteRow
709 Profile *store.User
710 Card *ProfileCard
711 DescHTML template.HTML
712 Timeline []TimelineItem
713 CompareFrom string
714 CompareTo string
715 FormTitle string
716 Labels []string
717 CanEditMR bool
718 Issues *IssueBoard
719 IssueDoc string
720 DescTpls []string
721 TplPick string
722 FormBody string
723 Social *card.Meta
724}
725
726// LangChoice is één taal in de instellingen.
727type LangChoice struct {
728 Code, Label string
729}
730
731// RepoCard is een repository in een groepslijst.
732type RepoCard struct {
733 Repo store.Repo
734 Stars int
735 Starred bool
736 When string
737}
738
739// AccountLink is een naam die naar een profiel wijst.
740type AccountLink struct {
741 Name string
742 URL string
743}
744
745// ProfileCard is het blok over een gebruiker, boven de activiteitenkalender.
746type ProfileCard struct {
747 User store.User
748 Name, Since, Bio, URL string
749 Heading string
750 Repos, Groups, Contrib int
751 Own bool
752}
753
754// NoteRow is een reactie in de interface.
755type NoteRow struct {
756 ID int64
757 Author, AuthorURL, Body, When, Path string
758 Start, End int
759 HasSuggestion bool
760 ParentID int64
761 HTML template.HTML
762 Replies []NoteRow
763 At time.Time
764}
765
766// DiffFileView is één bestand in de merge-request-diff.
767type DiffFileView struct {
768 Path string
769 Lines []DiffLineView
770}
771
772// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
773type DiffLineView struct {
774 Kind string
775 Text string
776 Old int
777 New int
778 Notes []NoteRow
779}
780
781// TagRow is één tag op de tagspagina.
782type TagRow struct {
783 Name, Message, SHA, Short, Subject, Date, When string
784 Annotated, Protected, HasRelease, CanDelete bool
785 ZipURL, TarURL string
786}
787
788// FileRow is een rij in de bestandstabel of de boom.
789type FileRow struct {
790 Name, Path, Icon, Subject, When, SHA string
791 Dir bool
792 Depth int
793 Active bool
794 // Open geldt voor een map die het huidige pad bevat. De browser
795 // onthoudt afwijkingen daarvan per repository.
796 Open bool
797}
798
799// CodeLine is één regel broncode.
800type CodeLine struct {
801 N int
802 HTML template.HTML
803}
804
805// CommitRow is een commit in de interface.
806// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
807// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
808type CommitRow struct {
809 SHA, Short, Author, Who, Date, Subject, Body, When string
810 UserURL, WhoURL, Avatar, Initial, RawName, PushedBy string
811 Ident template.HTML
812 PipeID int64
813 PipeStatus, PipeLabel, PipeDuration string
814 PipeStages []StageView
815 PipeLive, PipeFailed bool
816}
817
818// CommitDay is één dag op de commitlijst, nieuwste dag eerst.
819type CommitDay struct {
820 Label string
821 Items []CommitRow
822}
823
824// EntryRow is een bestand of map.
825type EntryRow struct {
826 Name, Type, Path string
827}
828
829// BranchRow is een branch, met of zonder bescherming.
830type BranchRow struct {
831 Name, SHA, Short, Subject, When, WhenTitle string
832 RepoPath, ZipURL, TarURL string
833 Protected, Default, CanEdit bool
834 Target string
835 Ahead, Behind int
836 Unix int64
837 PipeID int64
838 PipeStatus, PipeLabel string
839 OpenMRs []int64
840}
841
842// BranchBoard is de gegroepeerde branches-pagina.
843type BranchBoard struct {
844 State string
845 ShowActive, ShowStale bool
846 Active, Stale []BranchRow
847}
848
849// TimelineItem is één gebeurtenis of reactie op een merge request.
850type TimelineItem struct {
851 ID int64
852 Kind string
853 Actor, ActorURL, Text string
854 When string
855 Body string
856 HTML template.HTML
857 URL string
858 Replies []TimelineItem
859 At time.Time
860 Rank int
861}
862
863// HookView is een webhook plus de laatste pogingen.
864type HookView struct {
865 ID int64
866 Name string
867 Preset string
868 URL string
869 Method string
870 Filter string
871 Events string
872 Badges []string
873 Deliveries []store.Delivery
874}
875
876// HookDraft vult het webhookformulier bij bewerken. ID 0 is een nieuw formulier.
877type HookDraft struct {
878 ID int64
879 Name string
880 Preset string
881 Filter string
882 URL string
883 Username string
884 Avatar string
885 Icon string
886 Alias string
887 Token string
888 Chat string
889 Server string
890 Topic string
891 Home string
892 Room string
893 Method string
894 CType string
895 Headers string
896 Body string
897 OnPush bool
898 OnMR bool
899 OnOK bool
900 OnFail bool
901 OnRel bool
902 OnIssue bool
903 Extra []HookEventChoice
904}
905
906// HookEventChoice is een fijner event als vinkje in het webhookformulier.
907type HookEventChoice struct {
908 Name string
909 Key string
910 On bool
911}
912
913func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }