BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

feat: vrije tekst wordt een repository- of groepsslug
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Failed f9225546 History
server.go 11.7 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 "strings"
14 "sync"
15 "time"
16
17 "gitlab.com/Timfa/bluegit/internal/access"
18 "gitlab.com/Timfa/bluegit/internal/auth"
19 "gitlab.com/Timfa/bluegit/internal/config"
20 "gitlab.com/Timfa/bluegit/internal/realip"
21 "gitlab.com/Timfa/bluegit/internal/runner"
22 "gitlab.com/Timfa/bluegit/internal/store"
23)
24
25//go:embed templates/*.html static/*
26var webFS embed.FS
27
28// Server bedient BlueGit.
29type Server struct {
30 Cfg config.Config
31 Store *store.Store
32 Auth auth.Provider
33 Dev bool
34 Git string
35 HookBin string
36 Runner *runner.Runner
37 Log *slog.Logger
38 // StateDir is de map met database en het bestand storage_path.
39 StateDir string
40 // AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
41 AfterStorage func(path string)
42 tmpl *template.Template
43
44 storageMu sync.RWMutex
45 storage string
46 storageSet bool
47}
48
49type principal struct {
50 User store.User
51 Session store.Session
52 OK bool
53}
54
55type ctxKey struct{}
56
57// Handler is de HTTP-handler met sessies en koppen.
58func (s *Server) Handler() http.Handler {
59 s.mustTemplates()
60 mux := http.NewServeMux()
61 mux.HandleFunc("GET /assets/{file}", s.asset)
62 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
63 w.WriteHeader(http.StatusOK)
64 _, _ = w.Write([]byte("ok\n"))
65 })
66 mux.HandleFunc("GET /login", s.login)
67 mux.HandleFunc("GET /auth/callback", s.callback)
68 mux.HandleFunc("POST /logout", s.logout)
69 mux.HandleFunc("GET /{$}", s.home)
70 mux.HandleFunc("GET /new", s.newPage)
71 mux.HandleFunc("GET /new/slug", s.slugPreview)
72 mux.HandleFunc("POST /new/repo", s.createRepo)
73 mux.HandleFunc("POST /new/group", s.createGroup)
74 mux.HandleFunc("GET /setup", s.setupPage)
75 mux.HandleFunc("POST /setup", s.setupSave)
76 mux.HandleFunc("GET /settings", s.account)
77 mux.HandleFunc("POST /settings/tokens", s.createToken)
78 mux.HandleFunc("POST /settings/tokens/delete", s.deleteToken)
79 mux.HandleFunc("POST /settings/ssh", s.addSSH)
80 mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
81 mux.HandleFunc("GET /settings/export", s.export)
82 mux.HandleFunc("GET /groups/{path}", s.groupPage)
83 mux.HandleFunc("POST /groups/{path}/members", s.groupMember)
84 mux.HandleFunc("POST /groups/{path}/members/remove", s.groupMemberRemove)
85 mux.HandleFunc("POST /groups/{path}/secrets", s.groupSecret)
86 mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
87 mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
88 mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)
89
90 mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
91 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
92 mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
93 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
94
95 mux.HandleFunc("GET /{owner}/{repo}", s.repoHome)
96 mux.HandleFunc("GET /{owner}/{repo}/-/tree/{path...}", s.tree)
97 mux.HandleFunc("GET /{owner}/{repo}/-/blob/{path...}", s.blob)
98 mux.HandleFunc("GET /{owner}/{repo}/-/commits", s.commits)
99 mux.HandleFunc("GET /{owner}/{repo}/-/commit/{sha}", s.commit)
100 mux.HandleFunc("GET /{owner}/{repo}/-/branches", s.branches)
101 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests)
102 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR)
103 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR)
104 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR)
105 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR)
106 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines)
107 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline)
108 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline)
109 mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases)
110 mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
111 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
112 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
113 mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember)
114 mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove)
115 mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected)
116 mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected)
117 mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret)
118 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
119 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
120 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
121 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
122
123 return s.realIP(s.withSession(s.secure(s.gate(mux))))
124}
125
126func (s *Server) realIP(next http.Handler) http.Handler {
127 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
128 realip.Apply(r, s.Cfg.ProxySet())
129 next.ServeHTTP(w, r)
130 })
131}
132
133func (s *Server) mustTemplates() {
134 if s.tmpl != nil {
135 return
136 }
137 s.tmpl = template.Must(template.New("web").Funcs(template.FuncMap{
138 "short": func(v string) string {
139 if len(v) > 10 {
140 return v[:10]
141 }
142 return v
143 },
144 "join": strings.Join,
145 }).ParseFS(webFS, "templates/*.html"))
146}
147
148func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
149 name := r.PathValue("file")
150 if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") {
151 http.NotFound(w, r)
152 return
153 }
154 sub, err := fs.Sub(webFS, "static")
155 if err != nil {
156 http.Error(w, "assets", http.StatusInternalServerError)
157 return
158 }
159 http.ServeFileFS(w, r, sub, name)
160}
161
162func (s *Server) secure(next http.Handler) http.Handler {
163 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
164 w.Header().Set("X-Content-Type-Options", "nosniff")
165 w.Header().Set("X-Frame-Options", "DENY")
166 w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
167 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'")
168 next.ServeHTTP(w, r)
169 })
170}
171
172func (s *Server) withSession(next http.Handler) http.Handler {
173 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
174 p := principal{}
175 if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" {
176 sess, err := s.Store.Session(r.Context(), c.Value)
177 if err == nil && sess.ExpiresAt.After(time.Now()) {
178 p.Session = sess
179 p.User = sess.User
180 p.OK = true
181 s.maybeExtend(r.Context(), sess)
182 }
183 }
184 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
185 })
186}
187
188func (s *Server) maybeExtend(ctx context.Context, sess store.Session) {
189 if time.Until(sess.ExpiresAt) > 6*time.Hour {
190 return
191 }
192 sec, err := s.Auth.Extend(ctx, sess.AccessToken)
193 if err != nil || sec <= 0 {
194 return
195 }
196 _ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second))
197}
198
199func (s *Server) who(r *http.Request) principal {
200 p, _ := r.Context().Value(ctxKey{}).(principal)
201 return p
202}
203
204func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool {
205 if err := r.ParseForm(); err != nil {
206 http.Error(w, "ongeldig formulier", http.StatusBadRequest)
207 return false
208 }
209 p := s.who(r)
210 if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
211 http.Error(w, "ongeldig formulier, vernieuw de pagina", http.StatusBadRequest)
212 return false
213 }
214 return true
215}
216
217func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) {
218 p := s.who(r)
219 if !p.OK {
220 http.Redirect(w, r, "/login", http.StatusFound)
221 return store.User{}, false
222 }
223 return p.User, true
224}
225
226func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) {
227 http.SetCookie(w, &http.Cookie{
228 Name: "bluegit_session",
229 Value: id,
230 Path: "/",
231 HttpOnly: true,
232 SameSite: http.SameSiteLaxMode,
233 Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://"),
234 Expires: exp,
235 })
236}
237
238func (s *Server) flash(w http.ResponseWriter, notice, problem string) {
239 secure := strings.HasPrefix(s.Cfg.BaseURL, "https://")
240 if notice != "" {
241 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: notice, Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
242 }
243 if problem != "" {
244 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: problem, Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
245 }
246}
247
248func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) {
249 notice, problem := cookieVal(r, "bluegit_notice"), cookieVal(r, "bluegit_error")
250 if notice != "" {
251 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1})
252 }
253 if problem != "" {
254 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1})
255 }
256 return notice, problem
257}
258
259func cookieVal(r *http.Request, name string) string {
260 c, err := r.Cookie(name)
261 if err != nil {
262 return ""
263 }
264 return c.Value
265}
266
267func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) {
268 s.flash(w, notice, problem)
269 http.Redirect(w, r, path, http.StatusSeeOther)
270}
271
272func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View {
273 notice, problem := s.takeFlash(w, r)
274 v := View{Title: title, BaseURL: s.Cfg.BaseURL, Notice: notice, Err: problem, StorageUnset: s.StoragePath() == ""}
275 if p := s.who(r); p.OK {
276 u := p.User
277 v.User = &u
278 v.CSRF = p.Session.CSRF
279 }
280 return v
281}
282
283func (s *Server) render(w http.ResponseWriter, name string, v View) {
284 w.Header().Set("Content-Type", "text/html; charset=utf-8")
285 if err := s.tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
286 s.Log.Error("sjabloon", "name", name, "err", err)
287 }
288}
289
290func randomState() (string, error) {
291 b := make([]byte, 32)
292 if _, err := rand.Read(b); err != nil {
293 return "", err
294 }
295 return hex.EncodeToString(b), nil
296}
297
298// View is de gegevensset voor elk scherm.
299type View struct {
300 Title string
301 BaseURL string
302 User *store.User
303 CSRF string
304 Notice string
305 Err string
306 Repos []store.Repo
307 Groups []store.Group
308 Repo *store.Repo
309 Role access.Role
310 CanWrite bool
311 CanAdmin bool
312 CanMerge bool
313 Commits []CommitRow
314 Commit *CommitRow
315 Entries []EntryRow
316 TreePath string
317 Blob string
318 BlobPath string
319 Binary bool
320 Branches []BranchRow
321 MRs []store.MergeRequest
322 MR *store.MergeRequest
323 Diff string
324 Pipes []store.Pipeline
325 Pipe *store.Pipeline
326 Jobs []store.Job
327 Releases []store.Release
328 Members []store.Member
329 Secrets []store.SecretMeta
330 Hooks []HookView
331 Patterns []string
332 Tokens []store.TokenInfo
333 Keys []store.SSHKey
334 CloneHTTP string
335 CloneSSH string
336 Group *store.Group
337 Tab string
338 Rev string
339 NewToken string
340 StorageUnset bool
341 StoragePath string
342 StorageFree string
343 StorageTotal string
344 MinFree string
345}
346
347// CommitRow is een commit in de interface.
348type CommitRow struct {
349 SHA, Short, Author, Date, Subject, Body string
350}
351
352// EntryRow is een bestand of map.
353type EntryRow struct {
354 Name, Type, Path string
355}
356
357// BranchRow is een branch, met of zonder bescherming.
358type BranchRow struct {
359 Name string
360 Protected bool
361}
362
363// HookView is een webhook plus de laatste pogingen.
364type HookView struct {
365 ID int64
366 Name string
367 Preset string
368 URL string
369 Filter string
370 Events string
371 Deliveries []store.Delivery
372}
373
374func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }