-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
AuthProceduresIT.java
365 lines (318 loc) · 13 KB
/
AuthProceduresIT.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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.server.security.auth;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.config.Setting;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.graphdb.mockfs.EphemeralFileSystemAbstraction;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.kernel.api.security.exception.InvalidArgumentsException;
import org.neo4j.kernel.api.security.exception.InvalidAuthTokenException;
import org.neo4j.kernel.internal.GraphDatabaseAPI;
import org.neo4j.test.TestGraphDatabaseBuilder;
import org.neo4j.test.TestGraphDatabaseFactory;
import static junit.framework.TestCase.fail;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.neo4j.helpers.collection.MapUtil.map;
import static org.neo4j.kernel.api.security.AuthenticationResult.PASSWORD_CHANGE_REQUIRED;
public class AuthProceduresIT
{
private static final String PWD_CHANGE = PASSWORD_CHANGE_REQUIRED.name().toLowerCase();
protected GraphDatabaseAPI db;
private EphemeralFileSystemAbstraction fs;
private BasicAuthManager authManager;
private BasicAuthSubject admin;
//---------- change password -----------
@Test
public void shouldChangePassword() throws Throwable
{
// Given
assertEmpty( admin, "CALL dbms.changePassword('abc')" );
assert( authManager.getUser( "neo4j" ).credentials().matchesPassword( "abc" ) );
}
@Test
public void shouldNotChangeOwnPasswordIfNewPasswordInvalid() throws Exception
{
assertFail( admin, "CALL dbms.changePassword( '' )", "A password cannot be empty." );
assertFail( admin, "CALL dbms.changePassword( 'neo4j' )", "Old password and new password cannot be the same." );
}
//---------- create user -----------
@Test
public void shouldCreateUser() throws Exception
{
assertEmpty( admin, "CALL dbms.security.createUser('andres', '123', true)" );
try
{
assertThat( authManager.getUser( "andres" ).passwordChangeRequired(), equalTo( true ) );
}
catch ( Throwable t )
{
fail( "Expected no exception!" );
}
}
@Test
public void shouldCreateUserWithNoPasswordChange() throws Exception
{
assertEmpty( admin, "CALL dbms.security.createUser('andres', '123', false)" );
try
{
assertThat( authManager.getUser( "andres" ).passwordChangeRequired(), equalTo( false ) );
}
catch ( Throwable t )
{
fail( "Expected no exception!" );
}
}
@Test
public void shouldCreateUserWithDefault() throws Exception
{
assertEmpty( admin, "CALL dbms.security.createUser('andres', '123')" );
try
{
assertThat( authManager.getUser( "andres" ).passwordChangeRequired(), equalTo( true ) );
}
catch ( Throwable t )
{
fail( "Expected no exception!" );
}
}
@Test
public void shouldNotCreateUserIfInvalidUsername() throws Exception
{
assertFail( admin, "CALL dbms.security.createUser('', '1234', true)", "The provided user name is empty." );
assertFail( admin, "CALL dbms.security.createUser('&%ss!', '1234', true)",
"User name '&%ss!' contains illegal characters." );
assertFail( admin, "CALL dbms.security.createUser('&%ss!', '', true)", "User name '&%ss!' contains illegal characters." );
}
@Test
public void shouldNotCreateUserIfInvalidPassword() throws Exception
{
assertFail( admin, "CALL dbms.security.createUser('andres', '', true)", "A password cannot be empty." );
}
@Test
public void shouldNotCreateExistingUser() throws Exception
{
assertFail( admin, "CALL dbms.security.createUser('neo4j', '1234', true)",
"The specified user 'neo4j' already exists" );
assertFail( admin, "CALL dbms.security.createUser('neo4j', '', true)", "A password cannot be empty." );
}
//---------- delete user -----------
@Test
public void shouldDeleteUser() throws Exception
{
authManager.newUser( "andres", "123", false );
assertEmpty( admin, "CALL dbms.security.deleteUser('andres')" );
try
{
authManager.getUser( "andres" );
fail("Andres should no longer exist, expected exception.");
}
catch ( InvalidArgumentsException e )
{
assertThat( e.getMessage(), containsString( "User 'andres' does not exist." ) );
}
catch ( Throwable t )
{
assertThat( t.getClass(), equalTo( InvalidArgumentsException.class ) );
}
}
@Test
public void shouldNotDeleteNonExistentUser() throws Exception
{
assertFail( admin, "CALL dbms.security.deleteUser('nonExistentUser')", "User 'nonExistentUser' does not exist" );
}
//---------- list users -----------
@Test
public void shouldListUsers() throws Exception
{
authManager.newUser( "andres", "123", false );
assertSuccess( admin, "CALL dbms.security.listUsers() YIELD username",
r -> assertKeyIs( r, "username", "neo4j", "andres" ) );
}
@Test
public void shouldReturnUsersWithFlags() throws Exception
{
authManager.newUser( "andres", "123", false );
Map<String,Object> expected = map(
"neo4j", listOf( PWD_CHANGE ),
"andres", listOf()
);
assertSuccess( admin, "CALL dbms.security.listUsers()",
r -> assertKeyIsMap( r, "username", "flags", expected ) );
}
@Test
public void shouldShowCurrentUser() throws Exception
{
assertSuccess( admin, "CALL dbms.security.showCurrentUser()",
r -> assertKeyIsMap( r, "username", "flags", map( "neo4j", listOf( PWD_CHANGE ) ) ) );
authManager.newUser( "andres", "123", false );
BasicAuthSubject andres = login( "andres", "123" );
assertSuccess( andres, "CALL dbms.security.showCurrentUser()",
r -> assertKeyIsMap( r, "username", "flags", map( "andres", listOf() ) ) );
}
//---------- utility -----------
@Before
public void setup() throws InvalidAuthTokenException, IOException
{
fs = new EphemeralFileSystemAbstraction();
db = (GraphDatabaseAPI) createGraphDatabase( fs );
authManager = db.getDependencyResolver().resolveDependency( BasicAuthManager.class );
admin = login( "neo4j", "neo4j" );
}
@After
public void cleanup() throws Exception
{
db.shutdown();
fs.shutdown();
}
private GraphDatabaseService createGraphDatabase( EphemeralFileSystemAbstraction fs ) throws IOException
{
removePreviousAuthFile();
Map<Setting<?>, String> settings = new HashMap<>();
settings.put( GraphDatabaseSettings.auth_enabled, "true" );
settings.put( GraphDatabaseSettings.auth_manager, "basic-auth-manager" );
TestGraphDatabaseBuilder graphDatabaseFactory = (TestGraphDatabaseBuilder) new TestGraphDatabaseFactory()
.setFileSystem( fs )
.newImpermanentDatabaseBuilder()
.setConfig( GraphDatabaseSettings.auth_enabled, "true" )
.setConfig( GraphDatabaseSettings.auth_manager, "basic-auth-manager" );
return graphDatabaseFactory.newGraphDatabase();
}
private void removePreviousAuthFile() throws IOException
{
Path file = Paths.get( "target/test-data/impermanent-db/data/dbms/auth" );
if ( Files.exists( file ) )
{
Files.delete( file );
}
}
private BasicAuthSubject login( String username, String password ) throws InvalidAuthTokenException
{
return authManager.login( SecurityTestUtils.authToken( username, password ) );
}
private void assertEmpty( BasicAuthSubject subject, String query )
{
assertThat(
execute( subject, query, r -> { assert(!r.hasNext() ); } ),
equalTo( "" ) );
}
private void assertFail( BasicAuthSubject subject, String query, String partOfErrorMsg )
{
assertThat(
execute( subject, query, r -> { assert(!r.hasNext() ); } ),
containsString( partOfErrorMsg ) );
}
private void assertSuccess( BasicAuthSubject subject, String query,
Consumer<ResourceIterator<Map<String,Object>>> resultConsumer )
{
assertThat(
execute( subject, query, resultConsumer ),
equalTo( "" ) );
}
private String execute( BasicAuthSubject subject, String query,
Consumer<ResourceIterator<Map<String, Object>>> resultConsumer )
{
try ( Transaction tx = db.beginTransaction( KernelTransaction.Type.implicit, subject ) )
{
resultConsumer.accept( db.execute( query ) );
tx.success();
return "";
}
catch ( Exception e )
{
return e.getMessage();
}
}
private List<Object> getObjectsAsList( ResourceIterator<Map<String,Object>> r, String key )
{
return r.stream().map( s -> s.get( key ) ).collect( Collectors.toList() );
}
private void assertKeyIs( ResourceIterator<Map<String,Object>> r, String key, String... items )
{
assertKeyIsArray( r, key, items );
}
private void assertKeyIsArray( ResourceIterator<Map<String,Object>> r, String key, String[] items )
{
List<Object> results = getObjectsAsList( r, key );
assertEquals( Arrays.asList( items ).size(), results.size() );
Assert.assertThat( results, containsInAnyOrder( items ) );
}
protected String[] with( String[] strs, String... moreStr )
{
return Stream.concat( Arrays.stream(strs), Arrays.stream( moreStr ) ).toArray( String[]::new );
}
private List<String> listOf( String... values )
{
return Stream.of( values ).collect( Collectors.toList() );
}
@SuppressWarnings( "unchecked" )
public static void assertKeyIsMap( ResourceIterator<Map<String, Object>> r, String keyKey, String valueKey, Map<String,Object> expected )
{
List<Map<String, Object>> result = r.stream().collect( Collectors.toList() );
assertEquals( "Results for should have size " + expected.size() + " but was " + result.size(),
expected.size(), result.size() );
for ( Map<String, Object> row : result )
{
String key = (String) row.get( keyKey );
assertTrue( "Unexpected key '" + key + "'", expected.containsKey( key ) );
assertTrue( "Value key '" + valueKey + "' not found in results", row.containsKey( valueKey ) );
Object objectValue = row.get( valueKey );
if ( objectValue instanceof List )
{
List<String> value = (List<String>) objectValue;
List<String> expectedValues = (List<String>) expected.get( key );
assertEquals( "Results for '" + key + "' should have size " + expectedValues.size() + " but was " +
value.size(), value.size(), expectedValues.size() );
assertThat( value, containsInAnyOrder( expectedValues.toArray() ) );
}
else
{
String value = objectValue.toString();
String expectedValue = expected.get( key ).toString();
assertTrue(
String.format( "Wrong value for '%s', expected '%s', got '%s'", key, expectedValue, value),
value.equals( expectedValue )
);
}
}
}
}