/
oauth2provider_test.go
262 lines (226 loc) · 7.37 KB
/
oauth2provider_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
package oauth2provider
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"golang.org/x/crypto/bcrypt"
"golang.org/x/net/context"
"google.golang.org/appengine"
"google.golang.org/appengine/aetest"
"google.golang.org/appengine/datastore"
)
var (
inst aetest.Instance
server *AEServer
userID = "AFC22203-63A0-4812-9283-5376D304BB5D"
username = "test@test.com"
password = "testpass"
clientID = "47bef51d-1b4a-4028-b4a1-07dfe3116a9b"
clientSecret = "aabbccdd"
redirectURI = "https://www.google.com/"
accessToken = "fakeaccesstoken"
refreshToken = "fakerefreshtoken"
)
type basicAuth struct {
Username string
Password string
}
func TestMain(m *testing.M) {
setUp()
defer tearDown()
os.Exit(m.Run())
}
func setUp() {
server = NewServer()
opt := aetest.Options{AppID: "auth", StronglyConsistentDatastore: true}
var err error
inst, err = aetest.NewInstance(&opt)
if err != nil || inst == nil {
log.Printf("ERROR: %v", fmt.Errorf("Failed to created aetest instance, %v", err))
inst.Close()
}
r, err := inst.NewRequest("GET", "/", nil)
if err != nil {
log.Panicf("Failed to create request: %v", err)
inst.Close()
}
c := appengine.NewContext(r)
_, err = setupFakeClient(c)
if err != nil {
log.Panicf("Failed to create fake client: %v", err)
inst.Close()
}
userKey, err := setupFakeUser(c)
if err != nil {
log.Panicf("Failed to create fake user: %v", err)
inst.Close()
}
_, err = setupFakeAccessToken(c, userKey)
if err != nil {
log.Panicf("Failed to create fake access token: %v", err)
inst.Close()
}
}
func tearDown() {
if inst != nil {
inst.Close()
}
}
//TestPasswordAuth tests password password grant, expects a valid token
func TestPasswordAuth(t *testing.T) {
// construct new request
credentialsBodyStr := fmt.Sprintf("username=%s&password=%s", url.QueryEscape(username), url.QueryEscape(password))
r, err := newRequest("POST", "/token?grant_type=password", credentialsBodyStr, map[string]string{"Content-Type": "application/x-www-form-urlencoded"}, &basicAuth{clientID, clientSecret})
if err != nil {
t.Fatalf("Failed to create request, reason: %v", err)
}
w := httptest.NewRecorder()
server.HandleToken(w, r)
if w.Code != http.StatusOK {
t.Fail()
}
res, err := parseResponseBody(w.Body.Bytes())
if err != nil {
t.Fail()
}
assert.NotNil(t, res, "No valid JSON response was detected")
if res["error_description"] != nil {
t.Fatalf("JSON response indicated an error: %s", res["error_description"])
}
assert.NotNil(t, res["access_token"], "Access token was not provided")
assert.NotNil(t, res["refresh_token"], "Refresh token was not provided")
assert.NotNil(t, res["expires_in"], "Expiry info was not provided")
}
//TestPasswordAuth tests token refreshing method, expects a response with newly created access token in JSON format
func TestRefreshToken(t *testing.T) {
aurl := fmt.Sprintf("/token?grant_type=refresh_token&refresh_token=%s", url.QueryEscape(refreshToken))
r, err := newRequest("GET", aurl, "", nil, &basicAuth{clientID, clientSecret})
if err != nil {
t.Fatalf("Failed to create request, reason: %v", err)
}
w := httptest.NewRecorder()
server.HandleToken(w, r)
if w.Code != http.StatusOK {
t.Fail()
}
res, err := parseResponseBody(w.Body.Bytes())
if err != nil {
t.Fail()
}
assert.NotNil(t, res, "No valid JSON response was detected")
if res["error_description"] != nil {
t.Fatalf("JSON response indicated an error: %s", res["error_description"])
}
assert.NotNil(t, res["access_token"], "Access token was not provided")
assert.NotNil(t, res["refresh_token"], "Refresh token was not provided")
assert.NotNil(t, res["expires_in"], "Expiry info was not provided")
}
//TestTokenInfo invokes /appauth/tokenInfo and expects a JSON response having attributes compatible with Google Endpoints
func TestTokenInfo(t *testing.T) {
aurl := fmt.Sprintf("/appauth/tokenInfo?access_token=%s", url.QueryEscape(accessToken))
r, err := newRequest("GET", aurl, "", nil, &basicAuth{clientID, clientSecret})
if err != nil {
t.Fatalf("Failed to create request, reason: %v", err)
}
w := httptest.NewRecorder()
server.HandleAppAuthTokenInfo(w, r)
assert.Equal(t, http.StatusOK, w.Code, fmt.Sprintf("HTTP return code was %d, expected 200", w.Code))
res, err := parseResponseBody(w.Body.Bytes())
if err != nil {
t.Fail()
}
assert.NotNil(t, res, "No valid JSON response was detected")
if res["error_description"] != nil {
t.Fatalf("JSON response indicated an error: %s", res["error_description"])
}
assert.NotNil(t, res["user_id"], "Attribute user_id was not found")
assert.NotNil(t, res["email"], "Attribute email was not found")
assert.NotNil(t, res["verified_email"], "Attribute verified_email was not found")
assert.NotNil(t, res["issued_to"], "Attribute issued_to was not found")
assert.NotNil(t, res["audience"], "Attribute audience was not found")
assert.NotNil(t, res["scope"], "Attribute scope was not found")
assert.NotNil(t, res["scope"], "Attribute scope was not found")
assert.NotNil(t, res["expires_in"], "Attribute expires_in was not found")
assert.NotNil(t, res["access_type"], "Attribute access_type was not found")
}
func setupFakeClient(c context.Context) (*datastore.Key, error) {
cl := &ClientModel{
Id: clientID,
Name: "Test Client",
Secret: clientSecret,
GrantType: "password",
RedirectUri: redirectURI,
Active: true,
}
k := datastore.NewKey(c, ClientKind, clientID, 0, nil)
return datastore.Put(c, k, cl)
}
func setupFakeUser(c context.Context) (*datastore.Key, error) {
u := &User{
ID: userID,
FullName: "Test User",
Email: username,
Password: password,
CreatedAt: time.Now(),
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
u.PasswordHash = string(hash)
k := datastore.NewKey(c, UserKind, u.ID, 0, nil)
return datastore.Put(c, k, u)
}
func setupFakeAccessToken(c context.Context, userKey *datastore.Key) (*datastore.Key, error) {
ad := &AccessDataModel{
UserKey: userKey,
ClientID: clientID,
AuthorizationCode: "",
PreviousAccessToken: "fakepreviousaccesstoken",
AccessToken: accessToken,
RefreshToken: refreshToken,
ExpiresIn: 3600,
Scope: "email",
RedirectUri: redirectURI,
CreatedAt: time.Now(),
}
key := datastore.NewKey(c, AccessDataKind, ad.AccessToken, 0, nil)
return datastore.Put(c, key, ad)
}
func newRequest(method, url, body string, headers map[string]string, auth *basicAuth) (*http.Request, error) {
bodyBuf := bytes.NewBufferString(body)
r, err := inst.NewRequest(method, url, bodyBuf)
if err != nil {
return nil, err
}
if headers != nil {
for k := range headers {
r.Header.Add(k, headers[k])
}
}
if auth != nil {
r.SetBasicAuth(auth.Username, auth.Password)
}
return r, err
}
func newRequestAndContext(method, url, body string, headers map[string]string, auth *basicAuth) (*http.Request, context.Context, error) {
r, err := newRequest(method, url, body, headers, auth)
if err != nil {
return nil, nil, err
}
c := appengine.NewContext(r)
return r, c, nil
}
func parseResponseBody(body []byte) (map[string]interface{}, error) {
var response map[string]interface{}
err := json.Unmarshal(body, &response)
return response, err
}