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