forked from BuzzBumbleBee/fosite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
refresh_token_grant_test.go
285 lines (258 loc) · 9.77 KB
/
refresh_token_grant_test.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
/*
* Copyright © 2015-2018 Aeneas Rekkas <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <[email protected]>
* @copyright 2015-2018 Aeneas Rekkas <[email protected]>
* @license Apache-2.0
*
*/
package integration_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/ory/fosite/internal/gen"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
"github.com/ory/fosite"
"github.com/ory/fosite/compose"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
)
type introspectionResponse struct {
Active bool `json:"active"`
ClientID string `json:"client_id,omitempty"`
Scope string `json:"scope,omitempty"`
Audience []string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
Subject string `json:"sub,omitempty"`
Username string `json:"username,omitempty"`
}
func TestRefreshTokenFlow(t *testing.T) {
session := &defaultSession{
DefaultSession: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: "peter",
},
Headers: &jwt.Headers{},
Subject: "peter",
Username: "peteru",
},
}
fc := new(fosite.Config)
fc.RefreshTokenLifespan = -1
fc.GlobalSecret = []byte("some-secret-thats-random-some-secret-thats-random-")
f := compose.ComposeAllEnabled(fc, fositeStore, gen.MustRSAKey())
ts := mockServer(t, f, session)
defer ts.Close()
oauthClient := newOAuth2Client(ts)
state := "1234567890"
fositeStore.Clients["my-client"].(*fosite.DefaultClient).RedirectURIs[0] = ts.URL + "/callback"
refreshCheckClient := &fosite.DefaultClient{
ID: "refresh-client",
Secret: []byte(`$2a$10$IxMdI6d.LIRZPpSfEwNoeu4rY3FhDREsxFJXikcgdRRAStxUlsuEO`), // = "foobar"
RedirectURIs: []string{ts.URL + "/callback"},
ResponseTypes: []string{"id_token", "code", "token", "token code", "id_token code", "token id_token", "token code id_token"},
GrantTypes: []string{"implicit", "refresh_token", "authorization_code", "password", "client_credentials"},
Scopes: []string{"fosite", "offline", "openid"},
Audience: []string{"https://www.ory.sh/api"},
}
fositeStore.Clients["refresh-client"] = refreshCheckClient
fositeStore.Clients["my-client"].(*fosite.DefaultClient).RedirectURIs[0] = ts.URL + "/callback"
for _, c := range []struct {
description string
setup func(t *testing.T)
pass bool
params []oauth2.AuthCodeOption
check func(t *testing.T, original, refreshed *oauth2.Token, or, rr *introspectionResponse)
beforeRefresh func(t *testing.T)
mockServer func(t *testing.T) *httptest.Server
}{
{
description: "should fail because refresh scope missing",
setup: func(t *testing.T) {
oauthClient.Scopes = []string{"fosite"}
},
pass: false,
},
{
description: "should pass but not yield id token",
setup: func(t *testing.T) {
oauthClient.Scopes = []string{"offline"}
},
pass: true,
check: func(t *testing.T, original, refreshed *oauth2.Token, or, rr *introspectionResponse) {
assert.NotEqual(t, original.RefreshToken, refreshed.RefreshToken)
assert.NotEqual(t, original.AccessToken, refreshed.AccessToken)
assert.Nil(t, refreshed.Extra("id_token"))
},
},
{
description: "should pass and yield id token",
params: []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("audience", "https://www.ory.sh/api")},
setup: func(t *testing.T) {
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
},
pass: true,
check: func(t *testing.T, original, refreshed *oauth2.Token, or, rr *introspectionResponse) {
assert.NotEqual(t, original.RefreshToken, refreshed.RefreshToken)
assert.NotEqual(t, original.AccessToken, refreshed.AccessToken)
assert.NotEqual(t, original.Extra("id_token"), refreshed.Extra("id_token"))
assert.NotNil(t, refreshed.Extra("id_token"))
assert.NotEmpty(t, or.Audience)
assert.NotEmpty(t, or.ClientID)
assert.NotEmpty(t, or.Scope)
assert.NotEmpty(t, or.ExpiresAt)
assert.NotEmpty(t, or.IssuedAt)
assert.True(t, or.Active)
assert.EqualValues(t, "peter", or.Subject)
assert.EqualValues(t, "peteru", or.Username)
assert.EqualValues(t, or.Audience, rr.Audience)
assert.EqualValues(t, or.ClientID, rr.ClientID)
assert.EqualValues(t, or.Scope, rr.Scope)
assert.NotEqual(t, or.ExpiresAt, rr.ExpiresAt)
assert.True(t, or.ExpiresAt < rr.ExpiresAt)
assert.NotEqual(t, or.IssuedAt, rr.IssuedAt)
assert.True(t, or.IssuedAt < rr.IssuedAt)
assert.EqualValues(t, or.Active, rr.Active)
assert.EqualValues(t, or.Subject, rr.Subject)
assert.EqualValues(t, or.Username, rr.Username)
},
},
{
description: "should fail because scope is no longer allowed",
setup: func(t *testing.T) {
oauthClient.ClientID = refreshCheckClient.ID
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
},
beforeRefresh: func(t *testing.T) {
refreshCheckClient.Scopes = []string{"offline", "openid"}
},
pass: false,
},
{
description: "should fail because audience is no longer allowed",
params: []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("audience", "https://www.ory.sh/api")},
setup: func(t *testing.T) {
oauthClient.ClientID = refreshCheckClient.ID
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
refreshCheckClient.Scopes = []string{"fosite", "offline", "openid"}
},
beforeRefresh: func(t *testing.T) {
refreshCheckClient.Audience = []string{"https://www.not-ory.sh/api"}
},
pass: false,
},
{
description: "should fail with expired refresh token",
setup: func(t *testing.T) {
fc = new(fosite.Config)
fc.RefreshTokenLifespan = time.Nanosecond
fc.GlobalSecret = []byte("some-secret-thats-random-some-secret-thats-random-")
f = compose.ComposeAllEnabled(fc, fositeStore, gen.MustRSAKey())
ts = mockServer(t, f, session)
oauthClient = newOAuth2Client(ts)
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
fositeStore.Clients["my-client"].(*fosite.DefaultClient).RedirectURIs[0] = ts.URL + "/callback"
},
pass: false,
},
{
description: "should pass with limited but not expired refresh token",
setup: func(t *testing.T) {
fc = new(fosite.Config)
fc.RefreshTokenLifespan = time.Minute
fc.GlobalSecret = []byte("some-secret-thats-random-some-secret-thats-random-")
f = compose.ComposeAllEnabled(fc, fositeStore, gen.MustRSAKey())
ts = mockServer(t, f, session)
oauthClient = newOAuth2Client(ts)
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
fositeStore.Clients["my-client"].(*fosite.DefaultClient).RedirectURIs[0] = ts.URL + "/callback"
},
beforeRefresh: func(t *testing.T) {
refreshCheckClient.Audience = []string{}
},
pass: true,
check: func(t *testing.T, original, refreshed *oauth2.Token, or, rr *introspectionResponse) {},
},
{
description: "should deny access if original token was reused",
setup: func(t *testing.T) {
oauthClient.Scopes = []string{"offline"}
},
pass: true,
check: func(t *testing.T, original, refreshed *oauth2.Token, or, rr *introspectionResponse) {
tokenSource := oauthClient.TokenSource(oauth2.NoContext, original)
_, err := tokenSource.Token()
require.Error(t, err)
require.Equal(t, http.StatusUnauthorized, err.(*oauth2.RetrieveError).Response.StatusCode)
refreshed.Expiry = refreshed.Expiry.Add(-time.Hour * 24)
tokenSource = oauthClient.TokenSource(oauth2.NoContext, refreshed)
_, err = tokenSource.Token()
require.Error(t, err)
require.Equal(t, http.StatusUnauthorized, err.(*oauth2.RetrieveError).Response.StatusCode)
},
},
} {
t.Run("case="+c.description, func(t *testing.T) {
c.setup(t)
var intro = func(token string, p interface{}) {
req, err := http.NewRequest("POST", ts.URL+"/introspect", strings.NewReader(url.Values{"token": {token}}.Encode()))
require.NoError(t, err)
req.SetBasicAuth("refresh-client", "foobar")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, r.StatusCode)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
require.NoError(t, dec.Decode(p))
}
resp, err := http.Get(oauthClient.AuthCodeURL(state, c.params...))
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
if resp.StatusCode != http.StatusOK {
return
}
token, err := oauthClient.Exchange(oauth2.NoContext, resp.Request.URL.Query().Get("code"))
require.NoError(t, err)
require.NotEmpty(t, token.AccessToken)
var ob introspectionResponse
intro(token.AccessToken, &ob)
token.Expiry = token.Expiry.Add(-time.Hour * 24)
if c.beforeRefresh != nil {
c.beforeRefresh(t)
}
tokenSource := oauthClient.TokenSource(oauth2.NoContext, token)
// This sleep guarantees time difference in exp/iat
time.Sleep(time.Second * 2)
refreshed, err := tokenSource.Token()
if c.pass {
require.NoError(t, err)
var rb introspectionResponse
intro(refreshed.AccessToken, &rb)
c.check(t, token, refreshed, &ob, &rb)
} else {
require.Error(t, err)
}
})
}
}