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