forked from meshery/meshery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremote_auth.go
343 lines (298 loc) · 8.44 KB
/
remote_auth.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package models
import (
"bytes"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"math/big"
"net/http"
"net/url"
"time"
"github.com/golang-jwt/jwt"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"golang.org/x/oauth2"
)
// JWK - a type respresting the JSON web Key
type JWK map[string]string
// SafeClose is a helper function help to close the io
func SafeClose(co io.Closer) {
if cerr := co.Close(); cerr != nil {
logrus.Error(cerr)
}
}
// DoRequest - executes a request and does refreshing automatically
func (l *RemoteProvider) DoRequest(req *http.Request, tokenString string) (*http.Response, error) {
resp, err := l.doRequestHelper(req, tokenString)
if err != nil {
return nil, ErrTokenRefresh(err)
}
if resp.StatusCode == 401 {
// Read and close response body before reusing request
// https://github.com/golang/go/issues/19653#issuecomment-341540384
_, _ = io.ReadAll(resp.Body)
resp.Body.Close()
logrus.Warn("trying after refresh")
newToken, err := l.refreshToken(tokenString)
logrus.Info("token refresh successful")
if err != nil {
return nil, ErrTokenRefresh(err)
}
return l.doRequestHelper(req, newToken)
}
return resp, err
}
// refreshToken - takes a tokenString and returns a new tokenString
func (l *RemoteProvider) refreshToken(tokenString string) (string, error) {
l.TokenStoreMut.Lock()
defer l.TokenStoreMut.Unlock()
newTokenString := l.TokenStore[tokenString]
if newTokenString != "" {
return newTokenString, nil
}
bd := map[string]string{
tokenName: tokenString,
}
jsonString, err := json.Marshal(bd)
if err != nil {
return "", ErrMarshal(err, "refreshing token")
}
r, err := http.Post(l.RemoteProviderURL+"/refresh", "application/json; charset=utf-8", bytes.NewReader(jsonString))
if err != nil {
return "", err
}
if r.StatusCode == http.StatusInternalServerError {
return "", ErrTokenRefresh(fmt.Errorf("failed to refresh token: status code 500"))
}
defer SafeClose(r.Body)
var target map[string]string
err = json.NewDecoder(r.Body).Decode(&target)
if err != nil {
return "", err
}
l.TokenStore[tokenString] = target[tokenName]
time.AfterFunc(1*time.Hour, func() {
logrus.Infof("deleting old token string")
delete(l.TokenStore, tokenString)
})
return target[tokenName], nil
}
func (l *RemoteProvider) doRequestHelper(req *http.Request, tokenString string) (*http.Response, error) {
token, err := l.DecodeTokenData(tokenString)
if err != nil {
return nil, ErrTokenDecode(err)
}
c := &http.Client{}
req.Header.Set("Authorization", fmt.Sprintf("bearer %s", token.AccessToken))
req.Header.Set("SystemID", viper.GetString("INSTANCE_ID")) // Adds the system id to the header for event tracking
resp, err := c.Do(req)
if err != nil {
return nil, ErrTokenClientCheck(err)
}
return resp, nil
}
// GetToken - extracts token form a request
func (l *RemoteProvider) GetToken(req *http.Request) (string, error) {
ck, err := req.Cookie(tokenName)
if err != nil {
return "", ErrGetToken(err)
}
return ck.Value, nil
}
// DecodeTokenData - Decodes a tokenString to a token
func (l *RemoteProvider) DecodeTokenData(tokenStringB64 string) (*oauth2.Token, error) {
var token oauth2.Token
// logrus.Debugf("Token string %s", tokenStringB64)
tokenString, err := base64.RawStdEncoding.DecodeString(tokenStringB64)
if err != nil {
return nil, err
}
err = json.Unmarshal(tokenString, &token)
if err != nil {
return nil, ErrUnmarshal(err, "Token String")
}
return &token, nil
}
// UpdateJWKs - Updates Keys to the JWKS
func (l *RemoteProvider) UpdateJWKs() error {
resp, err := http.Get(l.RemoteProviderURL + "/keys")
if err != nil {
return ErrJWKsKeys(err)
}
defer SafeClose(resp.Body)
jsonDataFromHTTP, err := io.ReadAll(resp.Body)
if err != nil {
return ErrDataRead(err, "Response Body")
}
jwksJSON := map[string][]map[string]string{}
if err := json.Unmarshal([]byte(jsonDataFromHTTP), &jwksJSON); err != nil {
return ErrUnmarshal(err, "JWKs Keys")
}
jwks := jwksJSON["keys"]
if jwks == nil {
return ErrNilJWKs
}
l.Keys = jwks
return nil
}
// GetJWK - Takes a keyId and returns the JWK
func (l *RemoteProvider) GetJWK(kid string) (JWK, error) {
for _, key := range l.Keys {
if key["kid"] == kid {
return key, nil
}
}
err := l.UpdateJWKs()
if err != nil {
return nil, err
}
for _, key := range l.Keys {
if key["kid"] == kid {
return key, nil
}
}
return nil, ErrNilKeys
}
// GenerateKey - generate the actual key from the JWK
func (l *RemoteProvider) GenerateKey(jwk JWK) (*rsa.PublicKey, error) {
// decode the base64 bytes for n
nb, err := base64.RawURLEncoding.DecodeString(jwk["n"])
if err != nil {
return nil, ErrDecodeBase64(err, "JWK")
}
e := 0
// The default exponent is usually 65537, so just compare the
// base64 for [1,0,1] or [0,1,0,1]
if jwk["e"] == "AQAB" || jwk["e"] == "AAEAAQ" {
e = 65537
} else {
// need to decode "e" as a big-endian int
return nil, ErrDecodeBase64(err, "JWK as big-endian int")
}
pk := &rsa.PublicKey{
N: new(big.Int).SetBytes(nb),
E: e,
}
der, err := x509.MarshalPKIXPublicKey(pk)
if err != nil {
return nil, ErrMarshalPKIX(err)
}
block := &pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: der,
}
var out bytes.Buffer
if err := pem.Encode(&out, block); err != nil {
return nil, ErrEncodingPEM(err)
}
return jwt.ParseRSAPublicKeyFromPEM(out.Bytes())
}
// VerifyToken - verifies the validity of a tokenstring
func (l *RemoteProvider) VerifyToken(tokenString string) (*jwt.MapClaims, error) {
dtoken, err := l.DecodeTokenData(tokenString)
if err != nil {
return nil, ErrTokenDecode(err)
}
tokenString = dtoken.AccessToken
tokenUP, x, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
return nil, ErrPraseUnverified(err)
}
kid := tokenUP.Header["kid"].(string)
var jtk map[string]interface{}
t, _ := base64.RawStdEncoding.DecodeString(x[1])
if err := json.Unmarshal(t, &jtk); err != nil {
return nil, ErrPraseUnverified(err)
}
// TODO: Once hydra fixes https://github.com/ory/hydra/issues/1542
// we should rather configure hydra auth server to remove nbf field in the token
_, ok := jtk["exp"]
if ok {
exp := int64(jtk["exp"].(float64))
if jwt.TimeFunc().Unix() > exp {
return nil, ErrTokenExpired
}
}
keyJSON, err := l.GetJWK(kid)
if err != nil {
return nil, err
}
key, err := l.GenerateKey(keyJSON)
if err != nil {
return nil, err
}
// Verifies the signature
tokenParser := jwt.Parser{
SkipClaimsValidation: true,
}
token, err := tokenParser.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
return nil, ErrTokenPrase(err)
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, ErrTokenClaims
}
return &claims, nil
}
func (l *RemoteProvider) revokeToken(tokenString string) error {
jsonData := make(map[string]string)
token, err := l.DecodeTokenData(tokenString)
if err != nil {
return ErrTokenDecode(err)
}
jsonData["token"] = token.RefreshToken
body, err := json.Marshal(jsonData)
if err != nil {
return ErrMarshal(err, "refresh token")
}
remoteURL, err := url.Parse(fmt.Sprintf("%s/revoke", l.RemoteProviderURL))
if err != nil {
logrus.Errorf("maformed url: %v", err)
return err
}
r, err := http.Post(remoteURL.String(), "application/json", bytes.NewReader(body))
if err != nil {
logrus.Errorf("Error revoking token: %v", err)
return err
}
if r.StatusCode != http.StatusOK {
return ErrTokenRevoke(fmt.Errorf("failed to revoke token: status %d", r.StatusCode))
}
return nil
}
func (l *RemoteProvider) introspectToken(tokenString string) error {
jsonData := make(map[string]string)
token, err := l.DecodeTokenData(tokenString)
if err != nil {
return ErrTokenDecode(err)
}
jsonData["token"] = token.AccessToken
body, err := json.Marshal(jsonData)
if err != nil {
return ErrMarshal(err, "refresh token")
}
remoteURL, err := url.Parse(fmt.Sprintf("%s/introspect", l.RemoteProviderURL))
if err != nil {
logrus.Errorf("maformed url: %v", err)
return err
}
r, err := http.Post(remoteURL.String(), "application/json", bytes.NewReader(body))
if err != nil {
logrus.Errorf("Error introspecting token: %v", err)
return err
}
if r.StatusCode == http.StatusUnauthorized {
return ErrTokenIntrospect(fmt.Errorf("unauthorized access: status %d", r.StatusCode))
}
if r.StatusCode != http.StatusOK {
return ErrTokenIntrospect(fmt.Errorf("failed to introspect token: status %d", r.StatusCode))
}
return nil
}