BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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