-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
198 lines (165 loc) · 5.37 KB
/
middleware.go
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
package authcontrol
import (
"cmp"
"errors"
"net/http"
"strings"
"time"
"github.com/go-chi/jwtauth/v5"
"github.com/lestrrat-go/jwx/v2/jwt"
"github.com/0xsequence/authcontrol/proto"
)
// Options for the authcontrol middleware handlers Session and AccessControl.
type Options struct {
// JWT secret used to verify the JWT token.
JWTSecret string
// AccessKeyFuncs are used to extract the access key from the request.
AccessKeyFuncs []AccessKeyFunc
// UserStore is a pluggable backends that verifies if the account exists.
UserStore UserStore
// ProjectStore is a pluggable backends that verifies if the project exists.
ProjectStore ProjectStore
// ErrHandler is a function that is used to handle and respond to errors.
ErrHandler ErrHandler
}
func (o *Options) ApplyDefaults() {
// Set default access key functions if not provided.
// We intentionally check for nil instead of len == 0 because
// if you can pass an empty slice to have no access key defaults.
if o.AccessKeyFuncs == nil {
o.AccessKeyFuncs = []AccessKeyFunc{AccessKeyFromHeader}
}
// Set default error handler if not provided
if o.ErrHandler == nil {
o.ErrHandler = errHandler
}
}
func Session(cfg Options) func(next http.Handler) http.Handler {
cfg.ApplyDefaults()
auth := jwtauth.New("HS256", []byte(cfg.JWTSecret), nil, jwt.WithAcceptableSkew(2*time.Minute))
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// check if the request already contains session, if it does then continue
if _, ok := GetSessionType(ctx); ok {
next.ServeHTTP(w, r)
return
}
var (
sessionType proto.SessionType
accessKey string
token jwt.Token
)
for _, f := range cfg.AccessKeyFuncs {
if accessKey = f(r); accessKey != "" {
break
}
}
// Verify JWT token and validate its claims.
token, err := jwtauth.VerifyRequest(auth, r, jwtauth.TokenFromHeader)
if err != nil {
if errors.Is(err, jwtauth.ErrExpired) {
cfg.ErrHandler(r, w, proto.ErrSessionExpired)
return
}
if !errors.Is(err, jwtauth.ErrNoTokenFound) {
cfg.ErrHandler(r, w, proto.ErrUnauthorized)
return
}
}
if token != nil {
claims, err := token.AsMap(ctx)
if err != nil {
cfg.ErrHandler(r, w, err)
return
}
if originClaim, _ := claims["ogn"].(string); originClaim != "" {
originClaim = strings.TrimSuffix(originClaim, "/")
originHeader := strings.TrimSuffix(r.Header.Get("Origin"), "/")
if originHeader != "" && originHeader != originClaim {
cfg.ErrHandler(r, w, proto.ErrUnauthorized.WithCausef("invalid origin claim"))
return
}
}
serviceClaim, _ := claims["service"].(string)
accountClaim, _ := claims["account"].(string)
adminClaim, _ := claims["admin"].(bool)
// We support both claims for now, we'll deprecate one if we can.
// - `project` is used by the builder to generate Project JWT tokens.
// - `project_id` is used by API for WaaS related authentication.
projectClaim, _ := cmp.Or(claims["project"], claims["project_id"]).(float64)
switch {
case serviceClaim != "":
ctx = WithService(ctx, serviceClaim)
sessionType = proto.SessionType_InternalService
case accountClaim != "":
ctx = WithAccount(ctx, accountClaim)
sessionType = proto.SessionType_Wallet
if cfg.UserStore != nil {
user, isAdmin, err := cfg.UserStore.GetUser(ctx, accountClaim)
if err != nil {
cfg.ErrHandler(r, w, err)
return
}
if user != nil {
ctx = WithUser(ctx, user)
sessionType = proto.SessionType_User
if isAdmin {
sessionType = proto.SessionType_Admin
}
}
}
if adminClaim {
sessionType = proto.SessionType_Admin
}
if projectClaim > 0 {
projectID := uint64(projectClaim)
if cfg.ProjectStore != nil {
project, err := cfg.ProjectStore.GetProject(ctx, projectID)
if err != nil {
cfg.ErrHandler(r, w, err)
return
}
if project == nil {
cfg.ErrHandler(r, w, proto.ErrProjectNotFound)
return
}
ctx = WithProject(ctx, project)
}
ctx = WithProjectID(ctx, projectID)
sessionType = proto.SessionType_Project
}
}
}
if accessKey != "" && sessionType < proto.SessionType_Admin {
ctx = WithAccessKey(ctx, accessKey)
sessionType = max(sessionType, proto.SessionType_AccessKey)
}
ctx = WithSessionType(ctx, sessionType)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// AccessControl middleware that checks if the session type is allowed to access the endpoint.
// It also sets the compute units on the context if the endpoint requires it.
func AccessControl(acl Config[ACL], cfg Options) func(next http.Handler) http.Handler {
cfg.ApplyDefaults()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
acl, err := acl.Get(r.URL.Path)
if err != nil {
cfg.ErrHandler(r, w, proto.ErrUnauthorized.WithCausef("get acl: %w", err))
return
}
if session, _ := GetSessionType(r.Context()); !acl.Includes(session) {
err := proto.ErrPermissionDenied
if session == proto.SessionType_Public {
err = proto.ErrUnauthorized
}
cfg.ErrHandler(r, w, err)
return
}
next.ServeHTTP(w, r)
})
}
}