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