BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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