-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
AbstractRESTInteraction.java
357 lines (313 loc) · 11.8 KB
/
AbstractRESTInteraction.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
/*
* Copyright (c) 2002-2017 "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.rest.security;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.IntNode;
import org.codehaus.jackson.node.LongNode;
import org.codehaus.jackson.node.ObjectNode;
import org.codehaus.jackson.node.TextNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Consumer;
import javax.ws.rs.core.HttpHeaders;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.HostnamePort;
import org.neo4j.io.fs.DefaultFileSystemAbstraction;
import org.neo4j.io.fs.FileSystemAbstraction;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.kernel.api.security.SecurityContext;
import org.neo4j.kernel.configuration.BoltConnector;
import org.neo4j.kernel.configuration.ConnectorPortRegister;
import org.neo4j.kernel.configuration.ssl.LegacySslPolicyConfig;
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.server.enterprise.helpers.EnterpriseServerBuilder;
import org.neo4j.server.helpers.CommunityServerBuilder;
import org.neo4j.server.rest.domain.JsonHelper;
import org.neo4j.server.rest.domain.JsonParseException;
import org.neo4j.server.security.enterprise.auth.EnterpriseAuthAndUserManager;
import org.neo4j.server.security.enterprise.auth.EnterpriseUserManager;
import org.neo4j.server.security.enterprise.auth.NeoInteractionLevel;
import org.neo4j.test.server.HTTP;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.neo4j.kernel.api.security.AuthToken.newBasicAuthToken;
import static org.neo4j.kernel.configuration.BoltConnector.EncryptionLevel.OPTIONAL;
abstract class AbstractRESTInteraction extends CommunityServerTestBase implements NeoInteractionLevel<RESTSubject>
{
private ConnectorPortRegister connectorPortRegister;
abstract String commitPath();
abstract void consume( Consumer<ResourceIterator<Map<String,Object>>> resultConsumer, JsonNode data );
abstract HTTP.RawPayload constructQuery( String query );
protected abstract HTTP.Response authenticate( String principalCredentials );
static final String POST = "POST";
private EnterpriseAuthManager authManager;
AbstractRESTInteraction( Map<String,String> config ) throws IOException
{
CommunityServerBuilder builder = EnterpriseServerBuilder.serverOnRandomPorts();
builder = builder
.withProperty( new BoltConnector( "bolt" ).type.name(), "BOLT" )
.withProperty( new BoltConnector( "bolt" ).enabled.name(), "true" )
.withProperty( new BoltConnector( "bolt" ).encryption_level.name(), OPTIONAL.name() )
.withProperty( LegacySslPolicyConfig.tls_key_file.name(),
NeoInteractionLevel.tempPath( "key", ".key" ) )
.withProperty( LegacySslPolicyConfig.tls_certificate_file.name(),
NeoInteractionLevel.tempPath( "cert", ".cert" ) )
.withProperty( GraphDatabaseSettings.auth_enabled.name(), Boolean.toString( true ) );
for ( Map.Entry<String,String> entry : config.entrySet() )
{
builder = builder.withProperty( entry.getKey(), entry.getValue() );
}
this.server = builder.build();
this.server.start();
authManager = this.server.getDependencyResolver().resolveDependency( EnterpriseAuthManager.class );
connectorPortRegister = server.getDependencyResolver().resolveDependency( ConnectorPortRegister.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 server.getDatabase().getGraph();
}
@Override
public FileSystemAbstraction fileSystem()
{
return new DefaultFileSystemAbstraction();
}
@Override
public InternalTransaction beginLocalTransactionAsUser( RESTSubject subject, KernelTransaction.Type txType )
throws Throwable
{
SecurityContext securityContext = authManager.login( newBasicAuthToken( subject.username, subject.password ) );
return getLocalGraph().beginTransaction( txType, securityContext );
}
@Override
public String executeQuery( RESTSubject subject, String call, Map<String,Object> params,
Consumer<ResourceIterator<Map<String, Object>>> resultConsumer )
{
HTTP.RawPayload payload = constructQuery( call );
HTTP.Response response = HTTP.withHeaders( HttpHeaders.AUTHORIZATION, subject.principalCredentials )
.request( POST, commitURL(), payload );
try
{
String error = parseErrorMessage( response );
if ( !error.isEmpty() )
{
return error;
}
consume( resultConsumer, JsonHelper.jsonNode( response.rawContent() ) );
}
catch ( JsonParseException e )
{
fail( "Unexpected error parsing Json!" );
}
return "";
}
@Override
public RESTSubject login( String username, String password ) throws Exception
{
String principalCredentials = challengeResponse( username, password );
return new RESTSubject( username, password, principalCredentials );
}
@Override
public void logout( RESTSubject subject )
{
}
@Override
public void updateAuthToken( RESTSubject subject, String username, String password )
{
subject.principalCredentials = challengeResponse( username, password );
}
@Override
public String nameOf( RESTSubject subject )
{
return subject.username;
}
@Override
public void tearDown()
{
if ( server != null )
{
server.stop();
}
}
@Override
public void assertAuthenticated( RESTSubject subject )
{
HTTP.Response authenticate = authenticate( subject.principalCredentials );
assertThat( authenticate.rawContent(), authenticate.status(), equalTo( 200 ) );
}
@Override
public void assertPasswordChangeRequired( RESTSubject subject ) throws Exception
{
HTTP.Response response = authenticate( subject.principalCredentials );
assertThat( response.status(), equalTo( 403 ) );
assertThat( parseErrorMessage( response ), containsString( "User is required to change their password." ) );
}
@Override
public void assertInitFailed( RESTSubject subject )
{
assertThat( authenticate( subject.principalCredentials ).status(), not( equalTo( 200 ) ) );
}
@Override
public void assertSessionKilled( RESTSubject subject )
{
// There is no session that could have been killed
}
@Override
public String getConnectionProtocol()
{
return "http";
}
@Override
public HostnamePort lookupConnector( String connectorKey )
{
return connectorPortRegister.getLocalAddress( connectorKey );
}
private String parseErrorMessage( HTTP.Response response )
{
try
{
JsonNode data = JsonHelper.jsonNode( response.rawContent() );
if ( data.has( "errors" ) && data.get( "errors" ).has( 0 ) )
{
JsonNode firstError = data.get( "errors" ).get( 0 );
if ( firstError.has( "message" ) )
{
return firstError.get( "message" ).asText();
}
}
}
catch ( JsonParseException e )
{
fail( "Unexpected error parsing Json!" );
}
return "";
}
String commitURL()
{
return server.baseUri().resolve( commitPath() ).toString();
}
abstract class AbstractRESTResult implements ResourceIterator<Map<String,Object>>
{
private JsonNode data;
private JsonNode columns;
private int index;
AbstractRESTResult( JsonNode fullResult )
{
this.data = fullResult.get( "data" );
this.columns = fullResult.get( "columns" );
}
@Override
public void close()
{
index = data.size();
}
@Override
public boolean hasNext()
{
return index < data.size();
}
@Override
public Map<String,Object> next()
{
JsonNode row = getRow( data, index++ );
TreeMap<String,Object> map = new TreeMap<>();
for ( int i = 0; i < columns.size(); i++ )
{
String key = columns.get( i ).asText();
Object value = getValue( row.get( i ) );
map.put( key, value );
}
return map;
}
protected abstract JsonNode getRow( JsonNode data, int i );
}
private Object getValue( JsonNode valueNode )
{
Object value;
if ( valueNode instanceof TextNode )
{
value = valueNode.asText();
}
else if ( valueNode instanceof ObjectNode )
{
value = mapValue( valueNode.getFieldNames(), valueNode );
}
else if ( valueNode instanceof ArrayNode )
{
ArrayNode aNode = (ArrayNode) valueNode;
ArrayList<String> listValue = new ArrayList<>( aNode.size() );
for ( int j = 0; j < aNode.size(); j++ )
{
listValue.add( aNode.get( j ).asText() );
}
value = listValue;
}
else if ( valueNode instanceof IntNode )
{
value = valueNode.getIntValue();
}
else if ( valueNode instanceof LongNode )
{
value = valueNode.getLongValue();
}
else if ( valueNode.isNull() )
{
return null;
}
else
{
throw new RuntimeException( String.format(
"Unhandled REST value type '%s'. Need String (TextNode), List (ArrayNode), Object (ObjectNode), " +
"long (LongNode), or int (IntNode).", valueNode.getClass()
) );
}
return value;
}
private Map<String,Object> mapValue( Iterator<String> columns, JsonNode node )
{
TreeMap<String,Object> map = new TreeMap<>();
while ( columns.hasNext() )
{
String key = columns.next();
Object value = getValue( node.get( key ) );
map.put( key, value );
}
return map;
}
}