1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package rpc
4
5import (
6 "context"
7 "errors"
8 "math"
9 "net/http"
10 "net/netip"
11 "strconv"
12 "strings"
13 "time"
14
15 "connectrpc.com/connect"
16 "github.com/bnema/zerowrap"
17
18 "bnema.dev/ermite-api/gen/ermite/ermiteconnect"
19 "bnema.dev/ermite/internal/clientlimit"
20 "bnema.dev/ermite/internal/domain"
21 "bnema.dev/ermite/internal/ports"
22)
23
24var errInternal = errors.New("internal error")
25
26// interceptor authenticates the caller of every call and logs it.
27//
28// A request that carries "Authorization: Bearer <secret>" is authenticated
29// with it; one without the header is anonymous. A secret that is not valid is
30// unauthenticated and counts as a failure of the client address in the
31// limiter; a client that used up its failures gets resource_exhausted (429 on
32// the Connect protocol) whatever it presents, like on the Git routes.
33//
34// A principal in the context of a network request, say one put there by a
35// server's base context, is ignored and the request is authenticated from its
36// headers.
37type interceptor struct {
38 auth ports.AuthService
39 limiter ports.FailureLimiter
40 trusted []netip.Prefix
41}
42
43func newInterceptor(cfg Config) *interceptor {
44 return &interceptor{auth: cfg.Auth, limiter: cfg.Limiter, trusted: cfg.TrustedProxies}
45}
46
47// authenticate returns the context to run the call in.
48func (i *interceptor) authenticate(ctx context.Context, procedure, peerAddr string, h http.Header) (context.Context, error) {
49 // Whatever the context carried, the caller is anonymous until proven
50 // otherwise.
51 ctx = domain.ContextWithPrincipal(ctx, domain.Anonymous())
52 if procedure == ermiteconnect.ServerServiceGetVersionProcedure || procedure == ermiteconnect.ServerServiceGetSigningKeyProcedure {
53 // GetVersion needs no authentication, so that a client can check
54 // compatibility first, even with a token that has expired. The signing
55 // key is public: whoever verifies a commit needs it.
56 return ctx, nil
57 }
58 log := zerowrap.FromCtx(ctx)
59 addr := clientlimit.ClientAddr(&http.Request{RemoteAddr: peerAddr, Header: h}, i.trusted)
60 ctx = context.WithValue(ctx, clientKey{}, clientlimit.Key(addr))
61 if blocked, wait := i.limiter.Blocked(ctx, addr); blocked {
62 log.Warn().Str("client", addr).Msg("too many failed authentications, api request blocked")
63 err := connect.NewError(connect.CodeResourceExhausted, errors.New("too many failed authentications"))
64 err.Meta().Set("Retry-After", strconv.Itoa(int(math.Ceil(wait.Seconds()))))
65 return ctx, err
66 }
67
68 secret, present := bearer(h)
69 if !present {
70 return ctx, nil
71 }
72 if runnerSecretProcedures[procedure] {
73 // A runner or job token: not a stored token. The use case checks it
74 // and answers unauthenticated; runnerService.failed counts the
75 // failures against the client address.
76 ctx = context.WithValue(ctx, addrKey{}, addr)
77 return context.WithValue(ctx, secretKey{}, secret), nil
78 }
79 p, err := i.auth.Authenticate(ctx, secret)
80 switch {
81 case errors.Is(err, domain.ErrUnauthenticated):
82 i.limiter.Fail(ctx, addr)
83 log.Debug().Str("client", addr).Msg("invalid api credentials")
84 return ctx, connect.NewError(connect.CodeUnauthenticated, errors.New("invalid token"))
85 case err != nil:
86 return ctx, connectError(ctx, err)
87 }
88 return domain.ContextWithPrincipal(ctx, p), nil
89}
90
91type clientKey struct{}
92
93// addrKey carries the normalized client address of a call whose credential the
94// use case checks.
95type addrKey struct{}
96
97func addrFromContext(ctx context.Context) string {
98 a, _ := ctx.Value(addrKey{}).(string)
99 return a
100}
101
102// clientFromContext returns the normalized address of the client of a call:
103// its peer, empty when there is none.
104func clientFromContext(ctx context.Context) string {
105 c, _ := ctx.Value(clientKey{}).(string)
106 return c
107}
108
109// bearer extracts the secret of an "Authorization: Bearer" header. present is
110// true when the header exists, even when it carries nothing usable, which
111// then fails authentication.
112func bearer(h http.Header) (secret string, present bool) {
113 auth := h.Get("Authorization")
114 if auth == "" {
115 return "", false
116 }
117 scheme, rest, ok := strings.Cut(auth, " ")
118 if !ok || !strings.EqualFold(scheme, "Bearer") {
119 return "", true
120 }
121 return strings.TrimSpace(rest), true
122}
123
124// logCall logs a finished call at debug level: procedure, code, caller and
125// duration. Never headers or messages: they can carry credentials.
126func logCall(ctx context.Context, procedure string, start time.Time, err error) {
127 code := "ok"
128 if err != nil {
129 code = connect.CodeOf(err).String()
130 }
131 p, _ := domain.PrincipalFromContext(ctx)
132 log := zerowrap.FromCtx(ctx)
133 log.Debug().
134 Str("procedure", procedure).
135 Str("code", code).
136 Str("principal", p.Label()).Str("token_id", p.TokenID()).
137 Dur("duration", time.Since(start)).
138 Msg("api call")
139}
140
141// WrapUnary implements connect.Interceptor.
142func (i *interceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
143 return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
144 start := time.Now()
145 ctx, err := i.authenticate(ctx, req.Spec().Procedure, req.Peer().Addr, req.Header())
146 var resp connect.AnyResponse
147 if err == nil {
148 resp, err = next(ctx, req)
149 }
150 logCall(ctx, req.Spec().Procedure, start, err)
151 return resp, err
152 }
153}
154
155// WrapStreamingClient implements connect.Interceptor; the server has no
156// client side.
157func (i *interceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
158 return next
159}
160
161// WrapStreamingHandler implements connect.Interceptor.
162func (i *interceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
163 return func(ctx context.Context, conn connect.StreamingHandlerConn) error {
164 start := time.Now()
165 ctx, err := i.authenticate(ctx, conn.Spec().Procedure, conn.Peer().Addr, conn.RequestHeader())
166 if err == nil {
167 err = next(ctx, conn)
168 }
169 logCall(ctx, conn.Spec().Procedure, start, err)
170 return err
171 }
172}