summaryrefslogtreecommitdiff
path: root/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java
blob: cba6058426ecef5facc48b7946be9c161af2179d (plain)
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
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.qpid.server.security.auth.manager;

import static org.apache.qpid.server.security.auth.AuthenticatedPrincipalTestHelper.assertOnlyContainsWrapped;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.security.Principal;
import java.util.List;
import java.util.Map;

import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import javax.security.sasl.SaslServerFactory;

import org.apache.qpid.server.configuration.IllegalConfigurationException;
import org.apache.qpid.server.security.auth.AuthenticationResult;
import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus;
import org.apache.qpid.server.security.auth.UsernamePrincipal;
import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase;
import org.apache.qpid.server.security.auth.database.PrincipalDatabase;
import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser;
import org.apache.qpid.test.utils.QpidTestCase;

/**
 * Tests the public methods of PrincipalDatabaseAuthenticationManager.
 *
 */
public class PrincipalDatabaseAuthenticationManagerTest extends QpidTestCase
{
    private static final String LOCALHOST = "localhost";
    private static final String MOCK_MECH_NAME = "MOCK-MECH-NAME";
    private static final UsernamePrincipal PRINCIPAL = new UsernamePrincipal("guest");

    private AuthenticationManager _manager = null; // Class under test
    private PrincipalDatabase _principalDatabase;
    private String _passwordFileLocation;

    @Override
    public void setUp() throws Exception
    {
        super.setUp();
        _passwordFileLocation = TMP_FOLDER + File.separator + PrincipalDatabaseAuthenticationManagerTest.class.getSimpleName() + "-" + getName();
        deletePasswordFileIfExists();
    }

    @Override
    public void tearDown() throws Exception
    {
        try
        {
            if (_manager != null)
            {
                _manager.close();
            }
        }
        finally
        {
            deletePasswordFileIfExists();
        }
        super.tearDown();
    }

    private void setupMocks() throws Exception
    {
        _principalDatabase = mock(PrincipalDatabase.class);

        when(_principalDatabase.getMechanisms()).thenReturn(MOCK_MECH_NAME);
        when(_principalDatabase.createSaslServer(MOCK_MECH_NAME, LOCALHOST, null)).thenReturn(new MySaslServer(false, true));

        _manager = new PrincipalDatabaseAuthenticationManager(_principalDatabase, _passwordFileLocation);
        _manager.initialise();
    }

    public void testInitialiseWhenPasswordFileNotFound() throws Exception
    {
        _principalDatabase = new PlainPasswordFilePrincipalDatabase();
        _manager = new PrincipalDatabaseAuthenticationManager(_principalDatabase, _passwordFileLocation);

        try
        {
            _manager.initialise();
            fail("Initialisiation should fail when users file does not exist");
        }
        catch (IllegalConfigurationException e)
        {
            assertTrue(e.getCause() instanceof FileNotFoundException);
        }
    }

    public void testInitialiseWhenPasswordFileExists() throws Exception
    {
        _principalDatabase = new PlainPasswordFilePrincipalDatabase();
        _manager = new PrincipalDatabaseAuthenticationManager(_principalDatabase, _passwordFileLocation);

        File f = new File(_passwordFileLocation);
        f.createNewFile();
        FileOutputStream fos = null;
        try
        {
            fos = new FileOutputStream(f);
            fos.write("admin:admin".getBytes());
        }
        finally
        {
            if (fos != null)
            {
                fos.close();
            }
        }
        _manager.initialise();
        List<Principal> users = _principalDatabase.getUsers();
        assertEquals("Unexpected uses size", 1, users.size());
        Principal p = _principalDatabase.getUser("admin");
        assertEquals("Unexpected principal name", "admin", p.getName());
    }

    /**
     * Tests that the SASL factory method createSaslServer correctly
     * returns a non-null implementation.
     */
    public void testSaslMechanismCreation() throws Exception
    {
        setupMocks();

        SaslServer server = _manager.createSaslServer(MOCK_MECH_NAME, LOCALHOST, null);
        assertNotNull(server);
        // Merely tests the creation of the mechanism. Mechanisms themselves are tested
        // by their own tests.
    }

    /**
     * Tests that the authenticate method correctly interprets an
     * authentication success.
     *
     */
    public void testSaslAuthenticationSuccess() throws Exception
    {
        setupMocks();

        SaslServer testServer = createTestSaslServer(true, false);

        AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes());

