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