1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3// Package web is the HTML front of ermite: the pages of the read-only
4// showcase, rendered with templ from the data of the use cases.
5//
6// Like every other inbound adapter, the package reads and writes through the
7// use case interfaces of package ports (ADR 0024), never through the API. The
8// caller of every use case call is passed explicitly: the principal of the
9// request, which is anonymous unless the request carries a valid owner session
10// (ServeHTTP sets it in the context, principal reads it). The use cases then
11// show public repositories only to an anonymous caller; a private repository
12// is indistinguishable from a missing one (domain.ErrNotFound), here as
13// everywhere.
14//
15// Adding a page: a handler on Server, a route in routes, a templ page in
16// pages.templ and its view model in view.go.
17package web
18
19import (
20 "bytes"
21 "context"
22 "crypto/rand"
23 "encoding/hex"
24 "errors"
25 "fmt"
26 "net/http"
27 "net/netip"
28 "net/url"
29 "strings"
30 "time"
31
32 "github.com/a-h/templ"
33 "github.com/bnema/zerowrap"
34
35 "bnema.dev/ermite/internal/domain"
36 "bnema.dev/ermite/internal/ports"
37)
38
39// Patterns are the ServeMux patterns the handler serves: everything. The
40// router of the package answers the paths it does not know with its 404
41// page, and the more specific patterns of the server (health, API, Git) win
42// over this one.
43var Patterns = []string{"/"}
44
45// requestTimeout bounds the use case calls that build one page.
46const requestTimeout = 30 * time.Second
47
48// Config configures a Server.
49type Config struct {
50 // Repos and Browse are the use cases the pages are built from.
51 Repos ports.RepoService
52 Browse ports.BrowseService
53 // MergeRequests serves the merge request pages (ADR 0017). Without it
54 // there are no such pages, nor section for them. Leave it unset rather
55 // than assigning a typed nil pointer.
56 MergeRequests ports.MergeRequestService
57 // Issues serves the issue pages (ADR 0031). Without it there are no such
58 // pages, nor tab for them. Leave it unset rather than assigning a typed
59 // nil pointer.
60 Issues ports.IssueService
61 // IssueNumbers tells whether a number names an issue or a merge request,
62 // so that the page of the wrong kind redirects to the right one. Without
63 // it there is no such redirect. Leave it unset rather than assigning a
64 // typed nil pointer.
65 IssueNumbers ports.IssueNumberResolver
66 // IssueForm serves the public issue form of repositories whose issues
67 // mode is public (GET and POST /<repo>/issues/new for a visitor). Without
68 // it there is no such form. Leave it unset rather than assigning a typed
69 // nil pointer.
70 IssueForm ports.IssueSubmissionService
71 // Moderation serves the Approve, Reject and Reject-and-ban buttons of the
72 // pending issues in the inbox. It needs Inbox. Without it there are no
73 // such routes. Leave it unset rather than assigning a typed nil pointer.
74 Moderation ports.IssueModerationService
75 // Inbox serves the owner's inbox page (/-/inbox) and the button that
76 // leads to it. Without it there is neither. Leave it unset rather than
77 // assigning a typed nil pointer.
78 Inbox ports.InboxService
79 // SigningKey tells the key that signs the squash and merge commits, shown
80 // in the merge box. Without it the box does not name the key. Leave it
81 // unset rather than assigning a typed nil pointer.
82 SigningKey ports.SigningKeyService
83 // Runs serves the CI pages (/<repo>/actions) and the checks shown next to
84 // commits and merge requests. Without it there are no such pages. Leave it
85 // unset rather than assigning a typed nil pointer.
86 Runs ports.RunService
87 // Artifacts serves the artifacts of the runs: a section of the run page,
88 // their download and their deletion. It needs Runs. Without it there is
89 // neither. Leave it unset rather than assigning a typed nil pointer.
90 Artifacts ports.ArtifactService
91 // Events is the source of the event stream behind /-/events. Without
92 // it the pages are not live and the route answers 404. Leave it unset
93 // rather than assigning a typed nil pointer.
94 Events ports.EventService
95 // Heartbeat is how often an idle event stream gets a comment line;
96 // DefaultHeartbeat when zero.
97 Heartbeat time.Duration
98 // Owner is the owner login the GitHub-shaped URLs of CI show
99 // (<server>/<owner>/<repo>/...). A GET or HEAD of /<owner>/<rest> is
100 // redirected to /<rest> unless a repository named like the owner is
101 // visible to the caller. Empty: no redirect.
102 Owner string
103 // PublicURL is the base URL of the instance, without a trailing slash:
104 // the clone URLs are built on it, and its host is the instance name.
105 PublicURL string
106 // SourceURL is the link to the source of the running version (AGPL §13).
107 SourceURL string
108 // Version is the version of the running server.
109 Version string
110 // Now is the clock of relative dates; time.Now when nil.
111 Now func() time.Time
112 // Sessions signs the owner in (ADR 0018). Without it there are no login
113 // routes and every visitor is anonymous.
114 Sessions ports.WebSessionService
115 // Passkeys signs the owner in with a passkey and manages the passkeys
116 // (ADR 0026). Without it, or without Sessions, there are no passkey
117 // routes and no link to them. Leave it unset rather than assigning a typed
118 // nil pointer.
119 Passkeys ports.WebPasskeyService
120 // Limiter counts the failed logins; required with Sessions. Share it with
121 // the API and Git, so that a client has one budget of failures.
122 Limiter ports.FailureLimiter
123 // TrustedProxies are the networks allowed to set X-Forwarded-For, to find
124 // the address of the client that fails a login.
125 TrustedProxies []netip.Prefix
126}
127
128// Server serves the pages. It is an http.Handler.
129type Server struct {
130 cfg Config
131 instance string
132 origin string // scheme://host of the public URL, what a POST must come from
133 assets *assetSet
134 md *markdown
135 // pathCache holds the path lists the file finder fetches.
136 pathCache *pathCache
137 // hl holds the colours of highlighted diffs.
138 hl *hlCache
139 mux *http.ServeMux
140 // ownerRepo is the owner login as a repository name, zero when it is not
141 // a valid one (then no repository can be named like the owner).
142 ownerRepo domain.RepoName
143 // refsFan shares the fragments of the refs page between the watchers of
144 // a push; entries are few and short-lived.
145 refsFan fanout
146 // pulses holds the activity curves of the home rows.
147 pulses pulseCache
148}
149
150// New builds the web handler.
151func New(cfg Config) (*Server, error) {
152 if cfg.Repos == nil || cfg.Browse == nil {
153 return nil, errors.New("web: the repository and browse use cases are required")
154 }
155 u, err := url.Parse(cfg.PublicURL)
156 if err != nil || u.Host == "" {
157 return nil, fmt.Errorf("web: public URL %q is not a valid base URL", cfg.PublicURL)
158 }
159 if cfg.Now == nil {
160 cfg.Now = time.Now
161 }
162 assets, err := loadAssets()
163 if err != nil {
164 return nil, fmt.Errorf("web: load assets: %w", err)
165 }
166 if cfg.Sessions != nil && cfg.Limiter == nil {
167 return nil, errors.New("web: sessions need a failure limiter")
168 }
169 s := &Server{
170 cfg: cfg, instance: u.Host, assets: assets, md: newMarkdown(),
171 pathCache: newPathCache(pathCacheBytes, pathBuilds),
172 hl: newHLCache(hlCacheBytes),
173 origin: originOf(u),
174 }
175 s.ownerRepo, _ = domain.ParseRepoName(cfg.Owner)
176 s.mux = s.routes()
177 return s, nil
178}
179
180// routes is the router of the web. Any path that is not a page is the 404
181// page.
182func (s *Server) routes() *http.ServeMux {
183 mux := http.NewServeMux()
184 mux.HandleFunc("GET "+StaticPrefix, s.assets.serve)
185 mux.HandleFunc("GET /-/events", s.events)
186 mux.HandleFunc("GET "+ServiceWorkerPath, s.assets.sw.serve)
187 if s.cfg.Sessions != nil {
188 mux.HandleFunc("GET "+loginPrefix+"{nonce}", s.loginConfirm)
189 mux.HandleFunc("POST "+loginPrefix+"{nonce}", s.loginPost)
190 mux.HandleFunc("POST /-/logout", s.logout)
191 }
192 if s.passkeysOn() {
193 s.passkeyRoutes(mux)
194 }
195 if s.cfg.Inbox != nil {
196 mux.HandleFunc("GET "+inboxPath, s.page(s.inbox))
197 if s.cfg.Moderation != nil {
198 mux.HandleFunc("POST "+inboxPath+"/pending/{repo}/{id}/approve", s.mrAction(s.pendingApprove))
199 mux.HandleFunc("POST "+inboxPath+"/pending/{repo}/{id}/reject", s.mrAction(s.pendingReject(false)))
200 mux.HandleFunc("POST "+inboxPath+"/pending/{repo}/{id}/ban", s.mrAction(s.pendingReject(true)))
201 }
202 }
203 mux.HandleFunc("GET /{$}", s.page(s.home))
204 mux.HandleFunc("GET /{repo}", s.page(s.summary))
205 mux.HandleFunc("GET /{repo}/{$}", s.page(s.summary))
206 mux.HandleFunc("GET /{repo}/refs", s.page(s.refs))
207 mux.HandleFunc("GET /{repo}/commits", s.page(s.commits))
208 mux.HandleFunc("GET /{repo}/commits/{rest...}", s.page(s.commits))
209 mux.HandleFunc("GET /{repo}/commit/{sha}", s.page(s.commit))
210 mux.HandleFunc("GET /{repo}/tree", s.page(s.tree))
211 mux.HandleFunc("GET /{repo}/tree/{rest...}", s.page(s.tree))
212 mux.HandleFunc("GET /{repo}/blob/{rest...}", s.page(s.blob))
213 mux.HandleFunc("GET /{repo}/raw/{rest...}", s.raw)
214 mux.HandleFunc("GET /{repo}/paths/{sha}", s.paths)
215 mux.HandleFunc("GET /{repo}/context/{sha}", s.page(s.diffContext))
216 if s.cfg.MergeRequests != nil {
217 mux.HandleFunc("GET /{repo}/merge-requests", s.page(s.mrList))
218 mux.HandleFunc("GET /{repo}/merge-requests/{$}", s.page(s.mrList))
219 mux.HandleFunc("GET /{repo}/merge-requests/{n}", s.pageOrRedirect(s.mrShow, s.mrToIssue))
220 mux.HandleFunc("GET /{repo}/merge-requests/{n}/since", s.page(s.mrSince))
221 mux.HandleFunc("GET /{repo}/merge-requests/{n}/files", s.page(s.mrFiles))
222 mux.HandleFunc("GET /{repo}/compare/{rest...}", s.page(s.compare))
223 // The writes: POST only, behind the gate (ServeHTTP).
224 mux.HandleFunc("POST /{repo}/merge-requests", s.mrAction(s.mrCreate))
225 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments", s.mrAction(s.mrComment))
226 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments/{id}/resolve", s.mrAction(s.mrResolve))
227 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments/{id}/edit", s.mrAction(s.mrEditComment))
228 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments/{id}/delete", s.mrAction(s.mrDeleteComment))
229 mux.HandleFunc("POST /{repo}/merge-requests/{n}/merge", s.mrAction(s.mrMerge))
230 mux.HandleFunc("POST /{repo}/merge-requests/{n}/close", s.mrAction(s.mrClose))
231 mux.HandleFunc("POST /{repo}/merge-requests/{n}/ready", s.mrAction(s.mrReady))
232 mux.HandleFunc("POST /{repo}/merge-requests/{n}/read", s.mrAction(s.mrRead))
233 }
234 if s.cfg.Issues != nil {
235 mux.HandleFunc("GET /{repo}/issues", s.page(s.issueList))
236 mux.HandleFunc("GET /{repo}/issues/{$}", s.page(s.issueList))
237 mux.HandleFunc("GET /{repo}/issues/new", s.issueNewRoute)
238 mux.HandleFunc("GET /{repo}/issues/{n}", s.pageOrRedirect(s.issueShow, s.issueToMR))
239 // The writes: POST only, behind the gate (ServeHTTP).
240 mux.HandleFunc("POST /{repo}/issues", s.issueAction(s.issueCreate))
241 mux.HandleFunc("POST /{repo}/issues/{n}/comments", s.issueAction(s.issueComment))
242 mux.HandleFunc("POST /{repo}/issues/{n}/close", s.issueAction(s.issueClose))
243 mux.HandleFunc("POST /{repo}/issues/{n}/reopen", s.issueAction(s.issueReopen))
244 }
245 if s.cfg.IssueForm != nil {
246 mux.HandleFunc("GET /{repo}/issues/submitted", s.issueSubmittedPage)
247 mux.HandleFunc("POST /{repo}/issues/new", s.issueFormPost)
248 }
249 if s.cfg.Runs != nil {
250 mux.HandleFunc("GET /{repo}/actions", s.page(s.actions))
251 mux.HandleFunc("GET /{repo}/actions/{$}", s.page(s.actions))
252 mux.HandleFunc("GET /{repo}/actions/runs/{id}", s.page(s.run))
253 mux.HandleFunc("GET /{repo}/actions/runs/{id}/job/{job}", s.page(s.job))
254 mux.HandleFunc("GET /{repo}/actions/runs/{id}/job/{job}/raw", s.rawLog)
255 mux.HandleFunc("GET /{repo}/actions/runs/{id}/job/{job}/stream", s.logStream)
256 mux.HandleFunc("POST /{repo}/actions/runs/{id}/cancel", s.ciAction(s.runCancel))
257 mux.HandleFunc("POST /{repo}/actions/runs/{id}/rerun", s.ciAction(s.runRerun(false)))
258 mux.HandleFunc("POST /{repo}/actions/runs/{id}/rerun-failed", s.ciAction(s.runRerun(true)))
259 if s.cfg.Artifacts != nil {
260 mux.HandleFunc("GET /{repo}/actions/runs/{id}/artifacts/{artifact}", s.artifactDownload)
261 mux.HandleFunc("POST /{repo}/actions/runs/{id}/artifacts/{artifact}/delete", s.ciAction(s.artifactDelete))
262 }
263 }
264 mux.HandleFunc(catchAll, s.page(s.notFound))
265 return mux
266}
267
268// ServeHTTP implements http.Handler.
269func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
270 // Whatever the context carried, the caller is anonymous until a valid
271 // session says otherwise (withSession).
272 r = r.WithContext(domain.ContextWithPrincipal(r.Context(), domain.Anonymous()))
273 r = s.withSession(w, r)
274 if !s.gate(w, r) {
275 return
276 }
277 if to, ok := s.ownerRedirect(r); ok {
278 http.Redirect(w, r, to, http.StatusPermanentRedirect)
279 return
280 }
281 s.mux.ServeHTTP(w, r)
282}
283
284// catchAll is the pattern of the paths that are no page.
285const catchAll = "GET /{repo}/{rest...}"
286
287// ownerRedirect maps /<owner>/<repo>[.git][/rest] to /<repo>[.git][/rest]: the
288// URLs that the github context of CI shows (html_url, commit and compare
289// URLs, clone_url) have the owner of the instance in front, like GitHub's.
290//
291// The rule is by repository, not by route: when no repository named like the
292// owner is visible to the caller, every GET or HEAD of /<owner>/<rest> is
293// redirected, so /<owner>/actions reaches the repository named "actions". A
294// repository named like the owner keeps its own pages. A private one is seen
295// as missing by an anonymous caller (the use case answers ErrNotFound), so the
296// redirect is the same as for a name nobody has and tells nothing.
297//
298// The target is built from a segment that parses as a repository name, which
299// has no slash, backslash, percent sign or dot-dot: it can only be a path on
300// this origin, never a "//host" one.
301func (s *Server) ownerRedirect(r *http.Request) (string, bool) {
302 if s.cfg.Owner == "" || (r.Method != http.MethodGet && r.Method != http.MethodHead) {
303 return "", false
304 }
305 first, rest, ok := strings.Cut(strings.TrimPrefix(r.URL.EscapedPath(), "/"), "/")
306 if !ok || !domain.OwnerMatches(s.cfg.Owner, first) || rest == "" {
307 return "", false
308 }
309 repo, _, _ := strings.Cut(rest, "/")
310 if _, err := domain.ParseRepoPath(repo); err != nil {
311 return "", false
312 }
313 if s.ownerNamesARepo(r) {
314 return "", false
315 }
316 to := "/" + rest
317 if r.URL.RawQuery != "" {
318 to += "?" + r.URL.RawQuery
319 }
320 return to, true
321}
322
323// ownerNamesARepo tells whether the caller can see a repository named like
324// the owner. A lookup that fails otherwise counts as yes: the request is then
325// served as it was before, without a redirect.
326func (s *Server) ownerNamesARepo(r *http.Request) bool {
327 if s.ownerRepo.IsZero() {
328 return false // the owner login is not a repository name
329 }
330 ctx := r.Context()
331 _, err := s.cfg.Repos.Get(ctx, principal(ctx), s.ownerRepo)
332 switch {
333 case err == nil:
334 return true
335 case errors.Is(err, domain.ErrNotFound):
336 return false
337 }
338 log := zerowrap.FromCtx(ctx)
339 log.Debug().Err(err).Msg("owner redirect: the lookup of the repository named like the owner failed")
340 return true
341}
342
343// handler builds a page. It returns the component and its status, or an
344// error, which becomes the 404 or 500 page.
345type handler func(ctx context.Context, r *http.Request) (templ.Component, int, error)
346
347// page adapts a handler: it bounds the use case calls, renders the component into
348// a buffer (so that a failure never leaves half a page), and maps errors to
349// the state pages.
350func (s *Server) page(h handler) http.HandlerFunc {
351 return func(w http.ResponseWriter, r *http.Request) {
352 ctx, cancel := context.WithTimeout(r.Context(), requestTimeout)
353 defer cancel()
354 c, status, err := h(ctx, r)
355 if err != nil {
356 s.fail(ctx, w, r, err)
357 return
358 }
359 s.write(ctx, w, r, status, c)
360 }
361}
362
363// write renders c with the given status.
364func (s *Server) write(ctx context.Context, w http.ResponseWriter, r *http.Request, status int, c templ.Component) {
365 var buf bytes.Buffer
366 if err := c.Render(ctx, &buf); err != nil {
367 // The error page itself failed: a bare answer is all that is left.
368 log := zerowrap.FromCtx(ctx)
369 log.Error().Err(err).Str("path", logPath(r.URL.Path)).Msg("render page")
370 http.Error(w, "internal error", http.StatusInternalServerError)
371 return
372 }
373 h := w.Header()
374 h.Set("Content-Type", "text/html; charset=utf-8")
375 // Links on this origin are prefetched on hover, so a click shows the page
376 // at once. Every GET page is safe to load (nothing is marked read on GET).
377 h.Set("Speculation-Rules", `"`+s.assets.urls.Rules+`"`)
378 // Public pages: the browser and any proxy revalidate each time. A page
379 // rendered for the owner is private and never stored; a handler that set
380 // its own Cache-Control keeps it.
381 if h.Get("Cache-Control") == "" {
382 cacheHeaders(ctx, h, "no-cache", sessionCache)
383 }
384 body := buf.Bytes()
385 // Whether the body is sent gzipped follows from its size and the request
386 // alone, so that the tag is known before the compression is spent.
387 gz := len(body) >= minCompress && acceptsGzip(r.Header) &&
388 !noTransform(h) && h.Get("Content-Encoding") == ""
389 addVary(h, "Accept-Encoding")
390 readOnly := r.Method == http.MethodGet || r.Method == http.MethodHead
391 // A page that may be stored gets a validator: the browser then
392 // revalidates with If-None-Match and a page that did not change costs a
393 // 304. A no-store page (the owner's) is never revalidated.
394 if readOnly && status == http.StatusOK && h.Get("ETag") == "" && !hasCacheDirective(h, noStore) {
395 tag := pageETag(body, SignedIn(ctx), gz)
396 h.Set("ETag", tag)
397 if etagMatches(strings.Join(r.Header.Values("If-None-Match"), ","), tag) {
398 h.Del("Content-Type")
399 w.WriteHeader(http.StatusNotModified)
400 return
401 }
402 }
403 if gz {
404 if z, err := gzipPage(body); err == nil && len(z) < len(body) {
405 body = z
406 h.Set("Content-Encoding", "gzip")
407 }
408 }
409 h.Set("Content-Length", itoa(len(body)))
410 w.WriteHeader(status)
411 if r.Method != http.MethodHead {
412 _, _ = w.Write(body)
413 }
414}
415
416// fail answers an error of a use case: not found (and a name or revision the
417// use case refuses, which no page can show either) gives the 404 page, a
418// visitor that left gives nothing, anything else gives the 500 page with an id
419// to find the cause in the log.
420func (s *Server) fail(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
421 switch {
422 case errors.Is(err, domain.ErrNotFound), domain.IsInvalid(err):
423 s.write(ctx, w, r, http.StatusNotFound, s.notFoundPage())
424 case errors.Is(err, context.Canceled):
425 // The client is gone; there is nobody to answer.
426 default:
427 id := requestID()
428 log := zerowrap.FromCtx(ctx)
429 log.Error().Err(err).Str("request_id", id).Str("path", logPath(r.URL.Path)).Msg("web request failed")
430 s.write(ctx, w, r, http.StatusInternalServerError, s.errorPage(id))
431 }
432}
433
434// errNotFound is returned by handlers for a resource that does not exist
435// although the use case did not say so (a ref or a path that is not there).
436var errNotFound = domain.ErrNotFound
437
438// requestID is a short random id, shown on the 500 page and logged.
439func requestID() string {
440 var b [4]byte
441 _, _ = rand.Read(b[:])
442 return hex.EncodeToString(b[:])
443}
444
445// notFound is the handler of the paths without a page.
446func (s *Server) notFound(context.Context, *http.Request) (templ.Component, int, error) {
447 return nil, 0, errNotFound
448}
449
450// base is the Layout every page starts from.
451func (s *Server) base() Layout {
452 return Layout{
453 Owner: s.cfg.Owner,
454 Version: s.cfg.Version,
455 SourceURL: s.cfg.SourceURL,
456 Assets: s.assets.urls,
457 Passkeys: s.passkeysOn(),
458 }
459}
460
461// stateLayout is the layout of a state page: only the way home.
462func (s *Server) stateLayout(title string, crumbs []Crumb) Layout {
463 l := s.base()
464 l.Title = title + " · " + s.instance
465 l.Crumbs = crumbs
466 l.Cmd = []CmdItem{{Kind: "go", Label: "home", Href: "/"}}
467 return l
468}
469
470func (s *Server) notFoundPage() templ.Component {
471 l := s.stateLayout("404", []Crumb{{Label: "not found", Current: true}})
472 return State(l, StatePage{
473 Code: "404", Title: "not found",
474 Lines: []string{"no such page, ref or path.", "check the URL, or start from the repo list."},
475 Back: []Link{{Label: "home", Href: "/"}},
476 })
477}
478
479func (s *Server) errorPage(id string) templ.Component {
480 l := s.stateLayout("error", []Crumb{{Label: "error", Current: true}})
481 return State(l, StatePage{
482 Code: "500", Title: "internal error",
483 Lines: []string{
484 "the server failed to answer this request.",
485 "request id: " + id,
486 "retry in a moment; if it persists, the owner has the log.",
487 },
488 Back: []Link{{Label: "home", Href: "/"}},
489 })
490}
491
492// originOf is the origin of a URL as a browser writes it in the Origin
493// header: scheme and host in lower case, the port only when it is not the
494// default of the scheme.
495func originOf(u *url.URL) string {
496 scheme, host, port := strings.ToLower(u.Scheme), strings.ToLower(u.Hostname()), u.Port()
497 if strings.Contains(host, ":") {
498 host = "[" + host + "]"
499 }
500 defaultPort := (scheme == "http" && port == "80") || (scheme == "https" && port == "443")
501 if port != "" && !defaultPort {
502 host += ":" + port
503 }
504 return scheme + "://" + host
505}