1+ /*
2+ * Copyright (c) 2008-2014 MongoDB, Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+ package com .mongodb .connection ;
18+
19+ import com .mongodb .MongoCredential ;
20+ import com .mongodb .MongoSecurityException ;
21+ import com .mongodb .ServerAddress ;
22+ import com .mongodb .protocol .message .RequestMessage ;
23+ import org .bson .io .InputBuffer ;
24+ import org .junit .Before ;
25+ import org .junit .Test ;
26+
27+ import java .util .List ;
28+
29+ import static org .junit .Assert .assertEquals ;
30+ import static org .junit .Assert .fail ;
31+
32+ public class X509AuthenticatorUnitTest {
33+ private TestInternalConnection connection ;
34+ private MongoCredential credential ;
35+ private X509Authenticator subject ;
36+
37+ @ Before
38+ public void before () {
39+ connection = new TestInternalConnection ("1" , new ServerAddress ("localhost" , 27017 ));
40+ credential = MongoCredential .createMongoX509Credential (
41+ "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US" );
42+ subject = new X509Authenticator (this .credential , this .connection );
43+ }
44+
45+ @ Test
46+ public void testFailedAuthentication () {
47+ int currentRequestId = RequestMessage .getCurrentGlobalId ();
48+ ResponseBuffers authenticateReply = MessageHelper .buildSuccessfulReply (
49+ currentRequestId ,
50+ "{ok: 0}" );
51+
52+ connection .enqueueReply (authenticateReply );
53+
54+ try {
55+ subject .authenticate ();
56+ fail ();
57+ } catch (MongoSecurityException e ) {
58+ // all good
59+ }
60+ }
61+
62+ @ Test
63+ public void testSuccessfulAuthentication () {
64+ int currentRequestId = RequestMessage .getCurrentGlobalId ();
65+ ResponseBuffers authenticateReply = MessageHelper .buildSuccessfulReply (
66+ currentRequestId ,
67+ "{ok: 1}" );
68+
69+ connection .enqueueReply (authenticateReply );
70+
71+ subject .authenticate ();
72+
73+ List <InputBuffer > sent = connection .getSent ();
74+ String command = MessageHelper .decodeCommandAsJson (sent .get (0 ));
75+ String expectedCommand = "{ \" authenticate\" : 1, "
76+ + "\" user\" : \" CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US\" , "
77+ + "\" mechanism\" : \" MONGODB-X509\" }" ;
78+
79+ assertEquals (expectedCommand , command );
80+ }
81+ }
0 commit comments