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