v0.26.1 dfd6f0b

web.go RawHistoryFolder

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

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 2

Tags 45

↑↓ moveenter openesc close