BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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