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