v0.7.0 45bfc5b

web.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package app
4
5import (
6	"context"
7	"errors"
8	"net/http"
9	"net/netip"
10	"net/url"
11	"strings"
12	"time"
13
14	"github.com/bnema/zerowrap"
15
16	"bnema.dev/ermite/internal/adapters/httpserver"
17	"bnema.dev/ermite/internal/adapters/web"
18	"bnema.dev/ermite/internal/clientlimit"
19	"bnema.dev/ermite/internal/config"
20	"bnema.dev/ermite/internal/domain"
21	"bnema.dev/ermite/internal/ports"
22	"bnema.dev/ermite/internal/usecase"
23)
24
25// newWeb builds the web pages on the use cases of this process, through the
26// ports (ADR 0020), like the API and Git over HTTP.
27//
28// The owner's session cookie turns a request into the owner's (web.Server
29// checks it with sessions); every other request is anonymous. The web passes
30// the principal of the request to each use case call itself.
31func newWeb(cfg config.Config, f *forge, limiter *clientlimit.Limiter) (http.Handler, error) {
32	// A nil *usecase.Passkeys must not become a non-nil interface (the web
33	// tests for nil to leave the passkey routes out).
34	var passkeys ports.WebPasskeyService
35	if f.Passkeys != nil {
36		passkeys = webPasskeys{f.Passkeys}
37	}
38	return web.New(web.Config{
39		Repos:         f.Repos,
40		Browse:        f.Browse,
41		MergeRequests: f.MergeRequests,
42		Runs:          f.CI,
43		Events:        f.EventLog,
44		PublicURL:     cfg.PublicURL,
45		SourceURL:     cfg.SourceURL,
46		Version:       serverVersion(),
47
48		Sessions:       webSessions{f.Sessions},
49		Passkeys:       passkeys,
50		Limiter:        limiter,
51		TrustedProxies: cfg.TrustedProxies,
52	})
53}
54
55// sessionsNeedHTTPS reports whether browser sign-in cannot work on this public
56// URL: the session cookie is Secure (and __Host-), which a browser keeps only
57// from https, except on a loopback host (localhost, 127.0.0.0/8, ::1), where
58// browsers treat http as secure.
59func sessionsNeedHTTPS(publicURL string) bool {
60	u, err := url.Parse(publicURL)
61	if err != nil || !strings.EqualFold(u.Scheme, "http") {
62		return false
63	}
64	host := strings.ToLower(u.Hostname())
65	if host == "localhost" {
66		return false
67	}
68	ip, err := netip.ParseAddr(host)
69	return err != nil || !ip.Unmap().IsLoopback()
70}
71
72// passkeysAvailable reports whether passkeys can work on this public URL, and
73// if not, why. WebAuthn needs a secure context (https, or localhost) and a
74// relying party ID that is a DNS name, not an IP address, so a server on
75// http://127.0.0.1 starts without passkeys. A sign-in needs the session
76// cookie, hence the same https rule as sessionsNeedHTTPS.
77func passkeysAvailable(publicURL string) (ok bool, reason string) {
78	if sessionsNeedHTTPS(publicURL) {
79		return false, "needs https"
80	}
81	u, err := url.Parse(publicURL)
82	if err != nil || u.Hostname() == "" {
83		return false, "public URL has no host"
84	}
85	if _, err := netip.ParseAddr(strings.ToLower(u.Hostname())); err == nil {
86		return false, "public URL host is an IP address"
87	}
88	return true, ""
89}
90
91// warnSessionsNeedHTTPS tells the operator, at startup, that web sign-in will
92// not work on an http public URL. It does not stop the server: the pages,
93// the API and Git do not need the cookie.
94func warnSessionsNeedHTTPS(ctx context.Context, publicURL string) {
95	if !sessionsNeedHTTPS(publicURL) {
96		return
97	}
98	log := zerowrap.FromCtx(ctx)
99	log.Warn().Str("public_url", publicURL).Msg(
100		"browser sign-in cannot work: " + config.EnvPublicURL + " is http:// on a host that is not loopback, " +
101			"and the session cookie is Secure (__Host-), so browsers drop it; serve the site over https")
102}
103
104// warnSharedClientKey tells the operator, at startup, that without trusted
105// proxies every request is attributed to the address of its TCP peer. Behind a
106// reverse proxy that is the proxy: all the clients then share one key, and so
107// one cap on the Git backends running at once (maxPerClient) and one budget of
108// failed authentications. The keying is unchanged; the fix is to list the
109// proxy networks.
110func warnSharedClientKey(ctx context.Context, trusted []netip.Prefix, maxPerClient int) {
111	if len(trusted) > 0 || maxPerClient <= 0 {
112		return
113	}
114	log := zerowrap.FromCtx(ctx)
115	log.Warn().Int("max_git_backends_per_client", maxPerClient).Msg(
116		config.EnvTrustedProxies + " is not set: clients are told apart by their TCP peer address only. " +
117			"Behind a reverse proxy, all clients share the proxy's address, so one cap of concurrent Git " +
118			"requests and one budget of failed authentications; set it to the proxy networks")
119}
120
121// webSessions adapts the session use cases to ports.WebSessionService: a valid
122// token gives the owner, the principal the web passes to the use cases for
123// that request.
124type webSessions struct{ *usecase.Sessions }
125
126var _ ports.WebSessionService = webSessions{}
127
128func (s webSessions) Login(ctx context.Context, nonce string) (string, time.Duration, error) {
129	token, expiresAt, err := s.Sessions.Login(ctx, nonce)
130	if errors.Is(err, domain.ErrUnauthenticated) {
131		return "", 0, ports.ErrLinkRejected
132	}
133	if err != nil {
134		return "", 0, err
135	}
136	lifetime, ok := cookieLifetime(expiresAt)
137	if !ok {
138		return "", 0, ports.ErrLinkRejected
139	}
140	return token, lifetime, nil
141}
142
143// cookieLifetime is how long the session cookie lasts for a session that
144// expires at expiresAt: as long as the session, which the expiry of the token
145// that made a login link may cut short. The session token carries its own
146// expiry, so a cookie that outlives it by under a second is harmless. The
147// expiry is truncated to the second, hence the slack on the full TTL. ok is
148// false when under a second is left: there is no session to give.
149func cookieLifetime(expiresAt time.Time) (lifetime time.Duration, ok bool) {
150	lifetime = usecase.SessionTTL
151	if d := time.Until(expiresAt); d < usecase.SessionTTL-time.Second {
152		lifetime = d.Round(time.Second)
153	}
154	return lifetime, lifetime >= time.Second
155}
156
157func (s webSessions) Verify(ctx context.Context, token string) (domain.Principal, bool, error) {
158	p, err := s.Sessions.Verify(ctx, token)
159	if errors.Is(err, domain.ErrUnauthenticated) {
160		return domain.Anonymous(), false, nil
161	}
162	if err != nil {
163		return domain.Anonymous(), false, err
164	}
165	return p, true, nil
166}
167
168// webPasskeys adapts the passkey use cases to ports.WebPasskeyService. Only
169// FinishLogin differs from *usecase.Passkeys: the session a passkey sign-in
170// opens is given to the web as a token and a lifetime, like webSessions.Login
171// does for a link, and a refusal is ports.ErrLinkRejected.
172type webPasskeys struct{ *usecase.Passkeys }
173
174var _ ports.WebPasskeyService = webPasskeys{}
175
176func (p webPasskeys) FinishLogin(ctx context.Context, ceremony string, response []byte) (string, time.Duration, error) {
177	token, expiresAt, err := p.Passkeys.FinishLogin(ctx, ceremony, response)
178	if errors.Is(err, domain.ErrUnauthenticated) {
179		return "", 0, ports.ErrLinkRejected
180	}
181	if err != nil {
182		return "", 0, err
183	}
184	lifetime, ok := cookieLifetime(expiresAt)
185	if !ok {
186		return "", 0, ports.ErrLinkRejected
187	}
188	return token, lifetime, nil
189}
190
191// webRoutes mounts the web on the patterns it serves.
192func webRoutes(h http.Handler) []httpserver.Route {
193	routes := make([]httpserver.Route, 0, len(web.Patterns))
194	for _, p := range web.Patterns {
195		routes = append(routes, httpserver.Route{Pattern: p, Handler: h})
196	}
197	return routes
198}

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 3

Tags 44

↑↓ moveenter openesc close