BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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