BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

feat: noem de ingebouwde runner Steve
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Failed f32ad8a5 History
server.go 18.0 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 name := strings.TrimSpace(s.Cfg.Runner.Name)
373 if name == "" {
374 name = "Steve"
375 }
376 v := View{
377 Title: title, BaseURL: s.Cfg.BaseURL, RunnerName: name, Notice: notice, Err: problem,
378 StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang),
379 Cunei: lang == i18n.Cuneiform,
380 }
381 for _, l := range i18n.All() {
382 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
383 }
384 if p := s.who(r); p.OK {
385 u := p.User
386 v.User = &u
387 v.CSRF = p.Session.CSRF
388 }
389 return v
390}
391
392func htmlLang(l i18n.Lang) string {
393 switch l {
394 case i18n.NL:
395 return "nl"
396 case i18n.DE:
397 return "de"
398 case i18n.FR:
399 return "fr"
400 default:
401 return "en"
402 }
403}
404
405func (s *Server) render(w http.ResponseWriter, name string, v View) {
406 w.Header().Set("Content-Type", "text/html; charset=utf-8")
407 tmpl := s.byLang[v.Lang]
408 if tmpl == nil {
409 tmpl = s.tmpl
410 }
411 if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
412 s.Log.Error("sjabloon", "name", name, "err", err)
413 }
414}
415
416func randomState() (string, error) {
417 b := make([]byte, 32)
418 if _, err := rand.Read(b); err != nil {
419 return "", err
420 }
421 return hex.EncodeToString(b), nil
422}
423
424// View is de gegevensset voor elk scherm.
425type View struct {
426 Title string
427 BaseURL string
428 RunnerName string
429 User *store.User
430 CSRF string
431 Notice string
432 Err string
433 Repos []store.Repo
434 Groups []store.Group
435 Repo *store.Repo
436 Role access.Role
437 CanWrite bool
438 CanAdmin bool
439 CanMerge bool
440 CanComment bool
441 CanApply bool
442 Commits []CommitRow
443 Commit *CommitRow
444 Entries []EntryRow
445 TreePath string
446 Blob string
447 BlobPath string
448 Binary bool
449 Branches []BranchRow
450 MRs []store.MergeRequest
451 MR *store.MergeRequest
452 MRPipe *PipeRow
453 MergeBlocks []string
454 Approval *ApprovalView
455 Reviews []ReviewRow
456 CanReview bool
457 CanApprove bool
458 CanDismiss bool
459 CanClose bool
460 CanReopen bool
461 IsOwner bool
462 Candidates []store.Member
463 Diff string
464 DiffFiles []DiffFileView
465 Pipes []store.Pipeline
466 PipeRows []PipeRow
467 Pipe *store.Pipeline
468 Jobs []store.Job
469 JobPage *JobPage
470 Editor *CIEditor
471 Releases []store.Release
472 Members []store.Member
473 Secrets []store.SecretMeta
474 Hooks []HookView
475 Patterns []string
476 Tokens []store.TokenInfo
477 Keys []store.SSHKey
478 CloneHTTP string
479 CloneSSH string
480 Group *store.Group
481 Tab string
482 Rev string
483 NewToken string
484 StorageUnset bool
485 StoragePath string
486 StorageFree string
487 StorageTotal string
488 MinFree string
489 Wide bool
490 Page string
491 Lang string
492 HTMLLang string
493 Cunei bool
494 Langs []LangChoice
495 Query string
496 SortDir string
497 FlipDir string
498 Cards []RepoCard
499 Head *CommitRow
500 Files []FileRow
501 Tree []FileRow
502 Readme template.HTML
503 ReadmeName string
504 LicensePath string
505 NCommits int
506 NBranches int
507 NTags int
508 NReleases int
509 Created string
510 Lines []CodeLine
511 BlobSize string
512 FileName string
513 RevProtected bool
514 TagNames []string
515 Heat *activity.Calendar
516 Notes []NoteRow
517 Profile *store.User
518}
519
520// LangChoice is één taal in de instellingen.
521type LangChoice struct {
522 Code, Label string
523}
524
525// RepoCard is een repository in een groepslijst.
526type RepoCard struct {
527 Repo store.Repo
528 Stars int
529 Starred bool
530 When string
531}
532
533// NoteRow is een reactie in de interface.
534type NoteRow struct {
535 ID int64
536 Author, Body, When, Path string
537 Start, End int
538 HasSuggestion bool
539}
540
541// DiffFileView is één bestand in de merge-request-diff.
542type DiffFileView struct {
543 Path string
544 Lines []DiffLineView
545}
546
547// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
548type DiffLineView struct {
549 Kind string
550 Text string
551 Old int
552 New int
553 Notes []NoteRow
554}
555
556// FileRow is een rij in de bestandstabel of de boom.
557type FileRow struct {
558 Name, Path, Icon, Subject, When, SHA string
559 Dir bool
560 Depth int
561 Active bool
562}
563
564// CodeLine is één regel broncode.
565type CodeLine struct {
566 N int
567 HTML template.HTML
568}
569
570// CommitRow is een commit in de interface.
571// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
572// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
573type CommitRow struct {
574 SHA, Short, Author, Date, Subject, Body, When string
575 UserURL, Avatar, Initial, RawName, PushedBy string
576}
577
578// EntryRow is een bestand of map.
579type EntryRow struct {
580 Name, Type, Path string
581}
582
583// BranchRow is een branch, met of zonder bescherming.
584type BranchRow struct {
585 Name string
586 Protected bool
587}
588
589// HookView is een webhook plus de laatste pogingen.
590type HookView struct {
591 ID int64
592 Name string
593 Preset string
594 URL string
595 Method string
596 Filter string
597 Events string
598 Deliveries []store.Delivery
599}
600
601func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }