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