BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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