/
connection_test.go
479 lines (401 loc) · 13.5 KB
/
connection_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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// Copyright 2021 FerretDB Inc.
//
// 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.
package users
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/x/mongo/driver/topology"
"github.com/FerretDB/FerretDB/integration"
"github.com/FerretDB/FerretDB/integration/setup"
"github.com/FerretDB/FerretDB/internal/types"
"github.com/FerretDB/FerretDB/internal/util/must"
"github.com/FerretDB/FerretDB/internal/util/testutil"
"github.com/FerretDB/FerretDB/internal/util/testutil/testtb"
)
func TestAuthentication(t *testing.T) {
t.Parallel()
s := setup.SetupWithOpts(t, &setup.SetupOpts{SetupUser: true})
ctx := s.Ctx
collection := s.Collection
db := collection.Database()
testCases := map[string]struct { //nolint:vet // for readability
username string
password string
updatePassword string // if true, the password will be updated to this one after the user is created.
mechanisms []string // mechanisms to use for creating user authentication
connectionMechanism string // if set, try to establish connection with this mechanism
userNotFound bool
wrongPassword bool
topologyError bool
errorMessage string
}{
"Success": {
username: "username", // when using the PLAIN mechanism we must use user "username"
password: "password",
mechanisms: []string{"PLAIN"},
connectionMechanism: "PLAIN",
},
"ScramSHA1": {
username: "scramsha1",
password: "password",
mechanisms: []string{"SCRAM-SHA-1"},
connectionMechanism: "SCRAM-SHA-1",
},
"ScramSHA256": {
username: "scramsha256",
password: "password",
mechanisms: []string{"SCRAM-SHA-256"},
connectionMechanism: "SCRAM-SHA-256",
},
"MultipleScramSHA1": {
username: "scramsha1multi",
password: "password",
mechanisms: []string{"SCRAM-SHA-1", "SCRAM-SHA-256"},
connectionMechanism: "SCRAM-SHA-1",
},
"MultipleScramSHA256": {
username: "scramsha256multi",
password: "password",
mechanisms: []string{"SCRAM-SHA-1", "SCRAM-SHA-256"},
connectionMechanism: "SCRAM-SHA-256",
},
"ScramSHA1Updated": {
username: "scramsha1updated",
password: "pass123",
updatePassword: "anotherpassword",
mechanisms: []string{"SCRAM-SHA-1"},
connectionMechanism: "SCRAM-SHA-1",
},
"ScramSHA256Updated": {
username: "scramsha256updated",
password: "pass123",
updatePassword: "anotherpassword",
mechanisms: []string{"SCRAM-SHA-256"},
connectionMechanism: "SCRAM-SHA-256",
},
"NotFoundUser": {
username: "notfound",
password: "something",
mechanisms: []string{"SCRAM-SHA-256"},
connectionMechanism: "SCRAM-SHA-256",
userNotFound: true,
errorMessage: "Authentication failed.",
topologyError: true,
},
"BadPassword": {
username: "baduser",
password: "something",
mechanisms: []string{"SCRAM-SHA-256"},
connectionMechanism: "SCRAM-SHA-256",
wrongPassword: true,
topologyError: true,
errorMessage: "Authentication failed.",
},
"MechanismNotSet": {
username: "user_mechanism_not_set",
password: "password",
mechanisms: []string{"SCRAM-SHA-256"},
connectionMechanism: "SCRAM-SHA-1",
topologyError: true,
errorMessage: "Unable to use SCRAM-SHA-1 based authentication for user without any SCRAM-SHA-1 credentials registered",
},
}
for name, tc := range testCases {
name, tc := name, tc
t.Run(name, func(tt *testing.T) {
tt.Parallel()
var t testtb.TB = tt
if !tc.userNotFound {
var (
// Use default mechanism for MongoDB and SCRAM-SHA-256 for FerretDB as SHA-1 won't be supported as it's deprecated.
mechanisms bson.A
hasPlain bool
)
if tc.mechanisms == nil {
if !setup.IsMongoDB(t) {
mechanisms = append(mechanisms, "SCRAM-SHA-1", "SCRAM-SHA-256")
}
} else {
mechanisms = bson.A{}
for _, mechanism := range tc.mechanisms {
switch mechanism {
case "PLAIN":
hasPlain = true
fallthrough
case "SCRAM-SHA-1", "SCRAM-SHA-256":
mechanisms = append(mechanisms, mechanism)
default:
t.Fatalf("unimplemented mechanism %s", mechanism)
}
}
}
if hasPlain {
setup.SkipForMongoDB(t, "PLAIN mechanism is not supported by MongoDB")
}
createPayload := bson.D{
{"createUser", tc.username},
{"roles", bson.A{}},
{"pwd", tc.password},
{"mechanisms", mechanisms},
}
err := db.RunCommand(ctx, createPayload).Err()
require.NoErrorf(t, err, "cannot create user")
}
if tc.updatePassword != "" {
updatePayload := bson.D{
{"updateUser", tc.username},
{"pwd", tc.updatePassword},
}
err := db.RunCommand(ctx, updatePayload).Err()
require.NoErrorf(t, err, "cannot update user")
}
password := tc.password
if tc.updatePassword != "" {
password = tc.updatePassword
}
if tc.wrongPassword {
password = "wrongpassword"
}
connectionMechanism := tc.connectionMechanism
credential := options.Credential{
AuthMechanism: connectionMechanism,
AuthSource: db.Name(),
Username: tc.username,
Password: password,
}
opts := options.Client().ApplyURI(s.MongoDBURI).SetAuth(credential)
client, err := mongo.Connect(ctx, opts)
require.NoError(t, err, "cannot connect to MongoDB")
// Ping to force connection to be established and tested.
err = client.Ping(ctx, nil)
if tc.errorMessage != "" {
require.Contains(t, err.Error(), tc.errorMessage, "expected error message")
}
if tc.topologyError {
var ce topology.ConnectionError
require.ErrorAs(t, err, &ce, "expected a connection error")
return
}
require.NoError(t, err, "cannot ping MongoDB")
connCollection := client.Database(db.Name()).Collection(collection.Name())
require.NotNil(t, connCollection, "cannot get collection")
r, err := connCollection.InsertOne(ctx, bson.D{{"ping", "pong"}})
require.NoError(t, err, "cannot insert document")
id := r.InsertedID.(primitive.ObjectID)
require.NotEmpty(t, id)
var result bson.D
err = connCollection.FindOne(ctx, bson.D{{"_id", id}}).Decode(&result)
require.NoError(t, err, "cannot find document")
assert.Equal(t, bson.D{{"_id", id}, {"ping", "pong"}}, result)
require.NoError(t, client.Disconnect(context.Background()))
})
}
}
func TestAuthenticationOnAuthenticatedConnection(t *testing.T) {
t.Parallel()
s := setup.SetupWithOpts(t, &setup.SetupOpts{SetupUser: true})
ctx, db := s.Ctx, s.Collection.Database()
username, password, mechanism := "testuser", "testpass", "SCRAM-SHA-256"
err := db.RunCommand(ctx, bson.D{
{"createUser", username},
{"roles", bson.A{}},
{"pwd", password},
{"mechanisms", bson.A{mechanism}},
}).Err()
require.NoError(t, err, "cannot create user")
credential := options.Credential{
AuthMechanism: mechanism,
AuthSource: db.Name(),
Username: username,
Password: password,
}
opts := options.Client().ApplyURI(s.MongoDBURI).SetAuth(credential)
client, err := mongo.Connect(ctx, opts)
require.NoError(t, err, "cannot connect to MongoDB")
t.Cleanup(func() {
require.NoError(t, client.Disconnect(ctx))
})
expectedUsers := must.NotFail(types.NewArray(must.NotFail(types.NewDocument("user", username, "db", db.Name()))))
db = client.Database(db.Name())
var res bson.D
err = db.RunCommand(ctx, bson.D{{"connectionStatus", 1}}).Decode(&res)
require.NoError(t, err)
actualAuth, err := integration.ConvertDocument(t, res).Get("authInfo")
require.NoError(t, err)
actualUsersV, err := actualAuth.(*types.Document).Get("authenticatedUsers")
require.NoError(t, err)
require.Equal(t, expectedUsers, actualUsersV.(*types.Array))
saslStart := bson.D{
{"saslStart", 1},
{"mechanism", mechanism},
{"payload", []byte("n,,n=testuser,r=Y0iJqJu58tGDrUdtqS7+m0oMe4sau3f6")},
{"autoAuthorize", 1},
{"options", bson.D{{"skipEmptyExchange", true}}},
}
err = db.RunCommand(ctx, saslStart).Decode(&res)
require.NoError(t, err)
err = db.RunCommand(ctx, bson.D{{"connectionStatus", 1}}).Decode(&res)
require.NoError(t, err)
actualAuth, err = integration.ConvertDocument(t, res).Get("authInfo")
require.NoError(t, err)
actualUsersV, err = actualAuth.(*types.Document).Get("authenticatedUsers")
require.NoError(t, err)
require.Equal(t, expectedUsers, actualUsersV.(*types.Array))
err = db.RunCommand(ctx, saslStart).Decode(&res)
require.NoError(t, err)
}
func TestAuthenticationLocalhostException(tt *testing.T) {
tt.Parallel()
t := setup.FailsForMongoDB(tt, "MongoDB is not connected via localhost")
s := setup.SetupWithOpts(t, &setup.SetupOpts{CollectionName: testutil.CollectionName(t)})
ctx := s.Ctx
collection := s.Collection
db := collection.Database()
opts := options.Client().ApplyURI(s.MongoDBURI)
clientNoAuth, err := mongo.Connect(ctx, opts)
require.NoError(t, err, "cannot connect to MongoDB")
t.Cleanup(func() {
require.NoError(t, clientNoAuth.Disconnect(ctx))
})
db = clientNoAuth.Database(db.Name())
username, password, mechanism := "testuser", "testpass", "SCRAM-SHA-256"
firstUser := bson.D{
{"createUser", username},
{"roles", bson.A{}},
{"pwd", password},
{"mechanisms", bson.A{mechanism}},
}
err = db.RunCommand(ctx, firstUser).Err()
require.NoError(t, err, "cannot create user")
secondUser := bson.D{
{"createUser", "anotheruser"},
{"roles", bson.A{}},
{"pwd", "anotherpass"},
{"mechanisms", bson.A{mechanism}},
}
err = db.RunCommand(ctx, secondUser).Err()
integration.AssertEqualCommandError(t, mongo.CommandError{
Code: 18,
Name: "AuthenticationFailed",
Message: "Authentication failed",
}, err)
credential := options.Credential{
AuthMechanism: mechanism,
AuthSource: db.Name(),
Username: username,
Password: password,
}
opts = options.Client().ApplyURI(s.MongoDBURI).SetAuth(credential)
client, err := mongo.Connect(ctx, opts)
require.NoError(t, err, "cannot connect to MongoDB")
t.Cleanup(func() {
require.NoError(t, client.Disconnect(ctx))
})
db = client.Database(db.Name())
err = db.RunCommand(ctx, secondUser).Err()
require.NoError(t, err, "cannot create user")
}
func TestAuthenticationEnableNewAuthPLAIN(tt *testing.T) {
tt.Parallel()
t := setup.FailsForMongoDB(tt, "PLAIN mechanism is not supported by MongoDB")
s := setup.SetupWithOpts(t, &setup.SetupOpts{SetupUser: true})
ctx, cName, db := s.Ctx, s.Collection.Name(), s.Collection.Database()
err := db.RunCommand(ctx, bson.D{
{"createUser", "plain-user"},
{"roles", bson.A{}},
{"pwd", "correct"},
{"mechanisms", bson.A{"PLAIN"}},
}).Err()
require.NoError(t, err, "cannot create user")
err = db.RunCommand(ctx, bson.D{
{"createUser", "scram-user"},
{"roles", bson.A{}},
{"pwd", "correct"},
{"mechanisms", bson.A{"SCRAM-SHA-1", "SCRAM-SHA-256"}},
}).Err()
require.NoError(t, err, "cannot create user")
testCases := map[string]struct {
username string
password string
mechanism string
err *mongo.CommandError
}{
"Success": {
username: "plain-user",
password: "correct",
mechanism: "PLAIN",
},
"BadPassword": {
username: "plain-user",
password: "wrong",
mechanism: "PLAIN",
err: &mongo.CommandError{
Code: 18,
Name: "AuthenticationFailed",
Message: "Authentication failed",
},
},
"NonExistentUser": {
username: "not-found-user",
password: "something",
mechanism: "PLAIN",
err: &mongo.CommandError{
Code: 18,
Name: "AuthenticationFailed",
Message: "Authentication failed",
},
},
"NonPLAINUser": {
username: "scram-user",
password: "correct",
mechanism: "PLAIN",
err: &mongo.CommandError{
Code: 334,
Name: "ErrMechanismUnavailable",
Message: "Unable to use PLAIN based authentication for user without any PLAIN credentials registered",
},
},
}
for name, tc := range testCases {
name, tc := name, tc
tt.Run(name, func(t *testing.T) {
t.Parallel()
credential := options.Credential{
AuthMechanism: tc.mechanism,
AuthSource: db.Name(),
Username: tc.username,
Password: tc.password,
}
opts := options.Client().ApplyURI(s.MongoDBURI).SetAuth(credential)
client, err := mongo.Connect(ctx, opts)
require.NoError(t, err, "cannot connect to MongoDB")
t.Cleanup(func() {
require.NoError(t, client.Disconnect(ctx))
})
c := client.Database(db.Name()).Collection(cName)
_, err = c.InsertOne(ctx, bson.D{{"ping", "pong"}})
if tc.err != nil {
integration.AssertEqualCommandError(t, *tc.err, err)
return
}
require.NoError(t, err, "cannot insert document")
})
}
}