-
Notifications
You must be signed in to change notification settings - Fork 657
Expand file tree
/
Copy pathanonymous_test.go
More file actions
335 lines (287 loc) · 10.3 KB
/
anonymous_test.go
File metadata and controls
335 lines (287 loc) · 10.3 KB
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
package api
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/gofrs/uuid"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/supabase/auth/internal/conf"
mail "github.com/supabase/auth/internal/mailer"
"github.com/supabase/auth/internal/models"
"github.com/supabase/auth/internal/storage"
)
type AnonymousTestSuite struct {
suite.Suite
API *API
Config *conf.GlobalConfiguration
}
func TestAnonymous(t *testing.T) {
cb := func(cfg *conf.GlobalConfiguration, _ *storage.Connection) {
if cfg != nil {
cfg.RateLimitAnonymousUsers = 5
}
}
api, config, err := setupAPIForTestWithCallback(cb)
require.NoError(t, err)
ts := &AnonymousTestSuite{
API: api,
Config: config,
}
defer api.db.Close()
suite.Run(t, ts)
}
func (ts *AnonymousTestSuite) SetupTest() {
models.TruncateAll(ts.API.db)
// Create anonymous user
params := &SignupParams{
Aud: ts.Config.JWT.Aud,
Provider: "anonymous",
}
u, err := params.ToUserModel(false)
require.NoError(ts.T(), err, "Error creating test user model")
require.NoError(ts.T(), ts.API.db.Create(u), "Error saving new anonymous test user")
}
func (ts *AnonymousTestSuite) TestAnonymousLogins() {
ts.Config.External.AnonymousUsers.Enabled = true
// Request body
var buffer bytes.Buffer
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
"data": map[string]interface{}{
"field": "foo",
},
}))
req := httptest.NewRequest(http.MethodPost, "/signup", &buffer)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
require.Equal(ts.T(), http.StatusOK, w.Code)
data := &AccessTokenResponse{}
require.NoError(ts.T(), json.NewDecoder(w.Body).Decode(&data))
assert.NotEmpty(ts.T(), data.User.ID)
assert.Equal(ts.T(), ts.Config.JWT.Aud, data.User.Aud)
assert.Empty(ts.T(), data.User.GetEmail())
assert.Empty(ts.T(), data.User.GetPhone())
assert.True(ts.T(), data.User.IsAnonymous)
assert.Equal(ts.T(), models.JSONMap(models.JSONMap{"field": "foo"}), data.User.UserMetaData)
}
func (ts *AnonymousTestSuite) TestConvertAnonymousUserToPermanent() {
ts.Config.External.AnonymousUsers.Enabled = true
ts.Config.Sms.TestOTP = conf.TestOTPMap{"1234567890": "000000", "1234560000": "000000"}
// test OTPs still require setting up an sms provider
ts.Config.Sms.Provider = "twilio"
ts.Config.Sms.Twilio.AccountSid = "fake-sid"
ts.Config.Sms.Twilio.AuthToken = "fake-token"
ts.Config.Sms.Twilio.MessageServiceSid = "fake-message-service-sid"
cases := []struct {
desc string
body map[string]interface{}
verificationType string
}{
{
desc: "convert anonymous user to permanent user with email",
body: map[string]interface{}{
"email": "test@example.com",
},
verificationType: "email_change",
},
{
desc: "convert anonymous user to permanent user with phone",
body: map[string]interface{}{
"phone": "1234567890",
},
verificationType: "phone_change",
},
{
desc: "convert anonymous user to permanent user with email & password",
body: map[string]interface{}{
"email": "test2@example.com",
"password": "test-password",
},
verificationType: "email_change",
},
{
desc: "convert anonymous user to permanent user with phone & password",
body: map[string]interface{}{
"phone": "1234560000",
"password": "test-password",
},
verificationType: "phone_change",
},
}
for _, c := range cases {
ts.Run(c.desc, func() {
// Request body
var buffer bytes.Buffer
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{}))
req := httptest.NewRequest(http.MethodPost, "/signup", &buffer)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
require.Equal(ts.T(), http.StatusOK, w.Code)
signupResponse := &AccessTokenResponse{}
require.NoError(ts.T(), json.NewDecoder(w.Body).Decode(&signupResponse))
// Add email to anonymous user
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(c.body))
req = httptest.NewRequest(http.MethodPut, "/user", &buffer)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", signupResponse.Token))
w = httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
require.Equal(ts.T(), http.StatusOK, w.Code)
// Check if anonymous user is still anonymous
user, err := models.FindUserByID(ts.API.db, signupResponse.User.ID)
require.NoError(ts.T(), err)
require.NotEmpty(ts.T(), user)
require.True(ts.T(), user.IsAnonymous)
// Check if user has a password set
if c.body["password"] != nil {
require.True(ts.T(), user.HasPassword())
}
switch c.verificationType {
case mail.EmailChangeVerification:
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
"token_hash": user.EmailChangeTokenNew,
"type": c.verificationType,
}))
case phoneChangeVerification:
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
"phone": user.PhoneChange,
"token": "000000",
"type": c.verificationType,
}))
}
req = httptest.NewRequest(http.MethodPost, "/verify", &buffer)
req.Header.Set("Content-Type", "application/json")
w = httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
require.Equal(ts.T(), http.StatusOK, w.Code)
data := &AccessTokenResponse{}
require.NoError(ts.T(), json.NewDecoder(w.Body).Decode(&data))
// User is a permanent user and not anonymous anymore
assert.Equal(ts.T(), signupResponse.User.ID, data.User.ID)
assert.Equal(ts.T(), ts.Config.JWT.Aud, data.User.Aud)
assert.False(ts.T(), data.User.IsAnonymous)
// User should have an identity
assert.Len(ts.T(), data.User.Identities, 1)
switch c.verificationType {
case mail.EmailChangeVerification:
assert.Equal(ts.T(), c.body["email"], data.User.GetEmail())
assert.Equal(ts.T(), models.JSONMap(models.JSONMap{"provider": "email", "providers": []interface{}{"email"}}), data.User.AppMetaData)
assert.NotEmpty(ts.T(), data.User.EmailConfirmedAt)
case phoneChangeVerification:
assert.Equal(ts.T(), c.body["phone"], data.User.GetPhone())
assert.Equal(ts.T(), models.JSONMap(models.JSONMap{"provider": "phone", "providers": []interface{}{"phone"}}), data.User.AppMetaData)
assert.NotEmpty(ts.T(), data.User.PhoneConfirmedAt)
}
})
}
}
func (ts *AnonymousTestSuite) TestRateLimitAnonymousSignups() {
var buffer bytes.Buffer
ts.Config.External.AnonymousUsers.Enabled = true
// It rate limits after 30 requests
for i := 0; i < int(ts.Config.RateLimitAnonymousUsers); i++ {
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{}))
req := httptest.NewRequest(http.MethodPost, "http://localhost/signup", &buffer)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("My-Custom-Header", "1.2.3.4")
w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
assert.Equal(ts.T(), http.StatusOK, w.Code)
}
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{}))
req := httptest.NewRequest(http.MethodPost, "http://localhost/signup", &buffer)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("My-Custom-Header", "1.2.3.4")
w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
assert.Equal(ts.T(), http.StatusTooManyRequests, w.Code)
// It ignores X-Forwarded-For by default
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{}))
req.Header.Set("X-Forwarded-For", "1.1.1.1")
w = httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
assert.Equal(ts.T(), http.StatusTooManyRequests, w.Code)
// It doesn't rate limit a new value for the limited header
req.Header.Set("My-Custom-Header", "5.6.7.8")
w = httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
assert.Equal(ts.T(), http.StatusBadRequest, w.Code)
}
func (ts *AnonymousTestSuite) TestAdminUpdateAnonymousUser() {
claims := &AccessTokenClaims{
Role: "supabase_admin",
}
adminJwt, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(ts.Config.JWT.Secret))
require.NoError(ts.T(), err)
u1, err := models.NewUser("", "", "", ts.Config.JWT.Aud, nil)
require.NoError(ts.T(), err)
u1.IsAnonymous = true
require.NoError(ts.T(), ts.API.db.Create(u1))
u2, err := models.NewUser("", "", "", ts.Config.JWT.Aud, nil)
require.NoError(ts.T(), err)
u2.IsAnonymous = true
require.NoError(ts.T(), ts.API.db.Create(u2))
cases := []struct {
desc string
userId uuid.UUID
body map[string]interface{}
expected map[string]interface{}
expectedIdentities int
}{
{
desc: "update anonymous user with email and email confirm true",
userId: u1.ID,
body: map[string]interface{}{
"email": "foo@example.com",
"email_confirm": true,
},
expected: map[string]interface{}{
"email": "foo@example.com",
"is_anonymous": false,
},
expectedIdentities: 1,
},
{
desc: "update anonymous user with email and email confirm false",
userId: u2.ID,
body: map[string]interface{}{
"email": "bar@example.com",
"email_confirm": false,
},
expected: map[string]interface{}{
"email": "bar@example.com",
"is_anonymous": true,
},
expectedIdentities: 1,
},
}
for _, c := range cases {
ts.Run(c.desc, func() {
// Request body
var buffer bytes.Buffer
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(c.body))
req := httptest.NewRequest(http.MethodPut, fmt.Sprintf("/admin/users/%s", c.userId), &buffer)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", adminJwt))
w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
require.Equal(ts.T(), http.StatusOK, w.Code)
var data models.User
require.NoError(ts.T(), json.NewDecoder(w.Body).Decode(&data))
require.NotNil(ts.T(), data)
require.Len(ts.T(), data.Identities, c.expectedIdentities)
actual := map[string]interface{}{
"email": data.GetEmail(),
"is_anonymous": data.IsAnonymous,
}
require.Equal(ts.T(), c.expected, actual)
})
}
}