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