Debian Codegraph @

server/server_auth.go

raw
1 package server
2
3 import (
4 "encoding/base64"
5 "errors"
6 "net/http"
7 "strings"
8 "time"
9
10 "heckel.io/ntfy/v2/user"
11 )
12
13 // maybeAuthenticate reads the "Authorization" header and will try to authenticate the user
14 // if it is set.
15 //
16 // - If auth-file is not configured, immediately return an IP-based visitor
17 // - If the header is not set or not supported (anything non-Basic and non-Bearer),
18 // an IP-based visitor is returned
19 // - If the header is set, authenticate will be called to check the username/password (Basic auth),
20 // or the token (Bearer auth), and read the user from the database
21 //
22 // This function will ALWAYS return a visitor, even if an error occurs (e.g. unauthorized), so
23 // that subsequent logging calls still have a visitor context.
24 func (s *Server) maybeAuthenticate(r *http.Request) (*http.Request, *visitor, error) {
25 // Read the "Authorization" header value and exit out early if it's not set
26 ip := extractIPAddress(r, s.config.BehindProxy, s.config.ProxyForwardedHeader, s.config.ProxyTrustedPrefixes)
27 // Stash the extracted client IP in the request context so downstream code (the abuse ban-feed in
28 // handleError) can reuse it without re-parsing headers, and so an account-keyed (tier'd) visitor --
29 // whose shared visitor object has a stale v.ip -- is still attributed to the actual request IP.
30 r = withContext(r, map[contextKey]any{contextVisitorIP: ip})
31 vip := s.visitor(ip, nil)
32 if s.userManager == nil {
33 return r, vip, nil
34 }
35 header, err := readAuthHeader(r)
36 if err != nil {
37 return r, vip, err
38 } else if !supportedAuthHeader(header) {
39 return r, vip, nil
40 }
41 // If we're trying to auth, check the rate limiter first
42 if !vip.AuthAllowed() {
43 return r, vip, errHTTPTooManyRequestsLimitAuthFailure // Always return visitor, even when error occurs!
44 }
45 u, err := s.authenticate(r, header)
46 if err != nil {
47 vip.AuthFailed()
48 logr(r).Err(err).Debug("Authentication failed")
49 return r, vip, errHTTPUnauthorized // Always return visitor, even when error occurs!
50 }
51 // Authentication with user was successful
52 return r, s.visitor(ip, u), nil
53 }
54
55 // authenticate a user based on basic auth username/password (Authorization: Basic ...), or token auth (Authorization: Bearer ...).
56 // The Authorization header can be passed as a header or the ?auth=... query param. The latter is required only to
57 // support the WebSocket JavaScript class, which does not support passing headers during the initial request. The auth
58 // query param is effectively doubly base64 encoded. Its format is base64(Basic base64(user:pass)).
59 func (s *Server) authenticate(r *http.Request, header string) (user *user.User, err error) {
60 if strings.HasPrefix(header, "Bearer") {
61 return s.authenticateBearerAuth(r, strings.TrimSpace(strings.TrimPrefix(header, "Bearer")))
62 }
63 return s.authenticateBasicAuth(r, header)
64 }
65
66 // readAuthHeader reads the raw value of the Authorization header, either from the actual HTTP header,
67 // or from the ?auth... query parameter
68 func readAuthHeader(r *http.Request) (string, error) {
69 value := strings.TrimSpace(r.Header.Get("Authorization"))
70 queryParam := readQueryParam(r, "authorization", "auth")
71 if queryParam != "" {
72 a, err := base64.RawURLEncoding.DecodeString(queryParam)
73 if err != nil {
74 return "", err
75 }
76 value = strings.TrimSpace(string(a))
77 }
78 return value, nil
79 }
80
81 // supportedAuthHeader returns true only if the Authorization header value starts
82 // with "Basic" or "Bearer". In particular, an empty value is not supported, and neither
83 // are things like "WebPush", or "vapid" (see #629).
84 func supportedAuthHeader(value string) bool {
85 value = strings.ToLower(value)
86 return strings.HasPrefix(value, "basic ") || strings.HasPrefix(value, "bearer ")
87 }
88
89 func (s *Server) authenticateBasicAuth(r *http.Request, value string) (user *user.User, err error) {
90 r.Header.Set("Authorization", value)
91 username, password, ok := r.BasicAuth()
92 if !ok {
93 return nil, errors.New("invalid basic auth")
94 } else if username == "" {
95 return s.authenticateBearerAuth(r, password) // Treat password as token
96 }
97 return s.userManager.Authenticate(username, password)
98 }
99
100 func (s *Server) authenticateBearerAuth(r *http.Request, token string) (*user.User, error) {
101 u, err := s.userManager.AuthenticateToken(token)
102 if err != nil {
103 return nil, err
104 }
105 ip := extractIPAddress(r, s.config.BehindProxy, s.config.ProxyForwardedHeader, s.config.ProxyTrustedPrefixes)
106 go s.userManager.EnqueueTokenUpdate(token, &user.TokenUpdate{
107 LastAccess: time.Now(),
108 LastOrigin: ip,
109 })
110 return u, nil
111 }