-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoauth2w.go
250 lines (213 loc) · 7.87 KB
/
oauth2w.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*
Copyright (c) JSC iCore.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
package oauth2w // import "github.com/i-core/oauth2w"
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type ctxkey string
const (
errMsgInternalServerError = "internal server error"
errMsgPermissionDenied = "permission denied"
claimEmail = "email"
defaultRole = "_default"
ctxkeyUser ctxkey = "github.com/i-core/oauth2w/user"
)
// User contains data of an authenticated user.
type User struct {
Email string
Roles []string
}
// LogFn is a function that provides a logging function for HTTP request.
type LogFn func(context.Context) func(string, ...interface{})
var dummyLogFn = func(context.Context) func(string, ...interface{}) { return func(string, ...interface{}) {} }
// RoleFinder is an interface to find user roles using the user's claims.
type RoleFinder interface {
FindRoles(claims map[string]interface{}) ([]string, error)
}
type config struct {
logPrintFn, logDebugFn LogFn
roleFinder RoleFinder
}
// Option describes a function for the middleware's configuration.
type Option func(*config)
// WithLogPrint returns an option that configures an info logger.
func WithLogPrint(logFn LogFn) Option {
return func(cnf *config) {
cnf.logPrintFn = logFn
}
}
// WithLogDebug returns an option that configures a debug logger.
func WithLogDebug(logFn LogFn) Option {
return func(cnf *config) {
cnf.logDebugFn = logFn
}
}
// New returns a new instance of the middleware.
//
// To authorize HTTP request the middleware validates that the user has all required roles.
// When there is no required roles the middleware authorizes all HTTP requests.
//
// To get user roles the middleware requests user claims from an OpenID Connect Provider,
// and then transforms the claims to roles using the interface RoleFinder.
//
// endpoint is an endpoint of an OpenID Connect Provider.
func New(endpoint string, roleFinder RoleFinder, opts ...Option) (func([]string) func(http.Handler) http.Handler, error) {
httpClient := &http.Client{}
if endpoint == "" {
return nil, fmt.Errorf("oauth2w: OIDC's endpoint is empty")
}
if roleFinder == nil {
return nil, fmt.Errorf("oauth2w: role finder is not defined")
}
cnf := &config{logPrintFn: dummyLogFn, logDebugFn: dummyLogFn, roleFinder: roleFinder}
for _, opt := range opts {
opt(cnf)
}
req, err := http.NewRequest(http.MethodGet, endpoint+"/.well-known/openid-configuration", nil)
if err != nil {
return nil, fmt.Errorf("oauth2w: OIDC's configuration request: %s", err)
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("oauth2w: send a request for getting OIDC's configuration: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var msg []byte
if msg, err = ioutil.ReadAll(resp.Body); err != nil {
return nil, fmt.Errorf("oauth2w: get OIDC's configuration: url=%q, status=%d: %s", req.URL, resp.StatusCode, err)
}
return nil, fmt.Errorf("oauth2w: get OIDC's configuration: url=%q, status=%d: %s", req.URL, resp.StatusCode, string(msg))
}
type oidcConfig struct {
UserinfoEP string `json:"userinfo_endpoint"`
}
var oidcCnf oidcConfig
if resp.Body != http.NoBody {
if err = json.NewDecoder(resp.Body).Decode(&oidcCnf); err != nil {
return nil, fmt.Errorf("oauth2w: parse OIDC's configuration: %s", err)
}
}
if oidcCnf.UserinfoEP == "" {
return nil, fmt.Errorf("oauth2w: OIDC's configuration: userinfo's endpoint is empty")
}
return func(wantRoles []string) func(http.Handler) http.Handler {
if len(wantRoles) == 0 {
return func(next http.Handler) http.Handler { return next }
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logPrint, logDebug := cnf.logPrintFn(r.Context()), cnf.logDebugFn(r.Context())
token := r.Header.Get("Authorization")
if token == "" {
httpError(w, http.StatusUnauthorized, "no OAuth2 access token")
logDebug("Authorization is unsuccessful because no OAuth2 access token")
return
}
req, err := http.NewRequest(http.MethodPost, oidcCnf.UserinfoEP, nil)
if err != nil {
httpError(w, http.StatusInternalServerError, errMsgInternalServerError)
logPrint("Failed to create a request to get a user's info", "userinfoEndpoint", req.URL.String(), "error", err)
return
}
req.Header.Set("Authorization", token)
resp, err := httpClient.Do(req)
if err != nil {
httpError(w, http.StatusInternalServerError, errMsgInternalServerError)
logPrint("Failed to send a request to get a user's info", "userinfoEndpoint", req.URL.String(), "error", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusUnauthorized {
var msg []byte
if resp.Body != http.NoBody {
if msg, err = ioutil.ReadAll(resp.Body); err != nil {
httpError(w, http.StatusInternalServerError, errMsgInternalServerError)
logPrint("Failed to read a user's info response", "userinfoEndpoint", req.URL.String(), "status", resp.StatusCode, "error", err)
return
}
}
httpError(w, http.StatusUnauthorized, "the access token is invalid")
logDebug("Authorization is unsuccessful because of an invalid OAuth2 access token", "userinfoEndpoint", req.URL.String(), "message", string(msg))
return
}
httpError(w, http.StatusInternalServerError, errMsgInternalServerError)
logPrint("Failed to get a user's info", "userinfoEndpoint", req.URL.String(), "status", resp.StatusCode, "error", err)
return
}
claims := make(map[string]interface{})
if resp.Body != http.NoBody {
if err = json.NewDecoder(resp.Body).Decode(&claims); err != nil {
httpError(w, http.StatusInternalServerError, errMsgInternalServerError)
logPrint("Failed to parse a user's info", "userinfoEndpoint", req.URL.String(), "error", err)
return
}
}
emailClaim, ok := claims[claimEmail]
if !ok {
httpError(w, http.StatusInternalServerError, "")
logDebug("Authorization failed while finding email", "claims", claims)
return
}
email, ok := emailClaim.(string)
if !ok || email == "" {
httpError(w, http.StatusInternalServerError, "")
logDebug("Authorization failed: invalid email", "claims", claims)
return
}
roles, err := cnf.roleFinder.FindRoles(claims)
if err != nil {
httpError(w, http.StatusInternalServerError, "")
logDebug("Authorization failed while finding roles", "claims", claims, "rolesClaim", err)
return
}
roles = append(roles, defaultRole)
var found bool
for _, wr := range wantRoles {
for _, gr := range roles {
if wr == gr {
found = true
break
}
}
}
if !found {
httpError(w, http.StatusForbidden, errMsgPermissionDenied)
logDebug("Authorization failed because the user has no required roles", "requiredRoles", wantRoles)
return
}
logDebug("Authorization is successful", "token", token)
next.ServeHTTP(w, r.WithContext(contextWithUser(r.Context(), &User{Email: email, Roles: roles})))
})
}
}, nil
}
// httpError writes an error to a response in a standard form.
func httpError(w http.ResponseWriter, code int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(map[string]interface{}{"message": msg}); err != nil {
panic(err)
}
}
// FindUser returs data of an authenticated user from the request context.
func FindUser(ctx context.Context) *User {
v := ctx.Value(ctxkeyUser)
user, ok := v.(*User)
if !ok || v == nil {
return nil
}
return user
}
func contextWithUser(ctx context.Context, user *User) context.Context {
return context.WithValue(ctx, ctxkeyUser, user)
}