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 // Runs serves the CI pages (/<repo>/actions) and the checks shown next to
58 // commits and merge requests. Without it there are no such pages. Leave it
59 // unset rather than assigning a typed nil pointer.
60 Runs ports.RunService
61 // Events is the source of the event stream behind /-/events. Without
62 // it the pages are not live and the route answers 404. Leave it unset
63 // rather than assigning a typed nil pointer.
64 Events ports.EventService
65 // Heartbeat is how often an idle event stream gets a comment line;
66 // DefaultHeartbeat when zero.
67 Heartbeat time.Duration
68 // Owner is the owner login the GitHub-shaped URLs of CI show
69 // (<server>/<owner>/<repo>/...). A GET or HEAD of /<owner>/<rest> is
70 // redirected to /<rest> unless a repository named like the owner is
71 // visible to the caller. Empty: no redirect.
72 Owner string
73 // PublicURL is the base URL of the instance, without a trailing slash:
74 // the clone URLs are built on it, and its host is the instance name.
75 PublicURL string
76 // SourceURL is the link to the source of the running version (AGPL §13).
77 SourceURL string
78 // Version is the version of the running server.
79 Version string
80 // Now is the clock of relative dates; time.Now when nil.
81 Now func() time.Time
82 // Sessions signs the owner in (ADR 0018). Without it there are no login
83 // routes and every visitor is anonymous.
84 Sessions ports.WebSessionService
85 // Passkeys signs the owner in with a passkey and manages the passkeys
86 // (ADR 0026). Without it, or without Sessions, there are no passkey
87 // routes and no link to them. Leave it unset rather than assigning a typed
88 // nil pointer.
89 Passkeys ports.WebPasskeyService
90 // Limiter counts the failed logins; required with Sessions. Share it with
91 // the API and Git, so that a client has one budget of failures.
92 Limiter ports.FailureLimiter
93 // TrustedProxies are the networks allowed to set X-Forwarded-For, to find
94 // the address of the client that fails a login.
95 TrustedProxies []netip.Prefix
96}
97
98// Server serves the pages. It is an http.Handler.
99type Server struct {
100 cfg Config
101 instance string
102 origin string // scheme://host of the public URL, what a POST must come from
103 assets *assetSet
104 md *markdown
105 // pathCache holds the path lists the file finder fetches.
106 pathCache *pathCache
107 mux *http.ServeMux
108 // ownerRepo is the owner login as a repository name, zero when it is not
109 // a valid one (then no repository can be named like the owner).
110 ownerRepo domain.RepoName
111 // refsFan shares the fragments of the refs page between the watchers of
112 // a push; entries are few and short-lived.
113 refsFan fanout
114}
115
116// New builds the web handler.
117func New(cfg Config) (*Server, error) {
118 if cfg.Repos == nil || cfg.Browse == nil {
119 return nil, errors.New("web: the repository and browse use cases are required")
120 }
121 u, err := url.Parse(cfg.PublicURL)
122 if err != nil || u.Host == "" {
123 return nil, fmt.Errorf("web: public URL %q is not a valid base URL", cfg.PublicURL)
124 }
125 if cfg.Now == nil {
126 cfg.Now = time.Now
127 }
128 assets, err := loadAssets()
129 if err != nil {
130 return nil, fmt.Errorf("web: load assets: %w", err)
131 }
132 if cfg.Sessions != nil && cfg.Limiter == nil {
133 return nil, errors.New("web: sessions need a failure limiter")
134 }
135 s := &Server{
136 cfg: cfg, instance: u.Host, assets: assets, md: newMarkdown(),
137 pathCache: newPathCache(pathCacheBytes, pathBuilds),
138 origin: originOf(u),
139 }
140 s.ownerRepo, _ = domain.ParseRepoName(cfg.Owner)
141 s.mux = s.routes()
142 return s, nil
143}
144
145// routes is the router of the web. Any path that is not a page is the 404
146// page.
147func (s *Server) routes() *http.ServeMux {
148 mux := http.NewServeMux()
149 mux.HandleFunc("GET "+StaticPrefix, s.assets.serve)
150 mux.HandleFunc("GET /-/events", s.events)
151 if s.cfg.Sessions != nil {
152 mux.HandleFunc("GET "+loginPrefix+"{nonce}", s.loginConfirm)
153 mux.HandleFunc("POST "+loginPrefix+"{nonce}", s.loginPost)
154 mux.HandleFunc("POST /-/logout", s.logout)
155 }
156 if s.passkeysOn() {
157 s.passkeyRoutes(mux)
158 }
159 mux.HandleFunc("GET /{$}", s.page(s.home))
160 mux.HandleFunc("GET /{repo}", s.page(s.summary))
161 mux.HandleFunc("GET /{repo}/{$}", s.page(s.summary))
162 mux.HandleFunc("GET /{repo}/refs", s.page(s.refs))
163 mux.HandleFunc("GET /{repo}/commits", s.page(s.commits))
164 mux.HandleFunc("GET /{repo}/commits/{rest...}", s.page(s.commits))
165 mux.HandleFunc("GET /{repo}/commit/{sha}", s.page(s.commit))
166 mux.HandleFunc("GET /{repo}/tree", s.page(s.tree))
167 mux.HandleFunc("GET /{repo}/tree/{rest...}", s.page(s.tree))
168 mux.HandleFunc("GET /{repo}/blob/{rest...}", s.page(s.blob))
169 mux.HandleFunc("GET /{repo}/raw/{rest...}", s.raw)
170 mux.HandleFunc("GET /{repo}/paths/{sha}", s.paths)
171 if s.cfg.MergeRequests != nil {
172 mux.HandleFunc("GET /{repo}/merge-requests", s.page(s.mrList))
173 mux.HandleFunc("GET /{repo}/merge-requests/{$}", s.page(s.mrList))
174 mux.HandleFunc("GET /{repo}/merge-requests/{n}", s.page(s.mrShow))
175 mux.HandleFunc("GET /{repo}/merge-requests/{n}/since", s.page(s.mrSince))
176 mux.HandleFunc("GET /{repo}/compare/{rest...}", s.page(s.compare))
177 // The writes: POST only, behind the gate (ServeHTTP).
178 mux.HandleFunc("POST /{repo}/merge-requests", s.mrAction(s.mrCreate))
179 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments", s.mrAction(s.mrComment))
180 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments/{id}/resolve", s.mrAction(s.mrResolve))
181 mux.HandleFunc("POST /{repo}/merge-requests/{n}/merge", s.mrAction(s.mrMerge))
182 mux.HandleFunc("POST /{repo}/merge-requests/{n}/close", s.mrAction(s.mrClose))
183 mux.HandleFunc("POST /{repo}/merge-requests/{n}/read", s.mrAction(s.mrRead))
184 }
185 if s.cfg.Runs != nil {
186 mux.HandleFunc("GET /{repo}/actions", s.page(s.actions))
187 mux.HandleFunc("GET /{repo}/actions/{$}", s.page(s.actions))
188 mux.HandleFunc("GET /{repo}/actions/runs/{id}", s.page(s.run))
189 mux.HandleFunc("GET /{repo}/actions/runs/{id}/job/{job}", s.page(s.job))
190 mux.HandleFunc("GET /{repo}/actions/runs/{id}/job/{job}/raw", s.rawLog)
191 mux.HandleFunc("GET /{repo}/actions/runs/{id}/job/{job}/stream", s.logStream)
192 mux.HandleFunc("POST /{repo}/actions/runs/{id}/cancel", s.ciAction(s.runCancel))
193 mux.HandleFunc("POST /{repo}/actions/runs/{id}/rerun", s.ciAction(s.runRerun(false)))
194 mux.HandleFunc("POST /{repo}/actions/runs/{id}/rerun-failed", s.ciAction(s.runRerun(true)))
195 }
196 mux.HandleFunc(catchAll, s.page(s.notFound))
197 return mux
198}
199
200// ServeHTTP implements http.Handler.
201func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
202 // Whatever the context carried, the caller is anonymous until a valid
203 // session says otherwise (withSession).
204 r = r.WithContext(domain.ContextWithPrincipal(r.Context(), domain.Anonymous()))
205 r = s.withSession(w, r)
206 if !s.gate(w, r) {
207 return
208 }
209 if to, ok := s.ownerRedirect(r); ok {
210 http.Redirect(w, r, to, http.StatusPermanentRedirect)
211 return
212 }
213 s.mux.ServeHTTP(w, r)
214}
215
216// catchAll is the pattern of the paths that are no page.
217const catchAll = "GET /{repo}/{rest...}"
218
219// ownerRedirect maps /<owner>/<repo>[.git][/rest] to /<repo>[.git][/rest]: the
220// URLs that the github context of CI shows (html_url, commit and compare
221// URLs, clone_url) have the owner of the instance in front, like GitHub's.
222//
223// The rule is by repository, not by route: when no repository named like the
224// owner is visible to the caller, every GET or HEAD of /<owner>/<rest> is
225// redirected, so /<owner>/actions reaches the repository named "actions". A
226// repository named like the owner keeps its own pages. A private one is seen
227// as missing by an anonymous caller (the use case answers ErrNotFound), so the
228// redirect is the same as for a name nobody has and tells nothing.
229//
230// The target is built from a segment that parses as a repository name, which
231// has no slash, backslash, percent sign or dot-dot: it can only be a path on
232// this origin, never a "//host" one.
233func (s *Server) ownerRedirect(r *http.Request) (string, bool) {
234 if s.cfg.Owner == "" || (r.Method != http.MethodGet && r.Method != http.MethodHead) {
235 return "", false
236 }
237 first, rest, ok := strings.Cut(strings.TrimPrefix(r.URL.EscapedPath(), "/"), "/")
238 if !ok || first != s.cfg.Owner || rest == "" {
239 return "", false
240 }
241 repo, _, _ := strings.Cut(rest, "/")
242 if _, err := domain.ParseRepoPath(repo); err != nil {
243 return "", false
244 }
245 if s.ownerNamesARepo(r) {
246 return "", false
247 }
248 to := "/" + rest
249 if r.URL.RawQuery != "" {
250 to += "?" + r.URL.RawQuery
251 }
252 return to, true
253}
254
255// ownerNamesARepo tells whether the caller can see a repository named like
256// the owner. A lookup that fails otherwise counts as yes: the request is then
257// served as it was before, without a redirect.
258func (s *Server) ownerNamesARepo(r *http.Request) bool {
259 if s.ownerRepo.IsZero() {
260 return false // the owner login is not a repository name
261 }
262 ctx := r.Context()
263 _, err := s.cfg.Repos.Get(ctx, principal(ctx), s.ownerRepo)
264 switch {
265 case err == nil:
266 return true
267 case errors.Is(err, domain.ErrNotFound):
268 return false
269 }
270 log := zerowrap.FromCtx(ctx)
271 log.Debug().Err(err).Msg("owner redirect: the lookup of the repository named like the owner failed")
272 return true
273}
274
275// handler builds a page. It returns the component and its status, or an
276// error, which becomes the 404 or 500 page.
277type handler func(ctx context.Context, r *http.Request) (templ.Component, int, error)
278
279// page adapts a handler: it bounds the use case calls, renders the component into
280// a buffer (so that a failure never leaves half a page), and maps errors to
281// the state pages.
282func (s *Server) page(h handler) http.HandlerFunc {
283 return func(w http.ResponseWriter, r *http.Request) {
284 ctx, cancel := context.WithTimeout(r.Context(), requestTimeout)
285 defer cancel()
286 c, status, err := h(ctx, r)
287 if err != nil {
288 s.fail(ctx, w, r, err)
289 return
290 }
291 s.write(ctx, w, r, status, c)
292 }
293}
294
295// write renders c with the given status.
296func (s *Server) write(ctx context.Context, w http.ResponseWriter, r *http.Request, status int, c templ.Component) {
297 var buf bytes.Buffer
298 if err := c.Render(ctx, &buf); err != nil {
299 // The error page itself failed: a bare answer is all that is left.
300 log := zerowrap.FromCtx(ctx)
301 log.Error().Err(err).Str("path", logPath(r.URL.Path)).Msg("render page")
302 http.Error(w, "internal error", http.StatusInternalServerError)
303 return
304 }
305 h := w.Header()
306 h.Set("Content-Type", "text/html; charset=utf-8")
307 // Links on this origin are prefetched on hover, so a click shows the page
308 // at once. Every GET page is safe to load (nothing is marked read on GET).
309 h.Set("Speculation-Rules", `"`+s.assets.urls.Rules+`"`)
310 // Public pages: the browser and any proxy revalidate each time. A page
311 // rendered for the owner is private and never stored; a handler that set
312 // its own Cache-Control keeps it.
313 if h.Get("Cache-Control") == "" {
314 cacheHeaders(ctx, h, "no-cache", sessionCache)
315 }
316 body := buf.Bytes()
317 // Whether the body is sent gzipped follows from its size and the request
318 // alone, so that the tag is known before the compression is spent.
319 gz := len(body) >= minCompress && acceptsGzip(r.Header) &&
320 !noTransform(h) && h.Get("Content-Encoding") == ""
321 addVary(h, "Accept-Encoding")
322 readOnly := r.Method == http.MethodGet || r.Method == http.MethodHead
323 // A page that may be stored gets a validator: the browser then
324 // revalidates with If-None-Match and a page that did not change costs a
325 // 304. A no-store page (the owner's) is never revalidated.
326 if readOnly && status == http.StatusOK && h.Get("ETag") == "" && !hasCacheDirective(h, noStore) {
327 tag := pageETag(body, SignedIn(ctx), gz)
328 h.Set("ETag", tag)
329 if etagMatches(strings.Join(r.Header.Values("If-None-Match"), ","), tag) {
330 h.Del("Content-Type")
331 w.WriteHeader(http.StatusNotModified)
332 return
333 }
334 }
335 if gz {
336 if z, err := gzipPage(body); err == nil && len(z) < len(body) {
337 body = z
338 h.Set("Content-Encoding", "gzip")
339 }
340 }
341 h.Set("Content-Length", itoa(len(body)))
342 w.WriteHeader(status)
343 if r.Method != http.MethodHead {
344 _, _ = w.Write(body)
345 }
346}
347
348// fail answers an error of a use case: not found (and a name or revision the
349// use case refuses, which no page can show either) gives the 404 page, a
350// visitor that left gives nothing, anything else gives the 500 page with an id
351// to find the cause in the log.
352func (s *Server) fail(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
353 switch {
354 case errors.Is(err, domain.ErrNotFound), domain.IsInvalid(err):
355 s.write(ctx, w, r, http.StatusNotFound, s.notFoundPage())
356 case errors.Is(err, context.Canceled):
357 // The client is gone; there is nobody to answer.
358 default:
359 id := requestID()
360 log := zerowrap.FromCtx(ctx)
361 log.Error().Err(err).Str("request_id", id).Str("path", logPath(r.URL.Path)).Msg("web request failed")
362 s.write(ctx, w, r, http.StatusInternalServerError, s.errorPage(id))
363 }
364}
365
366// errNotFound is returned by handlers for a resource that does not exist
367// although the use case did not say so (a ref or a path that is not there).
368var errNotFound = domain.ErrNotFound
369
370// requestID is a short random id, shown on the 500 page and logged.
371func requestID() string {
372 var b [4]byte
373 _, _ = rand.Read(b[:])
374 return hex.EncodeToString(b[:])
375}
376
377// notFound is the handler of the paths without a page.
378func (s *Server) notFound(context.Context, *http.Request) (templ.Component, int, error) {
379 return nil, 0, errNotFound
380}
381
382// base is the Layout every page starts from.
383func (s *Server) base() Layout {
384 return Layout{
385 Instance: s.instance,
386 Version: s.cfg.Version,
387 SourceURL: s.cfg.SourceURL,
388 Assets: s.assets.urls,
389 Passkeys: s.passkeysOn(),
390 }
391}
392
393// stateLayout is the layout of a state page: only the way home.
394func (s *Server) stateLayout(title string, crumbs []Crumb) Layout {
395 l := s.base()
396 l.Title = title + " · " + s.instance
397 l.Crumbs = crumbs
398 l.Cmd = []CmdItem{{Kind: "go", Label: "home", Href: "/"}}
399 return l
400}
401
402func (s *Server) notFoundPage() templ.Component {
403 l := s.stateLayout("404", []Crumb{{Label: "not found", Current: true}})
404 return State(l, StatePage{
405 Code: "404", Title: "not found",
406 Lines: []string{"no such page, ref or path.", "check the URL, or start from the repo list."},
407 Back: []Link{{Label: "home", Href: "/"}},
408 })
409}
410
411func (s *Server) errorPage(id string) templ.Component {
412 l := s.stateLayout("error", []Crumb{{Label: "error", Current: true}})
413 return State(l, StatePage{
414 Code: "500", Title: "internal error",
415 Lines: []string{
416 "the server failed to answer this request.",
417 "request id: " + id,
418 "retry in a moment; if it persists, the owner has the log.",
419 },
420 Back: []Link{{Label: "home", Href: "/"}},
421 })
422}
423
424// originOf is the origin of a URL as a browser writes it in the Origin
425// header: scheme and host in lower case, the port only when it is not the
426// default of the scheme.
427func originOf(u *url.URL) string {
428 scheme, host, port := strings.ToLower(u.Scheme), strings.ToLower(u.Hostname()), u.Port()
429 if strings.Contains(host, ":") {
430 host = "[" + host + "]"
431 }
432 defaultPort := (scheme == "http" && port == "80") || (scheme == "https" && port == "443")
433 if port != "" && !defaultPort {
434 host += ":" + port
435 }
436 return scheme + "://" + host
437}