-
-
Notifications
You must be signed in to change notification settings - Fork 341
Expand file tree
/
Copy pathauthorization.go
More file actions
210 lines (169 loc) · 5.73 KB
/
Copy pathauthorization.go
File metadata and controls
210 lines (169 loc) · 5.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package mercure
import (
"errors"
"fmt"
"log/slog"
"net/http"
"net/url"
"slices"
"strings"
"github.com/golang-jwt/jwt/v5"
)
// claims contains Mercure's JWT claims.
type claims struct {
jwt.RegisteredClaims
Mercure mercureClaim `json:"mercure"`
// Optional fallback
MercureNamespaced *mercureClaim `json:"https://mercure.rocks/"`
}
type mercureClaim struct {
Publish []string `json:"publish"`
Subscribe []string `json:"subscribe"`
Payload any `json:"payload"`
}
type role int
const (
defaultCookieName = "mercureAuthorization"
bearerPrefix = "Bearer "
)
const (
roleSubscriber role = iota
rolePublisher
)
var (
// ErrInvalidAuthorizationHeader is returned when the Authorization header is invalid.
ErrInvalidAuthorizationHeader = errors.New(`invalid "Authorization" HTTP header`)
// ErrInvalidAuthorizationQuery is returned when the authorization query parameter is invalid.
ErrInvalidAuthorizationQuery = errors.New(`invalid "authorization" Query parameter`)
// ErrNoOrigin is returned when the cookie authorization mechanism is used and no Origin nor Referer headers are presents.
ErrNoOrigin = errors.New(`an "Origin" or a "Referer" HTTP header must be present to use the cookie-based authorization mechanism`)
// ErrOriginNotAllowed is returned when the Origin is not allowed to post updates.
ErrOriginNotAllowed = errors.New("origin not allowed to post updates")
// ErrInvalidJWT is returned when the JWT is invalid.
ErrInvalidJWT = errors.New("invalid JWT")
)
// wildcard has been copied from https://github.com/rs/cors/blob/1084d89a16921942356d1c831fbe523426cf836e/utils.go
// Copyright (c) 2014 Olivier Poitrey <rs@dailymotion.com>
// MIT licensed.
type wildcard struct {
prefix string
suffix string
}
func (w wildcard) match(s string) bool {
return len(s) >= len(w.prefix)+len(w.suffix) &&
strings.HasPrefix(s, w.prefix) &&
strings.HasSuffix(s, w.suffix)
}
// authorize validates the JWT that may be provided through an "Authorization" HTTP header or an authorization cookie.
// It returns the claims contained in the token if it exists and is valid, nil if no token is provided (anonymous mode), and an error if the token is not valid.
func (h *Hub) authorize(r *http.Request, publish bool) (*claims, error) { //nolint:funlen
var jwtKeyfunc jwt.Keyfunc
if publish {
jwtKeyfunc = h.publisherJWTKeyFunc
} else {
jwtKeyfunc = h.subscriberJWTKeyFunc
}
authorizationHeaders, authorizationHeaderExists := r.Header["Authorization"]
if authorizationHeaderExists {
if len(authorizationHeaders) != 1 || len(authorizationHeaders[0]) < 48 || authorizationHeaders[0][:7] != bearerPrefix {
return nil, ErrInvalidAuthorizationHeader
}
return validateJWT(authorizationHeaders[0][7:], jwtKeyfunc)
}
if authorizationQuery, queryExists := r.URL.Query()["authorization"]; queryExists {
if len(authorizationQuery) != 1 || len(authorizationQuery[0]) < 41 {
return nil, ErrInvalidAuthorizationQuery
}
return validateJWT(authorizationQuery[0], jwtKeyfunc)
}
cookie, err := r.Cookie(h.cookieName)
if err != nil {
// Anonymous
return nil, nil //nolint:nilerr,nilnil
}
// CSRF attacks cannot occur when using safe methods
if r.Method != http.MethodPost {
return validateJWT(cookie.Value, jwtKeyfunc)
}
origin := r.Header.Get("Origin")
if origin == "" {
// Try to extract the origin from the Referer, or return an error
referer := r.Header.Get("Referer")
if referer == "" {
return nil, ErrNoOrigin
}
u, err := url.Parse(referer)
if err != nil {
return nil, fmt.Errorf("unable to parse referer: %w", err)
}
origin = fmt.Sprintf("%s://%s", u.Scheme, u.Host)
}
if h.publishOriginsAll {
return validateJWT(cookie.Value, jwtKeyfunc)
}
if slices.Contains(h.publishOrigins, origin) {
return validateJWT(cookie.Value, jwtKeyfunc)
}
for _, allowedOrigin := range h.publishWOrigins {
if allowedOrigin.match(origin) {
return validateJWT(cookie.Value, jwtKeyfunc)
}
}
return nil, fmt.Errorf("%q: %w", origin, ErrOriginNotAllowed)
}
// ErrTooManyClaimMatchers is returned when mercure.subscribe or
// mercure.publish exceeds maxClaimMatchers.
var ErrTooManyClaimMatchers = errors.New("too many matchers in mercure claim")
// validateJWT validates that the provided JWT token is a valid Mercure token.
func validateJWT(encodedToken string, jwtKeyfunc jwt.Keyfunc) (*claims, error) {
token, err := jwt.ParseWithClaims(encodedToken, &claims{}, jwtKeyfunc)
if err != nil {
return nil, fmt.Errorf("unable to parse JWT: %w", err)
}
c, ok := token.Claims.(*claims)
if !ok || !token.Valid {
return nil, ErrInvalidJWT
}
if c.MercureNamespaced != nil {
c.Mercure = *c.MercureNamespaced
}
if len(c.Mercure.Publish) > maxClaimMatchers || len(c.Mercure.Subscribe) > maxClaimMatchers {
return nil, ErrTooManyClaimMatchers
}
return c, nil
}
func canReceive(s *TopicSelectorStore, topics, topicSelectors []string) bool {
for _, topic := range topics {
for _, topicSelector := range topicSelectors {
if s.match(topic, topicSelector) {
return true
}
}
}
return false
}
func canDispatch(s *TopicSelectorStore, topics, topicSelectors []string) bool {
for _, topic := range topics {
var matched bool
for _, topicSelector := range topicSelectors {
if topicSelector == "*" {
return true
}
if s.match(topic, topicSelector) {
matched = true
break
}
}
if !matched {
return false
}
}
return true
}
func (h *Hub) httpAuthorizationError(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
ctx := r.Context()
if h.logger.Enabled(ctx, slog.LevelDebug) {
h.logger.LogAttrs(ctx, slog.LevelDebug, "Topic selectors not matched, not provided or authorization error", slog.Any("error", err))
}
}