        assertOnlyContainsWrapped(PRINCIPAL, result.getPrincipals());
        assertEquals(AuthenticationStatus.SUCCESS, result.getStatus());
    }

    /**
     *
     * Tests that the authenticate method correctly interprets an
     * authentication not complete.
     *
     */
    public void testSaslAuthenticationNotCompleted() throws Exception
    {
        setupMocks();

        SaslServer testServer = createTestSaslServer(false, false);

        AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes());
        assertEquals("Principals was not expected size", 0, result.getPrincipals().size());

        assertEquals(AuthenticationStatus.CONTINUE, result.getStatus());
    }

    /**
     *
     * Tests that the authenticate method correctly interprets an
     * authentication error.
     *
     */
    public void testSaslAuthenticationError() throws Exception
    {
        setupMocks();

        SaslServer testServer = createTestSaslServer(false, true);

        AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes());
        assertEquals("Principals was not expected size", 0, result.getPrincipals().size());
        assertEquals(AuthenticationStatus.ERROR, result.getStatus());
    }

    public void testNonSaslAuthenticationSuccess() throws Exception
    {
        setupMocks();

        when(_principalDatabase.verifyPassword("guest", "guest".toCharArray())).thenReturn(true);

        AuthenticationResult result = _manager.authenticate("guest", "guest");
        assertOnlyContainsWrapped(PRINCIPAL, result.getPrincipals());
        assertEquals(AuthenticationStatus.SUCCESS, result.getStatus());
    }

    public void testNonSaslAuthenticationNotCompleted() throws Exception
    {
        setupMocks();

        when(_principalDatabase.verifyPassword("guest", "wrongpassword".toCharArray())).thenReturn(false);

        AuthenticationResult result = _manager.authenticate("guest", "wrongpassword");
        assertEquals("Principals was not expected size", 0, result.getPrincipals().size());
        assertEquals(AuthenticationStatus.CONTINUE, result.getStatus());
    }

    public void testOnCreate() throws Exception
    {
        setupMocks();

        _manager.onCreate();
        assertTrue("Password file was not created", new File(_passwordFileLocation).exists());
    }

    public void testOnDelete() throws Exception
    {
        setupMocks();

        _manager.onCreate();
        assertTrue("Password file was not created", new File(_passwordFileLocation).exists());

        _manager.onDelete();
        assertFalse("Password file was not deleted", new File(_passwordFileLocation).exists());
    }

    private void deletePasswordFileIfExists()
    {
        File passwordFile = new File(_passwordFileLocation);
        if (passwordFile.exists())
        {
            passwordFile.delete();
        }
    }

    /**
     * Test SASL implementation used to test the authenticate() method.
     */
    private SaslServer createTestSaslServer(final boolean complete, final boolean throwSaslException)
    {
        return new MySaslServer(throwSaslException, complete);
    }

    public static final class MySaslServer implements SaslServer
    {
        private final boolean _throwSaslException;
        private final boolean _complete;

        public MySaslServer()
        {
            this(false, true);
        }

        private MySaslServer(boolean throwSaslException, boolean complete)
        {
            _throwSaslException = throwSaslException;
            _complete = complete;
        }

        public String getMechanismName()
        {
            return null;
        }

        public byte[] evaluateResponse(byte[] response) throws SaslException
        {
            if (_throwSaslException)
            {
                throw new SaslException("Mocked exception");
            }
            return null;
        }

        public boolean isComplete()
        {
            return _complete;
        }

        public String getAuthorizationID()
        {
            return _complete ? "guest" : null;
        }

        public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException
        {
            return null;
        }

        public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException
        {
            return null;
        }

        public Object getNegotiatedProperty(String propName)
        {
            return null;
        }

        public void dispose() throws SaslException
        {
        }
    }

    public static class MySaslServerFactory implements SaslServerFactory
    {
        @Override
        public SaslServer createSaslServer(String mechanism, String protocol,
                String serverName, Map<String, ?> props, CallbackHandler cbh)
                throws SaslException
        {
            if (MOCK_MECH_NAME.equals(mechanism))
            {
                return new MySaslServer();
            }
            else
            {
                return null;
            }
        }

        @Override
        public String[] getMechanismNames(Map<String, ?> props)
        {
            return new String[]{MOCK_MECH_NAME};
        }
    }
}