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