BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

feat: groepseigenaar blijft beheerder en kan eigenaarschap overdragen
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
63e5d53c History
server.go 17.9 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 "html/template"
10 "io/fs"
11 "log/slog"
12 "net/http"
13 "net/url"
14 "strings"
15 "sync"
16 "time"
17 "unicode/utf8"
18
19 "gitlab.com/Timfa/bluegit/internal/access"
20 "gitlab.com/Timfa/bluegit/internal/activity"
21 "gitlab.com/Timfa/bluegit/internal/auth"
22 "gitlab.com/Timfa/bluegit/internal/config"
23 "gitlab.com/Timfa/bluegit/internal/i18n"
24 "gitlab.com/Timfa/bluegit/internal/realip"
25 "gitlab.com/Timfa/bluegit/internal/runner"
26 "gitlab.com/Timfa/bluegit/internal/store"
27)
28
29//go:embed templates/*.html static/*
30var webFS embed.FS
31
32// Server bedient BlueGit.
33type Server struct {
34 Cfg config.Config
35 Store *store.Store
36 Auth auth.Provider
37 Mail auth.Mailer
38 Dev bool
39 Git string
40 HookBin string
41 Runner *runner.Runner
42 Log *slog.Logger
43 // StateDir is de map met database en het bestand storage_path.
44 StateDir string
45 // AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
46 AfterStorage func(path string)
47 tmpl *template.Template
48 byLang map[string]*template.Template
49
50 storageMu sync.RWMutex
51 storage string
52 storageSet bool
53}
54
55type principal struct {
56 User store.User
57 Session store.Session
58 OK bool
59}
60
61type ctxKey struct{}
62
63// Handler is de HTTP-handler met sessies en koppen.
64func (s *Server) Handler() http.Handler {
65 s.mustTemplates()
66 mux := http.NewServeMux()
67 mux.HandleFunc("GET /assets/{file}", s.asset)
68 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
69 w.WriteHeader(http.StatusOK)
70 _, _ = w.Write([]byte("ok\n"))
71 })
72 mux.HandleFunc("GET /login", s.login)
73 mux.HandleFunc("GET /auth/callback", s.callback)
74 mux.HandleFunc("POST /logout", s.logout)
75 mux.HandleFunc("GET /{$}", s.home)
76 mux.HandleFunc("GET /new", s.newPage)
77 mux.HandleFunc("GET /new/slug", s.slugPreview)
78 mux.HandleFunc("POST /new/repo", s.createRepo)
79 mux.HandleFunc("POST /new/group", s.createGroup)
80 mux.HandleFunc("GET /setup", s.setupPage)
81 mux.HandleFunc("POST /setup", s.setupSave)
82 mux.HandleFunc("GET /settings", s.account)
83 mux.HandleFunc("POST /settings/language", s.saveLanguage)
84 mux.HandleFunc("POST /settings/tokens", s.createToken)
85 mux.HandleFunc("POST /settings/tokens/delete", s.deleteToken)
86 mux.HandleFunc("POST /settings/ssh", s.addSSH)
87 mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
88 mux.HandleFunc("GET /settings/export", s.export)
89 mux.HandleFunc("GET /users/{username}", s.profile)
90 mux.HandleFunc("GET /groups/{path}", s.groupPage)
91 mux.HandleFunc("GET /groups/{path}/logo", s.groupLogo)
92 mux.HandleFunc("POST /groups/{path}/settings", s.saveGroup)
93 mux.HandleFunc("POST /groups/{path}/approvals", s.saveGroupApproval)
94 mux.HandleFunc("POST /groups/{path}/owner", s.transferGroup)
95 mux.HandleFunc("POST /groups/{path}/logo", s.uploadGroupLogo)
96 mux.HandleFunc("POST /groups/{path}/members", s.groupMember)
97 mux.HandleFunc("POST /groups/{path}/members/remove", s.groupMemberRemove)
98 mux.HandleFunc("POST /groups/{path}/secrets", s.groupSecret)
99 mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
100 mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
101 mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)
102
103 mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
104 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
105 mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
106 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
107
108 mux.HandleFunc("GET /{owner}/{repo}", s.repoHome)
109 mux.HandleFunc("GET /{owner}/{repo}/-/tree", s.treeRoot)
110 mux.HandleFunc("GET /{owner}/{repo}/-/tree/{path...}", s.tree)
111 mux.HandleFunc("GET /{owner}/{repo}/-/blob/{path...}", s.blob)
112 mux.HandleFunc("GET /{owner}/{repo}/-/commits", s.commits)
113 mux.HandleFunc("GET /{owner}/{repo}/-/tags", s.tags)
114 mux.HandleFunc("GET /{owner}/{repo}/-/commit/{sha}", s.commit)
115 mux.HandleFunc("GET /{owner}/{repo}/-/branches", s.branches)
116 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests)
117 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR)
118 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR)
119 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR)
120 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR)
121 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reopen", s.reopenMR)
122 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews", s.postReview)
123 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews/dismiss", s.dismissReview)
124 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/notes", s.createNote)
125 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/suggestions", s.applySuggestions)
126 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines)
127 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline)
128 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline)
129 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}", s.showJob)
130 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/log", s.jobLog)
131 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/play", s.playJob)
132 mux.HandleFunc("GET /{owner}/{repo}/-/ci/editor", s.ciEditor)
133 mux.HandleFunc("POST /{owner}/{repo}/-/ci/editor", s.saveCIEditor)
134 mux.HandleFunc("POST /{owner}/{repo}/-/ci/lint", s.lintCI)
135 mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases)
136 mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
137 mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
138 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
139 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
140 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
141 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
142 mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
143 mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember)
144 mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove)
145 mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected)
146 mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected)
147 mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret)
148 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
149 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
150 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
151 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
152
153 return s.realIP(s.withSession(s.secure(s.gate(mux))))
154}
155
156func (s *Server) realIP(next http.Handler) http.Handler {
157 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
158 realip.Apply(r, s.Cfg.ProxySet())
159 next.ServeHTTP(w, r)
160 })
161}
162
163func (s *Server) mustTemplates() {
164 if s.byLang != nil {
165 return
166 }
167 s.byLang = map[string]*template.Template{}
168 for _, lang := range i18n.All() {
169 l := lang
170 s.byLang[string(l)] = template.Must(template.New("web").Funcs(template.FuncMap{
171 "short": func(v string) string {
172 if len(v) > 10 {
173 return v[:10]
174 }
175 return v
176 },
177 "join": strings.Join,
178 "initial": func(s string) string {
179 s = strings.TrimSpace(s)
180 if s == "" {
181 return "?"
182 }
183 r, _ := utf8.DecodeRuneInString(s)
184 return strings.ToUpper(string(r))
185 },
186 "splitPath": func(p string) []string {
187 if p == "" {
188 return nil
189 }
190 return strings.Split(p, "/")
191 },
192 "iconOf": func(name string) string { return fileIcon(name, "blob") },
193 "t": func(key string, args ...any) string { return i18n.T(l, key, args...) },
194 "tn": func(n int, one, many string) string {
195 key := many
196 if n == 1 {
197 key = one
198 }
199 return i18n.T(l, key, n)
200 },
201 "roleName": func(r access.Role) string { return i18n.T(l, "role."+string(r)) },
202 "visName": func(v string) string { return i18n.T(l, "vis."+v) },
203 "presetName": func(id string) string {
204 label := i18n.T(l, "set.preset."+id)
205 if label == "set.preset."+id {
206 return id
207 }
208 return label
209 },
210 }).ParseFS(webFS, "templates/*.html"))
211 }
212 s.tmpl = s.byLang[string(i18n.EN)]
213}
214
215func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
216 name := r.PathValue("file")
217 if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") {
218 http.NotFound(w, r)
219 return
220 }
221 sub, err := fs.Sub(webFS, "static")
222 if err != nil {
223 http.Error(w, "assets", http.StatusInternalServerError)
224 return
225 }
226 http.ServeFileFS(w, r, sub, name)
227}
228
229func (s *Server) secure(next http.Handler) http.Handler {
230 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
231 w.Header().Set("X-Content-Type-Options", "nosniff")
232 w.Header().Set("X-Frame-Options", "DENY")
233 w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
234 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'")
235 next.ServeHTTP(w, r)
236 })
237}
238
239func (s *Server) withSession(next http.Handler) http.Handler {
240 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
241 p := principal{}
242 if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" {
243 sess, err := s.Store.Session(r.Context(), c.Value)
244 if err == nil && sess.ExpiresAt.After(time.Now()) {
245 p.Session = sess
246 p.User = sess.User
247 p.OK = true
248 s.maybeExtend(r.Context(), sess)
249 }
250 }
251 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
252 })
253}
254
255func (s *Server) maybeExtend(ctx context.Context, sess store.Session) {
256 if time.Until(sess.ExpiresAt) > 6*time.Hour {
257 return
258 }
259 sec, err := s.Auth.Extend(ctx, sess.AccessToken)
260 if err != nil || sec <= 0 {
261 return
262 }
263 _ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second))
264}
265
266func (s *Server) who(r *http.Request) principal {
267 p, _ := r.Context().Value(ctxKey{}).(principal)
268 return p
269}
270
271func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool {
272 if err := r.ParseForm(); err != nil {
273 http.Error(w, s.tr(r, "err.badForm"), http.StatusBadRequest)
274 return false
275 }
276 p := s.who(r)
277 if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
278 http.Error(w, s.tr(r, "err.badCSRF"), http.StatusBadRequest)
279 return false
280 }
281 return true
282}
283
284func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) {
285 p := s.who(r)
286 if !p.OK {
287 http.Redirect(w, r, "/login", http.StatusFound)
288 return store.User{}, false
289 }
290 return p.User, true
291}
292
293func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) {
294 http.SetCookie(w, &http.Cookie{
295 Name: "bluegit_session",
296 Value: id,
297 Path: "/",
298 HttpOnly: true,
299 SameSite: http.SameSiteLaxMode,
300 Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://"),
301 Expires: exp,
302 })
303}
304
305func (s *Server) flash(w http.ResponseWriter, notice, problem string) {
306 secure := strings.HasPrefix(s.Cfg.BaseURL, "https://")
307 if notice != "" {
308 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: url.QueryEscape(notice), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
309 }
310 if problem != "" {
311 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: url.QueryEscape(problem), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
312 }
313}
314
315func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) {
316 notice, problem := flashVal(r, "bluegit_notice"), flashVal(r, "bluegit_error")
317 if notice != "" {
318 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1})
319 }
320 if problem != "" {
321 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1})
322 }
323 return notice, problem
324}
325
326func cookieVal(r *http.Request, name string) string {
327 c, err := r.Cookie(name)
328 if err != nil {
329 return ""
330 }
331 return c.Value
332}
333
334func flashVal(r *http.Request, name string) string {
335 raw := cookieVal(r, name)
336 if raw == "" {
337 return ""
338 }
339 v, err := url.QueryUnescape(raw)
340 if err != nil {
341 return raw
342 }
343 return v
344}
345
346func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) {
347 s.flash(w, notice, problem)
348 http.Redirect(w, r, path, http.StatusSeeOther)
349}
350
351func (s *Server) langOf(r *http.Request) i18n.Lang {
352 if p := s.who(r); p.OK {
353 return i18n.Parse(p.User.Language)
354 }
355 return i18n.EN
356}
357
358func (s *Server) tr(r *http.Request, key string, args ...any) string {
359 return i18n.T(s.langOf(r), key, args...)
360}
361
362func (s *Server) trErr(r *http.Request, err error) string {
363 return i18n.Text(s.langOf(r), err)
364}
365
366func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View {
367 notice, problem := s.takeFlash(w, r)
368 lang := s.langOf(r)
369 if strings.HasPrefix(title, "title.") {
370 title = i18n.T(lang, title)
371 }
372 v := View{
373 Title: title, BaseURL: s.Cfg.BaseURL, Notice: notice, Err: problem,
374 StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang),
375 Cunei: lang == i18n.Cuneiform,
376 }
377 for _, l := range i18n.All() {
378 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
379 }
380 if p := s.who(r); p.OK {
381 u := p.User
382 v.User = &u
383 v.CSRF = p.Session.CSRF
384 }
385 return v
386}
387
388func htmlLang(l i18n.Lang) string {
389 switch l {
390 case i18n.NL:
391 return "nl"
392 case i18n.DE:
393 return "de"
394 case i18n.FR:
395 return "fr"
396 default:
397 return "en"
398 }
399}
400
401func (s *Server) render(w http.ResponseWriter, name string, v View) {
402 w.Header().Set("Content-Type", "text/html; charset=utf-8")
403 tmpl := s.byLang[v.Lang]
404 if tmpl == nil {
405 tmpl = s.tmpl
406 }
407 if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
408 s.Log.Error("sjabloon", "name", name, "err", err)
409 }
410}
411
412func randomState() (string, error) {
413 b := make([]byte, 32)
414 if _, err := rand.Read(b); err != nil {
415 return "", err
416 }
417 return hex.EncodeToString(b), nil
418}
419
420// View is de gegevensset voor elk scherm.
421type View struct {
422 Title string
423 BaseURL string
424 User *store.User
425 CSRF string
426 Notice string
427 Err string
428 Repos []store.Repo
429 Groups []store.Group
430 Repo *store.Repo
431 Role access.Role
432 CanWrite bool
433 CanAdmin bool
434 CanMerge bool
435 CanComment bool
436 CanApply bool
437 Commits []CommitRow
438 Commit *CommitRow
439 Entries []EntryRow
440 TreePath string
441 Blob string
442 BlobPath string
443 Binary bool
444 Branches []BranchRow
445 MRs []store.MergeRequest
446 MR *store.MergeRequest
447 MRPipe *PipeRow
448 MergeBlocks []string
449 Approval *ApprovalView
450 Reviews []ReviewRow
451 CanReview bool
452 CanApprove bool
453 CanDismiss bool
454 CanClose bool
455 CanReopen bool
456 IsOwner bool
457 Candidates []store.Member
458 Diff string
459 DiffFiles []DiffFileView
460 Pipes []store.Pipeline
461 PipeRows []PipeRow
462 Pipe *store.Pipeline
463 Jobs []store.Job
464 JobPage *JobPage
465 Editor *CIEditor
466 Releases []store.Release
467 Members []store.Member
468 Secrets []store.SecretMeta
469 Hooks []HookView
470 Patterns []string
471 Tokens []store.TokenInfo
472 Keys []store.SSHKey
473 CloneHTTP string
474 CloneSSH string
475 Group *store.Group
476 Tab string
477 Rev string
478 NewToken string
479 StorageUnset bool
480 StoragePath string
481 StorageFree string
482 StorageTotal string
483 MinFree string
484 Wide bool
485 Page string
486 Lang string
487 HTMLLang string
488 Cunei bool
489 Langs []LangChoice
490 Query string
491 SortDir string
492 FlipDir string
493 Cards []RepoCard
494 Head *CommitRow
495 Files []FileRow
496 Tree []FileRow
497 Readme template.HTML
498 ReadmeName string
499 LicensePath string
500 NCommits int
501 NBranches int
502 NTags int
503 NReleases int
504 Created string
505 Lines []CodeLine
506 BlobSize string
507 FileName string
508 RevProtected bool
509 TagNames []string
510 Heat *activity.Calendar
511 Notes []NoteRow
512 Profile *store.User
513}
514
515// LangChoice is één taal in de instellingen.
516type LangChoice struct {
517 Code, Label string
518}
519
520// RepoCard is een repository in een groepslijst.
521type RepoCard struct {
522 Repo store.Repo
523 Stars int
524 Starred bool
525 When string
526}
527
528// NoteRow is een reactie in de interface.
529type NoteRow struct {
530 ID int64
531 Author, Body, When, Path string
532 Start, End int
533 HasSuggestion bool
534}
535
536// DiffFileView is één bestand in de merge-request-diff.
537type DiffFileView struct {
538 Path string
539 Lines []DiffLineView
540}
541
542// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
543type DiffLineView struct {
544 Kind string
545 Text string
546 Old int
547 New int
548 Notes []NoteRow
549}
550
551// FileRow is een rij in de bestandstabel of de boom.
552type FileRow struct {
553 Name, Path, Icon, Subject, When, SHA string
554 Dir bool
555 Depth int
556 Active bool
557}
558
559// CodeLine is één regel broncode.
560type CodeLine struct {
561 N int
562 HTML template.HTML
563}
564
565// CommitRow is een commit in de interface.
566// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
567// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
568type CommitRow struct {
569 SHA, Short, Author, Date, Subject, Body, When string
570 UserURL, Avatar, Initial, RawName, PushedBy string
571}
572
573// EntryRow is een bestand of map.
574type EntryRow struct {
575 Name, Type, Path string
576}
577
578// BranchRow is een branch, met of zonder bescherming.
579type BranchRow struct {
580 Name string
581 Protected bool
582}
583
584// HookView is een webhook plus de laatste pogingen.
585type HookView struct {
586 ID int64
587 Name string
588 Preset string
589 URL string
590 Method string
591 Filter string
592 Events string
593 Deliveries []store.Delivery
594}
595
596func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }