| 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 | "fmt" |
| 10 | "gitlab.com/Timfa/bluegit/internal/langpick" |
| 11 | "gitlab.com/Timfa/bluegit/internal/readcache" |
| 12 | "gitlab.com/Timfa/bluegit/internal/runnercfg" |
| 13 | "html/template" |
| 14 | "io/fs" |
| 15 | "log/slog" |
| 16 | "net/http" |
| 17 | "net/url" |
| 18 | "strings" |
| 19 | "sync" |
| 20 | "time" |
| 21 | "unicode/utf8" |
| 22 | |
| 23 | "gitlab.com/Timfa/bluegit/internal/access" |
| 24 | "gitlab.com/Timfa/bluegit/internal/activity" |
| 25 | "gitlab.com/Timfa/bluegit/internal/auth" |
| 26 | "gitlab.com/Timfa/bluegit/internal/card" |
| 27 | "gitlab.com/Timfa/bluegit/internal/cispec" |
| 28 | "gitlab.com/Timfa/bluegit/internal/config" |
| 29 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 30 | "gitlab.com/Timfa/bluegit/internal/realip" |
| 31 | "gitlab.com/Timfa/bluegit/internal/runner" |
| 32 | "gitlab.com/Timfa/bluegit/internal/store" |
| 33 | ) |
| 34 | |
| 35 | //go:embed templates/*.html static/*.css static/*.js static/*.svg static/*.ttf static/*.txt |
| 36 | var webFS embed.FS |
| 37 | |
| 38 | // Server bedient BlueGit. |
| 39 | type Server struct { |
| 40 | Cfg config.Config |
| 41 | Store *store.Store |
| 42 | Auth auth.Provider |
| 43 | Mail auth.Mailer |
| 44 | Dev bool |
| 45 | Git string |
| 46 | HookBin string |
| 47 | Runner *runner.Runner |
| 48 | Log *slog.Logger |
| 49 | // hookSink vangt de JSON-body af in tests, vóór het HTTP-verzoek. |
| 50 | hookSink func([]byte) |
| 51 | // StateDir is de map met database en het bestand storage_path. |
| 52 | StateDir string |
| 53 | // AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH. |
| 54 | AfterStorage func(path string) |
| 55 | // UpdateStarter start bluegit-update.service. Nil gebruikt systemctl. |
| 56 | UpdateStarter UpdateStarter |
| 57 | updateHits updateLimiter |
| 58 | tmpl *template.Template |
| 59 | byLang map[string]*template.Template |
| 60 | |
| 61 | storageMu sync.RWMutex |
| 62 | storage string |
| 63 | storageSet bool |
| 64 | usageMu sync.Mutex |
| 65 | usage dirUsage |
| 66 | usageDone chan struct{} |
| 67 | cards *card.Cache |
| 68 | // mergingMR zijn merge requests die opMergeMR nu zelf afrondt. |
| 69 | // AfterPush mag hun bronbranch niet alvast verwijderen. |
| 70 | mergingMR sync.Map |
| 71 | |
| 72 | cacheMu sync.RWMutex |
| 73 | rcache *readcache.Cache |
| 74 | } |
| 75 | |
| 76 | type principal struct { |
| 77 | User store.User |
| 78 | Session store.Session |
| 79 | OK bool |
| 80 | } |
| 81 | |
| 82 | type ctxKey struct{} |
| 83 | |
| 84 | // Handler is de HTTP-handler met sessies en koppen. |
| 85 | func (s *Server) Handler() http.Handler { |
| 86 | s.mustTemplates() |
| 87 | mux := http.NewServeMux() |
| 88 | mux.HandleFunc("GET /assets/{file}", s.asset) |
| 89 | mux.HandleFunc("GET /-/info", s.infoPage) |
| 90 | mux.HandleFunc("GET /help", s.helpIndex) |
| 91 | mux.HandleFunc("GET /help/{doc}", s.helpPage) |
| 92 | s.mountRunnerAdmin(mux) |
| 93 | s.mountAdmin(mux) |
| 94 | mux.HandleFunc("POST /-/lang", s.switchLang) |
| 95 | mux.HandleFunc("GET /-/card.png", s.cardPNG) |
| 96 | mux.HandleFunc("GET /api/v1/oembed", s.oembed) |
| 97 | s.mountAPI(mux) |
| 98 | mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus) |
| 99 | mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate) |
| 100 | mux.HandleFunc("GET /api/v1/webhooks/openapi.json", s.webhookSpec) |
| 101 | mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { |
| 102 | w.WriteHeader(http.StatusOK) |
| 103 | _, _ = w.Write([]byte("ok\n")) |
| 104 | }) |
| 105 | mux.HandleFunc("GET /login", s.login) |
| 106 | mux.HandleFunc("GET /auth/callback", s.callback) |
| 107 | mux.HandleFunc("POST /logout", s.logout) |
| 108 | mux.HandleFunc("GET /{$}", s.home) |
| 109 | mux.HandleFunc("GET /new", s.newPage) |
| 110 | mux.HandleFunc("GET /new/slug", s.slugPreview) |
| 111 | mux.HandleFunc("POST /new/repo", s.createRepo) |
| 112 | mux.HandleFunc("POST /new/group", s.createGroup) |
| 113 | mux.HandleFunc("GET /setup", s.setupPage) |
| 114 | mux.HandleFunc("POST /setup", s.setupSave) |
| 115 | mux.HandleFunc("POST /setup/cache", s.setupCacheSave) |
| 116 | mux.HandleFunc("POST /setup/cache/clear", s.setupCacheClear) |
| 117 | s.routeRunners(mux) |
| 118 | mux.HandleFunc("GET /settings", s.account) |
| 119 | mux.HandleFunc("POST /settings/language", s.saveLanguage) |
| 120 | mux.HandleFunc("POST /settings/profile", s.saveProfile) |
| 121 | mux.HandleFunc("POST /settings/tokens", s.createToken) |
| 122 | mux.HandleFunc("POST /settings/tokens/delete", s.deleteToken) |
| 123 | mux.HandleFunc("POST /settings/ssh", s.addSSH) |
| 124 | mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH) |
| 125 | mux.HandleFunc("GET /settings/export", s.export) |
| 126 | mux.HandleFunc("GET /users/{username}", s.profile) |
| 127 | mux.HandleFunc("GET /{name}", s.userShort) |
| 128 | mux.HandleFunc("GET /groups/{path}", s.groupPage) |
| 129 | mux.HandleFunc("GET /groups/{path}/logo", s.groupLogo) |
| 130 | mux.HandleFunc("POST /groups/{path}/settings", s.saveGroup) |
| 131 | mux.HandleFunc("POST /groups/{path}/approvals", s.saveGroupApproval) |
| 132 | mux.HandleFunc("POST /groups/{path}/owner", s.transferGroup) |
| 133 | mux.HandleFunc("POST /groups/{path}/logo", s.uploadGroupLogo) |
| 134 | mux.HandleFunc("POST /groups/{path}/members", s.groupMember) |
| 135 | mux.HandleFunc("POST /groups/{path}/members/remove", s.groupMemberRemove) |
| 136 | mux.HandleFunc("POST /groups/{path}/secrets", s.groupSecret) |
| 137 | mux.HandleFunc("POST /groups/{path}/secrets/reveal", s.groupSecretReveal) |
| 138 | mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete) |
| 139 | mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook) |
| 140 | mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete) |
| 141 | |
| 142 | mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP) |
| 143 | mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP) |
| 144 | mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP) |
| 145 | mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease) |
| 146 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI) |
| 147 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff", s.commitDiffAPI) |
| 148 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/merge-requests/{number}/diff", s.mrDiffAPI) |
| 149 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI) |
| 150 | mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI) |
| 151 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI) |
| 152 | mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI) |
| 153 | mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI) |
| 154 | mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues/{number}/notes", s.issueNoteAPI) |
| 155 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI) |
| 156 | mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI) |
| 157 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI) |
| 158 | mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI) |
| 159 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets) |
| 160 | mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI) |
| 161 | mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate) |
| 162 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretsAPI) |
| 163 | mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretCreateAPI) |
| 164 | mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretRevealAPI) |
| 165 | mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretUpdateAPI) |
| 166 | mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets/{name}/replace", s.repoSecretReplaceAPI) |
| 167 | mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretDeleteAPI) |
| 168 | mux.HandleFunc("GET /api/v1/groups/{path}/webhook-secrets", s.groupWebhookSecrets) |
| 169 | mux.HandleFunc("POST /api/v1/groups/{path}/hooks", s.groupWebhookAPI) |
| 170 | mux.HandleFunc("PUT /api/v1/groups/{path}/hooks/{id}", s.groupWebhookUpdate) |
| 171 | mux.HandleFunc("GET /api/v1/groups/{path}/secrets", s.groupSecretsAPI) |
| 172 | mux.HandleFunc("POST /api/v1/groups/{path}/secrets", s.groupSecretCreateAPI) |
| 173 | mux.HandleFunc("GET /api/v1/groups/{path}/secrets/{name}", s.groupSecretRevealAPI) |
| 174 | mux.HandleFunc("PUT /api/v1/groups/{path}/secrets/{name}", s.groupSecretUpdateAPI) |
| 175 | mux.HandleFunc("POST /api/v1/groups/{path}/secrets/{name}/replace", s.groupSecretReplaceAPI) |
| 176 | mux.HandleFunc("DELETE /api/v1/groups/{path}/secrets/{name}", s.groupSecretDeleteAPI) |
| 177 | mux.HandleFunc("GET /{owner}/{repo}", s.repoHome) |
| 178 | mux.HandleFunc("GET /{owner}/{repo}/{$}", s.repoRootAlias) |
| 179 | mux.HandleFunc("GET /{owner}/{repo}/-", s.repoRootAlias) |
| 180 | mux.HandleFunc("GET /{owner}/{repo}/-/{$}", s.repoRootAlias) |
| 181 | mux.HandleFunc("GET /{owner}/{repo}/-/tree", s.treeRoot) |
| 182 | mux.HandleFunc("GET /{owner}/{repo}/-/tree/{path...}", s.tree) |
| 183 | mux.HandleFunc("GET /{owner}/{repo}/-/blob/{path...}", s.blob) |
| 184 | mux.HandleFunc("GET /{owner}/{repo}/-/raw/{path...}", s.raw) |
| 185 | mux.HandleFunc("GET /{owner}/{repo}/-/commits", s.commits) |
| 186 | mux.HandleFunc("GET /{owner}/{repo}/-/tags", s.tags) |
| 187 | mux.HandleFunc("POST /{owner}/{repo}/-/tags", s.createTag) |
| 188 | mux.HandleFunc("POST /{owner}/{repo}/-/tags/delete", s.deleteTag) |
| 189 | mux.HandleFunc("GET /{owner}/{repo}/-/tags/archive", s.tagArchive) |
| 190 | mux.HandleFunc("GET /{owner}/{repo}/-/archive/{rev}/{file}", s.commitArchive) |
| 191 | mux.HandleFunc("GET /{owner}/{repo}/-/commit/{sha}", s.commit) |
| 192 | mux.HandleFunc("GET /{owner}/{repo}/-/branches/archive", s.branchArchive) |
| 193 | mux.HandleFunc("GET /{owner}/{repo}/-/branches", s.branches) |
| 194 | mux.HandleFunc("POST /{owner}/{repo}/-/branches", s.createBranch) |
| 195 | mux.HandleFunc("POST /{owner}/{repo}/-/branches/delete", s.deleteBranch) |
| 196 | mux.HandleFunc("POST /{owner}/{repo}/-/branches/rename", s.renameBranch) |
| 197 | mux.HandleFunc("GET /{owner}/{repo}/-/compare", s.compare) |
| 198 | mux.HandleFunc("POST /{owner}/{repo}/-/markdown", s.previewMarkdown) |
| 199 | mux.HandleFunc("POST /{owner}/{repo}/-/tasks", s.toggleTask) |
| 200 | mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests) |
| 201 | mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/new", s.newMR) |
| 202 | mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR) |
| 203 | mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR) |
| 204 | mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}", s.updateMR) |
| 205 | mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR) |
| 206 | mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR) |
| 207 | mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reopen", s.reopenMR) |
| 208 | mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews", s.postReview) |
| 209 | mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews/dismiss", s.dismissReview) |
| 210 | mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/notes", s.createNote) |
| 211 | mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/suggestions", s.applySuggestions) |
| 212 | mux.HandleFunc("GET /{owner}/{repo}/-/issues", s.issuesPage) |
| 213 | mux.HandleFunc("GET /{owner}/{repo}/-/issues/new", s.newIssue) |
| 214 | mux.HandleFunc("POST /{owner}/{repo}/-/issues", s.createIssue) |
| 215 | mux.HandleFunc("POST /{owner}/{repo}/-/issues/labels", s.createIssueLabel) |
| 216 | mux.HandleFunc("POST /{owner}/{repo}/-/issues/milestones", s.createIssueMilestone) |
| 217 | mux.HandleFunc("GET /{owner}/{repo}/-/issues/{number}", s.showIssue) |
| 218 | mux.HandleFunc("POST /{owner}/{repo}/-/issues/{number}", s.postIssue) |
| 219 | mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines) |
| 220 | mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline) |
| 221 | mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline) |
| 222 | mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}", s.showJob) |
| 223 | mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/log", s.jobLog) |
| 224 | mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/play", s.playJob) |
| 225 | mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/retry", s.retryPipeline) |
| 226 | mux.HandleFunc("GET /{owner}/{repo}/-/ci/editor", s.ciEditor) |
| 227 | mux.HandleFunc("POST /{owner}/{repo}/-/ci/editor", s.saveCIEditor) |
| 228 | mux.HandleFunc("POST /{owner}/{repo}/-/ci/lint", s.lintCI) |
| 229 | mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases) |
| 230 | mux.HandleFunc("GET /{owner}/{repo}/-/releases/{$}", s.releasesSlash) |
| 231 | mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset) |
| 232 | mux.HandleFunc("POST /{owner}/{repo}/-/releases/{tag}/assets/{name}/delete", s.uiDeleteReleaseAsset) |
| 233 | mux.HandleFunc("POST /{owner}/{repo}/-/releases/{tag}/delete", s.uiDeleteRelease) |
| 234 | mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo) |
| 235 | mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo) |
| 236 | mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar) |
| 237 | mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings) |
| 238 | mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo) |
| 239 | mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval) |
| 240 | mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember) |
| 241 | mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove) |
| 242 | mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected) |
| 243 | mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected) |
| 244 | mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags", s.addProtectedTag) |
| 245 | mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags/remove", s.removeProtectedTag) |
| 246 | mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret) |
| 247 | mux.HandleFunc("POST /{owner}/{repo}/-/secrets/reveal", s.repoSecretReveal) |
| 248 | mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete) |
| 249 | mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook) |
| 250 | mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete) |
| 251 | mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo) |
| 252 | |
| 253 | return s.realIP(s.withSession(s.secure(s.gate(mux)))) |
| 254 | } |
| 255 | |
| 256 | func (s *Server) realIP(next http.Handler) http.Handler { |
| 257 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 258 | realip.Apply(r, s.Cfg.ProxySet()) |
| 259 | next.ServeHTTP(w, r) |
| 260 | }) |
| 261 | } |
| 262 | |
| 263 | func (s *Server) mustTemplates() { |
| 264 | if s.byLang != nil { |
| 265 | return |
| 266 | } |
| 267 | s.byLang = map[string]*template.Template{} |
| 268 | for _, lang := range i18n.All() { |
| 269 | l := lang |
| 270 | s.byLang[string(l)] = template.Must(template.New("web").Funcs(template.FuncMap{ |
| 271 | "tip": func(key string) template.HTML { return runnercfg.Tip(l, key) }, |
| 272 | "admintabs": adminTabs, |
| 273 | "adminpage": isAdminPage, |
| 274 | "short": func(v string) string { |
| 275 | if len(v) > 10 { |
| 276 | return v[:10] |
| 277 | } |
| 278 | return v |
| 279 | }, |
| 280 | "join": strings.Join, |
| 281 | "initial": func(s string) string { |
| 282 | s = strings.TrimSpace(s) |
| 283 | if s == "" { |
| 284 | return "?" |
| 285 | } |
| 286 | r, _ := utf8.DecodeRuneInString(s) |
| 287 | return strings.ToUpper(string(r)) |
| 288 | }, |
| 289 | "tileHue": tileHue, |
| 290 | "splitPath": func(p string) []string { |
| 291 | if p == "" { |
| 292 | return nil |
| 293 | } |
| 294 | return strings.Split(p, "/") |
| 295 | }, |
| 296 | "iconOf": func(name string) string { return fileIcon(name, "blob") }, |
| 297 | "t": func(key string, args ...any) string { return i18n.T(l, key, args...) }, |
| 298 | "date": func(t time.Time) string { return i18n.FormatDate(l, t) }, |
| 299 | "tn": func(n int, one, many string) string { |
| 300 | key := many |
| 301 | if n == 1 { |
| 302 | key = one |
| 303 | } |
| 304 | return i18n.T(l, key, n) |
| 305 | }, |
| 306 | "roleName": func(r access.Role) string { return i18n.T(l, "role."+string(r)) }, |
| 307 | "visName": func(v string) string { return i18n.T(l, "vis."+v) }, |
| 308 | "presetName": func(id string) string { |
| 309 | label := i18n.T(l, "set.preset."+id) |
| 310 | if label == "set.preset."+id { |
| 311 | return id |
| 312 | } |
| 313 | return label |
| 314 | }, |
| 315 | "printf": fmt.Sprintf, |
| 316 | "dict": func(kv ...any) (map[string]any, error) { |
| 317 | if len(kv)%2 != 0 { |
| 318 | return nil, fmt.Errorf("dict") |
| 319 | } |
| 320 | m := make(map[string]any, len(kv)/2) |
| 321 | for i := 0; i < len(kv); i += 2 { |
| 322 | key, ok := kv[i].(string) |
| 323 | if !ok { |
| 324 | return nil, fmt.Errorf("dict") |
| 325 | } |
| 326 | m[key] = kv[i+1] |
| 327 | } |
| 328 | return m, nil |
| 329 | }, |
| 330 | }).ParseFS(webFS, "templates/*.html")) |
| 331 | } |
| 332 | s.tmpl = s.byLang[string(i18n.EN)] |
| 333 | } |
| 334 | |
| 335 | func (s *Server) asset(w http.ResponseWriter, r *http.Request) { |
| 336 | name := r.PathValue("file") |
| 337 | if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") { |
| 338 | http.NotFound(w, r) |
| 339 | return |
| 340 | } |
| 341 | sub, err := fs.Sub(webFS, "static") |
| 342 | if err != nil { |
| 343 | http.Error(w, "assets", http.StatusInternalServerError) |
| 344 | return |
| 345 | } |
| 346 | http.ServeFileFS(w, r, sub, name) |
| 347 | } |
| 348 | |
| 349 | func (s *Server) secure(next http.Handler) http.Handler { |
| 350 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 351 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 352 | w.Header().Set("X-Frame-Options", "DENY") |
| 353 | w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") |
| 354 | 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'") |
| 355 | next.ServeHTTP(w, r) |
| 356 | }) |
| 357 | } |
| 358 | |
| 359 | func (s *Server) withSession(next http.Handler) http.Handler { |
| 360 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 361 | p := principal{} |
| 362 | if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" { |
| 363 | sess, err := s.Store.Session(r.Context(), c.Value) |
| 364 | if err == nil && sess.ExpiresAt.After(time.Now()) { |
| 365 | p.Session = sess |
| 366 | p.User = sess.User |
| 367 | p.OK = true |
| 368 | s.maybeExtend(r.Context(), sess) |
| 369 | } |
| 370 | } |
| 371 | next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p))) |
| 372 | }) |
| 373 | } |
| 374 | |
| 375 | func (s *Server) maybeExtend(ctx context.Context, sess store.Session) { |
| 376 | if time.Until(sess.ExpiresAt) > 6*time.Hour { |
| 377 | return |
| 378 | } |
| 379 | sec, err := s.Auth.Extend(ctx, sess.AccessToken) |
| 380 | if err != nil || sec <= 0 { |
| 381 | return |
| 382 | } |
| 383 | _ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second)) |
| 384 | } |
| 385 | |
| 386 | func (s *Server) who(r *http.Request) principal { |
| 387 | p, _ := r.Context().Value(ctxKey{}).(principal) |
| 388 | return p |
| 389 | } |
| 390 | |
| 391 | func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool { |
| 392 | if err := r.ParseForm(); err != nil { |
| 393 | http.Error(w, s.tr(r, "err.badForm"), http.StatusBadRequest) |
| 394 | return false |
| 395 | } |
| 396 | p := s.who(r) |
| 397 | if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF { |
| 398 | http.Error(w, s.tr(r, "err.badCSRF"), http.StatusBadRequest) |
| 399 | return false |
| 400 | } |
| 401 | return true |
| 402 | } |
| 403 | |
| 404 | func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) { |
| 405 | p := s.who(r) |
| 406 | if !p.OK { |
| 407 | http.Redirect(w, r, "/login", http.StatusFound) |
| 408 | return store.User{}, false |
| 409 | } |
| 410 | return p.User, true |
| 411 | } |
| 412 | |
| 413 | func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) { |
| 414 | http.SetCookie(w, &http.Cookie{ |
| 415 | Name: "bluegit_session", |
| 416 | Value: id, |
| 417 | Path: "/", |
| 418 | HttpOnly: true, |
| 419 | SameSite: http.SameSiteLaxMode, |
| 420 | Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://"), |
| 421 | Expires: exp, |
| 422 | }) |
| 423 | } |
| 424 | |
| 425 | func (s *Server) flash(w http.ResponseWriter, notice, problem string) { |
| 426 | secure := strings.HasPrefix(s.Cfg.BaseURL, "https://") |
| 427 | if notice != "" { |
| 428 | http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: url.QueryEscape(notice), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode}) |
| 429 | } |
| 430 | if problem != "" { |
| 431 | http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: url.QueryEscape(problem), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode}) |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) { |
| 436 | notice, problem := flashVal(r, "bluegit_notice"), flashVal(r, "bluegit_error") |
| 437 | if notice != "" { |
| 438 | http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1}) |
| 439 | } |
| 440 | if problem != "" { |
| 441 | http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1}) |
| 442 | } |
| 443 | return notice, problem |
| 444 | } |
| 445 | |
| 446 | func cookieVal(r *http.Request, name string) string { |
| 447 | c, err := r.Cookie(name) |
| 448 | if err != nil { |
| 449 | return "" |
| 450 | } |
| 451 | return c.Value |
| 452 | } |
| 453 | |
| 454 | func flashVal(r *http.Request, name string) string { |
| 455 | raw := cookieVal(r, name) |
| 456 | if raw == "" { |
| 457 | return "" |
| 458 | } |
| 459 | v, err := url.QueryUnescape(raw) |
| 460 | if err != nil { |
| 461 | return raw |
| 462 | } |
| 463 | return v |
| 464 | } |
| 465 | |
| 466 | func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) { |
| 467 | s.flash(w, notice, problem) |
| 468 | http.Redirect(w, r, path, http.StatusSeeOther) |
| 469 | } |
| 470 | |
| 471 | func (s *Server) langOf(r *http.Request) i18n.Lang { |
| 472 | if p := s.who(r); p.OK { |
| 473 | return i18n.Parse(p.User.Language) |
| 474 | } |
| 475 | if c, err := r.Cookie("bluegit_lang"); err == nil { |
| 476 | return i18n.Parse(c.Value) |
| 477 | } |
| 478 | return i18n.EN |
| 479 | } |
| 480 | |
| 481 | // switchLang is de taalkiezer in de kopbalk: ingelogd slaat hij de taal op |
| 482 | // het account op, anoniem in een cookie. back is altijd een lokaal pad. |
| 483 | func (s *Server) switchLang(w http.ResponseWriter, r *http.Request) { |
| 484 | lang := i18n.Parse(r.FormValue("lang")) |
| 485 | back := langpick.SafeBack(r.FormValue("back")) |
| 486 | if p := s.who(r); p.OK { |
| 487 | if !s.csrfOK(w, r) { |
| 488 | return |
| 489 | } |
| 490 | if _, err := s.opSetLanguage(r.Context(), p.User, string(lang)); err != nil { |
| 491 | s.redirect(w, r, back, "", s.trErr(r, err)) |
| 492 | return |
| 493 | } |
| 494 | } else { |
| 495 | http.SetCookie(w, &http.Cookie{Name: "bluegit_lang", Value: string(lang), Path: "/", MaxAge: 365 * 86400, HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://")}) |
| 496 | } |
| 497 | http.Redirect(w, r, back, http.StatusSeeOther) |
| 498 | } |
| 499 | |
| 500 | func (s *Server) tr(r *http.Request, key string, args ...any) string { |
| 501 | return i18n.T(s.langOf(r), key, args...) |
| 502 | } |
| 503 | |
| 504 | func (s *Server) trErr(r *http.Request, err error) string { |
| 505 | return i18n.Text(s.langOf(r), err) |
| 506 | } |
| 507 | |
| 508 | func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View { |
| 509 | notice, problem := s.takeFlash(w, r) |
| 510 | lang := s.langOf(r) |
| 511 | if strings.HasPrefix(title, "title.") { |
| 512 | title = i18n.T(lang, title) |
| 513 | } |
| 514 | name := strings.TrimSpace(s.Cfg.Runner.Name) |
| 515 | if name == "" { |
| 516 | name = "Steve" |
| 517 | } |
| 518 | v := View{ |
| 519 | Title: title, BaseURL: s.Cfg.BaseURL, RunnerName: name, Notice: notice, Err: problem, |
| 520 | StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang), |
| 521 | Cunei: lang == i18n.Cuneiform, |
| 522 | } |
| 523 | for _, l := range i18n.All() { |
| 524 | v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()}) |
| 525 | } |
| 526 | if p := s.who(r); p.OK && !isCrawler(r) { |
| 527 | u := p.User |
| 528 | v.User = &u |
| 529 | v.CSRF = p.Session.CSRF |
| 530 | } |
| 531 | back := r.URL.Path |
| 532 | if r.URL.RawQuery != "" { |
| 533 | back += "?" + r.URL.RawQuery |
| 534 | } |
| 535 | csrfField := "" |
| 536 | if v.User != nil { |
| 537 | csrfField = "csrf" |
| 538 | } |
| 539 | v.LangPick = langpick.HTML(lang, "/-/lang", back, csrfField, v.CSRF) |
| 540 | pic := s.cardForPath(r.Context(), r.URL.Path, r.URL.RawQuery, r.URL.Fragment) |
| 541 | v.Social = &pic.Meta |
| 542 | return v |
| 543 | } |
| 544 | |
| 545 | func htmlLang(l i18n.Lang) string { |
| 546 | switch l { |
| 547 | case i18n.NL: |
| 548 | return "nl" |
| 549 | case i18n.DE: |
| 550 | return "de" |
| 551 | case i18n.FR: |
| 552 | return "fr" |
| 553 | default: |
| 554 | return "en" |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | func (s *Server) render(w http.ResponseWriter, name string, v View) { |
| 559 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 560 | tmpl := s.byLang[v.Lang] |
| 561 | if tmpl == nil { |
| 562 | tmpl = s.tmpl |
| 563 | } |
| 564 | if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil { |
| 565 | s.Log.Error("sjabloon", "name", name, "err", err) |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | func randomState() (string, error) { |
| 570 | b := make([]byte, 32) |
| 571 | if _, err := rand.Read(b); err != nil { |
| 572 | return "", err |
| 573 | } |
| 574 | return hex.EncodeToString(b), nil |
| 575 | } |
| 576 | |
| 577 | // View is de gegevensset voor elk scherm. |
| 578 | type View struct { |
| 579 | RunnerList []RunnerView |
| 580 | RunnerPref string |
| 581 | NewRunnerToken string |
| 582 | BuiltinFirst bool |
| 583 | RunnerOptIn bool |
| 584 | OptInNames []string |
| 585 | Title string |
| 586 | BaseURL string |
| 587 | RunnerName string |
| 588 | User *store.User |
| 589 | CSRF string |
| 590 | Notice string |
| 591 | Err string |
| 592 | Repos []store.Repo |
| 593 | Groups []store.Group |
| 594 | Repo *store.Repo |
| 595 | Role access.Role |
| 596 | CanWrite bool |
| 597 | CanAdmin bool |
| 598 | CanMerge bool |
| 599 | CanForce bool |
| 600 | CanComment bool |
| 601 | CanApply bool |
| 602 | Commits []CommitRow |
| 603 | CommitDays []CommitDay |
| 604 | CommitPrev string |
| 605 | CommitNext string |
| 606 | Commit *CommitRow |
| 607 | CommitDiff *CommitDiff |
| 608 | Entries []EntryRow |
| 609 | TreePath string |
| 610 | Blob string |
| 611 | BlobPath string |
| 612 | Binary bool |
| 613 | Branches []BranchRow |
| 614 | Branch *BranchBoard |
| 615 | MRs []store.MergeRequest |
| 616 | Flow *FlowBoard |
| 617 | MR *store.MergeRequest |
| 618 | Banner *MRBanner |
| 619 | MRPipe *PipeRow |
| 620 | MergeBlocks []string |
| 621 | Approval *ApprovalView |
| 622 | Reviews []ReviewRow |
| 623 | CanReview bool |
| 624 | CanApprove bool |
| 625 | CanDismiss bool |
| 626 | CanClose bool |
| 627 | CanReopen bool |
| 628 | IsOwner bool |
| 629 | Candidates []store.Member |
| 630 | Diff string |
| 631 | DiffFiles []DiffFileView |
| 632 | Pipes []store.Pipeline |
| 633 | PipeRows []PipeRow |
| 634 | Pipe *store.Pipeline |
| 635 | PipeSource string |
| 636 | PipeStatus string |
| 637 | PipeLabel string |
| 638 | PipeJobs []JobLink |
| 639 | PipeStages []StageView |
| 640 | PipeFailed bool |
| 641 | Live bool |
| 642 | LiveURL string |
| 643 | Jobs []store.Job |
| 644 | JobPage *JobPage |
| 645 | Editor *CIEditor |
| 646 | Releases []store.Release |
| 647 | Members []store.Member |
| 648 | Secrets []store.SecretMeta |
| 649 | HookSecrets []SecretChoice |
| 650 | Hooks []HookView |
| 651 | HookEdit HookDraft |
| 652 | Patterns []string |
| 653 | TagPatterns []string |
| 654 | Tags []TagRow |
| 655 | Tokens []store.TokenInfo |
| 656 | ShowExpiry bool |
| 657 | Keys []store.SSHKey |
| 658 | CloneHTTP string |
| 659 | CloneSSH string |
| 660 | Group *store.Group |
| 661 | Tab string |
| 662 | Rev string |
| 663 | NewToken string |
| 664 | StorageUnset bool |
| 665 | StoragePath string |
| 666 | StorageFree string |
| 667 | StorageUsed string |
| 668 | StorageTotal string |
| 669 | StoragePercent int |
| 670 | StorageBlueGit string |
| 671 | StoragePartial bool |
| 672 | Cache map[string]any |
| 673 | StorageReserved string |
| 674 | HasReserved bool |
| 675 | MinFree string |
| 676 | Wide bool |
| 677 | Info bool |
| 678 | Help bool |
| 679 | HelpDocs []HelpDoc |
| 680 | HelpDoc *HelpDoc |
| 681 | RunnerUI template.HTML |
| 682 | AdminUsers []AdminUserRow |
| 683 | ReleaseOnly bool |
| 684 | ShowReleases bool |
| 685 | ReleaseRepos []store.Repo |
| 686 | LangPick template.HTML |
| 687 | ShowUpdate bool |
| 688 | Update *UpdateView |
| 689 | HookDoc string |
| 690 | Spec cispec.Doc |
| 691 | SpecJSON template.JS |
| 692 | APIJSON template.JS |
| 693 | Page string |
| 694 | Lang string |
| 695 | HTMLLang string |
| 696 | Cunei bool |
| 697 | Langs []LangChoice |
| 698 | Query string |
| 699 | SortDir string |
| 700 | FlipDir string |
| 701 | Cards []RepoCard |
| 702 | Head *CommitRow |
| 703 | Files []FileRow |
| 704 | Tree []FileRow |
| 705 | Readme template.HTML |
| 706 | ReadmeName string |
| 707 | LicensePath string |
| 708 | NCommits int |
| 709 | NBranches int |
| 710 | NTags int |
| 711 | NReleases int |
| 712 | Created string |
| 713 | Lines []CodeLine |
| 714 | BlobSize string |
| 715 | IsSVG bool |
| 716 | IsImage bool // rasterafbeelding met kloppende magic bytes |
| 717 | FileName string |
| 718 | RevProtected bool |
| 719 | Heat *activity.Calendar |
| 720 | Notes []NoteRow |
| 721 | Profile *store.User |
| 722 | Card *ProfileCard |
| 723 | DescHTML template.HTML |
| 724 | Timeline []TimelineItem |
| 725 | CompareFrom string |
| 726 | CompareTo string |
| 727 | FormTitle string |
| 728 | Labels []string |
| 729 | CanEditMR bool |
| 730 | Issues *IssueBoard |
| 731 | IssueDoc string |
| 732 | DescTpls []string |
| 733 | TplPick string |
| 734 | FormBody string |
| 735 | Social *card.Meta |
| 736 | } |
| 737 | |
| 738 | // LangChoice is één taal in de instellingen. |
| 739 | type LangChoice struct { |
| 740 | Code, Label string |
| 741 | } |
| 742 | |
| 743 | // RepoCard is een repository in een groepslijst. |
| 744 | type RepoCard struct { |
| 745 | Repo store.Repo |
| 746 | Stars int |
| 747 | Starred bool |
| 748 | When string |
| 749 | } |
| 750 | |
| 751 | // AccountLink is een naam die naar een profiel wijst. |
| 752 | type AccountLink struct { |
| 753 | Name string |
| 754 | URL string |
| 755 | } |
| 756 | |
| 757 | // ProfileCard is het blok over een gebruiker, boven de activiteitenkalender. |
| 758 | type ProfileCard struct { |
| 759 | User store.User |
| 760 | Name, Since, Bio, URL string |
| 761 | Heading string |
| 762 | Repos, Groups, Contrib int |
| 763 | Own bool |
| 764 | } |
| 765 | |
| 766 | // NoteRow is een reactie in de interface. |
| 767 | type NoteRow struct { |
| 768 | ID int64 |
| 769 | Author, AuthorURL, Body, When, Path string |
| 770 | Start, End int |
| 771 | HasSuggestion bool |
| 772 | ParentID int64 |
| 773 | HTML template.HTML |
| 774 | Replies []NoteRow |
| 775 | At time.Time |
| 776 | } |
| 777 | |
| 778 | // DiffFileView is één bestand in de merge-request-diff. |
| 779 | type DiffFileView struct { |
| 780 | Path string |
| 781 | Lines []DiffLineView |
| 782 | } |
| 783 | |
| 784 | // DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen. |
| 785 | type DiffLineView struct { |
| 786 | Kind string |
| 787 | Text string |
| 788 | Old int |
| 789 | New int |
| 790 | Notes []NoteRow |
| 791 | } |
| 792 | |
| 793 | // TagRow is één tag op de tagspagina. |
| 794 | type TagRow struct { |
| 795 | Name, Message, SHA, Short, Subject, Date, When string |
| 796 | Annotated, Protected, HasRelease, CanDelete bool |
| 797 | ZipURL, TarURL string |
| 798 | } |
| 799 | |
| 800 | // FileRow is een rij in de bestandstabel of de boom. |
| 801 | type FileRow struct { |
| 802 | Name, Path, Icon, Subject, When, SHA string |
| 803 | Dir bool |
| 804 | Depth int |
| 805 | Active bool |
| 806 | // Open geldt voor een map die het huidige pad bevat. De browser |
| 807 | // onthoudt afwijkingen daarvan per repository. |
| 808 | Open bool |
| 809 | } |
| 810 | |
| 811 | // CodeLine is één regel broncode. |
| 812 | type CodeLine struct { |
| 813 | N int |
| 814 | HTML template.HTML |
| 815 | } |
| 816 | |
| 817 | // CommitRow is een commit in de interface. |
| 818 | // Author is de gekoppelde gebruiker, of anders de ruwe git-naam. |
| 819 | // RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt. |
| 820 | type CommitRow struct { |
| 821 | SHA, Short, Author, Who, Date, Subject, Body, When string |
| 822 | UserURL, WhoURL, Avatar, Initial, RawName, PushedBy string |
| 823 | Ident template.HTML |
| 824 | PipeID int64 |
| 825 | PipeStatus, PipeLabel, PipeDuration string |
| 826 | PipeStages []StageView |
| 827 | PipeLive, PipeFailed bool |
| 828 | } |
| 829 | |
| 830 | // CommitDay is één dag op de commitlijst, nieuwste dag eerst. |
| 831 | type CommitDay struct { |
| 832 | Label string |
| 833 | Items []CommitRow |
| 834 | } |
| 835 | |
| 836 | // EntryRow is een bestand of map. |
| 837 | type EntryRow struct { |
| 838 | Name, Type, Path string |
| 839 | } |
| 840 | |
| 841 | // BranchRow is een branch, met of zonder bescherming. |
| 842 | type BranchRow struct { |
| 843 | Name, SHA, Short, Subject, When, WhenTitle string |
| 844 | RepoPath, ZipURL, TarURL string |
| 845 | Protected, Default, CanEdit bool |
| 846 | Target string |
| 847 | Ahead, Behind int |
| 848 | Unix int64 |
| 849 | PipeID int64 |
| 850 | PipeStatus, PipeLabel string |
| 851 | OpenMRs []int64 |
| 852 | } |
| 853 | |
| 854 | // BranchBoard is de gegroepeerde branches-pagina. |
| 855 | type BranchBoard struct { |
| 856 | State string |
| 857 | ShowActive, ShowStale bool |
| 858 | Active, Stale []BranchRow |
| 859 | } |
| 860 | |
| 861 | // TimelineItem is één gebeurtenis of reactie op een merge request. |
| 862 | type TimelineItem struct { |
| 863 | ID int64 |
| 864 | Kind string |
| 865 | Actor, ActorURL, Text string |
| 866 | When string |
| 867 | Body string |
| 868 | HTML template.HTML |
| 869 | URL string |
| 870 | Replies []TimelineItem |
| 871 | At time.Time |
| 872 | Rank int |
| 873 | } |
| 874 | |
| 875 | // HookView is een webhook plus de laatste pogingen. |
| 876 | type HookView struct { |
| 877 | ID int64 |
| 878 | Name string |
| 879 | Preset string |
| 880 | URL string |
| 881 | Method string |
| 882 | Filter string |
| 883 | Events string |
| 884 | Badges []string |
| 885 | Deliveries []store.Delivery |
| 886 | } |
| 887 | |
| 888 | // HookDraft vult het webhookformulier bij bewerken. ID 0 is een nieuw formulier. |
| 889 | type HookDraft struct { |
| 890 | ID int64 |
| 891 | Name string |
| 892 | Preset string |
| 893 | Filter string |
| 894 | URL string |
| 895 | Username string |
| 896 | Avatar string |
| 897 | Icon string |
| 898 | Alias string |
| 899 | Token string |
| 900 | Chat string |
| 901 | Server string |
| 902 | Topic string |
| 903 | Home string |
| 904 | Room string |
| 905 | Method string |
| 906 | CType string |
| 907 | Headers string |
| 908 | Body string |
| 909 | OnPush bool |
| 910 | OnMR bool |
| 911 | OnOK bool |
| 912 | OnFail bool |
| 913 | OnRel bool |
| 914 | OnIssue bool |
| 915 | Extra []HookEventChoice |
| 916 | } |
| 917 | |
| 918 | // HookEventChoice is een fijner event als vinkje in het webhookformulier. |
| 919 | type HookEventChoice struct { |
| 920 | Name string |
| 921 | Key string |
| 922 | On bool |
| 923 | } |
| 924 | |
| 925 | func repoURL(repo store.Repo) string { return "/" + repo.FullPath() } |