-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
BoltInteraction.java
365 lines (327 loc) · 12.9 KB
/
BoltInteraction.java
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
/*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.server.security.enterprise.auth;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.neo4j.bolt.security.auth.AuthenticationException;
import org.neo4j.bolt.v1.messaging.message.FailureMessage;
import org.neo4j.bolt.v1.messaging.message.InitMessage;
import org.neo4j.bolt.v1.messaging.message.PullAllMessage;
import org.neo4j.bolt.v1.messaging.message.RecordMessage;
import org.neo4j.bolt.v1.messaging.message.ResponseMessage;
import org.neo4j.bolt.v1.messaging.message.RunMessage;
import org.neo4j.bolt.v1.messaging.message.SuccessMessage;
import org.neo4j.bolt.v1.transport.integration.Neo4jWithSocket;
import org.neo4j.bolt.v1.transport.integration.TransportTestUtil;
import org.neo4j.bolt.v1.transport.socket.client.SocketConnection;
import org.neo4j.bolt.v1.transport.socket.client.TransportConnection;
import org.neo4j.function.Factory;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.graphdb.mockfs.EphemeralFileSystemAbstraction;
import org.neo4j.helpers.HostnamePort;
import org.neo4j.io.fs.FileSystemAbstraction;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.kernel.api.exceptions.Status;
import org.neo4j.kernel.api.security.AuthenticationResult;
import org.neo4j.kernel.api.security.SecurityContext;
import org.neo4j.kernel.enterprise.api.security.EnterpriseAuthManager;
import org.neo4j.kernel.impl.coreapi.InternalTransaction;
import org.neo4j.kernel.impl.factory.GraphDatabaseFacade;
import org.neo4j.test.TestEnterpriseGraphDatabaseFactory;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.neo4j.bolt.v1.messaging.message.ResetMessage.reset;
import static org.neo4j.helpers.collection.MapUtil.map;
import static org.neo4j.kernel.api.security.AuthToken.BASIC_SCHEME;
import static org.neo4j.kernel.api.security.AuthToken.CREDENTIALS;
import static org.neo4j.kernel.api.security.AuthToken.NATIVE_REALM;
import static org.neo4j.kernel.api.security.AuthToken.PRINCIPAL;
import static org.neo4j.kernel.api.security.AuthToken.REALM_KEY;
import static org.neo4j.kernel.api.security.AuthToken.SCHEME_KEY;
import static org.neo4j.kernel.api.security.AuthToken.newBasicAuthToken;
class BoltInteraction implements NeoInteractionLevel<BoltInteraction.BoltSubject>
{
protected final HostnamePort address = new HostnamePort( "localhost:7687" );
private final Factory<TransportConnection> connectionFactory = SocketConnection::new;
private final Neo4jWithSocket server;
private Map<String,BoltSubject> subjects = new HashMap<>();
private FileSystemAbstraction fileSystem;
private EnterpriseAuthManager authManager;
BoltInteraction( Map<String, String> config ) throws IOException
{
this(config, EphemeralFileSystemAbstraction::new);
}
BoltInteraction( Map<String, String> config, Supplier<FileSystemAbstraction> fileSystemSupplier ) throws IOException
{
TestEnterpriseGraphDatabaseFactory factory = new TestEnterpriseGraphDatabaseFactory();
fileSystem = fileSystemSupplier.get();
server = new Neo4jWithSocket( getClass(),
factory,
() -> fileSystem,
settings -> {
settings.put( GraphDatabaseSettings.auth_enabled.name(), "true" );
settings.putAll( config );
} );
server.ensureDatabase( r -> {} );
GraphDatabaseFacade db = (GraphDatabaseFacade) server.graphDatabaseService();
authManager = db.getDependencyResolver().resolveDependency( EnterpriseAuthManager.class );
}
@Override
public EnterpriseUserManager getLocalUserManager() throws Exception
{
if ( authManager instanceof EnterpriseAuthAndUserManager )
{
return ((EnterpriseAuthAndUserManager) authManager).getUserManager();
}
throw new Exception( "The used configuration does not have a user manager" );
}
@Override
public GraphDatabaseFacade getLocalGraph()
{
return (GraphDatabaseFacade) server.graphDatabaseService();
}
@Override
public FileSystemAbstraction fileSystem()
{
return fileSystem;
}
@Override
public InternalTransaction beginLocalTransactionAsUser( BoltSubject subject, KernelTransaction.Type txType )
throws Throwable
{
SecurityContext securityContext = authManager.login( newBasicAuthToken( subject.username, subject.password ) );
return getLocalGraph().beginTransaction( txType, securityContext );
}
@Override
public String executeQuery( BoltSubject subject, String call, Map<String,Object> params,
Consumer<ResourceIterator<Map<String,Object>>> resultConsumer )
{
if ( params == null )
{
params = Collections.emptyMap();
}
try
{
subject.client.send( TransportTestUtil.chunk( RunMessage.run( call, params ), PullAllMessage.pullAll() ) );
resultConsumer.accept( collectResults( subject.client ) );
return "";
}
catch (Exception e)
{
return e.getMessage();
}
}
@Override
public BoltSubject login( String username, String password ) throws Exception
{
BoltSubject subject = subjects.get( username );
if ( subject == null )
{
subject = new BoltSubject( connectionFactory.newInstance(), username, password );
subjects.put( username, subject );
}
else
{
subject.client.disconnect();
subject.client = connectionFactory.newInstance();
}
subject.client.connect( address ).send( TransportTestUtil.acceptedVersions( 1, 0, 0, 0 ) )
.send( TransportTestUtil.chunk( InitMessage.init( "TestClient/1.1",
map( REALM_KEY, NATIVE_REALM, PRINCIPAL, username, CREDENTIALS, password,
SCHEME_KEY, BASIC_SCHEME ) ) ) );
assertThat( subject.client, TransportTestUtil.eventuallyReceives( new byte[]{0, 0, 0, 1} ) );
subject.setLoginResult( TransportTestUtil.receiveOneResponseMessage( subject.client ) );
return subject;
}
@Override
public void logout( BoltSubject subject ) throws Exception
{
subject.client.disconnect();
subject.client = connectionFactory.newInstance();
}
@Override
public void updateAuthToken( BoltSubject subject, String username, String password )
{
}
@Override
public String nameOf( BoltSubject subject )
{
return subject.username;
}
@Override
public void tearDown() throws Throwable
{
for ( BoltSubject subject : subjects.values() )
{
subject.client.disconnect();
}
subjects.clear();
server.graphDatabaseService().shutdown();
fileSystem.close();
}
@Override
public void assertAuthenticated( BoltSubject subject )
{
assertTrue( "Should be authenticated", subject.isAuthenticated() );
}
@Override
public void assertPasswordChangeRequired( BoltSubject subject )
{
assertTrue( "Should need to change password", subject.passwordChangeRequired() );
}
@Override
public void assertInitFailed( BoltSubject subject )
{
assertFalse( "Should not be authenticated", subject.isAuthenticated() );
}
@Override
public void assertSessionKilled( BoltSubject subject )
{
assertThat( subject.client, TransportTestUtil.eventuallyDisconnects() );
}
@Override
public String getConnectionDetails()
{
return "bolt-session";
}
private static BoltResult collectResults( TransportConnection client ) throws Exception
{
ResponseMessage message = TransportTestUtil.receiveOneResponseMessage( client );
List<String> fieldNames = new ArrayList<>();
List<Map<String,Object>> result = new ArrayList<>();
if ( message instanceof SuccessMessage )
{
Map<String,Object> metadata = ((SuccessMessage) message).meta();
fieldNames = (List<String>) metadata.get( "fields" );
}
else if ( message instanceof FailureMessage )
{
FailureMessage failMessage = ((FailureMessage) message);
// drain ignoredMessage, ack failure, get successMessage
TransportTestUtil.receiveOneResponseMessage( client );
client.send( TransportTestUtil.chunk( reset() ) );
TransportTestUtil.receiveOneResponseMessage( client );
throw new AuthenticationException( failMessage.status(), failMessage.message() );
}
do
{
message = TransportTestUtil.receiveOneResponseMessage( client );
if ( message instanceof RecordMessage )
{
Object[] row = ((RecordMessage) message).record().fields();
Map<String,Object> rowMap = new HashMap<>();
for ( int i = 0; i < row.length; i++ )
{
rowMap.put( fieldNames.get( i ), row[i] );
}
result.add( rowMap );
}
}
while ( !(message instanceof SuccessMessage) && !(message instanceof FailureMessage) );
if ( message instanceof FailureMessage )
{
FailureMessage failMessage = ((FailureMessage) message);
// ack failure, get successMessage
client.send( TransportTestUtil.chunk( reset() ) );
TransportTestUtil.receiveOneResponseMessage( client );
throw new AuthenticationException( failMessage.status(), failMessage.message() );
}
return new BoltResult( result );
}
static class BoltSubject
{
TransportConnection client;
String username;
String password;
AuthenticationResult loginResult = AuthenticationResult.FAILURE;
BoltSubject( TransportConnection client, String username, String password )
{
this.client = client;
this.username = username;
this.password = password;
}
void setLoginResult( ResponseMessage result )
{
if ( result instanceof SuccessMessage )
{
Map<String,Object> meta = ((SuccessMessage) result).meta();
if ( meta.containsKey( "credentials_expired" ) && meta.get( "credentials_expired" ).equals( true ) )
{
loginResult = AuthenticationResult.PASSWORD_CHANGE_REQUIRED;
}
else
{
loginResult = AuthenticationResult.SUCCESS;
}
}
else if ( result instanceof FailureMessage )
{
loginResult = AuthenticationResult.FAILURE;
Status status = ((FailureMessage) result).status();
if ( status.equals( Status.Security.AuthenticationRateLimit ) )
{
loginResult = AuthenticationResult.TOO_MANY_ATTEMPTS;
}
}
}
boolean isAuthenticated()
{
return loginResult.equals( AuthenticationResult.SUCCESS );
}
boolean passwordChangeRequired()
{
return loginResult.equals( AuthenticationResult.PASSWORD_CHANGE_REQUIRED );
}
}
static class BoltResult implements ResourceIterator<Map<String,Object>>
{
private int index = 0;
private List<Map<String,Object>> data;
BoltResult( List<Map<String,Object>> data )
{
this.data = data;
}
@Override
public void close()
{
index = data.size();
}
@Override
public boolean hasNext()
{
return index < data.size();
}
@Override
public Map<String,Object> next()
{
Map<String,Object> row = data.get( index );
index++;
return row;
}
}
}